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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

The question is, how do we get our data from our file. First, we create a new function called SetupWorld(). We define our file as filein, and we open it for read-only access. We must also close our file when we are done. Let us take a look at the code so far:

// Previous Declaration: char* worldfile = "data\\world.txt";

void SetupWorld() // Setup Our World

{

FILE *filein; // File To Work With

filein = fopen(worldfile, "rt"); // Open Our File

(read our data)

fclose(filein); // Close Our File

return; // Jump Back

}

Our next challenge is to read each individual line of text into a variable. This can be done in a number of ways. One problem is that not all lines in the file will contain meaningful information. Blank lines and comments shouldn't be read. Let us create a function called readstr(). This function will read one meaningful line of text into an initialised string. Here's the code:

void readstr(FILE *f, char *string) // Read In A String

{

do // Start A Loop

{

fgets(string, 255, f); // Read One Line

} while ((string[0] == '/') || (string[0] == '\n')); // See If It Is Worthy Of Processing

return; // Jump Back

}

Next, we must read in the sector data. This lesson will deal with one sector only, but it is easy to implement a multi-sector engine. Let us turn back to SetupWorld().Our program must know how many triangles are in our sector. In our data file, we will define the number of triangles as follows:

NUMPOLLIES n

Here's the code to read the number of triangles:

int numtriangles; // Number Of Triangles In Sector

char oneline[255]; // String To Store Data In

readstr(filein,oneline); // Get Single Line Of Data

sscanf(oneline, "NUMPOLLIES %d\n", &numtriangles); // Read In Number Of Triangles

The rest of our world-loading process will use the same process. Next, we initialize our sector and read some data into it:

// Previous Declaration: SECTOR sector1;

char oneline[255]; // String To Store Data In

int numtriangles; // Number Of Triangles In Sector

float x, y, z, u, v; // 3D And Texture Coordinates

sector1.triangle = new TRIANGLE[numtriangles]; // Allocate Memory For numtriangles And Set Pointer

sector1.numtriangles = numtriangles; // Define The Number Of Triangles In Sector 1

// Step Through Each Triangle In Sector

for (int triloop = 0; triloop < numtriangles; triloop++) // Loop Through All The Triangles

{

// Step Through Each Vertex In Triangle

for (int vertloop = 0; vertloop < 3; vertloop++) // Loop Through All The Vertices

{

readstr(filein,oneline); // Read String To Work With

// Read Data Into Respective Vertex Values

sscanf(oneline, "%f %f %f %f %f", &x, &y, &z, &u, &v);

// Store Values Into Respective Vertices

sector1.triangle[triloop].vertex[vertloop].x = x; // Sector 1, Triangle triloop, Vertice vertloop, x Value=x

sector1.triangle[triloop].vertex[vertloop].y = y; // Sector 1, Triangle triloop, Vertice vertloop, y Value=y

sector1.triangle[triloop].vertex[vertloop].z = z; // Sector 1, Triangle triloop, Vertice vertloop, z Value=z

sector1.triangle[triloop].vertex[vertloop].u = u; // Sector 1, Triangle triloop, Vertice vertloop, u Value=u

sector1.triangle[triloop].vertex[vertloop].v = v; // Sector 1, Triangle triloop, Vertice vertloop, v Value=v

}

}

Each triangle in our data file is declared as follows:

X1 Y1 Z1 U1 V1

X2 Y2 Z2 U2 V2

X3 Y3 Z3 U3 V3

Displaying Worlds

Now that we can load our sector into memory, we need to display it on screen. So far we have done some minor rotations and translations, but our camera was always centered at the origin (0,0,0). Any good 3D engine would have the user be able to walk around and explore the world, and so will ours. One way of doing this is to move the camera around and draw the 3D environment relative to the camera position. This is slow and hard to code. What we will do is this:

1. Rotate and translate the camera position according to user commands

2. Rotate the world around the origin in the opposite direction of the camera rotation (giving the illusion that the camera has been rotated)

3. Translate the world in the opposite manner that the camera has been translated (again, giving the illusion that the camera has moved)

This is pretty simple to implement. Let's start with the first stage (Rotation and translation of the camera).

if (keys[VK_RIGHT]) // Is The Right Arrow Being Pressed?

{

yrot –= 1.5f; // Rotate The Scene To The Left

}

if (keys[VK_LEFT]) // Is The Left Arrow Being Pressed?

{

yrot += 1.5f; // Rotate The Scene To The Right

}

if (keys[VK_UP]) // Is The Up Arrow Being Pressed?

{

xpos –= (float)sin(heading*piover180) * 0.05f; // Move On The X-Plane Based On Player Direction

zpos –= (float)cos(heading*piover180) * 0.05f; // Move On The Z-Plane Based On Player Direction

if (walkbiasangle >= 359.0f) // Is walkbiasangle>=359?

{

walkbiasangle = 0.0f; // Make walkbiasangle Equal 0

} else // Otherwise

{

walkbiasangle+= 10; // If walkbiasangle < 359 Increase It By 10

}

walkbias = (float)sin(walkbiasangle * piover180)/20.0f; // Causes The Player To Bounce

}

if (keys[VK_DOWN]) // Is The Down Arrow Being Pressed?

{

xpos += (float)sin(heading*piover180) * 0.05f; // Move On The X-Plane Based On Player Direction

zpos += (float)cos(heading*piover180) * 0.05f; // Move On The Z-Plane Based On Player Direction

if (walkbiasangle <= 1.0f) // Is walkbiasangle<=1?

{

walkbiasangle = 359.0f; // Make walkbiasangle Equal 359

} else // Otherwise

{

walkbiasangle-= 10; // If walkbiasangle > 1 Decrease It By 10

}

walkbias = (float)sin(walkbiasangle * piover180)/20.0f; // Causes The Player To Bounce

}

That was fairly simple. When either the left or right cursor key is pressed, the rotation variable yrot is incremented or decremented appropriatly. When the forward or backwards cursor key is pressed, a new location for the camera is calculated using the sine and cosine calculations (some trigonometry required :-). Piover180 is simply a conversion factor for converting between degrees and radians.

Next you ask me: What is this walkbias? It's a word I invented :-) It's basically an offset that occurs when a person walks around (head bobbing up and down like a buoy. It simply adjusts the camera's Y position with a sine wave. I had to put this in, as simply moving forwards and backwards didn't look to great.

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

Интервал:

Закладка:

Сделать

Похожие книги на «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