This page has been translated automatically.
Основы UNIGINE
1. Введение
2. Виртуальные миры и работа с ними
3. Подготовка 3D моделей
4. Материалы
5. Камеры и освещение
6. Реализация логики приложения
7. Создание кат-сцен и запись видео
8. Подготовка проекта к релизу
9. Физика
10. Основы оптимизации
11. ПРОЕКТ2: Шутер от первого лица
13. ПРОЕКТ4: VR приложение с простым взаимодействием

Создание ландшафта

So far, the car has been moving on the test plane. However, the game needs a vast and variegated open space with various, so let's add a landscape to the scene.До сих пор автомобиль двигался по тестовой плоскости. Игре нужно большое и разнообразное открытое пространство, добавим в сцену ландшафт.

For this purpose we'll use terrain — a special type of geometry object designed for creating landscapes. The main object for working with landscape in UNIGINE is Landscape Terrain. It is optimized for vast areas and uses the material with specific texture blending to realistically simulate natural and artificial surfaces: soil, rocks, asphalt, paving stones, etc. Typically, it serves as the foundational element for open-world games, providing a basis for static geometry placement and character movement.Для этого используем террейн — особый тип геометрии, предназначенный для моделирования ландшафтов. Основной объект для работы с ландшафтом в UNIGINE — это Landscape Terrain. Он оптимизирован для больших локаций и использует материал с особым смешиванием текстур для реалистичной имитации естественных и рукотворных поверхностей: почвы, скал, асфальта, брусчатки и т.д. Как правило, это основной объект в играх с открытым пространством, служащий основой для расстановки статичной геометрии и перемещения игровых персонажей.

The Landscape Terrain system is represented by two types of nodes:Система Landscape Terrain состоит из двух типов нод:

  • Object Landscape Terrain — a virtual object ensuring the terrain rendering.Object Landscape Terrain — виртуальный объект, ответственный за рендеринг террейна.
  • One or several Landscape Layer Map objects — layers with the terrain graphic data. The layer system allows you to combine and mix layer data in different order, as well as to place high-detailed layers of small size over large low-detailed layers (the so-called inset).Один или несколько объектов Landscape Layer Map — слои с графическими данными террейна. Система слоев позволяет совмещать и смешивать данные слоев в разном порядке, а также располагать высокодетальные слои небольшого размера над крупными низкодетальными слоями (делая так называемый inset — вставка).

To create a terrain, you need a set of the following textures created in third-party software:Для создания террейна необходим набор следующих текстур, созданных в стороннем ПО:

  • Height map — terrain height dataHeight map — карта высот;
  • Albedo — colored terrain surface textureAlbedo — цветная текстура поверхности;
  • Masks — a set of masks that can be used to arrange plants and apply additional detailMasks — набор масок, по которым можно расставить растения и применить дополнительную детализацию;
  • Albedo, Roughness, and Height textures for each additional detailТекстуры Albedo, Roughness и Height для каждой дополнительной детализации.

You can model a fairly simple terrain by drawing it manually using the UnigineEditor's built-in landscape editor. However, realistic natural terrains are usually created in specialized software such as: Quadspinner Gaea, World Machine, World Creator, SideFX Houdini, etc. Using these tools, you can simulate a suitable landscape and get a set of textures that define the shape and color of the terrain for the game engine.Достаточно простой террейн можно смоделировать, нарисовав вручную при помощи встроенного в UnigineEditor редактора террейна. Однако для создания реалистичных природных ландшафтов используется специализированное ПО, такое как: Quadspinner Gaea, World Machine, World Creator, SideFX Houdini и т.д. Используя эти пакеты, можно смоделировать подходящий ландшафт и получить набор текстур, определяющих форму и цвет террейна для игрового движка.

Terrain in Quadspinner Gaea

Terrain in Quadspinner GaeaТеррейн в Quadspinner Gaea

