(leaf int)
| 328 | } |
| 329 | |
| 330 | func (tree *B2DynamicTree) InsertLeaf(leaf int) { |
| 331 | tree.M_insertionCount++ |
| 332 | |
| 333 | if tree.M_root == B2_nullNode { |
| 334 | tree.M_root = leaf |
| 335 | tree.M_nodes[tree.M_root].Parent = B2_nullNode |
| 336 | return |
| 337 | } |
| 338 | |
| 339 | // Find the best sibling for this node |
| 340 | leafAABB := tree.M_nodes[leaf].Aabb |
| 341 | index := tree.M_root |
| 342 | for tree.M_nodes[index].IsLeaf() == false { |
| 343 | child1 := tree.M_nodes[index].Child1 |
| 344 | child2 := tree.M_nodes[index].Child2 |
| 345 | |
| 346 | area := tree.M_nodes[index].Aabb.GetPerimeter() |
| 347 | |
| 348 | combinedAABB := NewB2AABB() |
| 349 | combinedAABB.CombineTwoInPlace(tree.M_nodes[index].Aabb, leafAABB) |
| 350 | combinedArea := combinedAABB.GetPerimeter() |
| 351 | |
| 352 | // Cost of creating a new parent for this node and the new leaf |
| 353 | cost := 2.0 * combinedArea |
| 354 | |
| 355 | // Minimum cost of pushing the leaf further down the tree |
| 356 | inheritanceCost := 2.0 * (combinedArea - area) |
| 357 | |
| 358 | // Cost of descending into child1 |
| 359 | cost1 := 0.0 |
| 360 | if tree.M_nodes[child1].IsLeaf() { |
| 361 | aabb := NewB2AABB() |
| 362 | aabb.CombineTwoInPlace(leafAABB, tree.M_nodes[child1].Aabb) |
| 363 | cost1 = aabb.GetPerimeter() + inheritanceCost |
| 364 | } else { |
| 365 | aabb := NewB2AABB() |
| 366 | aabb.CombineTwoInPlace(leafAABB, tree.M_nodes[child1].Aabb) |
| 367 | oldArea := tree.M_nodes[child1].Aabb.GetPerimeter() |
| 368 | newArea := aabb.GetPerimeter() |
| 369 | cost1 = (newArea - oldArea) + inheritanceCost |
| 370 | } |
| 371 | |
| 372 | // Cost of descending into child2 |
| 373 | cost2 := 0.0 |
| 374 | if tree.M_nodes[child2].IsLeaf() { |
| 375 | aabb := NewB2AABB() |
| 376 | aabb.CombineTwoInPlace(leafAABB, tree.M_nodes[child2].Aabb) |
| 377 | cost2 = aabb.GetPerimeter() + inheritanceCost |
| 378 | } else { |
| 379 | aabb := NewB2AABB() |
| 380 | aabb.CombineTwoInPlace(leafAABB, tree.M_nodes[child2].Aabb) |
| 381 | oldArea := tree.M_nodes[child2].Aabb.GetPerimeter() |
| 382 | newArea := aabb.GetPerimeter() |
| 383 | cost2 = newArea - oldArea + inheritanceCost |
| 384 | } |
| 385 | |
| 386 | // Descend according to the minimum cost. |
| 387 | if cost < cost1 && cost < cost2 { |
no test coverage detected