/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
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.
****************************************************************************/
var PrefabHelper = require('./prefab-helper');
var Flags = require('../platform/CCObject').Flags;
var Misc = require('./misc');
var js = require('../platform/js');
var IdGenerater = require('../platform/id-generater');
var eventManager = require('../event-manager');
var Destroying = Flags.Destroying;
var DontDestroy = Flags.DontDestroy;
var Deactivating = Flags.Deactivating;
var CHILD_ADDED = 'child-added';
var CHILD_REMOVED = 'child-removed';
var idGenerater = new IdGenerater('Node');
function getConstructor(typeOrClassName) {
if (!typeOrClassName) {
cc.errorID(3804);
return null;
}
if (typeof typeOrClassName === 'string') {
return js.getClassByName(typeOrClassName);
}
return typeOrClassName;
}
function findComponent(node, constructor) {
for (var i = 0; i < node._components.length; ++i) {
var comp = node._components[i];
if (comp instanceof constructor) {
return comp;
}
}
return null;
}
function findComponents(node, constructor, components) {
for (var i = 0; i < node._components.length; ++i) {
var comp = node._components[i];
if (comp instanceof constructor) {
components.push(comp);
}
}
}
function findChildComponent(children, constructor) {
for (var i = 0; i < children.length; ++i) {
var node = children[i];
var comp = findComponent(node, constructor);
if (comp) {
return comp;
}
else if (node._children.length > 0) {
comp = findChildComponent(node._children, constructor);
if (comp) {
return comp;
}
}
}
return null;
}
function findChildComponents(children, constructor, components) {
for (var i = 0; i < children.length; ++i) {
var node = children[i];
findComponents(node, constructor, components);
if (node._children.length > 0) {
findChildComponents(node._children, constructor, components);
}
}
}
/**
* A base node for CCNode, it will:
* - maintain scene hierarchy and active logic
* - notifications if some properties changed
* - define some interfaces shares between CCNode
* - define machanisms for Enity Component Systems
* - define prefab and serialize functions
*
* @class _BaseNode
* @extends Object
* @uses EventTarget
* @constructor
* @param {String} [name]
* @private
*/
var BaseNode = cc.Class({
name: 'cc._BaseNode',
extends: cc.Object,
mixins: [cc.EventTarget],
properties: {
// SERIALIZABLE
_parent: null,
_children: [],
_active: true,
/**
* @property _components
* @type {Component[]}
* @default []
* @readOnly
* @private
*/
_components: [],
/**
* The PrefabInfo object
* @property _prefab
* @type {PrefabInfo}
* @private
*/
_prefab: null,
/**
* If true, the node is an persist node which won't be destroyed during scene transition.
* If false, the node will be destroyed automatically when loading a new scene. Default is false.
* @property _persistNode
* @type {Boolean}
* @default false
* @private
*/
_persistNode: {
get () {
return (this._objFlags & DontDestroy) > 0;
},
set (value) {
if (value) {
this._objFlags |= DontDestroy;
}
else {
this._objFlags &= ~DontDestroy;
}
}
},
// API
/**
* !#en Name of node.
* !#zh 该节点名称。
* @property name
* @type {String}
* @example
* node.name = "New Node";
* cc.log("Node Name: " + node.name);
*/
name: {
get () {
return this._name;
},
set (value) {
if (CC_DEV && value.indexOf('/') !== -1) {
cc.errorID(1632);
return;
}
this._name = value;
},
},
_id: {
default: '',
editorOnly: true
},
/**
* !#en The uuid for editor, will be stripped before building project.
* !#zh 主要用于编辑器的 uuid,在编辑器下可用于持久化存储,在项目构建之后将变成自增的 id。
* @property uuid
* @type {String}
* @readOnly
* @example
* cc.log("Node Uuid: " + node.uuid);
*/
uuid: {
get () {
var id = this._id;
if (!id) {
id = this._id = CC_EDITOR ? Editor.Utils.UuidUtils.uuid() : idGenerater.getNewId();
}
return id;
}
},
/**
* !#en All children nodes.
* !#zh 节点的所有子节点。
* @property children
* @type {Node[]}
* @readOnly
* @example
* var children = node.children;
* for (var i = 0; i < children.length; ++i) {
* cc.log("Node: " + children[i]);
* }
*/
children: {
get () {
return this._children;
}
},
/**
* !#en All children nodes.
* !#zh 节点的子节点数量。
* @property childrenCount
* @type {Number}
* @readOnly
* @example
* var count = node.childrenCount;
* cc.log("Node Children Count: " + count);
*/
childrenCount: {
get () {
return this._children.length;
}
},
/**
* !#en
* The local active state of this node.
* Note that a Node may be inactive because a parent is not active, even if this returns true.
* Use {{#crossLink "Node/activeInHierarchy:property"}}{{/crossLink}} if you want to check if the Node is actually treated as active in the scene.
* !#zh
* 当前节点的自身激活状态。
* 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。
* 如果你想检查节点在场景中实际的激活状态可以使用 {{#crossLink "Node/activeInHierarchy:property"}}{{/crossLink}}。
* @property active
* @type {Boolean}
* @default true
* @example
* node.active = false;
*/
active: {
get () {
return this._active;
},
set (value) {
value = !!value;
if (this._active !== value) {
this._active = value;
var parent = this._parent;
if (parent) {
var couldActiveInScene = parent._activeInHierarchy;
if (couldActiveInScene) {
cc.director._nodeActivator.activateNode(this, value);
}
}
}
}
},
/**
* !#en Indicates whether this node is active in the scene.
* !#zh 表示此节点是否在场景中激活。
* @property activeInHierarchy
* @type {Boolean}
* @example
* cc.log("activeInHierarchy: " + node.activeInHierarchy);
*/
activeInHierarchy: {
get () {
return this._activeInHierarchy;
}
},
},
/**
* @method constructor
* @param {String} [name]
*/
ctor (name) {
this._name = typeof name !== 'undefined' ? name : 'New Node';
this._activeInHierarchy = false;
// Support for ActionManager and EventManager
this.__instanceId = this._id || cc.ClassManager.getNewInstanceId();
/**
* Register all related EventTargets,
* all event callbacks will be removed in _onPreDestroy
* @property __eventTargets
* @type {EventTarget[]}
* @private
*/
this.__eventTargets = [];
},
/**
* !#en The parent of the node.
* !#zh 该节点的父节点。
* @property parent
* @type {Node}
* @default null
* @example
* node.parent = newNode;
*/
getParent () {
return this._parent;
},
setParent (value) {
if (this._parent === value) {
return;
}
if (CC_EDITOR && !cc.engine.isPlaying) {
if (_Scene.DetectConflict.beforeAddChild(this)) {
return;
}
}
var oldParent = this._parent;
if (CC_DEBUG && oldParent && (oldParent._objFlags & Deactivating)) {
cc.errorID(3821);
}
this._parent = value || null;
this._onSetParent(value);
if (value) {
if (CC_DEBUG && (value._objFlags & Deactivating)) {
cc.errorID(3821);
}
if (!CC_JSB) {
eventManager._setDirtyForNode(this);
}
value._children.push(this);
value.emit(CHILD_ADDED, this);
}
if (oldParent) {
if (!(oldParent._objFlags & Destroying)) {
var removeAt = oldParent._children.indexOf(this);
if (CC_DEV && removeAt < 0) {
return cc.errorID(1633);
}
oldParent._children.splice(removeAt, 1);
oldParent.emit(CHILD_REMOVED, this);
this._onHierarchyChanged(oldParent);
}
}
else if (value) {
this._onHierarchyChanged(null);
}
},
// ABSTRACT INTERFACES
/**
* !#en
* Properties configuration function
* All properties in attrs will be set to the node,
* when the setter of the node is available,
* the property will be set via setter function.
* !#zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。
* @method attr
* @param {Object} attrs - Properties to be set to node
* @example
* var attrs = { key: 0, num: 100 };
* node.attr(attrs);
*/
attr (attrs) {
js.mixin(this, attrs);
},
// composition: GET
/**
* !#en Returns a child from the container given its uuid.
* !#zh 通过 uuid 获取节点的子节点。
* @method getChildByUuid
* @param {String} uuid - The uuid to find the child node.
* @return {Node} a Node whose uuid equals to the input parameter
* @example
* var child = node.getChildByUuid(uuid);
*/
getChildByUuid (uuid) {
if (!uuid) {
cc.log("Invalid uuid");
return null;
}
var locChildren = this._children;
for (var i = 0, len = locChildren.length; i < len; i++) {
if (locChildren[i]._id === uuid)
return locChildren[i];
}
return null;
},
/**
* !#en Returns a child from the container given its name.
* !#zh 通过名称获取节点的子节点。
* @method getChildByName
* @param {String} name - A name to find the child node.
* @return {Node} a CCNode object whose name equals to the input parameter
* @example
* var child = node.getChildByName("Test Node");
*/
getChildByName (name) {
if (!name) {
cc.log("Invalid name");
return null;
}
var locChildren = this._children;
for (var i = 0, len = locChildren.length; i < len; i++) {
if (locChildren[i]._name === name)
return locChildren[i];
}
return null;
},
// composition: ADD
addChild (child) {
if (CC_DEV && !(child instanceof cc._BaseNode)) {
return cc.errorID(1634, cc.js.getClassName(child));
}
cc.assertID(child, 1606);
cc.assertID(child._parent === null, 1605);
// invokes the parent setter
child.setParent(this);
},
/**
* !#en
* Inserts a child to the node at a specified index.
* !#zh
* 插入子节点到指定位置
* @method insertChild
* @param {Node} child - the child node to be inserted
* @param {Number} siblingIndex - the sibling index to place the child in
* @example
* node.insertChild(child, 2);
*/
insertChild (child, siblingIndex) {
child.parent = this;
child.setSiblingIndex(siblingIndex);
},
// HIERARCHY METHODS
/**
* !#en Get the sibling index.
* !#zh 获取同级索引。
* @method getSiblingIndex
* @return {number}
* @example
* var index = node.getSiblingIndex();
*/
getSiblingIndex () {
if (this._parent) {
return this._parent._children.indexOf(this);
}
else {
return 0;
}
},
/**
* !#en Set the sibling index of this node.
* !#zh 设置节点同级索引。
* @method setSiblingIndex
* @param {Number} index
* @example
* node.setSiblingIndex(1);
*/
setSiblingIndex (index) {
if (!this._parent) {
return;
}
if (this._parent._objFlags & Deactivating) {
cc.errorID(3821);
return;
}
var siblings = this._parent._children;
index = index !== -1 ? index : siblings.length - 1;
var oldIndex = siblings.indexOf(this);
if (index !== oldIndex) {
siblings.splice(oldIndex, 1);
if (index < siblings.length) {
siblings.splice(index, 0, this);
}
else {
siblings.push(this);
}
this._onSiblingIndexChanged && this._onSiblingIndexChanged(index);
}
},
/**
* !#en Walk though the sub children tree of the current node.
* Each node, including the current node, in the sub tree will be visited two times, before all children and after all children.
* This function call is not recursive, it's based on stack.
* Please don't walk any other node inside the walk process.
* !#zh 遍历该节点的子树里的所有节点并按规则执行回调函数。
* 对子树中的所有节点,包含当前节点,会执行两次回调,prefunc 会在访问它的子节点之前调用,postfunc 会在访问所有子节点之后调用。
* 这个函数的实现不是基于递归的,而是基于栈展开递归的方式。
* 请不要在 walk 过程中对任何其他的节点嵌套执行 walk。
* @method Walk the child tree
* @param {Function} prefunc The callback to process node when reach the node for the first time
* @param {_BaseNode} prefunc.target The current visiting node
* @param {Function} postfunc The callback to process node when re-visit the node after walked all children in its sub tree
* @param {_BaseNode} postfunc.target The current visiting node
* @example
* node.walk(function (target) {
* console.log('Walked through node ' + target.name + ' for the first time');
* }, function (target) {
* console.log('Walked through node ' + target.name + ' after walked all children in its sub tree');
* });
*/
walk (prefunc, postfunc) {
var BaseNode = cc._BaseNode;
var index = 1;
var children, child, curr, i, afterChildren;
var stack = BaseNode._stacks[BaseNode._stackId];
if (!stack) {
stack = [];
BaseNode._stacks.push(stack);
}
BaseNode._stackId++;
stack.length = 0;
stack[0] = this;
var parent = null;
afterChildren = false;
while (index) {
index--;
curr = stack[index];
if (!curr) {
continue;
}
if (!afterChildren && prefunc) {
// pre call
prefunc(curr);
}
else if (afterChildren && postfunc) {
// post call
postfunc(curr);
}
// Avoid memory leak
stack[index] = null;
// Do not repeatly visit child tree, just do post call and continue walk
if (afterChildren) {
afterChildren = false;
}
else {
// Children not proceeded and has children, proceed to child tree
if (curr._children.length > 0) {
parent = curr;
children = curr._children;
i = 0;
stack[index] = children[i];
index++;
}
// No children, then repush curr to be walked for post func
else {
stack[index] = curr;
index++;
afterChildren = true;
}
continue;
}
// curr has no sub tree, so look into the siblings in parent children
if (children) {
i++;
// Proceed to next sibling in parent children
if (children[i]) {
stack[index] = children[i];
index++;
}
// No children any more in this sub tree, go upward
else if (parent) {
stack[index] = parent;
index++;
// Setup parent walk env
afterChildren = true;
if (parent._parent) {
children = parent._parent._children;
i = children.indexOf(parent);
parent = parent._parent;
}
else {
// At root
parent = null;
children = null;
}
// ERROR
if (i < 0) {
break;
}
}
}
}
stack.length = 0;
BaseNode._stackId--;
},
cleanup () {
},
/**
* !#en
* Remove itself from its parent node. If cleanup is `true`, then also remove all events and actions.
* If the cleanup parameter is not passed, it will force a cleanup, so it is recommended that you always pass in the `false` parameter when calling this API.
* If the node orphan, then nothing happens.
* !#zh
* 从父节点中删除该节点。如果不传入 cleanup 参数或者传入 `true`,那么这个节点上所有绑定的事件、action 都会被删除。
* 因此建议调用这个 API 时总是传入 `false` 参数。
* 如果这个节点是一个孤节点,那么什么都不会发生。
* @method removeFromParent
* @param {Boolean} [cleanup=true] - true if all actions and callbacks on this node should be removed, false otherwise.
* @see cc.Node#removeFromParentAndCleanup
* @example
* node.removeFromParent();
* node.removeFromParent(false);
*/
removeFromParent (cleanup) {
if (this._parent) {
if (cleanup === undefined)
cleanup = true;
this._parent.removeChild(this, cleanup);
}
},
/**
* !#en
* Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter.