Jeff Molofee - NeHe's OpenGL Tutorials

Здесь есть возможность читать онлайн «Jeff Molofee - NeHe's OpenGL Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

NeHe's OpenGL Tutorials: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «NeHe's OpenGL Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

NeHe's OpenGL Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «NeHe's OpenGL Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

OldPos[i]=ArrayPos[i];

TVector::unit(ArrayVel[i],uveloc);

ArrayPos[i]=ArrayPos[i]+ArrayVel[i]*RestTime;

rt2=OldPos[i].dist(ArrayPos[i]);

// Test If Collision Occured Between Ball And All 5 Planes

if (TestIntersionPlane(pl1,OldPos[i],uveloc,rt,norm)) {

// Find Intersection Time

rt4=rt*RestTime/rt2;

// If Smaller Than The One Already Stored Replace In Timestep

if (rt4<=lamda) {

// If Intersection Time In Current Time Step

if (rt4<=RestTime+ZERO) if (! ((rt<=ZERO)&&(uveloc.dot(norm)>ZERO)) ) {

normal=norm;

point=OldPos[i]+uveloc*rt;

lamda=rt4;

BallNr=i;

}

}

}

if (TestIntersionPlane(pl2, OldPos[i], uveloc, rt, norm)) {

// …The Same As Above Omitted For Space Reasons

}

if (TestIntersionPlane(pl3, OldPos[i], uveloc, rt, norm)) {

// …The Same As Above Omitted For Space Reasons

}

if (TestIntersionPlane(pl4, OldPos[i], uveloc, rt, norm)) {

// …The Same As Above Omitted For Space Reasons

}

if (TestIntersionPlane(pl5, OldPos[i], uveloc, rt, norm)) {

// …The Same As Above Omitted For Space Reasons

}

// Now Test Intersection With The 3 Cylinders

if (TestIntersionCylinder(cyl1, OldPos[i], uveloc, rt, norm, Nc)) {

rt4 = rt*RestTime/rt2;

if (rt4<=lamda) {

if (rt4<=RestTime+ZERO) if (! ((rt<=ZERO)&&(uveloc.dot(norm)>ZERO)) ) {

normal=norm;

point=Nc;

lamda=rt4;

BallNr=i;

}

}

}

if (TestIntersionCylinder(cyl2, OldPos[i], uveloc, rt, norm, Nc)) {

// …The Same As Above Omitted For Space Reasons

}

if (TestIntersionCylinder(cyl3, OldPos[i], uveloc, rt, norm, Nc)) {

// …The Same As Above Omitted For Space Reasons

}

}

// After All Balls Were Tested With Planes / Cylinders Test For Collision

// Between Them And Replace If Collision Time Smaller

if (FindBallCol(Pos2, BallTime, RestTime, BallColNr1, BallColNr2)) {

if (sounds) PlaySound("Explode.wav", NULL, SND_FILENAME|SND_ASYNC);

if ((lamda==10000) || (lamda>BallTime)) {

RestTime=RestTime-BallTime;

TVector pb1, pb2, xaxis, U1x, U1y, U2x, U2y, V1x, V1y, V2x, V2y;

double a,b;

Code Omitted For Space Reasons

The Code Is Described In The Physically Based Modeling Section Under Sphere To Sphere Collision

//Update Explosion Array And Insert Explosion

for(j=0; j<20; j++) {

if (ExplosionArray[j]._Alpha<=0) {

ExplosionArray[j]._Alpha=1;

ExplosionArray[j]._Position=ArrayPos[BallColNr1];

ExplosionArray[j]._Scale=1;

break;

}

}

continue;

}

}

// End Of Tests

// If Collision Occured Move Simulation For The Correct Timestep

// And Compute Response For The Colliding Ball

