This page has been translated automatically.
Видеоуроки
Интерфейс
Основы
Продвинутый уровень
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Профессиональный уровень (SIM)
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Контроль версий
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World-ноды
Звуковые объекты
Объекты поиска пути
Player-ноды
Программирование
Основы
Настройка среды разработки
Примеры использования
C++
C#
UnigineScript
UUSL (Unified UNIGINE Shader Language)
Плагины
Форматы файлов
Материалы и шейдеры
Rebuilding the Engine Tools
Интерфейс пользователя (GUI)
Двойная точность координат
API
Animations-Related Classes
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
VR-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples

Добавление целей морфинга

This article describes how to work with the morph target animation also known as blend shapes in UNIGINE. Usually, morph targets are used to change facial expressions of characters.В этой статье описывается, как работать в UNIGINE с анимацией morph target (целей морфинга), также известной как blend shapes (формы смешивания). Обычно цели морфинга используются для изменения выражений лиц персонажей.

The article shows how to export the mesh with morph targets from Autodesk Maya and then add it to UNIGINE.В статье показано, как экспортировать меш с целями морфинга из Autodesk Maya, а затем добавить его в UNIGINE.

The model used in this tutorial is Spot by Keenan Crane distributed under CC0 1.0 Universal.Модель, используемая в этом руководстве, - Spot от Keenan Crane, распространяемая под CC0 1.0 Universal.

RequirementsТребования#

  • It is supposed that you already have a 3D model with blend shapes ready to be exported, and this model is within the limitations set in UNIGINE.Предполагается, что у вас уже есть 3D-модель со смешанными формами, готовая к экспорту, и эта модель учитывает ограничения, установленные в UNIGINE.
  • It is supposed that you already have a world created.Предполагается, что у вас уже есть созданный мир.

See AlsoСмотрите также#

Step 1. Export a Mesh with Blend Shapes from MayaШаг 1. Экспорт меша с формами смешивания из Maya#

This section shows the way of exporting meshes with blend shapes in the FBX format from Autodesk Maya. It contains an example mesh of a calf, which has 2 blend shapes (morph targets).В этом разделе показан способ экспорта мешей с формами смешивания в формате FBX из Autodesk Maya. Он содержит в качестве примера меш теленка, у которого есть 2 формы смешивания (цели морфинга).

To export the mesh with blend shapes, do the following:Чтобы экспортировать меш с формами смешивания, выполните следующее:

  1. In Autodesk Maya, select the mesh with blend shapes to be exported.В Autodesk Maya выберите меш с формами смешивания для экспорта.

  2. In the main menu, click File -> Export Selection...В главном меню выберите File -> Export Selection...

  3. In the Export Selection window, choose a folder to save the mesh and specify a name for the FBX file. In the Files of type drop-down list, choose FBX export.В окне Export Selection выберите папку для сохранения меша и укажите имя для файла FBX. В раскрывающемся списке Files of type выберите FBX export.
  4. In the File Type Specific Options tab with export options, specify parameters to export the mesh.На вкладке File Type Specific Options с параметрами экспорта укажите параметры для экспорта меша.
  5. In the Deformed Models tab, check the Blend Shapes checkbox to export blend shapes.На вкладке Deformed Models установите флажок Blend Shapes, чтобы экспортировать формы смешивания.
  6. Click Export Selection.Нажмите Export Selection.

Now you have the mesh in the FBX format that can be easily added to your project.Теперь у вас есть меш в формате FBX, который можно легко добавить в проект.

Step 2. Add a Mesh into the WorldШаг 2. Добавление меша в мир#

This section shows how to add the exported mesh to the world and set up morph target animation.В этом разделе показано, как добавить экспортированный меш в мир и настроить анимацию целей морфинга.

To add the exported mesh to the world:Чтобы добавить экспортированный меш в мир:

  1. Import the .fbx file with the Import Morph Targets option enabled. Импортируйте файл .fbx с включенной опцией Import Morph Targets.

  2. Add the imported file to the scene. Добавьте импортированный файл в сцену.
  3. Save the world.Сохраните мир.

Each blend shape of the mesh is a target. You need to create morph targets for a surface of the mesh and set parameters to these targets to control the morph target animation. The following example shows how to create morph targets and set parameters via code:Каждая форма смешивания меша является целью морфинга. Вам нужно создать цели морфинга для поверхности меша и задать параметры для этих целей, чтобы управлять анимацией цели морфинга. В следующем примере показано, как создавать цели морфинга и задавать параметры из кода:

AppWorldLogic.h:AppWorldLogic.h:

Исходный код (C++)
#ifndef __APP_WORLD_LOGIC_H__
#define __APP_WORLD_LOGIC_H__

#include <UnigineLogic.h>
#include <UnigineStreams.h>
#include <UnigineObjects.h>
#include <UnigineGame.h>
#include <UnigineMathLib.h>

using namespace Unigine;

class AppWorldLogic : public Unigine::WorldLogic
{

public:
	AppWorldLogic();
	~AppWorldLogic() override;

	int init() override;

	int update() override;
	int postUpdate() override;
	int updatePhysics() override;

	int shutdown() override;

	int save(const Unigine::StreamPtr &stream) override;
	int restore(const Unigine::StreamPtr &stream) override;

private:
	ObjectMeshSkinnedPtr mesh;
};

#endif // __APP_WORLD_LOGIC_H__

AppWorldLogic.cpp:AppWorldLogic.cpp:

Исходный код (C++)
#include "AppWorldLogic.h"
#include <UnigineWorld.h>

int AppWorldLogic::init()
{
	// get the node that refers to the exported FBX file and cast it to a skinned mesh
	mesh = static_ptr_cast<ObjectMeshSkinned>(World::getNodeByName("spot_the_cow"));
	// set the number of morph targets 
	mesh->setNumTargets(5, 0);

	return 1;
}

int AppWorldLogic::update()
{
	float time = Game::getTime() * 2.0f;
	// calculate weights of targets	
	float k0 = sin(time * 3.0f) + 0.75f;
	float k1 = cos(time * 3.0f) + 0.75f;

	// set targets with parameters
	mesh->setTarget(0, 1, 0, 1.0f, 0);
	mesh->setTarget(1, 1, 0, -k0, 0);
	mesh->setTarget(2, 1, 0, -k1, 0);
	mesh->setTarget(3, 1, 1, k0, 0);
	mesh->setTarget(4, 1, 2, k1, 0); 
	return 1;
}

int AppWorldLogic::shutdown()
{
	mesh.clear();

	return 1;
}

The code given above gets the node that refers to the FBX file and sets parameters to morph targets. Let's clarify the essential things:Приведенный выше код получает ноду, которая ссылается на файл FBX, и задает параметры для целей морфинга. Давайте проясним основные моменты:

  • The exported mesh was obtained by casting the node that refers to the FBX asset to ObjectMeshSkinned. The node is obtained from the World by its name.Экспортированный меш был получен путем приведения ноды, которая ссылается на ассет FBX, к ObjectMeshSkinned. Ноду получаем из мира по ее названию.
  • The setNumTargets() function sets the number of targets for the surface of the mesh. The exported mesh in the example given above has 2 targets (blend shapes).Функция setNumTargets() задает количество целей для поверхности меша. Экспортированный меш в приведенном выше примере имеет 2 цели (формы смешивания).
  • By using the setTarget() function, all parameters for each created morph target are set in the update() function. Each target has its target weight. Weights have an influence on coordinates of the mesh: coordinates are multiplied by their weights. Thus, all enabled targets are multiplied by their weights and the new mesh is created:При использовании функции setTarget() все параметры для каждой созданной цели морфинга задаются в функции update(). Каждая цель имеет свой целевой вес. Веса влияют на координаты меша: координаты умножаются на их веса. Таким образом, все включенные целевые объекты умножаются на их веса и создается новый меш:

    final_xyz = target_0_xyz * weight_0 + target_1_xyz * weight_1 + ...
  • Since in the code given above, sin() and cos() functions are used for animation blending of different targets, five targets are created:Поскольку в приведенном выше коде функции sin() и cos() используются для смешивания анимации различных целевых объектов, создаются пять целевых объектов:

    • Исходный код (C++)
      mesh->setTarget(0, 1, 0, 1.0f, 0);

      This target is for the bind pose without any interpolation.Эта цель - для позы привязки (bind pose) без какой-либо интерполяции.

    • Исходный код (C++)
      mesh->setTarget(1, 1, 0, -k0, 0);
      mesh->setTarget(2, 1, 0, -k1, 0);

      These targets are used for interpolation of two animations blending.Эти целевые объекты используются для интерполяции при смешивании двух анимаций.

    • Исходный код (C++)
      mesh->setTarget(3, 1, 1, k0, 0);

      This target is used for the first animation blending, which uses the sin() function for interpolation.Этот целевой объект используется для первого смешивания анимации, которое использует функцию sin() для интерполяции.

    • Исходный код (C++)
      mesh->setTarget(4, 1, 2, k1, 0);

      This target is used for the second animation blending, which uses the cos() function for interpolation.Этот целевой объект используется для второго смешивания анимации, которое использует функцию cos() для интерполяции.

After assigning the material to the mesh, the result looks as follows:После назначения материала мешу результат выглядит следующим образом:

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