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)
VR Development
Двойная точность координат
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
Учебные материалы

Класс Unigine :: NodeReference

Header: #include <UnigineNodes.h>
Inherits from: Node

NodeReference is a node that refers to an external *.node asset on the disk, which is obtained by exporting a node from the world. The world can contain several NodeReference nodes referring to the same *.node file. NodeReference — это нода, которая ссылается на внешний файл *.node на диске, который получается путем экспорта ноды из мира.

Примечание
Мир может содержать несколько экземпляров NodeReference, ссылающихся на один и тот же файл *.node.

The *.node file usually contains a pre-fabricated node (or a hierarchy of nodes) with links to all materials, properties and physical bodies that are required for its rendering and behaviour. All changes that are made to NodeReference via UNIGINE Editor are saved to this file. When editing NodeReference via code, implement saving changes to the *.node file. Файл *.node обычно содержит предварительно созданную ноду (или иерархию нод) со всеми материалами и свойствами, которые требуются для ее визуализации. Все изменения, сделанные для NodeReference через UnigineEditor, сохраняются в этом файле.

Примечание
При редактировании NodeReference с помощью кода реализуйте сохранение изменений в файле *.node.

NodeReferences should be used to propagate multiple identical objects repeated in the world: unlike regular nodes, reference nodes are loaded into the world faster because of the internal cache usage. It will also make it easier to apply the same changes to all repeated objects. NodeReference следует использовать вместо ноды, если в мире много повторяющихся идентичных объектов: это позволит избежать ручного редактирования каждого объекта, если вам нужно внести одинаковые изменения во все эти объекты.

Примечание
A NodeReference itself does not have bounds and is excluded from the spatial tree. Ограничивающий прямоугольник NodeReference равен ограничивающему прямоугольнику его корневой ноды, хранящейся в ссылке (дочерние ноды не учитываются).

В отличие от обычных нод, NodeReference загружаются в мир быстрее из-за использования внутреннего кеша.

A NodeReference instance is a Posessor of the nodes stored by it, so it is responsible for loading and deleting them. You can detach the node from the NodeReference instance to make it managed by the World. Экземпляр NodeReference является владельцем ноды (или нод), хранящейся по ссылке, поэтому он отвечает за их загрузку и удаление.

NodeReference TransformationsПреобразования NodeReference#

Local transformation of the root node stored by NodeReference is not necessarily identity, it can be displaced relative to the NodeReference position, for example. Преобразование NodeReference отличается от преобразования ноды (или нод), хранящейся в ссылке. Однако для NodeReference используется матричная иерархия . Таким образом, при перемещении NodeReference его корневая нода, хранящаяся в ссылке, также будет перемещаться относительно этой NodeReference. При этом локальная матрица преобразования корневой NodeReference не изменится.

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

  • Article on Nodes that lists the main differences between the regular nodes and reference nodes Статья о Нодах , в которой перечислены основные различия между обычными нодами и NodeReference
  • Article on Node Reference Статья о NodeReference

Creating a Node ReferenceСоздание NodeReference#

To create a NodeReference, you should specify a path to the existing *.node file. For example, you can export a node into a *.node file and then create a NodeReference by using it: Чтобы создать NodeReference, вы должны указать путь к существующему файлу *.node. Например, вы можете экспортировать ноду в файл *.node, а затем создать NodeReference, используя его:

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

using namespace Unigine;

int AppWorldLogic::init() {

	// create a mesh
	MeshPtr mesh = Mesh::create();
	mesh->addBoxSurface("box_0", Math::vec3(1.0f));
	// create a dynamic mesh by using the mesh
	ObjectMeshDynamicPtr dynamic = ObjectMeshDynamic::create(mesh);
	// export the dynamic mesh into a *.node file
	World::saveNode("unigine_project/nodes/node_reference_0.node", dynamic->getNode());
	// create a node reference
	NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/node_reference_0.node");

	return 1;
}

Also you can cast a Node instance to the NodeReference. However, such type casting is possible only if the Node type is NODE_REFERENCE. For example: Также вы можете привести экземпляр Node к NodeReference. Однако такое приведение типов возможно только в том случае, если типом ноды является NODE_REFERENCE . Например:

Исходный код (C++)
// AppWorldLogic.h

#include <UnigineLogic.h>
#include <UnigineStreams.h>
#include <UnigineNode.h>
#include <UnigineNodes.h>

