| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221 |
- //
- // Urho3D Engine
- // Copyright (c) 2008-2012 Lasse Öörni
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- //
- #include "Precompiled.h"
- #include "Component.h"
- #include "Context.h"
- #include "Log.h"
- #include "MemoryBuffer.h"
- #include "Profiler.h"
- #include "ReplicationState.h"
- #include "Scene.h"
- #include "SmoothedTransform.h"
- #include "XMLFile.h"
- #include "DebugNew.h"
- // Normalize rotation quaternion after this many incremental updates to prevent distortion
- static const int NORMALIZE_ROTATION_EVERY = 32;
- OBJECTTYPESTATIC(Node);
- Node::Node(Context* context) :
- Serializable(context),
- id_(0),
- parent_(0),
- scene_(0),
- owner_(0),
- position_(Vector3::ZERO),
- rotation_(Quaternion::IDENTITY),
- scale_(Vector3::ONE),
- worldTransform_(Matrix3x4::IDENTITY),
- rotateCount_(0),
- dirty_(false)
- {
- }
- Node::~Node()
- {
- RemoveAllChildren();
- RemoveAllComponents();
-
- // Remove from the scene
- if (scene_)
- scene_->NodeRemoved(this);
- }
- void Node::RegisterObject(Context* context)
- {
- context->RegisterFactory<Node>();
-
- /// \todo When position/rotation updates are received from the network, route to SmoothedTransform if exists
- REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String(), AM_DEFAULT);
- REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
- REF_ACCESSOR_ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
- REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
- ATTRIBUTE(Node, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE); // Network replication of vars uses custom data
- REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO, AM_NET | AM_LATESTDATA | AM_NOEDIT);
- REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
- REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_NOEDIT);
- }
- void Node::OnEvent(Object* sender, bool broadcast, StringHash eventType, VariantMap& eventData)
- {
- // Make a weak pointer to self to check for destruction during event handling
- WeakPtr<Node> self(this);
-
- // If this is a targeted event, forward it to all components
- if (!broadcast)
- {
- for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
- {
- components_[i]->OnEvent(sender, broadcast, eventType, eventData);
- if (self.Expired())
- return;
- }
- }
- else
- Object::OnEvent(sender, broadcast, eventType, eventData);
- }
- bool Node::Load(Deserializer& source)
- {
- SceneResolver resolver;
-
- // Read own ID. Will not be applied, only stored for resolving possible references
- unsigned nodeID = source.ReadInt();
- resolver.AddNode(nodeID, this);
-
- // Read attributes, components and child nodes
- bool success = Load(source, resolver);
- if (success)
- {
- resolver.Resolve();
- ApplyAttributes();
- }
-
- return success;
- }
- bool Node::Save(Serializer& dest)
- {
- // Write node ID
- if (!dest.WriteUInt(id_))
- return false;
-
- // Write attributes
- if (!Serializable::Save(dest))
- return false;
-
- // Write components
- dest.WriteVLE(components_.Size());
- for (unsigned i = 0; i < components_.Size(); ++i)
- {
- Component* component = components_[i];
- // Create a separate buffer to be able to skip unknown components during deserialization
- VectorBuffer compBuffer;
- if (!component->Save(compBuffer))
- return false;
- dest.WriteVLE(compBuffer.GetSize());
- dest.Write(compBuffer.GetData(), compBuffer.GetSize());
- }
-
- // Write child nodes
- dest.WriteVLE(children_.Size());
- for (unsigned i = 0; i < children_.Size(); ++i)
- {
- Node* node = children_[i];
- if (!node->Save(dest))
- return false;
- }
-
- return true;
- }
- bool Node::LoadXML(const XMLElement& source)
- {
- SceneResolver resolver;
-
- // Read own ID. Will not be applied, only stored for resolving possible references
- unsigned nodeID = source.GetInt("id");
- resolver.AddNode(nodeID, this);
-
- // Read attributes, components and child nodes
- bool success = LoadXML(source, resolver);
- if (success)
- {
- resolver.Resolve();
- ApplyAttributes();
- }
-
- return success;
- }
- bool Node::SaveXML(XMLElement& dest)
- {
- // Write node ID
- if (!dest.SetInt("id", id_))
- return false;
-
- // Write attributes
- if (!Serializable::SaveXML(dest))
- return false;
-
- // Write components
- for (unsigned i = 0; i < components_.Size(); ++i)
- {
- Component* component = components_[i];
- XMLElement compElem = dest.CreateChild("component");
- if (!component->SaveXML(compElem))
- return false;
- }
-
- // Write child nodes
- for (unsigned i = 0; i < children_.Size(); ++i)
- {
- Node* node = children_[i];
- XMLElement childElem = dest.CreateChild("node");
- if (!node->SaveXML(childElem))
- return false;
- }
-
- return true;
- }
- void Node::ApplyAttributes()
- {
- for (unsigned i = 0; i < components_.Size(); ++i)
- components_[i]->ApplyAttributes();
-
- for (unsigned i = 0; i < children_.Size(); ++i)
- children_[i]->ApplyAttributes();
- }
- void Node::AddReplicationState(NodeReplicationState* state)
- {
- replicationStates_.Push(state);
- }
- bool Node::SaveXML(Serializer& dest)
- {
- SharedPtr<XMLFile> xml(new XMLFile(context_));
- XMLElement rootElem = xml->CreateRoot("node");
- if (!SaveXML(rootElem))
- return false;
-
- return xml->Save(dest);
- }
- void Node::SetName(const String& name)
- {
- name_ = name;
- nameHash_ = StringHash(name);
- }
- void Node::SetPosition(const Vector3& position)
- {
- position_ = position;
- if (!dirty_)
- MarkDirty();
- }
- void Node::SetRotation(const Quaternion& rotation)
- {
- rotation_ = rotation;
- if (!dirty_)
- MarkDirty();
-
- rotateCount_ = 0;
- }
- void Node::SetDirection(const Vector3& direction)
- {
- SetRotation(Quaternion(Vector3::FORWARD, direction));
- }
- void Node::SetScale(float scale)
- {
- scale_ = Vector3(scale, scale, scale).Abs();
- if (!dirty_)
- MarkDirty();
- }
- void Node::SetScale(const Vector3& scale)
- {
- scale_ = scale.Abs();
- if (!dirty_)
- MarkDirty();
- }
- void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
- {
- position_ = position;
- rotation_ = rotation;
- if (!dirty_)
- MarkDirty();
-
- rotateCount_ = 0;
- }
- void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
- {
- position_ = position;
- rotation_ = rotation;
- scale_ = Vector3(scale, scale, scale);
- if (!dirty_)
- MarkDirty();
-
- rotateCount_ = 0;
- }
- void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
- {
- position_ = position;
- rotation_ = rotation;
- scale_ = scale;
- if (!dirty_)
- MarkDirty();
-
- rotateCount_ = 0;
- }
- void Node::SetWorldPosition(const Vector3& position)
- {
- if (!parent_)
- SetPosition(position);
- else
- SetPosition(parent_->GetWorldTransform().Inverse() * position);
- }
- void Node::SetWorldRotation(const Quaternion& rotation)
- {
- if (!parent_)
- SetRotation(rotation);
- else
- SetRotation(parent_->GetWorldRotation().Inverse() * rotation);
- }
- void Node::SetWorldDirection(const Vector3& direction)
- {
- Vector3 localDirection;
- if (!parent_)
- localDirection = direction;
- else
- localDirection = parent_->GetWorldTransform().Inverse() * direction;
-
- SetRotation(Quaternion(Vector3::FORWARD, localDirection));
- }
- void Node::SetWorldScale(float scale)
- {
- if (!parent_)
- SetScale(scale);
- else
- {
- Vector3 parentWorldScale = parent_->GetWorldScale();
- SetScale(Vector3(scale / parentWorldScale.x_, scale / parentWorldScale.y_, scale / parentWorldScale.z_));
- }
- }
- void Node::SetWorldScale(const Vector3& scale)
- {
- if (!parent_)
- SetScale(scale);
- else
- SetScale(scale / parent_->GetWorldScale());
- }
- void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
- {
- SetWorldPosition(position);
- SetWorldRotation(rotation);
- }
- void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
- {
- SetWorldPosition(position);
- SetWorldRotation(rotation);
- SetWorldScale(scale);
- }
- void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
- {
- SetWorldPosition(position);
- SetWorldRotation(rotation);
- SetWorldScale(scale);
- }
- void Node::Translate(const Vector3& delta)
- {
- position_ += delta;
- if (!dirty_)
- MarkDirty();
- }
- void Node::TranslateRelative(const Vector3& delta)
- {
- position_ += rotation_ * delta;
- if (!dirty_)
- MarkDirty();
- }
- void Node::Rotate(const Quaternion& delta, bool fixedAxis)
- {
- if (!fixedAxis)
- rotation_ = rotation_ * delta;
- else
- rotation_ = delta * rotation_;
-
- ++rotateCount_;
- if (rotateCount_ >= NORMALIZE_ROTATION_EVERY)
- {
- rotation_.Normalize();
- rotateCount_ = 0;
- }
-
- if (!dirty_)
- MarkDirty();
- }
- void Node::Yaw(float angle, bool fixedAxis)
- {
- Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
- }
- void Node::Pitch(float angle, bool fixedAxis)
- {
- Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
- }
- void Node::Roll(float angle, bool fixedAxis)
- {
- Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
- }
- void Node::LookAt(const Vector3& target, const Vector3& upAxis, bool worldSpace)
- {
- Vector3 targetZ;
- if (worldSpace)
- targetZ = (target - GetWorldPosition()).Normalized();
- else
- targetZ = (target - position_).Normalized();
-
- Vector3 targetX = upAxis.CrossProduct(targetZ).Normalized();
- Vector3 targetY = targetZ.CrossProduct(targetX).Normalized();
-
- if (!worldSpace || !parent_)
- SetRotation(Quaternion(targetX, targetY, targetZ));
- else
- SetRotation(parent_->GetWorldRotation().Inverse() * Quaternion(targetX, targetY, targetZ));
- }
- void Node::Scale(float scale)
- {
- scale_ *= scale;
- if (!dirty_)
- MarkDirty();
- }
- void Node::Scale(const Vector3& scale)
- {
- scale_ *= scale;
- if (!dirty_)
- MarkDirty();
- }
- void Node::SetOwner(Connection* owner)
- {
- owner_ = owner;
- }
- void Node::MarkDirty()
- {
- dirty_ = true;
-
- // Notify listener components first, then mark child nodes
- for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
- {
- if (*i)
- {
- (*i)->OnMarkedDirty(this);
- ++i;
- }
- // If listener has expired, erase from list
- else
- i = listeners_.Erase(i);
- }
-
- for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
- (*i)->MarkDirty();
- }
- Node* Node::CreateChild(const String& name, CreateMode mode)
- {
- Node* newNode = CreateChild(0, mode);
- newNode->SetName(name);
- return newNode;
- }
- void Node::AddChild(Node* node)
- {
- // Check for illegal or redundant parent assignment
- if (!node || node == this || node->parent_ == this)
- return;
- // Check for possible cyclic parent assignment
- Node* parent = parent_;
- while (parent)
- {
- if (parent == node)
- return;
- parent = parent->parent_;
- }
-
- // Add first, then remove from old parent, to ensure the node does not get deleted
- children_.Push(SharedPtr<Node>(node));
-
- if (node->parent_)
- node->parent_->RemoveChild(node);
-
- // Add to the scene if not added yet
- if (scene_ && !node->GetScene())
- scene_->NodeAdded(node);
-
- node->parent_ = this;
- node->MarkDirty();
- }
- void Node::RemoveChild(Node* node)
- {
- if (!node)
- return;
-
- for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
- {
- if (*i == node)
- {
- RemoveChild(i);
- return;
- }
- }
- }
- void Node::RemoveAllChildren()
- {
- while (children_.Size())
- RemoveChild(children_.End() - 1);
- }
- Component* Node::CreateComponent(ShortStringHash type, CreateMode mode)
- {
- return CreateComponent(type, 0, mode);
- }
- Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
- {
- Component* oldComponent = GetComponent(type);
- if (oldComponent)
- return oldComponent;
- else
- return CreateComponent(type, 0, mode);
- }
- void Node::RemoveComponent(Component* component)
- {
- for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if (*i == component)
- {
- WeakPtr<Component> componentWeak(*i);
-
- RemoveListener(*i);
- if (scene_)
- scene_->ComponentRemoved(*i);
- components_.Erase(i);
-
- // If the component is still referenced elsewhere, reset its node pointer now
- if (componentWeak)
- componentWeak->SetNode(0);
-
- // Mark node dirty in all replication states
- MarkReplicationDirty();
- return;
- }
- }
- }
- void Node::RemoveAllComponents()
- {
- if (components_.Empty())
- return;
-
- while (components_.Size())
- {
- Vector<SharedPtr<Component> >::Iterator i = components_.End() - 1;
- WeakPtr<Component> componentWeak(*i);
-
- RemoveListener(*i);
- if (scene_)
- scene_->ComponentRemoved(*i);
- components_.Erase(i);
-
- // If the component is still referenced elsewhere, reset its node pointer now
- if (componentWeak)
- componentWeak->SetNode(0);
- }
-
- // Mark node dirty in all replication states
- MarkReplicationDirty();
- }
- Node* Node::Clone(CreateMode mode)
- {
- // The scene itself can not be cloned
- if (this == scene_ || !parent_)
- return 0;
-
- PROFILE(CloneNode);
-
- SceneResolver resolver;
- Node* clone = CloneRecursive(parent_, resolver, mode);
- resolver.Resolve();
- clone->ApplyAttributes();
- return clone;
- }
- void Node::Remove()
- {
- if (parent_)
- parent_->RemoveChild(this);
- }
- void Node::SetParent(Node* parent)
- {
- if (parent)
- {
- Vector3 worldPosition;
- Quaternion worldRotation;
- Vector3 worldScale;
- GetWorldTransform().Decompose(worldPosition, worldRotation, worldScale);
-
- parent->AddChild(this);
- SetWorldTransform(worldPosition, worldRotation, worldScale);
- }
- }
- void Node::AddListener(Component* component)
- {
- if (!component)
- return;
-
- // Check for not adding twice
- for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
- {
- if (*i == component)
- return;
- }
-
- listeners_.Push(WeakPtr<Component>(component));
- // If the node is currently dirty, notify immediately
- if (dirty_)
- component->OnMarkedDirty(this);
- }
- void Node::RemoveListener(Component* component)
- {
- for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
- {
- if (*i == component)
- {
- listeners_.Erase(i);
- return;
- }
- }
- }
- Vector3 Node::LocalToWorld(const Vector3& position) const
- {
- return GetWorldTransform() * position;
- }
- Vector3 Node::LocalToWorld(const Vector4& vector) const
- {
- return GetWorldTransform() * vector;
- }
- Vector3 Node::WorldToLocal(const Vector3& position) const
- {
- return GetWorldTransform().Inverse() * position;
- }
- Vector3 Node::WorldToLocal(const Vector4& vector) const
- {
- return GetWorldTransform().Inverse() * vector;
- }
- unsigned Node::GetNumChildren(bool recursive) const
- {
- if (!recursive)
- return children_.Size();
- else
- {
- unsigned allChildren = children_.Size();
- for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- allChildren += (*i)->GetNumChildren(true);
-
- return allChildren;
- }
- }
- void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
- {
- dest.Clear();
-
- if (!recursive)
- {
- for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- dest.Push(*i);
- }
- else
- GetChildrenRecursive(dest);
- }
- void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
- {
- dest.Clear();
-
- if (!recursive)
- {
- for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- if ((*i)->HasComponent(type))
- dest.Push(*i);
- }
- }
- else
- GetChildrenWithComponentRecursive(dest, type);
- }
- Node* Node::GetChild(unsigned index) const
- {
- return index < children_.Size() ? children_[index].Get() : 0;
- }
- Node* Node::GetChild(const String& name, bool recursive) const
- {
- return GetChild(StringHash(name), recursive);
- }
- Node* Node::GetChild(StringHash nameHash, bool recursive) const
- {
- for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- if ((*i)->GetNameHash() == nameHash)
- return *i;
-
- if (recursive)
- {
- Node* node = (*i)->GetChild(nameHash, true);
- if (node)
- return node;
- }
- }
-
- return 0;
- }
- unsigned Node::GetNumNetworkComponents() const
- {
- unsigned num = 0;
- for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if ((*i)->GetID() < FIRST_LOCAL_ID)
- ++num;
- }
-
- return num;
- }
- void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
- {
- dest.Clear();
- for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if ((*i)->GetType() == type)
- dest.Push(*i);
- }
- }
- bool Node::HasComponent(ShortStringHash type) const
- {
- for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if ((*i)->GetType() == type)
- return true;
- }
- return false;
- }
- Component* Node::GetComponent(ShortStringHash type) const
- {
- for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if ((*i)->GetType() == type)
- return *i;
- }
- return 0;
- }
- void Node::PrepareNetworkUpdate()
- {
- // Process dependencies first
- dependencyNodes_.Clear();
-
- // Add the parent node, but if it is local, traverse to the first non-local node
- if (parent_ && parent_ != scene_)
- {
- Node* current = parent_;
- while (current->id_ >= FIRST_LOCAL_ID)
- current = current->parent_;
- if (current && current != scene_)
- dependencyNodes_.Push(current);
- }
-
- // Then let the components add their dependencies
- for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- (*i)->GetDependencyNodes(dependencyNodes_);
-
- const Vector<AttributeInfo>* attributes = GetNetworkAttributes();
- if (attributes)
- {
- unsigned numAttributes = attributes->Size();
-
- if (currentState_.Size() != numAttributes)
- {
- currentState_.Resize(numAttributes);
- previousState_.Resize(numAttributes);
-
- // Copy the default attribute values to the previous state as a starting point
- for (unsigned i = 0; i < numAttributes; ++i)
- previousState_[i] = attributes->At(i).defaultValue_;
- }
-
- // Check for attribute changes
- for (unsigned i = 0; i < numAttributes; ++i)
- {
- const AttributeInfo& attr = attributes->At(i);
- OnGetAttribute(attr, currentState_[i]);
-
- if (currentState_[i] != previousState_[i])
- {
- previousState_[i] = currentState_[i];
-
- // Mark the attribute dirty in all replication states that are tracking this node
- for (PODVector<NodeReplicationState*>::Iterator j = replicationStates_.Begin(); j != replicationStates_.End();
- ++j)
- {
- (*j)->dirtyAttributes_.Set(i);
-
- // Add node to the dirty set if not added yet
- if (!(*j)->markedDirty_)
- {
- (*j)->markedDirty_ = true;
- (*j)->sceneState_->dirtyNodes_.Insert(id_);
- }
- }
- }
- }
- }
-
- // Check for user var changes
- for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
- {
- VariantMap::ConstIterator j = previousVars_.Find(i->first_);
- if (j == previousVars_.End() || j->second_ != i->second_)
- {
- previousVars_[i->first_] = i->second_;
-
- // Mark the var dirty in all replication states that are tracking this node
- for (PODVector<NodeReplicationState*>::Iterator j = replicationStates_.Begin(); j != replicationStates_.End(); ++j)
- {
- (*j)->dirtyVars_.Insert(i->first_);
-
- if (!(*j)->markedDirty_)
- {
- (*j)->markedDirty_ = true;
- (*j)->sceneState_->dirtyNodes_.Insert(id_);
- }
- }
- }
- }
- }
- void Node::CleanupConnection(Connection* connection)
- {
- if (owner_ == connection)
- owner_ = 0;
-
- for (unsigned i = replicationStates_.Size() - 1; i < replicationStates_.Size(); --i)
- {
- if (replicationStates_[i]->connection_ == connection)
- replicationStates_.Erase(i);
- }
- }
- void Node::MarkReplicationDirty()
- {
- for (PODVector<NodeReplicationState*>::Iterator j = replicationStates_.Begin(); j != replicationStates_.End(); ++j)
- {
- // Add component's parent node to the dirty set if not added yet
- if (!(*j)->markedDirty_)
- {
- (*j)->markedDirty_ = true;
- (*j)->sceneState_->dirtyNodes_.Insert(id_);
- }
- }
- }
- void Node::SetID(unsigned id)
- {
- id_ = id;
- }
- void Node::SetScene(Scene* scene)
- {
- scene_ = scene;
- }
- void Node::SetNetPositionAttr(const Vector3& value)
- {
- SmoothedTransform* transform = GetComponent<SmoothedTransform>();
- if (transform)
- transform->SetTargetPosition(value);
- else
- SetPosition(value);
- }
- void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
- {
- MemoryBuffer buf(value);
- SmoothedTransform* transform = GetComponent<SmoothedTransform>();
- if (transform)
- transform->SetTargetRotation(buf.ReadPackedQuaternion());
- else
- SetRotation(buf.ReadPackedQuaternion());
- }
- void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
- {
- Scene* scene = GetScene();
- if (!scene)
- return;
-
- MemoryBuffer buf(value);
- // If nothing in the buffer, parent is the root node
- if (buf.IsEof())
- {
- scene->AddChild(this);
- return;
- }
-
- unsigned baseNodeID = buf.ReadNetID();
- Node* baseNode = scene->GetNode(baseNodeID);
- if (!baseNode)
- {
- LOGWARNING("Failed to find parent node " + String(baseNodeID));
- return;
- }
-
- // If buffer contains just an ID, the parent is replicated and we are done
- if (buf.IsEof())
- baseNode->AddChild(this);
- else
- {
- // Else the parent is local and we must find it recursively by name hash
- StringHash nameHash = buf.ReadStringHash();
- Node* parentNode = baseNode->GetChild(nameHash, true);
- if (!parentNode)
- LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
- else
- parentNode->AddChild(this);
- }
- }
- const Vector3& Node::GetNetPositionAttr() const
- {
- return position_;
- }
- const PODVector<unsigned char>& Node::GetNetRotationAttr() const
- {
- attrBuffer_.Clear();
- attrBuffer_.WritePackedQuaternion(rotation_);
- return attrBuffer_.GetBuffer();
- }
- const PODVector<unsigned char>& Node::GetNetParentAttr() const
- {
- attrBuffer_.Clear();
- Scene* scene = GetScene();
- if (scene && parent_ && parent_ != scene)
- {
- // If parent is replicated, can write the ID directly
- unsigned parentID = parent_->GetID();
- if (parentID < FIRST_LOCAL_ID)
- attrBuffer_.WriteNetID(parentID);
- else
- {
- // Parent is local: traverse hierarchy to find a non-local base node
- // This iteration always stops due to the scene (root) being non-local
- Node* current = parent_;
- while (current->GetID() >= FIRST_LOCAL_ID)
- current = current->GetParent();
-
- // Then write the base node ID and the parent's name hash
- attrBuffer_.WriteVLE(current->GetID());
- attrBuffer_.WriteStringHash(parent_->GetNameHash());
- }
- }
-
- return attrBuffer_.GetBuffer();
- }
- bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
- {
- // Remove all children and components first in case this is not a fresh load
- RemoveAllChildren();
- RemoveAllComponents();
-
- // ID has been read at the parent level
- if (!Serializable::Load(source))
- return false;
-
- unsigned numComponents = source.ReadVLE();
- for (unsigned i = 0; i < numComponents; ++i)
- {
- VectorBuffer compBuffer(source, source.ReadVLE());
- ShortStringHash compType = compBuffer.ReadShortStringHash();
- unsigned compID = compBuffer.ReadUInt();
- Component* newComponent = CreateComponent(compType, rewriteIDs ? 0 : compID, (mode == REPLICATED &&
- compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
- if (newComponent)
- {
- resolver.AddComponent(compID, newComponent);
- if (!newComponent->Load(compBuffer))
- return false;
- }
- }
-
- if (!readChildren)
- return true;
-
- unsigned numChildren = source.ReadVLE();
- for (unsigned i = 0; i < numChildren; ++i)
- {
- unsigned nodeID = source.ReadUInt();
- Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
- LOCAL);
- resolver.AddNode(nodeID, newNode);
- if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
- return false;
- }
-
- return true;
- }
- bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
- {
- // Remove all children and components first in case this is not a fresh load
- RemoveAllChildren();
- RemoveAllComponents();
-
- if (!Serializable::LoadXML(source))
- return false;
-
- XMLElement compElem = source.GetChild("component");
- while (compElem)
- {
- String typeName = compElem.GetAttribute("type");
- unsigned compID = compElem.GetInt("id");
- Component* newComponent = CreateComponent(ShortStringHash(typeName), rewriteIDs ? 0 : compID, (mode == REPLICATED &&
- compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
- if (newComponent)
- {
- resolver.AddComponent(compID, newComponent);
- if (!newComponent->LoadXML(compElem))
- return false;
- }
-
- compElem = compElem.GetNext("component");
- }
-
- if (!readChildren)
- return true;
-
- XMLElement childElem = source.GetChild("node");
- while (childElem)
- {
- unsigned nodeID = childElem.GetInt("id");
- Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
- LOCAL);
- resolver.AddNode(nodeID, newNode);
- if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
- return false;
-
- childElem = childElem.GetNext("node");
- }
-
- return true;
- }
- Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
- {
- // Check that creation succeeds and that the object in fact is a component
- SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
- if (!newComponent)
- {
- LOGERROR("Could not create unknown component type " + type.ToString());
- return 0;
- }
-
- components_.Push(newComponent);
-
- // If zero ID specified, or the ID is already taken, let the scene assign
- if (scene_)
- {
- if (!id || scene_->GetComponent(id))
- id = scene_->GetFreeComponentID(mode);
- newComponent->SetID(id);
- scene_->ComponentAdded(newComponent);
- }
- else
- newComponent->SetID(id);
-
- newComponent->SetNode(this);
- newComponent->OnMarkedDirty(this);
-
- // Mark node dirty in all replication states
- MarkReplicationDirty();
-
- return newComponent;
- }
- Node* Node::CreateChild(unsigned id, CreateMode mode)
- {
- SharedPtr<Node> newNode(new Node(context_));
-
- // If zero ID specified, or the ID is already taken, let the scene assign
- if (scene_)
- {
- if (!id || scene_->GetNode(id))
- id = scene_->GetFreeNodeID(mode);
- newNode->SetID(id);
- }
- else
- newNode->SetID(id);
-
- AddChild(newNode);
- return newNode;
- }
- void Node::UpdateWorldTransform() const
- {
- if (parent_)
- {
- if (parent_->dirty_)
- parent_->UpdateWorldTransform();
- worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
- }
- else
- worldTransform_ = Matrix3x4(position_, rotation_, scale_);
-
- dirty_ = false;
- }
- void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
- {
- (*i)->parent_ = 0;
- (*i)->MarkDirty();
- children_.Erase(i);
- }
- void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
- {
- for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- Node* node = *i;
- dest.Push(node);
- if (!node->children_.Empty())
- node->GetChildrenRecursive(dest);
- }
- }
- void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
- {
- for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- Node* node = *i;
- if (node->HasComponent(type))
- dest.Push(node);
- if (!node->children_.Empty())
- node->GetChildrenRecursive(dest);
- }
- }
- Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
- {
- // Create clone node
- Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
- resolver.AddNode(id_, cloneNode);
-
- // Copy attributes
- unsigned numAttributes = GetNumAttributes();
- for (unsigned j = 0; j < numAttributes; ++j)
- cloneNode->SetAttribute(j, GetAttribute(j));
-
- // Clone components
- for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- Component* component = *i;
- Component* cloneComponent = cloneNode->CreateComponent(component->GetType(), (mode == REPLICATED && component->GetID() <
- FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
- if (!cloneComponent)
- {
- LOGERROR("Could not clone component " + component->GetTypeName());
- continue;
- }
- resolver.AddComponent(component->GetID(), cloneComponent);
-
- numAttributes = component->GetNumAttributes();
- for (unsigned j = 0; j < numAttributes; ++j)
- cloneComponent->SetAttribute(j, component->GetAttribute(j));
- }
-
- // Clone child nodes recursively
- for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- Node* node = *i;
- node->CloneRecursive(cloneNode, resolver, mode);
- }
-
- return cloneNode;
- }
|