aiquadtreejs 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  Part of the [ai\*js micro-runtime ecosystem](https://github.com/yshengliao) — see also [aifsmjs](https://github.com/yshengliao/aifsmjs) (FSM), [aiecsjs](https://github.com/yshengliao/aiecsjs) (ECS), [aibridgejs](https://github.com/yshengliao/aibridgejs) (cross-context RPC), [aieventjs](https://github.com/yshengliao/aieventjs) (event emitter), [aipooljs](https://github.com/yshengliao/aipooljs) (object pool), and [aiaudiojs](https://github.com/yshengliao/aiaudiojs) (Web Audio shell).
12
12
 
13
- > **Status: 0.3.0 published.** Adds `retrieveInto(region, target)` zero-allocation broadphase + property-based dedup invariants. ≥95% coverage, ≤2 KB gzip.
13
+ > **Status: 0.3.1 published.** `retrieveInto(region, target)` is a steady-state zero-allocation broadphase (reused internal scratch + caller buffer); property-based dedup invariants. ≥95% coverage, ≤2 KB gzip.
14
14
 
15
15
  ---
16
16
 
package/README_ZHTW.md CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  隸屬 [ai\*js micro-runtime 生態系](https://github.com/yshengliao) ─ 另見 [aifsmjs](https://github.com/yshengliao/aifsmjs)(FSM)、[aiecsjs](https://github.com/yshengliao/aiecsjs)(ECS)、[aibridgejs](https://github.com/yshengliao/aibridgejs)(cross-context RPC)、[aieventjs](https://github.com/yshengliao/aieventjs)(event emitter)、[aipooljs](https://github.com/yshengliao/aipooljs)(物件池)、[aiaudiojs](https://github.com/yshengliao/aiaudiojs)(Web Audio 薄殼)。
12
12
 
13
- > **狀態:0.3.0 已發佈。** 新增 `retrieveInto(region, target)` 零分配 broadphase 與 property-based 去重不變式驗證。≥95% coverage,≤2 KB gzip。
13
+ > **狀態:0.3.1 已發佈。** `retrieveInto(region, target)` 為 steady-state 零分配 broadphase(內部 scratch 重用 + caller buffer)與 property-based 去重不變式驗證。≥95% coverage,≤2 KB gzip。
14
14
 
15
15
  ---
16
16
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var h=class extends Error{name="QuadtreeError"},m=class extends Error{name="QuadtreeDisposedError"};function x(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function A(e,t){let i=e.bounds.x+e.bounds.width/2,s=e.bounds.y+e.bounds.height/2,n=t.x<i,o=t.width===0?t.x>=i:t.x+t.width>i,d=t.y<s,c=t.height===0?t.y>=s:t.y+t.height>s,r=[];return d&&n&&r.push(0),d&&o&&r.push(1),c&&n&&r.push(2),c&&o&&r.push(3),r}function w(e){let t=e.bounds.width/2,i=e.bounds.height/2,s=e.bounds.x,n=e.bounds.y,o=e.level+1;e.children.push({bounds:{x:s,y:n,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s+t,y:n,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s,y:n+i,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s+t,y:n+i,width:t,height:i},level:o,objects:[],children:[]});for(let d of e.objects)for(let c of A(e,d)){let r=e.children[c];r!==void 0&&r.objects.push(d);}e.objects.length=0;}function B(e,t,i,s){if(!(e.level===0&&!x(e.bounds,t))){if(e.children.length===4){for(let n of A(e,t)){let o=e.children[n];o!==void 0&&B(o,t,i,s);}return}e.objects.push(t),e.objects.length>i&&e.level<s&&w(e);}}function v(e){e.objects.length=0;for(let t of e.children)v(t);e.children.length=0;}function y(e){let{bounds:t}=e,i=e.maxObjects??10,s=e.maxLevels??4;if(!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.width)||!Number.isFinite(t.height))throw new h("bounds must contain finite numbers");if(t.width<=0)throw new h("bounds.width must be > 0");if(t.height<=0)throw new h("bounds.height must be > 0");if(!Number.isInteger(i)||i<=0)throw new h("maxObjects must be a positive integer");if(!Number.isInteger(s)||s<=0)throw new h("maxLevels must be a positive integer");let n={root:{bounds:{...t},level:0,objects:[],children:[]},maxObjects:i,maxLevels:s,disposed:false};function o(){if(n.disposed)throw new m("aiquadtreejs: quadtree has been disposed")}function d(u){o(),B(n.root,u,n.maxObjects,n.maxLevels);}function c(u){let l=new Set,b=[n.root];for(;b.length>0;){let f=b.pop();if(f!==void 0&&x(f.bounds,u)){for(let a of f.objects)l.add(a);for(let a of f.children)b.push(a);}}return l}function r(u){return o(),Array.from(c(u))}function p(u,l){o();let b=c(u);l.length=0;for(let f of b)l.push(f);return l}function g(){o(),v(n.root);}function T(){n.disposed||(n.disposed=true,n.root.objects.length=0,n.root.children.length=0);}return {insert:d,retrieve:r,retrieveInto:p,clear:g,dispose:T,get disposed(){return n.disposed}}}exports.QuadtreeDisposedError=m;exports.QuadtreeError=h;exports.createQuadtree=y;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var l=class extends Error{name="QuadtreeError"},b=class extends Error{name="QuadtreeDisposedError"};function m(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function x(e,t){let i=e.bounds.x+e.bounds.width/2,s=e.bounds.y+e.bounds.height/2,n=t.x<i,o=t.width===0?t.x>=i:t.x+t.width>i,u=t.y<s,d=t.height===0?t.y>=s:t.y+t.height>s,r=[];return u&&n&&r.push(0),u&&o&&r.push(1),d&&n&&r.push(2),d&&o&&r.push(3),r}function y(e){let t=e.bounds.width/2,i=e.bounds.height/2,s=e.bounds.x,n=e.bounds.y,o=e.level+1;e.children.push({bounds:{x:s,y:n,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s+t,y:n,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s,y:n+i,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s+t,y:n+i,width:t,height:i},level:o,objects:[],children:[]});for(let u of e.objects)for(let d of x(e,u)){let r=e.children[d];r!==void 0&&r.objects.push(u);}e.objects.length=0;}function A(e,t,i,s){if(!(e.level===0&&!m(e.bounds,t))){if(e.children.length===4){for(let n of x(e,t)){let o=e.children[n];o!==void 0&&A(o,t,i,s);}return}e.objects.push(t),e.objects.length>i&&e.level<s&&y(e);}}function B(e){e.objects.length=0;for(let t of e.children)B(t);e.children.length=0;}function N(e){let{bounds:t}=e,i=e.maxObjects??10,s=e.maxLevels??4;if(!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.width)||!Number.isFinite(t.height))throw new l("bounds must contain finite numbers");if(t.width<=0)throw new l("bounds.width must be > 0");if(t.height<=0)throw new l("bounds.height must be > 0");if(!Number.isInteger(i)||i<=0)throw new l("maxObjects must be a positive integer");if(!Number.isInteger(s)||s<=0)throw new l("maxLevels must be a positive integer");let n={root:{bounds:{...t},level:0,objects:[],children:[]},maxObjects:i,maxLevels:s,disposed:false};function o(){if(n.disposed)throw new b("aiquadtreejs: quadtree has been disposed")}function u(h){o(),A(n.root,h,n.maxObjects,n.maxLevels);}let d=new Set,r=[];function a(h){for(d.clear(),r.length=0,r.push(n.root);r.length>0;){let c=r.pop();if(c!==void 0&&m(c.bounds,h)){for(let f of c.objects)d.add(f);for(let f of c.children)r.push(f);}}return d}function v(h){return o(),Array.from(a(h))}function p(h,c){o();let f=a(h);c.length=0;for(let w of f)c.push(w);return c}function g(){o(),B(n.root);}function T(){n.disposed||(n.disposed=true,n.root.objects.length=0,n.root.children.length=0,d.clear(),r.length=0);}return {insert:u,retrieve:v,retrieveInto:p,clear:g,dispose:T,get disposed(){return n.disposed}}}exports.QuadtreeDisposedError=b;exports.QuadtreeError=l;exports.createQuadtree=N;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["QuadtreeError","QuadtreeDisposedError","rectsOverlap","a","b","quadrantIndices","node","obj","midX","midY","inLeft","inRight","inTop","inBottom","result","subdivide","w","h","x","y","lvl","i","child","insertNode","maxObjects","maxLevels","clearNode","createQuadtree","opts","bounds","state","ck","insert","retrie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CACrBV,GAAG,CACHL,CAAAA,CAAUI,EAAM,IAAI,EACtB,CAEA,SAASY,GAAgB,CACnBZ,CAAAA,CAAM,QAAA,GACVA,CAAAA,CAAM,SAAW,IAAA,CACjBA,CAAAA,CAAM,IAAA,CAAK,OAAA,CAAQ,OAAS,CAAA,CAC5BA,CAAAA,CAAM,IAAA,CAAK,QAAA,CAAS,OAAS,CAAA,EAC/B,CAEA,OAAO,CACL,OAAAE,CAAAA,CACA,QAAA,CAAAI,CAAAA,CACA,YAAA,CAAAC,EACA,KAAA,CAAAI,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAI,QAAA,EAAW,CACb,OAAOZ,CAAAA,CAAM,QACf,CACF,CACF","file":"index.cjs","sourcesContent":["// aiquadtreejs — 2D quadtree for per-frame rebuild collision broadphase.\n//\n// v0.1.0: full implementation. Plain-object nodes, iterative-DFS retrieve,\n// Set-based dedup, idempotent dispose, destructurable methods (no `this`).\n\n/**\n * Axis-aligned bounding box.\n *\n * Coordinate semantics follow PixiJS `getBounds()`: `x` / `y` are the top-left\n * corner and `x + width` / `y + height` are **exclusive**. A 32×32 sprite at\n * `(0, 0)` covers pixels `[0, 32)` on both axes.\n *\n * @public\n */\nexport interface AABB {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Configuration for {@link createQuadtree}.\n *\n * @public\n */\nexport interface QuadtreeOptions {\n /**\n * Outer bounds. Objects partially outside `bounds` still insert into\n * whichever child nodes they overlap; objects fully outside are ignored\n * by `retrieve()` because no node overlaps them.\n */\n bounds: AABB;\n\n /**\n * Threshold above which a node subdivides. Default `10`. Lower values\n * mean deeper trees and fewer candidates per `retrieve()`; higher values\n * mean shallower trees and cheaper `insert()`.\n */\n maxObjects?: number;\n\n /**\n * Maximum subdivision depth. Default `4`. Caps recursion so a very dense\n * cluster doesn't blow up into an unbounded tree.\n */\n maxLevels?: number;\n}\n\n/**\n * Quadtree storing objects that extend {@link AABB}. `T` may carry any\n * payload (entity ID, sprite reference, user data) alongside the geometry.\n *\n * The expected usage pattern is **per-frame rebuild**: at the start of each\n * frame, call `clear()` and re-`insert()` every active object. This is\n * cheaper than tracking movements through the tree and gives correct results\n * regardless of how objects moved.\n *\n * @public\n */\nexport interface Quadtree<T extends AABB> {\n /**\n * Insert an object. The same object reference may legitimately appear\n * in multiple leaf nodes when it spans quadrant boundaries; `retrieve()`\n * deduplicates with a `Set` so the caller sees it exactly once.\n */\n insert(obj: T): void;\n\n /**\n * Return every inserted object whose containing node overlaps `region`,\n * deduplicated. The result is a **broadphase**: callers must still run\n * a precise AABB or pixel-level hit test on each candidate.\n */\n retrieve(region: AABB): T[];\n\n /**\n * Zero-allocation variant of {@link retrieve}.\n *\n * Clears `target` (sets `target.length = 0`), walks the tree using the same\n * iterative DFS + Set-based dedup as {@link retrieve}, then writes every\n * deduplicated candidate into `target` and returns it.\n *\n * Designed for hot-path callers (per-frame broadphase queries in a game\n * loop) that hold a permanent `T[]` buffer and want to avoid allocating a\n * fresh result array on every call.\n *\n * @invariant `target` identity is preserved — only its contents are\n * replaced. `retrieveInto(r, buf) === buf` always holds.\n * @invariant After return, `target.length` equals the deduplicated\n * candidate count. No `undefined` / `null` holes.\n * @invariant Empty result set → `target.length === 0`.\n * @invariant Dedup semantics identical to {@link retrieve}: objects\n * spanning multiple quadrants appear exactly once.\n *\n * Note: `retrieveInto` is not strictly zero-allocation — the internal\n * dedup `Set<T>` and DFS stack are still allocated per call. What it\n * eliminates is the result `Array` allocation, which is the largest\n * frame-to-frame churn item.\n */\n retrieveInto(region: AABB, target: T[]): T[];\n\n /**\n * Reset the tree to empty. The root node object is reused across\n * frames; child nodes are released on clear() and re-created next\n * time subdivision triggers. The per-frame churn is bounded by\n * `4 * (subdivided-internal-node-count)` and stays well inside V8's\n * young-generation budget for typical game-loop usage.\n */\n clear(): void;\n\n /**\n * Idempotent teardown. Drops references so the GC can reclaim everything.\n * Subsequent `insert` / `retrieve` / `clear` throw {@link QuadtreeDisposedError}.\n */\n dispose(): void;\n\n /** `true` once {@link dispose} has been called. */\n readonly disposed: boolean;\n}\n\n/**\n * Recoverable quadtree error — currently unused at the public surface, but\n * reserved for future precondition violations (e.g. an inserted object with\n * `NaN` coordinates or negative `width`).\n *\n * @public\n */\nexport class QuadtreeError extends Error {\n override readonly name = \"QuadtreeError\";\n}\n\n/**\n * Thrown by any quadtree method called after {@link Quadtree.dispose}.\n *\n * @public\n */\nexport class QuadtreeDisposedError extends Error {\n override readonly name = \"QuadtreeDisposedError\";\n}\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\ninterface Node<T extends AABB> {\n bounds: AABB;\n level: number;\n objects: T[];\n children: Node<T>[];\n}\n\ninterface State<T extends AABB> {\n root: Node<T>;\n maxObjects: number;\n maxLevels: number;\n disposed: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction rectsOverlap(a: AABB, b: AABB): boolean {\n return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;\n}\n\nfunction quadrantIndices<T extends AABB>(node: Node<T>, obj: AABB): number[] {\n const midX = node.bounds.x + node.bounds.width / 2;\n const midY = node.bounds.y + node.bounds.height / 2;\n // Zero-extent objects (points) sitting exactly on midX / midY would fall\n // through both `<` and `>` checks; treat the point as belonging to the\n // right/bottom side so it doesn't silently disappear.\n const inLeft = obj.x < midX;\n const inRight = obj.width === 0 ? obj.x >= midX : obj.x + obj.width > midX;\n const inTop = obj.y < midY;\n const inBottom = obj.height === 0 ? obj.y >= midY : obj.y + obj.height > midY;\n const result: number[] = [];\n if (inTop && inLeft) result.push(0);\n if (inTop && inRight) result.push(1);\n if (inBottom && inLeft) result.push(2);\n if (inBottom && inRight) result.push(3);\n return result;\n}\n\nfunction subdivide<T extends AABB>(node: Node<T>): void {\n const w = node.bounds.width / 2;\n const h = node.bounds.height / 2;\n const x = node.bounds.x;\n const y = node.bounds.y;\n const lvl = node.level + 1;\n node.children.push(\n { bounds: { x, y, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x: x + w, y, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x, y: y + h, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x: x + w, y: y + h, width: w, height: h }, level: lvl, objects: [], children: [] },\n );\n for (const obj of node.objects) {\n for (const i of quadrantIndices(node, obj)) {\n const child = node.children[i];\n if (child !== undefined) child.objects.push(obj);\n }\n }\n node.objects.length = 0;\n}\n\nfunction insertNode<T extends AABB>(\n node: Node<T>,\n obj: T,\n maxObjects: number,\n maxLevels: number,\n): void {\n // Reject objects entirely outside the root bounds; for inner nodes we\n // trust `quadrantIndices` to route correctly (it has zero-extent fallback\n // logic that `rectsOverlap` does not, so the strict check is too tight\n // at child level for points sitting on a child boundary).\n if (node.level === 0 && !rectsOverlap(node.bounds, obj)) return;\n if (node.children.length === 4) {\n for (const i of quadrantIndices(node, obj)) {\n const child = node.children[i];\n if (child !== undefined) insertNode(child, obj, maxObjects, maxLevels);\n }\n return;\n }\n node.objects.push(obj);\n if (node.objects.length > maxObjects && node.level < maxLevels) {\n subdivide(node);\n }\n}\n\nfunction clearNode<T extends AABB>(node: Node<T>): void {\n node.objects.length = 0;\n for (const child of node.children) {\n clearNode(child);\n }\n node.children.length = 0;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Construct a 2D quadtree.\n *\n * @example\n * ```ts\n * import { createQuadtree, type AABB } from \"aiquadtreejs\";\n *\n * interface Body extends AABB {\n * id: number;\n * }\n *\n * const entities: Body[] = [\n * { id: 1, x: 100, y: 100, width: 32, height: 32 },\n * { id: 2, x: 400, y: 250, width: 32, height: 32 },\n * ];\n * const player: Body = { id: 0, x: 200, y: 200, width: 32, height: 32 };\n *\n * const qt = createQuadtree<Body>({\n * bounds: { x: 0, y: 0, width: 800, height: 600 },\n * maxObjects: 10,\n * maxLevels: 4,\n * });\n *\n * // Per-frame:\n * qt.clear();\n * for (const e of entities) qt.insert(e);\n *\n * // Broadphase lookup near the player:\n * const region: AABB = { x: player.x - 50, y: player.y - 50, width: 100, height: 100 };\n * const candidates = qt.retrieve(region);\n * // Caller runs a precise hit test on `candidates`.\n * ```\n *\n * @public\n */\nexport function createQuadtree<T extends AABB>(opts: QuadtreeOptions): Quadtree<T> {\n const { bounds } = opts;\n const maxObjects = opts.maxObjects ?? 10;\n const maxLevels = opts.maxLevels ?? 4;\n\n if (\n !Number.isFinite(bounds.x) ||\n !Number.isFinite(bounds.y) ||\n !Number.isFinite(bounds.width) ||\n !Number.isFinite(bounds.height)\n ) {\n throw new QuadtreeError(\"bounds must contain finite numbers\");\n }\n if (bounds.width <= 0) {\n throw new QuadtreeError(\"bounds.width must be > 0\");\n }\n if (bounds.height <= 0) {\n throw new QuadtreeError(\"bounds.height must be > 0\");\n }\n if (!Number.isInteger(maxObjects) || maxObjects <= 0) {\n throw new QuadtreeError(\"maxObjects must be a positive integer\");\n }\n if (!Number.isInteger(maxLevels) || maxLevels <= 0) {\n throw new QuadtreeError(\"maxLevels must be a positive integer\");\n }\n\n const state: State<T> = {\n root: {\n bounds: { ...bounds },\n level: 0,\n objects: [],\n children: [],\n },\n maxObjects,\n maxLevels,\n disposed: false,\n };\n\n function ck(): void {\n if (state.disposed) throw new QuadtreeDisposedError(\"aiquadtreejs: quadtree has been disposed\");\n }\n\n function insert(obj: T): void {\n ck();\n insertNode(state.root, obj, state.maxObjects, state.maxLevels);\n }\n\n function retrieveSet(region: AABB): Set<T> {\n const result = new Set<T>();\n const stack: Node<T>[] = [state.root];\n while (stack.length > 0) {\n const node = stack.pop();\n if (node === undefined) continue;\n if (!rectsOverlap(node.bounds, region)) continue;\n for (const obj of node.objects) result.add(obj);\n for (const child of node.children) stack.push(child);\n }\n return result;\n }\n\n function retrieve(region: AABB): T[] {\n ck();\n return Array.from(retrieveSet(region));\n }\n\n function retrieveInto(region: AABB, target: T[]): T[] {\n ck();\n const set = retrieveSet(region);\n target.length = 0;\n for (const v of set) target.push(v);\n return target;\n }\n\n function clear(): void {\n ck();\n clearNode(state.root);\n }\n\n function dispose(): void {\n if (state.disposed) return;\n state.disposed = true;\n state.root.objects.length = 0;\n state.root.children.length = 0;\n }\n\n return {\n insert,\n retrieve,\n retrieveInto,\n clear,\n dispose,\n get disposed() {\n return state.disposed;\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts"],"names":["QuadtreeError","QuadtreeDisposedError","rectsOverlap","a","b","quadrantIndices","node","obj","midX","midY","inLeft","inRight","inTop","inBottom","result","subdivide","w","h","x","y","lvl","i","child","insertNode","maxObjects","maxLevels","clearNode","createQuadtree","opts","bounds","state","ck","insert","scratchSet","scratchStack","retrieveSet","region","retrieve","retrieveInto","target","set","v","clear","dispose"],"mappings":"aAkIO,IAAMA,EAAN,cAA4B,KAAM,CACrB,IAAA,CAAO,eAC3B,CAAA,CAOaC,CAAAA,CAAN,cAAoC,KAAM,CAC7B,IAAA,CAAO,uBAC3B,EAwBA,SAASC,EAAaC,CAAAA,CAASC,CAAAA,CAAkB,CAC/C,OAAOD,EAAE,CAAA,CAAIC,CAAAA,CAAE,CAAA,CAAIA,CAAAA,CAAE,OAASD,CAAAA,CAAE,CAAA,CAAIA,CAAAA,CAAE,KAAA,CAAQC,EAAE,CAAA,EAAKD,CAAAA,CAAE,EAAIC,CAAAA,CAAE,CAAA,CAAIA,EAAE,MAAA,EAAUD,CAAAA,CAAE,CAAA,CAAIA,CAAAA,CAAE,OAASC,CAAAA,CAAE,CAClG,CAEA,SAASC,EAAgCC,CAAAA,CAAeC,CAAAA,CAAqB,CAC3E,IAAMC,EAAOF,CAAAA,CAAK,MAAA,CAAO,EAAIA,CAAAA,CAAK,MAAA,CAAO,MAAQ,CAAA,CAC3CG,CAAAA,CAAOH,CAAAA,CAAK,MAAA,CAAO,EAAIA,CAAAA,CAAK,MAAA,CAAO,MAAA,CAAS,CAAA,CAI5CI,EAASH,CAAAA,CAAI,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AK,QAAA,CAAU4B,EAAa,IAAA,CAAKZ,CAAK,EAAA,CAC5D,CACA,OAAOW,CACT,CAEA,SAASI,CAAAA,CAASD,EAAmB,CACnC,OAAAL,GAAG,CACI,KAAA,CAAM,KAAKI,CAAAA,CAAYC,CAAM,CAAC,CACvC,CAEA,SAASE,CAAAA,CAAaF,CAAAA,CAAcG,CAAAA,CAAkB,CACpDR,CAAAA,EAAG,CACH,IAAMS,CAAAA,CAAML,EAAYC,CAAM,CAAA,CAC9BG,EAAO,MAAA,CAAS,CAAA,CAChB,QAAWE,CAAAA,IAAKD,CAAAA,CAAKD,CAAAA,CAAO,IAAA,CAAKE,CAAC,CAAA,CAClC,OAAOF,CACT,CAEA,SAASG,CAAAA,EAAc,CACrBX,CAAAA,EAAG,CACHL,EAAUI,CAAAA,CAAM,IAAI,EACtB,CAEA,SAASa,GAAgB,CACnBb,CAAAA,CAAM,QAAA,GACVA,CAAAA,CAAM,SAAW,IAAA,CACjBA,CAAAA,CAAM,IAAA,CAAK,OAAA,CAAQ,OAAS,CAAA,CAC5BA,CAAAA,CAAM,IAAA,CAAK,QAAA,CAAS,OAAS,CAAA,CAC7BG,CAAAA,CAAW,OAAM,CACjBC,CAAAA,CAAa,OAAS,CAAA,EACxB,CAEA,OAAO,CACL,OAAAF,CAAAA,CACA,QAAA,CAAAK,CAAAA,CACA,YAAA,CAAAC,EACA,KAAA,CAAAI,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAI,QAAA,EAAW,CACb,OAAOb,CAAAA,CAAM,QACf,CACF,CACF","file":"index.cjs","sourcesContent":["// aiquadtreejs — 2D quadtree for per-frame rebuild collision broadphase.\n//\n// v0.1.0: full implementation. Plain-object nodes, iterative-DFS retrieve,\n// Set-based dedup, idempotent dispose, destructurable methods (no `this`).\n\n/**\n * Axis-aligned bounding box.\n *\n * Right-open coordinate semantics: `x` / `y` are the top-left corner and\n * `x + width` / `y + height` are **exclusive**. A 32×32 box at `(0, 0)`\n * covers `[0, 32)` on both axes. (This matches the convention used by\n * renderers such as PixiJS `getBounds()`, but the type is renderer-agnostic.)\n *\n * @public\n */\nexport interface AABB {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Configuration for {@link createQuadtree}.\n *\n * @public\n */\nexport interface QuadtreeOptions {\n /**\n * Outer bounds. Objects partially outside `bounds` still insert into\n * whichever child nodes they overlap; objects fully outside are ignored\n * by `retrieve()` because no node overlaps them.\n */\n bounds: AABB;\n\n /**\n * Threshold above which a node subdivides. Default `10`. Lower values\n * mean deeper trees and fewer candidates per `retrieve()`; higher values\n * mean shallower trees and cheaper `insert()`.\n */\n maxObjects?: number;\n\n /**\n * Maximum subdivision depth. Default `4`. Caps recursion so a very dense\n * cluster doesn't blow up into an unbounded tree.\n */\n maxLevels?: number;\n}\n\n/**\n * Quadtree storing objects that extend {@link AABB}. `T` may carry any\n * payload (entity ID, sprite reference, user data) alongside the geometry.\n *\n * The expected usage pattern is **per-frame rebuild**: at the start of each\n * frame, call `clear()` and re-`insert()` every active object. This is\n * cheaper than tracking movements through the tree and gives correct results\n * regardless of how objects moved.\n *\n * @public\n */\nexport interface Quadtree<T extends AABB> {\n /**\n * Insert an object. The same object reference may legitimately appear\n * in multiple leaf nodes when it spans quadrant boundaries; `retrieve()`\n * deduplicates with a `Set` so the caller sees it exactly once.\n */\n insert(obj: T): void;\n\n /**\n * Return every inserted object whose containing node overlaps `region`,\n * deduplicated. The result is a **broadphase**: callers must still run\n * a precise AABB or pixel-level hit test on each candidate.\n */\n retrieve(region: AABB): T[];\n\n /**\n * Zero-allocation variant of {@link retrieve}.\n *\n * Clears `target` (sets `target.length = 0`), walks the tree using the same\n * iterative DFS + Set-based dedup as {@link retrieve}, then writes every\n * deduplicated candidate into `target` and returns it.\n *\n * Designed for hot-path callers (per-frame broadphase queries in a game\n * loop) that hold a permanent `T[]` buffer and want to avoid allocating a\n * fresh result array on every call.\n *\n * @invariant `target` identity is preserved — only its contents are\n * replaced. `retrieveInto(r, buf) === buf` always holds.\n * @invariant After return, `target.length` equals the deduplicated\n * candidate count. No `undefined` / `null` holes.\n * @invariant Empty result set → `target.length === 0`.\n * @invariant Dedup semantics identical to {@link retrieve}: objects\n * spanning multiple quadrants appear exactly once.\n *\n * Allocation: in steady state this performs no per-call heap allocation.\n * The dedup `Set` and DFS stack are reused across calls (cleared, not\n * re-created), and results are written into the caller's `target` instead\n * of a fresh array. The first calls may grow the internal scratch; once\n * result sizes stabilise, allocation amortises to zero — the design goal\n * for per-frame broadphase loops issuing thousands of queries.\n */\n retrieveInto(region: AABB, target: T[]): T[];\n\n /**\n * Reset the tree to empty. The root node object is reused across\n * frames; child nodes are released on clear() and re-created next\n * time subdivision triggers. The per-frame churn is bounded by\n * `4 * (subdivided-internal-node-count)` and stays well inside V8's\n * young-generation budget for typical game-loop usage.\n */\n clear(): void;\n\n /**\n * Idempotent teardown. Drops references so the GC can reclaim everything.\n * After disposal, every method except `dispose` itself — `insert`,\n * `retrieve`, `retrieveInto`, `clear` — throws {@link QuadtreeDisposedError}.\n */\n dispose(): void;\n\n /** `true` once {@link dispose} has been called. */\n readonly disposed: boolean;\n}\n\n/**\n * Recoverable quadtree error — currently unused at the public surface, but\n * reserved for future precondition violations (e.g. an inserted object with\n * `NaN` coordinates or negative `width`).\n *\n * @public\n */\nexport class QuadtreeError extends Error {\n override readonly name = \"QuadtreeError\";\n}\n\n/**\n * Thrown by any quadtree method called after {@link Quadtree.dispose}.\n *\n * @public\n */\nexport class QuadtreeDisposedError extends Error {\n override readonly name = \"QuadtreeDisposedError\";\n}\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\ninterface Node<T extends AABB> {\n bounds: AABB;\n level: number;\n objects: T[];\n children: Node<T>[];\n}\n\ninterface State<T extends AABB> {\n root: Node<T>;\n maxObjects: number;\n maxLevels: number;\n disposed: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction rectsOverlap(a: AABB, b: AABB): boolean {\n return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;\n}\n\nfunction quadrantIndices<T extends AABB>(node: Node<T>, obj: AABB): number[] {\n const midX = node.bounds.x + node.bounds.width / 2;\n const midY = node.bounds.y + node.bounds.height / 2;\n // Zero-extent objects (points) sitting exactly on midX / midY would fall\n // through both `<` and `>` checks; treat the point as belonging to the\n // right/bottom side so it doesn't silently disappear.\n const inLeft = obj.x < midX;\n const inRight = obj.width === 0 ? obj.x >= midX : obj.x + obj.width > midX;\n const inTop = obj.y < midY;\n const inBottom = obj.height === 0 ? obj.y >= midY : obj.y + obj.height > midY;\n const result: number[] = [];\n if (inTop && inLeft) result.push(0);\n if (inTop && inRight) result.push(1);\n if (inBottom && inLeft) result.push(2);\n if (inBottom && inRight) result.push(3);\n return result;\n}\n\nfunction subdivide<T extends AABB>(node: Node<T>): void {\n const w = node.bounds.width / 2;\n const h = node.bounds.height / 2;\n const x = node.bounds.x;\n const y = node.bounds.y;\n const lvl = node.level + 1;\n node.children.push(\n { bounds: { x, y, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x: x + w, y, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x, y: y + h, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x: x + w, y: y + h, width: w, height: h }, level: lvl, objects: [], children: [] },\n );\n for (const obj of node.objects) {\n for (const i of quadrantIndices(node, obj)) {\n const child = node.children[i];\n if (child !== undefined) child.objects.push(obj);\n }\n }\n node.objects.length = 0;\n}\n\nfunction insertNode<T extends AABB>(\n node: Node<T>,\n obj: T,\n maxObjects: number,\n maxLevels: number,\n): void {\n // Reject objects entirely outside the root bounds; for inner nodes we\n // trust `quadrantIndices` to route correctly (it has zero-extent fallback\n // logic that `rectsOverlap` does not, so the strict check is too tight\n // at child level for points sitting on a child boundary).\n if (node.level === 0 && !rectsOverlap(node.bounds, obj)) return;\n if (node.children.length === 4) {\n for (const i of quadrantIndices(node, obj)) {\n const child = node.children[i];\n if (child !== undefined) insertNode(child, obj, maxObjects, maxLevels);\n }\n return;\n }\n node.objects.push(obj);\n if (node.objects.length > maxObjects && node.level < maxLevels) {\n subdivide(node);\n }\n}\n\nfunction clearNode<T extends AABB>(node: Node<T>): void {\n node.objects.length = 0;\n for (const child of node.children) {\n clearNode(child);\n }\n node.children.length = 0;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Construct a 2D quadtree.\n *\n * @example\n * ```ts\n * import { createQuadtree, type AABB } from \"aiquadtreejs\";\n *\n * interface Body extends AABB {\n * id: number;\n * }\n *\n * const entities: Body[] = [\n * { id: 1, x: 100, y: 100, width: 32, height: 32 },\n * { id: 2, x: 400, y: 250, width: 32, height: 32 },\n * ];\n * const player: Body = { id: 0, x: 200, y: 200, width: 32, height: 32 };\n *\n * const qt = createQuadtree<Body>({\n * bounds: { x: 0, y: 0, width: 800, height: 600 },\n * maxObjects: 10,\n * maxLevels: 4,\n * });\n *\n * // Per-frame:\n * qt.clear();\n * for (const e of entities) qt.insert(e);\n *\n * // Broadphase lookup near the player:\n * const region: AABB = { x: player.x - 50, y: player.y - 50, width: 100, height: 100 };\n * const candidates = qt.retrieve(region);\n * // Caller runs a precise hit test on `candidates`.\n * ```\n *\n * @public\n */\nexport function createQuadtree<T extends AABB>(opts: QuadtreeOptions): Quadtree<T> {\n const { bounds } = opts;\n const maxObjects = opts.maxObjects ?? 10;\n const maxLevels = opts.maxLevels ?? 4;\n\n if (\n !Number.isFinite(bounds.x) ||\n !Number.isFinite(bounds.y) ||\n !Number.isFinite(bounds.width) ||\n !Number.isFinite(bounds.height)\n ) {\n throw new QuadtreeError(\"bounds must contain finite numbers\");\n }\n if (bounds.width <= 0) {\n throw new QuadtreeError(\"bounds.width must be > 0\");\n }\n if (bounds.height <= 0) {\n throw new QuadtreeError(\"bounds.height must be > 0\");\n }\n if (!Number.isInteger(maxObjects) || maxObjects <= 0) {\n throw new QuadtreeError(\"maxObjects must be a positive integer\");\n }\n if (!Number.isInteger(maxLevels) || maxLevels <= 0) {\n throw new QuadtreeError(\"maxLevels must be a positive integer\");\n }\n\n const state: State<T> = {\n root: {\n bounds: { ...bounds },\n level: 0,\n objects: [],\n children: [],\n },\n maxObjects,\n maxLevels,\n disposed: false,\n };\n\n function ck(): void {\n if (state.disposed) throw new QuadtreeDisposedError(\"aiquadtreejs: quadtree has been disposed\");\n }\n\n function insert(obj: T): void {\n ck();\n insertNode(state.root, obj, state.maxObjects, state.maxLevels);\n }\n\n // Reusable scratch for retrieveSet, hoisted so steady-state queries\n // allocate nothing. Safe because the returned Set never escapes the\n // module: retrieve copies it out via Array.from and retrieveInto via a\n // push loop, both synchronously and fully before any subsequent call.\n const scratchSet = new Set<T>();\n const scratchStack: Node<T>[] = [];\n\n function retrieveSet(region: AABB): Set<T> {\n scratchSet.clear();\n scratchStack.length = 0;\n scratchStack.push(state.root);\n while (scratchStack.length > 0) {\n const node = scratchStack.pop();\n if (node === undefined) continue;\n if (!rectsOverlap(node.bounds, region)) continue;\n for (const obj of node.objects) scratchSet.add(obj);\n for (const child of node.children) scratchStack.push(child);\n }\n return scratchSet;\n }\n\n function retrieve(region: AABB): T[] {\n ck();\n return Array.from(retrieveSet(region));\n }\n\n function retrieveInto(region: AABB, target: T[]): T[] {\n ck();\n const set = retrieveSet(region);\n target.length = 0;\n for (const v of set) target.push(v);\n return target;\n }\n\n function clear(): void {\n ck();\n clearNode(state.root);\n }\n\n function dispose(): void {\n if (state.disposed) return;\n state.disposed = true;\n state.root.objects.length = 0;\n state.root.children.length = 0;\n scratchSet.clear();\n scratchStack.length = 0;\n }\n\n return {\n insert,\n retrieve,\n retrieveInto,\n clear,\n dispose,\n get disposed() {\n return state.disposed;\n },\n };\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * Axis-aligned bounding box.
3
3
  *
4
- * Coordinate semantics follow PixiJS `getBounds()`: `x` / `y` are the top-left
5
- * corner and `x + width` / `y + height` are **exclusive**. A 32×32 sprite at
6
- * `(0, 0)` covers pixels `[0, 32)` on both axes.
4
+ * Right-open coordinate semantics: `x` / `y` are the top-left corner and
5
+ * `x + width` / `y + height` are **exclusive**. A 32×32 box at `(0, 0)`
6
+ * covers `[0, 32)` on both axes. (This matches the convention used by
7
+ * renderers such as PixiJS `getBounds()`, but the type is renderer-agnostic.)
7
8
  *
8
9
  * @public
9
10
  */
@@ -80,10 +81,12 @@ interface Quadtree<T extends AABB> {
80
81
  * @invariant Dedup semantics identical to {@link retrieve}: objects
81
82
  * spanning multiple quadrants appear exactly once.
82
83
  *
83
- * Note: `retrieveInto` is not strictly zero-allocation — the internal
84
- * dedup `Set<T>` and DFS stack are still allocated per call. What it
85
- * eliminates is the result `Array` allocation, which is the largest
86
- * frame-to-frame churn item.
84
+ * Allocation: in steady state this performs no per-call heap allocation.
85
+ * The dedup `Set` and DFS stack are reused across calls (cleared, not
86
+ * re-created), and results are written into the caller's `target` instead
87
+ * of a fresh array. The first calls may grow the internal scratch; once
88
+ * result sizes stabilise, allocation amortises to zero — the design goal
89
+ * for per-frame broadphase loops issuing thousands of queries.
87
90
  */
88
91
  retrieveInto(region: AABB, target: T[]): T[];
89
92
  /**
@@ -96,7 +99,8 @@ interface Quadtree<T extends AABB> {
96
99
  clear(): void;
97
100
  /**
98
101
  * Idempotent teardown. Drops references so the GC can reclaim everything.
99
- * Subsequent `insert` / `retrieve` / `clear` throw {@link QuadtreeDisposedError}.
102
+ * After disposal, every method except `dispose` itself — `insert`,
103
+ * `retrieve`, `retrieveInto`, `clear` — throws {@link QuadtreeDisposedError}.
100
104
  */
101
105
  dispose(): void;
102
106
  /** `true` once {@link dispose} has been called. */
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * Axis-aligned bounding box.
3
3
  *
4
- * Coordinate semantics follow PixiJS `getBounds()`: `x` / `y` are the top-left
5
- * corner and `x + width` / `y + height` are **exclusive**. A 32×32 sprite at
6
- * `(0, 0)` covers pixels `[0, 32)` on both axes.
4
+ * Right-open coordinate semantics: `x` / `y` are the top-left corner and
5
+ * `x + width` / `y + height` are **exclusive**. A 32×32 box at `(0, 0)`
6
+ * covers `[0, 32)` on both axes. (This matches the convention used by
7
+ * renderers such as PixiJS `getBounds()`, but the type is renderer-agnostic.)
7
8
  *
8
9
  * @public
9
10
  */
@@ -80,10 +81,12 @@ interface Quadtree<T extends AABB> {
80
81
  * @invariant Dedup semantics identical to {@link retrieve}: objects
81
82
  * spanning multiple quadrants appear exactly once.
82
83
  *
83
- * Note: `retrieveInto` is not strictly zero-allocation — the internal
84
- * dedup `Set<T>` and DFS stack are still allocated per call. What it
85
- * eliminates is the result `Array` allocation, which is the largest
86
- * frame-to-frame churn item.
84
+ * Allocation: in steady state this performs no per-call heap allocation.
85
+ * The dedup `Set` and DFS stack are reused across calls (cleared, not
86
+ * re-created), and results are written into the caller's `target` instead
87
+ * of a fresh array. The first calls may grow the internal scratch; once
88
+ * result sizes stabilise, allocation amortises to zero — the design goal
89
+ * for per-frame broadphase loops issuing thousands of queries.
87
90
  */
88
91
  retrieveInto(region: AABB, target: T[]): T[];
89
92
  /**
@@ -96,7 +99,8 @@ interface Quadtree<T extends AABB> {
96
99
  clear(): void;
97
100
  /**
98
101
  * Idempotent teardown. Drops references so the GC can reclaim everything.
99
- * Subsequent `insert` / `retrieve` / `clear` throw {@link QuadtreeDisposedError}.
102
+ * After disposal, every method except `dispose` itself — `insert`,
103
+ * `retrieve`, `retrieveInto`, `clear` — throws {@link QuadtreeDisposedError}.
100
104
  */
101
105
  dispose(): void;
102
106
  /** `true` once {@link dispose} has been called. */
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var h=class extends Error{name="QuadtreeError"},m=class extends Error{name="QuadtreeDisposedError"};function x(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function A(e,t){let i=e.bounds.x+e.bounds.width/2,s=e.bounds.y+e.bounds.height/2,n=t.x<i,o=t.width===0?t.x>=i:t.x+t.width>i,d=t.y<s,c=t.height===0?t.y>=s:t.y+t.height>s,r=[];return d&&n&&r.push(0),d&&o&&r.push(1),c&&n&&r.push(2),c&&o&&r.push(3),r}function w(e){let t=e.bounds.width/2,i=e.bounds.height/2,s=e.bounds.x,n=e.bounds.y,o=e.level+1;e.children.push({bounds:{x:s,y:n,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s+t,y:n,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s,y:n+i,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s+t,y:n+i,width:t,height:i},level:o,objects:[],children:[]});for(let d of e.objects)for(let c of A(e,d)){let r=e.children[c];r!==void 0&&r.objects.push(d);}e.objects.length=0;}function B(e,t,i,s){if(!(e.level===0&&!x(e.bounds,t))){if(e.children.length===4){for(let n of A(e,t)){let o=e.children[n];o!==void 0&&B(o,t,i,s);}return}e.objects.push(t),e.objects.length>i&&e.level<s&&w(e);}}function v(e){e.objects.length=0;for(let t of e.children)v(t);e.children.length=0;}function y(e){let{bounds:t}=e,i=e.maxObjects??10,s=e.maxLevels??4;if(!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.width)||!Number.isFinite(t.height))throw new h("bounds must contain finite numbers");if(t.width<=0)throw new h("bounds.width must be > 0");if(t.height<=0)throw new h("bounds.height must be > 0");if(!Number.isInteger(i)||i<=0)throw new h("maxObjects must be a positive integer");if(!Number.isInteger(s)||s<=0)throw new h("maxLevels must be a positive integer");let n={root:{bounds:{...t},level:0,objects:[],children:[]},maxObjects:i,maxLevels:s,disposed:false};function o(){if(n.disposed)throw new m("aiquadtreejs: quadtree has been disposed")}function d(u){o(),B(n.root,u,n.maxObjects,n.maxLevels);}function c(u){let l=new Set,b=[n.root];for(;b.length>0;){let f=b.pop();if(f!==void 0&&x(f.bounds,u)){for(let a of f.objects)l.add(a);for(let a of f.children)b.push(a);}}return l}function r(u){return o(),Array.from(c(u))}function p(u,l){o();let b=c(u);l.length=0;for(let f of b)l.push(f);return l}function g(){o(),v(n.root);}function T(){n.disposed||(n.disposed=true,n.root.objects.length=0,n.root.children.length=0);}return {insert:d,retrieve:r,retrieveInto:p,clear:g,dispose:T,get disposed(){return n.disposed}}}export{m as QuadtreeDisposedError,h as QuadtreeError,y as createQuadtree};//# sourceMappingURL=index.js.map
1
+ var l=class extends Error{name="QuadtreeError"},b=class extends Error{name="QuadtreeDisposedError"};function m(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function x(e,t){let i=e.bounds.x+e.bounds.width/2,s=e.bounds.y+e.bounds.height/2,n=t.x<i,o=t.width===0?t.x>=i:t.x+t.width>i,u=t.y<s,d=t.height===0?t.y>=s:t.y+t.height>s,r=[];return u&&n&&r.push(0),u&&o&&r.push(1),d&&n&&r.push(2),d&&o&&r.push(3),r}function y(e){let t=e.bounds.width/2,i=e.bounds.height/2,s=e.bounds.x,n=e.bounds.y,o=e.level+1;e.children.push({bounds:{x:s,y:n,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s+t,y:n,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s,y:n+i,width:t,height:i},level:o,objects:[],children:[]},{bounds:{x:s+t,y:n+i,width:t,height:i},level:o,objects:[],children:[]});for(let u of e.objects)for(let d of x(e,u)){let r=e.children[d];r!==void 0&&r.objects.push(u);}e.objects.length=0;}function A(e,t,i,s){if(!(e.level===0&&!m(e.bounds,t))){if(e.children.length===4){for(let n of x(e,t)){let o=e.children[n];o!==void 0&&A(o,t,i,s);}return}e.objects.push(t),e.objects.length>i&&e.level<s&&y(e);}}function B(e){e.objects.length=0;for(let t of e.children)B(t);e.children.length=0;}function N(e){let{bounds:t}=e,i=e.maxObjects??10,s=e.maxLevels??4;if(!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.width)||!Number.isFinite(t.height))throw new l("bounds must contain finite numbers");if(t.width<=0)throw new l("bounds.width must be > 0");if(t.height<=0)throw new l("bounds.height must be > 0");if(!Number.isInteger(i)||i<=0)throw new l("maxObjects must be a positive integer");if(!Number.isInteger(s)||s<=0)throw new l("maxLevels must be a positive integer");let n={root:{bounds:{...t},level:0,objects:[],children:[]},maxObjects:i,maxLevels:s,disposed:false};function o(){if(n.disposed)throw new b("aiquadtreejs: quadtree has been disposed")}function u(h){o(),A(n.root,h,n.maxObjects,n.maxLevels);}let d=new Set,r=[];function a(h){for(d.clear(),r.length=0,r.push(n.root);r.length>0;){let c=r.pop();if(c!==void 0&&m(c.bounds,h)){for(let f of c.objects)d.add(f);for(let f of c.children)r.push(f);}}return d}function v(h){return o(),Array.from(a(h))}function p(h,c){o();let f=a(h);c.length=0;for(let w of f)c.push(w);return c}function g(){o(),B(n.root);}function T(){n.disposed||(n.disposed=true,n.root.objects.length=0,n.root.children.length=0,d.clear(),r.length=0);}return {insert:u,retrieve:v,retrieveInto:p,clear:g,dispose:T,get disposed(){return n.disposed}}}export{b as QuadtreeDisposedError,l as QuadtreeError,N as createQuadtree};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["QuadtreeError","QuadtreeDisposedError","rectsOverlap","a","b","quadrantIndices","node","obj","midX","midY","inLeft","inRight","inTop","inBottom","result","subdivide","w","h","x","y","lvl","i","child","insertNode","maxObjects","maxLevels","clearNode","createQuadtree","opts","bounds","state","ck","insert","retrieveSet","region","stack","retrieve","retrieveInto","target","set","v","clear","dispose"],"mappings":"AA8HO,IAAMA,EAAN,cAA4B,KAAM,CACrB,IAAA,CAAO,eAC3B,CAAA,CAOaC,CAAAA,CAAN,cAAoC,KAAM,CAC7B,IAAA,CAAO,uBAC3B,EAwBA,SAASC,EAAaC,CAAAA,CAASC,CAAAA,CAAkB,CAC/C,OAAOD,EAAE,CAAA,CAA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AEA,OAAO,CACL,OAAAE,CAAAA,CACA,QAAA,CAAAI,CAAAA,CACA,YAAA,CAAAC,EACA,KAAA,CAAAI,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAI,QAAA,EAAW,CACb,OAAOZ,CAAAA,CAAM,QACf,CACF,CACF","file":"index.js","sourcesContent":["// aiquadtreejs — 2D quadtree for per-frame rebuild collision broadphase.\n//\n// v0.1.0: full implementation. Plain-object nodes, iterative-DFS retrieve,\n// Set-based dedup, idempotent dispose, destructurable methods (no `this`).\n\n/**\n * Axis-aligned bounding box.\n *\n * Coordinate semantics follow PixiJS `getBounds()`: `x` / `y` are the top-left\n * corner and `x + width` / `y + height` are **exclusive**. A 32×32 sprite at\n * `(0, 0)` covers pixels `[0, 32)` on both axes.\n *\n * @public\n */\nexport interface AABB {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Configuration for {@link createQuadtree}.\n *\n * @public\n */\nexport interface QuadtreeOptions {\n /**\n * Outer bounds. Objects partially outside `bounds` still insert into\n * whichever child nodes they overlap; objects fully outside are ignored\n * by `retrieve()` because no node overlaps them.\n */\n bounds: AABB;\n\n /**\n * Threshold above which a node subdivides. Default `10`. Lower values\n * mean deeper trees and fewer candidates per `retrieve()`; higher values\n * mean shallower trees and cheaper `insert()`.\n */\n maxObjects?: number;\n\n /**\n * Maximum subdivision depth. Default `4`. Caps recursion so a very dense\n * cluster doesn't blow up into an unbounded tree.\n */\n maxLevels?: number;\n}\n\n/**\n * Quadtree storing objects that extend {@link AABB}. `T` may carry any\n * payload (entity ID, sprite reference, user data) alongside the geometry.\n *\n * The expected usage pattern is **per-frame rebuild**: at the start of each\n * frame, call `clear()` and re-`insert()` every active object. This is\n * cheaper than tracking movements through the tree and gives correct results\n * regardless of how objects moved.\n *\n * @public\n */\nexport interface Quadtree<T extends AABB> {\n /**\n * Insert an object. The same object reference may legitimately appear\n * in multiple leaf nodes when it spans quadrant boundaries; `retrieve()`\n * deduplicates with a `Set` so the caller sees it exactly once.\n */\n insert(obj: T): void;\n\n /**\n * Return every inserted object whose containing node overlaps `region`,\n * deduplicated. The result is a **broadphase**: callers must still run\n * a precise AABB or pixel-level hit test on each candidate.\n */\n retrieve(region: AABB): T[];\n\n /**\n * Zero-allocation variant of {@link retrieve}.\n *\n * Clears `target` (sets `target.length = 0`), walks the tree using the same\n * iterative DFS + Set-based dedup as {@link retrieve}, then writes every\n * deduplicated candidate into `target` and returns it.\n *\n * Designed for hot-path callers (per-frame broadphase queries in a game\n * loop) that hold a permanent `T[]` buffer and want to avoid allocating a\n * fresh result array on every call.\n *\n * @invariant `target` identity is preserved — only its contents are\n * replaced. `retrieveInto(r, buf) === buf` always holds.\n * @invariant After return, `target.length` equals the deduplicated\n * candidate count. No `undefined` / `null` holes.\n * @invariant Empty result set → `target.length === 0`.\n * @invariant Dedup semantics identical to {@link retrieve}: objects\n * spanning multiple quadrants appear exactly once.\n *\n * Note: `retrieveInto` is not strictly zero-allocation — the internal\n * dedup `Set<T>` and DFS stack are still allocated per call. What it\n * eliminates is the result `Array` allocation, which is the largest\n * frame-to-frame churn item.\n */\n retrieveInto(region: AABB, target: T[]): T[];\n\n /**\n * Reset the tree to empty. The root node object is reused across\n * frames; child nodes are released on clear() and re-created next\n * time subdivision triggers. The per-frame churn is bounded by\n * `4 * (subdivided-internal-node-count)` and stays well inside V8's\n * young-generation budget for typical game-loop usage.\n */\n clear(): void;\n\n /**\n * Idempotent teardown. Drops references so the GC can reclaim everything.\n * Subsequent `insert` / `retrieve` / `clear` throw {@link QuadtreeDisposedError}.\n */\n dispose(): void;\n\n /** `true` once {@link dispose} has been called. */\n readonly disposed: boolean;\n}\n\n/**\n * Recoverable quadtree error — currently unused at the public surface, but\n * reserved for future precondition violations (e.g. an inserted object with\n * `NaN` coordinates or negative `width`).\n *\n * @public\n */\nexport class QuadtreeError extends Error {\n override readonly name = \"QuadtreeError\";\n}\n\n/**\n * Thrown by any quadtree method called after {@link Quadtree.dispose}.\n *\n * @public\n */\nexport class QuadtreeDisposedError extends Error {\n override readonly name = \"QuadtreeDisposedError\";\n}\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\ninterface Node<T extends AABB> {\n bounds: AABB;\n level: number;\n objects: T[];\n children: Node<T>[];\n}\n\ninterface State<T extends AABB> {\n root: Node<T>;\n maxObjects: number;\n maxLevels: number;\n disposed: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction rectsOverlap(a: AABB, b: AABB): boolean {\n return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;\n}\n\nfunction quadrantIndices<T extends AABB>(node: Node<T>, obj: AABB): number[] {\n const midX = node.bounds.x + node.bounds.width / 2;\n const midY = node.bounds.y + node.bounds.height / 2;\n // Zero-extent objects (points) sitting exactly on midX / midY would fall\n // through both `<` and `>` checks; treat the point as belonging to the\n // right/bottom side so it doesn't silently disappear.\n const inLeft = obj.x < midX;\n const inRight = obj.width === 0 ? obj.x >= midX : obj.x + obj.width > midX;\n const inTop = obj.y < midY;\n const inBottom = obj.height === 0 ? obj.y >= midY : obj.y + obj.height > midY;\n const result: number[] = [];\n if (inTop && inLeft) result.push(0);\n if (inTop && inRight) result.push(1);\n if (inBottom && inLeft) result.push(2);\n if (inBottom && inRight) result.push(3);\n return result;\n}\n\nfunction subdivide<T extends AABB>(node: Node<T>): void {\n const w = node.bounds.width / 2;\n const h = node.bounds.height / 2;\n const x = node.bounds.x;\n const y = node.bounds.y;\n const lvl = node.level + 1;\n node.children.push(\n { bounds: { x, y, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x: x + w, y, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x, y: y + h, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x: x + w, y: y + h, width: w, height: h }, level: lvl, objects: [], children: [] },\n );\n for (const obj of node.objects) {\n for (const i of quadrantIndices(node, obj)) {\n const child = node.children[i];\n if (child !== undefined) child.objects.push(obj);\n }\n }\n node.objects.length = 0;\n}\n\nfunction insertNode<T extends AABB>(\n node: Node<T>,\n obj: T,\n maxObjects: number,\n maxLevels: number,\n): void {\n // Reject objects entirely outside the root bounds; for inner nodes we\n // trust `quadrantIndices` to route correctly (it has zero-extent fallback\n // logic that `rectsOverlap` does not, so the strict check is too tight\n // at child level for points sitting on a child boundary).\n if (node.level === 0 && !rectsOverlap(node.bounds, obj)) return;\n if (node.children.length === 4) {\n for (const i of quadrantIndices(node, obj)) {\n const child = node.children[i];\n if (child !== undefined) insertNode(child, obj, maxObjects, maxLevels);\n }\n return;\n }\n node.objects.push(obj);\n if (node.objects.length > maxObjects && node.level < maxLevels) {\n subdivide(node);\n }\n}\n\nfunction clearNode<T extends AABB>(node: Node<T>): void {\n node.objects.length = 0;\n for (const child of node.children) {\n clearNode(child);\n }\n node.children.length = 0;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Construct a 2D quadtree.\n *\n * @example\n * ```ts\n * import { createQuadtree, type AABB } from \"aiquadtreejs\";\n *\n * interface Body extends AABB {\n * id: number;\n * }\n *\n * const entities: Body[] = [\n * { id: 1, x: 100, y: 100, width: 32, height: 32 },\n * { id: 2, x: 400, y: 250, width: 32, height: 32 },\n * ];\n * const player: Body = { id: 0, x: 200, y: 200, width: 32, height: 32 };\n *\n * const qt = createQuadtree<Body>({\n * bounds: { x: 0, y: 0, width: 800, height: 600 },\n * maxObjects: 10,\n * maxLevels: 4,\n * });\n *\n * // Per-frame:\n * qt.clear();\n * for (const e of entities) qt.insert(e);\n *\n * // Broadphase lookup near the player:\n * const region: AABB = { x: player.x - 50, y: player.y - 50, width: 100, height: 100 };\n * const candidates = qt.retrieve(region);\n * // Caller runs a precise hit test on `candidates`.\n * ```\n *\n * @public\n */\nexport function createQuadtree<T extends AABB>(opts: QuadtreeOptions): Quadtree<T> {\n const { bounds } = opts;\n const maxObjects = opts.maxObjects ?? 10;\n const maxLevels = opts.maxLevels ?? 4;\n\n if (\n !Number.isFinite(bounds.x) ||\n !Number.isFinite(bounds.y) ||\n !Number.isFinite(bounds.width) ||\n !Number.isFinite(bounds.height)\n ) {\n throw new QuadtreeError(\"bounds must contain finite numbers\");\n }\n if (bounds.width <= 0) {\n throw new QuadtreeError(\"bounds.width must be > 0\");\n }\n if (bounds.height <= 0) {\n throw new QuadtreeError(\"bounds.height must be > 0\");\n }\n if (!Number.isInteger(maxObjects) || maxObjects <= 0) {\n throw new QuadtreeError(\"maxObjects must be a positive integer\");\n }\n if (!Number.isInteger(maxLevels) || maxLevels <= 0) {\n throw new QuadtreeError(\"maxLevels must be a positive integer\");\n }\n\n const state: State<T> = {\n root: {\n bounds: { ...bounds },\n level: 0,\n objects: [],\n children: [],\n },\n maxObjects,\n maxLevels,\n disposed: false,\n };\n\n function ck(): void {\n if (state.disposed) throw new QuadtreeDisposedError(\"aiquadtreejs: quadtree has been disposed\");\n }\n\n function insert(obj: T): void {\n ck();\n insertNode(state.root, obj, state.maxObjects, state.maxLevels);\n }\n\n function retrieveSet(region: AABB): Set<T> {\n const result = new Set<T>();\n const stack: Node<T>[] = [state.root];\n while (stack.length > 0) {\n const node = stack.pop();\n if (node === undefined) continue;\n if (!rectsOverlap(node.bounds, region)) continue;\n for (const obj of node.objects) result.add(obj);\n for (const child of node.children) stack.push(child);\n }\n return result;\n }\n\n function retrieve(region: AABB): T[] {\n ck();\n return Array.from(retrieveSet(region));\n }\n\n function retrieveInto(region: AABB, target: T[]): T[] {\n ck();\n const set = retrieveSet(region);\n target.length = 0;\n for (const v of set) target.push(v);\n return target;\n }\n\n function clear(): void {\n ck();\n clearNode(state.root);\n }\n\n function dispose(): void {\n if (state.disposed) return;\n state.disposed = true;\n state.root.objects.length = 0;\n state.root.children.length = 0;\n }\n\n return {\n insert,\n retrieve,\n retrieveInto,\n clear,\n dispose,\n get disposed() {\n return state.disposed;\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts"],"names":["QuadtreeError","QuadtreeDisposedError","rectsOverlap","a","b","quadrantIndices","node","obj","midX","midY","inLeft","inRight","inTop","inBottom","result","subdivide","w","h","x","y","lvl","i","child","insertNode","maxObjects","maxLevels","clearNode","createQuadtree","opts","bounds","state","ck","insert","scratchSet","scratchStack","retrieveSet","region","retrieve","retrieveInto","target","set","v","clear","dispose"],"mappings":"AAkIO,IAAMA,EAAN,cAA4B,KAAM,CACrB,IAAA,CAAO,eAC3B,CAAA,CAOaC,CAAAA,CAAN,cAAoC,KAAM,CAC7B,IAAA,CAAO,uBAC3B,EAwBA,SAASC,EAAaC,CAAAA,CAASC,CAAAA,CAAkB,CAC/C,OAAOD,EAAE,CAAA,CAAIC,CAAAA,CAAE,CAAA,CAAIA,CAAAA,CAAE,OAASD,CAAAA,CAAE,CAAA,CAAIA,CAAAA,CAAE,KAAA,CAAQC,EAAE,CAAA,EAAKD,CAAAA,CAAE,EAAIC,CAAAA,CAAE,CAAA,CAAIA,EAAE,MAAA,EAAUD,CAAAA,CAAE,CAAA,CAAIA,CAAAA,CAAE,OAASC,CAAAA,CAAE,CAClG,CAEA,SAASC,EAAgCC,CAAAA,CAAeC,CAAAA,CAAqB,CAC3E,IAAMC,EAAOF,CAAAA,CAAK,MAAA,CAAO,EAAIA,CAAAA,CAAK,MAAA,CAAO,MAAQ,CAAA,CAC3CG,CAAAA,CAAOH,CAAAA,CAAK,MAAA,CAAO,EAAIA,CAAAA,CAAK,MAAA,CAAO,MAAA,CAAS,CAAA,CAI5CI,EAASH,CAAAA,CAAI,CAAA,CAAIC,CAAAA,CACjBG,CAAAA,CAAUJ,EAAI,KAAA,GAAU,CAAA,CAAIA,EAAI,CAAA,EAAKC,CAAAA,CAAOD,EAAI,CAAA,CAAIA,CAAAA,CAAI,KAAA,CAAQC,CAAAA,CAChEI,EAAQL,CAAAA,CAAI,CAAA,CAAIE,CAAAA,CAChBI,CAAAA,CAAWN,EAAI,MAAA,GAAW,CAAA,C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G,CACH,IAAMS,CAAAA,CAAML,EAAYC,CAAM,CAAA,CAC9BG,EAAO,MAAA,CAAS,CAAA,CAChB,QAAWE,CAAAA,IAAKD,CAAAA,CAAKD,CAAAA,CAAO,IAAA,CAAKE,CAAC,CAAA,CAClC,OAAOF,CACT,CAEA,SAASG,CAAAA,EAAc,CACrBX,CAAAA,EAAG,CACHL,EAAUI,CAAAA,CAAM,IAAI,EACtB,CAEA,SAASa,GAAgB,CACnBb,CAAAA,CAAM,QAAA,GACVA,CAAAA,CAAM,SAAW,IAAA,CACjBA,CAAAA,CAAM,IAAA,CAAK,OAAA,CAAQ,OAAS,CAAA,CAC5BA,CAAAA,CAAM,IAAA,CAAK,QAAA,CAAS,OAAS,CAAA,CAC7BG,CAAAA,CAAW,OAAM,CACjBC,CAAAA,CAAa,OAAS,CAAA,EACxB,CAEA,OAAO,CACL,OAAAF,CAAAA,CACA,QAAA,CAAAK,CAAAA,CACA,YAAA,CAAAC,EACA,KAAA,CAAAI,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAI,QAAA,EAAW,CACb,OAAOb,CAAAA,CAAM,QACf,CACF,CACF","file":"index.js","sourcesContent":["// aiquadtreejs — 2D quadtree for per-frame rebuild collision broadphase.\n//\n// v0.1.0: full implementation. Plain-object nodes, iterative-DFS retrieve,\n// Set-based dedup, idempotent dispose, destructurable methods (no `this`).\n\n/**\n * Axis-aligned bounding box.\n *\n * Right-open coordinate semantics: `x` / `y` are the top-left corner and\n * `x + width` / `y + height` are **exclusive**. A 32×32 box at `(0, 0)`\n * covers `[0, 32)` on both axes. (This matches the convention used by\n * renderers such as PixiJS `getBounds()`, but the type is renderer-agnostic.)\n *\n * @public\n */\nexport interface AABB {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Configuration for {@link createQuadtree}.\n *\n * @public\n */\nexport interface QuadtreeOptions {\n /**\n * Outer bounds. Objects partially outside `bounds` still insert into\n * whichever child nodes they overlap; objects fully outside are ignored\n * by `retrieve()` because no node overlaps them.\n */\n bounds: AABB;\n\n /**\n * Threshold above which a node subdivides. Default `10`. Lower values\n * mean deeper trees and fewer candidates per `retrieve()`; higher values\n * mean shallower trees and cheaper `insert()`.\n */\n maxObjects?: number;\n\n /**\n * Maximum subdivision depth. Default `4`. Caps recursion so a very dense\n * cluster doesn't blow up into an unbounded tree.\n */\n maxLevels?: number;\n}\n\n/**\n * Quadtree storing objects that extend {@link AABB}. `T` may carry any\n * payload (entity ID, sprite reference, user data) alongside the geometry.\n *\n * The expected usage pattern is **per-frame rebuild**: at the start of each\n * frame, call `clear()` and re-`insert()` every active object. This is\n * cheaper than tracking movements through the tree and gives correct results\n * regardless of how objects moved.\n *\n * @public\n */\nexport interface Quadtree<T extends AABB> {\n /**\n * Insert an object. The same object reference may legitimately appear\n * in multiple leaf nodes when it spans quadrant boundaries; `retrieve()`\n * deduplicates with a `Set` so the caller sees it exactly once.\n */\n insert(obj: T): void;\n\n /**\n * Return every inserted object whose containing node overlaps `region`,\n * deduplicated. The result is a **broadphase**: callers must still run\n * a precise AABB or pixel-level hit test on each candidate.\n */\n retrieve(region: AABB): T[];\n\n /**\n * Zero-allocation variant of {@link retrieve}.\n *\n * Clears `target` (sets `target.length = 0`), walks the tree using the same\n * iterative DFS + Set-based dedup as {@link retrieve}, then writes every\n * deduplicated candidate into `target` and returns it.\n *\n * Designed for hot-path callers (per-frame broadphase queries in a game\n * loop) that hold a permanent `T[]` buffer and want to avoid allocating a\n * fresh result array on every call.\n *\n * @invariant `target` identity is preserved — only its contents are\n * replaced. `retrieveInto(r, buf) === buf` always holds.\n * @invariant After return, `target.length` equals the deduplicated\n * candidate count. No `undefined` / `null` holes.\n * @invariant Empty result set → `target.length === 0`.\n * @invariant Dedup semantics identical to {@link retrieve}: objects\n * spanning multiple quadrants appear exactly once.\n *\n * Allocation: in steady state this performs no per-call heap allocation.\n * The dedup `Set` and DFS stack are reused across calls (cleared, not\n * re-created), and results are written into the caller's `target` instead\n * of a fresh array. The first calls may grow the internal scratch; once\n * result sizes stabilise, allocation amortises to zero — the design goal\n * for per-frame broadphase loops issuing thousands of queries.\n */\n retrieveInto(region: AABB, target: T[]): T[];\n\n /**\n * Reset the tree to empty. The root node object is reused across\n * frames; child nodes are released on clear() and re-created next\n * time subdivision triggers. The per-frame churn is bounded by\n * `4 * (subdivided-internal-node-count)` and stays well inside V8's\n * young-generation budget for typical game-loop usage.\n */\n clear(): void;\n\n /**\n * Idempotent teardown. Drops references so the GC can reclaim everything.\n * After disposal, every method except `dispose` itself — `insert`,\n * `retrieve`, `retrieveInto`, `clear` — throws {@link QuadtreeDisposedError}.\n */\n dispose(): void;\n\n /** `true` once {@link dispose} has been called. */\n readonly disposed: boolean;\n}\n\n/**\n * Recoverable quadtree error — currently unused at the public surface, but\n * reserved for future precondition violations (e.g. an inserted object with\n * `NaN` coordinates or negative `width`).\n *\n * @public\n */\nexport class QuadtreeError extends Error {\n override readonly name = \"QuadtreeError\";\n}\n\n/**\n * Thrown by any quadtree method called after {@link Quadtree.dispose}.\n *\n * @public\n */\nexport class QuadtreeDisposedError extends Error {\n override readonly name = \"QuadtreeDisposedError\";\n}\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\ninterface Node<T extends AABB> {\n bounds: AABB;\n level: number;\n objects: T[];\n children: Node<T>[];\n}\n\ninterface State<T extends AABB> {\n root: Node<T>;\n maxObjects: number;\n maxLevels: number;\n disposed: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction rectsOverlap(a: AABB, b: AABB): boolean {\n return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;\n}\n\nfunction quadrantIndices<T extends AABB>(node: Node<T>, obj: AABB): number[] {\n const midX = node.bounds.x + node.bounds.width / 2;\n const midY = node.bounds.y + node.bounds.height / 2;\n // Zero-extent objects (points) sitting exactly on midX / midY would fall\n // through both `<` and `>` checks; treat the point as belonging to the\n // right/bottom side so it doesn't silently disappear.\n const inLeft = obj.x < midX;\n const inRight = obj.width === 0 ? obj.x >= midX : obj.x + obj.width > midX;\n const inTop = obj.y < midY;\n const inBottom = obj.height === 0 ? obj.y >= midY : obj.y + obj.height > midY;\n const result: number[] = [];\n if (inTop && inLeft) result.push(0);\n if (inTop && inRight) result.push(1);\n if (inBottom && inLeft) result.push(2);\n if (inBottom && inRight) result.push(3);\n return result;\n}\n\nfunction subdivide<T extends AABB>(node: Node<T>): void {\n const w = node.bounds.width / 2;\n const h = node.bounds.height / 2;\n const x = node.bounds.x;\n const y = node.bounds.y;\n const lvl = node.level + 1;\n node.children.push(\n { bounds: { x, y, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x: x + w, y, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x, y: y + h, width: w, height: h }, level: lvl, objects: [], children: [] },\n { bounds: { x: x + w, y: y + h, width: w, height: h }, level: lvl, objects: [], children: [] },\n );\n for (const obj of node.objects) {\n for (const i of quadrantIndices(node, obj)) {\n const child = node.children[i];\n if (child !== undefined) child.objects.push(obj);\n }\n }\n node.objects.length = 0;\n}\n\nfunction insertNode<T extends AABB>(\n node: Node<T>,\n obj: T,\n maxObjects: number,\n maxLevels: number,\n): void {\n // Reject objects entirely outside the root bounds; for inner nodes we\n // trust `quadrantIndices` to route correctly (it has zero-extent fallback\n // logic that `rectsOverlap` does not, so the strict check is too tight\n // at child level for points sitting on a child boundary).\n if (node.level === 0 && !rectsOverlap(node.bounds, obj)) return;\n if (node.children.length === 4) {\n for (const i of quadrantIndices(node, obj)) {\n const child = node.children[i];\n if (child !== undefined) insertNode(child, obj, maxObjects, maxLevels);\n }\n return;\n }\n node.objects.push(obj);\n if (node.objects.length > maxObjects && node.level < maxLevels) {\n subdivide(node);\n }\n}\n\nfunction clearNode<T extends AABB>(node: Node<T>): void {\n node.objects.length = 0;\n for (const child of node.children) {\n clearNode(child);\n }\n node.children.length = 0;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Construct a 2D quadtree.\n *\n * @example\n * ```ts\n * import { createQuadtree, type AABB } from \"aiquadtreejs\";\n *\n * interface Body extends AABB {\n * id: number;\n * }\n *\n * const entities: Body[] = [\n * { id: 1, x: 100, y: 100, width: 32, height: 32 },\n * { id: 2, x: 400, y: 250, width: 32, height: 32 },\n * ];\n * const player: Body = { id: 0, x: 200, y: 200, width: 32, height: 32 };\n *\n * const qt = createQuadtree<Body>({\n * bounds: { x: 0, y: 0, width: 800, height: 600 },\n * maxObjects: 10,\n * maxLevels: 4,\n * });\n *\n * // Per-frame:\n * qt.clear();\n * for (const e of entities) qt.insert(e);\n *\n * // Broadphase lookup near the player:\n * const region: AABB = { x: player.x - 50, y: player.y - 50, width: 100, height: 100 };\n * const candidates = qt.retrieve(region);\n * // Caller runs a precise hit test on `candidates`.\n * ```\n *\n * @public\n */\nexport function createQuadtree<T extends AABB>(opts: QuadtreeOptions): Quadtree<T> {\n const { bounds } = opts;\n const maxObjects = opts.maxObjects ?? 10;\n const maxLevels = opts.maxLevels ?? 4;\n\n if (\n !Number.isFinite(bounds.x) ||\n !Number.isFinite(bounds.y) ||\n !Number.isFinite(bounds.width) ||\n !Number.isFinite(bounds.height)\n ) {\n throw new QuadtreeError(\"bounds must contain finite numbers\");\n }\n if (bounds.width <= 0) {\n throw new QuadtreeError(\"bounds.width must be > 0\");\n }\n if (bounds.height <= 0) {\n throw new QuadtreeError(\"bounds.height must be > 0\");\n }\n if (!Number.isInteger(maxObjects) || maxObjects <= 0) {\n throw new QuadtreeError(\"maxObjects must be a positive integer\");\n }\n if (!Number.isInteger(maxLevels) || maxLevels <= 0) {\n throw new QuadtreeError(\"maxLevels must be a positive integer\");\n }\n\n const state: State<T> = {\n root: {\n bounds: { ...bounds },\n level: 0,\n objects: [],\n children: [],\n },\n maxObjects,\n maxLevels,\n disposed: false,\n };\n\n function ck(): void {\n if (state.disposed) throw new QuadtreeDisposedError(\"aiquadtreejs: quadtree has been disposed\");\n }\n\n function insert(obj: T): void {\n ck();\n insertNode(state.root, obj, state.maxObjects, state.maxLevels);\n }\n\n // Reusable scratch for retrieveSet, hoisted so steady-state queries\n // allocate nothing. Safe because the returned Set never escapes the\n // module: retrieve copies it out via Array.from and retrieveInto via a\n // push loop, both synchronously and fully before any subsequent call.\n const scratchSet = new Set<T>();\n const scratchStack: Node<T>[] = [];\n\n function retrieveSet(region: AABB): Set<T> {\n scratchSet.clear();\n scratchStack.length = 0;\n scratchStack.push(state.root);\n while (scratchStack.length > 0) {\n const node = scratchStack.pop();\n if (node === undefined) continue;\n if (!rectsOverlap(node.bounds, region)) continue;\n for (const obj of node.objects) scratchSet.add(obj);\n for (const child of node.children) scratchStack.push(child);\n }\n return scratchSet;\n }\n\n function retrieve(region: AABB): T[] {\n ck();\n return Array.from(retrieveSet(region));\n }\n\n function retrieveInto(region: AABB, target: T[]): T[] {\n ck();\n const set = retrieveSet(region);\n target.length = 0;\n for (const v of set) target.push(v);\n return target;\n }\n\n function clear(): void {\n ck();\n clearNode(state.root);\n }\n\n function dispose(): void {\n if (state.disposed) return;\n state.disposed = true;\n state.root.objects.length = 0;\n state.root.children.length = 0;\n scratchSet.clear();\n scratchStack.length = 0;\n }\n\n return {\n insert,\n retrieve,\n retrieveInto,\n clear,\n dispose,\n get disposed() {\n return state.disposed;\n },\n };\n}\n"]}
package/llms-full.txt CHANGED
@@ -23,7 +23,7 @@ The short index lives at `llms.txt` (see https://llmstxt.org/).
23
23
 
24
24
  Part of the [ai\*js micro-runtime ecosystem](https://github.com/yshengliao) — see also [aifsmjs](https://github.com/yshengliao/aifsmjs) (FSM), [aiecsjs](https://github.com/yshengliao/aiecsjs) (ECS), [aibridgejs](https://github.com/yshengliao/aibridgejs) (cross-context RPC), [aieventjs](https://github.com/yshengliao/aieventjs) (event emitter), [aipooljs](https://github.com/yshengliao/aipooljs) (object pool), and [aiaudiojs](https://github.com/yshengliao/aiaudiojs) (Web Audio shell).
25
25
 
26
- > **Status: 0.3.0 published.** Adds `retrieveInto(region, target)` zero-allocation broadphase + property-based dedup invariants. ≥95% coverage, ≤2 KB gzip.
26
+ > **Status: 0.3.1 published.** `retrieveInto(region, target)` is a steady-state zero-allocation broadphase (reused internal scratch + caller buffer); property-based dedup invariants. ≥95% coverage, ≤2 KB gzip.
27
27
 
28
28
  ---
29
29
 
@@ -155,6 +155,43 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
155
155
 
156
156
  ## [Unreleased]
157
157
 
158
+ ## [0.3.1] - 2026-05-29
159
+
160
+ ### Changed
161
+
162
+ - **`retrieveInto` is now genuinely zero-allocation in steady state.** The
163
+ internal dedup `Set` and DFS stack are hoisted to the tree instance and
164
+ reused across calls (cleared, not re-created) instead of being allocated
165
+ per query. Combined with the caller-owned `target` buffer, a per-frame
166
+ broadphase loop issuing thousands of `retrieveInto` queries now allocates
167
+ nothing once result sizes stabilise — the design goal stated in 0.3.0.
168
+ Purely internal: no API, signature, or observable-behaviour change.
169
+ `retrieve` still returns a fresh array each call.
170
+ - **`dispose()`** now also clears the internal scratch, preserving the
171
+ "drops references so the GC can reclaim everything" guarantee.
172
+ - **Docs** — `AABB` JSDoc leads with a renderer-neutral right-open
173
+ definition (PixiJS `getBounds()` demoted to a compatibility note);
174
+ `dispose()` JSDoc now lists `retrieveInto` among the post-dispose
175
+ throwers; the 0.3.0 changelog note reworded ("observationally identical"
176
+ rather than "byte-for-byte"); `STABILITY.md` exports list now includes
177
+ the `Quadtree<T>` interface.
178
+
179
+ ### Internal (not shipped to npm)
180
+
181
+ - Property test `prop2` uses `fc.uniqueArray` keyed on `id` instead of an
182
+ early-return guard that skipped ~39% of runs on id collisions; the
183
+ id-uniqueness invariant now runs on every case. Property generators mix
184
+ in zero-extent midpoint points (`fc.oneof`) so the dedup invariants
185
+ exercise the G4 regression shape, not just deterministic fixtures.
186
+ - Tightened `I4` (`toBe(1)`); added `I13` (retrieve fresh-array vs
187
+ retrieveInto buffer-reuse contrast — backward-compat lock) and `I14`
188
+ (interleaved retrieve / retrieveInto correctness — shared-scratch guard).
189
+
190
+ ### Notes
191
+
192
+ - `dist/index.js` runtime differs from 0.3.0 only by the scratch-hoist
193
+ optimisation; the public API and all observable behaviour are unchanged.
194
+
158
195
  ## [0.3.0] - 2026-05-29
159
196
 
160
197
  ### Added
@@ -184,7 +221,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
184
221
 
185
222
  ### Notes
186
223
 
187
- - `retrieve` behaviour is byte-for-byte identical to 0.1.1: the
224
+ - `retrieve` behaviour is observationally identical to 0.1.1: the
188
225
  internal refactor extracts a shared `retrieveSet` helper that both
189
226
  `retrieve` and `retrieveInto` call, but `Set` insertion order →
190
227
  `Array.from` order is preserved by spec.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiquadtreejs",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Tiny 2D quadtree for per-frame rebuild collision broadphase. Insert AABBs, retrieve candidates, clear. Caller does precise hit-testing. Designed for PixiJS games with 500–10,000 active entities.",
5
5
  "keywords": [
6
6
  "quadtree",