For this tutorial, you can use the ready-made textures available in the race/terrain folder.Для этого урока уже доступны подготовленные текстуры в папке race/terrain.

  1. In the menu, select Create → Landscape → Landscape Terrain and add it to the scene. Two new nodes will appear in the world hierarchy: ObjectLandscapeTerrain — the terrain itself, and LandscapeLayerMap — the layer with data. The standard terrain layer is represented by a colorless plane with the size of 1000×1000 m. The ground_plane test plane can be disabled for convenience.Выберем в меню Create → Landscape → Landscape Terrain и добавим его на сцену. В иерархии мира появится две новых ноды: ObjectLandscapeTerrain — сам террейн — и LandscapeLayerMap — слой с данными. Стандартный слой террейна представлен бесцветной плоскостью размером 1000×1000 м. Тестовую плоскость ground_plane можно отключить, чтобы она не мешала.
  2. Set the Size of this layer to 5000 × 5000 m.Установим размер этого слоя в поле Size в 5000 × 5000 м.
  3. Find the ready-made terrain textures in the race/terrain folder. In the Parameters tab of LandscapeLayerMap, click the + button in the Landscape field to create and apply a new *.lmap asset that will store data of our terrain layer.Найдём подготовленные текстуры террейна в race/terrain. В параметрах LandscapeLayerMap нажмите кнопку + в поле Landscape, чтобы создать и применить новый ассет *.lmap, который будет хранить данные нашего слоя террейна.

  4. In the import settings, for Data Filling select From Tileset and add the source textures for the terrain:В настройках импорта Data Filling выберем From Tileset и укажем исходные текстуры для террейна:

    1. Height map in the Heightmap field. Here you also need to set the terrain layer height Max: 1000 meters.Карту высот Height в поле Heightmap. Здесь также необходимо установить высоту слоя террейна в поле Max: 1000 метров;
    2. Albedo texture in the Albedo Color field.Текстуру Albedo в Albedo Color;
    3. Each of the 6 masks from the race/terrain folder is added to an individual slot in the Masks section. For easier customization, we recommend to name each mask accordingly.Каждую из 6 имеющихся в папке race/terrain масок определим в отдельный слот раздела Masks. Для удобства настройки рекомендуем также назвать каждую маску соответствующим именем.

    4. Click Reimport Data to load the selected textures.Нажмем Reimport Data, чтобы загрузить указанные текстуры.

Landscape Terrain has the Collision and Physics Intersections options enabled by default (your can check this by selecting the ObjectLandscapeTerrain node and viewing the Surfaces tab in parameters), so the car will be able to drive on it without any problems.У Landscape Terrain по умолчанию включены опции Collision и Physics Intersections (это можно проверить, выделив ноду ObjectLandscapeTerrain и перейдя во вкладку Surfaces в параметрах), поэтому автомобиль сможет ездить по нему без проблем.

Details
Детали
#

No matter how large the textures used for the surface are, the data density still won't be enough for a terrain 5 kilometers on a side. The data density is too low when viewed from the surface.Сколь бы крупные текстуры мы не использовали для поверхности, для террейна со стороной в 5 километров плотности данных будет недостаточно. Плотность данных слишком низкая при взгляде от поверхности.

One solution is to split the original high-resolution textures into a set of tiles and use them for creating a terrain. However, even with a total resolution of 65536×65536 pixels (8×8 tiles with the size of 8192×8192 each), the density of the texels will barely exceed 13 pixels per meter. This is also not enough.Одно из решений — разбить исходные текстуры огромного разрешения на набор тайлов и использовать в качестве основы для создания террейна. Однако даже при суммарном разрешении 65536×65536 пикселей (8×8 тайлов размером 8192×8192), плотность текселей едва превысит 13 пикселей на метр. Этого также недостаточно.

For high detailing of the surface we use terrain details — additional materials that can be mixed based on the terrain masks: the grass mask defines where the detailed grass texture will be located, the same is done for rocks, soil, sandstone, etc.Для высокой детализации поверхности используем детали террейна (details) — дополнительные материалы, смешивание которых производится на основе масок террейна, таким образом на маске для травы будет расположена детализированная текстура травы, равно как и для скал, почвы, песчаника и т.д.

Примечание
To view the terrain masks, go to Helpers → Show Landscape Data.Для просмотра масок террейна, перейдите в Helpers → Show Landscape Data.

Select the ObjectLandscapeTerrain node and go to the Details parameter section. You can add as many details as you want for each mask:Выделим ноду ObjectLandscapeTerrain и перейдем в раздел параметров Details. Для каждой маски можно добавить сколько угодно деталей:

  1. After selecting a mask, click "+" on the panel to add a detail layer.После выбора маски нажмем "+" на панели, чтобы добавить слой деталей.

  2. Then click "+" on the detail material panel to add a new editable material.Затем "+" на панели материала деталей, чтобы добавить новый редактируемый материал.
  3. In the race/terrain/details/textures folder there is a set of textures to recreate different natural surfaces. Use the Albedo, Roughness and Height textures to make each masked area look unique.В папке race/terrain/details/textures приготовлен набор текстур для различных естественных поверхностей, используем текстуры Albedo, Roughness и Height для того, чтобы придать уникальный вид каждой маскированной области.
  4. Pay specific attention to the following parameters:Особое внимание следует уделить параметрам:

    • Size — the size of one tile of the detail. Higher values increase the layer size.Size — размер одного тайла детали, чем он выше, тем крупнее будет отображен слой;
    • Scale — the intensity of the height displacement. Higher Scale values make the geometry irregularities more protruding.Scale — интенсивность дисплейсмента по карте высот. Чем выше Scale, тем сильнее будут выступать геометрические неровности.

Customizing details is a completely artistic task. Usually at least one detail layer needs to be assigned to each mask in order to cover the entire terrain surface. Detail layers, as well as masks, can be swapped if a different order of layers is required.Настройка деталей — это полностью художественная задача. Обычно как минимум для каждой маски требуется назначить хотя бы один слой деталей для того, чтобы покрыть всю поверхность террейна. Слои деталей, равно как и маски, можно менять местами, если требуется другой порядок наложения слоев.

