Класс Unigine.NodeReference
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 на диске, который получается путем экспорта ноды из мира.
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, сохраняются в этом файле.
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 следует использовать вместо ноды, если в мире много повторяющихся идентичных объектов: это позволит избежать ручного редактирования каждого объекта, если вам нужно внести одинаковые изменения во все эти объекты.
В отличие от обычных нод, 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, используя его:
using Unigine;
namespace UnigineApp
{
class AppWorldLogic : WorldLogic
{
public override bool Init()
{
// create a mesh
Mesh mesh = new Mesh();
mesh.addBoxSurface("box_0", new vec3(1.0f));
// create a dynamic mesh by using the mesh
ObjectMeshDynamic dynamic = new ObjectMeshDynamic(mesh);
// export the dynamic mesh into a *.node file
World.SaveNode("unigine_project/nodes/node_reference_0.node", dynamic);
// create a node reference
NodeReference nodeRef = new NodeReference("unigine_project/nodes/node_reference_0.node");
return true;
}
}
}
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. Например:
using Unigine;
namespace UnigineApp
{
class AppWorldLogic : WorldLogic
{
public void nodeCast(Node node)
{
// check if the node is a NodeReference
if (node.getType() == Node.NODE_REFERENCE)
{
// cast the node to the NodeReference
NodeReference nodeRef = node as NodeReference;
// set a name for the NodeReference
nodeRef.SetName("NodeReference_cast");
}
}
public override bool Init()
{
// create a NodeReference from the file
NodeReference nodeRef_0 = new NodeReference("unigine_project_10/nodes/node_reference_0.node");
// set a name
nodeRef_0.Name = "NodeReference_0";
// save changes into the *.world file
Console.Run("world_save");
// get the added NodeReference as a Node
Node node = World.GetNodeByName("NodeReference_0");
// cast the obtained Node to a NodeReference
nodeCast(node);
return true;
}
}
}
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 Reference property. To save the modified reference node to the same *.node asset, use World.SaveNode() method as follows: Чтобы получить доступ к ноде, к которой относится NodeReference, используйте свойство Reference. Чтобы сохранить измененную ссылку на ноду в тот же самый ассет *.node, используйте метод World::saveNode() следующим образом:
using Unigine;
namespace UnigineApp
{
class AppWorldLogic : WorldLogic
{
public override bool Init()
{
// create a NodeReference instance
NodeReference nodeRef = new NodeReference("unigine_project_10/nodes/node_reference_0.node");
// set a name
nodeRef.Name = "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
ObjectMeshDynamic dynamic = nodeRef.GetReference() as ObjectMeshDynamic;
// set a material
dynamic.SetMaterial("mesh_base", 0);
// save changes on the referenced node into the *.node file
World.SaveNode(nodeRef.NodeName, 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
Свойства
string NodeName#
// create an NodeReference instance
NodeReference nodeRef = new NodeReference("unigine_project/nodes/reference_0.node");
// ...
// return the path to the reference node
Log.Message("The referenced node is: {0}\n",nodeRef.NodePath);
// create an NodeReference instance
NodeReference nodeRef = new NodeReference("unigine_project/nodes/reference_0.node");
// ...
// return the path to the reference node
Log.Message("The referenced node is: {0}\n",nodeRef.getNodeName());
Node Reference#
// create a NodeReference instance
NodeReference nodeRef = new NodeReference("unigine_project/nodes/single_nref.node");
// get a node stored by the reference
Node node = nodeRef.Reference;
// if the node is a NodeDummy
if (node.Type == Node.TYPE.NODE_DUMMY){
// print the type name of each child node of the root node stored by the reference
for(int i = 0; i < node.NumChildren; i++) {
Log.Message("{0}: {1}\n",i,node.GetChild(i).TypeName);
}
}
// create a NodeReference instance
NodeReference nodeRef = new NodeReference("unigine_project/nodes/single_nref.node");
// get a node stored by the reference
Node 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("{0}: {1}\n",i,node.getChild(i).getTypeName());
}
}
Члены класса
NodeReference ( string name ) #
Constructor. Creates a new object that references a node from a given file. Конструктор. Создает новый объект, который ссылается на ноду из заданного файла.Аргументы
- string name - Path to a *.node file. Путь к файлу *.node.
bool CanBeReference ( string name, Node node ) #
Returns a value indicating if the hierarchy of the given node does not contain a node reference with the given name. Возвращает значение, указывающее, содержит ли иерархия данной ноды NodeReference с заданным именем.Аргументы
- string name - Node reference name. Ссылочное имя ноды.
- 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 .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.// create a new NodeReference instance
NodeReference nodeRef = new NodeReference("unigine_project/nodes/node_reference_0.node");
// perform something
// ...
// get the node stored by the reference and release NodeReference ownership of the node
Node node = nodeRef.DetachReference();
// destroy the NodeReference pointer as the NodeReference doesn't refer to a node any more
nodeRef.DeleteForce();
// create a new NodeReference instance
NodeReference nodeRef = new NodeReference("unigine_project/nodes/node_reference_0.node");
// perform something
// ...
// get the node stored by the reference and release NodeReference ownership of the node
Node node = nodeRef.detachReference();
// destroy the NodeReference pointer as the NodeReference doesn't refer to a node any more
nodeRef.destroyPtr();