if (lamda != 10000) {

RestTime-=lamda;

for (j=0; j

rt2=ArrayVel[BallNr].mag();

ArrayVel[BallNr].unit();

ArrayVel[BallNr] = TVector::unit( (normal*(2*normal.dot(-ArrayVel[BallNr]))) + ArrayVel[BallNr] );

ArrayVel[BallNr] = ArrayVel[BallNr]*rt2;

// Update Explosion Array And Insert Explosion

for(j=0; j<20; j++) {

if (ExplosionArray[j]._Alpha<=0) {

ExplosionArray[j]._Alpha=1;

ExplosionArray[j]._Position=point;

ExplosionArray[j]._Scale=1;

break;

}

}

} else RestTime=0;

} // End Of While Loop

The Main Global Variables Of Importance Are:

Represent the direction and position of the camera. The camera is moved using the LookAt function. As you will probably notice, if not in hook mode (which I will explain later), the whole scene rotates around, the degree of rotation is handled with camera_rotation. TVector dir TVector pos(0,-50,1000); float camera_rotation=0;
Represent the acceleration applied to the moving balls. Acts as gravity in the application. TVector accel(0,-0.05,0);
Arrays which hold the New and old ball positions and the velocity vector of each ball. The number of balls is hard coded to 10. TVector ArrayVel[10]; TVector ArrayPos[10]; TVector OldPos[10]; int NrOfBalls=3;
The time step we use. double Time=0.6;
If 1 the camera view changes and a (the ball with index 0 in the array) ball is followed. For making the camera following the ball we used its position and velocity vector to position the camera exactly behind the ball and make it look along the velocity vector of the ball. int hook_toball1=0;
Self explanatory structures for holding data about explosions, planes and cylinders. struct Plane struct Cylinder struct Explosion
The explosions are stored in a array, of fixed length. Explosion ExplosionArray[20];

The Main Functions Of Interest Are:

Perform Intersection tests with primitives int TestIntersionPlane(…); int TestIntersionCylinder(…);
Loads Textures from bmp files void LoadGLTextures();
Has the rendering code. Renders the balls, walls, columns and explosions void DrawGLScene();
Performs the main simulation logic void idle();
Sets Up OpenGL state void InitGL();
Find if any balls collide again each other in current time step int FindBallCol(…);

For more information look at the source code. I tried to comment it as best as I could. Once the collision detection and response logic is understood, the source should become very clear. For any more info don't hesitate to contact me.

As I stated at the beginning of this tutorial, the subject of collision detection is a very difficult subject to cover in one tutorial. You will learn a lot in this tutorial, enough to create some pretty impressive demos of your own, but there is still alot more to learn on this subject. Now that you have the basics, all the other sources on Collision Detection and Physically Based Modeling out there should become easier to understand. With this said, I send you on your way and wish you happy collisions!!!

Some information about Dimitrios Christopoulos: He is currently working as a Virtual Reality software engineer at the Foundation of the Hellenic World in Athens/Greece (www.fhw.gr). Although Born in Germany, he studied in Greece at the University of Patras for a B.Sc. in Computer Engineering and Informatics. He holds also a MSc degree (honours) from the University of Hull (UK) in Computer Graphics and Virtual Environments. He did his first steps in game programming using Basic on an Commodore 64, and switched to C/C++/Assembly on the PC platform after the start of his studium. During the last few years OpenGL has become his graphics API of choice. For more information visit his site at: http://members.xoom.com/D_Christop.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «NeHe's OpenGL Tutorials»

Представляем Вашему вниманию похожие книги на «NeHe's OpenGL Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Jeff Jacobson - Sleep Tight
Jeff Jacobson
Jeff Salyards - Veil of the Deserters
Jeff Salyards
Jeff LaSala - The Darkwood Mask
Jeff LaSala
Jeff Lindsay - Dexter's Final Cut
Jeff Lindsay
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
Отзывы о книге «NeHe's OpenGL Tutorials»

Обсуждение, отзывы о книге «NeHe's OpenGL Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x