Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Процедурна геометрія

There are many ways to procedurally generate geometry in Godot. In this tutorial series, we will explore a few of them. Each technique has its own benefits and drawbacks, so it is best to understand each one and how it can be useful in a given situation.

Примітка

All the procedural geometry generation methods described here run on the CPU. Godot doesn't support generating geometry on the GPU yet.

Що таке геометрія?

Геометрія - це химерний спосіб описати форму. У комп'ютерній графіці геометрія зазвичай представлена масивом позицій, що називаються "вершинами". У Godot геометрія представлена Meshes (Мешами).

Що таке Меш?

Many things in Godot have mesh in their name: the Mesh, the ArrayMesh, the ImmediateMesh, the MeshInstance3D, the MultiMesh, and the MultiMeshInstance3D. While they are all related, they have slightly different uses.

Meshes and ArrayMeshes are resources that are drawn using a MeshInstance3D node. Resources like Meshes and ArrayMeshes cannot be added to the scene directly. A MeshInstance3D represents one instance of a mesh in your scene. You can reuse a single mesh in multiple MeshInstance3Ds to draw it in different parts of your scene with different materials or transformations (scale, rotation, position etc.).

If you are going to draw the same object many times, it can be helpful to use a MultiMesh with a MultiMeshInstance3D. MultiMeshInstance3Ds draw meshes thousands of times very cheaply by taking advantage of hardware instancing. The drawback with using a MultiMeshInstance3D is that each of your mesh's surfaces are limited to one material for all instances. It uses an instance array to store different colors and transformations for each instance, but all the instances of each surface use the same material.

Чим є Меш

A Mesh is composed of one or more surfaces. A surface is an array composed of multiple sub-arrays containing vertices, normals, UVs, etc. Normally the process of constructing surfaces and meshes is hidden from the user in the RenderingServer, but with ArrayMeshes, the user can construct a Mesh manually by passing in an array containing the surface information.

Поверхні

Each surface has its own material. Alternatively, you can override the material for all surfaces in the Mesh when you use a MeshInstance3D using the material_override property.

Масив поверхні

The surface array is an array of length ArrayMesh.ARRAY_MAX. Each position in the array is filled with a sub-array containing per-vertex information. For example, the array located at ArrayMesh.ARRAY_NORMAL is a PackedVector3Array of vertex normals. See Mesh.ArrayType for more information.

Масив поверхні може бути проіндексований, або неіндексований. Створити неіндексований масив так само просто, як не призначити масиву індекс ArrayMesh.ARRAY_INDEX. Неіндексований масив зберігає унікальну інформацію про вершину для кожного трикутника, а це означає, що коли два трикутники мають вершину, вершина дублюється в масиві. Індексований масив поверхні зберігає лише інформацію про вершину для кожної унікальної вершини, а потім також зберігає масив індексів, які відображають, як побудувати трикутники з масиву вершин. Загалом, використання індексованого масиву є швидшим, але це означає, що ви повинні ділитися даними вершини між трикутниками, що не завжди бажано (наприклад, коли ви хочете лицьові нормалі).

Інструменти

Godot надає різні способи доступу та роботи з геометрією. Детальніша інформація про кожен буде висвітлена в наступних уроках.

Масив Mesh

Ресурс ArrayMesh розширює Mesh, щоб додати кілька різної якості функцій, і, найголовніше, можливість побудувати поверхню Mesh за допомогою коду.

Для отримання додаткової інформації про ArrayMesh, будь ласка, перегляньте урок про ArrayMesh.

MeshDataTool (Інструмент Дані Меша)

MeshDataTool - це ресурс, який перетворює дані Меша на масиви вершин, граней і ребр, які можна змінити під час виконання.

Для отримання додаткової інформації про MeshDataTool, будь ласка, перегляньте урок про MeshDataTool.

SurfaceTool (Інструмент Поверхні)

SurfaceTool дозволяє створювати Меші за допомогою інтерфейсу стилю негайного режиму OpenGL 1.x.

Для отримання додаткової інформації про SurfaceTool, будь ласка, перегляньте урок про SurfaceTool.

ImmediateMesh

ImmediateMesh is a mesh that uses an immediate mode style interface (like SurfaceTool) to draw objects. The difference between ImmediateMesh and the SurfaceTool is that ImmediateMesh is drawn directly with code dynamically, while the SurfaceTool is used to generated a Mesh that you can do whatever you want with.

ImmediateMesh is useful for prototyping because of its straightforward API, but it is slow because the geometry is rebuilt each time you make a change. It is most useful for adding simple geometry for visual debugging (e.g. by drawing lines to visualize physics raycasts etc.).

For more information about ImmediateMesh, please see the ImmediateMesh tutorial.

Який з них я повинен використовувати?

Який підхід використовувати, залежить від того, що ви намагаєтеся зробити і який варіант вам зручніший.

Як SurfaceTool, так і ArrayMesh, відмінно підходять для генерації статичної геометрії (мешів), які не змінюються з часом.

Використання ArrayMesh трохи швидше, ніж використання SurfaceTool, але API трохи складніше. Крім того, SurfaceTool має кілька методів якості, таких як generate_normals() і index().

ImmediateMesh is more limited than both ArrayMesh and SurfaceTool. However, if you need the geometry to change every frame anyway, it provides a much easier interface that can be slightly faster than generating an ArrayMesh every frame.

MeshDataTool не швидкий, але він дає вам доступ до всіх видів властивостей меша, які ви не отримуєте з іншими (ребра, грані тощо). Це неймовірно корисно, коли вам потрібні такі дані для перетворення меша, але не варто використовувати його, якщо ця інформація не потрібна. MeshDataTool найкраще використовувати, якщо ви збираєтеся використовувати алгоритм, який вимагає доступу до масиву граней та ребр.