#! Contains `aabb_tree`, a tree of boxes: each leaf a box holding a number of #! its user's, as an entity's bits, and each branch the least box holding its #! two children, so what's near a box, or along a ray, is found by passing down #! only the branches that reach it, as Box2D's dynamic tree finds it. #! #! A leaf's box is grown past what it holds by the tree's margin, so what moves #! a little stays within it, and the tree isn't changed. A leaf is put where it #! grows the area of the boxes above it least, and each branch it passes is #! turned, as an AVL tree turns one, where one child is two or more deeper than #! the other, so the tree stays shallow whatever order its leaves come in. import std::math; import malunal::geometry; import malunal::linear; module malunal::physics3d; # No node. const none_node: u32 = 0xFFFFFFFF; # The deepest a tree of shallow branches can be, with room to spare: past 2^40 # leaves. const most_depth: u64 = 64; struct tree_node { var box: bounds; var data: u64; var parent: u32 = 0xFFFFFFFF; # Or the next free node, where it's free. var left: u32 = 0xFFFFFFFF; # None of a leaf. var right: u32 = 0xFFFFFFFF; var height: i32; # 0 of a leaf, and -1 where it's free. } #! A tree of boxes, each leaf holding a number of its user's, named by the leaf #! `insert` gives, which stays its name until it's removed. pub struct aabb_tree { var nodes: vector; var root: u32 = 0xFFFFFFFF; var free: u32 = 0xFFFFFFFF; var leaves: u64; #! How far each leaf's box is grown past what it holds. pub var margin: f32 = 0.1; } #! A tree of no leaves, its boxes grown by a margin. pub def aabb_tree::new(margin: f32 = 0.1): aabb_tree { return aabb_tree{ nodes = vector::::new(), margin = margin }; } #! How many leaves it holds. pub val aabb_tree::length: u64 { get => this.leaves; } #! How deep it is: 0 of no leaves or one, and 1 more for each branch down to #! its deepest leaf. pub val aabb_tree::height: i32 { get => this.root == none_node ? 0 : this.nodes[this.root as u64].height; } #! Adds a box, and a number of the user's, as a leaf. #! @returns The leaf, which names it until it's removed. pub def aabb_tree::insert(&mut this, box: bounds, data: u64): u32 { val leaf := this.allocate(); this.nodes[leaf as u64].box = grown(box, this.margin); this.nodes[leaf as u64].data = data; this.nodes[leaf as u64].height = 0; this.insert_leaf(leaf); this.leaves++; return leaf; } #! Removes a leaf. pub def aabb_tree::remove(&mut this, leaf: u32): void { this.remove_leaf(leaf); this.release(leaf); this.leaves--; } #! Moves a leaf to hold a box, where its grown box doesn't hold it already. #! @returns Whether it was moved. pub def aabb_tree::move(&mut this, leaf: u32, box: bounds): bool { return false if this.nodes[leaf as u64].box.contains(box); this.remove_leaf(leaf); this.nodes[leaf as u64].box = grown(box, this.margin); this.insert_leaf(leaf); return true; } #! The number a leaf holds. pub def aabb_tree::data(&this, leaf: u32): u64 { return this.nodes[leaf as u64].data; } #! A leaf's box, grown by the margin. pub def aabb_tree::box_of(&this, leaf: u32): bounds { return this.nodes[leaf as u64].box; } #! Visits each leaf whose box meets a box, as `visit(leaf, data)`, until it #! gives false. pub def aabb_tree::query(&this, box: bounds, visit: F): void where F: invokable { return if this.root == none_node; var stack: u32[64]; var top: u64 = 1; stack[0] = this.root; while top > 0 { top--; val index := stack[top] as u64; continue if !this.nodes[index].box.overlaps(box); if this.nodes[index].left == none_node { return if !visit(index as u32, this.nodes[index].data); } else if top + 2 <= most_depth { stack[top] = this.nodes[index].left; stack[top + 1] = this.nodes[index].right; top += 2; } } } #! Visits each leaf whose box a ray meets, from a place, along a direction of #! length 1, as far as `reach`, as `visit(leaf, data, reach)`, which gives how #! far to go on: the distance of what it found there, so only what's nearer is #! visited after; `reach` as it was, to go on as far; or 0, to stop. pub def aabb_tree::ray_cast(&this, origin: vec3, direction: vec3, reach: f32, visit: F): void where F: invokable { return if this.root == none_node; var far := reach; var stack: u32[64]; var top: u64 = 1; stack[0] = this.root; while top > 0 { top--; val index := stack[top] as u64; continue if !ray_reaches(&this.nodes[index].box, origin, direction, far); if this.nodes[index].left == none_node { val next := visit(index as u32, this.nodes[index].data, far); return if next <= 0; far = math::min(far, next); } else if top + 2 <= most_depth { stack[top] = this.nodes[index].left; stack[top + 1] = this.nodes[index].right; top += 2; } } } #! Whether the tree is as it should be: each node's parent its parent, each #! branch's box the least holding its children's, and its height one more than #! its deeper child's, each branch's children no more than one apart in height. #! For tests. pub def aabb_tree::is_sound(&this): bool { return true if this.root == none_node; return false if this.nodes[this.root as u64].parent != none_node; var stack: u32[64]; var top: u64 = 1; var seen: u64 = 0; stack[0] = this.root; while top > 0 { top--; val index := stack[top] as u64; val left := this.nodes[index].left; val right := this.nodes[index].right; if left == none_node { return false if right != none_node || this.nodes[index].height != 0; seen++; continue; } val l := &this.nodes[left as u64]; val r := &this.nodes[right as u64]; return false if l.parent != index as u32 || r.parent != index as u32; return false if this.nodes[index].height != 1 + math::max(l.height, r.height) || math::abs(l.height - r.height) > 1; return false if !(l.box.merged(r.box) == this.nodes[index].box); return false if top + 2 > most_depth; stack[top] = left; stack[top + 1] = right; top += 2; } return seen == this.leaves; } # A box grown so far each way. def grown(box: bounds, by: f32): bounds { val reach := vec3{ by, by, by }; return bounds{ box.min - reach, box.max + reach }; } # The area of a box's faces, which a tree weighs where to put a box by, as the # chance a ray or a box passing by meets it. def area_of(box: bounds): f32 { val size := box.max - box.min; return 2 * (size.x * size.y + size.y * size.z + size.z * size.x); } # Whether a ray reaches a box, from a place, along a direction, as far as # `reach`: whether it's between the box's faces along every axis at once. def ray_reaches(box: &bounds, origin: vec3, direction: vec3, reach: f32): bool { var low: f32 = 0; var high := reach; val origins: f32[3] = [origin.x, origin.y, origin.z]; val ways: f32[3] = [direction.x, direction.y, direction.z]; val lows: f32[3] = [box.min.x, box.min.y, box.min.z]; val highs: f32[3] = [box.max.x, box.max.y, box.max.z]; for i in 0..3u { if math::abs(ways[i]) < tiny { return false if origins[i] < lows[i] || origins[i] > highs[i]; continue; } var near := (lows[i] - origins[i]) / ways[i]; var far := (highs[i] - origins[i]) / ways[i]; if near > far { val swapped := near; near = far; far = swapped; } low = math::max(low, near); high = math::min(high, far); return false if low > high; } return true; } # A node to use: a free one, or a new one. def aabb_tree::allocate(&mut this): u32 { if this.free == none_node { this.nodes.append(tree_node{}); return (this.nodes.length - 1) as u32; } val made := this.free; this.free = this.nodes[made as u64].parent; this.nodes[made as u64] = tree_node{}; return made; } # Frees a node, for another to use. def aabb_tree::release(&mut this, index: u32): void { this.nodes[index as u64] = tree_node{ parent = this.free, height = -1 }; this.free = index; } # What putting a box beneath a child costs: what the child's box grows by, or # all of it, of a leaf, which a new branch takes the place of. def aabb_tree::descent_cost(&this, child: u32, box: bounds): f32 { val node := &this.nodes[child as u64]; val merged := area_of(box.merged(node.box)); return merged if node.left == none_node; return merged - area_of(node.box); } # Puts a leaf where it grows the boxes above it least: beside a node, beneath a # new branch holding both. def aabb_tree::insert_leaf(&mut this, leaf: u32): void { if this.root == none_node { this.root = leaf; this.nodes[leaf as u64].parent = none_node; return; } val box := this.nodes[leaf as u64].box; var index := this.root; while this.nodes[index as u64].left != none_node { val node_box := this.nodes[index as u64].box; val left := this.nodes[index as u64].left; val right := this.nodes[index as u64].right; val combined := area_of(node_box.merged(box)); # Beside this node, a new branch holding both; beneath it, every box # above grows as this one does. val here := 2 * combined; val inherited := 2 * (combined - area_of(node_box)); val to_left := this.descent_cost(left, box) + inherited; val to_right := this.descent_cost(right, box) + inherited; break if here < to_left && here < to_right; index = to_left < to_right ? left : right; } val sibling := index; val old_parent := this.nodes[sibling as u64].parent; val branch := this.allocate(); this.nodes[branch as u64].parent = old_parent; this.nodes[branch as u64].box = box.merged(this.nodes[sibling as u64].box); this.nodes[branch as u64].height = this.nodes[sibling as u64].height + 1; this.nodes[branch as u64].left = sibling; this.nodes[branch as u64].right = leaf; this.nodes[sibling as u64].parent = branch; this.nodes[leaf as u64].parent = branch; if old_parent == none_node { this.root = branch; } else if this.nodes[old_parent as u64].left == sibling { this.nodes[old_parent as u64].left = branch; } else { this.nodes[old_parent as u64].right = branch; } this.refit(this.nodes[leaf as u64].parent); } # Takes a leaf out, its sibling taking its parent's place. def aabb_tree::remove_leaf(&mut this, leaf: u32): void { if leaf == this.root { this.root = none_node; return; } val parent := this.nodes[leaf as u64].parent; val grandparent := this.nodes[parent as u64].parent; val sibling := this.nodes[parent as u64].left == leaf ? this.nodes[parent as u64].right : this.nodes[parent as u64].left; this.nodes[sibling as u64].parent = grandparent; this.release(parent); if grandparent == none_node { this.root = sibling; return; } if this.nodes[grandparent as u64].left == parent { this.nodes[grandparent as u64].left = sibling; } else { this.nodes[grandparent as u64].right = sibling; } this.refit(grandparent); } # Walks up from a branch to the root, turning each that's out of balance, and # making its box and height those of its children again. def aabb_tree::refit(&mut this, from: u32): void { var index := from; while index != none_node { index = this.balance(index); val left := this.nodes[index as u64].left; val right := this.nodes[index as u64].right; this.nodes[index as u64].height = 1 + math::max(this.nodes[left as u64].height, this.nodes[right as u64].height); this.nodes[index as u64].box = this.nodes[left as u64].box.merged(this.nodes[right as u64].box); index = this.nodes[index as u64].parent; } } # Turns a branch whose children are two or more apart in height: the deeper # child takes its place, and it takes the deeper child's shallower child. # @returns The node in its place now. def aabb_tree::balance(&mut this, a: u32): u32 { return a if this.nodes[a as u64].left == none_node || this.nodes[a as u64].height < 2; val b := this.nodes[a as u64].left; val c := this.nodes[a as u64].right; val leaning := this.nodes[c as u64].height - this.nodes[b as u64].height; if leaning > 1 { this.raise(a, c, b, true); return c; } if leaning < -1 { this.raise(a, b, c, false); return b; } return a; } # Raises `up`, a child of `a`, into its place: `a` becomes `up`'s first child, # beside `up`'s deeper child, and takes `up`'s shallower child where `up` was, # `other` its child still. `on_right` says `up` was `a`'s right child. def aabb_tree::raise(&mut this, a: u32, up: u32, other: u32, on_right: bool): void { val f := this.nodes[up as u64].left; val g := this.nodes[up as u64].right; # `up` takes `a`'s place beneath its parent. val above := this.nodes[a as u64].parent; this.nodes[up as u64].left = a; this.nodes[up as u64].parent = above; this.nodes[a as u64].parent = up; if above == none_node { this.root = up; } else if this.nodes[above as u64].left == a { this.nodes[above as u64].left = up; } else { this.nodes[above as u64].right = up; } # `up` keeps its deeper child; `a` takes the shallower where `up` was. val deeper := this.nodes[f as u64].height > this.nodes[g as u64].height ? f : g; val shallower := deeper == f ? g : f; this.nodes[up as u64].right = deeper; if on_right { this.nodes[a as u64].right = shallower; } else { this.nodes[a as u64].left = shallower; } this.nodes[shallower as u64].parent = a; this.nodes[a as u64].box = this.nodes[other as u64].box.merged(this.nodes[shallower as u64].box); this.nodes[a as u64].height = 1 + math::max(this.nodes[other as u64].height, this.nodes[shallower as u64].height); this.nodes[up as u64].box = this.nodes[a as u64].box.merged(this.nodes[deeper as u64].box); this.nodes[up as u64].height = 1 + math::max(this.nodes[a as u64].height, this.nodes[deeper as u64].height); }