/// <summary> /// Formats the tree to look nicely. /// </summary> public void PositionNodesNicely() { var bt = window.tree; // Assumption for Nicify: // There must be a root set. if (bt.Root == null) { return; } // This is for the node editor to use to place the nodes. var positions = new Dictionary <BehaviourNode, Vector2>(); var levels = calculateLevels(); var posParams = new PositioningParameters(); Action <BehaviourNode> positionInPlace = (node) => { positionNode(node, positions, levels, posParams); }; TreeIterator <BehaviourNode> .Traverse(bt.Root, positionInPlace, Traversal.PostOrder); foreach (var editorNode in canvas.Nodes) { var behaviour = editorNode.behaviour; if (positions.ContainsKey(behaviour)) { Vector2 pos = positions[behaviour]; editorNode.bodyRect.position = pos; } } }
private void positionNode( BehaviourNode node, Dictionary <BehaviourNode, Vector2> positions, Dictionary <BehaviourNode, int> levels, PositioningParameters posParams ) { // Obtained from level order of tree. float yLevel = levels[node] * posParams.yLevelOffset; int childCount = node.ChildCount(); // If it is a parent of 2 or more children then center in between the children. if (childCount > 1) { BehaviourNode firstChild = node.GetChildAt(0); BehaviourNode lastChild = node.GetChildAt(childCount - 1); // Get the x-midpoint between the first and last children. Vector2 firstChildPos = positions[firstChild]; Vector2 lastChildPos = positions[lastChild]; float xMid = (firstChildPos.x + lastChildPos.x) / 2f; posParams.xIntermediate = xMid; positions.Add(node, new Vector2(xMid, yLevel)); } // A node with 1 child else if (childCount == 1) { positions.Add(node, new Vector2(posParams.xIntermediate, yLevel)); } // A leaf node else { Vector2 position = new Vector2(posParams.xLeaf, yLevel); posParams.xIntermediate = posParams.xLeaf; float width = calculateNameWidth(node); // Offset the x leaf position for the next leaf node. if (width > BonsaiNode.kDefaultSize.x) { posParams.xLeaf += width + PositioningParameters.xPadding; } else { posParams.xLeaf += posParams.xDeltaLeaf; } positions.Add(node, position); } }