class AppWorldLogic : public Unigine::WorldLogic {
	
public:
	AppWorldLogic();
	virtual ~AppWorldLogic();
	
	virtual int init();
	
	virtual int update();
	virtual int postUpdate();
	virtual int updatePhysics();
	
	virtual int shutdown();
	
	virtual int save(const Unigine::StreamPtr &stream);
	virtual int restore(const Unigine::StreamPtr &stream);

private:

	void nodeCast(Unigine::NodePtr node);
};
Исходный код (C++)
// AppWorldLogic.cpp

#include <UnigineConsole.h>
#include <UnigineObjects.h>
#include <UnigineWorld.h>

using namespace Unigine;

void AppWorldLogic::nodeCast(NodePtr node) {
	
	// check if the node is a NodeReference
	if (node->getType() == Node::NODE_REFERENCE)
	{	
		// cast the node to the NodeReference
		NodeReferencePtr nodeRef = checked_ptr_cast<NodeReference>(node);
		// set a name for the NodeReference
		nodeRef->setName("NodeReference_cast");
	}
}

int AppWorldLogic::init() {
	
	// create a NodeReference from the file
	NodeReferencePtr nodeRef_0 = NodeReference::create("unigine_project/nodes/node_reference_0.node");

	// set a name
	nodeRef_0->setName("NodeReference_0");

	// save changes into the *.world file
	Console::run("world_save");
	// get the added NodeReference as a Node
	NodePtr node = World::getNodeByName("NodeReference_0");
	// cast the obtained Node to a NodeReference
	nodeCast(node);

	return 1;
}

As a result, the NodeReference_0 node will be converted to the NodeReference_cast node. В результате нода NodeReference_0 будет преобразована в ноду NodeReference_cast.

Editing a Node ReferenceРедактирование NodeReference#

Editing a NodeReference includes: Редактирование NodeReference включает:

  • Changing the path to the referenced .node file. Изменение пути к указанному файлу *.node.
  • Editing the node stored by the reference. Редактирование ноды, хранящейся по ссылке.

To access the node to which the NodeReference refers, use the getReference() method. To save the modified reference node to the same *.node asset, use World::saveNode() method as follows: Чтобы получить доступ к ноде, к которой относится NodeReference, используйте метод getReference(). Чтобы сохранить измененную ссылку на ноду в тот же самый ассет *.node, используйте метод World::saveNode() следующим образом:

Исходный код (C++)
#include <UnigineConsole.h>
#include <UnigineEditor.h>
#include <UnigineNodes.h>
#include <UnigineObjects.h>
#include <UnigineWorld.h>

using namespace Unigine;

int AppWorldLogic::init() {
	
	// create a NodeReference instance
	NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/node_reference_0.node");

	// set a name
	nodeRef->setName("NodeReference_0");

	// get a node stored by the reference and check if it is an ObjectMeshDynamic
	if (nodeRef->getReference()->getType() == Node::OBJECT_MESH_DYNAMIC) {
		// cast the referenced node to the ObjectMeshDynamic type
		ObjectMeshDynamicPtr dynamic = checked_ptr_cast<ObjectMeshDynamic>(nodeRef->getReference());
		// set a material
		dynamic->setMaterial("mesh_base", 0);
		// save changes on the referenced node into the *.node file
		World::saveNode(nodeRef->getNodeName(), dynamic);
	}

	return 1;
}

As a result, the source *.node file, to which the NodeReference refers, will be updated and the NodeReference_0 node will refer to the updated node with the material assigned. If you want all NodeReferences that refer to the modifed *.node asset to update automatically, you should enable automatic reloading of NodeReferences by calling the setAutoReloadNodeReferences() method preliminarily. В результате будет обновлен исходный файл *.node, на который ссылается NodeReference, а нода NodeReference_0 будет ссылаться на обновленную ноду с назначенным материалом.

NodeReference Class

Члены класса


static NodeReferencePtr create ( const char * name ) #

Constructor. Creates a new object that references a node from a given file. Конструктор. Создает новый объект, который ссылается на ноду из заданного файла.

Аргументы

  • const char * name - Path to a *.node file. Путь к файлу *.node.

void setNodeName ( const char * name ) #

Sets a reference to a new *.node file.
Исходный код (C++)
// create an NodeReference instance
NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/reference_0.node");
// ...

// change a reference node
nodeRef->setNodePath("unigine_project/nodes/reference_1.node");
Устанавливает ссылку на новый файл *.node.
Исходный код (C++)
// create an NodeReference instance
NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/reference_0.node");
// ...
// change a reference node
nodeRef->setNodeName("unigine_project/nodes/reference_1.node");

