3D структуры

Страницы работы

3 страницы (Word-файл)

Содержание работы

3d structures - 3D структуры

In this section called "3d structures", we'll learn about howto structurize our code. This is important to do, if we wish to code ourself a 3dengine. Now, what do we mean by structurized code, and whats so good about it? Well, what we have to do in 3d, is to keep a record of where our vertices are placed in space. This could be done by the following (watcom C standard):

В этом разделе, называемом " 3D структуры ", мы узнаем относительно структуризации в нашем коде. Это важно делать, если мы желаем закодировать наш 3D двигатель. Теперь, что мы подразумеваем под структуризацией кода, и что является настолько хорошим относительно этого? Хорошо, что мы должны делать в 3D, должен хранить запись того, где наша вершина помещена в пространство. Это могло бы быть выполнено как показано ниже (watcom стандарт C):

float VertexX[1000]

float VertexY[1000]

float VertexZ[1000]

And the UV coordinates we could keep track of, like this:

И UV координаты мы могли бы сохранить, подобно этому:

float VertexU[1000]

float VertexV[1000]

Yes, some might say, this is an excellent way of doing it. Well, no actually. At first, you are limited to 1000 vertices, which means that you cannot load objects that would exceed 1000 vertices. And second, the vertices in the scene (x,y,z) have no connection to eachother. This means, that its lesser logical build. Now, lets look at some examples on how we could save our vertices in memory, as it should/could be done:

Да, некоторые могли бы говорить, это - превосходный способ выполнения этого. Хорошо, но нет фактически. Сначала, Вы ограничены 1000 вершиной, это означает что Вы не можете загружать предметы, которые превысили бы более 1000 вершин. И второе, вершины в сцене (x, y, z) не имеют никаких соединений друг с другом. Это означает, что нет логического построения. Теперь, допустим, рассмотрим некоторые примеры на том, как мы могли бы сохранять нашу вершину в памяти, поскольку это должен / мог бы быть выполненным:

typedef struct VertexTYPE

{

float x,y,z; - координаты в мире

float u,v; - координаты на текстуре

} vertextype;

Or it could be:

Или это могло бы быть:

typedef struct VertexTYPE

{

float x,y,z;

} vertextype;

typedef struct MappingTYPE

{

float u,v;

} mappingtype;

But let's stick with the first example. Now we have structurized our vertextype, but what if we want x numbers of vertices? Well, we declare the vertextype as dynamical:

Но давайте окончим первый пример. Теперь мы имеем структуризацию нашим типом вершины (vertextype), но что, если мы хотим n вершин? Хорошо, мы выделяем их динамически:

vertextype *vertices;

vertices = malloc(sizeof(vertextype)*n);

where x defines the number of vertices. So, we can have x number of vertices, but what about the faces? How do we keep track of them? Well, what we need in a face is pointers to its three vertices, and we might need a shading or a midz value for sorting. One way of doing it is:

где n определяет число вершин. Так, мы можем иметь n вершин, но что относительно плоскостей? Как мы сохраним их? Хорошо, для определения плоскости мы нуждаемся в  указателях на три вершины, и мы могли бы нуждаться в затенении или значении midz для сортировки. Один способ выполнения этого:

typedef struct FaceTYPE

{

vertextype *p1,*p2,*p3;

long vertex[3]; - номера вершин, в списке вершин

char shading;

long midz;

} facetype;

Now, if we let p1,p2 and p3 point at the vertices we can modify the vertices directly, through the face structure. The vertex[3] variable we use if we wish to manually access the vertex structures, e.g

Теперь, если мы допустим, что p1, p2 и p3 точки это вершины мы можем модифицировать вершину непосредственно, через структуру плоскости. Vertex [3] переменная, которую мы используем если мы желаем обратиться к структурам вершины, т.е.

x = vertices[face[currentface].vertex[0]].x;

y = vertices[face[currentface].vertex[0]].y;

z = vertices[face[currentface].vertex[0]].z;

Or with the use of pointers:

Или с использованием указателей:

x = face[currentface].p1.x;

y = face[currentface].p1.y;

z = face[currentface].p1.z;

Now, we also need an object structure to keep track of all these vertices. This might contain data about how much it should rotate, where it is positioned and maybe a pointer to a texturemap.

Теперь, мы также нуждаемся в структуре объекта, чтобы сохранить все эти вершины. Структура могла бы содержать данные относительно того, как объект должен вращаться, где он позиционирован и возможно указатель на текстуру.

typedef struct ObjectTYPE

{

float      rotatex,rotatey,rotatez;

long       numvertices;

long       numfaces;

vertextype *vertices;

vertextype *vertices_2d;

facetype   *face;

char       *textptr;

} objecttype;

If we just let the object.vertices variable point at the start of the objects vertices, we can find all vertices that are in this object, the vertices from object.vertices[0] to  оbject.vertices[numvertices]. The same goes for the facestructure. This also gives us a wayh of having several objects using the same array of vertices to draw from. Therefore we can find all vertices in our world within the variable called "vertices" and every face in the variable called "face". Therefore all vertices can be rotated to the new array, which we call "vertices_rot", and we donot have to access every object to rotate their particullar vertices. The same goes for facesorting, were we can sort all faces in the scene, starting with face[0], then moving up. We need another variable called "facesort", its the "face"-array, but its sorted by the face.midz value. Now, this should be enough for now, it should help in giving you an idear of how to structurize your code.

Если мы только допустим object.vertices переменную точку в начале вершин объектов, мы можем находить все вершины, которые находится в этом объекте, вершина из object.vertices [0] к оbject.vertex[numvertices-1]. Тот же самое для структур плоскостей. Это также дает нам,  путь использования для отрисовки нескольких объектов используюя тот же самый массив вершин. Следовательно мы можем найти все вершины в нашем мире внутри переменной называемой "vertices" и каждую плоскость в переменной называемой "face". Следовательно все вершины могут вращаться в новом массиве, который мы вызываем "vertices_rot", и мы имеем возможность обратиться к каждому объекту, чтобы вращать их частную вершину. Тот же самое относиться и для сортировки плоскостей, мы можем сортировать все плоскости в сцене, начинающейся с face[0], затем двигаемся вверх. Мы нуждаемся в другой переменной, называемой "facesort", это массив плоскостей, но отсортированный по значению face.midz. Теперь, это должно быть достаточно теперь, это должно помочь в предоставлении Вам идей того как структурировать ваш код.

Информация о работе