@jdultra/threedtiles 14.0.22 → 14.0.23

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.
@@ -16,17 +16,17 @@ function w(t) {
16
16
  function z(t) {
17
17
  return { x: +t[0], y: +t[1], z: +t[2], w: +t[3] };
18
18
  }
19
- function P(t, e) {
19
+ function O(t, e) {
20
20
  return { x: t.x - e.x, y: t.y - e.y, z: t.z - e.z };
21
21
  }
22
- function j(t, e) {
22
+ function P(t, e) {
23
23
  return { x: t.x * e, y: t.y * e, z: t.z * e };
24
24
  }
25
- function O(t) {
25
+ function j(t) {
26
26
  return Math.hypot(t.x, t.y, t.z);
27
27
  }
28
28
  function $(t) {
29
- const e = O(t) || 1;
29
+ const e = j(t) || 1;
30
30
  return { x: t.x / e, y: t.y / e, z: t.z / e };
31
31
  }
32
32
  async function v() {
@@ -88,8 +88,8 @@ function T(t, e) {
88
88
  I = "geocentric", W = { x: +t[0], y: +t[1], z: +t[2] }, q = +e, p && (p.gravity = { x: 0, y: 0, z: 0 });
89
89
  }
90
90
  function H(t) {
91
- const e = $(P(W, t));
92
- return j(e, q);
91
+ const e = $(O(W, t));
92
+ return P(e, q);
93
93
  }
94
94
  function V(t, e, o) {
95
95
  try {
@@ -229,19 +229,20 @@ function Q(t) {
229
229
  function X(t, e, o = 1e6) {
230
230
  const n = w(t), r = w(e), d = new l.Ray(n, r), h = p.castRay(d, o, !0);
231
231
  if (!h) return { hits: [] };
232
- const m = h.toi, k = d.pointAt(m), s = h.normal;
233
- let a = null;
234
- for (const [i, c] of C.entries())
235
- if (c.handle === h.collider.handle) {
236
- a = i;
232
+ const m = h.timeOfImpact, k = d.pointAt(m);
233
+ h.normal;
234
+ let s = null;
235
+ for (const [f, i] of C.entries())
236
+ if (i.handle === h.collider.handle) {
237
+ s = f;
237
238
  break;
238
239
  }
239
- let y = null;
240
- const f = h.collider.parent()?.handle;
241
- if (f != null) {
242
- for (const [i, c] of x.entries())
243
- if (c.handle === f) {
244
- y = i;
240
+ let a = null;
241
+ const y = h.collider.parent()?.handle;
242
+ if (y != null) {
243
+ for (const [f, i] of x.entries())
244
+ if (i.handle === y) {
245
+ a = f;
245
246
  break;
246
247
  }
247
248
  }
@@ -249,9 +250,8 @@ function X(t, e, o = 1e6) {
249
250
  hits: [{
250
251
  toi: m,
251
252
  point: [k.x, k.y, k.z],
252
- normal: [s.x, s.y, s.z],
253
- colliderId: a,
254
- bodyId: y
253
+ colliderId: s,
254
+ bodyId: a
255
255
  }]
256
256
  };
257
257
  }
@@ -390,4 +390,4 @@ async function Y(t) {
390
390
  }
391
391
  }
392
392
  self.addEventListener("message", Y);
393
- //# sourceMappingURL=physicsRapier.worker-jgQ9dgLt.js.map
393
+ //# sourceMappingURL=physicsRapier.worker-D664sBAY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"physicsRapier.worker-D664sBAY.js","sources":["../src/simulation/physicsRapier.worker.js"],"sourcesContent":["// physicsRapier.worker.js\r\n// Fully implemented physics worker using @dimforge/rapier3d-compat.\r\n// Handles rigid bodies, primitive and trimesh colliders, gravity (vector/geocentric), forces, stepping, and raycasts.\r\n// Message contract mirrors the placeholder worker but executes with Rapier under the hood.\r\n\r\nlet RAPIER = null;\r\nlet world = null;\r\n// Single-flight init to avoid concurrent wasm initialization races\r\nlet initPromise = null;\r\n\r\n// State maps\r\nconst bodies = new Map(); // id -> RigidBody\r\nconst bodyInfo = new Map(); // id -> { type, mass }\r\nconst colliders = new Map(); // id -> Collider\r\nconst colliderOwners = new Map(); // id -> bodyId\r\n\r\n// Gravity configuration\r\nlet gravityMode = 'vector'; // 'vector' | 'geocentric'\r\nlet gravityVec = { x: 0, y: -9.81, z: 0 };\r\nlet planetCenter = { x: 0, y: 0, z: 0 };\r\nlet gravityIntensity = 9.81;\r\n\r\n// Timing\r\nlet simTimeMs = 0;\r\nlet fixedDt = 1 / 60;\r\n\r\n// Utilities\r\nfunction ack(id, result = null) {\r\n if (id == null) return;\r\n postMessage({ replyTo: id, result });\r\n}\r\nfunction nack(id, error) {\r\n if (id == null) return;\r\n postMessage({ replyTo: id, error: (error && (error.message || error)) || 'error' });\r\n}\r\nfunction clamp(v, a, b) { return Math.max(a, Math.min(b, v)); }\r\nfunction v3(a) { return { x: +a[0], y: +a[1], z: +a[2] }; }\r\nfunction q4(a) { return { x: +a[0], y: +a[1], z: +a[2], w: +a[3] }; }\r\nfunction toArrV3(v) { return [v.x, v.y, v.z]; }\r\nfunction toArrQ4(q) { return [q.x, q.y, q.z, q.w]; }\r\nfunction addV(a, b) { return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z }; }\r\nfunction subV(a, b) { return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z }; }\r\nfunction scaleV(a, s) { return { x: a.x * s, y: a.y * s, z: a.z * s }; }\r\nfunction lenV(a) { return Math.hypot(a.x, a.y, a.z); }\r\nfunction normV(a) { const L = lenV(a) || 1; return { x: a.x / L, y: a.y / L, z: a.z / L }; }\r\n\r\nasync function ensureRapier() {\r\n // De-duplicate concurrent initialization to avoid WASM re-entrancy (\"unreachable\"/OOB) races.\r\n if (initPromise) {\r\n await initPromise;\r\n return;\r\n }\r\n initPromise = (async () => {\r\n if (!RAPIER) {\r\n postMessage({ type: 'debug', msg: 'importing rapier module' });\r\n // Import may provide the module as the default export or as the module namespace.\r\n const mod = await import('@dimforge/rapier3d-compat');\r\n\r\n // Provide locateFile so the worker can resolve the .wasm file relative to this worker module.\r\n const locateFile = (file) => {\r\n try {\r\n return new URL(file, import.meta.url).href;\r\n } catch (e) {\r\n // Fallback: return filename (bundlers may replace with emitted asset paths)\r\n return file;\r\n }\r\n };\r\n const initOptions = { locateFile };\r\n\r\n // Normalize common export patterns:\r\n // - Factory function: default or module export is a function that initializes/returns the module.\r\n // - Object with init(options) function: call init and then use the object.\r\n // - Already-initialized object/module returned directly.\r\n const maybe = mod?.default ?? mod;\r\n postMessage({\r\n type: 'debug',\r\n msg: 'rapier module import result',\r\n hasDefault: !!mod?.default,\r\n hasInitFunction: typeof (maybe?.init) === 'function',\r\n isFactoryFunction: typeof maybe === 'function'\r\n });\r\n\r\n try {\r\n if (typeof maybe === 'function') {\r\n // Factory function case: call it with initOptions. It may return a Promise or the module synchronously.\r\n postMessage({ type: 'debug', msg: 'rapier: calling module factory function' });\r\n const res = maybe(initOptions);\r\n RAPIER = (res && typeof res.then === 'function') ? await res : (res || maybe);\r\n postMessage({ type: 'debug', msg: 'rapier factory resolved', hasWorld: !!RAPIER?.World });\r\n } else if (typeof maybe?.init === 'function') {\r\n // Object with init() API\r\n postMessage({ type: 'debug', msg: 'rapier: calling init()' });\r\n await maybe.init(initOptions);\r\n RAPIER = maybe;\r\n postMessage({ type: 'debug', msg: 'rapier.init completed', hasWorld: !!RAPIER?.World });\r\n } else if (maybe) {\r\n // Already-initialized module/object\r\n RAPIER = maybe;\r\n postMessage({ type: 'debug', msg: 'rapier: using imported module as-is', hasWorld: !!RAPIER?.World });\r\n } else {\r\n throw new Error('Imported Rapier module is empty/invalid');\r\n }\r\n } catch (err) {\r\n // Emit a helpful debug/error message back to the main thread so the app can surface it.\r\n postMessage({ type: 'error', msg: 'rapier init failed', error: (err && (err.message || String(err))) || String(err) });\r\n throw err;\r\n }\r\n\r\n if (!RAPIER) throw new Error('Failed to import Rapier module');\r\n }\r\n\r\n if (!world) {\r\n // Initialize world with vector gravity; if geocentric, we keep world gravity = 0 and apply per-body forces each step\r\n const g = (gravityMode === 'vector') ? gravityVec : { x: 0, y: 0, z: 0 };\r\n\r\n // Different Rapier builds expose constructors differently; try common variants.\r\n try {\r\n if (typeof RAPIER.World === 'function') {\r\n world = new RAPIER.World(g);\r\n } else if (typeof RAPIER.World?.new === 'function') {\r\n world = RAPIER.World.new(g);\r\n } else if (typeof RAPIER?.World === 'object' && typeof RAPIER.World.create === 'function') {\r\n world = RAPIER.World.create(g);\r\n } else if (typeof RAPIER === 'function') {\r\n // In case RAPIER itself is callable and returns a World\r\n world = RAPIER(g);\r\n } else {\r\n // Last resort: attempt to call World as a function if present\r\n world = RAPIER.World ? RAPIER.World(g) : null;\r\n }\r\n postMessage({ type: 'debug', msg: 'rapier world created' });\r\n } catch (err) {\r\n // Surface a clearer error for debugging\r\n postMessage({ type: 'error', msg: 'failed to construct rapier World', error: (err && (err.message || String(err))) || String(err) });\r\n throw new Error('Failed to construct Rapier World: ' + (err && err.message ? err.message : String(err)));\r\n }\r\n }\r\n })();\r\n\r\n try {\r\n await initPromise;\r\n } finally {\r\n // Keep the resolved promise for future awaiters; do not clear to prevent re-init.\r\n }\r\n}\r\n\r\nfunction setVectorGravity(vec3) {\r\n gravityMode = 'vector';\r\n gravityVec = { x: +vec3[0], y: +vec3[1], z: +vec3[2] };\r\n if (world) world.gravity = gravityVec;\r\n}\r\n\r\nfunction setGeocentricGravity(center, intensity) {\r\n gravityMode = 'geocentric';\r\n planetCenter = { x: +center[0], y: +center[1], z: +center[2] };\r\n gravityIntensity = +intensity;\r\n if (world) world.gravity = { x: 0, y: 0, z: 0 };\r\n}\r\n\r\nfunction computeGeocentricAt(p) {\r\n const dir = normV(subV(planetCenter, p));\r\n return scaleV(dir, gravityIntensity);\r\n}\r\n\r\n// Bodies\r\nfunction createBody(desc, id, init) {\r\n try {\r\n if (typeof world.createRigidBody !== 'function') {\r\n postMessage({ type: 'error', msg: 'world.createRigidBody is not a function', value: typeof world.createRigidBody });\r\n throw new Error('world.createRigidBody is not a function');\r\n }\r\n postMessage({ type: 'debug', msg: 'createBody: about to call world.createRigidBody', id, descType: typeof desc, descCtor: (desc && desc.constructor) ? desc.constructor.name : null });\r\n const rb = world.createRigidBody(desc);\r\n if (init?.v && typeof rb.setLinvel === 'function') rb.setLinvel(v3(init.v), false);\r\n if (init?.w && typeof rb.setAngvel === 'function') rb.setAngvel(v3(init.w), false);\r\n bodies.set(id, rb);\r\n bodyInfo.set(id, { type: init.type, mass: init.mass });\r\n return rb;\r\n } catch (err) {\r\n postMessage({ type: 'error', msg: 'createBody failed', error: (err && (err.message || String(err))) || String(err), id, descType: typeof desc });\r\n throw err;\r\n }\r\n}\r\n\r\nfunction removeBodyById(id) {\r\n const rb = bodies.get(id);\r\n if (rb) {\r\n // Remove attached colliders\r\n for (const [cid, owner] of Array.from(colliderOwners.entries())) {\r\n if (owner === id) {\r\n const col = colliders.get(cid);\r\n if (col) world.removeCollider(col, true);\r\n colliders.delete(cid);\r\n colliderOwners.delete(cid);\r\n }\r\n }\r\n world.removeRigidBody(rb);\r\n }\r\n bodies.delete(id);\r\n bodyInfo.delete(id);\r\n}\r\n\r\n// Colliders - create from trimesh with baked scale\r\nfunction createTrimeshColliderScaled({ id, positions, indices, bodyId, local }) {\r\n // Validate incoming positions buffer\r\n if (!(positions instanceof Float32Array)) {\r\n throw new Error('attachCollider: positions must be Float32Array');\r\n }\r\n if (positions.length % 3 !== 0) {\r\n throw new Error('attachCollider: positions length must be a multiple of 3');\r\n }\r\n\r\n // Copy positions to avoid unsafe aliasing with other views that may share the same ArrayBuffer.\r\n // This also protects Rapier's wasm from receiving JS-owned buffers that might be reused elsewhere.\r\n const posCopy = new Float32Array(positions);\r\n\r\n // Bake non-uniform scale into the copied vertex positions\r\n const sx = (local && local.s && +local.s[0]) || 1;\r\n const sy = (local && local.s && +local.s[1]) || 1;\r\n const sz = (local && local.s && +local.s[2]) || 1;\r\n for (let i = 0, n = posCopy.length; i < n; i += 3) {\r\n posCopy[i + 0] *= sx;\r\n posCopy[i + 1] *= sy;\r\n posCopy[i + 2] *= sz;\r\n }\r\n\r\n // Prepare a safe copy of indices (if provided) and validate index ranges\r\n let idxCopy = null;\r\n if (indices) {\r\n const srcIdx = indices instanceof Uint32Array ? indices : new Uint32Array(indices.buffer || indices);\r\n idxCopy = new Uint32Array(srcIdx); // make a copy to avoid aliasing\r\n const vertCount = posCopy.length / 3;\r\n for (let i = 0; i < idxCopy.length; ++i) {\r\n const v = idxCopy[i];\r\n if (!Number.isFinite(v) || v < 0 || v >= vertCount) {\r\n throw new Error(`attachCollider: index out of range or invalid at ${i}: ${v} (vertCount=${vertCount})`);\r\n }\r\n }\r\n }\r\n\r\n // Validate numeric contents to prevent wasm OOB or NaN propagation\r\n for (let i = 0; i < posCopy.length; ++i) {\r\n const v = posCopy[i];\r\n if (!Number.isFinite(v)) throw new Error(`attachCollider: invalid position value at ${i}: ${v}`);\r\n }\r\n\r\n // Construct the Rapier collider descriptor with the copied, validated buffers\r\n const desc = RAPIER.ColliderDesc.trimesh(posCopy, idxCopy);\r\n if (local?.p) desc.setTranslation(+local.p[0], +local.p[1], +local.p[2]);\r\n if (local?.q) desc.setRotation(q4(local.q));\r\n\r\n const rb = bodies.get(bodyId);\r\n if (!rb) throw new Error(`attachCollider: body not found: ${bodyId}`);\r\n const col = world.createCollider(desc, rb);\r\n\r\n colliders.set(id, col);\r\n colliderOwners.set(id, bodyId);\r\n}\r\n\r\nfunction removeColliderById(id) {\r\n const col = colliders.get(id);\r\n if (col) world.removeCollider(col, true);\r\n colliders.delete(id);\r\n colliderOwners.delete(id);\r\n}\r\n\r\n// Engine-agnostic primitive shape adapter\r\nfunction colliderDescFromShape(shape) {\r\n if (!shape || typeof shape !== 'object') throw new Error('attachShapeCollider: missing shape');\r\n const kind = String(shape.kind || '').toLowerCase();\r\n const p = shape.params || {};\r\n switch (kind) {\r\n case 'ball': {\r\n const r = +p.radius;\r\n return RAPIER.ColliderDesc.ball(r);\r\n }\r\n case 'cuboid':\r\n case 'box': {\r\n const hx = +p.hx, hy = +p.hy, hz = +p.hz;\r\n return RAPIER.ColliderDesc.cuboid(hx, hy, hz);\r\n }\r\n case 'roundcuboid':\r\n case 'round_cuboid':\r\n case 'round-cuboid': {\r\n const hx = +p.hx, hy = +p.hy, hz = +p.hz, radius = +p.radius || 0;\r\n return RAPIER.ColliderDesc.roundCuboid(hx, hy, hz, radius);\r\n }\r\n case 'capsule': {\r\n const hh = +p.halfHeight;\r\n const r = +p.radius;\r\n return RAPIER.ColliderDesc.capsule(hh, r);\r\n }\r\n case 'cone': {\r\n const hh = +p.halfHeight;\r\n const r = +p.radius;\r\n return RAPIER.ColliderDesc.cone(hh, r);\r\n }\r\n case 'cylinder': {\r\n const hh = +p.halfHeight;\r\n const r = +p.radius;\r\n return RAPIER.ColliderDesc.cylinder(hh, r);\r\n }\r\n case 'segment': {\r\n const a = p.a || p.p1;\r\n const b = p.b || p.p2;\r\n if (!a || !b) throw new Error('segment requires a and b (or p1,p2)');\r\n return RAPIER.ColliderDesc.segment(v3(a), v3(b));\r\n }\r\n case 'triangle': {\r\n const a = p.a, b = p.b, c = p.c;\r\n if (!a || !b || !c) throw new Error('triangle requires a, b, c');\r\n return RAPIER.ColliderDesc.triangle(v3(a), v3(b), v3(c));\r\n }\r\n case 'polyline': {\r\n const verts = p.vertices instanceof Float32Array ? p.vertices : new Float32Array(p.vertices);\r\n let idx = null;\r\n if (p.indices) idx = p.indices instanceof Uint32Array ? p.indices : new Uint32Array(p.indices);\r\n return RAPIER.ColliderDesc.polyline(verts, idx);\r\n }\r\n case 'convexhull':\r\n case 'convex_hull':\r\n case 'convex-hull': {\r\n const verts = p.vertices instanceof Float32Array ? p.vertices : new Float32Array(p.vertices);\r\n const desc = RAPIER.ColliderDesc.convexHull(verts);\r\n if (!desc) throw new Error('convexHull: invalid or insufficient points');\r\n return desc;\r\n }\r\n case 'heightfield': {\r\n const rows = +p.rows, cols = +p.cols;\r\n const heights = p.heights instanceof Float32Array ? p.heights : new Float32Array(p.heights);\r\n const scale = p.scale || { x: 1, y: 1, z: 1 };\r\n return RAPIER.ColliderDesc.heightfield(rows, cols, heights, scale);\r\n }\r\n default:\r\n throw new Error(`Unknown primitive collider kind: ${shape.kind}`);\r\n }\r\n}\r\n\r\n// Step and state\r\nfunction applyExternalForces(dt) {\r\n if (gravityMode !== 'geocentric') return;\r\n for (const [id, rb] of bodies.entries()) {\r\n if (!rb || rb.isFixed()) continue;\r\n const mass = Math.max(1e-6, bodyInfo.get(id)?.mass ?? 1);\r\n const p = rb.translation();\r\n const g = computeGeocentricAt(p);\r\n const f = { x: g.x * mass, y: g.y * mass, z: g.z * mass };\r\n rb.applyForce(f, true);\r\n }\r\n}\r\n\r\nfunction step(dt) {\r\n world.timestep = dt;\r\n applyExternalForces(dt);\r\n world.step();\r\n simTimeMs += dt * 1000.0;\r\n\r\n const stateBodies = {};\r\n for (const [id, rb] of bodies.entries()) {\r\n const t = rb.translation();\r\n const r = rb.rotation();\r\n stateBodies[id] = { p: [t.x, t.y, t.z], q: [r.x, r.y, r.z, r.w] };\r\n }\r\n postMessage({ type: 'state', state: { timeMs: simTimeMs, bodies: stateBodies } });\r\n}\r\n\r\n// Raycast (first hit)\r\nfunction raycast(origin, dir, maxToi = 1e6) {\r\n const o = v3(origin);\r\n const d = v3(dir);\r\n const ray = new RAPIER.Ray(o, d);\r\n // solid=true returns time-of-impact including if ray starts inside collider\r\n const hit = world.castRay(ray, maxToi, true);\r\n if (!hit) return { hits: [] };\r\n\r\n const toi = hit.timeOfImpact;\r\n const point = ray.pointAt(toi);\r\n const normal = hit.normal;\r\n // Find collider id\r\n let colliderId = null;\r\n for (const [cid, col] of colliders.entries()) {\r\n if (col.handle === hit.collider.handle) {\r\n colliderId = cid;\r\n break;\r\n }\r\n }\r\n let bodyId = null;\r\n const rbHandle = hit.collider.parent()?.handle;\r\n if (rbHandle != null) {\r\n for (const [bid, rb] of bodies.entries()) {\r\n if (rb.handle === rbHandle) { bodyId = bid; break; }\r\n }\r\n }\r\n return {\r\n hits: [{\r\n toi,\r\n point: [point.x, point.y, point.z],\r\n colliderId,\r\n bodyId\r\n }]\r\n };\r\n}\r\n\r\n// Message handling\r\nasync function onMessage(e) {\r\n const msg = e.data || {};\r\n const { id, type, _envId, replyTo } = msg;\r\n const replyId = (typeof _envId !== 'undefined') ? _envId : (typeof replyTo !== 'undefined' ? replyTo : id);\r\n const _ack = (res) => ack(replyId, res);\r\n const _nack = (err) => nack(replyId, err);\r\n try {\r\n switch (type) {\r\n case 'init': {\r\n fixedDt = typeof msg.fixedDt === 'number' ? msg.fixedDt : fixedDt;\r\n const g = msg.gravity || {};\r\n const mode = (g.mode || 'vector').toLowerCase();\r\n if (mode === 'geocentric') {\r\n setGeocentricGravity(g.planetCenter || [0, 0, 0], typeof g.intensity === 'number' ? g.intensity : 9.81);\r\n } else {\r\n setVectorGravity(g.vector || [0, -9.81, 0]);\r\n }\r\n await ensureRapier();\r\n _ack({ ok: true });\r\n break;\r\n }\r\n\r\n case 'addObject': {\r\n await ensureRapier();\r\n const bodyId = msg.id;\r\n const b = msg.body || {};\r\n const typeStr = (b.type || 'dynamic').toLowerCase();\r\n const mass = typeof b.mass === 'number' ? b.mass : 1.0;\r\n const p = v3(b.p || [0, 0, 0]);\r\n const q = q4(b.q || [0, 0, 0, 1]);\r\n \r\n // Validate numeric values to avoid creating a RigidBodyDesc with NaN/Infinity\r\n function isNum(n) { return typeof n === 'number' && isFinite(n); }\r\n if (!isNum(p.x) || !isNum(p.y) || !isNum(p.z)) {\r\n postMessage({ type: 'debug', msg: 'addObject: invalid translation detected, resetting to 0', bodyId, p });\r\n p.x = isNum(p.x) ? p.x : 0;\r\n p.y = isNum(p.y) ? p.y : 0;\r\n p.z = isNum(p.z) ? p.z : 0;\r\n }\r\n if (![q.x, q.y, q.z, q.w].every(isNum)) {\r\n postMessage({ type: 'debug', msg: 'addObject: invalid rotation detected, using identity quat', bodyId, q });\r\n q.x = 0; q.y = 0; q.z = 0; q.w = 1;\r\n } else {\r\n // Normalize quaternion to be safe\r\n const L = Math.hypot(q.x, q.y, q.z, q.w) || 1;\r\n q.x /= L; q.y /= L; q.z /= L; q.w /= L;\r\n }\r\n \r\n let desc;\r\n if (typeStr === 'fixed') desc = RAPIER.RigidBodyDesc.fixed();\r\n else if (typeStr === 'kinematic') desc = RAPIER.RigidBodyDesc.kinematicPositionBased();\r\n else desc = RAPIER.RigidBodyDesc.dynamic().setAdditionalMass(mass);\r\n \r\n // Defensive setters to capture errors before calling into wasm\r\n try {\r\n desc.setTranslation(p.x, p.y, p.z);\r\n } catch (err) {\r\n postMessage({ type: 'error', msg: 'desc.setTranslation failed', error: (err && (err.message || String(err))) || String(err), bodyId, p });\r\n throw err;\r\n }\r\n try {\r\n desc.setRotation(q);\r\n } catch (err) {\r\n postMessage({ type: 'error', msg: 'desc.setRotation failed', error: (err && (err.message || String(err))) || String(err), bodyId, q });\r\n throw err;\r\n }\r\n \r\n postMessage({ type: 'debug', msg: 'addObject: creating body', bodyId, typeStr, mass, p, q });\r\n createBody(desc, bodyId, { type: typeStr, mass, v: b.v, w: b.w });\r\n _ack({ ok: true });\r\n break;\r\n }\r\n\r\n case 'removeObject': {\r\n await ensureRapier();\r\n removeBodyById(msg.id);\r\n _ack({ ok: true });\r\n break;\r\n }\r\n\r\n // addCollider removed: colliders are created during attachCollider\r\n\r\n // disposeCollider removed\r\n\r\n case 'attachCollider':\r\n case 'attachTrimeshCollider': {\r\n await ensureRapier();\r\n const bodyId = msg.bodyId;\r\n const colId = msg.id || msg.colliderId;\r\n const positions = msg.positions;\r\n const indices = msg.indices || null;\r\n const local = msg.local || {};\r\n if (!positions) { ack(id, { ok: false, reason: 'missing positions' }); break; }\r\n const verts = positions instanceof Float32Array ? positions : new Float32Array(positions.buffer || positions);\r\n let idx = indices;\r\n if (idx && !(idx instanceof Uint32Array)) idx = new Uint32Array(idx.buffer || idx);\r\n createTrimeshColliderScaled({\r\n id: colId,\r\n positions: verts,\r\n indices: idx || null,\r\n bodyId,\r\n local\r\n });\r\n _ack({ ok: true, colliderId: colId });\r\n break;\r\n }\r\n \r\n case 'attachShapeCollider': {\r\n await ensureRapier();\r\n const bodyId = msg.bodyId;\r\n const colId = msg.id || msg.colliderId;\r\n const shape = msg.shape;\r\n const local = msg.local || {};\r\n const desc = colliderDescFromShape(shape);\r\n if (local?.p) desc.setTranslation(+local.p[0], +local.p[1], +local.p[2]);\r\n if (local?.q) desc.setRotation(q4(local.q));\r\n const rb = bodies.get(bodyId);\r\n if (!rb) { ack(id, { ok: false, reason: 'unknown body' }); break; }\r\n const col = world.createCollider(desc, rb);\r\n colliders.set(colId, col);\r\n colliderOwners.set(colId, bodyId);\r\n _ack({ ok: true, colliderId: colId });\r\n break;\r\n }\r\n \r\n case 'detachCollider': {\r\n await ensureRapier();\r\n const colId = msg.colliderId || msg.id;\r\n removeColliderById(colId);\r\n _ack({ ok: true });\r\n break;\r\n }\r\n\r\n case 'applyForce': {\r\n await ensureRapier();\r\n const bodyId = msg.id;\r\n const rb = bodies.get(bodyId);\r\n if (!rb) { ack(id, { ok: false, reason: 'unknown body' }); break; }\r\n\r\n const impulse = !!msg.impulse;\r\n const force = v3(msg.force || [0, 0, 0]);\r\n const wake = msg.wake !== false;\r\n\r\n if (impulse) {\r\n if (msg.point && typeof rb.applyImpulseAtPoint === 'function') {\r\n rb.applyImpulseAtPoint(force, v3(msg.point), wake);\r\n } else {\r\n rb.applyImpulse(force, wake);\r\n }\r\n } else {\r\n if (msg.point && typeof rb.applyForceAtPoint === 'function') {\r\n rb.applyForceAtPoint(force, v3(msg.point), wake);\r\n } else {\r\n rb.applyForce(force, wake);\r\n }\r\n }\r\n _ack({ ok: true });\r\n break;\r\n }\r\n\r\n case 'setPose': {\r\n await ensureRapier();\r\n const bodyId = msg.id;\r\n const rb = bodies.get(bodyId);\r\n if (!rb) { _ack({ ok: false, reason: 'unknown body' }); break; }\r\n\r\n const p = msg.p; // [x,y,z] or null\r\n const q = msg.q; // [x,y,z,w] or null\r\n const wake = msg.wake !== false;\r\n\r\n try {\r\n if (typeof rb.isKinematic === 'function' && rb.isKinematic()) {\r\n // Kinematic bodies use \"next\" pose setters\r\n if (p) rb.setNextKinematicTranslation(v3(p));\r\n if (q) rb.setNextKinematicRotation(q4(q));\r\n } else {\r\n // Dynamic/fixed bodies: set pose directly\r\n if (p && typeof rb.setTranslation === 'function') rb.setTranslation(v3(p), true);\r\n if (q && typeof rb.setRotation === 'function') rb.setRotation(q4(q), true);\r\n }\r\n if (wake && typeof rb.wakeUp === 'function') rb.wakeUp();\r\n _ack({ ok: true });\r\n } catch (err) {\r\n _nack(err);\r\n }\r\n break;\r\n }\r\n\r\n case 'setGravity': {\r\n await ensureRapier();\r\n const g = msg.gravity || {};\r\n const mode = (g.mode || 'vector').toLowerCase();\r\n if (mode === 'geocentric') {\r\n setGeocentricGravity(g.planetCenter || [0, 0, 0], typeof g.intensity === 'number' ? g.intensity : 9.81);\r\n } else {\r\n setVectorGravity(g.vector || [0, -9.81, 0]);\r\n }\r\n _ack({ ok: true });\r\n break;\r\n }\r\n\r\n case 'step': {\r\n await ensureRapier();\r\n const dt = typeof msg.dt === 'number' ? clamp(msg.dt, 1 / 600, 1 / 10) : fixedDt;\r\n step(dt);\r\n _ack({ ok: true, dtUsed: dt });\r\n break;\r\n }\r\n\r\n case 'raycast': {\r\n await ensureRapier();\r\n const result = raycast(msg.origin || [0, 0, 0], msg.direction || [0, -1, 0], typeof msg.maxToi === 'number' ? msg.maxToi : 1e6);\r\n _ack(result);\r\n break;\r\n }\r\n\r\n default: {\r\n _ack({ ok: false, reason: 'unknown message type' });\r\n break;\r\n }\r\n }\r\n } catch (err) {\r\n _nack(err);\r\n }\r\n}\r\n\r\nself.addEventListener('message', onMessage);"],"names":["RAPIER","world","initPromise","bodies","bodyInfo","colliders","colliderOwners","gravityMode","gravityVec","planetCenter","gravityIntensity","simTimeMs","fixedDt","ack","id","result","nack","error","clamp","v","a","b","v3","q4","subV","scaleV","s","lenV","normV","L","ensureRapier","mod","initOptions","file","maybe","res","err","g","setVectorGravity","vec3","setGeocentricGravity","center","intensity","computeGeocentricAt","p","dir","createBody","desc","init","rb","removeBodyById","cid","owner","col","createTrimeshColliderScaled","positions","indices","bodyId","local","posCopy","sx","sy","sz","n","idxCopy","srcIdx","vertCount","i","removeColliderById","colliderDescFromShape","shape","kind","r","hx","hy","hz","radius","hh","c","verts","idx","rows","cols","heights","scale","applyExternalForces","dt","mass","f","step","stateBodies","t","raycast","origin","maxToi","o","d","ray","hit","toi","point","colliderId","rbHandle","bid","onMessage","e","msg","type","_envId","replyTo","replyId","_ack","_nack","isNum","typeStr","q","colId","impulse","force","wake"],"mappings":"AAKA,IAAIA,IAAS,MACTC,IAAQ,MAERC,IAAc;AAGlB,MAAMC,IAAS,oBAAI,OACbC,IAAW,oBAAI,OACfC,IAAY,oBAAI,OAChBC,IAAiB,oBAAI;AAG3B,IAAIC,IAAc,UACdC,IAAa,EAAE,GAAG,GAAG,GAAG,OAAO,GAAG,KAClCC,IAAe,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,KAChCC,IAAmB,MAGnBC,IAAY,GACZC,IAAU,IAAI;AAGlB,SAASC,EAAIC,GAAIC,IAAS,MAAM;AAC9B,EAAID,KAAM,QACV,YAAY,EAAE,SAASA,GAAI,QAAAC,EAAM,CAAE;AACrC;AACA,SAASC,EAAKF,GAAIG,GAAO;AACvB,EAAIH,KAAM,QACV,YAAY,EAAE,SAASA,GAAI,OAAQG,MAAUA,EAAM,WAAWA,MAAW,QAAO,CAAE;AACpF;AACA,SAASC,EAAMC,GAAGC,GAAGC,GAAG;AAAE,SAAO,KAAK,IAAID,GAAG,KAAK,IAAIC,GAAGF,CAAC,CAAC;AAAG;AAC9D,SAASG,EAAGF,GAAG;AAAE,SAAO,EAAE,GAAG,CAACA,EAAE,CAAC,GAAG,GAAG,CAACA,EAAE,CAAC,GAAG,GAAG,CAACA,EAAE,CAAC,EAAC;AAAI;AAC1D,SAASG,EAAGH,GAAG;AAAE,SAAO,EAAE,GAAG,CAACA,EAAE,CAAC,GAAG,GAAG,CAACA,EAAE,CAAC,GAAG,GAAG,CAACA,EAAE,CAAC,GAAG,GAAG,CAACA,EAAE,CAAC,EAAC;AAAI;AAIpE,SAASI,EAAKJ,GAAGC,GAAG;AAAE,SAAO,EAAE,GAAGD,EAAE,IAAIC,EAAE,GAAG,GAAGD,EAAE,IAAIC,EAAE,GAAG,GAAGD,EAAE,IAAIC,EAAE,EAAC;AAAI;AAC3E,SAASI,EAAOL,GAAGM,GAAG;AAAE,S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,CAAG;AAAA,QACX;AACA;AAAA,MACF;AAAA,MAEA,KAAK,cAAc;AACjB,cAAMN,EAAY;AAClB,cAAMO,IAAIqE,EAAI,WAAW;AAEzB,SADcrE,EAAE,QAAQ,UAAU,YAAW,MAChC,eACXG,EAAqBH,EAAE,gBAAgB,CAAC,GAAG,GAAG,CAAC,GAAG,OAAOA,EAAE,aAAc,WAAWA,EAAE,YAAY,IAAI,IAEtGC,EAAiBD,EAAE,UAAU,CAAC,GAAG,OAAO,CAAC,CAAC,GAE5C0E,EAAK,EAAE,IAAI,GAAI,CAAE;AACjB;AAAA,MACF;AAAA,MAEA,KAAK,QAAQ;AACX,cAAMjF,EAAY;AAClB,cAAMwD,IAAK,OAAOoB,EAAI,MAAO,WAAWxF,EAAMwF,EAAI,IAAI,IAAI,KAAK,IAAI,EAAE,IAAI9F;AACzE,QAAA6E,EAAKH,CAAE,GACPyB,EAAK,EAAE,IAAI,IAAM,QAAQzB,EAAE,CAAE;AAC7B;AAAA,MACF;AAAA,MAEA,KAAK,WAAW;AACd,cAAMxD,EAAY;AAClB,cAAMf,IAAS6E,EAAQc,EAAI,UAAU,CAAC,GAAG,GAAG,CAAC,GAAGA,EAAI,aAAa,CAAC,GAAG,IAAI,CAAC,GAAG,OAAOA,EAAI,UAAW,WAAWA,EAAI,SAAS,GAAG;AAC9H,QAAAK,EAAKhG,CAAM;AACX;AAAA,MACF;AAAA,MAEA,SAAS;AACP,QAAAgG,EAAK,EAAE,IAAI,IAAO,QAAQ,uBAAsB,CAAE;AAClD;AAAA,MACF;AAAA,IACN;AAAA,EACE,SAAS3E,GAAK;AACZ,IAAA4E,EAAM5E,CAAG;AAAA,EACX;AACF;AAEA,KAAK,iBAAiB,WAAWoE,CAAS;"}
@@ -1499,5 +1499,5 @@ out vec2 vUv;
1499
1499
  void main() {
1500
1500
  vUv = uv;
1501
1501
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
1502
- }`}function Qo(B,A,g,I){const Q=B.getX(g),C=B.getY(g),a=B.getZ(g),e=A.getX(g),i=A.getY(g),t=A.getZ(g);I.set(Q,C,a,C,e,i,a,i,t)}function Co(B,A,g){const I=B.determinant();if(Math.abs(I)<1e-12)return void g.set(0,0,0);const Q=1/I,C=new u.Matrix3().copy(B);C.elements[0]=A.x,C.elements[3]=A.y,C.elements[6]=A.z;const a=new u.Matrix3().copy(B);a.elements[1]=A.x,a.elements[4]=A.y,a.elements[7]=A.z;const e=new u.Matrix3().copy(B);e.elements[2]=A.x,e.elements[5]=A.y,e.elements[8]=A.z,g.set(C.determinant()*Q,a.determinant()*Q,e.determinant()*Q)}function TI(B,A){if(!A||Array.isArray(A)&&A.length!==3)throw new Error(`${B} must be a length-3 array [x,y,z]`);return A}function zC(B,A,g){return{kind:"cuboid",params:{hx:Number(B),hy:Number(A),hz:Number(g)}}}const NQ={createBall:function(B){return{kind:"ball",params:{radius:Number(B)}}},createCuboid:zC,createBox:function(B,A,g){return zC(B,A,g)},createRoundCuboid:function(B,A,g,I){return{kind:"roundCuboid",params:{hx:Number(B),hy:Number(A),hz:Number(g),radius:Number(I)}}},createCapsule:function(B,A){return{kind:"capsule",params:{halfHeight:Number(B),radius:Number(A)}}},createCone:function(B,A){return{kind:"cone",params:{halfHeight:Number(B),radius:Number(A)}}},createCylinder:function(B,A){return{kind:"cylinder",params:{halfHeight:Number(B),radius:Number(A)}}},createSegment:function(B,A){return{kind:"segment",params:{a:TI("a",B),b:TI("b",A)}}},createTriangle:function(B,A,g){return{kind:"triangle",params:{a:TI("a",B),b:TI("b",A),c:TI("c",g)}}},createPolyline:function(B,A){return{kind:"polyline",params:{vertices:B,indices:A||null}}},createConvexHull:function(B){return{kind:"convexHull",params:{vertices:B}}},createHeightfield:function(B,A,g,I={x:1,y:1,z:1}){return{kind:"heightfield",params:{rows:Number(B),cols:Number(A),heights:g,scale:I}}}};var MA;const yg=new Y.Sphere(new Y.Vector3(0,0,0),1),Lg=new tg([0,0,0,1,0,0,0,1,0,0,0,1]);new Y.Box3;const Pg=new Y.Vector3(0,0,0),fI=new Y.Vector3(0,0,0),ao=new Y.Vector3(0,1,0),nB=new Y.Ray,rB=new Y.Matrix4;new Y.Matrix4,new Y.Frustum;const sB=new Y.Vector3,cB=[],XC=new Y.Quaternion,Rg={};function Ue(){var B=[];for(let A in Rg)Rg.hasOwnProperty(A)&&Rg[A]>0&&B.push(A);return B}class jQ extends Y.Object3D{constructor(A){super();const g=this;g.physics=A.physics||{};const I=g.physics;if(I&&typeof I=="object"&&(I.type||(I.type="fixed"),I.shape==null&&(I.shape="none"),I.mass==null&&(I.mass=1),Array.isArray(I.velocity)||I.velocity&&I.velocity.isVector3||(I.velocity=[0,0,0]),Array.isArray(I.angularVelocity)||I.angularVelocity&&I.angularVelocity.isVector3||(I.angularVelocity=[0,0,0]),I.maxLOD==null&&(I.maxLOD=1/0),I.colliders&&typeof I.colliders=="object")){const e=I.colliders;e.maxLOD==null&&(e.maxLOD=Number.isFinite(I.maxLOD)?I.maxLOD:1/0),Array.isArray(e.priority)?(e.priority=e.priority.filter(i=>i==="mesh"||i==="hull"||i==="bounds"),e.priority.length===0&&(e.priority=["mesh","hull","bounds"])):e.priority=["mesh","hull","bounds"],Array.isArray(e.byGeometricError)||(e.byGeometricError=[]),Array.isArray(e.byLevel)||(e.byLevel=[])}if(g.splatsMesh=A.splatsMesh,g.oldUltraMeshSplats=A.oldUltraMeshSplats,g.iosCompatibility=A.iosCompatibility,g.splatsQuality=A.splatsQuality!=null?A.splatsQuality:.75,g.splatsCPUCulling=A.splatsCPUCulling!=null&&A.splatsCPUCulling,this.contentURL=[],A.domWidth&&A.domHeight?this.rendererSize=new Y.Vector2(A.domWidth,A.domHeight):this.rendererSize=new Y.Vector2(1e3,1e3),this.setClipShape(A.clipShape),this.loadingStrategy=A.loadingStrategy?A.loadingStrategy.toUpperCase():"INCREMENTAL",this.distanceBias=Math.max(1e-4,A.distanceBias?A.distanceBias:1),this.proxy=A.proxy,this.drawBoundingVolume=!!A.drawBoundingVolume&&A.drawBoundingVolume,this.displayErrors=A.displayErrors,this.displayCopyright=A.displayCopyright,A.queryParams&&(this.queryParams={...A.queryParams}),this.uuid=Va(),A.tileLoader)this.tileLoader=A.tileLoader;else{const e={};e.meshCallback=A.meshCallback?A.meshCallback:(t,E)=>{t.material.wireframe=!1,t.material.side=Y.DoubleSide},e.pointsCallback=A.pointsCallback?A.pointsCallback:(t,E)=>{t.material.size=Math.pow(E,.33),t.material.sizeAttenuation=!0},e.proxy=this.proxy,e.renderer=A.renderer,e.dracoLoader=A.dracoLoader,e.ktx2Loader=A.ktx2Loader,g.tileLoader=new Pa(e);const i=this.update;this.update=t=>{i.call(g,t),g.tileLoader.update()}}this.displayCopyright=!!A.displayCopyright,this.geometricErrorMultiplier=A.geometricErrorMultiplier?A.geometricErrorMultiplier:1,this.splatsCropRadius=Number.MAX_VALUE,this.splatsSizeMultiplier=1,this.splatsExposureEV=A&&A.splatsExposureEV!==void 0?A.splatsExposureEV:0,this.splatsSaturation=A&&A.splatsSaturation!==void 0?A.splatsSaturation:1,this.splatsContrast=A&&A.splatsContrast!==void 0?A.splatsContrast:1;const Q=A&&A.splatsTempTint!==void 0?A.splatsTempTint:[0,0];if(this.splatsTempTint=Array.isArray(Q)?[Number(Q[0]||0),Number(Q[1]||0)]:[Number(Q.temp||0),Number(Q.tint||0)],this.renderer=A.renderer,this.meshCallback=A.meshCallback,this.loadOutsideView=A.loadOutsideView,this.cameraOnLoad=A.cameraOnLoad,this.parentTile=A.parentTile,this.occlusionCullingService=A.occlusionCullingService,this.static=A.static,this.occlusionCullingService&&(this.color=new Y.Color,this.color.setHex(16777215*Math.random()),this.colorID=Y.MathUtils.clamp(255*g.color.r,0,255)<<16^Y.MathUtils.clamp(255*g.color.g,0,255)<<8^Y.MathUtils.clamp(255*g.color.b,0,255)),this.static&&(this.matrixAutoUpdate=!1,this.matrixWorldAutoUpdate=!1),this.childrenTiles=[],this.meshContent=[],this.tileContent,this.refine,this.rootPath,this.geometricError,this.boundingVolume,this.json,this.materialVisibility=!1,this.level=A.level?A.level:0,this.hasMeshContent=0,this.hasUnloadedJSONContent=0,this.centerModel=A.centerModel,this.abortController=new AbortController,this.onLoadCallback=A.onLoadCallback,A.json)g._setup(A);else if(A.url){var C=A.url;if(g.queryParams){var a="";for(let e in g.queryParams)g.queryParams.hasOwnProperty(e)&&(a+="&"+e+"="+g.queryParams[e]);C.includes("?")?C+=a:C+="?"+a.substring(1)}(g.proxy?()=>fetch(g.proxy,{method:"POST",body:C,signal:g.abortController.signal}):()=>fetch(C,{signal:g.abortController.signal}))().then(e=>{if(!e.ok)throw new Error(`couldn't load "${A.url}". Request failed with status ${e.status} : ${e.statusText}`);e.json().then(i=>mQ(i,C)).then(i=>{g._setup({rootPath:iI.dirname(A.url),json:i})})}).catch(e=>{g.displayErrors&&ZC(e)})}}setClipShape(A){if(A instanceof tg||A instanceof Y.Sphere)this.clipShape=A;else if(A instanceof Y.Box3){const g=new Y.Vector3,I=new Y.Vector3;A.getCenter(g),A.getSize(I).multiplyScalar(.5),this.clipShape=new tg([g.x,g.y,g.z,I.x,0,0,0,I.y,0,0,0,I.z])}else A=void 0;this.childrenTiles&&this.childrenTiles.forEach(g=>{g._setClipShape(this.clipShape)})}_setClipShape(A){this.clipShape=A,this.childrenTiles&&this.childrenTiles.forEach(g=>{g._setClipShape(this.clipShape)})}setSplatsSizeMultiplier(A){this.splatsSizeMultiplier=A,this.splatsMesh&&this.splatsMesh.setSplatsSizeMultiplier(this.splatsSizeMultiplier)}setSplatsCropRadius(A){this.splatsCropRadius=A,this.splatsMesh&&this.splatsMesh.setSplatsCropRadius(this.splatsCropRadius)}setSplatsDepthBias(A){this.splatsDepthBias=A,this.splatsMesh&&this.splatsMesh.setDepthBias(this.splatsDepthBias)}setSplatsCPUCulling(A){this.splatsCPUCulling=A,this.splatsMesh&&this.splatsMesh.setSplatsCPUCulling(A)}setSplatsQuality(A){this.splatsQuality=A,this.splatsMesh&&this.splatsMesh.setQuality(A)}setSplatsExposureEV(A){this.splatsExposureEV=A,this.splatsMesh&&typeof this.splatsMesh.setExposureEV=="function"&&this.splatsMesh.setExposureEV(A)}setSplatsSaturation(A){this.splatsSaturation=A,this.splatsMesh&&typeof this.splatsMesh.setSaturation=="function"&&this.splatsMesh.setSaturation(A)}setSplatsContrast(A){this.splatsContrast=A,this.splatsMesh&&typeof this.splatsMesh.setContrast=="function"&&this.splatsMesh.setContrast(A)}setSplatsTempTint(A,g){this.splatsTempTint=[A,g],this.splatsMesh&&typeof this.splatsMesh.setTempTint=="function"&&this.splatsMesh.setTempTint(A,g)}updateMatrices(){this.updateMatrix(),this.splatsMesh&&this.splatsMesh.updateMatrix(),this.static&&(this.traverse(A=>{A.isObject3D&&(A.matrixWorldAutoUpdate=!0)}),this.splatsMesh&&(this.splatsMesh.matrixWorldAutoUpdate=!0)),this.updateMatrixWorld(!0),this.static&&(this.traverse(A=>{A.isObject3D&&(A.matrixWorldAutoUpdate=!1)}),this.splatsMesh&&(this.splatsMesh.matrixWorldAutoUpdate=!1))}setCanvasSize(A,g){this.rendererSize.set(A,g)}async _setup(A){const g=this;if(A.json.extensionsRequired&&(A.json.extensionsRequired.includes("JDULTRA_gaussian_splats")||A.json.extensionsRequired.includes("JDULTRA_gaussian_splats_V2"))&&(g.oldUltraMeshSplats=!0),A.json.root?(g.json=A.json.root,g.json.refine||(g.json.refine=A.json.refine),g.json.geometricError||(g.json.geometricError=A.json.geometricError),g.json.transform||(g.json.transform=A.json.transform),g.json.boundingVolume||(g.json.boundingVolume=A.json.boundingVolume)):g.json=A.json,g.json.children||(g.json.getChildren?g.json.children=await g.json.getChildren():g.json.children=[]),g.rootPath=A.json.rootPath?A.json.rootPath:A.rootPath,g.json.refine?g.refine=g.json.refine:g.refine=A.parentRefine,g.json.geometricError?g.geometricError=g.json.geometricError:g.geometricError=A.parentGeometricError,g.json.transform){let Q=new Y.Matrix4;Q.elements=g.json.transform,g.applyMatrix4(Q)}if(g.json.boundingVolume)if(g.json.boundingVolume.box)g.boundingVolume=new tg(g.json.boundingVolume.box);else if(g.json.boundingVolume.region){const Q=g.json.boundingVolume.region;g._transformWGS84ToCartesian(Q[0],Q[1],Q[4],Pg),g._transformWGS84ToCartesian(Q[2],Q[3],Q[5],fI),Pg.lerp(fI,.5),g.boundingVolume=new Y.Sphere(new Y.Vector3(Pg.x,Pg.y,Pg.z),Pg.distanceTo(fI))}else if(g.json.boundingVolume.sphere){const Q=g.json.boundingVolume.sphere;g.boundingVolume=new Y.Sphere(new Y.Vector3(Q[0],Q[1],Q[2]),Q[3])}else g.boundingVolume=A.parentBoundingVolume;else g.boundingVolume=A.parentBoundingVolume;function I(Q){Q.uri&&Q.uri.includes("json")||Q.url&&Q.url.includes("json")?g.hasUnloadedJSONContent++:g.hasMeshContent++}if(g.json.content?(I(g.json.content),g.hasMeshContent==0&&(g.level=Math.max(0,g.parentTile?g.parentTile.level+.01:0)),g._load()):g.json.contents&&(g.json.contents.forEach(Q=>I(Q)),g.hasMeshContent==0&&(g.level=Math.max(0,g.parentTile?g.parentTile.level+.01:0))),g.centerModel&&(fI.copy(g.boundingVolume.center),this.json.boundingVolume.region&&(this._transformWGS84ToCartesian(.5*(this.json.boundingVolume.region[0]+this.json.boundingVolume.region[2]),.5*(this.json.boundingVolume.region[1]+this.json.boundingVolume.region[3]),.5*(this.json.boundingVolume.region[4]+this.json.boundingVolume.region[5]),Pg),XC.setFromUnitVectors(Pg.normalize(),ao.normalize()),g.applyQuaternion(XC)),fI.applyMatrix4(g.matrix),g.position.sub(fI),g.updateMatrices()),g.onLoadCallback&&g.onLoadCallback(g),!g.parentTile&&g.physics&&g.physics.sim&&(g.physics.rigidBodyID=g.physics.sim.addObject({object:g,type:g.physics.type,mass:g.physics.mass,position:g.position,rotation:g.quaternion,velocity:g.physics.velocity,angularVelocity:g.physics.angularVelocity})),g.isSetup=!0,g.level>0&&g.drawBoundingVolume)if(g.bbox&&console.log("double setup"),this.boundingVolume.aabb){let Q=this.boundingVolume.aabb.clone();Q.applyMatrix4(this.matrixWorld),g.bbox=new Y.Box3Helper(Q,new Y.Color(Math.random(),Math.random(),Math.random())),g.add(g.bbox),g.bbox.material.visible=!1}else g.boundingVolume instanceof tg&&(g.bbox=g.boundingVolume.helper(),g.add(g.bbox),g.bbox.material.visible=!1)}_assembleURL(A,g){A.endsWith("/")||(A+="/");try{const I=new URL(A);let Q=I.pathname.split("/").filter(a=>a!==""),C=g.split("/").filter(a=>a!=="");for(let a=1;a<=Q.length&&!(a>=C.length);a++)if(Q.slice(Q.length-a,Q.length).join("/")===C.slice(0,a).join("/")){for(let i=0;i<a;i++)Q.pop();break}for(;C.length>0&&C[0]==="..";)Q.pop(),C.shift();return`${I.protocol}//${I.host}/${[...Q,...C].join("/")}`}catch{return A.endsWith("/")||g.startsWith("/")?A+g:A+"/"+g}}_extractQueryParams(A,g){try{const I=new URL(A);for(let[Q,C]of I.searchParams)g[Q]=C;return I.search="",I.toString()}catch{return A}}async _load(A=!0,g=!0){var I=this;if(!I.deleted||!g){if(I.json.content)await Q(I.json.content,null,A,g);else if(I.json.contents){let C=I.json.contents.map((a,e)=>Q(a,e,A,g));Promise.all(C)}}async function Q(C,a,e,i){let t;C.uri?t=C.uri:C.url&&(t=C.url);const E=/^(?:http|https|ftp|tcp|udp):\/\/\S+/;if(E.test(I.rootPath)?E.test(t)||(t=I._assembleURL(I.rootPath,t)):t=I.rootPath+iI.sep+t,t.startsWith("/local-tiles")||(t=I._extractQueryParams(t,I.queryParams)),I.queryParams){var o="";for(let r in I.queryParams)I.queryParams.hasOwnProperty(r)&&(o+="&"+r+"="+I.queryParams[r]);t.includes("?")?t+=o:t+="?"+o.substring(1)}if(t)if(I.contentURL.push(t),i&&(t.includes(".b3dm")||t.includes(".glb")||t.includes(".gltf")))try{I.tileLoader.get(I.abortController,I.uuid,t,r=>{if(!I.deleted){if(r.asset&&r.asset.copyright&&(r.asset.copyright.split(";").forEach(n=>{Rg[n]?Rg[n]++:Rg[n]=1}),I.displayCopyright&&rQ()),r.isSplatsData){if(!I.splatsMesh){if(I.splatsMesh=new Ne(I.tileLoader.renderer,void 0,void 0,I.oldUltraMeshSplats?.25:1),I.splatsMesh.setQuality(I.splatsQuality),I.splatsMesh.setSplatsCPUCulling(I.splatsCPUCulling),I.splatsMesh.setSplatsCropRadius(I.splatsCropRadius),I.splatsMesh.setSplatsSizeMultiplier(I.splatsSizeMultiplier),I.splatsExposureEV!==void 0&&typeof I.splatsMesh.setExposureEV=="function"&&I.splatsMesh.setExposureEV(I.splatsExposureEV),I.splatsSaturation!==void 0&&typeof I.splatsMesh.setSaturation=="function"&&I.splatsMesh.setSaturation(I.splatsSaturation),I.splatsContrast!==void 0&&typeof I.splatsMesh.setContrast=="function"&&I.splatsMesh.setContrast(I.splatsContrast),I.splatsTempTint!==void 0&&typeof I.splatsMesh.setTempTint=="function"){const n=I.splatsTempTint||[0,0];I.splatsMesh.setTempTint(n[0],n[1])}I.static&&(I.splatsMesh.matrixAutoUpdate=!1,I.splatsMesh.matrixWorldAutoUpdate=!1),I.add(I.splatsMesh),I.updateMatrices()}r=I.splatsMesh.addSplatsTile(r.positions,r.colors,r.cov0,r.cov1)}return r.isSplatsBatch||(r.traverse(n=>{if((n.isMesh||n.isPoints)&&n.layers.disable(0),n.isMesh&&I.occlusionCullingService){const s=n.geometry.attributes.position,c=[];for(let D=0;D<s.count;D++)c.push(I.color.r,I.color.g,I.color.b);n.geometry.setAttribute("color",new Y.Float32BufferAttribute(c,3))}}),I.add(r),I.updateMatrices()),I.meshContent.push(r),r}},I.cameraOnLoad?()=>I.loadingStrategy=="IMMEDIATE"?I._calculateDistanceToCamera(I.cameraOnLoad):I.loadingStrategy=="INCREMENTAL"?I.parentTile?I.parentTile._calculateDistanceToCamera(I.cameraOnLoad)/Math.max(1,I.parentTile.level):I._calculateDistanceToCamera(I.cameraOnLoad)/Math.max(1,I.level):I.loadingStrategy=="PERLEVEL"?I.parentTile?I.level+I.parentTile._calculateDistanceToCamera(I.cameraOnLoad):I.level+I._calculateDistanceToCamera(I.cameraOnLoad):0:()=>0,()=>I._getSiblings(),I.level,I.loadingStrategy,!I.json.boundingVolume.region,!!I.json.boundingVolume.region,I.geometricError,I.oldUltraMeshSplats)}catch(r){I.displayErrors&&ZC(r)}else e&&t.includes(".json")&&(I.jsonRequested=t,I.tileLoader.get(I.abortController,I.uuid,t,async r=>{I.jsonReceived=!0,r.rootPath=iI.dirname(t),I.json.children.push(r),a==null?delete I.json.content:I.json.contents.splice(a,1),I.hasUnloadedJSONContent--}))}}dispose(){const A=this;if(A.physics&&A.physics.sim&&(A.colliderUUID&&(A.physics.sim.detachCollider({colliderId:A.colliderUUID}),A.colliderUUID=void 0),Array.isArray(A.colliderUUIDs)&&A.colliderUUIDs.length)){for(const g of A.colliderUUIDs)A.physics.sim.detachCollider({colliderId:g});A.colliderUUIDs=[]}A.meshContent.forEach(g=>{g&&g.asset&&g.asset.copyright&&(g.asset.copyright.split(";").forEach(I=>{Rg[I]&&Rg[I]--}),A.displayCopyright&&rQ())}),A.childrenTiles.forEach(g=>g.dispose()),A.deleted=!0,A.splatsMesh&&(A.meshContent.forEach(g=>g.hide()),A.parentTile||(A.splatsMesh.dispose(),A.splatsMesh=void 0)),A.contentURL&&(A.contentURL.forEach(g=>{A.tileLoader.invalidate(g,A.uuid)}),A.contentURL=[]),A.abortController&&!A.jsonRequested&&A.abortController.abort("tile not needed"),this.parent=null,A.meshContent=[],A.bbox&&A.bbox.dispose(),this.dispatchEvent({type:"removed"})}_disposeMeshContent(){const A=this;if(!A.deleted){A.deleted=!0,A.abortController&&(A.abortController.abort("tile not needed"),A.abortController=new AbortController);for(let g=A.meshContent.length-1;g>=0;g--){const I=A.meshContent[g];I&&I.asset&&I.asset.copyright&&(I.asset.copyright.split(";").forEach(Q=>{Rg[Q]&&Rg[Q]--}),A.displayCopyright&&rQ()),A.remove(I)}A.splatsMesh&&A.meshContent.forEach(g=>g.hide()),A.meshContent=[],A.contentURL.forEach(g=>{A.tileLoader.invalidate(g,A.uuid)}),A.contentURL=[]}}_disposeChildren(){var A=this;A.childrenTiles.forEach(g=>{g.dispose(),A.remove(g)}),A.childrenTiles=[]}raycast(A,g){if(this.splatsMesh){nB.copy(A.ray),rB.copy(this.matrixWorld).invert(),nB.applyMatrix4(rB);let I=!1;if(this.boundingVolume instanceof tg)I=this.boundingVolume.intersectsRay(nB);else{if(!(this.boundingVolume instanceof Y.Sphere))return!1;I=ray.intersectsSphere(this.boundingVolume)}return I&&this.materialVisibility&&this.splatsReady&&(cB.length=0,this.meshContent.forEach(Q=>{Q.isSplatsBatch&&(Q.raycast(nB,cB,A.params.Points.threshold),cB.forEach(C=>{C.point.applyMatrix4(this.matrixWorld)}),g.push(...cB))})),I}return super.raycast(A,g)}update(A){this.splatsMesh&&this.splatsMesh.updateShaderParams(A,this.renderer);const g=new Y.Frustum;g.setFromProjectionMatrix(new Y.Matrix4().multiplyMatrices(A.projectionMatrix,A.matrixWorldInverse));let I=[0],Q=[0],C=[0],a=[0];if(this.refine=="REPLACE"?this.loadingStrategy==="IMMEDIATE"?(this._updateImmediate(A,g),this._statsImmediate(C,I,a,Q)):(this._update(A,g),this._stats(C,I,a,Q)):(this._update(A,g),this._stats(C,I,a,Q)),I>0&&(a[0]/=I[0]),this.splatsMesh)if(sB.copy(A.position),rB.copy(this.matrixWorld).invert(),sB.applyMatrix4(rB),this.splatsCPUCulling){const e=new Y.Matrix4().multiplyMatrices(A.projectionMatrix,A.matrixWorldInverse).multiply(this.matrixWorld);this.splatsMesh.sort(sB,e)}else this.splatsMesh.sort(sB);return this.splatsMesh&&this.splatsMesh.update(),{numTilesLoaded:I[0],numTilesRendered:Q[0],maxLOD:C[0],percentageLoaded:a[0]}}_updateImmediate(A,g){this._computeMetricRecursive(A,g),this._updateNodeVisibilityImmediate(),this._expandTreeImmediate(A),this.shouldBeVisible=this.metric>0||!!this.loadOutsideView,this._shouldBeVisibleUpdateImmediate(),this._trimTreeImmediate(),this._loadMeshImmediate()}_statsImmediate(A,g,I,Q){A[0]=Math.max(A[0],this.level),(this.shouldBeVisible||this.materialVisibility)&&(g[0]++,this.materialVisibility&&I[0]++),this.materialVisibility&&Q[0]++,this.childrenTiles.forEach(C=>{C._statsImmediate(A,g,I,Q)})}_stats(A,g,I,Q){A[0]=Math.max(A[0],this.level),this.hasMeshContent&&(g[0]++,this.meshContent.length==this.hasMeshContent&&I[0]++,this.materialVisibility&&Q[0]++),this.childrenTiles.forEach(C=>{C._stats(A,g,I,Q)})}_trimTreeImmediate(){const A=this;if(A.metric!=null)if(A.hasMeshContent&&A.shouldBeVisible&&A.materialVisibility){if(A.splatsMesh&&!A.splatsReady)return;A._disposeChildren()}else A.childrenTiles.forEach(g=>{g._trimTreeImmediate()})}_updateNodeVisibilityImmediate(A=!1){const g=this;if(g.hasMeshContent)if(g.shouldBeVisible)g.meshContent.length==g.hasMeshContent?g.materialVisibility?g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(!0)}):(g._changeContentVisibility(!0),g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)})):g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)});else{if(!g.loadOutsideView&&g.metric<0)return g._changeContentVisibility(!1),g.meshContent.length>0&&g._disposeMeshContent(),void g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(!0)});if(!g.materialVisibility||g.splatsMesh&&!g.splatsReady)g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)});else if(A)g._changeContentVisibility(!1),g.meshContent.length>0&&g._disposeMeshContent(),g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)});else{let I=!0;g.childrenTiles.every(Q=>!!Q._isReadyImmediate()||(I=!1,!1)),I&&g.childrenTiles.length>0?(g._changeContentVisibility(!1),g.meshContent.length>0&&g._disposeMeshContent(),g.childrenTiles.forEach(Q=>{Q._updateNodeVisibilityImmediate(A)})):g.childrenTiles.forEach(Q=>{Q._updateNodeVisibilityImmediate(!g.splatsMesh||!!g.splatsReady)})}}else g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)})}_shouldBeVisibleUpdateImmediate(){const A=this;A.hasMeshContent?A.metric==null?A.shouldBeVisible=!1:A.metric<0?(A.shouldBeVisible=!!A.loadOutsideView,A.childrenTiles.forEach(g=>{g._setShouldNotBeVisibleRecursive()})):A.metric<A.geometricErrorMultiplier*A.geometricError?A.hasUnloadedJSONContent||(A.json&&A.json.children&&A.json.children.length>0?(A.shouldBeVisible=!1,A.childrenTiles.forEach(g=>{g.shouldBeVisible=!0,g._shouldBeVisibleUpdateImmediate()})):A.shouldBeVisible=!0):A.childrenTiles.forEach(g=>{g._setShouldNotBeVisibleRecursive()}):(A.childrenTiles.forEach(g=>{g.shouldBeVisible=!0,g._shouldBeVisibleUpdateImmediate()}),A.shouldBeVisible=!1)}_setShouldNotBeVisibleRecursive(){this.shouldBeVisible=!1,this.childrenTiles.forEach(A=>{A._setShouldNotBeVisibleRecursive()})}_loadMeshImmediate(){const A=this;A.hasMeshContent&&A.shouldBeVisible?A.meshContent.length<A.hasMeshContent&&A.contentURL.length==0&&(A.deleted=!1,A._load(!1,!0)):A.childrenTiles.forEach(g=>{g._loadMeshImmediate()})}_computeMetricRecursive(A,g){const I=this;I.metric=-1,I.isSetup&&(I.boundingVolume&&I.geometricError&&(I.metric=I._calculateUpdateMetric(A,g)),I.childrenTiles.forEach(Q=>Q._computeMetricRecursive(A,g)))}_expandTreeImmediate(A){const g=this;g.hasUnloadedJSONContent||(g.hasMeshContent?g.occlusionCullingService&&g.hasMeshContent&&!g.occlusionCullingService.hasID(g.colorID)||g.metric>=0&&g.metric<g.geometricErrorMultiplier*g.geometricError&&g.json&&g.json.children&&g.childrenTiles.length<g.json.children.length&&g._loadJsonChildren(A):g.json&&g.json.children&&g.childrenTiles.length<g.json.children.length&&g._loadJsonChildren(A)),g.childrenTiles.forEach(I=>I._expandTreeImmediate(A))}_update(A,g){const I=this;if(!I.isSetup)return;const Q=I.materialVisibility;I.boundingVolume&&I.geometricError&&(I.metric=I._calculateUpdateMetric(A,g)),I.childrenTiles.forEach(C=>C._update(A,g)),function(C){if(C<0)return I.inFrustum=!1,void I._changeContentVisibility(!!I.loadOutsideView);if(I.inFrustum=!0,!!I.hasMeshContent&&!(I.meshContent.length<I.hasMeshContent)){if(I.childrenTiles.length==0)return void I._changeContentVisibility(!0);if(C>=I.geometricErrorMultiplier*I.geometricError)I._changeContentVisibility(!0);else if(C<I.geometricErrorMultiplier*I.geometricError&&I.refine=="REPLACE"){let a=!0;I.childrenTiles.every(e=>!!e._isReady()||(a=!1,!1)),a?I._changeContentVisibility(!1):I._changeContentVisibility(!0)}}}(I.metric),function(C){C<0&&I.hasMeshContent||I.occlusionCullingService&&I.hasMeshContent&&!I.occlusionCullingService.hasID(I.colorID)||(!I.hasMeshContent||C<=I.geometricErrorMultiplier*I.geometricError&&(I.meshContent.length>0||I.splatsMesh))&&I.json&&I.json.children&&I.childrenTiles.length!=I.json.children.length&&I._loadJsonChildren(A)}(I.metric),function(C,a){if(I.hasMeshContent){if(!I.inFrustum)return void I._disposeChildren();if(I.occlusionCullingService&&!a&&I.hasMeshContent&&I.meshContent.length>0&&I.materialVisibility&&I._areAllChildrenLoadedAndHidden())return I.splatsMesh&&I.materialVisibility&&!I.splatsReady?void 0:void I._disposeChildren();if(C>=I.geometricErrorMultiplier*I.geometricError){if(I.splatsMesh&&I.materialVisibility&&!I.splatsReady)return;I._disposeChildren()}}}(I.metric,Q)}_loadJsonChildren(A){const g=this;for(let I=g.json.children.length-1;I>=0;I--)g.json.children[I].root||g.json.children[I].children||g.json.children[I].getChildren||g.json.children[I].content||g.json.children[I].contents||g.json.children.splice(I,1);g.json.children.forEach(I=>{let Q=new jQ({parentTile:g,queryParams:g.queryParams,parentGeometricError:g.geometricError,parentBoundingVolume:g.boundingVolume,parentRefine:g.refine,json:I,rootPath:g.rootPath,geometricErrorMultiplier:g.geometricErrorMultiplier,loadOutsideView:g.loadOutsideView,level:Math.floor(g.level)+1,tileLoader:g.tileLoader,cameraOnLoad:A,occlusionCullingService:g.occlusionCullingService,renderer:g.renderer,static:g.static,centerModel:!1,displayErrors:g.displayErrors,displayCopyright:g.displayCopyright,distanceBias:g.distanceBias,loadingStrategy:g.loadingStrategy,drawBoundingVolume:g.drawBoundingVolume,splatsMesh:g.splatsMesh,clipShape:g.clipShape,oldUltraMeshSplats:g.oldUltraMeshSplats,physics:g.physics});g.childrenTiles.push(Q),g.add(Q)}),g.updateMatrices(!0)}_areAllChildrenLoadedAndHidden(){let A=!0;const g=this;return this.childrenTiles.every(I=>{if(I.hasMeshContent){if(I.childrenTiles.length>0)return A=!1,!1;if(I.metric<0)return!0;if(I.materialVisibility&&(!g.splatsMesh||g.splatsReady)||g.occlusionCullingService.hasID(I.colorID))return A=!1,!1}else if(!I._areAllChildrenLoadedAndHidden())return A=!1,!1;return!0}),A}_isReady(){if(this.metric==null)return!1;if(this.metric<0)return!0;if(this.hasUnloadedJSONContent)return!1;if(!this.hasMeshContent&&this.json.children.length==0&&!this.hasUnloadedJSONContent)return!0;if(!this.hasMeshContent||this.meshContent.length==0||!this.materialVisibility){if(this.children.length>0){var A=!0;return this.childrenTiles.every(g=>!!g._isReady()||(A=!1,!1)),A}return!1}return!this.hasMeshContent||!(this.meshContent.length<this.hasMeshContent)&&!!this.materialVisibility}_isReadyImmediate(){if(this.materialVisibility||!this.loadOutsideView&&this.metric<0)return!0;if(this.childrenTiles.length>0){var A=!0;return this.childrenTiles.every(g=>!!g._isReadyImmediate()||(A=!1,!1)),A}return!1}_changeContentVisibility(A){const g=this;if(g.materialVisibility!=A){if(g.bbox&&(g.bbox.material.visible=A),g.splatsMesh)A!=g.materialVisibility&&(g.meshContent.forEach(I=>{A&&I.isSplatsBatch?I.show(()=>{g.materialVisibility&&(g.splatsReady=!0)}):(I.hide(),g.splatsReady=!1)}),g.materialVisibility=A);else{if(g.hasMeshContent&&g.meshContent.length>0&&(A?g.meshContent.forEach(I=>{I.traverse(Q=>{(Q.isMesh||Q.isPoints)&&Q.layers.enable(0)})}):g.meshContent.forEach(I=>{I.traverse(Q=>{(Q.isMesh||Q.isPoints)&&Q.layers.disable(0)})})),g.materialVisibility==A)return;g.materialVisibility=A}g._updateCollider()}}setPose(A,g,I){if(!A.isVector3)throw new TypeError("OGC3DTile.setPose: 'position' must be an instance of THREE.Vector3");if(!I.isVector3)throw new TypeError("OGC3DTile.setPose: 'scale' must be an instance of THREE.Vector3");if(!g.isEuler&&!g.isQuaternion)throw new TypeError("OGC3DTile.setPose: 'rotation' must be a THREE.Euler or THREE.Quaternion");this.physics&&this.physics.sim&&this.physics.rigidBodyID?(this.physics.sim.setPose({bodyId:this.physics.rigidBodyID,position:A,rotation:g}),I&&!I.equals(this.scale)&&(this.scale.copy(I),this.updateMatrices(),this.traverse(Q=>{Q._updateCollider&&Q._updateCollider()}))):(this.scale.copy(I),g.isQuaternion?this.setRotationFromQuaternion(g):this.setRotationFromEuler(g),this.position.copy(A),this.updateMatrices())}_updateCollider(){const A=this;if(!A.physics||!A.physics.sim)return;const g=A.physics.rigidBodyID,I=Math.floor(A.level||0),Q=!!A.materialVisibility,C=Array.isArray(A.childrenTiles)&&A.childrenTiles.length>0,a=A.physics&&A.physics.colliders&&typeof A.physics.colliders=="object"?A.physics.colliders:null,e=Number.isFinite(a?.maxLOD)?a.maxLOD:Number.isFinite(A.physics.maxLOD)?A.physics.maxLOD:1/0,i=(G,N)=>{const F=Array.isArray(N)&&N.length?N:["mesh","hull","bounds"];for(const k of F)if(G.includes(k))return k;return null},t=()=>{const G=a?.priority||["mesh","hull","bounds"];if(a&&Array.isArray(a.byGeometricError)&&a.byGeometricError.length){const N=A.geometricError;if(typeof N=="number"){const F=[];for(const m of a.byGeometricError){if(!m||!m.shape)continue;const S=typeof m.min=="number"?m.min:-1/0,j=typeof m.max=="number"?m.max:1/0;N>=S&&N<j&&F.push(m.shape)}const k=i(F,G);if(k)return k}return a.defaultShape?a.defaultShape:A.physics.shape?A.physics.shape:"none"}if(a&&Array.isArray(a.byLevel)&&a.byLevel.length){const N=Math.floor(A.level||0),F=[];for(const m of a.byLevel){if(!m||!m.shape)continue;const S=typeof m.min=="number"?m.min:-1/0,j=typeof m.max=="number"?m.max:1/0;N>=S&&N<=j&&F.push(m.shape)}return i(F,G)||(a.defaultShape?a.defaultShape:A.physics.shape?A.physics.shape:"none")}return A.physics.shape||"none"},E=t(),o=()=>{A.colliderUUID&&(A.physics.sim.detachCollider({colliderId:A.colliderUUID}),A.colliderUUID=void 0)},r=()=>{if(Array.isArray(A.colliderUUIDs)&&A.colliderUUIDs.length){for(const G of A.colliderUUIDs)A.physics.sim.detachCollider({colliderId:G});A.colliderUUIDs=[]}},n=()=>{o(),r(),A._activeColliderShape=void 0};if(!g||!E||E==="none"||I>e)return n(),void(A._activeColliderShape=void 0);const s=Q&&I<=e,c=A._activeColliderShape||"none";c===E||!Q&&I===e&&C||(c!=="mesh"&&c!=="hull"||E!=="bounds"?c!=="bounds"||E!=="mesh"&&E!=="hull"?c==="mesh"&&E==="hull"||c==="hull"&&E==="mesh"?r():n():o():r(),A._activeColliderShape=E&&E!=="none"?E:void 0);let D=A;for(;D&&D.parentTile;)D=D.parentTile;const d=new Y.Vector3,h=new Y.Quaternion,l=new Y.Vector3;D&&D.matrixWorld&&D.matrixWorld.decompose(d,h,l);const f=new Y.Matrix4().compose(d,h,new Y.Vector3(1,1,1)),R=new Y.Matrix4().copy(f).invert();if(E!=="bounds"){if(E==="mesh"||E==="hull")if(console.log(E+" "+this.level),o(),s){if(!A.hasMeshContent||A.meshContent.length!==A.hasMeshContent)return;if(!Array.isArray(A.colliderUUIDs)||A.colliderUUIDs.length===0){A.colliderUUIDs=[];const G=E==="hull"?"addConvexHullCollider":"attachTrimeshCollider",N=F=>{if(!(F&&F.isMesh&&F.geometry&&F.geometry.isBufferGeometry))return;const k=new Y.Matrix4().multiplyMatrices(R,F.matrixWorld),m=new Y.Vector3,S=new Y.Quaternion,j=new Y.Vector3;k.decompose(m,S,j);const z=new Y.Vector3;F.getWorldScale(z),z.set(Math.abs(z.x),Math.abs(z.y),Math.abs(z.z)),A.physics.sim[G]({bodyId:g,geometry:F.geometry,localPosition:[m.x,m.y,m.z],localRotation:S,localScale:[z.x,z.y,z.z]}).then($=>{const _=t(),X=!A.deleted&&(_==="mesh"||_==="hull"),CA=Math.floor(A.level||0)<=e,rA=Math.floor(A.level||0)===e&&Array.isArray(A.childrenTiles)&&A.childrenTiles.length>0;X&&(A.materialVisibility?CA:CA&&rA)?($&&A.colliderUUIDs.push($),A._activeColliderShape=E):$&&A.physics.sim.detachCollider({colliderId:$})}).catch(()=>{})};for(const F of A.meshContent)F&&!F.isSplatsBatch&&(F.isMesh&&N(F),F.traverse&&F.traverse(k=>{k.isMesh&&N(k)}))}}else I===e&&C||(r(),A._activeColliderShape=void 0)}else if(r(),s){if(!A.colliderUUID){if(A.boundingVolume instanceof tg||A.boundingVolume?.isOBB){const G=A.localToWorld(A.boundingVolume.center.clone()).clone().applyMatrix4(R),N=A.localToWorld(new Y.Vector3(0,0,0)).clone().applyMatrix4(R),F=A.boundingVolume.e1.clone().multiplyScalar(A.boundingVolume.halfSize.x),k=A.boundingVolume.e2.clone().multiplyScalar(A.boundingVolume.halfSize.y),m=A.boundingVolume.e3.clone().multiplyScalar(A.boundingVolume.halfSize.z),S=A.localToWorld(F.clone()).applyMatrix4(R),j=A.localToWorld(k.clone()).applyMatrix4(R),z=A.localToWorld(m.clone()).applyMatrix4(R),$=S.clone().sub(N),_=j.clone().sub(N),X=z.clone().sub(N),CA=$.length(),rA=_.length(),oA=X.length(),wA=CA>0?$.clone().multiplyScalar(1/CA):new Y.Vector3(1,0,0),bA=rA>0?_.clone().multiplyScalar(1/rA):new Y.Vector3(0,1,0),iA=oA>0?X.clone().multiplyScalar(1/oA):new Y.Vector3(0,0,1),yA=new Y.Matrix4().makeBasis(wA,bA,iA),EA=new Y.Quaternion().setFromRotationMatrix(yA);A.colliderUUID=A.physics.sim.attachShapeCollider({bodyId:g,shape:NQ.createBox(CA,rA,oA),localPosition:[G.x,G.y,G.z],localRotation:EA}),A._activeColliderShape="bounds"}else if(A.boundingVolume instanceof Y.Sphere||A.boundingVolume?.isSphere){const G=A.localToWorld(A.boundingVolume.center.clone()).clone().applyMatrix4(R),N=A.localToWorld(new Y.Vector3(0,0,0)).clone().applyMatrix4(R),F=A.localToWorld(new Y.Vector3(1,0,0)).applyMatrix4(R).sub(N).length(),k=A.localToWorld(new Y.Vector3(0,1,0)).applyMatrix4(R).sub(N).length(),m=A.localToWorld(new Y.Vector3(0,0,1)).applyMatrix4(R).sub(N).length(),S=Math.max(F,k,m),j=A.boundingVolume.radius*S;A.colliderUUID=A.physics.sim.attachShapeCollider({bodyId:g,shape:NQ.createBall(j),localPosition:[G.x,G.y,G.z]}),A._activeColliderShape="bounds"}}}else I===e&&C||(o(),A._activeColliderShape=void 0)}_calculateUpdateMetric(A,g){let I=0;if(this.boundingVolume instanceof tg){if(Lg.copy(this.boundingVolume),Lg.applyMatrix4(this.matrixWorld),!Lg.inFrustum(g))return-1;if(this.clipShape!=null&&(this.clipShape.isSphere&&!Lg.intersectsSphere(this.clipShape)||this.clipShape.isOBB&&!Lg.intersectsOBB(this.clipShape)))return Number.MAX_VALUE;I=Math.max(0,Lg.distanceToPoint(A.position)-A.near)}else{if(!(this.boundingVolume instanceof Y.Sphere))return console.error("unsupported shape"),-1;if(yg.copy(this.boundingVolume),yg.applyMatrix4(this.matrixWorld),this.clipShape!=null&&(this.clipShape.isOBB&&!this.clipShape.intersectsSphere(yg)||this.clipShape.isSphere&&!this.clipShape.intersectsSphere(yg)))return Number.MAX_VALUE;if(!g.intersectsSphere(yg))return-1;I=Math.max(0,A.position.distanceTo(yg.center)-yg.radius-A.near)}if(I=Math.pow(I,this.distanceBias),I==0)return 0;const Q=this.matrixWorld.getMaxScaleOnAxis();this.renderer&&this.renderer.getDrawingBufferSize(this.rendererSize);let C=this.rendererSize.y,a=A.fov;return A.aspect<1&&(a*=A.aspect,C=this.rendererSize.x),16*(2*Math.tan(.5*a*.017453292519943295)*I)/(C*Q)}_getSiblings(){const A=this,g=[];if(!A.parentTile)return g;let I=A.parentTile;for(;!I.hasMeshContent&&I.parentTile;)I=I.parentTile;return I.childrenTiles.forEach(Q=>{if(Q&&Q!=A){for(;!Q.hasMeshContent&&Q.childrenTiles[0];)Q=Q.childrenTiles[0];g.push(Q)}}),g}_calculateDistanceToCamera(A){return this.boundingVolume instanceof tg?(Lg.copy(this.boundingVolume),Lg.applyMatrix4(this.matrixWorld),Math.max(0,Lg.distanceToPoint(A.position))):this.boundingVolume instanceof Y.Sphere?(yg.copy(this.boundingVolume),yg.applyMatrix4(this.matrixWorld),Math.max(0,A.position.distanceTo(yg.center)-yg.radius)):(console.error("unsupported shape"),-1)}setGeometricErrorMultiplier(A){this.geometricErrorMultiplier=A,this.childrenTiles.forEach(g=>g.setGeometricErrorMultiplier(A))}setDistanceBias(A){this.distanceBias=A,this.childrenTiles.forEach(g=>g.setDistanceBias(A))}_transformWGS84ToCartesian(A,g,I,Q){const C=6378137/Math.sqrt(1-.006694384442042*Math.pow(Math.sin(g),2)),a=Math.cos(g),e=Math.cos(A),i=Math.sin(g),t=C+I,E=t*a*e,o=t*a*Math.sin(A),r=(.993305615557957*C+I)*i;Q.set(E,o,r)}hideCopyright(){(function(){MA||((MA=document.createElement("div")).style.position="fixed",MA.style.bottom="20px",MA.style.left="20px",MA.style.color="white",MA.style.textShadow="2px 2px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000",MA.style.padding="10px",MA.style.backgroundColor="rgba(0, 0, 0, 0.1)",document.body.appendChild(MA)),MA.style.opacity=0})()}showCopyright(){(function(){MA||((MA=document.createElement("div")).style.position="fixed",MA.style.bottom="20px",MA.style.left="20px",MA.style.color="white",MA.style.textShadow="2px 2px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000",MA.style.padding="10px",MA.style.backgroundColor="rgba(0, 0, 0, 0.1)",document.body.appendChild(MA)),MA.style.opacity=1})()}}function ZC(B){var A=document.createElement("div");A.textContent=B,A.style.position="fixed",A.style.top="10px",A.style.left="50%",A.style.transform="translateX(-50%)",A.style.padding="10px",A.style.backgroundColor="#ff8800",A.style.color="#ffffff",A.style.zIndex="9999",document.body.appendChild(A),setTimeout(function(){A.remove()},8e3)}function rQ(){MA||((MA=document.createElement("div")).style.position="fixed",MA.style.bottom="20px",MA.style.left="20px",MA.style.color="white",MA.style.textShadow="2px 2px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000",MA.style.padding="10px",MA.style.backgroundColor="rgba(0, 0, 0, 0.1)",document.body.appendChild(MA));const B=Ue();let A="";B.forEach(g=>{A+=g+", "}),A=A.slice(0,-2),MA.textContent=A}const ag=new Y.Sphere(new Y.Vector3(0,0,0),1),Vg=new Y.Vector3(0,0,0),sQ=new Y.Vector3(0,0,0),eo=new Y.Vector3(0,1,0),cQ=new Y.Vector2,_C=new Y.Quaternion,$C=new Y.Matrix4;class vQ extends Y.Object3D{constructor(A){super();const g=this;if(A.queryParams&&(this.queryParams={...A.queryParams}),this.uuid=Va(),A.tileLoader?this.tileLoader=A.tileLoader:console.error("an instanced tileset must be provided an InstancedTilesetLoader"),this.master=A.master,this.loadOutsideView=A.loadOutsideView,this.cameraOnLoad=A.cameraOnLoad,this.parentTile=A.parentTile,this.distanceBias=Math.max(1e-4,A.distanceBias?A.distanceBias:1),this.childrenTiles=[],this.jsonChildren=[],this.meshContent=new Set,this.static=A.static,this.static&&(this.matrixAutoUpdate=!1,this.matrixWorldAutoUpdate=!1),this.tileContent,this.refinement,this.rootPath,this.geometricError,this.boundingVolume,this.json,this.materialVisibility=!1,this.inFrustum=!0,this.level=A.level?A.level:0,this.hasMeshContent=0,this.hasUnloadedJSONContent=0,this.centerModel=A.centerModel,this.deleted=!1,this.abortController=new AbortController,A.json)this.rootPath=A.json.rootPath?A.json.rootPath:A.rootPath,A.json.children&&(this.jsonChildren=A.json.children),g.setup(A);else if(A.url){this.loadJson=(C,a)=>{const e=iI.dirname(a);g.setup({rootPath:e,json:C,onLoadCallback:A.onLoadCallback})};var I=A.url;if(g.queryParams){var Q="";for(let C in g.queryParams)g.queryParams.hasOwnProperty(C)&&(Q+="&"+C+"="+g.queryParams[C]);I.includes("?")?I+=Q:I+="?"+Q.substring(1)}g.tileLoader.get(g.abortController,I,g.uuid,g)}}async setup(A){const g=this;A.json.root?(g.json=A.json.root,!g.json.children&&g.json.getChildren&&(g.json.children=await g.json.getChildren()),g.jsonChildren=g.json.children,g.json.refinement||(g.json.refinement=A.json.refinement),g.json.geometricError||(g.json.geometricError=A.json.geometricError),g.json.transform||(g.json.transform=A.json.transform),g.json.boundingVolume||(g.json.boundingVolume=A.json.boundingVolume)):(g.json=A.json,!g.json.children&&g.json.getChildren&&(g.json.children=await g.json.getChildren(),g.jsonChildren=g.json.children)),g.rootPath=A.json.rootPath?A.json.rootPath:A.rootPath,g.json.refinement?g.refinement=g.json.refinement:g.refinement=A.parentRefinement,g.json.geometricError?g.geometricError=g.json.geometricError:g.geometricError=A.parentGeometricError;let I=new Y.Matrix4;if(g.json.transform&&!g.centerModel&&(I.elements=g.json.transform),g.applyMatrix4(I),g.parentTile&&g.parentTile.matrix&&(g.matrix.premultiply(g.parentTile.matrix),g.matrix.decompose(g.position,g.quaternion,g.scale)),g.matrixWorldNeedsUpdate=!0,g.updateWorldMatrix(!0,!0),g.json.boundingVolume)if(g.json.boundingVolume.box)g.boundingVolume=new tg(g.json.boundingVolume.box);else if(g.json.boundingVolume.region){const C=g.json.boundingVolume.region;g.transformWGS84ToCartesian(C[0],C[1],C[4],Vg),g.transformWGS84ToCartesian(C[2],C[3],C[5],sQ),Vg.lerp(sQ,.5),g.boundingVolume=new Y.Sphere(new Y.Vector3(Vg.x,Vg.y,Vg.z),Vg.distanceTo(sQ))}else if(g.json.boundingVolume.sphere){const C=g.json.boundingVolume.sphere;g.boundingVolume=new Y.Sphere(new Y.Vector3(C[0],C[1],C[2]),C[3])}else g.boundingVolume=A.parentBoundingVolume;else g.boundingVolume=A.parentBoundingVolume;function Q(C){C.uri&&C.uri.includes("json")||C.url&&C.url.includes("json")?g.hasUnloadedJSONContent++:g.hasMeshContent++}if(g.json.content?(Q(g.json.content),g.load()):g.json.contents&&(g.json.contents.forEach(C=>Q(C)),g.load()),g.centerModel){const C=new Y.Sphere;g.boundingVolume instanceof tg?C.copy(g.boundingVolume.sphere):g.boundingVolume instanceof Y.Sphere&&C.copy(g.boundingVolume),this.json.boundingVolume.region&&(g.transformWGS84ToCartesian(.5*(g.json.boundingVolume.region[0]+g.json.boundingVolume.region[2]),.5*(g.json.boundingVolume.region[1]+g.json.boundingVolume.region[3]),.5*(g.json.boundingVolume.region[4]+g.json.boundingVolume.region[5]),Vg),_C.setFromUnitVectors(Vg.normalize(),eo.normalize()),g.master.applyQuaternion(_C),g.master.updateWorldMatrix(!1,!1)),$C.makeTranslation(-C.center.x*g.scale.x,-C.center.y*g.scale.y,-C.center.z*g.scale.z),g.master.matrix.multiply($C),g.master.matrix.decompose(g.master.position,g.master.quaternion,g.master.scale)}g.isSetup=!0,A.onLoadCallback&&A.onLoadCallback(g)}isAbsolutePathOrURL(A){const g=/^(?:http|https|ftp|tcp|udp):\/\/\S+/.test(A),I=A.startsWith("/")&&!A.startsWith("//");return g||I}assembleURL(A,g){A.endsWith("/")||(A+="/");const I=new URL(A);let Q=I.pathname.split("/").filter(a=>a!==""),C=g.split("/").filter(a=>a!=="");for(let a=1;a<=Q.length&&!(a>=C.length);a++)if(Q.slice(Q.length-a,Q.length).join("/")===C.slice(0,a).join("/")){for(let e=0;e<a;e++)Q.pop();break}for(;C.length>0&&C[0]==="..";)Q.pop(),C.shift();return`${I.protocol}//${I.host}/${[...Q,...C].join("/")}`}extractQueryParams(A,g){const I=new URL(A);for(let[Q,C]of I.searchParams)g[Q]=C;return I.search="",I.toString()}load(){var A=this;function g(I){let Q;I.uri?Q=I.uri:I.url&&(Q=I.url);const C=/^(?:http|https|ftp|tcp|udp):\/\/\S+/;if(C.test(A.rootPath)?C.test(Q)||(Q=A.assembleURL(A.rootPath,Q)):iI.isAbsolute(A.rootPath)&&(Q=A.rootPath+iI.sep+Q),Q=A.extractQueryParams(Q,A.queryParams),A.queryParams){var a="";for(let e in A.queryParams)A.queryParams.hasOwnProperty(e)&&(a+="&"+e+"="+A.queryParams[e]);Q.includes("?")?Q+=a:Q+="?"+a.substring(1)}Q&&(Q.includes(".b3dm")||Q.includes(".glb")||Q.includes(".gltf")?(A.contentURL=Q,A.tileLoader.get(A.abortController,Q,A.uuid,A,A.cameraOnLoad?()=>A.calculateDistanceToCamera(A.cameraOnLoad):()=>0,()=>A.getSiblings(),A.level,!A.json.boundingVolume.region,!!A.json.boundingVolume.region,A.geometricError)):Q.includes(".json")&&A.tileLoader.get(A.abortController,Q,A.uuid,A))}A.deleted||(A.json.content?g(A.json.content):A.json.contents&&A.json.contents.forEach(I=>g(I)))}loadMesh(A){this.deleted||this.meshContent.add(A)}loadJson(A,g){this.deleted||(this.json.children&&(this.jsonChildren=this.json.children),A.rootPath=iI.dirname(g),this.jsonChildren.push(A),this.hasUnloadedJSONContent--)}dispose(){const A=this;A.childrenTiles.forEach(g=>g.dispose()),A.deleted=!0,A.abortController&&A.abortController.abort(),this.parent=null,this.parentTile=null,this.dispatchEvent({type:"removed"})}disposeChildren(){this.childrenTiles.forEach(A=>A.dispose()),this.childrenTiles=[]}_update(A,g){const I=this;function Q(C){if(I.hasMeshContent&&!(I.meshContent.size<I.hasMeshContent)){if(C<0)return I.inFrustum=!1,void I.changeContentVisibility(!!I.loadOutsideView);if(I.inFrustum=!0,I.childrenTiles.length!=0){if(C>=I.master.geometricErrorMultiplier*I.geometricError)I.changeContentVisibility(!0);else if(C<I.master.geometricErrorMultiplier*I.geometricError){let a=!0;I.childrenTiles.every(e=>!!e.isReady()||(a=!1,!1)),a&&I.changeContentVisibility(!1)}}else I.changeContentVisibility(!0)}}I.isSetup&&(I.materialVisibility,I.boundingVolume&&I.geometricError&&(I.metric=I.calculateUpdateMetric(A,g)),I.childrenTiles.forEach(C=>C._update(A,g)),Q(I.metric),function(C){C<0&&I.hasMeshContent||(!I.hasMeshContent&&I.rootPath||C<I.master.geometricErrorMultiplier*I.geometricError&&I.meshContent.size>0)&&I.json&&I.jsonChildren&&I.childrenTiles.length!=I.jsonChildren.length&&I.jsonChildren.forEach(a=>{if(!(a.root||a.children||a.getChildren||a.content||a.contents))return;let e=new vQ({parentTile:I,queryParams:I.queryParams,parentGeometricError:I.geometricError,parentBoundingVolume:I.boundingVolume,parentRefinement:I.refinement,json:a,rootPath:I.rootPath,loadOutsideView:I.loadOutsideView,level:I.level+1,tileLoader:I.tileLoader,cameraOnLoad:A,master:I.master,centerModel:!1});I.childrenTiles.push(e)})}(I.metric),function(C){if(I.hasMeshContent){if(!I.inFrustum)return I.disposeChildren(),void Q(C);C>=I.master.geometricErrorMultiplier*I.geometricError&&(I.disposeChildren(),Q(C))}}(I.metric))}areAllChildrenLoadedAndHidden(){let A=!0;return this.childrenTiles.every(g=>{if(g.hasMeshContent){if(g.childrenTiles.length>0)return A=!1,!1;if(!g.inFrustum)return!0;if(!g.materialVisibility||g.meshesToDisplay!=g.meshesDisplayed)return A=!1,!1}else if(!g.areAllChildrenLoadedAndHidden())return A=!1,!1;return!0}),A}isReady(){if(!this.inFrustum)return!0;if(this.hasUnloadedJSONContent)return!1;if(!this.hasMeshContent||this.meshContent.size==0||!this.materialVisibility){if(this.childrenTiles.length>0){var A=!0;return this.childrenTiles.every(g=>!!g.isReady()||(A=!1,!1)),A}return!1}return!this.hasMeshContent||!(this.meshContent.size<this.hasMeshContent)&&!!this.materialVisibility}changeContentVisibility(A){this.materialVisibility=A}calculateUpdateMetric(A,g){if(this.boundingVolume instanceof tg){if(ag.copy(this.boundingVolume.sphere),ag.applyMatrix4(this.matrixWorld),!g.intersectsSphere(ag))return-1}else{if(!(this.boundingVolume instanceof Y.Sphere))return console.error("unsupported shape"),-1;if(ag.copy(this.boundingVolume),ag.applyMatrix4(this.matrixWorld),!g.intersectsSphere(ag))return-1}let I=Math.max(0,A.position.distanceTo(ag.center)-ag.radius);if(I=Math.pow(I,this.distanceBias),I==0)return 0;const Q=this.matrixWorld.getMaxScaleOnAxis();this.master._renderSize(cQ);let C=cQ.y,a=A.fov;A.aspect<1&&(a*=A.aspect,C=cQ.x);let e=2*Math.tan(.5*a*.017453292519943295)*I;return 16*window.devicePixelRatio*e/(C*Q)}getSiblings(){const A=this,g=[];if(!A.parentTile)return g;let I=A.parentTile;for(;!I.hasMeshContent&&I.parentTile;)I=I.parentTile;return I.childrenTiles.forEach(Q=>{if(Q&&Q!=A){for(;!Q.hasMeshContent&&Q.childrenTiles[0];)Q=Q.childrenTiles[0];g.push(Q)}}),g}calculateDistanceToCamera(A){return this.boundingVolume instanceof tg?(ag.copy(this.boundingVolume.sphere),ag.applyMatrix4(this.matrixWorld)):this.boundingVolume instanceof Y.Sphere?(ag.copy(this.boundingVolume),ag.applyMatrix4(this.matrixWorld)):console.error("unsupported shape"),Math.max(0,A.position.distanceTo(ag.center)-ag.radius)}getWorldMatrix(){return this.matrixWorld}transformWGS84ToCartesian(A,g,I,Q){const C=6378137/Math.sqrt(1-.006694384442042*Math.pow(Math.sin(g),2)),a=Math.cos(g),e=Math.cos(A),i=Math.sin(g),t=C+I,E=t*a*e,o=t*a*Math.sin(A),r=(.993305615557957*C+I)*i;Q.set(E,o,r)}}class Eo extends Y.Object3D{constructor(A){super(),A.master=this,A.domWidth&&A.domHeight?this.rendererSize=new Y.Vector2(A.domWidth,A.domHeight):this.rendererSize=new Y.Vector2(1e3,1e3),this.renderer=A.renderer,this.distanceBias=Math.max(1e-4,A.distanceBias?A.distanceBias:1),this.geometricErrorMultiplier=A.geometricErrorMultiplier?A.geometricErrorMultiplier:1,this.tileset=new vQ(A),A.static&&(this.matrixAutoUpdate=!1),this.tileLoader=A.tileLoader}_renderSize(A){this.renderer?this.renderer.getDrawingBufferSize(A):A.copy(this.rendererSize)}setCanvasSize(A,g){this.rendererSize.set(A,g)}update(A,g){if(g)this.tileset._update(A,g);else{const I=new Y.Frustum;I.setFromProjectionMatrix(new Y.Matrix4().multiplyMatrices(A.projectionMatrix,A.matrixWorldInverse)),this.tileset._update(A,I)}}setGeometricErrorMultiplier(A){this.geometricErrorMultiplier=A||1}}class io{constructor(A){const g=this;g.scene=A,g.instancedTiles=[],g.instancedMesh,g.reuseableMatrix=new Y.Matrix4}addInstance(A){const g=this;A.added=!0,A.listOMesh=g.instancedTiles,g.instancedTiles.push(A),g.instancedMesh&&A.loadMesh(g.instancedMesh)}addToScene(){const A=this;A.instancedMesh.setMatrixAt(0,new Y.Matrix4),A.instancedMesh.instanceMatrix.needsUpdate=!0,A.instancedMesh.count=1,A.scene.add(A.instancedMesh),A.instancedMesh.onAfterRender=()=>{delete A.instancedMesh.onAfterRender,A.instancedMesh.displayedOnce=!0}}setObject(A){const g=this;g.instancedMesh=A,g.instancedMesh.matrixAutoUpdate=!1,g.instancedMesh.matrixWorldAutoUpdate=!1,g.scene.children.includes(A)||this.addToScene();for(let I=0;I<g.instancedTiles.length;I++)g.instancedTiles[I].loadMesh(g.instancedMesh)}update(){const A=this;for(let g=A.instancedTiles.length-1;g>=0;g--)A.instancedTiles[g].deleted&&A.instancedTiles.splice(g,1);if(A.instancedMesh){A.instancedMesh.count=0,A.instancedMesh.instancedTiles=[];for(let g=0;g<A.instancedTiles.length;g++)A.instancedTiles[g].meshContent.add(A.instancedMesh),A.instancedTiles[g].materialVisibility&&(A.instancedMesh.count++,A.reuseableMatrix.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),A.reuseableMatrix.multiply(A.instancedTiles[g].matrixWorld),A.reuseableMatrix.multiply(A.instancedMesh.baseMatrix),A.instancedMesh.setMatrixAt(A.instancedMesh.count-1,A.reuseableMatrix),A.instancedMesh.instancedTiles.push(A.instancedTiles[g]));A.instancedMesh.instanceMatrix.needsUpdate=!0,A.instancedMesh.needsUpdate=!0,A.instancedMesh.computeBoundingSphere()}}getCount(){return this.instancedTiles.length}dispose(){const A=this;return!(A.instancedTiles.length>0)&&!!A.instancedMesh&&(A.scene.remove(A.instancedMesh),A.instancedMesh.traverse(g=>{if(g.dispose&&g.dispose(),g.material)if(g.material.length)for(let I=0;I<g.material.length;++I)g.material[I].dispose();else g.material.dispose();g.geometry&&g.geometry.dispose()}),A.instancedMesh.dispose(),!0)}}class to{constructor(){const A=this;A.count=0,A.json,A.instancedTiles=[]}addInstance(A){this.instancedTiles.push(A),this.json&&A.loadJson(this.json,this.url)}setObject(A,g){const I=this;I.json=A,I.url=g;for(let Q=0;Q<I.instancedTiles.length;Q++)I.instancedTiles[Q].loadJson(I.json,I.url)}getCount(){return this.instancedTiles.length}update(){const A=this;for(let g=A.instancedTiles.length-1;g>=0;g--)A.instancedTiles[g].deleted&&A.instancedTiles.splice(g,1)}dispose(){return!(!this.json||this.instancedTiles.length!=0)}}let CI=0;async function oo(B){return new Promise(A=>{const g=setInterval(()=>{B.hasDracoLoader&&!B.dracoLoader||B.hasKTX2Loader&&!B.ktx2Loader||(clearInterval(g),A())},10)})}function no(B){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/physicsRapier.worker-jgQ9dgLt.js").href:new URL("assets/physicsRapier.worker-jgQ9dgLt.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{type:"module",name:B?.name})}function ro(B){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/physicsHelper.worker-Cr8S3sZk.js").href:new URL("assets/physicsHelper.worker-Cr8S3sZk.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{type:"module",name:B?.name})}function Eg(B,A=[0,-9.81,0]){return B?Array.isArray(B)&&B.length===3?[Number(B[0]),Number(B[1]),Number(B[2])]:B.isVector3?[B.x,B.y,B.z]:typeof B=="object"&&"x"in B&&"y"in B&&"z"in B?[Number(B.x),Number(B.y),Number(B.z)]:A.slice():A.slice()}function OI(B,A=[0,0,0,1]){if(!B)return A.slice();if(Array.isArray(B)&&B.length===4)return[Number(B[0]),Number(B[1]),Number(B[2]),Number(B[3])];if(B.isQuaternion)return[B.x,B.y,B.z,B.w];if(B.isEuler){const g=new Y.Quaternion().setFromEuler(B);return[g.x,g.y,g.z,g.w]}return A.slice()}function Aa(B){if(Array.isArray(B)||B&&B.isVector3)return{mode:"vector",vector:Eg(B)};const A=B||{};return(A.mode||"vector").toLowerCase()==="geocentric"?{mode:"geocentric",planetCenter:Eg(A.planetCenter||[0,0,0],[0,0,0]),intensity:typeof A.intensity=="number"?A.intensity:9.81}:{mode:"vector",vector:Eg(A.vector||A,[0,-9.81,0])}}function hB(){return typeof performance<"u"&&performance.now?performance.now():Date.now()}exports.ColliderShape=NQ,exports.InstancedOGC3DTile=Eo,exports.InstancedTileLoader=class{constructor(B,A){if(this.zUpToYUpMatrix=new Y.Matrix4,this.zUpToYUpMatrix.set(1,0,0,0,0,0,-1,0,0,1,0,0,0,0,0,1),this.maxCachedItems=100,this.maxInstances=1,this.proxy=A.proxy,A&&(this.meshCallback=A.meshCallback,this.pointsCallback=A.pointsCallback,A.maxCachedItems&&(this.maxCachedItems=A.maxCachedItems),A.maxInstances&&(this.maxInstances=A.maxInstances)),this.gltfLoader=new Ca,A&&A.dracoLoader)this.gltfLoader.setDRACOLoader(A.dracoLoader),this.hasDracoLoader=!0;else{const g=new Ea;g.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.4.3/"),this.gltfLoader.setDRACOLoader(g),this.gltfLoader.hasDracoLoader=!0}if(A&&A.ktx2Loader)this.gltfLoader.setKTX2Loader(A.ktx2Loader),this.hasKTX2Loader=!0;else if(A&&A.renderer){const g=new Dg;g.setTranscoderPath("https://storage.googleapis.com/ogc-3d-tiles/basis/").detectSupport(A.renderer),this.gltfLoader.setKTX2Loader(g),this.gltfLoader.hasKTX2Loader=!0}this.gltfLoader.setMeshoptDecoder(Wa),this.hasMeshOptDecoder=!0,this.b3dmDecoder=new Ba(this.gltfLoader),this.cache=new ga,this.scene=B,this.ready=[],this.downloads=[],this.nextReady=[],this.nextDownloads=[]}update(){const B=this;B._checkSize(),B.cache._data.forEach(A=>{A.update()}),CI<8&&B._download(),B._loadBatch()}_download(){const B=this;if(B.nextDownloads.length!=0||(B._getNextDownloads(),B.nextDownloads.length!=0))for(;B.nextDownloads.length>0;){const g=B.nextDownloads.shift();if(g){if(g.path.includes(".b3dm")&&(A=B.proxy?()=>fetch(B.proxy,{method:"POST",body:g.path}):()=>fetch(g.path),CI++,A().then(I=>{if(!I.ok)throw console.error("could not load tile with path : "+g.path),new Error(`couldn't load "${g.path}". Request failed with status ${I.status} : ${I.statusText}`);return I.arrayBuffer()}).then(I=>this.b3dmDecoder.parseB3DMInstanced(I,Q=>{B.meshCallback(Q,g.geometricError)},B.maxInstances,g.sceneZupToYup,g.meshZupToYup)).then(I=>{I.frustumCulled=!1,g.tile.setObject(I),B.ready.unshift(g)}).catch(I=>console.error(I)).finally(()=>{CI--})),g.path.includes(".glb")||g.path.includes(".gltf"))A=B.proxy?()=>fetch(B.proxy,{method:"POST",body:g.path}):()=>fetch(g.path),CI++,A().then(I=>{if(!I.ok)throw new Error("missing content");return I.arrayBuffer()}).then(async I=>{await oo(this.gltfLoader),this.gltfLoader.parse(I,null,Q=>{let C;Q.scene.asset=Q.asset,g.sceneZupToYup&&Q.scene.applyMatrix4(this.zUpToYUpMatrix),Q.scene.traverse(a=>{a.geometricError=g.geometricError,a.isMesh&&(g.meshZupToYup&&a.applyMatrix4(this.zUpToYUpMatrix),B.meshCallback&&B.meshCallback(a,a.geometricError)),a.isPoints&&console.error("instanced point cloud is not supported")}),Q.scene.updateWorldMatrix(!1,!0),Q.scene.traverse(a=>{a.isMesh&&(C=new Y.InstancedMesh(a.geometry,a.material,B.maxInstances),C.baseMatrix=a.matrixWorld)}),B.ready.unshift(g),C?(C.frustumCulled=!1,g.tile.setObject(C)):Q.scene.traverse(a=>{a.dispose&&a.dispose(),a.material&&a.material.dispose()})})},I=>{console.error("could not load tile : "+g.path)}).finally(()=>{CI--});else if(g.path.includes(".json")){var A;A=B.proxy?()=>fetch(B.proxy,{method:"POST",body:g.path}):()=>fetch(g.path),CI++,A().then(I=>{if(!I.ok)throw console.error("could not load tile with path : "+g.path),new Error(`couldn't load "${g.path}". Request failed with status ${I.status} : ${I.statusText}`);return I.json()}).then(I=>mQ(I,g.path)).then(I=>{g.tile.setObject(I,g.path),B.ready.unshift(g)}).catch(I=>console.error(I)).finally(()=>{CI--})}}}}_loadBatch(){return this.nextReady.length==0&&(this._getNextReady(),this.nextReady.length==0)?0:this.nextReady.shift()?1:0}_getNextReady(){let B=Number.MAX_VALUE,A=-1;for(let g=this.ready.length-1;g>=0;g--)this.ready[g].distanceFunction||this.nextReady.push(this.ready.splice(g,1)[0]);if(!(this.nextReady.length>0)){for(let g=this.ready.length-1;g>=0;g--){const I=this.ready[g].distanceFunction()*this.ready[g].level;I<B&&(B=I,A=g)}if(A>=0){const g=this.ready.splice(A,1).pop();this.nextReady.push(g);const I=g.getSiblings();for(let Q=this.ready.length-1;Q>=0;Q--)I.includes(this.ready[Q].uuid)&&this.nextready.push(this.ready.splice(Q,1).pop())}}}get(B,A,g,I,Q,C,a,e,i,t){const E=this,o=function(n){for(var s=n.split("/"),c=[],D=0,d=0;d<s.length;d++){var h=s[d];h!=="."&&h!==""&&h!==".."?c[D++]=h:h===".."&&D>0&&D--}if(D===0)return"/";var l="";for(d=0;d<D;d++)l+="/"+c[d];return l}(A);if(!(A.includes(".b3dm")||A.includes(".json")||A.includes(".glb")||A.includes(".gltf")))return void console.error("the 3DTiles cache can only be used to load B3DM, gltf and json data");const r=E.cache.get(o);if(r)r.addInstance(I);else if(A.includes(".b3dm")||A.includes(".glb")||A.includes(".gltf")){const n=new io(E.scene);n.addInstance(I),E.cache.put(o,n);const s=new AbortController;B.signal.addEventListener("abort",()=>{n.getCount()==0&&s.abort()}),this.downloads.push({abortController:s,tile:n,key:o,path:A,distanceFunction:Q,getSiblings:C,level:a,uuid:g,sceneZupToYup:e,meshZupToYup:i,geometricError:t,shouldDoDownload:()=>!0})}else if(A.includes(".json")){const n=new to;n.addInstance(I),E.cache.put(o,n);const s=new AbortController;B.signal.addEventListener("abort",()=>{n.getCount()==0&&s.abort()}),this.downloads.push({abortController:s,tile:n,key:o,path:A,distanceFunction:Q,getSiblings:C,level:a,shouldDoDownload:()=>!0})}}_getNextDownloads(){let B=Number.MAX_VALUE,A=-1;for(let g=this.downloads.length-1;g>=0;g--){const I=this.downloads[g];I.shouldDoDownload()?I.distanceFunction||this.nextDownloads.push(this.downloads.splice(g,1)[0]):this.downloads.splice(g,1)}if(!(this.nextDownloads.length>0)){for(let g=this.downloads.length-1;g>=0;g--){const I=this.downloads[g],Q=I.distanceFunction()*I.level;Q<B&&(B=Q,A=g)}if(A>=0){const g=this.downloads.splice(A,1).pop();this.nextDownloads.push(g);const I=g.getSiblings();for(let Q=this.downloads.length-1;Q>=0;Q--)I.includes(this.downloads[Q].uuid)&&this.nextDownloads.push(this.downloads.splice(Q,1).pop())}}}_checkSize(){const B=this;let A=0;for(;B.cache.size()>B.maxCachedItems&&A<B.cache.size();){A++;const g=B.cache.head();B.cache.remove(g.key),g.value.dispose()||B.cache.put(g.key,g.value)}}},exports.OBB=tg,exports.OGC3DTile=jQ,exports.OcclusionCullingService=class{constructor(){this.cullMap=[],this.cullMaterial=new Y.MeshBasicMaterial({vertexColors:!0}),this.cullMaterial.side=Y.FrontSide,this.cullTarget=this._createCullTarget(),this.cullPixels=new Uint8Array(4*this.cullTarget.width*this.cullTarget.height)}setSide(B){this.cullMaterial.side=B}_createCullTarget(){const B=new Y.WebGLRenderTarget(Math.floor(.05*window.innerWidth),Math.floor(.05*window.innerHeight));return B.texture.format=Y.RGBAFormat,B.texture.colorSpace=Y.LinearSRGBColorSpace,B.texture.minFilter=Y.NearestFilter,B.texture.magFilter=Y.NearestFilter,B.texture.generateMipmaps=!1,B.stencilBuffer=!1,B.depthBuffer=!0,B.depthTexture=new Y.DepthTexture,B.depthTexture.format=Y.DepthFormat,B.depthTexture.type=Y.UnsignedShortType,B}update(B,A,g){let I=A.getRenderTarget(),Q=B.overrideMaterial;B.overrideMaterial=this.cullMaterial,A.setRenderTarget(this.cullTarget),A.render(B,g),B.overrideMaterial=Q,A.setRenderTarget(I),A.readRenderTargetPixels(this.cullTarget,0,0,this.cullTarget.width,this.cullTarget.height,this.cullPixels),this.cullMap=[];for(let C=0;C<this.cullPixels.length;C+=4){const a=Y.MathUtils.clamp(this.cullPixels[C],0,255)<<16^Y.MathUtils.clamp(this.cullPixels[C+1],0,255)<<8^Y.MathUtils.clamp(this.cullPixels[C+2],0,255);this.cullMap[a]=!0}}hasID(B){return this.cullMap[B]}},exports.Physics=class{constructor(B={}){this.updateIntervalMs=typeof B.updateIntervalMs=="number"?B.updateIntervalMs:16,this.fixedDt=typeof B.fixedDt=="number"?B.fixedDt:this.updateIntervalMs/1e3,this.gravity=Aa(B.gravity),this.autoStart=B.autoStart!==!1,this.sharedMemorySupported=typeof SharedArrayBuffer<"u"&&!(!globalThis||!globalThis.crossOriginIsolated),this.worker=new no({}),this._msgId=0,this._pending=new Map,this._onWorkerMessage=this._onWorkerMessage.bind(this),this.worker.onmessage=this._onWorkerMessage,this.worker.onerror=A=>{console.error("Physics worker error:",A?.message||A)},this.helperWorker=null,this._helperMsgId=0,this._helperPending=new Map,this._onHelperMessage=this._onHelperMessage?this._onHelperMessage.bind(this):A=>{},this._paused=!1,this._lastTickTime=hB(),this._lastState=null,this._currentState=null,this._interpolationMax=1.25,this._nextBodyId=1,this._nextColliderId=1,this.rigidBodies=new Map,this.bodyToColliders=new Map,this.colliderToBody=new Map,this._listeners=new Map,this._initPromise=this._post({type:"init",gravity:this.gravity,sharedMemorySupported:this.sharedMemorySupported,fixedDt:this.fixedDt}),this.autoStart&&this._initPromise.then(()=>{this._scheduleNextTick()}).catch(A=>{console.error("Physics init failed:",A)})}addObject(B={}){const A="rb-"+this._nextBodyId++,g=(B.type||"dynamic").toLowerCase(),I=typeof B.mass=="number"?B.mass:1,Q=Eg(B.position,[0,0,0]),C=OI(B.rotation,[0,0,0,1]),a=B.velocity?Eg(B.velocity,[0,0,0]):void 0,e=B.angularVelocity?Eg(B.angularVelocity,[0,0,0]):void 0;return this.rigidBodies.set(A,{id:A,object:B.object||null,type:g,mass:I,last:{p:Q,q:C},current:{p:Q.slice(),q:C.slice()}}),this.bodyToColliders.set(A,new Set),this._post({type:"addObject",id:A,body:{type:g,mass:I,p:Q,q:C,v:a,w:e}}),A}attachTrimeshCollider({bodyId:B,geometry:A,positions:g,indices:I,localPosition:Q,localRotation:C,localScale:a}){if(!this.rigidBodies.has(B))return console.warn(`attachTrimeshCollider: unknown bodyId ${B}`),Promise.resolve(null);let e=null,i=null;if(A&&A.isBufferGeometry){const D=A.getAttribute("position");if(D)if(D.isInterleavedBufferAttribute){const h=D.count;e=new Float32Array(3*h);for(let l=0;l<h;l++)e[3*l+0]=D.getX(l),e[3*l+1]=D.getY(l),e[3*l+2]=D.getZ(l)}else D.array&&(e=new Float32Array(D.array));else console.warn("attachTrimeshCollider: geometry has no position attribute");const d=A.getIndex?.();if(d&&d.array){const h=d.array;i=new Uint32Array(h)}}else g&&(e=Array.isArray(g)||g instanceof Float32Array?new Float32Array(g):new Float32Array(g.buffer||g)),I&&(i=Array.isArray(I)||I instanceof Uint32Array?new Uint32Array(I):new Uint32Array(I.buffer||I));if(!(e instanceof Float32Array))return console.warn("attachTrimeshCollider: missing or invalid positions buffer"),Promise.resolve(null);const t=Q?Eg(Q,[0,0,0]):[0,0,0],E=C?OI(C,[0,0,0,1]):[0,0,0,1],o=Array.isArray(a)&&a.length===3?[Number(a[0]),Number(a[1]),Number(a[2])]:[1,1,1],r="col-"+this._nextColliderId++,n=this.bodyToColliders.get(B)||new Set;n.add(r),this.bodyToColliders.set(B,n),this.colliderToBody.set(r,B);const s={type:"attachTrimeshCollider",id:r,bodyId:B,positions:e,indices:i||null,local:{p:t,q:E,s:o}},c=[];return e?.buffer&&c.push(e.buffer),i?.buffer&&c.push(i.buffer),this._post(s,c).then(()=>r)}addConvexHullCollider({bodyId:B,geometry:A,positions:g,indices:I,localPosition:Q,localRotation:C,localScale:a}){if(!this.rigidBodies.has(B))return console.warn(`addConvexHullCollider: unknown bodyId ${B}`),Promise.resolve(null);let e=null,i=null;if(A&&A.isBufferGeometry){const D=A.getAttribute("position");if(D)if(D.isInterleavedBufferAttribute){const h=D.count;e=new Float32Array(3*h);for(let l=0;l<h;l++)e[3*l+0]=D.getX(l),e[3*l+1]=D.getY(l),e[3*l+2]=D.getZ(l)}else D.array&&(e=new Float32Array(D.array));else console.warn("addConvexHullCollider: geometry has no position attribute");const d=A.getIndex?.();if(d&&d.array){const h=d.array;i=new Uint32Array(h)}}else g&&(e=Array.isArray(g)||g instanceof Float32Array?new Float32Array(g):new Float32Array(g.buffer||g)),I&&(i=Array.isArray(I)||I instanceof Uint32Array?new Uint32Array(I):new Uint32Array(I.buffer||I));if(!(e instanceof Float32Array))return console.warn("addConvexHullCollider: missing or invalid positions buffer"),Promise.resolve(null);const t=Q?Eg(Q,[0,0,0]):[0,0,0],E=C?OI(C,[0,0,0,1]):[0,0,0,1],o=Array.isArray(a)&&a.length===3?[Number(a[0]),Number(a[1]),Number(a[2])]:[1,1,1],r="col-"+this._nextColliderId++,n=this.bodyToColliders.get(B)||new Set;n.add(r),this.bodyToColliders.set(B,n),this.colliderToBody.set(r,B);const s={type:"computeConvexHull",positions:e,indices:i||null,localScale:o},c=[];return e?.buffer&&c.push(e.buffer),i?.buffer&&c.push(i.buffer),this._helperPost(s,c).then(D=>{const d=D?.vertices;if(!(d instanceof Float32Array)||d.length<9)throw new Error("convex hull computation failed or returned insufficient vertices");const h={type:"attachShapeCollider",id:r,bodyId:B,shape:{kind:"convexHull",params:{vertices:d}},local:{p:t,q:E}},l=[];return d?.buffer&&l.push(d.buffer),this._post(h,l).then(()=>r)}).catch(D=>{const d=this.bodyToColliders.get(B);return d&&d.delete(r),this.colliderToBody.delete(r),console.warn("addConvexHullCollider failed:",D),null})}attachShapeCollider({bodyId:B,shape:A,localPosition:g,localRotation:I}){if(!this.rigidBodies.has(B))return console.warn(`attachShapeCollider: unknown bodyId ${B}`),Promise.resolve(null);if(!A||typeof A!="object")return console.warn("attachShapeCollider: missing or invalid shape descriptor"),Promise.resolve(null);const Q=g?Eg(g,[0,0,0]):[0,0,0],C=I?OI(I,[0,0,0,1]):[0,0,0,1],a="col-"+this._nextColliderId++,e=this.bodyToColliders.get(B)||new Set;e.add(a),this.bodyToColliders.set(B,e),this.colliderToBody.set(a,B);const i={type:"attachShapeCollider",id:a,bodyId:B,shape:A,local:{p:Q,q:C}};return this._post(i),a}detachCollider({colliderId:B}){const A=this.colliderToBody.get(B);if(!A)return;const g=this.bodyToColliders.get(A);g&&g.delete(B),this.colliderToBody.delete(B),this._post({type:"detachCollider",colliderId:B})}removeObject({bodyId:B}){if(!this.rigidBodies.has(B))return;const A=this.bodyToColliders.get(B);if(A)for(const g of A)this.colliderToBody.delete(g);this.bodyToColliders.delete(B),this.rigidBodies.delete(B),this._post({type:"removeObject",id:B})}applyForce({bodyId:B,force:A,worldPoint:g,wake:I=!0,impulse:Q=!1}){if(!this.rigidBodies.has(B))return void console.warn(`applyForce: unknown bodyId ${B}`);const C=Eg(A,[0,0,0]),a=g?Eg(g,[0,0,0]):void 0;this._post({type:"applyForce",id:B,force:C,point:a,wake:!!I,impulse:!!Q})}setGravity(B){this.gravity=Aa(B),this._post({type:"setGravity",gravity:this.gravity})}setPose({bodyId:B,position:A,rotation:g,wake:I=!0}){if(!this.rigidBodies.has(B))return void console.warn(`setPose: unknown bodyId ${B}`);const Q=A!=null?Eg(A,[0,0,0]):null,C=g!=null?OI(g,[0,0,0,1]):null;this._post({type:"setPose",id:B,p:Q,q:C,wake:!!I});const a=this.rigidBodies.get(B);a&&(Q&&(a.last.p=Q.slice(),a.current.p=Q.slice(),a.object?.isObject3D&&a.object.position.set(Q[0],Q[1],Q[2])),C&&(a.last.q=C.slice(),a.current.q=C.slice(),a.object?.isObject3D&&a.object.quaternion.set(C[0],C[1],C[2],C[3])),a.object?.isObject3D&&(a.object.updateMatrices?a.object.updateMatrices():(a.object.matrixAutoUpdate!==!1&&a.object.updateMatrix(),a.object.matrixWorldAutoUpdate!==!1&&a.object.updateMatrixWorld(!0))))}raycast({origin:B,direction:A,maxToi:g=1e6,filter:I}){const Q=Eg(B,[0,0,0]),C=Eg(A,[0,-1,0]);return this._post({type:"raycast",origin:Q,direction:C,maxToi:g,filter:I||null})}pause(){this._paused=!0}resume(){this._paused&&(this._paused=!1,this._lastTickTime=hB(),this._scheduleNextTick())}setUpdateInterval(B){this.updateIntervalMs=Math.max(1,Number(B)||16)}stepOnce(B){const A=typeof B=="number"?B:this.fixedDt;return this._post({type:"step",dt:A})}update(){if(!this._currentState)return;const B=this._lastState||this._currentState,A=this._currentState,g=hB(),I=B.timeMs||g,Q=A.timeMs||g,C=Math.max(.001,Q-I);let a=Y.MathUtils.clamp((g-Q)/C+1,0,this._interpolationMax);a=Y.MathUtils.clamp(a,0,1);const e=new Y.Quaternion,i=new Y.Quaternion,t=new Y.Quaternion;for(const[E,o]of this.rigidBodies.entries()){const r=B.bodies?.[E],n=A.bodies?.[E];if(!n&&!r)continue;const s=r?.p||o.current.p,c=r?.q||o.current.q,D=n?.p||o.current.p,d=n?.q||o.current.q,h=Y.MathUtils.lerp(s[0],D[0],a),l=Y.MathUtils.lerp(s[1],D[1],a),f=Y.MathUtils.lerp(s[2],D[2],a);e.set(c[0],c[1],c[2],c[3]),i.set(d[0],d[1],d[2],d[3]),t.copy(e).slerp(i,a),o.object&&o.object.isObject3D&&(o.object.position.set(h,l,f),o.object.quaternion.copy(t),o.object.updateMatrices?o.object.updateMatrices():(o.object.matrixAutoUpdate!==!1&&o.object.updateMatrix(),o.object.matrixWorldAutoUpdate!==!1&&o.object.updateMatrixWorld(!0))),o.last={p:s.slice(),q:c.slice()},o.current={p:D.slice(),q:d.slice()}}}dispose(){try{this.worker.terminate()}catch{}try{this.helperWorker?.terminate()}catch{}this.rigidBodies.clear(),this.bodyToColliders.clear(),this.colliderToBody.clear(),this._pending.clear(),this._listeners.clear(),this._lastState=null,this._currentState=null}_scheduleNextTick(){this._paused||setTimeout(()=>this._onTick(),this.updateIntervalMs)}_onTick(){if(this._paused)return;const B=hB();Math.max(1e-6,(B-this._lastTickTime)/1e3),this._lastTickTime=B,this._post({type:"step",dt:this.fixedDt}),this.update(),this._scheduleNextTick()}_onWorkerMessage(B){const A=B.data||{};if(A.replyTo){const g=this._pending.get(A.replyTo);g&&(this._pending.delete(A.replyTo),A.error?g.rej?g.rej(A.error):console.error("Physics worker error:",A.error):g.res&&g.res(A.result))}else switch(A.type){case"state":this._lastState=this._currentState,this._currentState=A.state||null,this._emit("state",this._currentState);break;case"event":this._emit("event",A.event)}}_ensureHelperWorker(){this.helperWorker||(this.helperWorker=new ro({}),this.helperWorker.onmessage=this._onHelperMessage,this.helperWorker.onerror=B=>{console.error("Physics helper worker error:",B?.message||B)})}_onHelperMessage(B){const A=B.data||{};if(A.replyTo){const g=this._helperPending.get(A.replyTo);g&&(this._helperPending.delete(A.replyTo),A.error?g.rej?g.rej(A.error):console.error("Physics helper worker error:",A.error):g.res&&g.res(A.result))}}_helperPost(B,A=[]){this._ensureHelperWorker();const g=++this._helperMsgId,I={...B,_envId:g};return this.helperWorker.postMessage(I,A),new Promise((Q,C)=>{this._helperPending.set(g,{res:Q,rej:C})})}_post(B,A=[]){const g=++this._msgId,I={...B,_envId:g};return this.worker.postMessage(I,A),new Promise((Q,C)=>{this._pending.set(g,{res:Q,rej:C})})}on(B,A){return this._listeners.has(B)||this._listeners.set(B,new Set),this._listeners.get(B).add(A),()=>this.off(B,A)}off(B,A){const g=this._listeners.get(B);g&&g.delete(A)}_emit(B,A){const g=this._listeners.get(B);if(g)for(const I of g)try{I(A)}catch(Q){console.error(Q)}}},exports.SplatsMesh=Ne,exports.TileLoader=Pa,exports.getOGC3DTilesCopyrightInfo=Ue,exports.splatsFragmentShader=me,exports.splatsVertexShader=ke;
1502
+ }`}function Qo(B,A,g,I){const Q=B.getX(g),C=B.getY(g),a=B.getZ(g),e=A.getX(g),i=A.getY(g),t=A.getZ(g);I.set(Q,C,a,C,e,i,a,i,t)}function Co(B,A,g){const I=B.determinant();if(Math.abs(I)<1e-12)return void g.set(0,0,0);const Q=1/I,C=new u.Matrix3().copy(B);C.elements[0]=A.x,C.elements[3]=A.y,C.elements[6]=A.z;const a=new u.Matrix3().copy(B);a.elements[1]=A.x,a.elements[4]=A.y,a.elements[7]=A.z;const e=new u.Matrix3().copy(B);e.elements[2]=A.x,e.elements[5]=A.y,e.elements[8]=A.z,g.set(C.determinant()*Q,a.determinant()*Q,e.determinant()*Q)}function TI(B,A){if(!A||Array.isArray(A)&&A.length!==3)throw new Error(`${B} must be a length-3 array [x,y,z]`);return A}function zC(B,A,g){return{kind:"cuboid",params:{hx:Number(B),hy:Number(A),hz:Number(g)}}}const NQ={createBall:function(B){return{kind:"ball",params:{radius:Number(B)}}},createCuboid:zC,createBox:function(B,A,g){return zC(B,A,g)},createRoundCuboid:function(B,A,g,I){return{kind:"roundCuboid",params:{hx:Number(B),hy:Number(A),hz:Number(g),radius:Number(I)}}},createCapsule:function(B,A){return{kind:"capsule",params:{halfHeight:Number(B),radius:Number(A)}}},createCone:function(B,A){return{kind:"cone",params:{halfHeight:Number(B),radius:Number(A)}}},createCylinder:function(B,A){return{kind:"cylinder",params:{halfHeight:Number(B),radius:Number(A)}}},createSegment:function(B,A){return{kind:"segment",params:{a:TI("a",B),b:TI("b",A)}}},createTriangle:function(B,A,g){return{kind:"triangle",params:{a:TI("a",B),b:TI("b",A),c:TI("c",g)}}},createPolyline:function(B,A){return{kind:"polyline",params:{vertices:B,indices:A||null}}},createConvexHull:function(B){return{kind:"convexHull",params:{vertices:B}}},createHeightfield:function(B,A,g,I={x:1,y:1,z:1}){return{kind:"heightfield",params:{rows:Number(B),cols:Number(A),heights:g,scale:I}}}};var MA;const yg=new Y.Sphere(new Y.Vector3(0,0,0),1),Lg=new tg([0,0,0,1,0,0,0,1,0,0,0,1]);new Y.Box3;const Pg=new Y.Vector3(0,0,0),fI=new Y.Vector3(0,0,0),ao=new Y.Vector3(0,1,0),nB=new Y.Ray,rB=new Y.Matrix4;new Y.Matrix4,new Y.Frustum;const sB=new Y.Vector3,cB=[],XC=new Y.Quaternion,Rg={};function Ue(){var B=[];for(let A in Rg)Rg.hasOwnProperty(A)&&Rg[A]>0&&B.push(A);return B}class jQ extends Y.Object3D{constructor(A){super();const g=this;g.physics=A.physics||{};const I=g.physics;if(I&&typeof I=="object"&&(I.type||(I.type="fixed"),I.shape==null&&(I.shape="none"),I.mass==null&&(I.mass=1),Array.isArray(I.velocity)||I.velocity&&I.velocity.isVector3||(I.velocity=[0,0,0]),Array.isArray(I.angularVelocity)||I.angularVelocity&&I.angularVelocity.isVector3||(I.angularVelocity=[0,0,0]),I.maxLOD==null&&(I.maxLOD=1/0),I.colliders&&typeof I.colliders=="object")){const e=I.colliders;e.maxLOD==null&&(e.maxLOD=Number.isFinite(I.maxLOD)?I.maxLOD:1/0),Array.isArray(e.priority)?(e.priority=e.priority.filter(i=>i==="mesh"||i==="hull"||i==="bounds"),e.priority.length===0&&(e.priority=["mesh","hull","bounds"])):e.priority=["mesh","hull","bounds"],Array.isArray(e.byGeometricError)||(e.byGeometricError=[]),Array.isArray(e.byLevel)||(e.byLevel=[])}if(g.splatsMesh=A.splatsMesh,g.oldUltraMeshSplats=A.oldUltraMeshSplats,g.iosCompatibility=A.iosCompatibility,g.splatsQuality=A.splatsQuality!=null?A.splatsQuality:.75,g.splatsCPUCulling=A.splatsCPUCulling!=null&&A.splatsCPUCulling,this.contentURL=[],A.domWidth&&A.domHeight?this.rendererSize=new Y.Vector2(A.domWidth,A.domHeight):this.rendererSize=new Y.Vector2(1e3,1e3),this.setClipShape(A.clipShape),this.loadingStrategy=A.loadingStrategy?A.loadingStrategy.toUpperCase():"INCREMENTAL",this.distanceBias=Math.max(1e-4,A.distanceBias?A.distanceBias:1),this.proxy=A.proxy,this.drawBoundingVolume=!!A.drawBoundingVolume&&A.drawBoundingVolume,this.displayErrors=A.displayErrors,this.displayCopyright=A.displayCopyright,A.queryParams&&(this.queryParams={...A.queryParams}),this.uuid=Va(),A.tileLoader)this.tileLoader=A.tileLoader;else{const e={};e.meshCallback=A.meshCallback?A.meshCallback:(t,E)=>{t.material.wireframe=!1,t.material.side=Y.DoubleSide},e.pointsCallback=A.pointsCallback?A.pointsCallback:(t,E)=>{t.material.size=Math.pow(E,.33),t.material.sizeAttenuation=!0},e.proxy=this.proxy,e.renderer=A.renderer,e.dracoLoader=A.dracoLoader,e.ktx2Loader=A.ktx2Loader,g.tileLoader=new Pa(e);const i=this.update;this.update=t=>{i.call(g,t),g.tileLoader.update()}}this.displayCopyright=!!A.displayCopyright,this.geometricErrorMultiplier=A.geometricErrorMultiplier?A.geometricErrorMultiplier:1,this.splatsCropRadius=Number.MAX_VALUE,this.splatsSizeMultiplier=1,this.splatsExposureEV=A&&A.splatsExposureEV!==void 0?A.splatsExposureEV:0,this.splatsSaturation=A&&A.splatsSaturation!==void 0?A.splatsSaturation:1,this.splatsContrast=A&&A.splatsContrast!==void 0?A.splatsContrast:1;const Q=A&&A.splatsTempTint!==void 0?A.splatsTempTint:[0,0];if(this.splatsTempTint=Array.isArray(Q)?[Number(Q[0]||0),Number(Q[1]||0)]:[Number(Q.temp||0),Number(Q.tint||0)],this.renderer=A.renderer,this.meshCallback=A.meshCallback,this.loadOutsideView=A.loadOutsideView,this.cameraOnLoad=A.cameraOnLoad,this.parentTile=A.parentTile,this.occlusionCullingService=A.occlusionCullingService,this.static=A.static,this.occlusionCullingService&&(this.color=new Y.Color,this.color.setHex(16777215*Math.random()),this.colorID=Y.MathUtils.clamp(255*g.color.r,0,255)<<16^Y.MathUtils.clamp(255*g.color.g,0,255)<<8^Y.MathUtils.clamp(255*g.color.b,0,255)),this.static&&(this.matrixAutoUpdate=!1,this.matrixWorldAutoUpdate=!1),this.childrenTiles=[],this.meshContent=[],this.tileContent,this.refine,this.rootPath,this.geometricError,this.boundingVolume,this.json,this.materialVisibility=!1,this.level=A.level?A.level:0,this.hasMeshContent=0,this.hasUnloadedJSONContent=0,this.centerModel=A.centerModel,this.abortController=new AbortController,this.onLoadCallback=A.onLoadCallback,A.json)g._setup(A);else if(A.url){var C=A.url;if(g.queryParams){var a="";for(let e in g.queryParams)g.queryParams.hasOwnProperty(e)&&(a+="&"+e+"="+g.queryParams[e]);C.includes("?")?C+=a:C+="?"+a.substring(1)}(g.proxy?()=>fetch(g.proxy,{method:"POST",body:C,signal:g.abortController.signal}):()=>fetch(C,{signal:g.abortController.signal}))().then(e=>{if(!e.ok)throw new Error(`couldn't load "${A.url}". Request failed with status ${e.status} : ${e.statusText}`);e.json().then(i=>mQ(i,C)).then(i=>{g._setup({rootPath:iI.dirname(A.url),json:i})})}).catch(e=>{g.displayErrors&&ZC(e)})}}setClipShape(A){if(A instanceof tg||A instanceof Y.Sphere)this.clipShape=A;else if(A instanceof Y.Box3){const g=new Y.Vector3,I=new Y.Vector3;A.getCenter(g),A.getSize(I).multiplyScalar(.5),this.clipShape=new tg([g.x,g.y,g.z,I.x,0,0,0,I.y,0,0,0,I.z])}else A=void 0;this.childrenTiles&&this.childrenTiles.forEach(g=>{g._setClipShape(this.clipShape)})}_setClipShape(A){this.clipShape=A,this.childrenTiles&&this.childrenTiles.forEach(g=>{g._setClipShape(this.clipShape)})}setSplatsSizeMultiplier(A){this.splatsSizeMultiplier=A,this.splatsMesh&&this.splatsMesh.setSplatsSizeMultiplier(this.splatsSizeMultiplier)}setSplatsCropRadius(A){this.splatsCropRadius=A,this.splatsMesh&&this.splatsMesh.setSplatsCropRadius(this.splatsCropRadius)}setSplatsDepthBias(A){this.splatsDepthBias=A,this.splatsMesh&&this.splatsMesh.setDepthBias(this.splatsDepthBias)}setSplatsCPUCulling(A){this.splatsCPUCulling=A,this.splatsMesh&&this.splatsMesh.setSplatsCPUCulling(A)}setSplatsQuality(A){this.splatsQuality=A,this.splatsMesh&&this.splatsMesh.setQuality(A)}setSplatsExposureEV(A){this.splatsExposureEV=A,this.splatsMesh&&typeof this.splatsMesh.setExposureEV=="function"&&this.splatsMesh.setExposureEV(A)}setSplatsSaturation(A){this.splatsSaturation=A,this.splatsMesh&&typeof this.splatsMesh.setSaturation=="function"&&this.splatsMesh.setSaturation(A)}setSplatsContrast(A){this.splatsContrast=A,this.splatsMesh&&typeof this.splatsMesh.setContrast=="function"&&this.splatsMesh.setContrast(A)}setSplatsTempTint(A,g){this.splatsTempTint=[A,g],this.splatsMesh&&typeof this.splatsMesh.setTempTint=="function"&&this.splatsMesh.setTempTint(A,g)}updateMatrices(){this.updateMatrix(),this.splatsMesh&&this.splatsMesh.updateMatrix(),this.static&&(this.traverse(A=>{A.isObject3D&&(A.matrixWorldAutoUpdate=!0)}),this.splatsMesh&&(this.splatsMesh.matrixWorldAutoUpdate=!0)),this.updateMatrixWorld(!0),this.static&&(this.traverse(A=>{A.isObject3D&&(A.matrixWorldAutoUpdate=!1)}),this.splatsMesh&&(this.splatsMesh.matrixWorldAutoUpdate=!1))}setCanvasSize(A,g){this.rendererSize.set(A,g)}async _setup(A){const g=this;if(A.json.extensionsRequired&&(A.json.extensionsRequired.includes("JDULTRA_gaussian_splats")||A.json.extensionsRequired.includes("JDULTRA_gaussian_splats_V2"))&&(g.oldUltraMeshSplats=!0),A.json.root?(g.json=A.json.root,g.json.refine||(g.json.refine=A.json.refine),g.json.geometricError||(g.json.geometricError=A.json.geometricError),g.json.transform||(g.json.transform=A.json.transform),g.json.boundingVolume||(g.json.boundingVolume=A.json.boundingVolume)):g.json=A.json,g.json.children||(g.json.getChildren?g.json.children=await g.json.getChildren():g.json.children=[]),g.rootPath=A.json.rootPath?A.json.rootPath:A.rootPath,g.json.refine?g.refine=g.json.refine:g.refine=A.parentRefine,g.json.geometricError?g.geometricError=g.json.geometricError:g.geometricError=A.parentGeometricError,g.json.transform){let Q=new Y.Matrix4;Q.elements=g.json.transform,g.applyMatrix4(Q)}if(g.json.boundingVolume)if(g.json.boundingVolume.box)g.boundingVolume=new tg(g.json.boundingVolume.box);else if(g.json.boundingVolume.region){const Q=g.json.boundingVolume.region;g._transformWGS84ToCartesian(Q[0],Q[1],Q[4],Pg),g._transformWGS84ToCartesian(Q[2],Q[3],Q[5],fI),Pg.lerp(fI,.5),g.boundingVolume=new Y.Sphere(new Y.Vector3(Pg.x,Pg.y,Pg.z),Pg.distanceTo(fI))}else if(g.json.boundingVolume.sphere){const Q=g.json.boundingVolume.sphere;g.boundingVolume=new Y.Sphere(new Y.Vector3(Q[0],Q[1],Q[2]),Q[3])}else g.boundingVolume=A.parentBoundingVolume;else g.boundingVolume=A.parentBoundingVolume;function I(Q){Q.uri&&Q.uri.includes("json")||Q.url&&Q.url.includes("json")?g.hasUnloadedJSONContent++:g.hasMeshContent++}if(g.json.content?(I(g.json.content),g.hasMeshContent==0&&(g.level=Math.max(0,g.parentTile?g.parentTile.level+.01:0)),g._load()):g.json.contents&&(g.json.contents.forEach(Q=>I(Q)),g.hasMeshContent==0&&(g.level=Math.max(0,g.parentTile?g.parentTile.level+.01:0))),g.centerModel&&(fI.copy(g.boundingVolume.center),this.json.boundingVolume.region&&(this._transformWGS84ToCartesian(.5*(this.json.boundingVolume.region[0]+this.json.boundingVolume.region[2]),.5*(this.json.boundingVolume.region[1]+this.json.boundingVolume.region[3]),.5*(this.json.boundingVolume.region[4]+this.json.boundingVolume.region[5]),Pg),XC.setFromUnitVectors(Pg.normalize(),ao.normalize()),g.applyQuaternion(XC)),fI.applyMatrix4(g.matrix),g.position.sub(fI),g.updateMatrices()),g.onLoadCallback&&g.onLoadCallback(g),!g.parentTile&&g.physics&&g.physics.sim&&(g.physics.rigidBodyID=g.physics.sim.addObject({object:g,type:g.physics.type,mass:g.physics.mass,position:g.position,rotation:g.quaternion,velocity:g.physics.velocity,angularVelocity:g.physics.angularVelocity})),g.isSetup=!0,g.level>0&&g.drawBoundingVolume)if(g.bbox&&console.log("double setup"),this.boundingVolume.aabb){let Q=this.boundingVolume.aabb.clone();Q.applyMatrix4(this.matrixWorld),g.bbox=new Y.Box3Helper(Q,new Y.Color(Math.random(),Math.random(),Math.random())),g.add(g.bbox),g.bbox.material.visible=!1}else g.boundingVolume instanceof tg&&(g.bbox=g.boundingVolume.helper(),g.add(g.bbox),g.bbox.material.visible=!1)}_assembleURL(A,g){A.endsWith("/")||(A+="/");try{const I=new URL(A);let Q=I.pathname.split("/").filter(a=>a!==""),C=g.split("/").filter(a=>a!=="");for(let a=1;a<=Q.length&&!(a>=C.length);a++)if(Q.slice(Q.length-a,Q.length).join("/")===C.slice(0,a).join("/")){for(let i=0;i<a;i++)Q.pop();break}for(;C.length>0&&C[0]==="..";)Q.pop(),C.shift();return`${I.protocol}//${I.host}/${[...Q,...C].join("/")}`}catch{return A.endsWith("/")||g.startsWith("/")?A+g:A+"/"+g}}_extractQueryParams(A,g){try{const I=new URL(A);for(let[Q,C]of I.searchParams)g[Q]=C;return I.search="",I.toString()}catch{return A}}async _load(A=!0,g=!0){var I=this;if(!I.deleted||!g){if(I.json.content)await Q(I.json.content,null,A,g);else if(I.json.contents){let C=I.json.contents.map((a,e)=>Q(a,e,A,g));Promise.all(C)}}async function Q(C,a,e,i){let t;C.uri?t=C.uri:C.url&&(t=C.url);const E=/^(?:http|https|ftp|tcp|udp):\/\/\S+/;if(E.test(I.rootPath)?E.test(t)||(t=I._assembleURL(I.rootPath,t)):t=I.rootPath+iI.sep+t,t.startsWith("/local-tiles")||(t=I._extractQueryParams(t,I.queryParams)),I.queryParams){var o="";for(let r in I.queryParams)I.queryParams.hasOwnProperty(r)&&(o+="&"+r+"="+I.queryParams[r]);t.includes("?")?t+=o:t+="?"+o.substring(1)}if(t)if(I.contentURL.push(t),i&&(t.includes(".b3dm")||t.includes(".glb")||t.includes(".gltf")))try{I.tileLoader.get(I.abortController,I.uuid,t,r=>{if(!I.deleted){if(r.asset&&r.asset.copyright&&(r.asset.copyright.split(";").forEach(n=>{Rg[n]?Rg[n]++:Rg[n]=1}),I.displayCopyright&&rQ()),r.isSplatsData){if(!I.splatsMesh){if(I.splatsMesh=new Ne(I.tileLoader.renderer,void 0,void 0,I.oldUltraMeshSplats?.25:1),I.splatsMesh.setQuality(I.splatsQuality),I.splatsMesh.setSplatsCPUCulling(I.splatsCPUCulling),I.splatsMesh.setSplatsCropRadius(I.splatsCropRadius),I.splatsMesh.setSplatsSizeMultiplier(I.splatsSizeMultiplier),I.splatsExposureEV!==void 0&&typeof I.splatsMesh.setExposureEV=="function"&&I.splatsMesh.setExposureEV(I.splatsExposureEV),I.splatsSaturation!==void 0&&typeof I.splatsMesh.setSaturation=="function"&&I.splatsMesh.setSaturation(I.splatsSaturation),I.splatsContrast!==void 0&&typeof I.splatsMesh.setContrast=="function"&&I.splatsMesh.setContrast(I.splatsContrast),I.splatsTempTint!==void 0&&typeof I.splatsMesh.setTempTint=="function"){const n=I.splatsTempTint||[0,0];I.splatsMesh.setTempTint(n[0],n[1])}I.static&&(I.splatsMesh.matrixAutoUpdate=!1,I.splatsMesh.matrixWorldAutoUpdate=!1),I.add(I.splatsMesh),I.updateMatrices()}r=I.splatsMesh.addSplatsTile(r.positions,r.colors,r.cov0,r.cov1)}return r.isSplatsBatch||(r.traverse(n=>{if((n.isMesh||n.isPoints)&&n.layers.disable(0),n.isMesh&&I.occlusionCullingService){const s=n.geometry.attributes.position,c=[];for(let D=0;D<s.count;D++)c.push(I.color.r,I.color.g,I.color.b);n.geometry.setAttribute("color",new Y.Float32BufferAttribute(c,3))}}),I.add(r),I.updateMatrices()),I.meshContent.push(r),r}},I.cameraOnLoad?()=>I.loadingStrategy=="IMMEDIATE"?I._calculateDistanceToCamera(I.cameraOnLoad):I.loadingStrategy=="INCREMENTAL"?I.parentTile?I.parentTile._calculateDistanceToCamera(I.cameraOnLoad)/Math.max(1,I.parentTile.level):I._calculateDistanceToCamera(I.cameraOnLoad)/Math.max(1,I.level):I.loadingStrategy=="PERLEVEL"?I.parentTile?I.level+I.parentTile._calculateDistanceToCamera(I.cameraOnLoad):I.level+I._calculateDistanceToCamera(I.cameraOnLoad):0:()=>0,()=>I._getSiblings(),I.level,I.loadingStrategy,!I.json.boundingVolume.region,!!I.json.boundingVolume.region,I.geometricError,I.oldUltraMeshSplats)}catch(r){I.displayErrors&&ZC(r)}else e&&t.includes(".json")&&(I.jsonRequested=t,I.tileLoader.get(I.abortController,I.uuid,t,async r=>{I.jsonReceived=!0,r.rootPath=iI.dirname(t),I.json.children.push(r),a==null?delete I.json.content:I.json.contents.splice(a,1),I.hasUnloadedJSONContent--}))}}dispose(){const A=this;if(A.physics&&A.physics.sim&&(A.colliderUUID&&(A.physics.sim.detachCollider({colliderId:A.colliderUUID}),A.colliderUUID=void 0),Array.isArray(A.colliderUUIDs)&&A.colliderUUIDs.length)){for(const g of A.colliderUUIDs)A.physics.sim.detachCollider({colliderId:g});A.colliderUUIDs=[]}A.meshContent.forEach(g=>{g&&g.asset&&g.asset.copyright&&(g.asset.copyright.split(";").forEach(I=>{Rg[I]&&Rg[I]--}),A.displayCopyright&&rQ())}),A.childrenTiles.forEach(g=>g.dispose()),A.deleted=!0,A.splatsMesh&&(A.meshContent.forEach(g=>g.hide()),A.parentTile||(A.splatsMesh.dispose(),A.splatsMesh=void 0)),A.contentURL&&(A.contentURL.forEach(g=>{A.tileLoader.invalidate(g,A.uuid)}),A.contentURL=[]),A.abortController&&!A.jsonRequested&&A.abortController.abort("tile not needed"),this.parent=null,A.meshContent=[],A.bbox&&A.bbox.dispose(),this.dispatchEvent({type:"removed"})}_disposeMeshContent(){const A=this;if(!A.deleted){A.deleted=!0,A.abortController&&(A.abortController.abort("tile not needed"),A.abortController=new AbortController);for(let g=A.meshContent.length-1;g>=0;g--){const I=A.meshContent[g];I&&I.asset&&I.asset.copyright&&(I.asset.copyright.split(";").forEach(Q=>{Rg[Q]&&Rg[Q]--}),A.displayCopyright&&rQ()),A.remove(I)}A.splatsMesh&&A.meshContent.forEach(g=>g.hide()),A.meshContent=[],A.contentURL.forEach(g=>{A.tileLoader.invalidate(g,A.uuid)}),A.contentURL=[]}}_disposeChildren(){var A=this;A.childrenTiles.forEach(g=>{g.dispose(),A.remove(g)}),A.childrenTiles=[]}raycast(A,g){if(this.splatsMesh){nB.copy(A.ray),rB.copy(this.matrixWorld).invert(),nB.applyMatrix4(rB);let I=!1;if(this.boundingVolume instanceof tg)I=this.boundingVolume.intersectsRay(nB);else{if(!(this.boundingVolume instanceof Y.Sphere))return!1;I=ray.intersectsSphere(this.boundingVolume)}return I&&this.materialVisibility&&this.splatsReady&&(cB.length=0,this.meshContent.forEach(Q=>{Q.isSplatsBatch&&(Q.raycast(nB,cB,A.params.Points.threshold),cB.forEach(C=>{C.point.applyMatrix4(this.matrixWorld)}),g.push(...cB))})),I}return super.raycast(A,g)}update(A){this.splatsMesh&&this.splatsMesh.updateShaderParams(A,this.renderer);const g=new Y.Frustum;g.setFromProjectionMatrix(new Y.Matrix4().multiplyMatrices(A.projectionMatrix,A.matrixWorldInverse));let I=[0],Q=[0],C=[0],a=[0];if(this.refine=="REPLACE"?this.loadingStrategy==="IMMEDIATE"?(this._updateImmediate(A,g),this._statsImmediate(C,I,a,Q)):(this._update(A,g),this._stats(C,I,a,Q)):(this._update(A,g),this._stats(C,I,a,Q)),I>0&&(a[0]/=I[0]),this.splatsMesh)if(sB.copy(A.position),rB.copy(this.matrixWorld).invert(),sB.applyMatrix4(rB),this.splatsCPUCulling){const e=new Y.Matrix4().multiplyMatrices(A.projectionMatrix,A.matrixWorldInverse).multiply(this.matrixWorld);this.splatsMesh.sort(sB,e)}else this.splatsMesh.sort(sB);return this.splatsMesh&&this.splatsMesh.update(),{numTilesLoaded:I[0],numTilesRendered:Q[0],maxLOD:C[0],percentageLoaded:a[0]}}_updateImmediate(A,g){this._computeMetricRecursive(A,g),this._updateNodeVisibilityImmediate(),this._expandTreeImmediate(A),this.shouldBeVisible=this.metric>0||!!this.loadOutsideView,this._shouldBeVisibleUpdateImmediate(),this._trimTreeImmediate(),this._loadMeshImmediate()}_statsImmediate(A,g,I,Q){A[0]=Math.max(A[0],this.level),(this.shouldBeVisible||this.materialVisibility)&&(g[0]++,this.materialVisibility&&I[0]++),this.materialVisibility&&Q[0]++,this.childrenTiles.forEach(C=>{C._statsImmediate(A,g,I,Q)})}_stats(A,g,I,Q){A[0]=Math.max(A[0],this.level),this.hasMeshContent&&(g[0]++,this.meshContent.length==this.hasMeshContent&&I[0]++,this.materialVisibility&&Q[0]++),this.childrenTiles.forEach(C=>{C._stats(A,g,I,Q)})}_trimTreeImmediate(){const A=this;if(A.metric!=null)if(A.hasMeshContent&&A.shouldBeVisible&&A.materialVisibility){if(A.splatsMesh&&!A.splatsReady)return;A._disposeChildren()}else A.childrenTiles.forEach(g=>{g._trimTreeImmediate()})}_updateNodeVisibilityImmediate(A=!1){const g=this;if(g.hasMeshContent)if(g.shouldBeVisible)g.meshContent.length==g.hasMeshContent?g.materialVisibility?g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(!0)}):(g._changeContentVisibility(!0),g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)})):g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)});else{if(!g.loadOutsideView&&g.metric<0)return g._changeContentVisibility(!1),g.meshContent.length>0&&g._disposeMeshContent(),void g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(!0)});if(!g.materialVisibility||g.splatsMesh&&!g.splatsReady)g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)});else if(A)g._changeContentVisibility(!1),g.meshContent.length>0&&g._disposeMeshContent(),g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)});else{let I=!0;g.childrenTiles.every(Q=>!!Q._isReadyImmediate()||(I=!1,!1)),I&&g.childrenTiles.length>0?(g._changeContentVisibility(!1),g.meshContent.length>0&&g._disposeMeshContent(),g.childrenTiles.forEach(Q=>{Q._updateNodeVisibilityImmediate(A)})):g.childrenTiles.forEach(Q=>{Q._updateNodeVisibilityImmediate(!g.splatsMesh||!!g.splatsReady)})}}else g.childrenTiles.forEach(I=>{I._updateNodeVisibilityImmediate(A)})}_shouldBeVisibleUpdateImmediate(){const A=this;A.hasMeshContent?A.metric==null?A.shouldBeVisible=!1:A.metric<0?(A.shouldBeVisible=!!A.loadOutsideView,A.childrenTiles.forEach(g=>{g._setShouldNotBeVisibleRecursive()})):A.metric<A.geometricErrorMultiplier*A.geometricError?A.hasUnloadedJSONContent||(A.json&&A.json.children&&A.json.children.length>0?(A.shouldBeVisible=!1,A.childrenTiles.forEach(g=>{g.shouldBeVisible=!0,g._shouldBeVisibleUpdateImmediate()})):A.shouldBeVisible=!0):A.childrenTiles.forEach(g=>{g._setShouldNotBeVisibleRecursive()}):(A.childrenTiles.forEach(g=>{g.shouldBeVisible=!0,g._shouldBeVisibleUpdateImmediate()}),A.shouldBeVisible=!1)}_setShouldNotBeVisibleRecursive(){this.shouldBeVisible=!1,this.childrenTiles.forEach(A=>{A._setShouldNotBeVisibleRecursive()})}_loadMeshImmediate(){const A=this;A.hasMeshContent&&A.shouldBeVisible?A.meshContent.length<A.hasMeshContent&&A.contentURL.length==0&&(A.deleted=!1,A._load(!1,!0)):A.childrenTiles.forEach(g=>{g._loadMeshImmediate()})}_computeMetricRecursive(A,g){const I=this;I.metric=-1,I.isSetup&&(I.boundingVolume&&I.geometricError&&(I.metric=I._calculateUpdateMetric(A,g)),I.childrenTiles.forEach(Q=>Q._computeMetricRecursive(A,g)))}_expandTreeImmediate(A){const g=this;g.hasUnloadedJSONContent||(g.hasMeshContent?g.occlusionCullingService&&g.hasMeshContent&&!g.occlusionCullingService.hasID(g.colorID)||g.metric>=0&&g.metric<g.geometricErrorMultiplier*g.geometricError&&g.json&&g.json.children&&g.childrenTiles.length<g.json.children.length&&g._loadJsonChildren(A):g.json&&g.json.children&&g.childrenTiles.length<g.json.children.length&&g._loadJsonChildren(A)),g.childrenTiles.forEach(I=>I._expandTreeImmediate(A))}_update(A,g){const I=this;if(!I.isSetup)return;const Q=I.materialVisibility;I.boundingVolume&&I.geometricError&&(I.metric=I._calculateUpdateMetric(A,g)),I.childrenTiles.forEach(C=>C._update(A,g)),function(C){if(C<0)return I.inFrustum=!1,void I._changeContentVisibility(!!I.loadOutsideView);if(I.inFrustum=!0,!!I.hasMeshContent&&!(I.meshContent.length<I.hasMeshContent)){if(I.childrenTiles.length==0)return void I._changeContentVisibility(!0);if(C>=I.geometricErrorMultiplier*I.geometricError)I._changeContentVisibility(!0);else if(C<I.geometricErrorMultiplier*I.geometricError&&I.refine=="REPLACE"){let a=!0;I.childrenTiles.every(e=>!!e._isReady()||(a=!1,!1)),a?I._changeContentVisibility(!1):I._changeContentVisibility(!0)}}}(I.metric),function(C){C<0&&I.hasMeshContent||I.occlusionCullingService&&I.hasMeshContent&&!I.occlusionCullingService.hasID(I.colorID)||(!I.hasMeshContent||C<=I.geometricErrorMultiplier*I.geometricError&&(I.meshContent.length>0||I.splatsMesh))&&I.json&&I.json.children&&I.childrenTiles.length!=I.json.children.length&&I._loadJsonChildren(A)}(I.metric),function(C,a){if(I.hasMeshContent){if(!I.inFrustum)return void I._disposeChildren();if(I.occlusionCullingService&&!a&&I.hasMeshContent&&I.meshContent.length>0&&I.materialVisibility&&I._areAllChildrenLoadedAndHidden())return I.splatsMesh&&I.materialVisibility&&!I.splatsReady?void 0:void I._disposeChildren();if(C>=I.geometricErrorMultiplier*I.geometricError){if(I.splatsMesh&&I.materialVisibility&&!I.splatsReady)return;I._disposeChildren()}}}(I.metric,Q)}_loadJsonChildren(A){const g=this;for(let I=g.json.children.length-1;I>=0;I--)g.json.children[I].root||g.json.children[I].children||g.json.children[I].getChildren||g.json.children[I].content||g.json.children[I].contents||g.json.children.splice(I,1);g.json.children.forEach(I=>{let Q=new jQ({parentTile:g,queryParams:g.queryParams,parentGeometricError:g.geometricError,parentBoundingVolume:g.boundingVolume,parentRefine:g.refine,json:I,rootPath:g.rootPath,geometricErrorMultiplier:g.geometricErrorMultiplier,loadOutsideView:g.loadOutsideView,level:Math.floor(g.level)+1,tileLoader:g.tileLoader,cameraOnLoad:A,occlusionCullingService:g.occlusionCullingService,renderer:g.renderer,static:g.static,centerModel:!1,displayErrors:g.displayErrors,displayCopyright:g.displayCopyright,distanceBias:g.distanceBias,loadingStrategy:g.loadingStrategy,drawBoundingVolume:g.drawBoundingVolume,splatsMesh:g.splatsMesh,clipShape:g.clipShape,oldUltraMeshSplats:g.oldUltraMeshSplats,physics:g.physics});g.childrenTiles.push(Q),g.add(Q)}),g.updateMatrices(!0)}_areAllChildrenLoadedAndHidden(){let A=!0;const g=this;return this.childrenTiles.every(I=>{if(I.hasMeshContent){if(I.childrenTiles.length>0)return A=!1,!1;if(I.metric<0)return!0;if(I.materialVisibility&&(!g.splatsMesh||g.splatsReady)||g.occlusionCullingService.hasID(I.colorID))return A=!1,!1}else if(!I._areAllChildrenLoadedAndHidden())return A=!1,!1;return!0}),A}_isReady(){if(this.metric==null)return!1;if(this.metric<0)return!0;if(this.hasUnloadedJSONContent)return!1;if(!this.hasMeshContent&&this.json.children.length==0&&!this.hasUnloadedJSONContent)return!0;if(!this.hasMeshContent||this.meshContent.length==0||!this.materialVisibility){if(this.children.length>0){var A=!0;return this.childrenTiles.every(g=>!!g._isReady()||(A=!1,!1)),A}return!1}return!this.hasMeshContent||!(this.meshContent.length<this.hasMeshContent)&&!!this.materialVisibility}_isReadyImmediate(){if(this.materialVisibility||!this.loadOutsideView&&this.metric<0)return!0;if(this.childrenTiles.length>0){var A=!0;return this.childrenTiles.every(g=>!!g._isReadyImmediate()||(A=!1,!1)),A}return!1}_changeContentVisibility(A){const g=this;if(g.materialVisibility!=A){if(g.bbox&&(g.bbox.material.visible=A),g.splatsMesh)A!=g.materialVisibility&&(g.meshContent.forEach(I=>{A&&I.isSplatsBatch?I.show(()=>{g.materialVisibility&&(g.splatsReady=!0)}):(I.hide(),g.splatsReady=!1)}),g.materialVisibility=A);else{if(g.hasMeshContent&&g.meshContent.length>0&&(A?g.meshContent.forEach(I=>{I.traverse(Q=>{(Q.isMesh||Q.isPoints)&&Q.layers.enable(0)})}):g.meshContent.forEach(I=>{I.traverse(Q=>{(Q.isMesh||Q.isPoints)&&Q.layers.disable(0)})})),g.materialVisibility==A)return;g.materialVisibility=A}g._updateCollider()}}setPose(A,g,I){if(!A.isVector3)throw new TypeError("OGC3DTile.setPose: 'position' must be an instance of THREE.Vector3");if(!I.isVector3)throw new TypeError("OGC3DTile.setPose: 'scale' must be an instance of THREE.Vector3");if(!g.isEuler&&!g.isQuaternion)throw new TypeError("OGC3DTile.setPose: 'rotation' must be a THREE.Euler or THREE.Quaternion");this.physics&&this.physics.sim&&this.physics.rigidBodyID?(this.physics.sim.setPose({bodyId:this.physics.rigidBodyID,position:A,rotation:g}),I&&!I.equals(this.scale)&&(this.scale.copy(I),this.updateMatrices(),this.traverse(Q=>{Q._updateCollider&&Q._updateCollider()}))):(this.scale.copy(I),g.isQuaternion?this.setRotationFromQuaternion(g):this.setRotationFromEuler(g),this.position.copy(A),this.updateMatrices())}_updateCollider(){const A=this;if(!A.physics||!A.physics.sim)return;const g=A.physics.rigidBodyID,I=Math.floor(A.level||0),Q=!!A.materialVisibility,C=Array.isArray(A.childrenTiles)&&A.childrenTiles.length>0,a=A.physics&&A.physics.colliders&&typeof A.physics.colliders=="object"?A.physics.colliders:null,e=Number.isFinite(a?.maxLOD)?a.maxLOD:Number.isFinite(A.physics.maxLOD)?A.physics.maxLOD:1/0,i=(G,N)=>{const F=Array.isArray(N)&&N.length?N:["mesh","hull","bounds"];for(const k of F)if(G.includes(k))return k;return null},t=()=>{const G=a?.priority||["mesh","hull","bounds"];if(a&&Array.isArray(a.byGeometricError)&&a.byGeometricError.length){const N=A.geometricError;if(typeof N=="number"){const F=[];for(const m of a.byGeometricError){if(!m||!m.shape)continue;const S=typeof m.min=="number"?m.min:-1/0,j=typeof m.max=="number"?m.max:1/0;N>=S&&N<j&&F.push(m.shape)}const k=i(F,G);if(k)return k}return a.defaultShape?a.defaultShape:A.physics.shape?A.physics.shape:"none"}if(a&&Array.isArray(a.byLevel)&&a.byLevel.length){const N=Math.floor(A.level||0),F=[];for(const m of a.byLevel){if(!m||!m.shape)continue;const S=typeof m.min=="number"?m.min:-1/0,j=typeof m.max=="number"?m.max:1/0;N>=S&&N<=j&&F.push(m.shape)}return i(F,G)||(a.defaultShape?a.defaultShape:A.physics.shape?A.physics.shape:"none")}return A.physics.shape||"none"},E=t(),o=()=>{A.colliderUUID&&(A.physics.sim.detachCollider({colliderId:A.colliderUUID}),A.colliderUUID=void 0)},r=()=>{if(Array.isArray(A.colliderUUIDs)&&A.colliderUUIDs.length){for(const G of A.colliderUUIDs)A.physics.sim.detachCollider({colliderId:G});A.colliderUUIDs=[]}},n=()=>{o(),r(),A._activeColliderShape=void 0};if(!g||!E||E==="none"||I>e)return n(),void(A._activeColliderShape=void 0);const s=Q&&I<=e,c=A._activeColliderShape||"none";c===E||!Q&&I===e&&C||(c!=="mesh"&&c!=="hull"||E!=="bounds"?c!=="bounds"||E!=="mesh"&&E!=="hull"?c==="mesh"&&E==="hull"||c==="hull"&&E==="mesh"?r():n():o():r(),A._activeColliderShape=E&&E!=="none"?E:void 0);let D=A;for(;D&&D.parentTile;)D=D.parentTile;const d=new Y.Vector3,h=new Y.Quaternion,l=new Y.Vector3;D&&D.matrixWorld&&D.matrixWorld.decompose(d,h,l);const f=new Y.Matrix4().compose(d,h,new Y.Vector3(1,1,1)),R=new Y.Matrix4().copy(f).invert();if(E!=="bounds"){if(E==="mesh"||E==="hull")if(o(),s){if(!A.hasMeshContent||A.meshContent.length!==A.hasMeshContent)return;if(!Array.isArray(A.colliderUUIDs)||A.colliderUUIDs.length===0){A.colliderUUIDs=[];const G=E==="hull"?"addConvexHullCollider":"attachTrimeshCollider",N=F=>{if(!(F&&F.isMesh&&F.geometry&&F.geometry.isBufferGeometry))return;const k=new Y.Matrix4().multiplyMatrices(R,F.matrixWorld),m=new Y.Vector3,S=new Y.Quaternion,j=new Y.Vector3;k.decompose(m,S,j);const z=new Y.Vector3;F.getWorldScale(z),z.set(Math.abs(z.x),Math.abs(z.y),Math.abs(z.z)),A.physics.sim[G]({bodyId:g,geometry:F.geometry,localPosition:[m.x,m.y,m.z],localRotation:S,localScale:[z.x,z.y,z.z]}).then($=>{const _=t(),X=!A.deleted&&(_==="mesh"||_==="hull"),CA=Math.floor(A.level||0)<=e,rA=Math.floor(A.level||0)===e&&Array.isArray(A.childrenTiles)&&A.childrenTiles.length>0;X&&(A.materialVisibility?CA:CA&&rA)?($&&A.colliderUUIDs.push($),A._activeColliderShape=E):$&&A.physics.sim.detachCollider({colliderId:$})}).catch(()=>{})};for(const F of A.meshContent)F&&!F.isSplatsBatch&&(F.isMesh&&N(F),F.traverse&&F.traverse(k=>{k.isMesh&&N(k)}))}}else I===e&&C||(r(),A._activeColliderShape=void 0)}else if(r(),s){if(!A.colliderUUID){if(A.boundingVolume instanceof tg||A.boundingVolume?.isOBB){const G=A.localToWorld(A.boundingVolume.center.clone()).clone().applyMatrix4(R),N=A.localToWorld(new Y.Vector3(0,0,0)).clone().applyMatrix4(R),F=A.boundingVolume.e1.clone().multiplyScalar(A.boundingVolume.halfSize.x),k=A.boundingVolume.e2.clone().multiplyScalar(A.boundingVolume.halfSize.y),m=A.boundingVolume.e3.clone().multiplyScalar(A.boundingVolume.halfSize.z),S=A.localToWorld(F.clone()).applyMatrix4(R),j=A.localToWorld(k.clone()).applyMatrix4(R),z=A.localToWorld(m.clone()).applyMatrix4(R),$=S.clone().sub(N),_=j.clone().sub(N),X=z.clone().sub(N),CA=$.length(),rA=_.length(),oA=X.length(),wA=CA>0?$.clone().multiplyScalar(1/CA):new Y.Vector3(1,0,0),bA=rA>0?_.clone().multiplyScalar(1/rA):new Y.Vector3(0,1,0),iA=oA>0?X.clone().multiplyScalar(1/oA):new Y.Vector3(0,0,1),yA=new Y.Matrix4().makeBasis(wA,bA,iA),EA=new Y.Quaternion().setFromRotationMatrix(yA);A.colliderUUID=A.physics.sim.attachShapeCollider({bodyId:g,shape:NQ.createBox(CA,rA,oA),localPosition:[G.x,G.y,G.z],localRotation:EA}),A._activeColliderShape="bounds"}else if(A.boundingVolume instanceof Y.Sphere||A.boundingVolume?.isSphere){const G=A.localToWorld(A.boundingVolume.center.clone()).clone().applyMatrix4(R),N=A.localToWorld(new Y.Vector3(0,0,0)).clone().applyMatrix4(R),F=A.localToWorld(new Y.Vector3(1,0,0)).applyMatrix4(R).sub(N).length(),k=A.localToWorld(new Y.Vector3(0,1,0)).applyMatrix4(R).sub(N).length(),m=A.localToWorld(new Y.Vector3(0,0,1)).applyMatrix4(R).sub(N).length(),S=Math.max(F,k,m),j=A.boundingVolume.radius*S;A.colliderUUID=A.physics.sim.attachShapeCollider({bodyId:g,shape:NQ.createBall(j),localPosition:[G.x,G.y,G.z]}),A._activeColliderShape="bounds"}}}else I===e&&C||(o(),A._activeColliderShape=void 0)}_calculateUpdateMetric(A,g){let I=0;if(this.boundingVolume instanceof tg){if(Lg.copy(this.boundingVolume),Lg.applyMatrix4(this.matrixWorld),!Lg.inFrustum(g))return-1;if(this.clipShape!=null&&(this.clipShape.isSphere&&!Lg.intersectsSphere(this.clipShape)||this.clipShape.isOBB&&!Lg.intersectsOBB(this.clipShape)))return Number.MAX_VALUE;I=Math.max(0,Lg.distanceToPoint(A.position)-A.near)}else{if(!(this.boundingVolume instanceof Y.Sphere))return console.error("unsupported shape"),-1;if(yg.copy(this.boundingVolume),yg.applyMatrix4(this.matrixWorld),this.clipShape!=null&&(this.clipShape.isOBB&&!this.clipShape.intersectsSphere(yg)||this.clipShape.isSphere&&!this.clipShape.intersectsSphere(yg)))return Number.MAX_VALUE;if(!g.intersectsSphere(yg))return-1;I=Math.max(0,A.position.distanceTo(yg.center)-yg.radius-A.near)}if(I=Math.pow(I,this.distanceBias),I==0)return 0;const Q=this.matrixWorld.getMaxScaleOnAxis();this.renderer&&this.renderer.getDrawingBufferSize(this.rendererSize);let C=this.rendererSize.y,a=A.fov;return A.aspect<1&&(a*=A.aspect,C=this.rendererSize.x),16*(2*Math.tan(.5*a*.017453292519943295)*I)/(C*Q)}_getSiblings(){const A=this,g=[];if(!A.parentTile)return g;let I=A.parentTile;for(;!I.hasMeshContent&&I.parentTile;)I=I.parentTile;return I.childrenTiles.forEach(Q=>{if(Q&&Q!=A){for(;!Q.hasMeshContent&&Q.childrenTiles[0];)Q=Q.childrenTiles[0];g.push(Q)}}),g}_calculateDistanceToCamera(A){return this.boundingVolume instanceof tg?(Lg.copy(this.boundingVolume),Lg.applyMatrix4(this.matrixWorld),Math.max(0,Lg.distanceToPoint(A.position))):this.boundingVolume instanceof Y.Sphere?(yg.copy(this.boundingVolume),yg.applyMatrix4(this.matrixWorld),Math.max(0,A.position.distanceTo(yg.center)-yg.radius)):(console.error("unsupported shape"),-1)}setGeometricErrorMultiplier(A){this.geometricErrorMultiplier=A,this.childrenTiles.forEach(g=>g.setGeometricErrorMultiplier(A))}setDistanceBias(A){this.distanceBias=A,this.childrenTiles.forEach(g=>g.setDistanceBias(A))}_transformWGS84ToCartesian(A,g,I,Q){const C=6378137/Math.sqrt(1-.006694384442042*Math.pow(Math.sin(g),2)),a=Math.cos(g),e=Math.cos(A),i=Math.sin(g),t=C+I,E=t*a*e,o=t*a*Math.sin(A),r=(.993305615557957*C+I)*i;Q.set(E,o,r)}hideCopyright(){(function(){MA||((MA=document.createElement("div")).style.position="fixed",MA.style.bottom="20px",MA.style.left="20px",MA.style.color="white",MA.style.textShadow="2px 2px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000",MA.style.padding="10px",MA.style.backgroundColor="rgba(0, 0, 0, 0.1)",document.body.appendChild(MA)),MA.style.opacity=0})()}showCopyright(){(function(){MA||((MA=document.createElement("div")).style.position="fixed",MA.style.bottom="20px",MA.style.left="20px",MA.style.color="white",MA.style.textShadow="2px 2px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000",MA.style.padding="10px",MA.style.backgroundColor="rgba(0, 0, 0, 0.1)",document.body.appendChild(MA)),MA.style.opacity=1})()}}function ZC(B){var A=document.createElement("div");A.textContent=B,A.style.position="fixed",A.style.top="10px",A.style.left="50%",A.style.transform="translateX(-50%)",A.style.padding="10px",A.style.backgroundColor="#ff8800",A.style.color="#ffffff",A.style.zIndex="9999",document.body.appendChild(A),setTimeout(function(){A.remove()},8e3)}function rQ(){MA||((MA=document.createElement("div")).style.position="fixed",MA.style.bottom="20px",MA.style.left="20px",MA.style.color="white",MA.style.textShadow="2px 2px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000",MA.style.padding="10px",MA.style.backgroundColor="rgba(0, 0, 0, 0.1)",document.body.appendChild(MA));const B=Ue();let A="";B.forEach(g=>{A+=g+", "}),A=A.slice(0,-2),MA.textContent=A}const ag=new Y.Sphere(new Y.Vector3(0,0,0),1),Vg=new Y.Vector3(0,0,0),sQ=new Y.Vector3(0,0,0),eo=new Y.Vector3(0,1,0),cQ=new Y.Vector2,_C=new Y.Quaternion,$C=new Y.Matrix4;class vQ extends Y.Object3D{constructor(A){super();const g=this;if(A.queryParams&&(this.queryParams={...A.queryParams}),this.uuid=Va(),A.tileLoader?this.tileLoader=A.tileLoader:console.error("an instanced tileset must be provided an InstancedTilesetLoader"),this.master=A.master,this.loadOutsideView=A.loadOutsideView,this.cameraOnLoad=A.cameraOnLoad,this.parentTile=A.parentTile,this.distanceBias=Math.max(1e-4,A.distanceBias?A.distanceBias:1),this.childrenTiles=[],this.jsonChildren=[],this.meshContent=new Set,this.static=A.static,this.static&&(this.matrixAutoUpdate=!1,this.matrixWorldAutoUpdate=!1),this.tileContent,this.refinement,this.rootPath,this.geometricError,this.boundingVolume,this.json,this.materialVisibility=!1,this.inFrustum=!0,this.level=A.level?A.level:0,this.hasMeshContent=0,this.hasUnloadedJSONContent=0,this.centerModel=A.centerModel,this.deleted=!1,this.abortController=new AbortController,A.json)this.rootPath=A.json.rootPath?A.json.rootPath:A.rootPath,A.json.children&&(this.jsonChildren=A.json.children),g.setup(A);else if(A.url){this.loadJson=(C,a)=>{const e=iI.dirname(a);g.setup({rootPath:e,json:C,onLoadCallback:A.onLoadCallback})};var I=A.url;if(g.queryParams){var Q="";for(let C in g.queryParams)g.queryParams.hasOwnProperty(C)&&(Q+="&"+C+"="+g.queryParams[C]);I.includes("?")?I+=Q:I+="?"+Q.substring(1)}g.tileLoader.get(g.abortController,I,g.uuid,g)}}async setup(A){const g=this;A.json.root?(g.json=A.json.root,!g.json.children&&g.json.getChildren&&(g.json.children=await g.json.getChildren()),g.jsonChildren=g.json.children,g.json.refinement||(g.json.refinement=A.json.refinement),g.json.geometricError||(g.json.geometricError=A.json.geometricError),g.json.transform||(g.json.transform=A.json.transform),g.json.boundingVolume||(g.json.boundingVolume=A.json.boundingVolume)):(g.json=A.json,!g.json.children&&g.json.getChildren&&(g.json.children=await g.json.getChildren(),g.jsonChildren=g.json.children)),g.rootPath=A.json.rootPath?A.json.rootPath:A.rootPath,g.json.refinement?g.refinement=g.json.refinement:g.refinement=A.parentRefinement,g.json.geometricError?g.geometricError=g.json.geometricError:g.geometricError=A.parentGeometricError;let I=new Y.Matrix4;if(g.json.transform&&!g.centerModel&&(I.elements=g.json.transform),g.applyMatrix4(I),g.parentTile&&g.parentTile.matrix&&(g.matrix.premultiply(g.parentTile.matrix),g.matrix.decompose(g.position,g.quaternion,g.scale)),g.matrixWorldNeedsUpdate=!0,g.updateWorldMatrix(!0,!0),g.json.boundingVolume)if(g.json.boundingVolume.box)g.boundingVolume=new tg(g.json.boundingVolume.box);else if(g.json.boundingVolume.region){const C=g.json.boundingVolume.region;g.transformWGS84ToCartesian(C[0],C[1],C[4],Vg),g.transformWGS84ToCartesian(C[2],C[3],C[5],sQ),Vg.lerp(sQ,.5),g.boundingVolume=new Y.Sphere(new Y.Vector3(Vg.x,Vg.y,Vg.z),Vg.distanceTo(sQ))}else if(g.json.boundingVolume.sphere){const C=g.json.boundingVolume.sphere;g.boundingVolume=new Y.Sphere(new Y.Vector3(C[0],C[1],C[2]),C[3])}else g.boundingVolume=A.parentBoundingVolume;else g.boundingVolume=A.parentBoundingVolume;function Q(C){C.uri&&C.uri.includes("json")||C.url&&C.url.includes("json")?g.hasUnloadedJSONContent++:g.hasMeshContent++}if(g.json.content?(Q(g.json.content),g.load()):g.json.contents&&(g.json.contents.forEach(C=>Q(C)),g.load()),g.centerModel){const C=new Y.Sphere;g.boundingVolume instanceof tg?C.copy(g.boundingVolume.sphere):g.boundingVolume instanceof Y.Sphere&&C.copy(g.boundingVolume),this.json.boundingVolume.region&&(g.transformWGS84ToCartesian(.5*(g.json.boundingVolume.region[0]+g.json.boundingVolume.region[2]),.5*(g.json.boundingVolume.region[1]+g.json.boundingVolume.region[3]),.5*(g.json.boundingVolume.region[4]+g.json.boundingVolume.region[5]),Vg),_C.setFromUnitVectors(Vg.normalize(),eo.normalize()),g.master.applyQuaternion(_C),g.master.updateWorldMatrix(!1,!1)),$C.makeTranslation(-C.center.x*g.scale.x,-C.center.y*g.scale.y,-C.center.z*g.scale.z),g.master.matrix.multiply($C),g.master.matrix.decompose(g.master.position,g.master.quaternion,g.master.scale)}g.isSetup=!0,A.onLoadCallback&&A.onLoadCallback(g)}isAbsolutePathOrURL(A){const g=/^(?:http|https|ftp|tcp|udp):\/\/\S+/.test(A),I=A.startsWith("/")&&!A.startsWith("//");return g||I}assembleURL(A,g){A.endsWith("/")||(A+="/");const I=new URL(A);let Q=I.pathname.split("/").filter(a=>a!==""),C=g.split("/").filter(a=>a!=="");for(let a=1;a<=Q.length&&!(a>=C.length);a++)if(Q.slice(Q.length-a,Q.length).join("/")===C.slice(0,a).join("/")){for(let e=0;e<a;e++)Q.pop();break}for(;C.length>0&&C[0]==="..";)Q.pop(),C.shift();return`${I.protocol}//${I.host}/${[...Q,...C].join("/")}`}extractQueryParams(A,g){const I=new URL(A);for(let[Q,C]of I.searchParams)g[Q]=C;return I.search="",I.toString()}load(){var A=this;function g(I){let Q;I.uri?Q=I.uri:I.url&&(Q=I.url);const C=/^(?:http|https|ftp|tcp|udp):\/\/\S+/;if(C.test(A.rootPath)?C.test(Q)||(Q=A.assembleURL(A.rootPath,Q)):iI.isAbsolute(A.rootPath)&&(Q=A.rootPath+iI.sep+Q),Q=A.extractQueryParams(Q,A.queryParams),A.queryParams){var a="";for(let e in A.queryParams)A.queryParams.hasOwnProperty(e)&&(a+="&"+e+"="+A.queryParams[e]);Q.includes("?")?Q+=a:Q+="?"+a.substring(1)}Q&&(Q.includes(".b3dm")||Q.includes(".glb")||Q.includes(".gltf")?(A.contentURL=Q,A.tileLoader.get(A.abortController,Q,A.uuid,A,A.cameraOnLoad?()=>A.calculateDistanceToCamera(A.cameraOnLoad):()=>0,()=>A.getSiblings(),A.level,!A.json.boundingVolume.region,!!A.json.boundingVolume.region,A.geometricError)):Q.includes(".json")&&A.tileLoader.get(A.abortController,Q,A.uuid,A))}A.deleted||(A.json.content?g(A.json.content):A.json.contents&&A.json.contents.forEach(I=>g(I)))}loadMesh(A){this.deleted||this.meshContent.add(A)}loadJson(A,g){this.deleted||(this.json.children&&(this.jsonChildren=this.json.children),A.rootPath=iI.dirname(g),this.jsonChildren.push(A),this.hasUnloadedJSONContent--)}dispose(){const A=this;A.childrenTiles.forEach(g=>g.dispose()),A.deleted=!0,A.abortController&&A.abortController.abort(),this.parent=null,this.parentTile=null,this.dispatchEvent({type:"removed"})}disposeChildren(){this.childrenTiles.forEach(A=>A.dispose()),this.childrenTiles=[]}_update(A,g){const I=this;function Q(C){if(I.hasMeshContent&&!(I.meshContent.size<I.hasMeshContent)){if(C<0)return I.inFrustum=!1,void I.changeContentVisibility(!!I.loadOutsideView);if(I.inFrustum=!0,I.childrenTiles.length!=0){if(C>=I.master.geometricErrorMultiplier*I.geometricError)I.changeContentVisibility(!0);else if(C<I.master.geometricErrorMultiplier*I.geometricError){let a=!0;I.childrenTiles.every(e=>!!e.isReady()||(a=!1,!1)),a&&I.changeContentVisibility(!1)}}else I.changeContentVisibility(!0)}}I.isSetup&&(I.materialVisibility,I.boundingVolume&&I.geometricError&&(I.metric=I.calculateUpdateMetric(A,g)),I.childrenTiles.forEach(C=>C._update(A,g)),Q(I.metric),function(C){C<0&&I.hasMeshContent||(!I.hasMeshContent&&I.rootPath||C<I.master.geometricErrorMultiplier*I.geometricError&&I.meshContent.size>0)&&I.json&&I.jsonChildren&&I.childrenTiles.length!=I.jsonChildren.length&&I.jsonChildren.forEach(a=>{if(!(a.root||a.children||a.getChildren||a.content||a.contents))return;let e=new vQ({parentTile:I,queryParams:I.queryParams,parentGeometricError:I.geometricError,parentBoundingVolume:I.boundingVolume,parentRefinement:I.refinement,json:a,rootPath:I.rootPath,loadOutsideView:I.loadOutsideView,level:I.level+1,tileLoader:I.tileLoader,cameraOnLoad:A,master:I.master,centerModel:!1});I.childrenTiles.push(e)})}(I.metric),function(C){if(I.hasMeshContent){if(!I.inFrustum)return I.disposeChildren(),void Q(C);C>=I.master.geometricErrorMultiplier*I.geometricError&&(I.disposeChildren(),Q(C))}}(I.metric))}areAllChildrenLoadedAndHidden(){let A=!0;return this.childrenTiles.every(g=>{if(g.hasMeshContent){if(g.childrenTiles.length>0)return A=!1,!1;if(!g.inFrustum)return!0;if(!g.materialVisibility||g.meshesToDisplay!=g.meshesDisplayed)return A=!1,!1}else if(!g.areAllChildrenLoadedAndHidden())return A=!1,!1;return!0}),A}isReady(){if(!this.inFrustum)return!0;if(this.hasUnloadedJSONContent)return!1;if(!this.hasMeshContent||this.meshContent.size==0||!this.materialVisibility){if(this.childrenTiles.length>0){var A=!0;return this.childrenTiles.every(g=>!!g.isReady()||(A=!1,!1)),A}return!1}return!this.hasMeshContent||!(this.meshContent.size<this.hasMeshContent)&&!!this.materialVisibility}changeContentVisibility(A){this.materialVisibility=A}calculateUpdateMetric(A,g){if(this.boundingVolume instanceof tg){if(ag.copy(this.boundingVolume.sphere),ag.applyMatrix4(this.matrixWorld),!g.intersectsSphere(ag))return-1}else{if(!(this.boundingVolume instanceof Y.Sphere))return console.error("unsupported shape"),-1;if(ag.copy(this.boundingVolume),ag.applyMatrix4(this.matrixWorld),!g.intersectsSphere(ag))return-1}let I=Math.max(0,A.position.distanceTo(ag.center)-ag.radius);if(I=Math.pow(I,this.distanceBias),I==0)return 0;const Q=this.matrixWorld.getMaxScaleOnAxis();this.master._renderSize(cQ);let C=cQ.y,a=A.fov;A.aspect<1&&(a*=A.aspect,C=cQ.x);let e=2*Math.tan(.5*a*.017453292519943295)*I;return 16*window.devicePixelRatio*e/(C*Q)}getSiblings(){const A=this,g=[];if(!A.parentTile)return g;let I=A.parentTile;for(;!I.hasMeshContent&&I.parentTile;)I=I.parentTile;return I.childrenTiles.forEach(Q=>{if(Q&&Q!=A){for(;!Q.hasMeshContent&&Q.childrenTiles[0];)Q=Q.childrenTiles[0];g.push(Q)}}),g}calculateDistanceToCamera(A){return this.boundingVolume instanceof tg?(ag.copy(this.boundingVolume.sphere),ag.applyMatrix4(this.matrixWorld)):this.boundingVolume instanceof Y.Sphere?(ag.copy(this.boundingVolume),ag.applyMatrix4(this.matrixWorld)):console.error("unsupported shape"),Math.max(0,A.position.distanceTo(ag.center)-ag.radius)}getWorldMatrix(){return this.matrixWorld}transformWGS84ToCartesian(A,g,I,Q){const C=6378137/Math.sqrt(1-.006694384442042*Math.pow(Math.sin(g),2)),a=Math.cos(g),e=Math.cos(A),i=Math.sin(g),t=C+I,E=t*a*e,o=t*a*Math.sin(A),r=(.993305615557957*C+I)*i;Q.set(E,o,r)}}class Eo extends Y.Object3D{constructor(A){super(),A.master=this,A.domWidth&&A.domHeight?this.rendererSize=new Y.Vector2(A.domWidth,A.domHeight):this.rendererSize=new Y.Vector2(1e3,1e3),this.renderer=A.renderer,this.distanceBias=Math.max(1e-4,A.distanceBias?A.distanceBias:1),this.geometricErrorMultiplier=A.geometricErrorMultiplier?A.geometricErrorMultiplier:1,this.tileset=new vQ(A),A.static&&(this.matrixAutoUpdate=!1),this.tileLoader=A.tileLoader}_renderSize(A){this.renderer?this.renderer.getDrawingBufferSize(A):A.copy(this.rendererSize)}setCanvasSize(A,g){this.rendererSize.set(A,g)}update(A,g){if(g)this.tileset._update(A,g);else{const I=new Y.Frustum;I.setFromProjectionMatrix(new Y.Matrix4().multiplyMatrices(A.projectionMatrix,A.matrixWorldInverse)),this.tileset._update(A,I)}}setGeometricErrorMultiplier(A){this.geometricErrorMultiplier=A||1}}class io{constructor(A){const g=this;g.scene=A,g.instancedTiles=[],g.instancedMesh,g.reuseableMatrix=new Y.Matrix4}addInstance(A){const g=this;A.added=!0,A.listOMesh=g.instancedTiles,g.instancedTiles.push(A),g.instancedMesh&&A.loadMesh(g.instancedMesh)}addToScene(){const A=this;A.instancedMesh.setMatrixAt(0,new Y.Matrix4),A.instancedMesh.instanceMatrix.needsUpdate=!0,A.instancedMesh.count=1,A.scene.add(A.instancedMesh),A.instancedMesh.onAfterRender=()=>{delete A.instancedMesh.onAfterRender,A.instancedMesh.displayedOnce=!0}}setObject(A){const g=this;g.instancedMesh=A,g.instancedMesh.matrixAutoUpdate=!1,g.instancedMesh.matrixWorldAutoUpdate=!1,g.scene.children.includes(A)||this.addToScene();for(let I=0;I<g.instancedTiles.length;I++)g.instancedTiles[I].loadMesh(g.instancedMesh)}update(){const A=this;for(let g=A.instancedTiles.length-1;g>=0;g--)A.instancedTiles[g].deleted&&A.instancedTiles.splice(g,1);if(A.instancedMesh){A.instancedMesh.count=0,A.instancedMesh.instancedTiles=[];for(let g=0;g<A.instancedTiles.length;g++)A.instancedTiles[g].meshContent.add(A.instancedMesh),A.instancedTiles[g].materialVisibility&&(A.instancedMesh.count++,A.reuseableMatrix.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),A.reuseableMatrix.multiply(A.instancedTiles[g].matrixWorld),A.reuseableMatrix.multiply(A.instancedMesh.baseMatrix),A.instancedMesh.setMatrixAt(A.instancedMesh.count-1,A.reuseableMatrix),A.instancedMesh.instancedTiles.push(A.instancedTiles[g]));A.instancedMesh.instanceMatrix.needsUpdate=!0,A.instancedMesh.needsUpdate=!0,A.instancedMesh.computeBoundingSphere()}}getCount(){return this.instancedTiles.length}dispose(){const A=this;return!(A.instancedTiles.length>0)&&!!A.instancedMesh&&(A.scene.remove(A.instancedMesh),A.instancedMesh.traverse(g=>{if(g.dispose&&g.dispose(),g.material)if(g.material.length)for(let I=0;I<g.material.length;++I)g.material[I].dispose();else g.material.dispose();g.geometry&&g.geometry.dispose()}),A.instancedMesh.dispose(),!0)}}class to{constructor(){const A=this;A.count=0,A.json,A.instancedTiles=[]}addInstance(A){this.instancedTiles.push(A),this.json&&A.loadJson(this.json,this.url)}setObject(A,g){const I=this;I.json=A,I.url=g;for(let Q=0;Q<I.instancedTiles.length;Q++)I.instancedTiles[Q].loadJson(I.json,I.url)}getCount(){return this.instancedTiles.length}update(){const A=this;for(let g=A.instancedTiles.length-1;g>=0;g--)A.instancedTiles[g].deleted&&A.instancedTiles.splice(g,1)}dispose(){return!(!this.json||this.instancedTiles.length!=0)}}let CI=0;async function oo(B){return new Promise(A=>{const g=setInterval(()=>{B.hasDracoLoader&&!B.dracoLoader||B.hasKTX2Loader&&!B.ktx2Loader||(clearInterval(g),A())},10)})}function no(B){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/physicsRapier.worker-D664sBAY.js").href:new URL("assets/physicsRapier.worker-D664sBAY.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{type:"module",name:B?.name})}function ro(B){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/physicsHelper.worker-Cr8S3sZk.js").href:new URL("assets/physicsHelper.worker-Cr8S3sZk.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{type:"module",name:B?.name})}function Eg(B,A=[0,-9.81,0]){return B?Array.isArray(B)&&B.length===3?[Number(B[0]),Number(B[1]),Number(B[2])]:B.isVector3?[B.x,B.y,B.z]:typeof B=="object"&&"x"in B&&"y"in B&&"z"in B?[Number(B.x),Number(B.y),Number(B.z)]:A.slice():A.slice()}function OI(B,A=[0,0,0,1]){if(!B)return A.slice();if(Array.isArray(B)&&B.length===4)return[Number(B[0]),Number(B[1]),Number(B[2]),Number(B[3])];if(B.isQuaternion)return[B.x,B.y,B.z,B.w];if(B.isEuler){const g=new Y.Quaternion().setFromEuler(B);return[g.x,g.y,g.z,g.w]}return A.slice()}function Aa(B){if(Array.isArray(B)||B&&B.isVector3)return{mode:"vector",vector:Eg(B)};const A=B||{};return(A.mode||"vector").toLowerCase()==="geocentric"?{mode:"geocentric",planetCenter:Eg(A.planetCenter||[0,0,0],[0,0,0]),intensity:typeof A.intensity=="number"?A.intensity:9.81}:{mode:"vector",vector:Eg(A.vector||A,[0,-9.81,0])}}function hB(){return typeof performance<"u"&&performance.now?performance.now():Date.now()}exports.ColliderShape=NQ,exports.InstancedOGC3DTile=Eo,exports.InstancedTileLoader=class{constructor(B,A){if(this.zUpToYUpMatrix=new Y.Matrix4,this.zUpToYUpMatrix.set(1,0,0,0,0,0,-1,0,0,1,0,0,0,0,0,1),this.maxCachedItems=100,this.maxInstances=1,this.proxy=A.proxy,A&&(this.meshCallback=A.meshCallback,this.pointsCallback=A.pointsCallback,A.maxCachedItems&&(this.maxCachedItems=A.maxCachedItems),A.maxInstances&&(this.maxInstances=A.maxInstances)),this.gltfLoader=new Ca,A&&A.dracoLoader)this.gltfLoader.setDRACOLoader(A.dracoLoader),this.hasDracoLoader=!0;else{const g=new Ea;g.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.4.3/"),this.gltfLoader.setDRACOLoader(g),this.gltfLoader.hasDracoLoader=!0}if(A&&A.ktx2Loader)this.gltfLoader.setKTX2Loader(A.ktx2Loader),this.hasKTX2Loader=!0;else if(A&&A.renderer){const g=new Dg;g.setTranscoderPath("https://storage.googleapis.com/ogc-3d-tiles/basis/").detectSupport(A.renderer),this.gltfLoader.setKTX2Loader(g),this.gltfLoader.hasKTX2Loader=!0}this.gltfLoader.setMeshoptDecoder(Wa),this.hasMeshOptDecoder=!0,this.b3dmDecoder=new Ba(this.gltfLoader),this.cache=new ga,this.scene=B,this.ready=[],this.downloads=[],this.nextReady=[],this.nextDownloads=[]}update(){const B=this;B._checkSize(),B.cache._data.forEach(A=>{A.update()}),CI<8&&B._download(),B._loadBatch()}_download(){const B=this;if(B.nextDownloads.length!=0||(B._getNextDownloads(),B.nextDownloads.length!=0))for(;B.nextDownloads.length>0;){const g=B.nextDownloads.shift();if(g){if(g.path.includes(".b3dm")&&(A=B.proxy?()=>fetch(B.proxy,{method:"POST",body:g.path}):()=>fetch(g.path),CI++,A().then(I=>{if(!I.ok)throw console.error("could not load tile with path : "+g.path),new Error(`couldn't load "${g.path}". Request failed with status ${I.status} : ${I.statusText}`);return I.arrayBuffer()}).then(I=>this.b3dmDecoder.parseB3DMInstanced(I,Q=>{B.meshCallback(Q,g.geometricError)},B.maxInstances,g.sceneZupToYup,g.meshZupToYup)).then(I=>{I.frustumCulled=!1,g.tile.setObject(I),B.ready.unshift(g)}).catch(I=>console.error(I)).finally(()=>{CI--})),g.path.includes(".glb")||g.path.includes(".gltf"))A=B.proxy?()=>fetch(B.proxy,{method:"POST",body:g.path}):()=>fetch(g.path),CI++,A().then(I=>{if(!I.ok)throw new Error("missing content");return I.arrayBuffer()}).then(async I=>{await oo(this.gltfLoader),this.gltfLoader.parse(I,null,Q=>{let C;Q.scene.asset=Q.asset,g.sceneZupToYup&&Q.scene.applyMatrix4(this.zUpToYUpMatrix),Q.scene.traverse(a=>{a.geometricError=g.geometricError,a.isMesh&&(g.meshZupToYup&&a.applyMatrix4(this.zUpToYUpMatrix),B.meshCallback&&B.meshCallback(a,a.geometricError)),a.isPoints&&console.error("instanced point cloud is not supported")}),Q.scene.updateWorldMatrix(!1,!0),Q.scene.traverse(a=>{a.isMesh&&(C=new Y.InstancedMesh(a.geometry,a.material,B.maxInstances),C.baseMatrix=a.matrixWorld)}),B.ready.unshift(g),C?(C.frustumCulled=!1,g.tile.setObject(C)):Q.scene.traverse(a=>{a.dispose&&a.dispose(),a.material&&a.material.dispose()})})},I=>{console.error("could not load tile : "+g.path)}).finally(()=>{CI--});else if(g.path.includes(".json")){var A;A=B.proxy?()=>fetch(B.proxy,{method:"POST",body:g.path}):()=>fetch(g.path),CI++,A().then(I=>{if(!I.ok)throw console.error("could not load tile with path : "+g.path),new Error(`couldn't load "${g.path}". Request failed with status ${I.status} : ${I.statusText}`);return I.json()}).then(I=>mQ(I,g.path)).then(I=>{g.tile.setObject(I,g.path),B.ready.unshift(g)}).catch(I=>console.error(I)).finally(()=>{CI--})}}}}_loadBatch(){return this.nextReady.length==0&&(this._getNextReady(),this.nextReady.length==0)?0:this.nextReady.shift()?1:0}_getNextReady(){let B=Number.MAX_VALUE,A=-1;for(let g=this.ready.length-1;g>=0;g--)this.ready[g].distanceFunction||this.nextReady.push(this.ready.splice(g,1)[0]);if(!(this.nextReady.length>0)){for(let g=this.ready.length-1;g>=0;g--){const I=this.ready[g].distanceFunction()*this.ready[g].level;I<B&&(B=I,A=g)}if(A>=0){const g=this.ready.splice(A,1).pop();this.nextReady.push(g);const I=g.getSiblings();for(let Q=this.ready.length-1;Q>=0;Q--)I.includes(this.ready[Q].uuid)&&this.nextready.push(this.ready.splice(Q,1).pop())}}}get(B,A,g,I,Q,C,a,e,i,t){const E=this,o=function(n){for(var s=n.split("/"),c=[],D=0,d=0;d<s.length;d++){var h=s[d];h!=="."&&h!==""&&h!==".."?c[D++]=h:h===".."&&D>0&&D--}if(D===0)return"/";var l="";for(d=0;d<D;d++)l+="/"+c[d];return l}(A);if(!(A.includes(".b3dm")||A.includes(".json")||A.includes(".glb")||A.includes(".gltf")))return void console.error("the 3DTiles cache can only be used to load B3DM, gltf and json data");const r=E.cache.get(o);if(r)r.addInstance(I);else if(A.includes(".b3dm")||A.includes(".glb")||A.includes(".gltf")){const n=new io(E.scene);n.addInstance(I),E.cache.put(o,n);const s=new AbortController;B.signal.addEventListener("abort",()=>{n.getCount()==0&&s.abort()}),this.downloads.push({abortController:s,tile:n,key:o,path:A,distanceFunction:Q,getSiblings:C,level:a,uuid:g,sceneZupToYup:e,meshZupToYup:i,geometricError:t,shouldDoDownload:()=>!0})}else if(A.includes(".json")){const n=new to;n.addInstance(I),E.cache.put(o,n);const s=new AbortController;B.signal.addEventListener("abort",()=>{n.getCount()==0&&s.abort()}),this.downloads.push({abortController:s,tile:n,key:o,path:A,distanceFunction:Q,getSiblings:C,level:a,shouldDoDownload:()=>!0})}}_getNextDownloads(){let B=Number.MAX_VALUE,A=-1;for(let g=this.downloads.length-1;g>=0;g--){const I=this.downloads[g];I.shouldDoDownload()?I.distanceFunction||this.nextDownloads.push(this.downloads.splice(g,1)[0]):this.downloads.splice(g,1)}if(!(this.nextDownloads.length>0)){for(let g=this.downloads.length-1;g>=0;g--){const I=this.downloads[g],Q=I.distanceFunction()*I.level;Q<B&&(B=Q,A=g)}if(A>=0){const g=this.downloads.splice(A,1).pop();this.nextDownloads.push(g);const I=g.getSiblings();for(let Q=this.downloads.length-1;Q>=0;Q--)I.includes(this.downloads[Q].uuid)&&this.nextDownloads.push(this.downloads.splice(Q,1).pop())}}}_checkSize(){const B=this;let A=0;for(;B.cache.size()>B.maxCachedItems&&A<B.cache.size();){A++;const g=B.cache.head();B.cache.remove(g.key),g.value.dispose()||B.cache.put(g.key,g.value)}}},exports.OBB=tg,exports.OGC3DTile=jQ,exports.OcclusionCullingService=class{constructor(){this.cullMap=[],this.cullMaterial=new Y.MeshBasicMaterial({vertexColors:!0}),this.cullMaterial.side=Y.FrontSide,this.cullTarget=this._createCullTarget(),this.cullPixels=new Uint8Array(4*this.cullTarget.width*this.cullTarget.height)}setSide(B){this.cullMaterial.side=B}_createCullTarget(){const B=new Y.WebGLRenderTarget(Math.floor(.05*window.innerWidth),Math.floor(.05*window.innerHeight));return B.texture.format=Y.RGBAFormat,B.texture.colorSpace=Y.LinearSRGBColorSpace,B.texture.minFilter=Y.NearestFilter,B.texture.magFilter=Y.NearestFilter,B.texture.generateMipmaps=!1,B.stencilBuffer=!1,B.depthBuffer=!0,B.depthTexture=new Y.DepthTexture,B.depthTexture.format=Y.DepthFormat,B.depthTexture.type=Y.UnsignedShortType,B}update(B,A,g){let I=A.getRenderTarget(),Q=B.overrideMaterial;B.overrideMaterial=this.cullMaterial,A.setRenderTarget(this.cullTarget),A.render(B,g),B.overrideMaterial=Q,A.setRenderTarget(I),A.readRenderTargetPixels(this.cullTarget,0,0,this.cullTarget.width,this.cullTarget.height,this.cullPixels),this.cullMap=[];for(let C=0;C<this.cullPixels.length;C+=4){const a=Y.MathUtils.clamp(this.cullPixels[C],0,255)<<16^Y.MathUtils.clamp(this.cullPixels[C+1],0,255)<<8^Y.MathUtils.clamp(this.cullPixels[C+2],0,255);this.cullMap[a]=!0}}hasID(B){return this.cullMap[B]}},exports.Physics=class{constructor(B={}){this.updateIntervalMs=typeof B.updateIntervalMs=="number"?B.updateIntervalMs:16,this.fixedDt=typeof B.fixedDt=="number"?B.fixedDt:this.updateIntervalMs/1e3,this.gravity=Aa(B.gravity),this.autoStart=B.autoStart!==!1,this.sharedMemorySupported=typeof SharedArrayBuffer<"u"&&!(!globalThis||!globalThis.crossOriginIsolated),this.worker=new no({}),this._msgId=0,this._pending=new Map,this._onWorkerMessage=this._onWorkerMessage.bind(this),this.worker.onmessage=this._onWorkerMessage,this.worker.onerror=A=>{console.error("Physics worker error:",A?.message||A)},this.helperWorker=null,this._helperMsgId=0,this._helperPending=new Map,this._onHelperMessage=this._onHelperMessage?this._onHelperMessage.bind(this):A=>{},this._paused=!1,this._lastTickTime=hB(),this._lastState=null,this._currentState=null,this._interpolationMax=1.25,this._nextBodyId=1,this._nextColliderId=1,this.rigidBodies=new Map,this.bodyToColliders=new Map,this.colliderToBody=new Map,this._listeners=new Map,this._initPromise=this._post({type:"init",gravity:this.gravity,sharedMemorySupported:this.sharedMemorySupported,fixedDt:this.fixedDt}),this.autoStart&&this._initPromise.then(()=>{this._scheduleNextTick()}).catch(A=>{console.error("Physics init failed:",A)})}addObject(B={}){const A="rb-"+this._nextBodyId++,g=(B.type||"dynamic").toLowerCase(),I=typeof B.mass=="number"?B.mass:1,Q=Eg(B.position,[0,0,0]),C=OI(B.rotation,[0,0,0,1]),a=B.velocity?Eg(B.velocity,[0,0,0]):void 0,e=B.angularVelocity?Eg(B.angularVelocity,[0,0,0]):void 0;return this.rigidBodies.set(A,{id:A,object:B.object||null,type:g,mass:I,last:{p:Q,q:C},current:{p:Q.slice(),q:C.slice()}}),this.bodyToColliders.set(A,new Set),this._post({type:"addObject",id:A,body:{type:g,mass:I,p:Q,q:C,v:a,w:e}}),A}attachTrimeshCollider({bodyId:B,geometry:A,positions:g,indices:I,localPosition:Q,localRotation:C,localScale:a}){if(!this.rigidBodies.has(B))return console.warn(`attachTrimeshCollider: unknown bodyId ${B}`),Promise.resolve(null);let e=null,i=null;if(A&&A.isBufferGeometry){const D=A.getAttribute("position");if(D)if(D.isInterleavedBufferAttribute){const h=D.count;e=new Float32Array(3*h);for(let l=0;l<h;l++)e[3*l+0]=D.getX(l),e[3*l+1]=D.getY(l),e[3*l+2]=D.getZ(l)}else D.array&&(e=new Float32Array(D.array));else console.warn("attachTrimeshCollider: geometry has no position attribute");const d=A.getIndex?.();if(d&&d.array){const h=d.array;i=new Uint32Array(h)}}else g&&(e=Array.isArray(g)||g instanceof Float32Array?new Float32Array(g):new Float32Array(g.buffer||g)),I&&(i=Array.isArray(I)||I instanceof Uint32Array?new Uint32Array(I):new Uint32Array(I.buffer||I));if(!(e instanceof Float32Array))return console.warn("attachTrimeshCollider: missing or invalid positions buffer"),Promise.resolve(null);const t=Q?Eg(Q,[0,0,0]):[0,0,0],E=C?OI(C,[0,0,0,1]):[0,0,0,1],o=Array.isArray(a)&&a.length===3?[Number(a[0]),Number(a[1]),Number(a[2])]:[1,1,1],r="col-"+this._nextColliderId++,n=this.bodyToColliders.get(B)||new Set;n.add(r),this.bodyToColliders.set(B,n),this.colliderToBody.set(r,B);const s={type:"attachTrimeshCollider",id:r,bodyId:B,positions:e,indices:i||null,local:{p:t,q:E,s:o}},c=[];return e?.buffer&&c.push(e.buffer),i?.buffer&&c.push(i.buffer),this._post(s,c).then(()=>r)}addConvexHullCollider({bodyId:B,geometry:A,positions:g,indices:I,localPosition:Q,localRotation:C,localScale:a}){if(!this.rigidBodies.has(B))return console.warn(`addConvexHullCollider: unknown bodyId ${B}`),Promise.resolve(null);let e=null,i=null;if(A&&A.isBufferGeometry){const D=A.getAttribute("position");if(D)if(D.isInterleavedBufferAttribute){const h=D.count;e=new Float32Array(3*h);for(let l=0;l<h;l++)e[3*l+0]=D.getX(l),e[3*l+1]=D.getY(l),e[3*l+2]=D.getZ(l)}else D.array&&(e=new Float32Array(D.array));else console.warn("addConvexHullCollider: geometry has no position attribute");const d=A.getIndex?.();if(d&&d.array){const h=d.array;i=new Uint32Array(h)}}else g&&(e=Array.isArray(g)||g instanceof Float32Array?new Float32Array(g):new Float32Array(g.buffer||g)),I&&(i=Array.isArray(I)||I instanceof Uint32Array?new Uint32Array(I):new Uint32Array(I.buffer||I));if(!(e instanceof Float32Array))return console.warn("addConvexHullCollider: missing or invalid positions buffer"),Promise.resolve(null);const t=Q?Eg(Q,[0,0,0]):[0,0,0],E=C?OI(C,[0,0,0,1]):[0,0,0,1],o=Array.isArray(a)&&a.length===3?[Number(a[0]),Number(a[1]),Number(a[2])]:[1,1,1],r="col-"+this._nextColliderId++,n=this.bodyToColliders.get(B)||new Set;n.add(r),this.bodyToColliders.set(B,n),this.colliderToBody.set(r,B);const s={type:"computeConvexHull",positions:e,indices:i||null,localScale:o},c=[];return e?.buffer&&c.push(e.buffer),i?.buffer&&c.push(i.buffer),this._helperPost(s,c).then(D=>{const d=D?.vertices;if(!(d instanceof Float32Array)||d.length<9)throw new Error("convex hull computation failed or returned insufficient vertices");const h={type:"attachShapeCollider",id:r,bodyId:B,shape:{kind:"convexHull",params:{vertices:d}},local:{p:t,q:E}},l=[];return d?.buffer&&l.push(d.buffer),this._post(h,l).then(()=>r)}).catch(D=>{const d=this.bodyToColliders.get(B);return d&&d.delete(r),this.colliderToBody.delete(r),console.warn("addConvexHullCollider failed:",D),null})}attachShapeCollider({bodyId:B,shape:A,localPosition:g,localRotation:I}){if(!this.rigidBodies.has(B))return console.warn(`attachShapeCollider: unknown bodyId ${B}`),Promise.resolve(null);if(!A||typeof A!="object")return console.warn("attachShapeCollider: missing or invalid shape descriptor"),Promise.resolve(null);const Q=g?Eg(g,[0,0,0]):[0,0,0],C=I?OI(I,[0,0,0,1]):[0,0,0,1],a="col-"+this._nextColliderId++,e=this.bodyToColliders.get(B)||new Set;e.add(a),this.bodyToColliders.set(B,e),this.colliderToBody.set(a,B);const i={type:"attachShapeCollider",id:a,bodyId:B,shape:A,local:{p:Q,q:C}};return this._post(i),a}detachCollider({colliderId:B}){const A=this.colliderToBody.get(B);if(!A)return;const g=this.bodyToColliders.get(A);g&&g.delete(B),this.colliderToBody.delete(B),this._post({type:"detachCollider",colliderId:B})}removeObject({bodyId:B}){if(!this.rigidBodies.has(B))return;const A=this.bodyToColliders.get(B);if(A)for(const g of A)this.colliderToBody.delete(g);this.bodyToColliders.delete(B),this.rigidBodies.delete(B),this._post({type:"removeObject",id:B})}applyForce({bodyId:B,force:A,worldPoint:g,wake:I=!0,impulse:Q=!1}){if(!this.rigidBodies.has(B))return void console.warn(`applyForce: unknown bodyId ${B}`);const C=Eg(A,[0,0,0]),a=g?Eg(g,[0,0,0]):void 0;this._post({type:"applyForce",id:B,force:C,point:a,wake:!!I,impulse:!!Q})}setGravity(B){this.gravity=Aa(B),this._post({type:"setGravity",gravity:this.gravity})}setPose({bodyId:B,position:A,rotation:g,wake:I=!0}){if(!this.rigidBodies.has(B))return void console.warn(`setPose: unknown bodyId ${B}`);const Q=A!=null?Eg(A,[0,0,0]):null,C=g!=null?OI(g,[0,0,0,1]):null;this._post({type:"setPose",id:B,p:Q,q:C,wake:!!I});const a=this.rigidBodies.get(B);a&&(Q&&(a.last.p=Q.slice(),a.current.p=Q.slice(),a.object?.isObject3D&&a.object.position.set(Q[0],Q[1],Q[2])),C&&(a.last.q=C.slice(),a.current.q=C.slice(),a.object?.isObject3D&&a.object.quaternion.set(C[0],C[1],C[2],C[3])),a.object?.isObject3D&&(a.object.updateMatrices?a.object.updateMatrices():(a.object.matrixAutoUpdate!==!1&&a.object.updateMatrix(),a.object.matrixWorldAutoUpdate!==!1&&a.object.updateMatrixWorld(!0))))}raycast({origin:B,direction:A,maxToi:g=1e6,filter:I}){const Q=Eg(B,[0,0,0]),C=Eg(A,[0,-1,0]);return this._post({type:"raycast",origin:Q,direction:C,maxToi:g,filter:I||null})}pause(){this._paused=!0}resume(){this._paused&&(this._paused=!1,this._lastTickTime=hB(),this._scheduleNextTick())}setUpdateInterval(B){this.updateIntervalMs=Math.max(1,Number(B)||16)}stepOnce(B){const A=typeof B=="number"?B:this.fixedDt;return this._post({type:"step",dt:A})}update(){if(!this._currentState)return;const B=this._lastState||this._currentState,A=this._currentState,g=hB(),I=B.timeMs||g,Q=A.timeMs||g,C=Math.max(.001,Q-I);let a=Y.MathUtils.clamp((g-Q)/C+1,0,this._interpolationMax);a=Y.MathUtils.clamp(a,0,1);const e=new Y.Quaternion,i=new Y.Quaternion,t=new Y.Quaternion;for(const[E,o]of this.rigidBodies.entries()){const r=B.bodies?.[E],n=A.bodies?.[E];if(!n&&!r)continue;const s=r?.p||o.current.p,c=r?.q||o.current.q,D=n?.p||o.current.p,d=n?.q||o.current.q,h=Y.MathUtils.lerp(s[0],D[0],a),l=Y.MathUtils.lerp(s[1],D[1],a),f=Y.MathUtils.lerp(s[2],D[2],a);e.set(c[0],c[1],c[2],c[3]),i.set(d[0],d[1],d[2],d[3]),t.copy(e).slerp(i,a),o.object&&o.object.isObject3D&&(o.object.position.set(h,l,f),o.object.quaternion.copy(t),o.object.updateMatrices?o.object.updateMatrices():(o.object.matrixAutoUpdate!==!1&&o.object.updateMatrix(),o.object.matrixWorldAutoUpdate!==!1&&o.object.updateMatrixWorld(!0))),o.last={p:s.slice(),q:c.slice()},o.current={p:D.slice(),q:d.slice()}}}dispose(){try{this.worker.terminate()}catch{}try{this.helperWorker?.terminate()}catch{}this.rigidBodies.clear(),this.bodyToColliders.clear(),this.colliderToBody.clear(),this._pending.clear(),this._listeners.clear(),this._lastState=null,this._currentState=null}_scheduleNextTick(){this._paused||setTimeout(()=>this._onTick(),this.updateIntervalMs)}_onTick(){if(this._paused)return;const B=hB();Math.max(1e-6,(B-this._lastTickTime)/1e3),this._lastTickTime=B,this._post({type:"step",dt:this.fixedDt}),this.update(),this._scheduleNextTick()}_onWorkerMessage(B){const A=B.data||{};if(A.replyTo){const g=this._pending.get(A.replyTo);g&&(this._pending.delete(A.replyTo),A.error?g.rej?g.rej(A.error):console.error("Physics worker error:",A.error):g.res&&g.res(A.result))}else switch(A.type){case"state":this._lastState=this._currentState,this._currentState=A.state||null,this._emit("state",this._currentState);break;case"event":this._emit("event",A.event)}}_ensureHelperWorker(){this.helperWorker||(this.helperWorker=new ro({}),this.helperWorker.onmessage=this._onHelperMessage,this.helperWorker.onerror=B=>{console.error("Physics helper worker error:",B?.message||B)})}_onHelperMessage(B){const A=B.data||{};if(A.replyTo){const g=this._helperPending.get(A.replyTo);g&&(this._helperPending.delete(A.replyTo),A.error?g.rej?g.rej(A.error):console.error("Physics helper worker error:",A.error):g.res&&g.res(A.result))}}_helperPost(B,A=[]){this._ensureHelperWorker();const g=++this._helperMsgId,I={...B,_envId:g};return this.helperWorker.postMessage(I,A),new Promise((Q,C)=>{this._helperPending.set(g,{res:Q,rej:C})})}_post(B,A=[]){const g=++this._msgId,I={...B,_envId:g};return this.worker.postMessage(I,A),new Promise((Q,C)=>{this._pending.set(g,{res:Q,rej:C})})}on(B,A){return this._listeners.has(B)||this._listeners.set(B,new Set),this._listeners.get(B).add(A),()=>this.off(B,A)}off(B,A){const g=this._listeners.get(B);g&&g.delete(A)}_emit(B,A){const g=this._listeners.get(B);if(g)for(const I of g)try{I(A)}catch(Q){console.error(Q)}}},exports.SplatsMesh=Ne,exports.TileLoader=Pa,exports.getOGC3DTilesCopyrightInfo=Ue,exports.splatsFragmentShader=me,exports.splatsVertexShader=ke;
1503
1503
  //# sourceMappingURL=threedtiles.cjs.js.map