Аргументы

  • const char * name - Path to a *.node file. Путь к файлу *.node.

const char * getNodeName ( ) #

Returns the path to the referenced *.node file.
Исходный код (C++)
// create an NodeReference instance
NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/reference_0.node");
// ...

// return the path to the reference node
Log::message("The referenced node is: %s\n", nodeRef->getNodePath());
Возвращает путь к указанному файлу *.node.
Исходный код (C++)
// create an NodeReference instance
NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/reference_0.node");
// ...
// return the path to the reference node
Log::message("The referenced node is: %s\n",nodeRef->getNodeName());

Возвращаемое значение

Path to the referenced *.node file. Путь к указанному файлу *.node.

Ptr<Node> getReference ( ) #

Returns the node stored by the reference. The method should be used when you need to change the referenced node. If getReference() has returned a NodeDummy instance, it means that several nodes of the same hierarchy level has been converted into the NodeReference.
Исходный код (C++)
// create a NodeReference instance
NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/single_nref.node");
// get a node stored by the reference
NodePtr node = nodeRef->getReference();
// if the node is a NodeDummy
if (node->getType() == Node::NODE_DUMMY) {
	// print the type name of each child node of the root node stored by the reference 
	for (int i = 0; i < node->getNumChildren(); i++) {
		Log::message("%d: %s\n", i, node->getChild(i)->getTypeName());
	}
}
Возвращает ноду, хранящуюся по ссылке. Этот метод следует использовать, когда вам нужно изменить указанную ноду. Если getReference() вернул экземпляр NodeDummy, это означает, что несколько нод одного и того же уровня иерархии были преобразованы в NodeReference .
Исходный код (C++)
// create a NodeReference instance
NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/single_nref.node");
// get a node stored by the reference
NodePtr node = nodeRef->getReference();
// if the node is a NodeDummy
if (node->>getType() == Node::NODE_DUMMY){
	// print the type name of each child node of the root node stored by the reference 
	for(int i = 0; i & node->getNumChildren(); i++) {
		Log::message("%d: %s\n",i,node->getChild(i)->getTypeName());
	}
}

Возвращаемое значение

Node instance. Экземпляр ноды.

int canBeReference ( const char * name, const Ptr<Node> & node ) #

Returns a value indicating if the hierarchy of the given node does not contain a node reference with the given name. Возвращает значение, указывающее, содержит ли иерархия данной ноды NodeReference с заданным именем.

Аргументы

  • const char * name - Node reference name. Ссылочное имя ноды.
  • const Ptr<Node> & node - Node to check. Нода для проверки.

Возвращаемое значение

true if the hierarchy of the given node does not contain a node reference with the given name; otherwise, false. 1 , если иерархия данной ноды не содержит NodeReference с данным именем; в противном случае 0 .

Ptr<Node> detachReference ( ) #

Returns the node stored by the reference and releases this node of ownership so it is no longer owned and referred to by the NodeReference. The node is managed by the World.

To remove the node do the following:To remove the node do the following:

Исходный код (C++)
// create a new NodeReference instance
NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/node_reference_0.node");
// perform something
// ...
// get the node stored by the reference and release NodeReference ownership of the node
NodePtr node = nodeRef->detachReference();
// destroy the NodeReference pointer as the NodeReference doesn't refer to a node any more
nodeRef.deleteForce();
To remove the node do the following:
Возвращает ноду, сохраненную ссылкой, и освобождает эту ноду от владения, чтобы она больше не принадлежала и не упоминалась NodeReference. Нода управляется миром.

To remove the node do the following: Чтобы удалить ноду, сделайте следующее:

Исходный код (C++)
// create a new NodeReference instance
NodeReferencePtr nodeRef = NodeReference::create("unigine_project/nodes/node_reference_0.node");
// perform something
// ...
// get the node stored by the reference and release NodeReference ownership of the node
NodePtr node = nodeRef->detachReference();
// destroy the NodeReference pointer as the NodeReference doesn't refer to a node any more
nodeRef.destroy();

Возвращаемое значение

Root node of the internal hierarchy. Корневая нода внутренней иерархии.

static int type ( ) #

Returns the type of the node. Возвращает тип ноды.

Возвращаемое значение

NodeReference type identifier. идентификатор типа NodeReference.
Последнее обновление: 19.12.2023
Build: ()