/** * Inserts a new GameObject into the DBVH. The node bounds are supposed to be up to date. */ public bool Insert(ObiActor actor) { // If no gameobject at all, we can't insert it. if (actor == null) return false; // Create a new node. DBVHNode node = new DBVHNode(actor); node.UpdateBounds(nodes); // If there are no nodes in the tree, this is the root. if (nodes.Count == 0){ node.Index = 0; nodes.Add(node); }else{ InsertNode(node,nodes[0]); } return true; }
/** * Reursively inserts a node into the tree, starting at the provided parent node. */ private void InsertNode(DBVHNode node, DBVHNode parent) { if (parent.content != null){ //parent is a leaf. // create a new parent for both the old leaf and the new leaf. DBVHNode branch = new DBVHNode(); // our branch node is the new parent. PutNode(branch,parent.Index); PutNode(parent,branch.Left); PutNode(node,branch.Right); parent = branch; }else{ // parent is a branch node, go down the child that will suffer less volume increase. Bounds bL = nodes[parent.Left].bounds; Bounds bR = nodes[parent.Right].bounds; bL.Encapsulate(node.bounds); bR.Encapsulate(node.bounds); float volumeDiffL = bL.Volume() - nodes[parent.Left].bounds.Volume(); float volumeDiffR = bR.Volume() - nodes[parent.Right].bounds.Volume(); if (volumeDiffL < volumeDiffR) InsertNode(node,nodes[parent.Left]); else InsertNode(node,nodes[parent.Right]); } // Update parent bounds on our way up the recursion stack. parent.UpdateBounds(nodes); }