For convenience, the project already contains ready-made materials for the details (race/terrain/details) that are to be assigned to the detail layers in the corresponding masks.Для удобства, в проект уже включены готовые материалы деталей (race/terrain/details), которые нужно назначить слоям деталей в соответствующих масках.

After customizing the details, the data density is much higher and the terrain looks more natural.После настройки деталей плотность данных гораздо выше и террейн теперь выглядит более естественно.

Примечание
All terrain components, and masks in particular, can be edited using the built-in landscape editor. Switch to Landscape Paint Mode, select a layer to paint on, a terrain component (Albedo, Height, or one of the masks) and a brush, and try editing it manually by painting on the terrain surface. To save changes, simply switch back to Object Mode.Все компоненты террейна, в частности маски, можно редактировать при помощи встроенного редактора террейна. Перейдите в режим Landscape Paint Mode, выберите слой для рисования, компонент террейна (будь то Albedo, Height или одна из масок) и кисть и попробуйте отредактировать его вручную, рисуя кистью по поверхности террейна. Чтобы сохранить изменения, достаточно переключиться обратно в режим Object Mode.

Vegetation
Растительность
#

To diversify the landscape, let's add vegetation. Use the ready-made tree and grass assets from the race/vegetation folder.Чтобы разнообразить ландшафт, добавим растительность. Используем подготовленные ассеты с деревьями и травой из папки race/vegetation:

Adding trees:Добавим деревья:

  1. Right-click on the trees_clutter.node asset from the trees folder, select Place as Node Content in the context menu and add the asset content to the scene.Кликните правой кнопкой мыши на ассете trees_clutter.node из папки trees, выберите Place as Node Content в контекстном меню и добавьте содержимое ассета на сцену.
  2. In the World Nodes window, drag the trees_clutter node to ObjectLandscapeTerrain to make the trees children of the terrain, and reset the position to align the trees with the terrain (the terrain itself and the LandscapeLayerMap node are also located in the origin).В окне World Nodes перетяните ноду trees_clutter на ObjectLandscapeTerrain, чтобы сделать деревья дочерними террейну, и сбросьте позицию, чтобы выровнять деревья по террейну (сам террейн и нода LandscapeLayerMap у нас также находятся в нулевых координатах).

  3. Trees (the trees_clutter node) are represented by the Mesh Clutter object that arranges polygonal meshes procedurally on a rectangular area according to the the specified parameters. In addition, this node is a child of the terrain object and the Intersection option is enabled in the object settings, so the trees automatically follow the surface of the terrain.Деревья (нода trees_clutter) представлены объектом Mesh Clutter для процедурной расстановки полигональных мешей по прямоугольной площади согласно заданным параметрам. А благодаря тому, что нода является дочерней террейну, а также включенной опции Intersection в настройках объекта, деревья автоматически следуют поверхности террейна.
  4. In the object settings, find the Mask Terrain parameter: use it to select the terrain mask that will be used to arrange procedural trees. It can be the Grass mask or any other mask at your choice.В настройках объекта найдите параметр Mask Terrain: он позволяет выбрать маску террейна, по которой и будут расставляться процедурные деревья. Это может быть маска Grass или любая другая на ваше усмотрение.
  5. Rendering multipolygonal trees at a great distance from the camera can significantly impact performance. To address this, the Grass object is added as a child node to the trees to handle rendering of impostors. This object has the same settings as the Mesh Clutter object, ensuring that each tree is replaced by its "photo" when viewed from a distance. In the Mask Terrain parameter of the Grass object's settings, select the same mask in the first of the four lists (since impostors only use one type of texture out of four possible) that was selected in the previous step.С точки зрения производительности, крайне неоптимально отрисовывать многополигональные деревья на большом удалении от камеры, поэтому дочерней нодой к деревьям добавлен объект Grass, отвечающий за рендеринг импосторов. Он имеет идентичные настройки объекту Mesh Clutter, поэтому каждое дерево корректно подменяется его “фотографией” при отдалении. В настройках этого объекта, в параметре Mask Terrain нужно выбрать ту же маску в первом из 4 списков (в данном случае испосторы используют только один тип текстур из 4 возможных), что вы выбрали на предыдущем шаге.

Add the contents of the grass/grass_clutter.node asset in the same way to generate grass on the terrain surface. Grass is also represented by Mesh Clutter objects (grass_close, grass_far) that procedurally arrange bunches of polygonal grass.Добавьте точно таким же образом содержимое ассета grass/grass_clutter.node, чтобы добавить траву на поверхность террейна. Трава также представлена объектами Mesh Clutter (grass_close, grass_far), процедурно расставляющими пучки полигональной травы.

Последнее обновление: 06.02.2024
Build: ()