incanto 0.25.2 → 0.25.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/2d.js +1 -1
- package/dist/3d.js +4 -4
- package/dist/{create-game-BaBDYcNj.js → create-game-K8A82JK5.js} +3 -3
- package/dist/{create-game-CO3qo_7Y.js → create-game-yGqGR-Ic.js} +1 -1
- package/dist/{gameplay-CXn_0_XD.js → gameplay-B8zVO3Dg.js} +30 -2
- package/dist/gameplay.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{physics-3d-B77uXt91.js → physics-3d-DY0EtjfT.js} +2 -2
- package/dist/react.js +1 -1
- package/dist/{register-C-q0XJAn.js → register-BgeMHtcG.js} +1 -1
- package/dist/test.js +4 -4
- package/editor/assets/{agent8-e6PNzw9c.js → agent8-DzaYTNiK.js} +1 -1
- package/editor/assets/{index-WP3vGgq9.js → index-BGtXxzJn.js} +31 -3
- package/editor/index.html +1 -1
- package/package.json +1 -1
- package/templates-app/beacon-isle-3d/package.json +1 -1
- package/templates-app/tps-3d/package.json +1 -1
- package/templates-app/village-quest-3d/package.json +1 -1
package/dist/2d.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as IncantoError } from "./errors-BpWbnbb_.js";
|
|
2
|
-
import { a as AssetStore2D, i as syncTree2D, r as Renderer2D, t as createGame2D } from "./create-game-
|
|
2
|
+
import { a as AssetStore2D, i as syncTree2D, r as Renderer2D, t as createGame2D } from "./create-game-yGqGR-Ic.js";
|
|
3
3
|
import { _ as RigidBody2D, a as parseCells, c as ColorRect2D, d as AnimatedSprite2D, f as Sprite2D, g as PhysicsBody2D, h as CharacterBody2D, i as mergeSolidRects, l as CharacterController2D, m as Area2D, n as UILayer, o as Particles2D, p as Joint2D, r as TileMap2D, s as Label, t as registerNodes2D, u as Camera2D, v as StaticBody2D, y as Node2D } from "./register-CvpSUU3O.js";
|
|
4
4
|
import { n as enablePhysics2D, t as Physics2D } from "./physics-2d-DiVFFlH3.js";
|
|
5
5
|
//#region src/2d/library-sprite.ts
|
package/dist/3d.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as IncantoError } from "./errors-BpWbnbb_.js";
|
|
2
|
-
import { A as Water3D, F as StaticBody3D, I as Node3D, M as CharacterBody3D, N as PhysicsBody3D, P as RigidBody3D, j as Area3D, z as WATER_MAX_RIPPLES } from "./gameplay-
|
|
3
|
-
import { a as Environment3D, c as sunDirectionFromElevationAzimuth, i as syncTree, l as sunDirectionFromSky, o as horizonColorFromSky, r as Renderer3D, s as parseEnvironment3D, t as createGame3D, u as AssetStore3D } from "./create-game-
|
|
4
|
-
import { A as QUARTER_PITCH, C as BoneAttachment3D, D as TERRAIN_THEMES, E as DEFAULT_TERRAIN_TEXTURE_BASE, M as keyboardIntensity, N as movementState, O as terrainThemeLayers, P as rigPose, S as BoneLookAt3D, T as Terrain3D, _ as Flowers3D, a as Trail3D, b as CharacterController3D, c as Particles3D, d as DirectionalLight3D, f as OmniLight3D, g as DENSITY_PRESETS, h as Foliage3D, i as Tree3D, j as cameraRelative, k as Joint3D, l as ModelInstance3D, m as MeshInstance3D, n as VOXEL_PALETTE, o as River3D, p as InstancedMesh3D, r as VoxelGrid3D, s as traceDownhillPath, t as registerNodes3D, u as LoftMesh3D, v as resolveFlowerDensity, w as Billboard3D, x as Camera3D, y as FLOWER_VARIETIES } from "./register-
|
|
2
|
+
import { A as Water3D, F as StaticBody3D, I as Node3D, M as CharacterBody3D, N as PhysicsBody3D, P as RigidBody3D, j as Area3D, z as WATER_MAX_RIPPLES } from "./gameplay-B8zVO3Dg.js";
|
|
3
|
+
import { a as Environment3D, c as sunDirectionFromElevationAzimuth, i as syncTree, l as sunDirectionFromSky, o as horizonColorFromSky, r as Renderer3D, s as parseEnvironment3D, t as createGame3D, u as AssetStore3D } from "./create-game-K8A82JK5.js";
|
|
4
|
+
import { A as QUARTER_PITCH, C as BoneAttachment3D, D as TERRAIN_THEMES, E as DEFAULT_TERRAIN_TEXTURE_BASE, M as keyboardIntensity, N as movementState, O as terrainThemeLayers, P as rigPose, S as BoneLookAt3D, T as Terrain3D, _ as Flowers3D, a as Trail3D, b as CharacterController3D, c as Particles3D, d as DirectionalLight3D, f as OmniLight3D, g as DENSITY_PRESETS, h as Foliage3D, i as Tree3D, j as cameraRelative, k as Joint3D, l as ModelInstance3D, m as MeshInstance3D, n as VOXEL_PALETTE, o as River3D, p as InstancedMesh3D, r as VoxelGrid3D, s as traceDownhillPath, t as registerNodes3D, u as LoftMesh3D, v as resolveFlowerDensity, w as Billboard3D, x as Camera3D, y as FLOWER_VARIETIES } from "./register-BgeMHtcG.js";
|
|
5
5
|
import { n as splatWeights, t as buildHeightmap } from "./heightmap-CRK0M4jT.js";
|
|
6
|
-
import { n as enablePhysics3D, t as Physics3D } from "./physics-3d-
|
|
6
|
+
import { n as enablePhysics3D, t as Physics3D } from "./physics-3d-DY0EtjfT.js";
|
|
7
7
|
//#region src/3d/environment-runtime.ts
|
|
8
8
|
/**
|
|
9
9
|
* Live environment editing — the renderer re-applies `scene.environment`
|
|
@@ -3,10 +3,10 @@ import { _ as registerBehavior, n as loadScene } from "./loader-BZqOKfI2.js";
|
|
|
3
3
|
import { l as AudioPlayer, u as Engine } from "./register-nObreUQR.js";
|
|
4
4
|
import { t as IncantoError } from "./errors-BpWbnbb_.js";
|
|
5
5
|
import { i as resolveRendering, n as attachTouchControls } from "./touch-031PxtCR.js";
|
|
6
|
-
import { I as Node3D, N as PhysicsBody3D, R as createCausticsQuad, n as registerGameplayBehaviors } from "./gameplay-
|
|
6
|
+
import { I as Node3D, N as PhysicsBody3D, R as createCausticsQuad, n as registerGameplayBehaviors } from "./gameplay-B8zVO3Dg.js";
|
|
7
7
|
import { t as debugSources } from "./debug-draw-CZmOYjL2.js";
|
|
8
|
-
import { d as DirectionalLight3D, l as ModelInstance3D, t as registerNodes3D, x as Camera3D } from "./register-
|
|
9
|
-
import { n as enablePhysics3D } from "./physics-3d-
|
|
8
|
+
import { d as DirectionalLight3D, l as ModelInstance3D, t as registerNodes3D, x as Camera3D } from "./register-BgeMHtcG.js";
|
|
9
|
+
import { n as enablePhysics3D } from "./physics-3d-DY0EtjfT.js";
|
|
10
10
|
import { ACESFilmicToneMapping, AmbientLight, Box3, BufferAttribute, BufferGeometry, Color, DepthTexture, EquirectangularReflectionMapping, FloatType, Fog, HalfFloatType, LineBasicMaterial, LineSegments, Matrix4, Mesh, PCFShadowMap, PMREMGenerator, PerspectiveCamera, PlaneGeometry, Quaternion, Raycaster, Scene, ShaderMaterial, Vector2, Vector3, WebGLRenderTarget, WebGLRenderer } from "three";
|
|
11
11
|
import { VRMLoaderPlugin, VRMUtils } from "@pixiv/three-vrm";
|
|
12
12
|
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
|
|
@@ -3,7 +3,7 @@ import { _ as registerBehavior, n as loadScene, o as computeViewport, s as resol
|
|
|
3
3
|
import { l as AudioPlayer, u as Engine } from "./register-nObreUQR.js";
|
|
4
4
|
import { t as IncantoError } from "./errors-BpWbnbb_.js";
|
|
5
5
|
import { i as resolveRendering, n as attachTouchControls } from "./touch-031PxtCR.js";
|
|
6
|
-
import { n as registerGameplayBehaviors } from "./gameplay-
|
|
6
|
+
import { n as registerGameplayBehaviors } from "./gameplay-B8zVO3Dg.js";
|
|
7
7
|
import { g as PhysicsBody2D, n as UILayer, t as registerNodes2D, u as Camera2D, y as Node2D } from "./register-CvpSUU3O.js";
|
|
8
8
|
import { t as debugSources } from "./debug-draw-CZmOYjL2.js";
|
|
9
9
|
import { n as enablePhysics2D } from "./physics-2d-DiVFFlH3.js";
|
|
@@ -1225,7 +1225,10 @@ float linearizeDepth(float depth, float near, float far) {
|
|
|
1225
1225
|
float waterColumnAt(vec2 uv, float linearWaterDepth, float camDist, vec3 viewDir, float surfaceY) {
|
|
1226
1226
|
float sceneD = linearizeDepth(texture2D(uDepthTexture, uv).r, uCameraNear, uCameraFar);
|
|
1227
1227
|
float t = camDist * (sceneD / max(linearWaterDepth, 1e-4));
|
|
1228
|
-
|
|
1228
|
+
// SIGNED on purpose: negative means the sample sticks up THROUGH the water
|
|
1229
|
+
// (a wader, a hull, a rock), and that is how a shoreline is told apart from
|
|
1230
|
+
// an object standing in one.
|
|
1231
|
+
return surfaceY - (cameraPosition.y + viewDir.y * t);
|
|
1229
1232
|
}
|
|
1230
1233
|
|
|
1231
1234
|
// incanto: splash WHITEWATER. The look that read as FAKE was a clean radial
|
|
@@ -1621,6 +1624,7 @@ void main() {
|
|
|
1621
1624
|
linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
1622
1625
|
float aboveD = -waterColumnAt(screenUV - vec2(0.0, uScenePassTexel.y),
|
|
1623
1626
|
linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
1627
|
+
// (the helper is signed: -column IS the height above the surface)
|
|
1624
1628
|
float sceneAbove = smoothstep(0.02, 0.25,
|
|
1625
1629
|
(aboveC * 2.0 + aboveL + aboveR + aboveU + aboveD) / 6.0);
|
|
1626
1630
|
float meanAbsorbed = 1.0 - dot(transmittance, vec3(0.299, 0.587, 0.114));
|
|
@@ -1826,9 +1830,33 @@ void main() {
|
|
|
1826
1830
|
float cR = waterColumnAt(screenUV + vec2(tx.x, 0.0), linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
1827
1831
|
float cD = waterColumnAt(screenUV - vec2(0.0, tx.y), linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
1828
1832
|
float cU = waterColumnAt(screenUV + vec2(0.0, tx.y), linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
1829
|
-
float column = (cC * 2.0 + cL + cR + cD + cU) / 6.0;
|
|
1833
|
+
float column = max((cC * 2.0 + cL + cR + cD + cU) / 6.0, 0.0);
|
|
1830
1834
|
float grad = max(max(abs(cR - cL), abs(cU - cD)) * 0.5, 1e-5);
|
|
1831
1835
|
float edgeT = clamp(column / (grad * SHORE_FADE_TEXELS), 0.0, 1.0);
|
|
1836
|
+
|
|
1837
|
+
// An OBJECT standing in the water is not a shoreline. A wader's silhouette
|
|
1838
|
+
// reads as a column that collapses to nothing over one texel — exactly the
|
|
1839
|
+
// shape of a beach — so the fade dissolved the water around every body and
|
|
1840
|
+
// let the sand show through as a gold outline. Tell them apart by what is
|
|
1841
|
+
// under the fragment ITSELF: at a shore the centre is already shallow; at a
|
|
1842
|
+
// silhouette the centre is proper water and only a NEIGHBOUR sticks up
|
|
1843
|
+
// through the surface.
|
|
1844
|
+
float nearestTop = min(min(cL, cR), min(cD, cU));
|
|
1845
|
+
float deepestBed = max(max(cL, cR), max(cD, cU));
|
|
1846
|
+
// A BEACH's depth changes gently: even a steep shore swings only a few
|
|
1847
|
+
// centimetres across one depth texel. A body standing in the water swings
|
|
1848
|
+
// more than a metre across the same texel — so a big spread WITH something
|
|
1849
|
+
// breaking the surface is an object, at any water depth. (Keying this on
|
|
1850
|
+
// "the water here is deep" failed exactly where waders stand: the shallows.)
|
|
1851
|
+
float spread = deepestBed - nearestTop;
|
|
1852
|
+
float objectEdge = smoothstep(0.3, 0.75, spread) * smoothstep(-0.04, -0.3, nearestTop);
|
|
1853
|
+
// The fade may only act where the water under THIS pixel is genuinely thin.
|
|
1854
|
+
// The neighbourhood decides how WIDE the band is; the pixel itself decides
|
|
1855
|
+
// whether it is in one at all — otherwise a silhouette's steep gradient
|
|
1856
|
+
// dissolves water that is half a metre deep.
|
|
1857
|
+
float thinHere = 1.0 - smoothstep(0.06, 0.3, cC);
|
|
1858
|
+
edgeT = mix(1.0, edgeT, thinHere);
|
|
1859
|
+
edgeT = mix(edgeT, 1.0, objectEdge);
|
|
1832
1860
|
// A SHORELINE is where the water is ankle-to-knee deep. Any other place
|
|
1833
1861
|
// the column changes fast — the seabed's own horizon, a hull's silhouette,
|
|
1834
1862
|
// a cliff under water — has a huge gradient too, and without this gate the
|
package/dist/gameplay.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as FollowCamera, D as Health, E as DamageOnContact, O as Collector, S as restartScene, T as phaseOf, _ as hitStop, a as Wander, b as GameFlow, c as Projectile, d as PathFollow, f as Oscillate, g as Cooldown, h as CameraShake, i as WaveSpawner, k as Chase, l as Pickup, m as Lifetime, n as registerGameplayBehaviors, o as Spawner, p as MoveTo, r as ZombieAI, s as ScoreKeeper, t as GAMEPLAY_BEHAVIORS, u as Patrol, v as screenFlash, w as DayNight, x as goToScene, y as Interactable } from "./gameplay-
|
|
1
|
+
import { C as FollowCamera, D as Health, E as DamageOnContact, O as Collector, S as restartScene, T as phaseOf, _ as hitStop, a as Wander, b as GameFlow, c as Projectile, d as PathFollow, f as Oscillate, g as Cooldown, h as CameraShake, i as WaveSpawner, k as Chase, l as Pickup, m as Lifetime, n as registerGameplayBehaviors, o as Spawner, p as MoveTo, r as ZombieAI, s as ScoreKeeper, t as GAMEPLAY_BEHAVIORS, u as Patrol, v as screenFlash, w as DayNight, x as goToScene, y as Interactable } from "./gameplay-B8zVO3Dg.js";
|
|
2
2
|
export { CameraShake, Chase, Collector, Cooldown, DamageOnContact, DayNight, FollowCamera, GAMEPLAY_BEHAVIORS, GameFlow, Health, Interactable, Lifetime, MoveTo, Oscillate, PathFollow, Patrol, Pickup, Projectile, ScoreKeeper, Spawner, Wander, WaveSpawner, ZombieAI, goToScene, hitStop, phaseOf, registerGameplayBehaviors, restartScene, screenFlash };
|
package/dist/index.js
CHANGED
|
@@ -295,6 +295,6 @@ function newUid() {
|
|
|
295
295
|
//#endregion
|
|
296
296
|
//#region src/index.ts
|
|
297
297
|
/** Engine version. Kept in sync with package.json by the release pipeline. */
|
|
298
|
-
const VERSION = "0.25.
|
|
298
|
+
const VERSION = "0.25.3";
|
|
299
299
|
//#endregion
|
|
300
300
|
export { AudioBuses, AudioPlayer, Behavior, CONST_REF_KEY, Engine, HudLayer, IncantoError, InputMap, LogManager, MusicManager, Node, ORDER_GROUP_BASE, PARTICLE_PRESETS, PARTICLE_PRESET_NAMES, ParticleSim, ROLLOFF_MODELS, Rng, SCENE_FORMAT, SFX_PRESETS, SFX_PRESET_NAMES, Scene, SceneTree, SfxEngine, Signal, Timer, TouchControls, UiBanner, UiBar, UiButton, UiDialogue, UiText, VERSION, WebAudioMusicBackend, applyParticlePreset, assetUrls, attachTouchControls, auditScene, clearBehaviors, clearRegistry, computeViewport, createNode, createNoise2D, createSaveStore, crossfadeGains, duplicateNode, effectiveOrder, fadeGain, findPath, getBehavior, getNodeSchema, getNodeSignals, getNodeType, gridFromRows, isAudioContextAvailable, isConstRef, joystickVector, jsonClone, jsonEquals, jsonKind, loadScene, mergeStaticSignals, newUid, parseNodePath, preloadUrls, registerBehavior, registerCoreNodes, registerNode, registeredBehaviors, registeredTypes, replay, resolveConstants, resolveRendering, resolveViewport, serializeNode, spatialGain, spatialPan, startRecording, synthSfx };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
2
|
import { t as IncantoError } from "./errors-BpWbnbb_.js";
|
|
3
|
-
import { I as Node3D, L as validateCollider3D, M as CharacterBody3D, N as PhysicsBody3D, P as RigidBody3D, j as Area3D } from "./gameplay-
|
|
3
|
+
import { I as Node3D, L as validateCollider3D, M as CharacterBody3D, N as PhysicsBody3D, P as RigidBody3D, j as Area3D } from "./gameplay-B8zVO3Dg.js";
|
|
4
4
|
import { n as registerDebugSource } from "./debug-draw-CZmOYjL2.js";
|
|
5
|
-
import { T as Terrain3D, k as Joint3D } from "./register-
|
|
5
|
+
import { T as Terrain3D, k as Joint3D } from "./register-BgeMHtcG.js";
|
|
6
6
|
import { Euler, Quaternion } from "three";
|
|
7
7
|
//#region src/3d/physics/physics-3d.ts
|
|
8
8
|
var physics_3d_exports = /* @__PURE__ */ __exportAll({
|
package/dist/react.js
CHANGED
|
@@ -156,7 +156,7 @@ function IncantoCanvas(props) {
|
|
|
156
156
|
pointer: latest.pointer,
|
|
157
157
|
...keyboard !== void 0 ? { keyboard } : {}
|
|
158
158
|
};
|
|
159
|
-
const next = await (_gameFactory ?? (mode === "3d" ? async (o) => (await import("./create-game-
|
|
159
|
+
const next = await (_gameFactory ?? (mode === "3d" ? async (o) => (await import("./create-game-K8A82JK5.js").then((n) => n.n)).createGame3D(o) : async (o) => (await import("./create-game-yGqGR-Ic.js").then((n) => n.n)).createGame2D(o)))(opts);
|
|
160
160
|
if (disposed) {
|
|
161
161
|
next.dispose();
|
|
162
162
|
return;
|
|
@@ -4,7 +4,7 @@ import { t as Rng } from "./rng-DP-SR7eg.js";
|
|
|
4
4
|
import { i as getNodeSchema, l as registerNode } from "./registry-BVJ2HbCn.js";
|
|
5
5
|
import { t as createNoise2D } from "./noise-CGUMx44x.js";
|
|
6
6
|
import { i as applyParticlePreset, r as PARTICLE_PRESET_NAMES, t as ParticleSim } from "./particle-sim-Bw7hB93B.js";
|
|
7
|
-
import { A as Water3D, B as colliderFootDrop, F as StaticBody3D, I as Node3D, M as CharacterBody3D, N as PhysicsBody3D, P as RigidBody3D, j as Area3D } from "./gameplay-
|
|
7
|
+
import { A as Water3D, B as colliderFootDrop, F as StaticBody3D, I as Node3D, M as CharacterBody3D, N as PhysicsBody3D, P as RigidBody3D, j as Area3D } from "./gameplay-B8zVO3Dg.js";
|
|
8
8
|
import { n as splatWeights, t as buildHeightmap } from "./heightmap-CRK0M4jT.js";
|
|
9
9
|
import { AdditiveBlending, AnimationClip, AnimationMixer, Box3, BoxGeometry, BufferAttribute, BufferGeometry, CanvasTexture, CapsuleGeometry, Color, ConeGeometry, CylinderGeometry, DataTexture, DirectionalLight, DoubleSide, DynamicDrawUsage, Euler, Group, IcosahedronGeometry, ImageBitmapLoader, InstancedBufferAttribute, InstancedMesh, LinearFilter, LoopOnce, LoopRepeat, Matrix4, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshPhysicalMaterial, MeshStandardMaterial, NearestFilter, NoBlending, NormalBlending, PerspectiveCamera, PlaneGeometry, PointLight, Points, PointsMaterial, Quaternion, QuaternionKeyframeTrack, RGBADepthPacking, RGBAFormat, RepeatWrapping, SRGBColorSpace, ShaderChunk, ShaderMaterial, SphereGeometry, Texture, TextureLoader, UniformsLib, UniformsUtils, Vector3, Vector4, VectorKeyframeTrack } from "three";
|
|
10
10
|
import { clone } from "three/addons/utils/SkeletonUtils.js";
|
package/dist/test.js
CHANGED
|
@@ -4,9 +4,9 @@ import { t as IncantoError } from "./errors-BpWbnbb_.js";
|
|
|
4
4
|
import { t as auditScene } from "./audit-C6rMyict.js";
|
|
5
5
|
import { n as jsonEquals, t as jsonClone } from "./json-BLk7H2Qa.js";
|
|
6
6
|
import { i as getNodeSchema, s as mergeStaticProps } from "./registry-BVJ2HbCn.js";
|
|
7
|
-
import { n as registerGameplayBehaviors } from "./gameplay-
|
|
7
|
+
import { n as registerGameplayBehaviors } from "./gameplay-B8zVO3Dg.js";
|
|
8
8
|
import { t as registerNodes2D } from "./register-CvpSUU3O.js";
|
|
9
|
-
import { t as registerNodes3D } from "./register-
|
|
9
|
+
import { t as registerNodes3D } from "./register-BgeMHtcG.js";
|
|
10
10
|
import { t as registerNodesNet } from "./register-BFFE1Mh1.js";
|
|
11
11
|
//#region src/test/index.ts
|
|
12
12
|
/**
|
|
@@ -127,7 +127,7 @@ async function runScript(json, opts) {
|
|
|
127
127
|
const { enablePhysics2D } = await import("./physics-2d-DiVFFlH3.js").then((n) => n.r);
|
|
128
128
|
await enablePhysics2D(engine);
|
|
129
129
|
} else if (physics === "3d" || physics === "auto" && scene.dimension === "3d") {
|
|
130
|
-
const { enablePhysics3D } = await import("./physics-3d-
|
|
130
|
+
const { enablePhysics3D } = await import("./physics-3d-DY0EtjfT.js").then((n) => n.r);
|
|
131
131
|
await enablePhysics3D(engine);
|
|
132
132
|
}
|
|
133
133
|
const failures = [];
|
|
@@ -232,7 +232,7 @@ async function createPlaySession(json, opts = {}) {
|
|
|
232
232
|
const { enablePhysics2D } = await import("./physics-2d-DiVFFlH3.js").then((n) => n.r);
|
|
233
233
|
await enablePhysics2D(engine);
|
|
234
234
|
} else if (physics === "3d" || physics === "auto" && scene.dimension === "3d") {
|
|
235
|
-
const { enablePhysics3D } = await import("./physics-3d-
|
|
235
|
+
const { enablePhysics3D } = await import("./physics-3d-DY0EtjfT.js").then((n) => n.r);
|
|
236
236
|
await enablePhysics3D(engine);
|
|
237
237
|
}
|
|
238
238
|
const stepMs = 1e3 / (opts.fixedHz ?? 60);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./index-
|
|
1
|
+
import{t as e}from"./index-BGtXxzJn.js";async function t(t){return new n((await e(()=>import(`./GameServer-C56iOUgF.js`),[],import.meta.url)).GameServer,t)}var n=class{raw;active=new Map;reconnecting=!1;disposed=!1;constructor(e,t){this.raw=new e({...t})}get account(){return this.raw.account}get connected(){return this.raw.connected}connect(){return this.raw.connected?Promise.resolve(!0):(this.disposed=!1,this.rawConnect())}rawConnect(){return this.raw.connect({onDisconnect:()=>void this.reconnect()})}disconnect(){this.disposed=!0;for(let e of this.active.values())e.off();return this.active.clear(),this.raw.disconnect()}remoteFunction(e,t,n){return this.raw.remoteFunction(e,t,n)}track(e){let t=Symbol(`sub`),n={make:e,off:e()};return this.active.set(t,n),()=>{n.off(),this.active.delete(t)}}async reconnect(){if(!this.disposed&&!this.reconnecting){this.reconnecting=!0;try{await this.rawConnect();for(let e of this.active.values())e.off(),e.off=e.make()}finally{this.reconnecting=!1}}}subscribeRoomState(e,t){return this.track(()=>this.raw.subscribeRoomState(e,t))}subscribeRoomMyState(e,t){return this.track(()=>this.raw.subscribeRoomMyState(e,t))}subscribeRoomAllUserStates(e,t){return this.track(()=>this.raw.subscribeRoomAllUserStates(e,e=>{let n={};for(let t of e??[]){if(!t||typeof t.account!=`string`||t.__leaved)continue;let{account:e,__updated:r,__leaved:i,...a}=t;n[e]=a}t(n)}))}subscribeRoomCollection(e,t,n){return this.track(()=>this.raw.subscribeRoomCollection(e,t,({items:e})=>{let t={};for(let n of e??[])n&&typeof n.__id==`string`&&(t[n.__id]=n);n(t)}))}onRoomMessage(e,t,n){return this.track(()=>this.raw.onRoomMessage(e,t,n))}onRoomUserJoin(e,t){return this.track(()=>this.raw.onRoomUserJoin(e,t))}onRoomUserLeave(e,t){return this.track(()=>this.raw.onRoomUserLeave(e,t))}subscribeGlobalState(e){return this.track(()=>this.raw.subscribeGlobalState(e))}subscribeGlobalMyState(e){return this.track(()=>this.raw.subscribeGlobalMyState(e))}subscribeGlobalUserState(e,t){return this.track(()=>this.raw.subscribeGlobalUserState(e,t))}subscribeGlobalCollection(e,t){return this.track(()=>this.raw.subscribeGlobalCollection(e,({items:e})=>{let n={};for(let t of e??[])t&&typeof t.__id==`string`&&(n[t.__id]=t);t(n)}))}subscribeAsset(e,t){return this.track(()=>this.raw.subscribeAsset(e,t))}onGlobalMessage(e,t){return this.track(()=>this.raw.onGlobalMessage(e,t))}};export{t as createAgent8Server};
|
|
@@ -4987,7 +4987,10 @@ float linearizeDepth(float depth, float near, float far) {
|
|
|
4987
4987
|
float waterColumnAt(vec2 uv, float linearWaterDepth, float camDist, vec3 viewDir, float surfaceY) {
|
|
4988
4988
|
float sceneD = linearizeDepth(texture2D(uDepthTexture, uv).r, uCameraNear, uCameraFar);
|
|
4989
4989
|
float t = camDist * (sceneD / max(linearWaterDepth, 1e-4));
|
|
4990
|
-
|
|
4990
|
+
// SIGNED on purpose: negative means the sample sticks up THROUGH the water
|
|
4991
|
+
// (a wader, a hull, a rock), and that is how a shoreline is told apart from
|
|
4992
|
+
// an object standing in one.
|
|
4993
|
+
return surfaceY - (cameraPosition.y + viewDir.y * t);
|
|
4991
4994
|
}
|
|
4992
4995
|
|
|
4993
4996
|
// incanto: splash WHITEWATER. The look that read as FAKE was a clean radial
|
|
@@ -5383,6 +5386,7 @@ void main() {
|
|
|
5383
5386
|
linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
5384
5387
|
float aboveD = -waterColumnAt(screenUV - vec2(0.0, uScenePassTexel.y),
|
|
5385
5388
|
linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
5389
|
+
// (the helper is signed: -column IS the height above the surface)
|
|
5386
5390
|
float sceneAbove = smoothstep(0.02, 0.25,
|
|
5387
5391
|
(aboveC * 2.0 + aboveL + aboveR + aboveU + aboveD) / 6.0);
|
|
5388
5392
|
float meanAbsorbed = 1.0 - dot(transmittance, vec3(0.299, 0.587, 0.114));
|
|
@@ -5588,9 +5592,33 @@ void main() {
|
|
|
5588
5592
|
float cR = waterColumnAt(screenUV + vec2(tx.x, 0.0), linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
5589
5593
|
float cD = waterColumnAt(screenUV - vec2(0.0, tx.y), linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
5590
5594
|
float cU = waterColumnAt(screenUV + vec2(0.0, tx.y), linearWaterDepth, camDist, viewDirection, vWorldPosition.y);
|
|
5591
|
-
float column = (cC * 2.0 + cL + cR + cD + cU) / 6.0;
|
|
5595
|
+
float column = max((cC * 2.0 + cL + cR + cD + cU) / 6.0, 0.0);
|
|
5592
5596
|
float grad = max(max(abs(cR - cL), abs(cU - cD)) * 0.5, 1e-5);
|
|
5593
5597
|
float edgeT = clamp(column / (grad * SHORE_FADE_TEXELS), 0.0, 1.0);
|
|
5598
|
+
|
|
5599
|
+
// An OBJECT standing in the water is not a shoreline. A wader's silhouette
|
|
5600
|
+
// reads as a column that collapses to nothing over one texel — exactly the
|
|
5601
|
+
// shape of a beach — so the fade dissolved the water around every body and
|
|
5602
|
+
// let the sand show through as a gold outline. Tell them apart by what is
|
|
5603
|
+
// under the fragment ITSELF: at a shore the centre is already shallow; at a
|
|
5604
|
+
// silhouette the centre is proper water and only a NEIGHBOUR sticks up
|
|
5605
|
+
// through the surface.
|
|
5606
|
+
float nearestTop = min(min(cL, cR), min(cD, cU));
|
|
5607
|
+
float deepestBed = max(max(cL, cR), max(cD, cU));
|
|
5608
|
+
// A BEACH's depth changes gently: even a steep shore swings only a few
|
|
5609
|
+
// centimetres across one depth texel. A body standing in the water swings
|
|
5610
|
+
// more than a metre across the same texel — so a big spread WITH something
|
|
5611
|
+
// breaking the surface is an object, at any water depth. (Keying this on
|
|
5612
|
+
// "the water here is deep" failed exactly where waders stand: the shallows.)
|
|
5613
|
+
float spread = deepestBed - nearestTop;
|
|
5614
|
+
float objectEdge = smoothstep(0.3, 0.75, spread) * smoothstep(-0.04, -0.3, nearestTop);
|
|
5615
|
+
// The fade may only act where the water under THIS pixel is genuinely thin.
|
|
5616
|
+
// The neighbourhood decides how WIDE the band is; the pixel itself decides
|
|
5617
|
+
// whether it is in one at all — otherwise a silhouette's steep gradient
|
|
5618
|
+
// dissolves water that is half a metre deep.
|
|
5619
|
+
float thinHere = 1.0 - smoothstep(0.06, 0.3, cC);
|
|
5620
|
+
edgeT = mix(1.0, edgeT, thinHere);
|
|
5621
|
+
edgeT = mix(edgeT, 1.0, objectEdge);
|
|
5594
5622
|
// A SHORELINE is where the water is ankle-to-knee deep. Any other place
|
|
5595
5623
|
// the column changes fast — the seabed's own horizon, a hull's silhouette,
|
|
5596
5624
|
// a cliff under water — has a huge gradient too, and without this gate the
|
|
@@ -8191,7 +8219,7 @@ void main() {
|
|
|
8191
8219
|
#include <tonemapping_fragment>
|
|
8192
8220
|
#include <colorspace_fragment>
|
|
8193
8221
|
|
|
8194
|
-
}`};var Sk=[`type`,`sunPosition`,`elevationDeg`,`azimuthDeg`,`turbidity`,`rayleigh`],Ck=[`color`,`near`,`far`],wk=[`coverage`,`density`,`base`,`top`,`color`,`shadeColor`,`speed`,`scale`],Tk=[`threshold`,`strength`],Ek=[`vignette`,`saturation`,`contrast`],Dk=[`mapSize`,`radius`,`static`],Ok=[1024,2048],kk=2,Ak=1,jk=50,Mk=800,Nk=`#cfd8e0`,Pk=Math.PI/180;function Fk(e){return{exposure:zk(e?.exposure),sky:Bk(e?.sky),fog:Vk(e?.fog,e?.sky!==void 0),clouds:Hk(e?.clouds),bloom:Uk(e?.bloom),post:Wk(e?.post),shadows:Gk(e?.shadows)}}function Ik(e,t){let n=(90-e)*Pk,r=t*Pk;return[Math.sin(n)*Math.sin(r),Math.cos(n),Math.sin(n)*Math.cos(r)]}function Lk(e){let[t,n,r]=e.sunPosition,i=Math.hypot(t,n,r)||1;return[t/i,n/i,r/i]}function Rk(e){let t=[191,213,232],n=[233,228,217],r=[242,201,150],i=Jk((e.turbidity-kk)/8),a=Lk(e),o=Jk((18-Math.asin(qk(a[1],-1,1))/Pk)/18)*.8,s=e=>Math.round(Yk(Yk(t[e],n[e],i),r[e],o));return`#${[s(0),s(1),s(2)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}function zk(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw new y(`BAD_FORMAT`,`environment.exposure must be a finite number > 0 (tone-mapping exposure, default 1), got ${JSON.stringify(e)}.`,{prop:`exposure`});return e}function Bk(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.sky must be an object ({ type?: "atmosphere", sunPosition? | elevationDeg?+azimuthDeg?, turbidity?, rayleigh? }), got ${JSON.stringify(e)}.`,{prop:`sky`});let t=e;for(let e of Object.keys(t))if(!Sk.includes(e))throw new y(`BAD_FORMAT`,`environment.sky has unknown key '${e}'. Valid keys: [${Sk.join(`, `)}].`,{prop:`sky`,validOptions:Sk});if(t.type!==void 0&&t.type!==`atmosphere`)throw new y(`BAD_FORMAT`,`environment.sky.type must be 'atmosphere' (the only sky type so far), got ${JSON.stringify(t.type)}.`,{prop:`sky`,validOptions:[`atmosphere`]});let n=t.elevationDeg!==void 0||t.azimuthDeg!==void 0;if(t.sunPosition!==void 0&&n)throw new y(`BAD_FORMAT`,`environment.sky takes sunPosition OR elevationDeg/azimuthDeg, not both.`,{prop:`sky`,validOptions:[`sunPosition`,`elevationDeg+azimuthDeg`]});let r;if(t.sunPosition!==void 0){let e=t.sunPosition;if(!Array.isArray(e)||e.length!==3||!e.every(e=>typeof e==`number`&&Number.isFinite(e))||Math.hypot(e[0],e[1],e[2])===0)throw new y(`BAD_FORMAT`,`environment.sky.sunPosition must be a non-zero [x, y, z] vector, got ${JSON.stringify(e)}.`,{prop:`sky`});r=[e[0],e[1],e[2]]}else{let e=Kk(t.elevationDeg,32,`sky.elevationDeg`),n=Kk(t.azimuthDeg,135,`sky.azimuthDeg`);if(e<-90||e>90)throw new y(`BAD_FORMAT`,`environment.sky.elevationDeg must be in [-90, 90] (degrees above the horizon), got ${e}.`,{prop:`sky`});r=Ik(e,n)}let i=Kk(t.turbidity,kk,`sky.turbidity`);if(i<=0)throw new y(`BAD_FORMAT`,`environment.sky.turbidity must be > 0 (atmospheric haze; 2 ≈ clear day), got ${i}.`,{prop:`sky`});let a=Kk(t.rayleigh,Ak,`sky.rayleigh`);if(a<0)throw new y(`BAD_FORMAT`,`environment.sky.rayleigh must be >= 0 (Rayleigh scattering; 1 ≈ earth-like), got ${a}.`,{prop:`sky`});return{sunPosition:r,turbidity:i,rayleigh:a}}function Vk(e,t){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.fog must be an object ({ color?, near?, far? }), got ${JSON.stringify(e)}.`,{prop:`fog`});let n=e;for(let e of Object.keys(n))if(!Ck.includes(e))throw new y(`BAD_FORMAT`,`environment.fog has unknown key '${e}'. Valid keys: [${Ck.join(`, `)}].`,{prop:`fog`,validOptions:Ck});if(n.color!==void 0&&typeof n.color!=`string`)throw new y(`BAD_FORMAT`,`environment.fog.color must be a hex color string, got ${JSON.stringify(n.color)}.`,{prop:`fog`});let r=Kk(n.near,jk,`fog.near`),i=Kk(n.far,Mk,`fog.far`);if(r<0)throw new y(`BAD_FORMAT`,`environment.fog.near must be >= 0 meters, got ${r}.`,{prop:`fog`});if(i<=r)throw new y(`BAD_FORMAT`,`environment.fog.far must be > near (got near ${r}, far ${i}).`,{prop:`fog`});return{color:n.color??(t?``:Nk),near:r,far:i}}function Hk(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.clouds must be an object ({ coverage?, density?, base?, top?, color?, shadeColor?, speed?, scale? }), got ${JSON.stringify(e)}.`,{prop:`clouds`});let t=e;for(let e of Object.keys(t))if(!wk.includes(e))throw new y(`BAD_FORMAT`,`environment.clouds has unknown key '${e}'. Valid keys: [${wk.join(`, `)}].`,{prop:`clouds`,validOptions:wk});for(let e of[`color`,`shadeColor`])if(t[e]!==void 0&&typeof t[e]!=`string`)throw new y(`BAD_FORMAT`,`environment.clouds.${e} must be a hex color string, got ${JSON.stringify(t[e])}.`,{prop:`clouds`});let n=Kk(t.coverage,.5,`clouds.coverage`);if(n<0||n>1)throw new y(`BAD_FORMAT`,`environment.clouds.coverage must be in [0, 1] (how much sky is cloudy), got ${n}.`,{prop:`clouds`});let r=Kk(t.density,1,`clouds.density`);if(r<0)throw new y(`BAD_FORMAT`,`environment.clouds.density must be >= 0 (optical thickness), got ${r}.`,{prop:`clouds`});let i=Kk(t.base,120,`clouds.base`),a=Kk(t.top,320,`clouds.top`);if(a<=i)throw new y(`BAD_FORMAT`,`environment.clouds.top must be > base (got base ${i}, top ${a}).`,{prop:`clouds`});let o=Kk(t.speed,1,`clouds.speed`),s=Kk(t.scale,240,`clouds.scale`);if(s<=0)throw new y(`BAD_FORMAT`,`environment.clouds.scale must be > 0 (feature size in world units), got ${s}.`,{prop:`clouds`});return{coverage:n,density:r,base:i,top:a,color:t.color??`#ffffff`,shadeColor:t.shadeColor??`#9fb0c8`,speed:o,scale:s}}function Uk(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.bloom must be an object ({ threshold?, strength? }), got ${JSON.stringify(e)}.`,{prop:`bloom`});let t=e;for(let e of Object.keys(t))if(!Tk.includes(e))throw new y(`BAD_FORMAT`,`environment.bloom has unknown key '${e}'. Valid keys: [${Tk.join(`, `)}].`,{prop:`bloom`,validOptions:Tk});let n=Kk(t.threshold,1,`bloom.threshold`);if(n<0||n>8)throw new y(`BAD_FORMAT`,`environment.bloom.threshold must be in [0, 8] (linear-HDR luminance; 1 = white), got ${n}.`,{prop:`bloom`});let r=Kk(t.strength,.8,`bloom.strength`);if(r<0)throw new y(`BAD_FORMAT`,`environment.bloom.strength must be >= 0, got ${r}.`,{prop:`bloom`});return{threshold:n,strength:r}}function Wk(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.post must be an object ({ vignette?, saturation?, contrast? }), got ${JSON.stringify(e)}.`,{prop:`post`});let t=e;for(let e of Object.keys(t))if(!Ek.includes(e))throw new y(`BAD_FORMAT`,`environment.post has unknown key '${e}'. Valid keys: [${Ek.join(`, `)}].`,{prop:`post`,validOptions:Ek});let n=Kk(t.vignette,0,`post.vignette`);if(n<0||n>1)throw new y(`BAD_FORMAT`,`environment.post.vignette must be in [0, 1], got ${n}.`,{prop:`post`});let r=Kk(t.saturation,1,`post.saturation`);if(r<0||r>4)throw new y(`BAD_FORMAT`,`environment.post.saturation must be in [0, 4] (1 = neutral), got ${r}.`,{prop:`post`});let i=Kk(t.contrast,1,`post.contrast`);if(i<.2||i>3)throw new y(`BAD_FORMAT`,`environment.post.contrast must be in [0.2, 3] (1 = neutral), got ${i}.`,{prop:`post`});return{vignette:n,saturation:r,contrast:i}}function Gk(e){if(e===void 0)return null;if(e===!1)return!1;if(e===!0)return{mapSize:2048,radius:1,static:!1};if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.shadows must be true, false or an object ({ mapSize?, radius? }), got ${JSON.stringify(e)}.`,{prop:`shadows`});let t=e;for(let e of Object.keys(t))if(!Dk.includes(e))throw new y(`BAD_FORMAT`,`environment.shadows has unknown key '${e}'. Valid keys: [${Dk.join(`, `)}].`,{prop:`shadows`,validOptions:Dk});let n=t.mapSize===void 0?2048:t.mapSize;if(!Ok.includes(n))throw new y(`BAD_FORMAT`,`environment.shadows.mapSize must be one of [${Ok.join(`, `)}], got ${JSON.stringify(t.mapSize)}.`,{prop:`shadows`,validOptions:Ok.map(String)});let r=Kk(t.radius,1,`shadows.radius`);if(r<0)throw new y(`BAD_FORMAT`,`environment.shadows.radius must be >= 0, got ${r}.`,{prop:`shadows`});let i=t.static===void 0?!1:t.static;if(typeof i!=`boolean`)throw new y(`BAD_FORMAT`,`environment.shadows.static must be a boolean, got ${JSON.stringify(t.static)}.`,{prop:`shadows`});return{mapSize:n,radius:r,static:i}}function Kk(e,t,n){if(e===void 0)return t;if(typeof e!=`number`||!Number.isFinite(e))throw new y(`BAD_FORMAT`,`environment.${n} must be a finite number, got ${JSON.stringify(e)}.`,{prop:n});return e}function qk(e,t,n){return Math.min(Math.max(e,t),n)}function Jk(e){return qk(e,0,1)}function Yk(e,t,n){return e+(t-e)*n}var Xk=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,Zk={apartment:`lebombo_1k.hdr`,city:`potsdamer_platz_1k.hdr`,dawn:`kiara_1_dawn_1k.hdr`,forest:`forest_slope_1k.hdr`,lobby:`st_fagans_interior_1k.hdr`,night:`dikhololo_night_1k.hdr`,park:`rooitou_park_1k.hdr`,studio:`studio_small_03_1k.hdr`,sunset:`venice_sunset_1k.hdr`,warehouse:`empty_warehouse_01_1k.hdr`};function Qk(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=Zk[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(Zk).join(`, `)}.`);return`${Xk}/${t}`}return null}var $k=75,eA=class{scene;ambient=new rl(`#ffffff`,0);envKey=null;config=Fk(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new oa(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new G;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?Lk(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get post(){return this.config.post}get sceneFog(){return this.scene.fog instanceof oa?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=Fk(e));let r=this.config,i=e?.ambient;if(this.ambient.color.set(i?.color??`#ffffff`),this.ambient.intensity=i?.intensity??0,t&&(t.toneMappingExposure=r.exposure,t.shadowMap.enabled=r.shadows!==!1,r.shadows!==!1&&r.shadows!==null&&r.shadows.static?t.shadowMap.autoUpdate&&(t.shadowMap.autoUpdate=!1,t.shadowMap.needsUpdate=!0):t.shadowMap.autoUpdate||(t.shadowMap.autoUpdate=!0)),this.applyHdri(e),this.applySky(r.sky,t),this._sky&&(this._sky.visible=!0),this.applyFog(r),this.scene.environment=this.hdriTexture??this.skyEnvTarget?.texture??null,this.scene.environmentIntensity=(this.scene.environment===this.skyEnvTarget?.texture&&this.skyEnvTarget?.55:1)*tA(e?.iblIntensity),e?.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new G(t):null}}applySunLight(e,t=null){if(!e)return;let n=this.sunDirection;if(t){let r=e.position.length()||100,i,a,o;if(n)[i,a,o]=n;else{i=e.position.x-e.target.position.x,a=e.position.y-e.target.position.y,o=e.position.z-e.target.position.z;let t=Math.hypot(i,a,o)||1;i/=t,a/=t,o/=t}e.target.position.set(t.x,t.y,t.z),e.target.updateMatrixWorld(),e.position.set(t.x+i*r,t.y+a*r,t.z+o*r)}else if(n){let t=e.position.length()||100;e.position.set(n[0],n[1],n[2]).multiplyScalar(t)}let r=this.config.shadows;if(r&&typeof r==`object`){if(!e.castShadow){let t=e.shadow.camera;`left`in t&&t.left===-5&&(t.left=-75,t.right=$k,t.top=$k,t.bottom=-75,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.castShadow=!0}e.shadow.mapSize.x!==r.mapSize&&(e.shadow.mapSize.set(r.mapSize,r.mapSize),e.shadow.map?.dispose(),e.shadow.map=null),e.shadow.radius=r.radius}}applyUnderwater(e){e&&(this.underwaterFog||=new oa(`#000000`,.5,e.visibility),this.underwaterFog.color.set(e.color),this.underwaterFog.near=.5,this.underwaterFog.far=e.visibility,this.scene.fog=this.underwaterFog,this.scene.background=this.underwaterBg.set(e.color),this._sky&&(this._sky.visible=!1))}applyHdri(e){let t=Qk(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new bk().load(t,e=>{if(this.hdriUrl!==t){e.dispose();return}e.mapping=303,this.hdriTexture=e}))}applySky(e,t){let n=e?JSON.stringify(e):``;if(n!==this.skyKey&&(this.skyKey=n,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null),e)){this._sky=new xk,this._sky.scale.setScalar(45e4);let t=this._sky.material.uniforms;(t.sunPosition?.value).set(...e.sunPosition),t.turbidity&&(t.turbidity.value=e.turbidity),t.rayleigh&&(t.rayleigh.value=e.rayleigh),this.scene.add(this._sky)}if(e&&t&&this._sky&&this.skyEnvKey!==n){this.skyEnvKey=n,this.skyEnvTarget?.dispose();let e=new ru(t),r=new sa;r.add(this._sky),this.skyEnvTarget=e.fromScene(r),e.dispose(),this.scene.add(this._sky)}!e&&this.skyEnvTarget&&(this.skyEnvTarget.dispose(),this.skyEnvTarget=null,this.skyEnvKey=``)}applyFog(e){if(!e.fog){this.scene.fog=null;return}let t=e.fog.color||(e.sky?Rk(e.sky):`#cfd8e0`);this.fog.color.set(t),this.fog.near=e.fog.near,this.fog.far=e.fog.far,this.scene.fog=this.fog}dispose(){this.hdriTexture?.dispose(),this.hdriTexture=null,this.skyEnvTarget?.dispose(),this.skyEnvTarget=null,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null)}};function tA(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new y(`BAD_FORMAT`,`environment.iblIntensity must be a finite number >= 0 (multiplies the image-based ambience: sky-derived base 0.55, HDRI base 1; default 1), got ${JSON.stringify(e)}.`,{prop:`iblIntensity`});return e}var nA=new Sa,rA=new H,iA=.4,aA=new Float32Array(72);function oA(e){if(!(e instanceof qp))return null;let t=e._ensureObject3D();if(t.updateWorldMatrix(!0,!0),nA.setFromObject(t),nA.getSize(rA),!Number.isFinite(rA.x)||rA.x===0&&rA.y===0&&rA.z===0){let e=new H().setFromMatrixPosition(t.matrixWorld);nA.min.set(e.x-iA,e.y-iA,e.z-iA),nA.max.set(e.x+iA,e.y+iA,e.z+iA)}else nA.expandByScalar(.02);let{min:n,max:r}=nA,i=0,a=(e,t,n,r,a,o)=>{aA[i++]=e,aA[i++]=t,aA[i++]=n,aA[i++]=r,aA[i++]=a,aA[i++]=o};return a(n.x,n.y,n.z,r.x,n.y,n.z),a(r.x,n.y,n.z,r.x,n.y,r.z),a(r.x,n.y,r.z,n.x,n.y,r.z),a(n.x,n.y,r.z,n.x,n.y,n.z),a(n.x,r.y,n.z,r.x,r.y,n.z),a(r.x,r.y,n.z,r.x,r.y,r.z),a(r.x,r.y,r.z,n.x,r.y,r.z),a(n.x,r.y,r.z,n.x,r.y,n.z),a(n.x,n.y,n.z,n.x,r.y,n.z),a(r.x,n.y,n.z,r.x,r.y,n.z),a(r.x,n.y,r.z,r.x,r.y,r.z),a(n.x,n.y,r.z,n.x,r.y,r.z),aA}function sA(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function cA(){let e=new Set,t=[],n=[],r=[];return{visited:e,cameras:t,renderHooks:n,emitters:r,state:{visited:e,cameras:t,renderHooks:n,emitters:r,assets:void 0,sunDirection:null,sunLight:null,alpha:1,ignoreStatic:!1}}}function lA(e,t,n,r,i){let a=i??cA();a.visited.clear(),a.cameras.length=0,a.renderHooks.length=0,a.emitters.length=0;let o=a.state;o.assets=n,o.sunDirection=r?.sunDirection??null,o.ignoreStatic=r?.ignoreStatic===!0,o.sunLight=null,o.alpha=r?.alpha??1,hA(e,t,o),vA(t,a.visited);let s=null;for(let e=0;e<a.cameras.length;e++){let t=a.cameras[e];if(t.current){s=t;break}}s||=a.cameras[0]??null;let c=s?s._ensureObject3D():null;return mA(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var uA=new H,dA=new H,fA=new H,pA=new H;function mA(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(dA),t.getWorldDirection(fA),pA.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[dA.x,dA.y,dA.z],forward:[fA.x,fA.y,fA.z],up:[pA.x,pA.y,pA.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(uA),t._setSpatialPose({position:[uA.x,uA.y,uA.z],listener:n})}function hA(e,t,n){let r=t;if(e instanceof qp){let i=e._ensureObject3D();if(e.static&&!n.ignoreStatic&&i.userData.incantoStaticSynced===!0){i.userData.incantoStatic=!0,n.visited.add(i);return}if(i.parent!==t&&t.add(i),e._syncObject3D(n.alpha),n.assets&&e instanceof AE&&e._syncModel(n.assets),typeof e._onRender3D==`function`&&n.renderHooks.push(e),n.sunDirection){let t=e._applySunDirection;typeof t==`function`&&t.call(e,n.sunDirection)}e instanceof hE&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof hC&&n.cameras.push(e),r=i}else sA(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)hA(t,r,n);if(e instanceof qp){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,_A(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var gA=new WeakSet;function _A(e){if(gA.has(e))return;gA.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof hC)&&t.push(`${e.name} (${e.constructor.typeName??`?`})`);for(let t of e.children)n(t)};n(e),t.length>0&&console.warn(`[incanto] static subtree '${e.name}' freezes animated/per-frame nodes: ${t.join(`, `)} — they will stop updating. Unmark static or move them out.`)}function vA(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&vA(i,t)}}var yA=class{viewOverride=null;overrideCam=new Yc(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new sa;environment=new eA(this.threeScene);engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;syncScratch=cA();ignoreStatic=!1;renderCtx=null;causticsTarget=null;causticsScene=null;causticsUniforms=null;cloudsTarget=null;cloudsHalfTarget=null;cloudsBlurTarget=null;cloudsScene=null;cloudsUniforms=null;cloudsBlurScene=null;cloudsBlurUniforms=null;cloudsCompositeScene=null;cloudsCompositeUniforms=null;bloomTarget=null;bloomBrightTarget=null;bloomBlurTarget=null;bloomBrightScene=null;bloomBrightUniforms=null;bloomBlurScene=null;bloomBlurUniforms=null;bloomCompositeScene=null;bloomCompositeUniforms=null;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.ownsAssets=!e.assets,this.assets=e.assets??new Sx;let t=lt(e.engine.scene?.environment,{antialias:!0,pixelRatio:Math.min(globalThis.devicePixelRatio??1,2)},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio});this.webgl=new Zf({canvas:e.canvas,antialias:t.antialias}),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.adaptive=e.adaptiveResolution===!1?null:new rk,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new ws(new q,new fs({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new ws(new q,new fs({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.threeScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>this.render())}basePixelRatio;adaptive;lastFrameAt=0;debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?oA(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new K(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of fh(`3d`))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new K(e,3))}governResolution(){let e=this.adaptive;if(!e)return;let t=globalThis.performance?.now?.()??0,n=this.lastFrameAt;if(this.lastFrameAt=t,n===0)return;let r=t-n;if(r>500){e.reset();return}let i=e.push(r);if(i===null)return;this.webgl.setPixelRatio(this.basePixelRatio*i);let a=this.lastSize;a.w>0&&a.h>0&&this.webgl.setSize(a.w,a.h,!1)}render(){let e=this.engine.scene;if(!e)return;this.governResolution(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e)),this.environment.apply(e.environment,this.webgl);let{activeCamera:t,renderHooks:n,sunLight:r}=lA(e.root,this.threeScene,this.assets,{sunDirection:this.environment.sunDirection,alpha:this.engine.interpolationAlpha,ignoreStatic:this.ignoreStatic},this.syncScratch),i=t;if(this.viewOverride){let[e,t,n]=this.viewOverride.position,[r,a,o]=this.viewOverride.target;this.overrideCam.position.set(e,t,n),this.overrideCam.lookAt(xA.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(EA),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i));let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(bA);(u.x!==c||u.y!==l)&&this.webgl.setSize(c,l,!1),this.lastSize={w:c,h:l};let d=l===0?1:c/l;i.aspect!==d&&(i.aspect=d,i.updateProjectionMatrix()),this.renderCtx||={gl:this.webgl,scene:this.threeScene,camera:i};let f=this.renderCtx;f.camera=i,o?(o.updateWorldMatrix(!0,!1),o.target.updateWorldMatrix(!0,!1),f.sunDir=CA.setFromMatrixPosition(o.matrixWorld).sub(wA.setFromMatrixPosition(o.target.matrixWorld)).normalize()):f.sunDir=null;for(let e=0;e<n.length;e++)n[e]?._onRender3D(f);let p=null;for(let e=0;e<n.length;e++){let t=n[e].underwaterAt?.(a.x,a.y,a.z);if(t){p=t;break}}this.environment.applyUnderwater(p);let m=this.environment.clouds,h=this.environment.bloom,g=this.environment.post;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):(h||g)&&!p?this.renderWithBloom(i,h,g):this.webgl.render(this.threeScene,i)}renderWithBloom(e,t,n=null){let r=this.webgl.getDrawingBufferSize(bA),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/2)),s=Math.max(1,Math.ceil(a/2));if(this.bloomTarget&&(this.bloomTarget.width!==i||this.bloomTarget.height!==a)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new Si(i,a,{type:Qt}),this.bloomBrightTarget=new Si(o,s,{type:Qt}),this.bloomBlurTarget=new Si(o,s,{type:Qt})),!this.bloomBrightScene){let e=lk();this.bloomBrightScene=new sa,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=uk();this.bloomBlurScene=new sa,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=dk();this.bloomCompositeScene=new sa,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let c=this.bloomBrightTarget,l=this.bloomBlurTarget;if(this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e),t){let n=this.bloomBrightUniforms;n.tScene.value=this.bloomTarget.texture,n.uThreshold.value=t.threshold,this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBrightScene,e);let r=this.bloomBlurUniforms;r.tTex.value=c.texture,r.uDir.value.set(1/o,0),this.webgl.setRenderTarget(l),this.webgl.render(this.bloomBlurScene,e),r.tTex.value=l.texture,r.uDir.value.set(0,1/s),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e)}let u=this.bloomCompositeUniforms;u.tScene.value=this.bloomTarget.texture,u.tBloom.value=t?c.texture:this.bloomTarget.texture,u.uStrength.value=t?t.strength:0,u.uVignette.value=n?.vignette??0,u.uSaturation.value=n?.saturation??1,u.uContrast.value=n?.contrast??1,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(bA),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/3)),s=Math.max(1,Math.ceil(a/3));if(this.cloudsTarget&&(this.cloudsTarget.width!==i||this.cloudsTarget.height!==a)&&(this.cloudsTarget.depthTexture?.dispose(),this.cloudsTarget.dispose(),this.cloudsTarget=null,this.cloudsHalfTarget?.dispose(),this.cloudsHalfTarget=null,this.cloudsBlurTarget?.dispose(),this.cloudsBlurTarget=null),!this.cloudsTarget){let e=new Fs(i,a);e.type=Zt,this.cloudsTarget=new Si(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Si(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Si(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=_k();this.cloudsScene=new sa,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=gk();this.cloudsBlurScene=new sa,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=vk();this.cloudsCompositeScene=new sa,this.cloudsCompositeScene.add(e),this.cloudsCompositeUniforms=t}this.webgl.setRenderTarget(this.cloudsTarget),this.webgl.render(this.threeScene,e);let c=this.cloudsUniforms;c.tDepth.value=this.cloudsTarget.depthTexture,c.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(c.uCameraPos.value),c.uTime.value=(globalThis.performance?.now()??0)*.001*t.speed;let l=this.environment.sunDirection??[.4,.8,.3];c.uSunDir.value.set(l[0],l[1],l[2]).normalize(),n&&c.uSunColor.value.copy(n.color),c.uCloudColor.value.set(t.color),c.uShadeColor.value.set(t.shadeColor);let u=this.environment.sceneFog;u?(c.uHorizonColor.value.copy(u.color),c.uFarFade.value=u.far):(c.uHorizonColor.value.set(`#cdd9e6`),c.uFarFade.value=6e3),c.uBase.value=t.base,c.uTop.value=t.top,c.uCoverage.value=t.coverage,c.uDensity.value=t.density,c.uScale.value=t.scale,c.uWind.value.set(1,.35),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(this.cloudsScene,e);let d=this.cloudsBlurUniforms,f=this.cloudsBlurScene;d.tTex.value=this.cloudsHalfTarget.texture,d.uDir.value.set(1/o,0),this.webgl.setRenderTarget(this.cloudsBlurTarget),this.webgl.render(f,e),d.tTex.value=this.cloudsBlurTarget.texture,d.uDir.value.set(0,1/s),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(f,e),this.webgl.setRenderTarget(null);let p=this.cloudsCompositeUniforms;p.tScene.value=this.cloudsTarget.texture,p.tClouds.value=this.cloudsHalfTarget.texture,this.webgl.render(this.cloudsCompositeScene,e)}renderWithCaustics(e,t){let n=this.webgl.getDrawingBufferSize(bA),r=Math.max(1,n.x),i=Math.max(1,n.y);if(this.causticsTarget&&(this.causticsTarget.width!==r||this.causticsTarget.height!==i)&&(this.causticsTarget.depthTexture?.dispose(),this.causticsTarget.dispose(),this.causticsTarget=null),!this.causticsTarget){let e=new Fs(r,i);e.type=Zt,this.causticsTarget=new Si(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=yp();this.causticsScene=new sa,this.causticsScene.add(e),this.causticsUniforms=t}this.webgl.setRenderTarget(this.causticsTarget),this.webgl.render(this.threeScene,e),this.webgl.setRenderTarget(null);let a=this.causticsUniforms;a.tColor.value=this.causticsTarget.texture,a.tDepth.value=this.causticsTarget.depthTexture,a.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(a.uCameraPos.value),a.uWaterLevel.value=t.surfaceY,a.uTime.value=(globalThis.performance?.now()??0)*.001*t.caustics.speed,a.uCausticColor.value.set(t.caustics.color),a.uCausticIntensity.value=t.caustics.intensity,a.uCausticScale.value=t.caustics.scale,a.uMaxDist.value=t.visibility;let o=this.environment.sunDirection;o&&a.uSunDirection.value.set(o[0],o[1],o[2]),a.uRayStrength.value=t.rays.enabled?t.rays.strength:0,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(SA.set(e,t,n).project(r),{x:(SA.x+1)/2*this.lastSize.w,y:(1-SA.y)/2*this.lastSize.h,behind:SA.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;OA.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),DA.setFromCamera(OA,n);let r=DA.intersectObjects(this.threeScene.children,!0);for(let e of r){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(n)return n}return null}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(TA):TA.identity();return{right:new H(1,0,0).applyQuaternion(t),up:new H(0,1,0).applyQuaternion(t),forward:new H(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){this.disconnect(),this.threeScene.traverse(e=>{let t=e;if(!(!t.isMesh||t.userData?.incantoModelShared))if(t.geometry?.dispose(),Array.isArray(t.material))for(let e of t.material)e.dispose();else t.material?.dispose()}),this.causticsTarget?.depthTexture?.dispose(),this.causticsTarget?.dispose();let e=this.causticsScene?.children[0];e?.geometry?.dispose(),e?.material?.dispose(),this.cloudsTarget?.depthTexture?.dispose(),this.cloudsTarget?.dispose(),this.cloudsHalfTarget?.dispose(),this.cloudsBlurTarget?.dispose(),this.bloomTarget?.dispose(),this.bloomBrightTarget?.dispose(),this.bloomBlurTarget?.dispose();for(let e of[this.cloudsScene,this.cloudsBlurScene,this.cloudsCompositeScene,this.bloomBrightScene,this.bloomBlurScene,this.bloomCompositeScene]){let t=e?.children[0];t?.geometry?.dispose(),t?.material?.dispose()}this.ownsAssets&&this.assets.dispose(),this.environment.dispose(),this.webgl.dispose()}},bA=new B,xA=new H,SA=new H,CA=new H,wA=new H,TA=new V,EA=new H,DA=new kl,OA=new B,kA=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>Yx,WATER_MAX_RIPPLES:()=>8,enablePhysics3D:()=>mS}),AA=new WeakMap,jA=class e{account;roomId;roomState=new t;allUserStates=new t;userJoined=new t;userLeft=new t;globalState=new t;globalMyState=new t;asset=new t;latestUserStates={};latestRoomState={};latestGlobalState={};latestGlobalMyState={};latestAsset={};server;engine;throttleMs;subs=[];messageSignals=new Map;collectionSignals=new Map;latestCollections=new Map;globalMessageSignals=new Map;globalCollectionSignals=new Map;latestGlobalCollections=new Map;scenes=new Map;lastSent=new Map;sendAccumulator=0;detachReplication=null;lastOwner=null;boundScene=null;static get(e){return AA.get(e)??null}static async create(t,n={}){await AA.get(t)?.dispose();let r=n.transport??await IA(n.config);await r.connect();let i=n.room??t.scene?.multiplayer?.room??`auto`,a=new e(t,r,await r.remoteFunction(`joinRoom`,[i===`auto`?void 0:i],{needResponse:!0}),n.throttleMs??50);return AA.set(t,a),a}constructor(e,t,n,r){this.engine=e,this.server=t,this.roomId=n,this.account=t.account,this.throttleMs=Math.max(30,r),this.boundScene=e.scene,this.subs.push(t.subscribeRoomState(n,e=>{this.latestRoomState=e,this.roomState.emit(e)}),t.subscribeRoomAllUserStates(n,e=>{this.latestUserStates=e,this.allUserStates.emit(e)}),t.onRoomUserJoin(n,e=>this.userJoined.emit(e)),t.onRoomUserLeave(n,e=>this.userLeft.emit(e))),t.subscribeGlobalState&&this.subs.push(t.subscribeGlobalState(e=>{this.latestGlobalState=e,this.globalState.emit(e)})),t.subscribeGlobalMyState&&this.subs.push(t.subscribeGlobalMyState(e=>{this.latestGlobalMyState=e,this.globalMyState.emit(e)})),t.subscribeAsset&&this.subs.push(t.subscribeAsset(this.account,e=>{this.latestAsset=e,this.asset.emit(e)})),this.detachReplication=e.fixedUpdated.connect(e=>this.replicate(e))}message(e){let n=this.messageSignals.get(e);return n||(n=new t,this.messageSignals.set(e,n),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>n?.emit(e)))),n}collection(e){let n=this.collectionSignals.get(e);return n||(n=new t,this.collectionSignals.set(e,n),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,t=>{this.latestCollections.set(e,t),n?.emit(t)}))),n}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let n=this.globalMessageSignals.get(e);if(!n){n=new t,this.globalMessageSignals.set(e,n);let r=this.server.onGlobalMessage?.(e,e=>n?.emit(e));r&&this.subs.push(r)}return n}globalCollection(e){let n=this.globalCollectionSignals.get(e);if(!n){n=new t,this.globalCollectionSignals.set(e,n);let r=this.server.subscribeGlobalCollection?.(e,t=>{this.latestGlobalCollections.set(e,t),n?.emit(t)});r&&this.subs.push(r)}return n}latestGlobalCollection(e){return this.globalCollection(e),this.latestGlobalCollections.get(e)??{}}setMyState(e){return this.server.remoteFunction(`setMyState`,[this.roomId,e],{throttle:this.throttleMs,throttleKey:`incanto:myState`})}patchRoomState(e){return this.server.remoteFunction(`patchRoomState`,[this.roomId,e])}addEntity(e,t){return this.server.remoteFunction(`addEntity`,[this.roomId,e,t])}updateEntity(e,t,n){return this.server.remoteFunction(`updateEntity`,[this.roomId,e,t,n])}removeEntity(e,t){return this.server.remoteFunction(`removeEntity`,[this.roomId,e,t])}sendEvent(e,t){return this.server.remoteFunction(`sendEvent`,[this.roomId,e,t])}call(e,...t){return this.server.remoteFunction(e,[this.roomId,...t],{needResponse:!0})}registerScene(e,t){this.scenes.set(e,t)}resolveScene(e){let t=this.scenes.get(e);if(!t)throw new y(`UNRESOLVED_INSTANCE`,`No scene registered for '${e}'. Registered: [${[...this.scenes.keys()].join(`, `)}]. Call manager.registerScene('${e}', sceneJson).`);return t}async dispose(){this.detachReplication?.();for(let e of this.subs)e();await this.server.remoteFunction(`leaveRoom`,[this.roomId]),AA.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3;let n=MA(t.root,!0);if(!n)return;n!==this.lastOwner&&(this.lastOwner=n,this.lastSent.clear());let r=n.network,i=Math.max(30,typeof r.throttleMs==`number`?r.throttleMs:this.throttleMs),a=Array.isArray(r.sync)?r.sync:[],o={};for(let e of a){let t=PA(n,e);t!==void 0&&(de(this.lastSent.get(e)??null,t)||(o[e]=j(t)))}if(!(this.sendAccumulator<i)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,j(t));this.sendAccumulator=0,this.setMyState({sync:o})}}};function MA(e,t=!1){let n=[];if(NA(e,n),t&&n.length>1)throw new y(`BAD_FORMAT`,`Multiple network owner nodes found (${n.map(e=>e.getPath()).join(`, `)}). Exactly ONE node per player may declare network.mode 'owner' — replicate spawned entities through collections instead.`);return n[0]??null}function NA(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)NA(n,t)}function PA(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:e.getNodeOrNull(t.slice(0,n))??void 0,i=n===-1?t:t.slice(n+1);if(r)return r[i]}function FA(e,t,n){for(let[r,i]of Object.entries(t)){let t=r.lastIndexOf(`.`),a=t===-1?e:e.getNodeOrNull(r.slice(0,t)),o=t===-1?r:r.slice(t+1);a&&n(a,o,i)}}async function IA(e){let{createAgent8Server:t}=await _h(async()=>{let{createAgent8Server:e}=await import(`./agent8-e6PNzw9c.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var LA=class extends Pe{static typeName=`NetworkSpawner`;static signals=[`spawned`,`despawned`];static props={source:{default:`users`},scene:{default:``},interpolate:{default:!0}};source=`users`;scene=``;interpolate=!0;spawned=new Map;positionTargets=new Map;failedKeys=new Set;update(e){let t=this.tree?.engine;if(!t)return;let n=jA.get(t);if(!n||this.scene===``)return;let r=this.currentEntries(n);for(let[e,t]of Object.entries(r)){let r=this.spawned.get(e);if(!r){if(this.failedKeys.has(e))continue;try{r=St(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=RA(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=t.sync;i&&FA(r,i,(e,t,n)=>this.setProp(e,t,n))}for(let[e,t]of[...this.spawned.entries()])e in r||(this.spawned.delete(e),this.positionTargets.delete(t),this.emit(`despawned`,t,e),t.free());this.interpolate&&this.stepInterpolation(e)}currentEntries(e){if(this.source===`users`){let t={};for(let[n,r]of Object.entries(e.latestUserStates))n!==e.account&&(t[n]=r);return t}return this.source.startsWith(`collection:`)?e.latestCollection(this.source.slice(11)):{}}setProp(e,t,n){if(this.interpolate&&t===`position`&&Array.isArray(n)){this.positionTargets.set(e,n);return}e[t]=n}stepInterpolation(e){let t=Math.min(1,e*8);for(let[e,n]of this.positionTargets){let r=e.position;Array.isArray(r)&&(e.position=r.map((e,r)=>e+((n[r]??e)-e)*t))}}};function RA(e){return e.replace(/[/%]/g,`_`)||`remote`}function zA(){ct(),M(LA)}var BA=80,VA=` `;function HA(e){return`${UA(e,0)}\n`}function UA(e,t){if(typeof e!=`object`||!e)return JSON.stringify(e);let n=WA(e);if(t*2+n.length<=BA)return n;let r=VA.repeat(t+1),i=VA.repeat(t);if(Array.isArray(e))return e.length===0?`[]`:`[\n${e.map(e=>r+UA(e,t+1)).join(`,
|
|
8222
|
+
}`};var Sk=[`type`,`sunPosition`,`elevationDeg`,`azimuthDeg`,`turbidity`,`rayleigh`],Ck=[`color`,`near`,`far`],wk=[`coverage`,`density`,`base`,`top`,`color`,`shadeColor`,`speed`,`scale`],Tk=[`threshold`,`strength`],Ek=[`vignette`,`saturation`,`contrast`],Dk=[`mapSize`,`radius`,`static`],Ok=[1024,2048],kk=2,Ak=1,jk=50,Mk=800,Nk=`#cfd8e0`,Pk=Math.PI/180;function Fk(e){return{exposure:zk(e?.exposure),sky:Bk(e?.sky),fog:Vk(e?.fog,e?.sky!==void 0),clouds:Hk(e?.clouds),bloom:Uk(e?.bloom),post:Wk(e?.post),shadows:Gk(e?.shadows)}}function Ik(e,t){let n=(90-e)*Pk,r=t*Pk;return[Math.sin(n)*Math.sin(r),Math.cos(n),Math.sin(n)*Math.cos(r)]}function Lk(e){let[t,n,r]=e.sunPosition,i=Math.hypot(t,n,r)||1;return[t/i,n/i,r/i]}function Rk(e){let t=[191,213,232],n=[233,228,217],r=[242,201,150],i=Jk((e.turbidity-kk)/8),a=Lk(e),o=Jk((18-Math.asin(qk(a[1],-1,1))/Pk)/18)*.8,s=e=>Math.round(Yk(Yk(t[e],n[e],i),r[e],o));return`#${[s(0),s(1),s(2)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}function zk(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw new y(`BAD_FORMAT`,`environment.exposure must be a finite number > 0 (tone-mapping exposure, default 1), got ${JSON.stringify(e)}.`,{prop:`exposure`});return e}function Bk(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.sky must be an object ({ type?: "atmosphere", sunPosition? | elevationDeg?+azimuthDeg?, turbidity?, rayleigh? }), got ${JSON.stringify(e)}.`,{prop:`sky`});let t=e;for(let e of Object.keys(t))if(!Sk.includes(e))throw new y(`BAD_FORMAT`,`environment.sky has unknown key '${e}'. Valid keys: [${Sk.join(`, `)}].`,{prop:`sky`,validOptions:Sk});if(t.type!==void 0&&t.type!==`atmosphere`)throw new y(`BAD_FORMAT`,`environment.sky.type must be 'atmosphere' (the only sky type so far), got ${JSON.stringify(t.type)}.`,{prop:`sky`,validOptions:[`atmosphere`]});let n=t.elevationDeg!==void 0||t.azimuthDeg!==void 0;if(t.sunPosition!==void 0&&n)throw new y(`BAD_FORMAT`,`environment.sky takes sunPosition OR elevationDeg/azimuthDeg, not both.`,{prop:`sky`,validOptions:[`sunPosition`,`elevationDeg+azimuthDeg`]});let r;if(t.sunPosition!==void 0){let e=t.sunPosition;if(!Array.isArray(e)||e.length!==3||!e.every(e=>typeof e==`number`&&Number.isFinite(e))||Math.hypot(e[0],e[1],e[2])===0)throw new y(`BAD_FORMAT`,`environment.sky.sunPosition must be a non-zero [x, y, z] vector, got ${JSON.stringify(e)}.`,{prop:`sky`});r=[e[0],e[1],e[2]]}else{let e=Kk(t.elevationDeg,32,`sky.elevationDeg`),n=Kk(t.azimuthDeg,135,`sky.azimuthDeg`);if(e<-90||e>90)throw new y(`BAD_FORMAT`,`environment.sky.elevationDeg must be in [-90, 90] (degrees above the horizon), got ${e}.`,{prop:`sky`});r=Ik(e,n)}let i=Kk(t.turbidity,kk,`sky.turbidity`);if(i<=0)throw new y(`BAD_FORMAT`,`environment.sky.turbidity must be > 0 (atmospheric haze; 2 ≈ clear day), got ${i}.`,{prop:`sky`});let a=Kk(t.rayleigh,Ak,`sky.rayleigh`);if(a<0)throw new y(`BAD_FORMAT`,`environment.sky.rayleigh must be >= 0 (Rayleigh scattering; 1 ≈ earth-like), got ${a}.`,{prop:`sky`});return{sunPosition:r,turbidity:i,rayleigh:a}}function Vk(e,t){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.fog must be an object ({ color?, near?, far? }), got ${JSON.stringify(e)}.`,{prop:`fog`});let n=e;for(let e of Object.keys(n))if(!Ck.includes(e))throw new y(`BAD_FORMAT`,`environment.fog has unknown key '${e}'. Valid keys: [${Ck.join(`, `)}].`,{prop:`fog`,validOptions:Ck});if(n.color!==void 0&&typeof n.color!=`string`)throw new y(`BAD_FORMAT`,`environment.fog.color must be a hex color string, got ${JSON.stringify(n.color)}.`,{prop:`fog`});let r=Kk(n.near,jk,`fog.near`),i=Kk(n.far,Mk,`fog.far`);if(r<0)throw new y(`BAD_FORMAT`,`environment.fog.near must be >= 0 meters, got ${r}.`,{prop:`fog`});if(i<=r)throw new y(`BAD_FORMAT`,`environment.fog.far must be > near (got near ${r}, far ${i}).`,{prop:`fog`});return{color:n.color??(t?``:Nk),near:r,far:i}}function Hk(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.clouds must be an object ({ coverage?, density?, base?, top?, color?, shadeColor?, speed?, scale? }), got ${JSON.stringify(e)}.`,{prop:`clouds`});let t=e;for(let e of Object.keys(t))if(!wk.includes(e))throw new y(`BAD_FORMAT`,`environment.clouds has unknown key '${e}'. Valid keys: [${wk.join(`, `)}].`,{prop:`clouds`,validOptions:wk});for(let e of[`color`,`shadeColor`])if(t[e]!==void 0&&typeof t[e]!=`string`)throw new y(`BAD_FORMAT`,`environment.clouds.${e} must be a hex color string, got ${JSON.stringify(t[e])}.`,{prop:`clouds`});let n=Kk(t.coverage,.5,`clouds.coverage`);if(n<0||n>1)throw new y(`BAD_FORMAT`,`environment.clouds.coverage must be in [0, 1] (how much sky is cloudy), got ${n}.`,{prop:`clouds`});let r=Kk(t.density,1,`clouds.density`);if(r<0)throw new y(`BAD_FORMAT`,`environment.clouds.density must be >= 0 (optical thickness), got ${r}.`,{prop:`clouds`});let i=Kk(t.base,120,`clouds.base`),a=Kk(t.top,320,`clouds.top`);if(a<=i)throw new y(`BAD_FORMAT`,`environment.clouds.top must be > base (got base ${i}, top ${a}).`,{prop:`clouds`});let o=Kk(t.speed,1,`clouds.speed`),s=Kk(t.scale,240,`clouds.scale`);if(s<=0)throw new y(`BAD_FORMAT`,`environment.clouds.scale must be > 0 (feature size in world units), got ${s}.`,{prop:`clouds`});return{coverage:n,density:r,base:i,top:a,color:t.color??`#ffffff`,shadeColor:t.shadeColor??`#9fb0c8`,speed:o,scale:s}}function Uk(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.bloom must be an object ({ threshold?, strength? }), got ${JSON.stringify(e)}.`,{prop:`bloom`});let t=e;for(let e of Object.keys(t))if(!Tk.includes(e))throw new y(`BAD_FORMAT`,`environment.bloom has unknown key '${e}'. Valid keys: [${Tk.join(`, `)}].`,{prop:`bloom`,validOptions:Tk});let n=Kk(t.threshold,1,`bloom.threshold`);if(n<0||n>8)throw new y(`BAD_FORMAT`,`environment.bloom.threshold must be in [0, 8] (linear-HDR luminance; 1 = white), got ${n}.`,{prop:`bloom`});let r=Kk(t.strength,.8,`bloom.strength`);if(r<0)throw new y(`BAD_FORMAT`,`environment.bloom.strength must be >= 0, got ${r}.`,{prop:`bloom`});return{threshold:n,strength:r}}function Wk(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.post must be an object ({ vignette?, saturation?, contrast? }), got ${JSON.stringify(e)}.`,{prop:`post`});let t=e;for(let e of Object.keys(t))if(!Ek.includes(e))throw new y(`BAD_FORMAT`,`environment.post has unknown key '${e}'. Valid keys: [${Ek.join(`, `)}].`,{prop:`post`,validOptions:Ek});let n=Kk(t.vignette,0,`post.vignette`);if(n<0||n>1)throw new y(`BAD_FORMAT`,`environment.post.vignette must be in [0, 1], got ${n}.`,{prop:`post`});let r=Kk(t.saturation,1,`post.saturation`);if(r<0||r>4)throw new y(`BAD_FORMAT`,`environment.post.saturation must be in [0, 4] (1 = neutral), got ${r}.`,{prop:`post`});let i=Kk(t.contrast,1,`post.contrast`);if(i<.2||i>3)throw new y(`BAD_FORMAT`,`environment.post.contrast must be in [0.2, 3] (1 = neutral), got ${i}.`,{prop:`post`});return{vignette:n,saturation:r,contrast:i}}function Gk(e){if(e===void 0)return null;if(e===!1)return!1;if(e===!0)return{mapSize:2048,radius:1,static:!1};if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`BAD_FORMAT`,`environment.shadows must be true, false or an object ({ mapSize?, radius? }), got ${JSON.stringify(e)}.`,{prop:`shadows`});let t=e;for(let e of Object.keys(t))if(!Dk.includes(e))throw new y(`BAD_FORMAT`,`environment.shadows has unknown key '${e}'. Valid keys: [${Dk.join(`, `)}].`,{prop:`shadows`,validOptions:Dk});let n=t.mapSize===void 0?2048:t.mapSize;if(!Ok.includes(n))throw new y(`BAD_FORMAT`,`environment.shadows.mapSize must be one of [${Ok.join(`, `)}], got ${JSON.stringify(t.mapSize)}.`,{prop:`shadows`,validOptions:Ok.map(String)});let r=Kk(t.radius,1,`shadows.radius`);if(r<0)throw new y(`BAD_FORMAT`,`environment.shadows.radius must be >= 0, got ${r}.`,{prop:`shadows`});let i=t.static===void 0?!1:t.static;if(typeof i!=`boolean`)throw new y(`BAD_FORMAT`,`environment.shadows.static must be a boolean, got ${JSON.stringify(t.static)}.`,{prop:`shadows`});return{mapSize:n,radius:r,static:i}}function Kk(e,t,n){if(e===void 0)return t;if(typeof e!=`number`||!Number.isFinite(e))throw new y(`BAD_FORMAT`,`environment.${n} must be a finite number, got ${JSON.stringify(e)}.`,{prop:n});return e}function qk(e,t,n){return Math.min(Math.max(e,t),n)}function Jk(e){return qk(e,0,1)}function Yk(e,t,n){return e+(t-e)*n}var Xk=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,Zk={apartment:`lebombo_1k.hdr`,city:`potsdamer_platz_1k.hdr`,dawn:`kiara_1_dawn_1k.hdr`,forest:`forest_slope_1k.hdr`,lobby:`st_fagans_interior_1k.hdr`,night:`dikhololo_night_1k.hdr`,park:`rooitou_park_1k.hdr`,studio:`studio_small_03_1k.hdr`,sunset:`venice_sunset_1k.hdr`,warehouse:`empty_warehouse_01_1k.hdr`};function Qk(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=Zk[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(Zk).join(`, `)}.`);return`${Xk}/${t}`}return null}var $k=75,eA=class{scene;ambient=new rl(`#ffffff`,0);envKey=null;config=Fk(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new oa(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new G;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?Lk(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get post(){return this.config.post}get sceneFog(){return this.scene.fog instanceof oa?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=Fk(e));let r=this.config,i=e?.ambient;if(this.ambient.color.set(i?.color??`#ffffff`),this.ambient.intensity=i?.intensity??0,t&&(t.toneMappingExposure=r.exposure,t.shadowMap.enabled=r.shadows!==!1,r.shadows!==!1&&r.shadows!==null&&r.shadows.static?t.shadowMap.autoUpdate&&(t.shadowMap.autoUpdate=!1,t.shadowMap.needsUpdate=!0):t.shadowMap.autoUpdate||(t.shadowMap.autoUpdate=!0)),this.applyHdri(e),this.applySky(r.sky,t),this._sky&&(this._sky.visible=!0),this.applyFog(r),this.scene.environment=this.hdriTexture??this.skyEnvTarget?.texture??null,this.scene.environmentIntensity=(this.scene.environment===this.skyEnvTarget?.texture&&this.skyEnvTarget?.55:1)*tA(e?.iblIntensity),e?.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new G(t):null}}applySunLight(e,t=null){if(!e)return;let n=this.sunDirection;if(t){let r=e.position.length()||100,i,a,o;if(n)[i,a,o]=n;else{i=e.position.x-e.target.position.x,a=e.position.y-e.target.position.y,o=e.position.z-e.target.position.z;let t=Math.hypot(i,a,o)||1;i/=t,a/=t,o/=t}e.target.position.set(t.x,t.y,t.z),e.target.updateMatrixWorld(),e.position.set(t.x+i*r,t.y+a*r,t.z+o*r)}else if(n){let t=e.position.length()||100;e.position.set(n[0],n[1],n[2]).multiplyScalar(t)}let r=this.config.shadows;if(r&&typeof r==`object`){if(!e.castShadow){let t=e.shadow.camera;`left`in t&&t.left===-5&&(t.left=-75,t.right=$k,t.top=$k,t.bottom=-75,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.castShadow=!0}e.shadow.mapSize.x!==r.mapSize&&(e.shadow.mapSize.set(r.mapSize,r.mapSize),e.shadow.map?.dispose(),e.shadow.map=null),e.shadow.radius=r.radius}}applyUnderwater(e){e&&(this.underwaterFog||=new oa(`#000000`,.5,e.visibility),this.underwaterFog.color.set(e.color),this.underwaterFog.near=.5,this.underwaterFog.far=e.visibility,this.scene.fog=this.underwaterFog,this.scene.background=this.underwaterBg.set(e.color),this._sky&&(this._sky.visible=!1))}applyHdri(e){let t=Qk(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new bk().load(t,e=>{if(this.hdriUrl!==t){e.dispose();return}e.mapping=303,this.hdriTexture=e}))}applySky(e,t){let n=e?JSON.stringify(e):``;if(n!==this.skyKey&&(this.skyKey=n,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null),e)){this._sky=new xk,this._sky.scale.setScalar(45e4);let t=this._sky.material.uniforms;(t.sunPosition?.value).set(...e.sunPosition),t.turbidity&&(t.turbidity.value=e.turbidity),t.rayleigh&&(t.rayleigh.value=e.rayleigh),this.scene.add(this._sky)}if(e&&t&&this._sky&&this.skyEnvKey!==n){this.skyEnvKey=n,this.skyEnvTarget?.dispose();let e=new ru(t),r=new sa;r.add(this._sky),this.skyEnvTarget=e.fromScene(r),e.dispose(),this.scene.add(this._sky)}!e&&this.skyEnvTarget&&(this.skyEnvTarget.dispose(),this.skyEnvTarget=null,this.skyEnvKey=``)}applyFog(e){if(!e.fog){this.scene.fog=null;return}let t=e.fog.color||(e.sky?Rk(e.sky):`#cfd8e0`);this.fog.color.set(t),this.fog.near=e.fog.near,this.fog.far=e.fog.far,this.scene.fog=this.fog}dispose(){this.hdriTexture?.dispose(),this.hdriTexture=null,this.skyEnvTarget?.dispose(),this.skyEnvTarget=null,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null)}};function tA(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new y(`BAD_FORMAT`,`environment.iblIntensity must be a finite number >= 0 (multiplies the image-based ambience: sky-derived base 0.55, HDRI base 1; default 1), got ${JSON.stringify(e)}.`,{prop:`iblIntensity`});return e}var nA=new Sa,rA=new H,iA=.4,aA=new Float32Array(72);function oA(e){if(!(e instanceof qp))return null;let t=e._ensureObject3D();if(t.updateWorldMatrix(!0,!0),nA.setFromObject(t),nA.getSize(rA),!Number.isFinite(rA.x)||rA.x===0&&rA.y===0&&rA.z===0){let e=new H().setFromMatrixPosition(t.matrixWorld);nA.min.set(e.x-iA,e.y-iA,e.z-iA),nA.max.set(e.x+iA,e.y+iA,e.z+iA)}else nA.expandByScalar(.02);let{min:n,max:r}=nA,i=0,a=(e,t,n,r,a,o)=>{aA[i++]=e,aA[i++]=t,aA[i++]=n,aA[i++]=r,aA[i++]=a,aA[i++]=o};return a(n.x,n.y,n.z,r.x,n.y,n.z),a(r.x,n.y,n.z,r.x,n.y,r.z),a(r.x,n.y,r.z,n.x,n.y,r.z),a(n.x,n.y,r.z,n.x,n.y,n.z),a(n.x,r.y,n.z,r.x,r.y,n.z),a(r.x,r.y,n.z,r.x,r.y,r.z),a(r.x,r.y,r.z,n.x,r.y,r.z),a(n.x,r.y,r.z,n.x,r.y,n.z),a(n.x,n.y,n.z,n.x,r.y,n.z),a(r.x,n.y,n.z,r.x,r.y,n.z),a(r.x,n.y,r.z,r.x,r.y,r.z),a(n.x,n.y,r.z,n.x,r.y,r.z),aA}function sA(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function cA(){let e=new Set,t=[],n=[],r=[];return{visited:e,cameras:t,renderHooks:n,emitters:r,state:{visited:e,cameras:t,renderHooks:n,emitters:r,assets:void 0,sunDirection:null,sunLight:null,alpha:1,ignoreStatic:!1}}}function lA(e,t,n,r,i){let a=i??cA();a.visited.clear(),a.cameras.length=0,a.renderHooks.length=0,a.emitters.length=0;let o=a.state;o.assets=n,o.sunDirection=r?.sunDirection??null,o.ignoreStatic=r?.ignoreStatic===!0,o.sunLight=null,o.alpha=r?.alpha??1,hA(e,t,o),vA(t,a.visited);let s=null;for(let e=0;e<a.cameras.length;e++){let t=a.cameras[e];if(t.current){s=t;break}}s||=a.cameras[0]??null;let c=s?s._ensureObject3D():null;return mA(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var uA=new H,dA=new H,fA=new H,pA=new H;function mA(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(dA),t.getWorldDirection(fA),pA.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[dA.x,dA.y,dA.z],forward:[fA.x,fA.y,fA.z],up:[pA.x,pA.y,pA.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(uA),t._setSpatialPose({position:[uA.x,uA.y,uA.z],listener:n})}function hA(e,t,n){let r=t;if(e instanceof qp){let i=e._ensureObject3D();if(e.static&&!n.ignoreStatic&&i.userData.incantoStaticSynced===!0){i.userData.incantoStatic=!0,n.visited.add(i);return}if(i.parent!==t&&t.add(i),e._syncObject3D(n.alpha),n.assets&&e instanceof AE&&e._syncModel(n.assets),typeof e._onRender3D==`function`&&n.renderHooks.push(e),n.sunDirection){let t=e._applySunDirection;typeof t==`function`&&t.call(e,n.sunDirection)}e instanceof hE&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof hC&&n.cameras.push(e),r=i}else sA(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)hA(t,r,n);if(e instanceof qp){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,_A(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var gA=new WeakSet;function _A(e){if(gA.has(e))return;gA.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof hC)&&t.push(`${e.name} (${e.constructor.typeName??`?`})`);for(let t of e.children)n(t)};n(e),t.length>0&&console.warn(`[incanto] static subtree '${e.name}' freezes animated/per-frame nodes: ${t.join(`, `)} — they will stop updating. Unmark static or move them out.`)}function vA(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&vA(i,t)}}var yA=class{viewOverride=null;overrideCam=new Yc(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new sa;environment=new eA(this.threeScene);engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;syncScratch=cA();ignoreStatic=!1;renderCtx=null;causticsTarget=null;causticsScene=null;causticsUniforms=null;cloudsTarget=null;cloudsHalfTarget=null;cloudsBlurTarget=null;cloudsScene=null;cloudsUniforms=null;cloudsBlurScene=null;cloudsBlurUniforms=null;cloudsCompositeScene=null;cloudsCompositeUniforms=null;bloomTarget=null;bloomBrightTarget=null;bloomBlurTarget=null;bloomBrightScene=null;bloomBrightUniforms=null;bloomBlurScene=null;bloomBlurUniforms=null;bloomCompositeScene=null;bloomCompositeUniforms=null;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.ownsAssets=!e.assets,this.assets=e.assets??new Sx;let t=lt(e.engine.scene?.environment,{antialias:!0,pixelRatio:Math.min(globalThis.devicePixelRatio??1,2)},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio});this.webgl=new Zf({canvas:e.canvas,antialias:t.antialias}),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.adaptive=e.adaptiveResolution===!1?null:new rk,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new ws(new q,new fs({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new ws(new q,new fs({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.threeScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>this.render())}basePixelRatio;adaptive;lastFrameAt=0;debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?oA(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new K(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of fh(`3d`))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new K(e,3))}governResolution(){let e=this.adaptive;if(!e)return;let t=globalThis.performance?.now?.()??0,n=this.lastFrameAt;if(this.lastFrameAt=t,n===0)return;let r=t-n;if(r>500){e.reset();return}let i=e.push(r);if(i===null)return;this.webgl.setPixelRatio(this.basePixelRatio*i);let a=this.lastSize;a.w>0&&a.h>0&&this.webgl.setSize(a.w,a.h,!1)}render(){let e=this.engine.scene;if(!e)return;this.governResolution(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e)),this.environment.apply(e.environment,this.webgl);let{activeCamera:t,renderHooks:n,sunLight:r}=lA(e.root,this.threeScene,this.assets,{sunDirection:this.environment.sunDirection,alpha:this.engine.interpolationAlpha,ignoreStatic:this.ignoreStatic},this.syncScratch),i=t;if(this.viewOverride){let[e,t,n]=this.viewOverride.position,[r,a,o]=this.viewOverride.target;this.overrideCam.position.set(e,t,n),this.overrideCam.lookAt(xA.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(EA),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i));let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(bA);(u.x!==c||u.y!==l)&&this.webgl.setSize(c,l,!1),this.lastSize={w:c,h:l};let d=l===0?1:c/l;i.aspect!==d&&(i.aspect=d,i.updateProjectionMatrix()),this.renderCtx||={gl:this.webgl,scene:this.threeScene,camera:i};let f=this.renderCtx;f.camera=i,o?(o.updateWorldMatrix(!0,!1),o.target.updateWorldMatrix(!0,!1),f.sunDir=CA.setFromMatrixPosition(o.matrixWorld).sub(wA.setFromMatrixPosition(o.target.matrixWorld)).normalize()):f.sunDir=null;for(let e=0;e<n.length;e++)n[e]?._onRender3D(f);let p=null;for(let e=0;e<n.length;e++){let t=n[e].underwaterAt?.(a.x,a.y,a.z);if(t){p=t;break}}this.environment.applyUnderwater(p);let m=this.environment.clouds,h=this.environment.bloom,g=this.environment.post;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):(h||g)&&!p?this.renderWithBloom(i,h,g):this.webgl.render(this.threeScene,i)}renderWithBloom(e,t,n=null){let r=this.webgl.getDrawingBufferSize(bA),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/2)),s=Math.max(1,Math.ceil(a/2));if(this.bloomTarget&&(this.bloomTarget.width!==i||this.bloomTarget.height!==a)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new Si(i,a,{type:Qt}),this.bloomBrightTarget=new Si(o,s,{type:Qt}),this.bloomBlurTarget=new Si(o,s,{type:Qt})),!this.bloomBrightScene){let e=lk();this.bloomBrightScene=new sa,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=uk();this.bloomBlurScene=new sa,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=dk();this.bloomCompositeScene=new sa,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let c=this.bloomBrightTarget,l=this.bloomBlurTarget;if(this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e),t){let n=this.bloomBrightUniforms;n.tScene.value=this.bloomTarget.texture,n.uThreshold.value=t.threshold,this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBrightScene,e);let r=this.bloomBlurUniforms;r.tTex.value=c.texture,r.uDir.value.set(1/o,0),this.webgl.setRenderTarget(l),this.webgl.render(this.bloomBlurScene,e),r.tTex.value=l.texture,r.uDir.value.set(0,1/s),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e)}let u=this.bloomCompositeUniforms;u.tScene.value=this.bloomTarget.texture,u.tBloom.value=t?c.texture:this.bloomTarget.texture,u.uStrength.value=t?t.strength:0,u.uVignette.value=n?.vignette??0,u.uSaturation.value=n?.saturation??1,u.uContrast.value=n?.contrast??1,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(bA),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/3)),s=Math.max(1,Math.ceil(a/3));if(this.cloudsTarget&&(this.cloudsTarget.width!==i||this.cloudsTarget.height!==a)&&(this.cloudsTarget.depthTexture?.dispose(),this.cloudsTarget.dispose(),this.cloudsTarget=null,this.cloudsHalfTarget?.dispose(),this.cloudsHalfTarget=null,this.cloudsBlurTarget?.dispose(),this.cloudsBlurTarget=null),!this.cloudsTarget){let e=new Fs(i,a);e.type=Zt,this.cloudsTarget=new Si(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Si(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Si(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=_k();this.cloudsScene=new sa,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=gk();this.cloudsBlurScene=new sa,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=vk();this.cloudsCompositeScene=new sa,this.cloudsCompositeScene.add(e),this.cloudsCompositeUniforms=t}this.webgl.setRenderTarget(this.cloudsTarget),this.webgl.render(this.threeScene,e);let c=this.cloudsUniforms;c.tDepth.value=this.cloudsTarget.depthTexture,c.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(c.uCameraPos.value),c.uTime.value=(globalThis.performance?.now()??0)*.001*t.speed;let l=this.environment.sunDirection??[.4,.8,.3];c.uSunDir.value.set(l[0],l[1],l[2]).normalize(),n&&c.uSunColor.value.copy(n.color),c.uCloudColor.value.set(t.color),c.uShadeColor.value.set(t.shadeColor);let u=this.environment.sceneFog;u?(c.uHorizonColor.value.copy(u.color),c.uFarFade.value=u.far):(c.uHorizonColor.value.set(`#cdd9e6`),c.uFarFade.value=6e3),c.uBase.value=t.base,c.uTop.value=t.top,c.uCoverage.value=t.coverage,c.uDensity.value=t.density,c.uScale.value=t.scale,c.uWind.value.set(1,.35),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(this.cloudsScene,e);let d=this.cloudsBlurUniforms,f=this.cloudsBlurScene;d.tTex.value=this.cloudsHalfTarget.texture,d.uDir.value.set(1/o,0),this.webgl.setRenderTarget(this.cloudsBlurTarget),this.webgl.render(f,e),d.tTex.value=this.cloudsBlurTarget.texture,d.uDir.value.set(0,1/s),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(f,e),this.webgl.setRenderTarget(null);let p=this.cloudsCompositeUniforms;p.tScene.value=this.cloudsTarget.texture,p.tClouds.value=this.cloudsHalfTarget.texture,this.webgl.render(this.cloudsCompositeScene,e)}renderWithCaustics(e,t){let n=this.webgl.getDrawingBufferSize(bA),r=Math.max(1,n.x),i=Math.max(1,n.y);if(this.causticsTarget&&(this.causticsTarget.width!==r||this.causticsTarget.height!==i)&&(this.causticsTarget.depthTexture?.dispose(),this.causticsTarget.dispose(),this.causticsTarget=null),!this.causticsTarget){let e=new Fs(r,i);e.type=Zt,this.causticsTarget=new Si(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=yp();this.causticsScene=new sa,this.causticsScene.add(e),this.causticsUniforms=t}this.webgl.setRenderTarget(this.causticsTarget),this.webgl.render(this.threeScene,e),this.webgl.setRenderTarget(null);let a=this.causticsUniforms;a.tColor.value=this.causticsTarget.texture,a.tDepth.value=this.causticsTarget.depthTexture,a.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(a.uCameraPos.value),a.uWaterLevel.value=t.surfaceY,a.uTime.value=(globalThis.performance?.now()??0)*.001*t.caustics.speed,a.uCausticColor.value.set(t.caustics.color),a.uCausticIntensity.value=t.caustics.intensity,a.uCausticScale.value=t.caustics.scale,a.uMaxDist.value=t.visibility;let o=this.environment.sunDirection;o&&a.uSunDirection.value.set(o[0],o[1],o[2]),a.uRayStrength.value=t.rays.enabled?t.rays.strength:0,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(SA.set(e,t,n).project(r),{x:(SA.x+1)/2*this.lastSize.w,y:(1-SA.y)/2*this.lastSize.h,behind:SA.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;OA.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),DA.setFromCamera(OA,n);let r=DA.intersectObjects(this.threeScene.children,!0);for(let e of r){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(n)return n}return null}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(TA):TA.identity();return{right:new H(1,0,0).applyQuaternion(t),up:new H(0,1,0).applyQuaternion(t),forward:new H(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){this.disconnect(),this.threeScene.traverse(e=>{let t=e;if(!(!t.isMesh||t.userData?.incantoModelShared))if(t.geometry?.dispose(),Array.isArray(t.material))for(let e of t.material)e.dispose();else t.material?.dispose()}),this.causticsTarget?.depthTexture?.dispose(),this.causticsTarget?.dispose();let e=this.causticsScene?.children[0];e?.geometry?.dispose(),e?.material?.dispose(),this.cloudsTarget?.depthTexture?.dispose(),this.cloudsTarget?.dispose(),this.cloudsHalfTarget?.dispose(),this.cloudsBlurTarget?.dispose(),this.bloomTarget?.dispose(),this.bloomBrightTarget?.dispose(),this.bloomBlurTarget?.dispose();for(let e of[this.cloudsScene,this.cloudsBlurScene,this.cloudsCompositeScene,this.bloomBrightScene,this.bloomBlurScene,this.bloomCompositeScene]){let t=e?.children[0];t?.geometry?.dispose(),t?.material?.dispose()}this.ownsAssets&&this.assets.dispose(),this.environment.dispose(),this.webgl.dispose()}},bA=new B,xA=new H,SA=new H,CA=new H,wA=new H,TA=new V,EA=new H,DA=new kl,OA=new B,kA=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>Yx,WATER_MAX_RIPPLES:()=>8,enablePhysics3D:()=>mS}),AA=new WeakMap,jA=class e{account;roomId;roomState=new t;allUserStates=new t;userJoined=new t;userLeft=new t;globalState=new t;globalMyState=new t;asset=new t;latestUserStates={};latestRoomState={};latestGlobalState={};latestGlobalMyState={};latestAsset={};server;engine;throttleMs;subs=[];messageSignals=new Map;collectionSignals=new Map;latestCollections=new Map;globalMessageSignals=new Map;globalCollectionSignals=new Map;latestGlobalCollections=new Map;scenes=new Map;lastSent=new Map;sendAccumulator=0;detachReplication=null;lastOwner=null;boundScene=null;static get(e){return AA.get(e)??null}static async create(t,n={}){await AA.get(t)?.dispose();let r=n.transport??await IA(n.config);await r.connect();let i=n.room??t.scene?.multiplayer?.room??`auto`,a=new e(t,r,await r.remoteFunction(`joinRoom`,[i===`auto`?void 0:i],{needResponse:!0}),n.throttleMs??50);return AA.set(t,a),a}constructor(e,t,n,r){this.engine=e,this.server=t,this.roomId=n,this.account=t.account,this.throttleMs=Math.max(30,r),this.boundScene=e.scene,this.subs.push(t.subscribeRoomState(n,e=>{this.latestRoomState=e,this.roomState.emit(e)}),t.subscribeRoomAllUserStates(n,e=>{this.latestUserStates=e,this.allUserStates.emit(e)}),t.onRoomUserJoin(n,e=>this.userJoined.emit(e)),t.onRoomUserLeave(n,e=>this.userLeft.emit(e))),t.subscribeGlobalState&&this.subs.push(t.subscribeGlobalState(e=>{this.latestGlobalState=e,this.globalState.emit(e)})),t.subscribeGlobalMyState&&this.subs.push(t.subscribeGlobalMyState(e=>{this.latestGlobalMyState=e,this.globalMyState.emit(e)})),t.subscribeAsset&&this.subs.push(t.subscribeAsset(this.account,e=>{this.latestAsset=e,this.asset.emit(e)})),this.detachReplication=e.fixedUpdated.connect(e=>this.replicate(e))}message(e){let n=this.messageSignals.get(e);return n||(n=new t,this.messageSignals.set(e,n),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>n?.emit(e)))),n}collection(e){let n=this.collectionSignals.get(e);return n||(n=new t,this.collectionSignals.set(e,n),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,t=>{this.latestCollections.set(e,t),n?.emit(t)}))),n}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let n=this.globalMessageSignals.get(e);if(!n){n=new t,this.globalMessageSignals.set(e,n);let r=this.server.onGlobalMessage?.(e,e=>n?.emit(e));r&&this.subs.push(r)}return n}globalCollection(e){let n=this.globalCollectionSignals.get(e);if(!n){n=new t,this.globalCollectionSignals.set(e,n);let r=this.server.subscribeGlobalCollection?.(e,t=>{this.latestGlobalCollections.set(e,t),n?.emit(t)});r&&this.subs.push(r)}return n}latestGlobalCollection(e){return this.globalCollection(e),this.latestGlobalCollections.get(e)??{}}setMyState(e){return this.server.remoteFunction(`setMyState`,[this.roomId,e],{throttle:this.throttleMs,throttleKey:`incanto:myState`})}patchRoomState(e){return this.server.remoteFunction(`patchRoomState`,[this.roomId,e])}addEntity(e,t){return this.server.remoteFunction(`addEntity`,[this.roomId,e,t])}updateEntity(e,t,n){return this.server.remoteFunction(`updateEntity`,[this.roomId,e,t,n])}removeEntity(e,t){return this.server.remoteFunction(`removeEntity`,[this.roomId,e,t])}sendEvent(e,t){return this.server.remoteFunction(`sendEvent`,[this.roomId,e,t])}call(e,...t){return this.server.remoteFunction(e,[this.roomId,...t],{needResponse:!0})}registerScene(e,t){this.scenes.set(e,t)}resolveScene(e){let t=this.scenes.get(e);if(!t)throw new y(`UNRESOLVED_INSTANCE`,`No scene registered for '${e}'. Registered: [${[...this.scenes.keys()].join(`, `)}]. Call manager.registerScene('${e}', sceneJson).`);return t}async dispose(){this.detachReplication?.();for(let e of this.subs)e();await this.server.remoteFunction(`leaveRoom`,[this.roomId]),AA.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3;let n=MA(t.root,!0);if(!n)return;n!==this.lastOwner&&(this.lastOwner=n,this.lastSent.clear());let r=n.network,i=Math.max(30,typeof r.throttleMs==`number`?r.throttleMs:this.throttleMs),a=Array.isArray(r.sync)?r.sync:[],o={};for(let e of a){let t=PA(n,e);t!==void 0&&(de(this.lastSent.get(e)??null,t)||(o[e]=j(t)))}if(!(this.sendAccumulator<i)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,j(t));this.sendAccumulator=0,this.setMyState({sync:o})}}};function MA(e,t=!1){let n=[];if(NA(e,n),t&&n.length>1)throw new y(`BAD_FORMAT`,`Multiple network owner nodes found (${n.map(e=>e.getPath()).join(`, `)}). Exactly ONE node per player may declare network.mode 'owner' — replicate spawned entities through collections instead.`);return n[0]??null}function NA(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)NA(n,t)}function PA(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:e.getNodeOrNull(t.slice(0,n))??void 0,i=n===-1?t:t.slice(n+1);if(r)return r[i]}function FA(e,t,n){for(let[r,i]of Object.entries(t)){let t=r.lastIndexOf(`.`),a=t===-1?e:e.getNodeOrNull(r.slice(0,t)),o=t===-1?r:r.slice(t+1);a&&n(a,o,i)}}async function IA(e){let{createAgent8Server:t}=await _h(async()=>{let{createAgent8Server:e}=await import(`./agent8-DzaYTNiK.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var LA=class extends Pe{static typeName=`NetworkSpawner`;static signals=[`spawned`,`despawned`];static props={source:{default:`users`},scene:{default:``},interpolate:{default:!0}};source=`users`;scene=``;interpolate=!0;spawned=new Map;positionTargets=new Map;failedKeys=new Set;update(e){let t=this.tree?.engine;if(!t)return;let n=jA.get(t);if(!n||this.scene===``)return;let r=this.currentEntries(n);for(let[e,t]of Object.entries(r)){let r=this.spawned.get(e);if(!r){if(this.failedKeys.has(e))continue;try{r=St(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=RA(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=t.sync;i&&FA(r,i,(e,t,n)=>this.setProp(e,t,n))}for(let[e,t]of[...this.spawned.entries()])e in r||(this.spawned.delete(e),this.positionTargets.delete(t),this.emit(`despawned`,t,e),t.free());this.interpolate&&this.stepInterpolation(e)}currentEntries(e){if(this.source===`users`){let t={};for(let[n,r]of Object.entries(e.latestUserStates))n!==e.account&&(t[n]=r);return t}return this.source.startsWith(`collection:`)?e.latestCollection(this.source.slice(11)):{}}setProp(e,t,n){if(this.interpolate&&t===`position`&&Array.isArray(n)){this.positionTargets.set(e,n);return}e[t]=n}stepInterpolation(e){let t=Math.min(1,e*8);for(let[e,n]of this.positionTargets){let r=e.position;Array.isArray(r)&&(e.position=r.map((e,r)=>e+((n[r]??e)-e)*t))}}};function RA(e){return e.replace(/[/%]/g,`_`)||`remote`}function zA(){ct(),M(LA)}var BA=80,VA=` `;function HA(e){return`${UA(e,0)}\n`}function UA(e,t){if(typeof e!=`object`||!e)return JSON.stringify(e);let n=WA(e);if(t*2+n.length<=BA)return n;let r=VA.repeat(t+1),i=VA.repeat(t);if(Array.isArray(e))return e.length===0?`[]`:`[\n${e.map(e=>r+UA(e,t+1)).join(`,
|
|
8195
8223
|
`)}\n${i}]`;let a=Object.entries(e);return a.length===0?`{}`:`{\n${a.map(([e,n])=>`${r}${JSON.stringify(e)}: ${UA(n,t+1)}`).join(`,
|
|
8196
8224
|
`)}\n${i}}`}function WA(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return e.length===0?`[]`:`[${e.map(WA).join(`, `)}]`;let t=Object.entries(e);return t.length===0?`{}`:`{ ${t.map(([e,t])=>`${JSON.stringify(e)}: ${WA(t)}`).join(`, `)} }`}async function GA(e){if(!e.ok)throw Error(`HTTP ${e.status} — ${await e.text()}`);return e}async function KA(){return await(await GA(await fetch(`/api/meta`))).json()}async function qA(){return await(await GA(await fetch(`/api/scenes`))).json()}async function JA(e){return await(await GA(await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})}))).json()}function YA(e){return e?`/api/scene?file=${encodeURIComponent(e)}`:`/api/scene`}async function XA(e){return await(await GA(await fetch(YA(e)))).json()}async function ZA(e,t){await GA(await fetch(YA(t),{method:`PUT`,body:HA(e)}))}var QA=localStorage.getItem(`incanto-editor-lang`)??`en`,$A=new Set;function ej(){return QA}function tj(e){QA=e,localStorage.setItem(`incanto-editor-lang`,e);for(let e of $A)e()}function nj(e){$A.add(e)}function rj(e){return e[QA]}var ij={node:{paths:[`M5 5h14v14H5z`]},move:{paths:[`M12 3v18M3 12h18`,`M8 7l4-4 4 4M8 17l4 4 4-4M7 8l-4 4 4 4M17 8l4 4-4 4`]},image:{paths:[`M4 5h16v14H4z`,`M4 15l5-5 4 4 3-3 4 4`],circles:[[9,9,1.6]]},film:{paths:[`M4 4h16v16H4z`,`M4 9h16M4 15h16`,`M9 4v16M15 4v16`]},video:{paths:[`M3 7h12v10H3z`,`M15 10l6-3v10l-6-3`]},text:{paths:[`M5 7V5h14v2`,`M12 5v14`,`M9 19h6`]},layers:{paths:[`M12 3 3 8l9 5 9-5-9-5z`,`M3 12l9 5 9-5`,`M3 16l9 5 9-5`]},square:{paths:[`M5 5h14v14H5z`,`M5 12h14`]},ball:{paths:[`M12 8v0`],circles:[[12,12,8],[12,12,1.4]]},person:{paths:[`M5 21v-1a7 7 0 0 1 14 0v1`],circles:[[12,7,4]]},area:{paths:[`M5 5h14v14H5z`],dashed:!0},gamepad:{paths:[`M7 9h-0M6 12h4M8 10v4`,`M4 8h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2z`],circles:[[16,11,1],[18.5,13.5,1]]},clock:{paths:[`M12 7v5l3 2`],circles:[[12,12,9]]},cube:{paths:[`M21 16V8l-9-5-9 5v8l9 5 9-5z`,`M3.3 7.5 12 12.5l8.7-5`,`M12 22V12.5`]},sun:{paths:[`M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9 17 7M7 17l-2.1 2.1`],circles:[[12,12,4]]},bulb:{paths:[`M9 18h6M10 21h4`,`M8 13a6 6 0 1 1 8 0c-1 1-1.5 2-1.5 3h-5c0-1-.5-2-1.5-3z`]},globe:{paths:[`M2 12h20`,`M12 2a15 15 0 0 1 0 20a15 15 0 0 1 0-20z`],circles:[[12,12,10]]},link:{paths:[`M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1`,`M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1`]},speaker:{paths:[`M11 5 6 9H3v6h3l5 4V5z`,`M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13`]},swatch:{paths:[`M4 4h16v16H4z`,`M4 4l16 16`]},sparkles:{paths:[`M12 4v5M12 15v5M5 12h5M14 12h5`],circles:[[6,5,1],[18,19,1]]},waves:{paths:[`M2 8c3-3 5 3 8 0s5 3 8 0`,`M2 14c3-3 5 3 8 0s5 3 8 0`,`M2 20c3-3 5 3 8 0s5 3 8 0`]},plant:{paths:[`M12 21v-8`,`M12 13c0-4-3-6-7-6 0 4 3 6 7 6z`,`M12 11c0-4 3-6 7-6 0 4-3 6-7 6z`]},flower:{paths:[`M12 21v-7`],circles:[[12,9,2],[12,4.5,2.2],[16.3,7.5,2.2],[14.7,12.6,2.2],[9.3,12.6,2.2],[7.7,7.5,2.2]]},voxels:{paths:[`M4 14h8v8H4z`,`M12 14h8v8h-8z`,`M8 6h8v8H8z`]}},aj={Node:`node`,Timer:`clock`,AudioPlayer:`speaker`,ColorRect2D:`swatch`,Particles2D:`sparkles`,Particles3D:`sparkles`,Water3D:`waves`,Foliage3D:`plant`,Flowers3D:`flower`,VoxelGrid3D:`voxels`,ModelInstance3D:`person`,CharacterController3D:`gamepad`,Node2D:`move`,Sprite2D:`image`,AnimatedSprite2D:`film`,Camera2D:`video`,Label:`text`,UILayer:`layers`,StaticBody2D:`square`,RigidBody2D:`ball`,CharacterBody2D:`person`,Area2D:`area`,CharacterController2D:`gamepad`,Node3D:`move`,Billboard3D:`layers`,MeshInstance3D:`cube`,LoftMesh3D:`cube`,Camera3D:`video`,DirectionalLight3D:`sun`,OmniLight3D:`bulb`,StaticBody3D:`square`,RigidBody3D:`ball`,CharacterBody3D:`person`,Area3D:`area`,NetworkSpawner:`globe`};function oj(e){let t=ij[aj[e??``]??(e?`node`:`link`)],n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`width`,`13`),n.setAttribute(`height`,`13`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),t.dashed&&n.setAttribute(`stroke-dasharray`,`3 2.4`);for(let e of t.paths){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,e),n.appendChild(t)}for(let[e,r,i]of t.circles??[]){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);t.setAttribute(`cx`,String(e)),t.setAttribute(`cy`,String(r)),t.setAttribute(`r`,String(i)),n.appendChild(t)}return n}function sj(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`width`,`12`),e.setAttribute(`height`,`12`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2.4`),e.setAttribute(`aria-hidden`,`true`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`d`,`m6 9 6 6 6-6`),e.appendChild(t),e}var cj=[{type:`texture`,label:`image (texture)`,metaHints:[`filter`]},{type:`spritesheet`,label:`spritesheet`,metaHints:[`filter`,`frameWidth`,`frameHeight`]},{type:`model`,label:`3D model (GLB/VRM)`,metaHints:[]},{type:`animation`,label:`animation (GLB clips)`,metaHints:[`clip`]}],lj=new Set,uj=null,dj=null;function fj(e,t,n){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e;let i=()=>{let i=r.value.trim().replace(/\//g,``);i&&i!==e?t(i):n()};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`/`&&e.preventDefault(),e.key===`Enter`&&i(),e.key===`Escape`&&n()});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());return r.addEventListener(`blur`,i),queueMicrotask(()=>{r.focus(),r.select()}),r}function pj(e,t){let n={path:``,name:``,folders:new Map,assets:[]},r=e=>{let t=n;if(e===``)return t;for(let n of e.split(`/`)){let e=t.folders.get(n);e||(e={path:t.path?`${t.path}/${n}`:n,name:n,folders:new Map,assets:[]},t.folders.set(n,e)),t=e}return t};for(let t of e){let e=t.lastIndexOf(`/`);r(e===-1?``:t.slice(0,e)).assets.push(t)}for(let e of t)r(e);return n}function mj(e){let t=e.assets.length;for(let n of e.folders.values())t+=mj(n);return t}function hj(e,t){e.textContent=``;let n=t.working.assets??{},r=Object.keys(n);if(r.length===0&&t.pendingGroups.size===0&&!t.addingAsset&&!t.addingGroup){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no assets yet — + adds textures, models, animations`,e.appendChild(t);return}let i=(e,n)=>{e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.add(`drop-target`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-target`)),e.addEventListener(`drop`,r=>{r.preventDefault(),r.stopPropagation(),e.classList.remove(`drop-target`);let i=r.dataTransfer?.getData(`text/incanto-asset`);i&&t.moveAsset(i,n);let a=r.dataTransfer?.getData(`text/incanto-group`);a&&t.moveGroup(a,n)})};i(e,``);let a=(e,r)=>{let i=n[e],a=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,o=document.createElement(`div`);o.className=`tree-row asset-row${t.selectedAsset===e?` selected`:``}`,o.draggable=!0,o.addEventListener(`dragstart`,t=>{t.dataTransfer?.setData(`text/incanto-asset`,e)});let s=document.createElement(`span`);if(s.className=`tree-icon`,s.appendChild(Dj(i.type??``)),s.addEventListener(`click`,e=>{e.stopPropagation(),Oj(s,i.type??``)}),uj===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;o.appendChild(fj(a,r=>{uj=null,t.renameAssetKey(e,n+r)},()=>{uj=null,t.selectAsset(t.selectedAsset)})),o.draggable=!1,o.insertBefore(s,o.firstChild),r.appendChild(o);return}let c=document.createElement(`span`);c.className=`tree-name asset-key`,c.textContent=`$${a}`,c.title=`$${e}`,c.addEventListener(`dblclick`,n=>{n.stopPropagation(),uj=e,t.selectAsset(e)}),o.append(s,c),o.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(o)},o=(e,n)=>{let r=lj.has(e.path),s=document.createElement(`div`);s.className=`asset-folder${r?` collapsed`:``}${t.selectedGroup===e.path?` selected`:``}`,s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.stopPropagation(),t.dataTransfer?.setData(`text/incanto-group`,e.path)});let c=document.createElement(`span`);c.className=`chev`,c.appendChild(sj());let l=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);l.setAttribute(`viewBox`,`0 0 24 24`),l.setAttribute(`width`,`12`),l.setAttribute(`height`,`12`),l.setAttribute(`fill`,`none`),l.setAttribute(`stroke`,`currentColor`),l.setAttribute(`stroke-width`,`1.8`),l.setAttribute(`aria-hidden`,`true`);let u=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);if(u.setAttribute(`d`,`M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`),l.appendChild(u),dj===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,fj(e.name,n=>{dj=null,t.renameGroup(e.path,i+n)},()=>{dj=null,t.selectGroup(t.selectedGroup)})),s.draggable=!1,n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}return}let d=document.createElement(`span`);d.textContent=e.name,d.addEventListener(`dblclick`,n=>{n.stopPropagation(),dj=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${mj(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{lj.has(e.path)?lj.delete(e.path):lj.add(e.path),t.selectGroup(e.path)}),i(s,e.path),n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}},s=pj(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function gj(e,t,n){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(Mj(t.newGroupParent?`NEW GROUP IN ${t.newGroupParent}/`:`NEW GROUP`));let n=document.createElement(`input`);n.placeholder=t.newGroupParent?`heroes`:`characters (or a/b to nest)`,n.className=`mono`,e.appendChild(Sj(`name`,n));let r=document.createElement(`button`);r.type=`button`,r.className=`primary`,r.textContent=`add`;let i=()=>{let e=n.value.trim().replace(/^\/+|\/+$/g,``);e&&(t.cancelAddForms(),t.addGroup(t.newGroupParent?`${t.newGroupParent}/${e}`:e))};r.addEventListener(`click`,i),n.addEventListener(`keydown`,e=>{e.key===`Enter`&&i()});let a=document.createElement(`div`);return a.className=`pop-actions`,a.appendChild(r),e.appendChild(a),setTimeout(()=>n.focus(),0),!0}if(t.addingAsset)return bj(e,t);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(Mj(`GROUP (${i} asset${i===1?``:`s`})`));let a=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)+1):``,o=r.includes(`/`)?r.slice(r.lastIndexOf(`/`)+1):r;e.appendChild(Cj(`name`,o,e=>{let n=e.trim().replace(/\/+/g,``);n&&n!==o&&t.renameGroup(r,a+n)}));let s=document.createElement(`button`);return s.type=`button`,s.className=`ghost danger`,s.textContent=`delete group`,s.addEventListener(`click`,()=>{if(i===0){t.deleteGroup(r);return}n(`'${r}/' contains ${i} asset${i===1?``:`s`} — deleting the group deletes them too.`,`delete group & assets`,()=>t.deleteGroup(r))}),e.appendChild(s),!0}let r=t.selectedAsset;if(r===null)return!1;let i=t.working.assets??{};if(!(r in i))return!1;e.appendChild(Mj(`ASSET — ${String(i[r].type??`?`)}`)),e.appendChild(kj(r)),e.appendChild(Aj(t,r)),e.appendChild(_j(t,i,r));let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost danger`,a.textContent=`delete asset`,a.addEventListener(`click`,()=>{t.selectAsset(null),t.mutate(()=>{delete i[r],Object.keys(i).length===0&&delete t.working.assets})}),e.appendChild(a),!0}function _j(e,t,n){let r=t[n],i=document.createElement(`div`);i.className=`asset-editor`;let a=n.includes(`/`)?n.slice(n.lastIndexOf(`/`)+1):n,o=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)+1):``,s=Cj(`name`,a,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==a&&e.renameAssetKey(n,o+r)});jj(s.querySelector(`input`)),i.appendChild(s),i.appendChild(Cj(`url`,String(r.url??``),t=>{e.mutate(()=>{r.url=t.trim()})}));let c=document.createElement(`div`);c.className=`muted-note`,c.textContent=`meta (key · value)`,i.appendChild(c);for(let[t,n]of Object.entries(r))t===`type`||t===`url`||i.appendChild(vj(e,r,t,n));return i.appendChild(yj(e,r)),i}function vj(e,t,n,r){let i=document.createElement(`div`);i.className=`meta-row`;let a=document.createElement(`input`);a.value=n,a.className=`mono`;let o=document.createElement(`input`);o.value=typeof r==`string`?r:JSON.stringify(r),o.className=`mono`;let s=()=>{let r=a.value.trim();e.mutate(()=>{delete t[n],r&&(t[r]=wj(o.value))})};a.addEventListener(`change`,s),o.addEventListener(`change`,s);let c=document.createElement(`button`);return c.type=`button`,c.className=`linklike danger-link`,c.textContent=`✕`,c.addEventListener(`click`,()=>{e.mutate(()=>{delete t[n]})}),i.append(a,o,c),i}function yj(e,t){let n=document.createElement(`div`);n.className=`meta-row`;let r=document.createElement(`input`);r.placeholder=`filter…`,r.className=`mono`;let i=document.createElement(`input`);i.placeholder=`nearest`,i.className=`mono`;let a=()=>{let n=r.value.trim();!n||i.value.trim()===``||e.mutate(()=>{t[n]=wj(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function bj(e,t){return e.appendChild(Mj(`NEW ASSET`)),e.appendChild(xj(t)),!0}function xj(e){let t=document.createElement(`div`);t.className=`asset-editor`;let n=document.createElement(`select`);for(let e of cj){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,n.appendChild(t)}t.appendChild(Sj(`type`,n));let r=document.createElement(`input`);r.placeholder=`(optional) characters`,r.className=`mono`,r.value=e.newAssetGroup;let i=`asset-groups-list`;r.setAttribute(`list`,i);let a=document.createElement(`datalist`);a.id=i;let o=new Set;for(let t of Object.keys(e.working.assets??{})){let e=t.lastIndexOf(`/`);e!==-1&&o.add(t.slice(0,e))}for(let t of e.pendingGroups)o.add(t);for(let e of o){let t=document.createElement(`option`);t.value=e,a.appendChild(t)}t.appendChild(Sj(`group`,r)),t.appendChild(a);let s=document.createElement(`input`);s.placeholder=`coin`,s.className=`mono`,jj(s),t.appendChild(Sj(`key`,s));let c=document.createElement(`input`);c.placeholder=`/textures/coin.png · https://… · data:…`,c.className=`mono`,t.appendChild(Sj(`url`,c));let l=document.createElement(`textarea`);l.rows=2,l.placeholder=`or paste a JSON object: { "type": "model", "url": "/m.glb" }`,t.appendChild(l);let u=document.createElement(`button`);u.type=`button`,u.className=`primary`,u.textContent=`add`,u.addEventListener(`click`,()=>{let t=s.value.trim().replace(/^\$/,``);if(!t)return;let i=r.value.trim().replace(/\/+$/,``),a=i?`${i}/${t}`:t,o=null,u=l.value.trim();if(u)try{o=JSON.parse(u)}catch{l.classList.add(`invalid`);return}else c.value.trim()&&(o={type:n.value,url:c.value.trim()});o&&(e.cancelAddForms(),e.selectedAsset=a,e.mutate(()=>{e.working.assets||(e.working.assets={});let t=e.working.assets;t[a]=o}))});let d=document.createElement(`div`);return d.className=`pop-actions`,d.appendChild(u),t.appendChild(d),t}function Sj(e,t){let n=document.createElement(`label`);n.className=`field`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n}function Cj(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),Sj(e,r)}function wj(e){let t=e.trim();if(t===`true`)return!0;if(t===`false`)return!1;if(t!==``&&Number.isFinite(Number(t)))return Number(t);if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.parse(t)}catch{return e}return e}var Tj={texture:`M3 5h18v14H3z M3 15l5-5 4 4 3-3 6 6 M8.5 9.5h.01`,spritesheet:`M3 4h18v16H3z M9 4v16 M15 4v16 M3 12h18`,model:`M12 2l9 5v10l-9 5-9-5V7z M12 12l9-5 M12 12L3 7 M12 12v10`,animation:`M12 2a10 10 0 1 0 10 10 M22 12l-3-3m3 3l3-3 M12 7v5l3 3`},Ej={texture:{en:`image (texture) — Sprite2D.texture references it as "$key".`,ko:`이미지(텍스처) — Sprite2D.texture에서 "$키"로 참조합니다.`},spritesheet:{en:`spritesheet — AnimatedSprite2D slices it into named frame animations.`,ko:`스프라이트시트 — AnimatedSprite2D가 이름 붙은 프레임 애니메이션으로 자릅니다.`},model:{en:`3D model (GLB/glTF/VRM) — ModelInstance3D.model references it as "$key".`,ko:`3D 모델(GLB/glTF/VRM) — ModelInstance3D.model에서 "$키"로 참조합니다.`},animation:{en:`animation clips (GLB, in memory — drawn nowhere) — any model can play them; mixamo retargets onto VRM.`,ko:`애니메이션 클립(GLB, 메모리 전용 — 그려지지 않음) — 어떤 모델이든 재생 가능, mixamo는 VRM에 자동 리타게팅.`}};function Dj(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`width`,`13`),t.setAttribute(`height`,`13`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.8`),t.setAttribute(`aria-hidden`,`true`);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return n.setAttribute(`d`,Tj[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function Oj(e,t){document.querySelector(`.balloon`)?.remove();let n=Ej[t];if(!n)return;let r=document.createElement(`div`);r.className=`balloon floating`;let i=document.createElement(`div`);i.className=`balloon-title`,i.textContent=t;let a=document.createElement(`span`);a.textContent=rj(n),r.append(i,a),document.body.appendChild(r);let o=e.getBoundingClientRect();r.style.left=`${o.right+8}px`,r.style.top=`${Math.max(8,o.top-8)}px`;let s=()=>{r.remove(),document.removeEventListener(`pointerdown`,s,!0)};setTimeout(()=>document.addEventListener(`pointerdown`,s,!0),0)}function kj(e){let t=document.createElement(`div`);t.className=`field uid-line`;let n=document.createElement(`span`);n.textContent=`key`;let r=document.createElement(`div`);r.className=`uid-value`;let i=document.createElement(`code`);i.textContent=`$${e}`;let a=document.createElement(`button`);return a.type=`button`,a.className=`uid-copy`,a.title=`Copy key`,a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,a.addEventListener(`click`,()=>{navigator.clipboard?.writeText(`$${e}`),a.classList.add(`copied`),setTimeout(()=>a.classList.remove(`copied`),600)}),r.append(i,a),t.append(n,r),t}function Aj(e,t){let n=t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``,r=document.createElement(`select`),i=new Set([``]);for(let t of Object.keys(e.working.assets??{})){let e=t.split(`/`);for(let t=1;t<e.length;t++)i.add(e.slice(0,t).join(`/`))}for(let t of e.pendingGroups)i.add(t);for(let e of[...i].sort()){let t=document.createElement(`option`);t.value=e,t.textContent=e===``?`(root)`:`${e}/`,e===n&&(t.selected=!0),r.appendChild(t)}r.addEventListener(`change`,()=>{e.moveAsset(t,r.value)});let a=document.createElement(`label`);a.className=`field`;let o=document.createElement(`span`);return o.textContent=`group`,a.append(o,r),a}function jj(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function Mj(e){let t=document.createElement(`div`);t.className=`section-title`,t.textContent=e;let n=document.createElement(`span`);return n.className=`rule`,t.appendChild(n),t}var Nj=window.parent!==window,Pj=new URLSearchParams(window.location.search).get(`parentOrigin`),Fj=!1;function Ij(e){if(Nj){if(!Pj){Fj||(Fj=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,Pj)}}var Lj={ready(e,t,n){Ij({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){Ij({type:`incanto-editor:open`,input:e,output:t})},change(e){Ij({type:`incanto-editor:change`,dirty:e})},save(e,t,n){Ij({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){Ij({type:`incanto-editor:error`,message:e})}},Rj=[[`Core`,e=>!e.endsWith(`2D`)&&!e.endsWith(`3D`)&&e!==`Label`&&e!==`UILayer`&&e!==`NetworkSpawner`],[`2D`,e=>e.endsWith(`2D`)&&!/Body|Area|Controller/.test(e)||e===`Label`||e===`UILayer`],[`2D Physics`,e=>e.endsWith(`2D`)&&/Body|Area|Controller/.test(e)],[`3D`,e=>e.endsWith(`3D`)&&!/Body|Area|Controller/.test(e)],[`3D Physics`,e=>e.endsWith(`3D`)&&/Body|Area|Controller/.test(e)],[`Network`,e=>e===`NetworkSpawner`]],zj=[...Rj,[`Other`,e=>Rj.every(([,t])=>!t(e))]],Bj={title:{en:`How Incanto scenes work`,ko:`Incanto 씬은 어떻게 동작하나`},sections:[{heading:{en:`Everything is a node in a tree`,ko:`모든 것은 트리 위의 노드`},text:{en:`A scene is ONE tree of typed nodes (Godot-style). Each node has a name (unique among its siblings), a type that defines its props and behavior, optional children, and an optional scene-wide-unique uid. The whole structure lives in a *.scene.json file — there is no hidden state: what you see in this editor IS the file.`,ko:`씬은 타입을 가진 노드들의 단일 트리입니다(Godot 방식). 각 노드는 이름(형제 간 유일), props와 동작을 결정하는 타입, 선택적 자식들, 그리고 선택적인 씬 전역 유일 uid를 가집니다. 전체 구조가 *.scene.json 파일 하나에 들어있고 숨겨진 상태는 없습니다 — 이 에디터에서 보는 것이 곧 파일 그 자체입니다.`}},{heading:{en:`Props are delta-only`,ko:`Props는 변경분만 기록`},text:{en:`Every prop has a default defined by the engine. The JSON only stores values that DIFFER from the default — so files stay small and diffs stay meaningful. This editor follows the same rule: set a value back to its default and it disappears from the file.`,ko:`모든 prop에는 엔진이 정의한 기본값이 있습니다. JSON에는 기본값과 다른 값만 기록되어 파일이 작고 diff가 의미를 가집니다. 이 에디터도 같은 규칙을 따릅니다 — 값을 기본값으로 되돌리면 파일에서 사라집니다.`}},{heading:{en:`Addressing: paths, names, uid, groups`,ko:`노드 찾기: 경로·이름·uid·그룹`},text:{en:`Code reaches nodes four ways: a path like "Player/Skin" (relative) or "%Unique" (marked-unique name), getNodesByName("Enemy") which returns a LIST (names repeat across the tree), getNodeByUid("n_x1y2") which returns exactly one node and survives moves/renames, and groups — free tags for queries like "every coin".`,ko:`코드는 네 가지 방법으로 노드에 접근합니다: "Player/Skin" 같은 경로(상대) 또는 "%Unique"(유일 표시 이름), 트리 전체에서 같은 이름을 모두 찾는 getNodesByName("Enemy") — 이름은 중복될 수 있어 리스트가 돌아옵니다 —, 정확히 한 노드를 돌려주고 이동/개명에도 살아남는 getNodeByUid("n_x1y2"), 그리고 "모든 코인"처럼 묶어 조회하는 자유 태그 groups.`}},{heading:{en:`Signals connect, behaviors act`,ko:`시그널로 잇고 비헤이비어로 움직인다`},text:{en:`Nodes emit signals (an Area2D fires triggerEnter, a Timer fires timeout). The scene's "connections" wire a signal to a handler — declaratively, in JSON. Game logic itself is a Behavior: a TypeScript class in YOUR game, attached by name via "script". The editor shows and edits these links but the code lives in the game.`,ko:`노드는 시그널을 발산합니다(Area2D의 triggerEnter, Timer의 timeout). 씬의 "connections"가 시그널을 핸들러에 선언적으로(JSON으로) 연결합니다. 게임 로직 자체는 Behavior — 게임 쪽 TypeScript 클래스이며 "script"에 이름으로 연결됩니다. 에디터는 이 연결을 보여주고 편집하지만 코드는 게임에 있습니다.`}},{heading:{en:`Assets are declared, then referenced`,ko:`에셋은 선언하고 $키로 참조`},text:{en:`The scene header declares assets (textures, spritesheets, 3D models, animation clips) under a key; nodes reference them as "$key". Animations are data too: an {type:"animation"} asset loads GLB clips into memory and any ModelInstance3D can play them — Mixamo clips retarget onto VRM avatars automatically.`,ko:`씬 헤더에서 에셋(텍스처·스프라이트시트·3D 모델·애니메이션 클립)을 키로 선언하고, 노드는 "$key"로 참조합니다. 애니메이션도 데이터입니다 — {type:"animation"} 에셋이 GLB 클립을 메모리에 올리고 어떤 ModelInstance3D든 재생할 수 있으며, Mixamo 클립은 VRM 아바타에 자동 리타게팅됩니다.`}}]},Z=(e,t,...n)=>({type:e,summary:t,body:n}),Vj=[{id:`core`,label:{en:`Core`,ko:`Core`},intro:{en:`Dimension-free building blocks: plain containers and the game clock. They render nothing themselves.`,ko:`차원과 무관한 기본 블록 — 순수 컨테이너와 게임 시계입니다. 스스로는 아무것도 그리지 않습니다.`},nodes:[Z(`Node`,{en:`A plain container with no transform.`,ko:`변환 없이 자식을 묶는 순수 컨테이너.`},{en:`Use it to group related nodes (all coins, all UI) without affecting their positions. Lifecycle, signals, groups, script — everything works; it just has no visual or spatial meaning of its own.`,ko:`위치에 영향을 주지 않으면서 관련 노드(코인 전부, UI 전부)를 묶을 때 씁니다. 라이프사이클·시그널·그룹·스크립트가 모두 동작하며, 시각적·공간적 의미만 없습니다.`}),Z(`Timer`,{en:"A serializable countdown that emits `timeout`.",ko:"`timeout` 시그널을 쏘는 직렬화 가능한 카운트다운."},{en:`Set waitTime (seconds), optionally autostart or oneShot, and connect its timeout signal to any handler. Because it is a node, the whole timing setup lives in the scene file — agents can read and tune it.`,ko:`waitTime(초)을 정하고 autostart·oneShot을 선택한 뒤 timeout 시그널을 핸들러에 연결하세요. 노드이기 때문에 타이밍 설정 전체가 씬 파일에 남아 에이전트가 읽고 조정할 수 있습니다.`}),Z(`HudLayer`,{en:`Screen-space HUD overlay above the canvas — parent for UiText/UiBar/UiBanner.`,ko:`캔버스 위 화면 고정 HUD 오버레이 — UiText/UiBar/UiBanner의 부모.`},{en:`A DOM overlay (position:fixed) that never blocks pointer input. Put UI widgets as children; each picks one of 9 anchors (topLeft…bottomRight). Works identically over 2D and 3D renderers; in headless/tests it is a silent no-op. zIndex lifts it above the canvas.`,ko:`포인터 입력을 가로막지 않는 DOM 오버레이(position:fixed)입니다. UI 위젯을 자식으로 두면 각자 9개 앵커(topLeft…bottomRight) 중 하나에 붙습니다. 2D·3D 렌더러 어디서나 동일하게 동작하고, 헤드리스/테스트에서는 조용히 no-op입니다. zIndex로 캔버스 위에 올립니다.`}),Z(`UiText`,{en:`A HUD text line — score, timers, hints.`,ko:`HUD 텍스트 한 줄 — 점수, 타이머, 힌트.`},{en:`Child of HudLayer. Set text/size/color in JSON; update from behaviors: (getNode('%Score') as UiText).text = String(score). shadow adds a soft outline for readability over any scene.`,ko:`HudLayer의 자식. text/size/color를 JSON으로 정하고, 비헤이비어에서 (getNode('%Score') as UiText).text = String(score) 로 갱신하세요. shadow는 어떤 화면 위에서도 읽히도록 부드러운 그림자를 더합니다.`}),Z(`UiBar`,{en:`A labeled progress bar — health, stamina, reload, boss HP.`,ko:`라벨 달린 진행 바 — 체력, 스태미나, 재장전, 보스 HP.`},{en:`Child of HudLayer. Drive value/max from behaviors; the fill animates and turns lowColor under lowThreshold (default 30%). width/height/color/background style it; label prefixes a small caption.`,ko:`HudLayer의 자식. 비헤이비어에서 value/max를 갱신하면 채움이 애니메이션되고 lowThreshold(기본 30%) 아래로 떨어지면 lowColor로 바뀝니다. width/height/color/background로 스타일, label로 작은 캡션을 붙입니다.`}),Z(`UiBanner`,{en:`Center-screen announcements with fade and a queue — "WAVE 2", "YOU DIED".`,ko:`페이드·큐가 있는 중앙 공지 — "WAVE 2", "YOU DIED".`},{en:`Child of HudLayer. Call show('WAVE 2', { color, seconds }) from behaviors; messages queue and fade in/out. seconds 0 = sticky until the next show(). clear() drops everything. Emits bannerShown(text).`,ko:`HudLayer의 자식. 비헤이비어에서 show('WAVE 2', { color, seconds })를 호출하면 메시지가 큐에 쌓여 페이드 인/아웃됩니다. seconds 0이면 다음 show()까지 고정, clear()로 전부 제거. bannerShown(text) 시그널을 냅니다.`}),Z(`UiButton`,{en:`A clickable HUD button — menus, START screens, dialog choices.`,ko:`클릭 가능한 HUD 버튼 — 메뉴, 시작 화면, 대화 선택지.`},{en:`Child of HudLayer. Set text/size/color/background; disabled greys it out. Emits the 'pressed' signal (behaviors: node.on('pressed', ...)); press() triggers it programmatically (gamepad menus, tests).`,ko:`HudLayer의 자식. text/size/color/background를 설정하고 disabled로 비활성화합니다. 'pressed' 시그널을 내며(비헤이비어에서 node.on('pressed', ...)), press()로 코드에서도 누를 수 있습니다(게임패드 메뉴, 테스트).`}),Z(`UiDialogue`,{en:`A typewriter dialogue box with a queue and choice buttons — the RPG conversation layer.`,ko:`타자기 효과·큐·선택지 버튼을 갖춘 대화창 — RPG 대화 레이어.`},{en:`Child of HudLayer (anchor bottom by default). say(speaker, text, choices?) queues lines; clicking (or advance()) reveals then advances; choice lines wait for choose(i). Signals: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0 = instant. Check .active to pause player input during conversations.`,ko:`HudLayer의 자식(기본 anchor bottom). say(화자, 텍스트, 선택지?)로 줄을 큐에 넣고, 클릭(또는 advance())이 전체 공개→다음 줄로 진행하며, 선택지 줄은 choose(i)를 기다립니다. 시그널: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0이면 즉시 표시. 대화 중 플레이어 입력을 멈추려면 .active를 확인하세요.`}),Z(`AudioPlayer`,{en:`Plays a sound: zero-asset procedural SFX, BGM loops, or one-shot effects.`,ko:`소리 재생 — 무에셋 절차적 효과음, 배경음 루프, 단발 효과음.`},{en:`Set preset (coin/jump/hurt/explosion/…) for an instant zero-asset SFX (pitch/seed vary it), or leave it "custom" and set src (URL or "$assetKey"). volume 0..1; bus routes through engine.audio (sfx|music) for global volume/mute; loop for music; autoplay starts on ready (browsers may hold it until the first user gesture). Call play()/stop() from game code. Dimension-free — 2D and 3D alike.`,ko:`preset(coin/jump/hurt/explosion/…)을 설정하면 즉시 무에셋 효과음이 납니다(pitch·seed로 변형). 아니면 "custom"으로 두고 src(URL 또는 "$에셋키")를 쓰세요. volume은 0..1, bus는 engine.audio(sfx|music)를 통해 전역 볼륨/음소거에 연결, 음악은 loop, autoplay는 준비되면 재생합니다(브라우저가 첫 입력까지 보류 가능). 게임 코드에서 play()/stop()을 부르세요. 2D·3D 어디서나 동작합니다.`})]},{id:`2d`,label:{en:`2D`,ko:`2D`},intro:{en:`The 2D world is y-down pixels: 1 unit = 1 px, (0,0) top-left, rotation in clockwise degrees. Rendering needs a current Camera2D.`,ko:`2D 세계는 y-아래 픽셀 좌표입니다: 1유닛=1px, (0,0)은 좌상단, 회전은 시계방향 도(degree). 렌더링에는 current 카메라(Camera2D)가 필요합니다.`},nodes:[Z(`Node2D`,{en:`The 2D transform container (position/rotation/scale).`,ko:`2D 변환 컨테이너(position/rotation/scale).`},{en:`Children inherit its transform — move the parent, everything follows. renderOrder orders drawing; visible hides the subtree.`,ko:`자식은 변환을 상속합니다 — 부모를 움직이면 전부 따라옵니다. renderOrder로 그리기 순서를, visible로 서브트리 표시를 제어합니다.`}),Z(`Sprite2D`,{en:`A textured quad.`,ko:`텍스처 사각형(스프라이트).`},{en:`texture is "$assetKey" from the scene assets. anchor [0.5,0.5] centers; flipX/flipY mirror; tint multiplies color; opacity fades. Size comes from the texture × scale.`,ko:`texture는 씬 에셋의 "$키"입니다. anchor [0.5,0.5]면 중앙 기준, flipX/flipY로 반전, tint로 색 곱, opacity로 투명도. 크기는 텍스처 × scale로 정해집니다.`}),Z(`ColorRect2D`,{en:`A flat colored rectangle — no texture needed.`,ko:`단색 사각형 — 텍스처 불필요.`},{en:`size [w,h] px, color, opacity, anchor. Backgrounds, platforms, walls, UI panels, generated-level tiles (maze2d/dungeon2d emit these) — blocky art without any asset.`,ko:`size [w,h] px, color, opacity, anchor. 배경·플랫폼·벽·UI 패널·생성 레벨 타일(maze2d/dungeon2d가 이걸 만듭니다) — 에셋 없이 만드는 블록 그래픽입니다.`}),Z(`TileMap2D`,{en:`A whole tile level as ONE node — grid render + merged static colliders.`,ko:`타일 레벨 전체를 노드 하나로 — 그리드 렌더 + 병합된 정적 콜라이더.`},{en:`Author cells as rows of characters: "." / space = empty, digits 0-9 = atlas tile index, other chars map through legend ({"G": 12}). texture is a "$atlas" asset read left-to-right top-to-bottom in tileSize squares (columns: 0 derives from the texture width). Tile indices listed in solid become static colliders, greedy-merged into a few rectangles. Cell (0,0) hangs its top-left on the node origin.`,ko:`cells를 문자 행으로 작성합니다: "."/공백 = 빈 칸, 숫자 0-9 = 아틀라스 타일 번호, 그 외 문자는 legend({"G": 12})로 매핑. texture는 tileSize 정사각형을 좌→우, 상→하로 읽는 "$아틀라스" 에셋입니다(columns: 0이면 텍스처 폭에서 유도). solid에 나열된 타일 번호는 정적 콜라이더가 되며 소수의 직사각형으로 탐욕 병합됩니다. (0,0) 칸의 좌상단이 노드 원점에 걸립니다.`}),Z(`AnimatedSprite2D`,{en:`Spritesheet animation player.`,ko:`스프라이트시트 애니메이션 플레이어.`},{en:`Point sheet at a "$sheet" asset, define animations as named frame ranges with fps/loop in JSON, set autoplay. Emits animationFinished(name) for one-shot chains.`,ko:`sheet에 "$시트" 에셋을 연결하고, JSON에 fps/loop를 가진 이름별 프레임 구간으로 animations를 정의한 뒤 autoplay를 지정하세요. 단발 애니메이션 연결을 위해 animationFinished(name)를 발산합니다.`}),Z(`Camera2D`,{en:`The 2D view: follow, zoom, limits.`,ko:`2D 시점 — 추적·줌·경계.`},{en:`position is the view CENTER. follow tracks a node path with smoothing (0..1, higher = snappier). limits [minX,minY,maxX,maxY] clamps the view inside a world region. current: true makes it THE camera.`,ko:`position은 화면의 중심입니다. follow가 노드 경로를 smoothing(0..1, 높을수록 빠릿)으로 추적합니다. limits [minX,minY,maxX,maxY]가 시점을 월드 영역 안에 가둡니다. current: true인 카메라가 실제 시점이 됩니다.`}),Z(`Particles2D`,{en:`A 2D particle emitter (fire, sparks, smoke…).`,ko:`2D 파티클 이미터(불·스파크·연기…).`},{en:`Start from a preset (fire/smoke/sparks/…) then override any prop: rate, lifetime/speed ranges, direction + spread, gravity, size/color/alpha start→end, additive blend. burst > 0 with emitting: false makes a one-shot that emits finished. Animates LIVE in this editor.`,ko:`preset(fire/smoke/sparks/…)에서 시작해 어떤 prop이든 덮어쓰세요: rate, lifetime/speed 구간, direction+spread, gravity, size/color/alpha 시작→끝, additive blend. emitting: false에 burst > 0이면 단발 발사 후 finished를 발산합니다. 이 에디터에서 라이브로 움직입니다.`}),Z(`Label`,{en:`Text rendered to a quad.`,ko:`텍스트를 그리는 노드.`},{en:`text/fontSize/color/font/align — rendered via CanvasTexture, so any system font string works. Inside a UILayer it pins to the screen (HUD).`,ko:`text/fontSize/color/font/align — CanvasTexture로 그려져 시스템 폰트 문자열을 그대로 쓸 수 있습니다. UILayer 아래에 두면 화면에 고정됩니다(HUD).`}),Z(`UILayer`,{en:`A screen-space subtree (HUD).`,ko:`화면 고정 서브트리(HUD).`},{en:`Everything under it ignores the camera: positions are screen pixels from the top-left. Score counters, prompts, menus go here.`,ko:`이 아래의 모든 것은 카메라를 무시합니다 — 좌상단 기준 화면 픽셀 좌표입니다. 점수, 안내 문구, 메뉴를 여기에 둡니다.`})]},{id:`2d-physics`,label:{en:`2D Physics`,ko:`2D 물리`},intro:{en:`Rapier-backed. Colliders are PROPS ({shape, …}) — the green dashed wireframes in this editor. Physics runs when the game calls enablePhysics2D (and in play mode). Gravity lives on the scene row.`,ko:`Rapier 기반입니다. 콜라이더는 prop({shape, …})이며 에디터의 초록 점선이 그것입니다. 물리는 게임이 enablePhysics2D를 부를 때(그리고 플레이 모드에서) 돌고, 중력은 씬 행에 있습니다.`},nodes:[Z(`StaticBody2D`,{en:`Immovable collision: ground, walls, platforms.`,ko:`움직이지 않는 충돌체 — 바닥·벽·플랫폼.`},{en:`Other bodies collide with it; it never moves. Cheapest body type — use it for all level geometry.`,ko:`다른 바디가 부딪히지만 자신은 절대 움직이지 않습니다. 가장 저렴한 바디 — 레벨 지형 전부에 쓰세요.`}),Z(`RigidBody2D`,{en:`Fully simulated: falls, bounces, pushes.`,ko:`완전 시뮬레이션 — 떨어지고 튕기고 밀립니다.`},{en:`Gravity and collisions drive it. Set linearVelocity to launch. For player characters prefer CharacterBody2D (direct control).`,ko:`중력과 충돌이 움직임을 결정합니다. linearVelocity로 발사하세요. 플레이어 캐릭터에는 직접 제어가 가능한 CharacterBody2D를 권합니다.`}),Z(`CharacterBody2D`,{en:`Kinematic character: you set velocity, it slides.`,ko:`키네마틱 캐릭터 — 속도를 주면 미끄러지듯 이동.`},{en:`moveAndSlide() resolves collisions without physics pushing back; isOnFloor() gates jumps. Sensors (Area2D) do not block it but still fire triggers.`,ko:`moveAndSlide()가 밀려나지 않으면서 충돌을 처리하고 isOnFloor()로 점프를 판정합니다. 센서(Area2D)는 길을 막지 않으면서 트리거를 발사합니다.`}),Z(`Area2D`,{en:`A sensor: overlap triggers, no collision response.`,ko:`센서 — 겹침 감지만, 충돌 반응 없음.`},{en:`Fires triggerEnter(other)/triggerExit(other). Coins, checkpoints, damage zones. Filter with other.isInGroup("player").`,ko:`triggerEnter(other)/triggerExit(other)를 발산합니다. 코인·체크포인트·데미지 존에 쓰고, other.isInGroup("player")로 거릅니다.`}),Z(`CharacterController2D`,{en:`Zero-code platformer/top-down movement.`,ko:`코드 없는 플랫포머/탑다운 이동.`},{en:`Put it UNDER a CharacterBody2D. mode "platformer" (gravity + jump via jumpAction) or "topDown" (free 2-axis). Reads the scene input map actions (moveAction/jumpAction). maxSpeed/jumpHeight are intent-level numbers.`,ko:`CharacterBody2D의 자식으로 두세요. mode는 "platformer"(중력+jumpAction 점프) 또는 "topDown"(자유 2축)이며 씬 입력 맵의 액션(moveAction/jumpAction)을 읽습니다. maxSpeed/jumpHeight는 의도 그대로의 숫자입니다.`}),Z(`Joint2D`,{en:`A physics joint linking its parent body to a target body — weld, hinge, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 힌지, 로프, 스프링.`},{en:`Child of body A (a physics body); "target" is a node path to body B. type: fixed (rigid weld) / revolute (pin at the anchors) / rope (caps anchor distance at length px; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL px offsets.`,ko:`바디 A(물리 바디)의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / revolute(앵커 핀 힌지) / rope(앵커 간 거리를 length px로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 px 오프셋.`})]},{id:`3d`,label:{en:`3D`,ko:`3D`},intro:{en:`Meters, y-up, rotations in degrees. Standard materials need LIGHT — add a DirectionalLight3D or scene ambient, or you get silhouettes.`,ko:`미터 단위, y-위, 회전은 도(degree)입니다. 표준 머티리얼은 빛이 필요합니다 — DirectionalLight3D나 씬 ambient가 없으면 실루엣만 보입니다.`},nodes:[Z(`Node3D`,{en:`The 3D transform container.`,ko:`3D 변환 컨테이너.`},{en:`position [x,y,z] in meters, rotation [x,y,z] in degrees, scale per axis. Children inherit.`,ko:`position [x,y,z] 미터, rotation [x,y,z] 도, scale은 축별. 자식이 상속합니다.`}),Z(`MeshInstance3D`,{en:`A primitive mesh + material.`,ko:`프리미티브 메시 + 머티리얼.`},{en:`mesh: box/sphere/plane/cylinder…, size per primitive, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat} (this editor gives it swatches, sliders, texture-URL fields, and a repeat [u,v] tiling vector). map/normalMap are texture URLs; repeat only takes effect with a map. castShadow/receiveShadow per node.`,ko:`mesh: box/sphere/plane/cylinder…, 프리미티브별 size, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat}(에디터가 스와치·슬라이더·텍스처 URL 입력·repeat [u,v] 타일링 벡터 제공). map/normalMap은 텍스처 URL, repeat는 map이 있을 때만 적용. 그림자는 castShadow/receiveShadow.`}),Z(`LoftMesh3D`,{en:`A smooth swept hull (loft).`,ko:`부드러운 스윕 선체(로프트).`},{en:`sections: ≥2 cross-section stations {z, width, height, y, corner 0..1} interpolated into ONE smooth curved surface — vehicle bodies, glass canopies, boat hulls. slices/smooth control tessellation. Same material as MeshInstance3D minus textures (no UVs); pair clearcoat paint or high-envMapIntensity glass with the smooth normals for the automotive look.`,ko:`sections: 단면 스테이션 {z, width, height, y, corner 0..1} 2개 이상을 보간해 하나의 매끈한 곡면을 만듭니다 — 차체, 유리 캐노피, 선체. slices/smooth로 테셀레이션 조절. material은 MeshInstance3D와 동일하되 텍스처 제외(UV 없음). clearcoat 도장이나 높은 envMapIntensity 유리를 곡면 법선과 조합하면 자동차 룩이 납니다.`}),Z(`ModelInstance3D`,{en:`A GLB/glTF/VRM model file.`,ko:`GLB/glTF/VRM 모델 파일.`},{en:'model: "$assetKey" or URL. targetHeight scales the model to stand N units tall (run `npx incanto-model file.glb` to read its real size first). animation plays an embedded clip name OR an "$animation" asset — Mixamo clips retarget onto VRM humanoids automatically. One node per VRM asset (the avatar runtime mounts live).',ko:'model은 "$에셋키" 또는 URL입니다. targetHeight가 모델을 N유닛 높이로 맞춥니다(먼저 `npx incanto-model 파일.glb`로 실제 크기를 확인하세요). animation은 내장 클립 이름 또는 "$애니메이션" 에셋을 재생하며, Mixamo 클립은 VRM 휴머노이드에 자동 리타게팅됩니다. VRM 에셋은 노드 하나만 쓸 수 있습니다(아바타 런타임이 라이브로 마운트됨).'}),Z(`Sprite3D`,{en:`A 2D image as a camera-facing billboard (the 2.5D look).`,ko:`카메라를 향하는 2D 빌보드 스프라이트(2.5D 룩).`},{en:`A textured quad that turns to face the camera inside the 3D world (Octopath / Don't Starve / MapleStory-in-3D). texture is an image URL; size is [w,h] in METERS. billboard: "y" stays upright with a screen-aligned yaw — off-center sprites never roll (characters/props), "full" faces it completely (items/FX), "none" is fixed to the node rotation. anchor [0.5,0] plants the feet on the ground. pixelArt nearest-filters for crisp pixels; alphaTest is a hard cutout that depth-sorts against 3D geometry (a tree occludes it); flipX mirrors left/right; tint/opacity recolor.`,ko:`3D 월드 안에서 카메라를 향해 도는 텍스처 쿼드(Octopath/Don't Starve, 3D 속 메이플스토리 룩). texture는 이미지 URL, size는 [너비,높이] 미터. billboard: "y"는 세로로 선 채 카메라 방향과 정렬된 yaw — 화면 가장자리에서도 기울지 않음(캐릭터/사물), "full"은 완전히 향함(아이템/FX), "none"은 노드 회전에 고정. anchor [0.5,0]은 발을 바닥에 둡니다. pixelArt는 nearest 필터로 픽셀을 또렷하게, alphaTest는 3D 지형과 깊이정렬되는 하드 컷아웃(나무가 가림), flipX는 좌우 반전, tint/opacity로 색·투명도.`}),Z(`AnimatedSprite3D`,{en:`A billboard sprite that plays spritesheet animations.`,ko:`스프라이트시트 애니를 재생하는 빌보드 스프라이트.`},{en:`Everything Sprite3D does, plus frame animation. sheet is a spritesheet image URL whose cells are frameWidth×frameHeight; animations maps a name to {frames, fps, loop} where frames is an inclusive [start,end] range or an explicit list; autoplay starts one on load. Game code calls play("walk") / stop(); a non-looping clip clamps on its last frame and emits animationFinished(name) — chain attack→idle from it.`,ko:`Sprite3D의 모든 기능 + 프레임 애니. sheet는 frameWidth×frameHeight 칸을 가진 스프라이트시트 URL, animations는 이름→{frames, fps, loop}(frames는 포함 [시작,끝] 범위 또는 명시 목록), autoplay는 로드 시 하나를 시작. 게임 코드에서 play("walk")/stop() 호출, 비반복 클립은 마지막 프레임에 머물며 animationFinished(name)를 emit(attack→idle 연결).`}),Z(`Billboard3D`,{en:`A group that turns toward the camera — children follow.`,ko:`카메라를 향해 도는 그룹 — 자식들이 함께 회전.`},{en:`A transform container that orients itself toward the camera every frame; children inherit the rotation, so hang world-space UI under it — HP bars, markers, floating icons (text is a canvas-rendered texture on a child Sprite3D). mode: "screen" (default) copies the camera orientation so a child rectangle stays an upright rectangle anywhere on screen (a yaw-only look-at visibly tilts off-center shapes under a pitched camera); "y" stays upright with a screen-aligned yaw (no off-center roll); "none" turns billboarding off. While billboarding, the node's own rotation prop (and the rotate gizmo) is overwritten every frame — switch to "none" to pose children, then switch back. Unlike Sprite3D (a textured quad that spins only its own image), Billboard3D rotates the whole group.`,ko:`매 프레임 카메라를 향해 자신을 회전시키는 변환 컨테이너로, 자식이 회전을 상속합니다 — HP바·마커·아이콘 같은 월드 UI를 자식으로 붙이세요(텍스트는 캔버스로 그린 텍스처를 자식 Sprite3D에). mode: "screen"(기본)은 카메라 자세를 그대로 복사해 자식 직사각형이 화면 어디서든 똑바른 직사각형으로 보입니다(yaw만 도는 look-at은 기울어진 카메라에서 중앙 밖 도형이 눈에 띄게 비스듬해짐); "y"는 세로로 선 채 카메라로 yaw만; "none"은 빌보드 끔. 빌보드 중에는 노드 자신의 rotation(회전 기즈모 포함)이 매 프레임 덮어써집니다 — 자식을 배치할 땐 "none"으로 바꿨다가 되돌리세요. 자기 그림만 도는 Sprite3D(텍스처 쿼드)와 달리 그룹 전체가 회전합니다.`}),Z(`Camera3D`,{en:`The 3D view.`,ko:`3D 시점.`},{en:`Perspective camera; fov in degrees; current: true selects it. Use the editor's "game cam" (0) to preview exactly what it renders.`,ko:`원근 카메라이며 fov는 도 단위, current: true가 실제 시점이 됩니다. 에디터의 "game cam"(0)으로 정확한 렌더 결과를 미리 보세요.`}),Z(`DirectionalLight3D`,{en:`Sun-like light from a direction.`,ko:`태양광 — 방향에서 평행하게.`},{en:`Position sets the direction toward the origin. intensity/color; pair with scene ambient for soft fill.`,ko:`위치가 원점을 향한 방향을 정합니다. intensity/color를 조절하고 부드러운 채움광은 씬 ambient와 함께 쓰세요.`}),Z(`OmniLight3D`,{en:`A point light radiating everywhere.`,ko:`점광 — 사방으로 퍼지는 빛.`},{en:`Lamps, torches, glows. range limits reach; intensity/color shape the falloff.`,ko:`램프·횃불·발광체. range로 도달 거리를, intensity/color로 감쇠를 만듭니다.`}),Z(`Particles3D`,{en:`A 3D particle emitter (fire, magic, weather…).`,ko:`3D 파티클 이미터(불·마법·날씨…).`},{en:`The same preset + override model as Particles2D, in meters with [x,y,z] gravity. Camera-facing billboard quads, instanced — hundreds are cheap. Animates LIVE in this editor.`,ko:`Particles2D와 같은 preset+덮어쓰기 모델을 미터 단위와 [x,y,z] 중력으로. 카메라를 향하는 빌보드 쿼드를 인스턴싱해 수백 개도 가볍습니다. 이 에디터에서 라이브로 움직입니다.`}),Z(`Terrain3D`,{en:`Procedural heightfield terrain with biome texture splatting.`,ko:`바이옴 텍스처 스플래팅이 적용된 절차적 하이트필드 지형.`},{en:`Seeded simplex hills displaced once on the CPU; theme (island/alpine/plains/desert/custom) picks the 4 blended biome textures by height and slope. heightAt(x,z) answers the surface height anywhere. For physics, parent it under a StaticBody3D with collider {shape:'heightfield'}.`,ko:`시드 기반 심플렉스 언덕을 CPU에서 한 번 변위합니다. theme(island/alpine/plains/desert/custom)이 높이·경사로 블렌딩되는 바이옴 텍스처 4장을 고릅니다. heightAt(x,z)로 어디서든 지표 높이를 얻고, 물리는 StaticBody3D 아래에 두고 collider {shape:'heightfield'}를 쓰세요.`}),Z(`Water3D`,{en:`A shader-water surface with splash signals.`,ko:`스플래시 신호를 내는 셰이더 물 표면.`},{en:`size [w,d] meters on XZ. quality 'fancy' (default) = FBM wave shader with a trough/surface/peak ramp (colors), CubeCamera reflections (reflection/reflectionInterval) and opt-in shoreline foam; 'simple' = the cheap sine material (color). Bodies crossing the surface emit entered/exited(body) and raise ripples (interaction). Volumetric gameplay still wants an Area3D. Waves animate LIVE in this editor.`,ko:`XZ 평면에 size [w,d] 미터. quality 'fancy'(기본)는 FBM 파도 셰이더 — trough/surface/peak 램프(colors), CubeCamera 반사(reflection/reflectionInterval), 옵트인 해안 거품(foam). 'simple'은 저사양용 사인파 머티리얼(color). 바디가 수면을 지나면 entered/exited(body) 신호와 물결이 일어납니다(interaction). 부피 기반 게임플레이엔 여전히 Area3D를 쓰세요. 이 에디터에서 파도가 라이브로 움직입니다.`}),Z(`River3D`,{en:`Running water derived from a path and the ground under it.`,ko:`경로와 그 아래 지형에서 유도되는 흐르는 물.`},{en:`Author a centerline path [[x,z],…] plus width/widths (a profile source→mouth) and depth; the node samples the Terrain3D underneath and derives the rest — a surface that follows the bed's descending envelope (water never climbs), a current that speeds up where the channel pinches or tips (flowSpeed is the mean), whitewater from grade, bank shear and thinning column, and banks cut by the ground itself (each vertex carries its own water column). Cut the bed first with a Terrain3D channels entry on the SAME path, or the water lies on the ground as a film. flowForce drags bodies downstream (drag, never thrust) and sampleAt(x,z) answers where a world point sits in the channel. No extra render passes — a map can carry a dozen.`,ko:`중심선 path [[x,z],…]와 width/widths(상류→하류 프로파일), depth만 주면 나머지는 아래 Terrain3D를 샘플링해 유도합니다 — 강바닥의 하강 포락선을 따르는 수면(물은 절대 거슬러 오르지 않음), 폭이 좁아지거나 경사가 급해지면 빨라지는 유속(flowSpeed는 평균), 경사·둑 전단·얕아지는 수심에서 생기는 흰 물살, 그리고 지형 자체가 깎아내는 강둑(정점마다 자기 수심을 지님). 같은 path로 Terrain3D의 channels를 먼저 파세요 — 아니면 물이 지면 위에 얇은 막처럼 깔립니다. flowForce가 바디를 하류로 끌고(밀지 않고 끌어당김), sampleAt(x,z)로 월드 좌표가 수로 어디에 있는지 알 수 있습니다. 추가 렌더 패스가 없어 한 맵에 여러 개를 둘 수 있습니다.`}),Z(`Foliage3D`,{en:`An instanced grass/flower carpet that sways.`,ko:`바람에 흔들리는 인스턴스 풀밭/꽃밭.`},{en:`kind grass/flowers/reeds scattered over area [w,d] at density (capped by maxInstances — instanced, tens of thousands of blades cheap). Grass defaults to style 'mesh': every instance is a REAL tapered blade curved by a bezier vertex shader — Voronoi-clump hue/lean, groundColor soil roots (match the terrain), sunDirection tip sheen, 2-octave rolling wind, fadeStart/fadeEnd camera LOD, and (interaction) blade-bending around moving bodies. style 'blades' keeps the 8-SDF-blades-per-quad ported shader, 'simple' the legacy quads. colorA/colorB tint bottom→top, sway sets the wind, seed makes the scatter reproducible.`,ko:`kind grass/flowers/reeds를 area [w,d]에 density로 흩뿌립니다(maxInstances 상한 — 인스턴싱이라 수만 가닥도 가벼움). grass는 기본 style 'mesh': 인스턴스 하나하나가 베지어 버텍스 셰이더로 휘어지는 진짜 잎 메시 — 보로노이 클럼프 색/기울기, groundColor 흙빛 뿌리(지형 색에 맞추세요), sunDirection 잎끝 광택, 2옥타브 굽이치는 바람, fadeStart/fadeEnd 카메라 LOD, (interaction) 움직이는 바디 주변 풀 눕힘까지. style 'blades'는 쿼드당 8가닥 SDF 셰이더, 'simple'은 기존 쿼드 룩. colorA/colorB가 아래→위 색, sway가 바람 세기, seed가 배치를 재현 가능하게 합니다.`}),Z(`Flowers3D`,{en:`Instanced flower PLANTS — stems, leaves, multi-petal heads.`,ko:`인스턴스 꽃밭 — 줄기·잎·여러 장 꽃잎의 진짜 꽃 식물.`},{en:`Real procedural flower plants (curved stem, 2-3 leaves, a 5-8 petal head around a contrasting center disc, 1-3 blooms per plant) scattered over area [w,d]. density is the vibe dial: 'lush' / 'sparse' (default) / 'none', or a number in plants/m². varieties picks a subset of daisy/cosmos/bellflower ([] = all three); palette sets the head colors ([] = white/yellow/violet). clustering 0-1 gathers plants into Voronoi patches that bloom one species + color together; sway bobs the heads in a gentle wind; seed makes the field reproducible. ≤3 varieties → ≤6 draw calls.`,ko:`진짜 프로시저럴 꽃 식물(휘어진 줄기, 잎 2-3장, 대비되는 중심 원반을 두른 꽃잎 5-8장 머리, 포기당 꽃 1-3송이)을 area [w,d]에 흩뿌립니다. density가 바이브 다이얼: 'lush'(풍성하게) / 'sparse'(듬성듬성, 기본) / 'none'(없게) 또는 m²당 개수. varieties는 daisy/cosmos/bellflower 부분집합([] = 셋 다), palette는 꽃 색([] = 흰/노랑/보라). clustering 0-1이 보로노이 패치로 모아 한 패치가 같은 종·같은 색으로 피고, sway가 바람에 머리를 끄덕이며, seed로 배치가 재현됩니다. 품종 ≤3 → 드로우 콜 ≤6.`}),Z(`Tree3D`,{en:`Procedural ez-tree groves — branchy trunks, textured leaves.`,ko:`프로시저럴 ez-tree 나무 — 가지 달린 줄기와 텍스처 잎까지.`},{en:`type conifer/broadleaf/dead picks the recipe family; tier is the cost dial: simple = primitive low-poly, medium = light forest presets (≤3k tris/tree), high = full ez-tree presets (8–20k, hero trees). count > 1 scatters a forest patch over area [w,d] — up to 3 seed variants, each branches + leaves InstancedMesh (≤6 draw calls); count × tris/tree is budget-checked at load. seed makes every branch and leaf reproducible; height jitters ±20% per instance; leaves sway in a simplex wind.`,ko:`type conifer/broadleaf/dead가 수종을, tier가 비용을 정합니다: simple = 기존 로우폴리, medium = 가벼운 forest 프리셋(나무당 ≤3k tris), high = 풀 ez-tree 프리셋(8–20k, 주인공 나무). count > 1이면 area [w,d]에 숲 패치를 흩뿌립니다 — 시드 변형 최대 3종, 변형마다 가지+잎 InstancedMesh(드로우 콜 ≤6), count × tris는 로드 시 예산 검사. seed로 가지와 잎이 전부 재현되고 height는 인스턴스마다 ±20% 지터링, 잎은 심플렉스 바람에 흔들립니다.`}),Z(`VoxelGrid3D`,{en:`A Minecraft-style block grid in ONE node.`,ko:`마인크래프트식 블록 그리드 — 노드 하나로.`},{en:`voxels is a list of [x,y,z,palette] integer cells (terrain/island generators emit these). Greedy-meshed and instanced — large worlds stay one draw batch. Game code edits blocks via setBlock/getBlock; emits blocksChanged.`,ko:`voxels는 [x,y,z,팔레트] 정수 셀 목록입니다(terrain/island 생성기가 만들어 냅니다). 그리디 메싱+인스턴싱으로 큰 월드도 드로우 배치 하나를 유지합니다. 게임 코드는 setBlock/getBlock으로 수정하고 blocksChanged가 발산됩니다.`})]},{id:`3d-physics`,label:{en:`3D Physics`,ko:`3D 물리`},intro:{en:`Same model as 2D, in meters with y-up gravity ([0,-9.81,0] default). Colliders: box {size}, sphere {radius}, capsule {radius,height}.`,ko:`2D와 같은 모델을 미터·y-위 중력([0,-9.81,0] 기본)으로. 콜라이더는 box {size}, sphere {radius}, capsule {radius,height}.`},nodes:[Z(`StaticBody3D`,{en:`Immovable 3D collision.`,ko:`움직이지 않는 3D 충돌체.`},{en:`Floors, walls, level geometry.`,ko:`바닥·벽·레벨 지형.`}),Z(`RigidBody3D`,{en:`Simulated 3D body.`,ko:`시뮬레이션되는 3D 바디.`},{en:`Crates, balls, debris — gravity and impacts drive it.`,ko:`상자·공·파편 — 중력과 충격이 움직입니다.`}),Z(`CharacterBody3D`,{en:`Kinematic 3D character.`,ko:`키네마틱 3D 캐릭터.`},{en:`moveAndSlide with up = +y; isOnFloor for jumps.`,ko:`+y를 위로 moveAndSlide, 점프 판정은 isOnFloor.`}),Z(`Area3D`,{en:`3D overlap sensor.`,ko:`3D 겹침 센서.`},{en:`triggerEnter/Exit — pickups, zones, goals.`,ko:`triggerEnter/Exit — 아이템·존·골인 지점.`}),Z(`CharacterController3D`,{en:`Zero-code 3D movement + camera rig.`,ko:`코드 없는 3D 이동 + 카메라 리그.`},{en:`Put it UNDER a CharacterBody3D. view: thirdPerson (orbit + zoom), firstPerson (eyeHeight, mouseLook), sideView or flightView. Reads moveAction/jumpAction/sprintAction from the scene input map; skinPath turns the visual child to face travel. Intent-level numbers: maxSpeed, jumpVelocity, camDistance.`,ko:`CharacterBody3D의 자식으로 두세요. view는 thirdPerson(궤도+줌), firstPerson(eyeHeight, mouseLook), sideView, flightView 중 하나입니다. 씬 입력 맵의 moveAction/jumpAction/sprintAction을 읽고 skinPath의 비주얼 자식을 진행 방향으로 돌립니다. maxSpeed·jumpVelocity·camDistance 같은 의도 수준의 숫자만 만집니다.`}),Z(`BoneLookAt3D`,{en:`Look-at IK for one bone — the head turns toward a target on top of the animation.`,ko:`본 하나의 룩앳 IK — 애니메이션 위에서 머리가 대상을 향해 돌아갑니다.`},{en:`"target" = ModelInstance3D path, "bone" = bone name (default Head), "lookAt" = the node to watch (e.g. "%Player"). Blends in/out smoothly and DISENGAGES beyond maxAngleDeg (no owl necks); weight sets how far it commits. forwardAxis names the bone's facing axis (mixamo heads: +z). Purely visual — headless no-op.`,ko:`"target"에 ModelInstance3D 경로, "bone"에 본 이름(기본 Head), "lookAt"에 바라볼 노드(예: "%Player")를 줍니다. 부드럽게 페이드 인/아웃하고 maxAngleDeg 밖에서는 해제됩니다(목이 돌아가지 않음). weight로 몰입도를 조절하고 forwardAxis는 본의 정면 축입니다(mixamo 머리: +z). 순수 시각 기능 — 헤드리스에서는 no-op.`}),Z(`InstancedMesh3D`,{en:`Hundreds of copies of one mesh in ONE draw call — rocks, posts, crates.`,ko:`메시 하나의 수백 개 복사본을 드로우콜 1개로 — 바위, 말뚝, 상자.`},{en:`Same mesh/size/material surface as MeshInstance3D; "transforms" places the copies — each row [x, y, z, yawDeg?, scale?]. Replace the whole array to update (mutations are not watched). The scattering workhorse for open worlds.`,ko:`MeshInstance3D와 같은 mesh/size/material 표면에 "transforms"로 복사본을 배치합니다 — 각 행은 [x, y, z, yawDeg?, scale?]. 갱신은 배열 전체 교체로 하세요(내부 변경은 감지되지 않음). 오픈월드 스캐터링의 주력입니다.`}),Z(`BoneAttachment3D`,{en:`Rides a skeleton bone of an animated model — swords in hands, hats on heads.`,ko:`애니메이션 모델의 스켈레톤 본을 따라다님 — 손에 쥔 검, 머리 위 모자.`},{en:`"target" is a node path to the ModelInstance3D, "bone" the bone name ("RightHand" also matches the Mixamo spellings). Children inherit the live animated transform; this node's own position/rotation become a bone-space offset. Purely visual — headless it stays where its props put it, so keep gameplay checks range-based.`,ko:`"target"에 ModelInstance3D 노드 경로, "bone"에 본 이름을 줍니다("RightHand"는 Mixamo 표기도 자동 매칭). 자식들이 살아있는 애니메이션 트랜스폼을 물려받고, 이 노드의 position/rotation은 본 기준 오프셋이 됩니다. 순수 시각 기능 — 헤드리스에서는 prop 위치에 머무니 게임 판정은 거리 기반으로 유지하세요.`}),Z(`Trail3D`,{en:`A fading world-space ribbon behind the parent — wingtip trails, sword arcs, tyre streaks.`,ko:`부모 뒤로 남는 페이드아웃 월드 리본 — 날개끝 궤적, 검격 궤적, 타이어 자국.`},{en:"Child of the moving node. Records the world position over `seconds` and renders a camera-facing strip that tapers and fades to the tail. width (m), color, opacity, additive for glowing energy trails, minDistance filters jitter. emitting: false stops laying new ribbon while the old tail fades out.",ko:`움직이는 노드의 자식으로 두세요. seconds 동안의 월드 위치를 기록해 꼬리로 갈수록 가늘어지고 투명해지는 카메라 지향 스트립을 그립니다. width(m), color, opacity, 빛나는 에너지 궤적에는 additive, minDistance로 떨림을 걸러냅니다. emitting: false면 새 리본만 멈추고 기존 꼬리는 자연스럽게 사라집니다.`}),Z(`Joint3D`,{en:`A physics joint linking its parent body to a target body — weld, ball joint, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 볼 조인트, 로프, 스프링.`},{en:`Child of body A; "target" is a node path to body B. type: fixed (rigid weld) / spherical (ball joint at the anchors) / rope (caps anchor distance at length m; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL meter offsets.`,ko:`바디 A의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / spherical(앵커 볼 조인트) / rope(앵커 간 거리를 length m로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 미터 오프셋.`})]},{id:`network`,label:{en:`Network`,ko:`네트워크`},intro:{en:`Multiplayer is transport-agnostic: the engine speaks one NetworkTransport interface (built-in offline Loopback + an @agent8/gameserver adapter). The scene declares replication; one owner node per player broadcasts its sync keys.`,ko:`멀티플레이어는 트랜스포트 불가지론입니다 — 엔진은 NetworkTransport 인터페이스 하나만 사용합니다(내장 오프라인 Loopback + @agent8/gameserver 어댑터). 복제는 씬이 선언하며, 플레이어당 하나의 owner 노드가 sync 키를 송출합니다.`},nodes:[Z(`NetworkSpawner`,{en:`Spawns a registered scene per remote player/entity.`,ko:`원격 플레이어/엔티티마다 등록된 씬을 생성.`},{en:`source "users" mirrors every OTHER account in the room (self skipped); "collection:<id>" mirrors a room collection. Replicated sync patches apply to each instance; position interpolates. Emits spawned/despawned.`,ko:`source "users"는 방의 다른 모든 계정을 미러링하고(자신 제외) "collection:<id>"는 방 컬렉션을 미러링합니다. 복제 sync 패치가 인스턴스에 적용되고 position은 보간됩니다. spawned/despawned를 발산합니다.`})]}],Hj=`overview`,Uj=null;function Wj(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),qj()}function Gj(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function Kj(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&Gj()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,Gj))}function qj(){let e=document.querySelector(`#docs-tabs`),t=document.querySelector(`#docs-body`);if(!e||!t)return;e.textContent=``;let n=(t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`docs-tab${Hj===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{Hj=t,Uj=null,qj()}),e.appendChild(r)};n(`overview`,rj({en:`Overview`,ko:`개요`}));for(let e of Vj)n(e.id,rj(e.label));if(t.textContent=``,Hj===`overview`){Jj(t);return}let r=Vj.find(e=>e.id===Hj);r&&Yj(t,r)}function Jj(e){let t=document.createElement(`h2`);t.textContent=rj(Bj.title),e.appendChild(t);for(let t of Bj.sections){let n=document.createElement(`h3`);n.textContent=rj(t.heading);let r=document.createElement(`p`);r.textContent=rj(t.text),e.append(n,r)}}function Yj(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=rj(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${Uj===n.type?` open`:``}`;let r=document.createElement(`button`);r.type=`button`,r.className=`docs-node-head`;let i=document.createElement(`span`);i.className=`tree-icon`,i.appendChild(oj(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=rj(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{Uj=Uj===n.type?null:n.type,qj()}),t.appendChild(r),Uj===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=rj(t),e.appendChild(n)}e.appendChild(Xj(n.type)),t.appendChild(e)}e.appendChild(t)}}function Xj(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[rj({en:`prop`,ko:`prop`}),rj({en:`default`,ko:`기본값`})]){let t=document.createElement(`th`);t.textContent=e,n.appendChild(t)}t.appendChild(n);try{let n=ge(e);for(let[e,r]of Object.entries(n)){let n=document.createElement(`tr`),i=document.createElement(`td`);i.className=`mono`,i.textContent=e;let a=document.createElement(`td`);a.className=`mono`,a.textContent=JSON.stringify(r.default),n.append(i,a),t.appendChild(n)}}catch{}return t}function Q(e){return Math.round(e*100)/100}function Zj(e,t,n,r,i){return{name:e,type:`StaticBody3D`,props:{collider:{shape:`box`,size:t},position:n,...i?{rotation:i}:{}},children:[{name:`Skin`,type:`MeshInstance3D`,props:{mesh:`box`,size:t,...r}}]}}function Qj(e,t,n,r,i,a){let o=Q(r.range(i[0],i[1])),s=Q(r.range(.5,.7));return{name:`Rock${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[t,Q(o*s*.6),n],rotation:[0,r.int(0,359),0],scale:[o,Q(o*s),Q(o*r.range(.8,1.1))],material:{color:a??$j(r),roughness:1},castShadow:!0}}}function $j(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function eM(e){return[{name:`Sun`,type:`DirectionalLight3D`,props:{position:[Q(e*.8),Q(e*1.5),Q(e*.6)],intensity:1,castShadow:!0,shadowArea:Q(e*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[Q(-e*.8),Q(e*.8),Q(-e*.6)],intensity:.4,color:`#b9d4ff`}}]}function tM(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function nM(e,t,n){return Math.min(Math.max(e,t),n)}var rM=[`boxes`,`ruins`,`garden`],iM=.5,aM=.1,oM=2,sM={boxes:{floor:`#3f3f3f`,wall:`#55504a`,obstacles:[`#b0413e`,`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#878787`]},ruins:{floor:`#7d766b`,wall:`#8a8378`,obstacles:[`#8a8378`,`#979085`,`#a39a8d`,`#7b746a`]},garden:{floor:`#4d7c3a`,wall:`#2f6b2f`,obstacles:[`#2f6b2f`,`#3a7a38`,`#356e33`]}};function cM(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!rM.includes(o))throw new y(`BAD_FORMAT`,`generateArena theme must be one of [${rM.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...rM]});let s=sM[o],c=new b(t),l=[Zj(`Floor`,[n,aM,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+iM*2,i,iM],f=[iM,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(Zj(`Wall1`,d,[0,u,-(r+iM)/2],p),Zj(`Wall2`,d,[0,u,(r+iM)/2],p),Zj(`Wall3`,f,[-(n+iM)/2,u,0],p),Zj(`Wall4`,f,[(n+iM)/2,u,0],p)),o===`ruins`?l.push(...uM(c,s,n,r,i,a)):l.push(...lM(c,s,n,r,i,a,o)),o===`garden`&&l.push(...dM(c,n,r));let m=Math.max(n,r);return l.push({name:`Sun`,type:`DirectionalLight3D`,props:{position:[Q(m*.8),Q(m*1.5),Q(m*.6)],intensity:1,castShadow:!0,shadowArea:Q(m*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[Q(-m*.8),Q(m*.8),Q(-m*.6)],intensity:.4,color:`#b9d4ff`}},{name:`Lamp`,type:`OmniLight3D`,props:{position:[0,Q(i+2),0],intensity:.5,color:`#fff3d6`,range:Q(m)}}),{name:`Arena`,type:`Node3D`,children:l}}function lM(e,t,n,r,i,a,o){let s=[],c=o===`garden`?Math.min(n,r)*.16:0;for(let o=1;o<=a;o++){let a=[Q(e.range(.8,2.6)),Q(e.range(.8,Math.max(1.2,i*.8))),Q(e.range(.8,2.6))],l=Q(e.range(-(n/2-oM),n/2-oM)),u=Q(e.range(-(r/2-oM),r/2-oM));if(c>0&&Math.hypot(l,u)<c+1.5){let t=Math.max(Math.hypot(l,u),.001);l=Q(l/t*(c+1.5+e.range(0,2))),u=Q(u/t*(c+1.5+e.range(0,2)))}let d=e.int(0,359);s.push(Zj(`Obstacle${o}`,a,[l,Q(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function uM(e,t,n,r,i,a){let o=[];if(a<=0)return o;let s=Math.max(1,Math.round(Math.sqrt(a/2))),c=Math.ceil(a/s),l=n-oM*2,u=r-oM*2,d=0;for(let n=0;n<s&&d<a;n++){let r=Q(s===1?0:-u/2+n/(s-1)*u);for(let n=0;n<c&&d<a;n++){d++;let a=Q((c===1?0:-l/2+n/(c-1)*l)+e.range(-.4,.4)),s=Q(e.next()>.35?e.range(i*.7,i*1.2):e.range(.4,.9)),u=Q(e.range(.8,1.2));o.push(Zj(`Obstacle${d}`,[u,s,u],[a,Q(s/2),Q(r+e.range(-.4,.4))],{material:{color:e.pick(t.obstacles),roughness:.95},castShadow:!0},[0,e.int(-8,8),0]))}}return o}function dM(e,t,n){let r=[],i=Math.min(t,n)*.16,a=r=>{let a=Math.min(t,n)/2-r/2-1,o=Q(e.range(-a,a)),s=Q(e.range(-a,a)),c=Math.max(Math.hypot(o,s),.001);return c<i+r/2&&(o=Q(o/c*(i+r/2+.5)),s=Q(s/c*(i+r/2+.5))),[o,s]};for(let i=1;i<=3;i++){let o=Q(Math.min(t,n)*e.range(.18,.26)),[s,c]=a(o);r.push({name:`Grass${i}`,type:`Foliage3D`,props:{kind:`grass`,area:[o,o],density:10,seed:e.int(1,1e9),position:[s,0,c]}})}for(let i=1;i<=2;i++){let o=Q(Math.min(t,n)*e.range(.12,.18)),[s,c]=a(o);r.push({name:`FlowerBed${i}`,type:`Flowers3D`,props:{density:`lush`,clustering:.3,area:[o,o],seed:e.int(1,1e9),position:[s,0,c]}})}return r.push({name:`Pool`,type:`Water3D`,props:{size:[Q(i*2),Q(i*2)],position:[0,.3,0],waveHeight:.04}}),r}var fM=32,pM=[4,8],mM=`#332f3a`,hM=`#6b6357`;function gM(e){let{seed:t,rooms:n=5}=e,[r,i]=tM(e.size,[960,720]),a=Math.max(8,Math.floor(r/fM)),o=Math.max(8,Math.floor(i/fM)),s=new b(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(pM[0],pM[1]),t=s.int(pM[0],pM[1]),n={x:s.int(1,Math.max(1,a-e-1)),y:s.int(1,Math.max(1,o-t-1)),w:e,h:t};c.some(e=>_M(e,n,1))||c.push(n)}let l=new Set,u=e=>{for(let t=e.y;t<e.y+e.h;t++)for(let n=e.x;n<e.x+e.w;n++)l.add(`${n},${t}`)};for(let e of c)u(e);let d=[];for(let e=1;e<c.length;e++){let[t,n]=vM(c[e-1]),[r,i]=vM(c[e]),a={x:Math.min(t,r),y:n,w:Math.abs(t-r)+1,h:1},o={x:r,y:Math.min(n,i),w:1,h:Math.abs(n-i)+1};for(let[t,n]of[[`H`,a],[`V`,o]])u(n),(n.w>1||n.h>1)&&d.push({name:`Corridor${e}${t}`,rect:n})}let f=new Set;for(let e of l){let[t,n]=e.split(`,`).map(Number);for(let e=-1;e<=1;e++)for(let r=-1;r<=1;r++){let i=`${t+r},${n+e}`;l.has(i)||f.add(i)}}let p=-(a*fM)/2,m=-(o*fM)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*fM,m+(t.y+t.h/2)*fM],size:[t.w*fM,t.h*fM],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,mM));for(let e of d)g.push(h(e.name,e.rect,mM));let _=0;for(let e=-1;e<=o;e++){let t=-1;for(;t<=a;){if(!f.has(`${t},${e}`)){t++;continue}let n=1;for(;t+n<=a&&f.has(`${t+n},${e}`);)n++;_++;let r=[n*fM,fM];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*fM,m+(e+.5)*fM],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:hM}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function _M(e,t,n){return e.x-n<t.x+t.w&&e.x+e.w+n>t.x&&e.y-n<t.y+t.h&&e.y+e.h+n>t.y}function vM(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var yM=[[0,-1],[1,0],[0,1],[-1,0]];function bM(e,t,n){let r=2*t+1,i=2*n+1,a=Array.from({length:i},()=>Array(r).fill(!1)),o=(e,t)=>{a[t][e]=!0};o(1,1);let s=new Set([`0,0`]),c=[[0,0]];for(;c.length>0;){let[r,i]=c[c.length-1],a=[];for(let[e,o]of yM){let c=r+e,l=i+o;c>=0&&c<t&&l>=0&&l<n&&!s.has(`${c},${l}`)&&a.push([c,l])}if(a.length===0){c.pop();continue}let[l,u]=e.pick(a);s.add(`${l},${u}`),o(2*l+1,2*u+1),o(r+l+1,i+u+1),c.push([l,u])}return o(0,1),o(2*t,2*n-1),{cols:t,rows:n,cells:a}}var xM=[`stone`,`hedge`,`canyon`],SM=.1,CM=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,wM=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,TM={stone:{wall:{color:`#e8e2d8`,map:`${CM}/blocks.png`,normalMap:`${CM}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${wM}/stone.png`,normalMap:`${wM}/stone_normal.png`,tile:3,roughness:1},cap:`#6b5848`,pillar:`#cfc8bb`,path:`#665f55`,sun:{color:`#c9d6ea`,intensity:.75,height:.5},fill:`#9fb4cc`,mood:{sky:{elevationDeg:10,azimuthDeg:150,turbidity:16,rayleigh:3.2},fog:{near:.5,far:3.5,color:`#86909c`},exposure:.82,ambient:{color:`#c9d4e2`,intensity:.12}}},hedge:{wall:{color:`#55a83e`,map:`${wM}/grass.png`,normalMap:`${wM}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${wM}/grass.png`,normalMap:`${wM}/grass_normal.png`,tile:3,roughness:1},pillar:`#3d7531`,path:`#7d6845`,sun:{color:`#e9eee6`,intensity:.7,height:1},fill:`#b9c8b4`,mood:{sky:{elevationDeg:35,azimuthDeg:150,turbidity:18,rayleigh:4.2},fog:{near:.8,far:5,color:`#aab8a6`},exposure:.88,ambient:{color:`#dde5d8`,intensity:.15}}},canyon:{wall:{color:`#f0b070`,map:`${wM}/stone.png`,normalMap:`${wM}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${wM}/sand.png`,normalMap:`${wM}/sand_normal.png`,tile:3.5,roughness:1},pillar:`#d8a868`,path:`#a98a58`,sun:{color:`#ffb572`,intensity:1.15,height:.35},fill:`#caa37e`,mood:{sky:{elevationDeg:9,azimuthDeg:230,turbidity:9,rayleigh:3.5},fog:{near:.7,far:4.5,color:`#c79c6e`},exposure:.92,ambient:{color:`#ffdcb6`,intensity:.13}}}};function EM(e,t,n){return{color:e.color,roughness:e.roughness,map:e.map,...e.normalMap?{normalMap:e.normalMap}:{},repeat:[Q(t/e.tile),Q(n/e.tile)]}}var DM=10;function OM(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!xM.includes(o))throw new y(`BAD_FORMAT`,`generateMaze theme must be one of [${xM.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...xM]});let s=TM[o],c=new b(t),l=bM(c,n,r),u=2*n+1,d=2*r+1,f=Q(u*i),p=Q(d*i),m=(e,t)=>[Q((e+.5)*i-f/2),Q((t+.5)*i-p/2)],h=[Zj(`Floor`,[f,SM,p],[0,-.1/2,0],{material:EM(s.floor,f,p),receiveShadow:!0})],g=[],_=0;for(let e=0;e<d;e++){let t=0;for(;t<u;){if(l.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<u&&!l.cells[e]?.[t+n];)n++;g.push({gx:t,gz:e,run:n}),_++;let r=Q(n*i);h.push(Zj(`Wall${_}`,[r,a,i],[Q((t+n/2)*i-f/2),Q(a/2),Q((e+.5)*i-p/2)],{material:EM(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...kM(g,i,a,f,p,s.cap)),h.push(...AM(c,l,i,a,m,s)),o===`hedge`?(h.push(...PM(c,g,i,a,m)),h.push(...FM(c,l,i,m,n,r))):o===`canyon`&&h.push(...IM(c,g,i,a,m)),h.push(...MM(l,i,a,m,s)),h.push(...eM(Math.max(f,p)).map((e,t)=>{if(t!==0)return{...e,props:{...e.props,color:s.fill}};let n=e.props?.position;return{...e,props:{...e.props,color:s.sun.color,intensity:s.sun.intensity,position:[n[0]??0,Q((n[1]??0)*s.sun.height),n[2]??0]}}})),{name:`Maze`,type:`Node3D`,children:h}}function kM(e,t,n,r,i,a){return e.map((e,o)=>({name:`Cap${o+1}`,type:`MeshInstance3D`,props:{mesh:`box`,size:[Q(e.run*t+.16),.12,Q(t+.16)],position:[Q((e.gx+e.run/2)*t-r/2),Q(n+.06),Q((e.gz+.5)*t-i/2)],material:{color:a,roughness:1},castShadow:!0,receiveShadow:!0}}))}function AM(e,t,n,r,i,a){let o=[],s=(e,n)=>t.cells[n]?.[e]===!1;for(let e=2;e<t.cells.length-1;e+=2)for(let n=2;n<(t.cells[e]?.length??0)-1;n+=2)s(n,e)&&Number(s(n-1,e))+Number(s(n+1,e))+Number(s(n,e-1))+Number(s(n,e+1))>=3&&o.push([n,e]);let c=Math.min(DM,o.length),l=[],u=new Set,d=Q(n*1.2),f=Q(r*1.12);for(let t=1;t<=c;t++){let n=e.int(0,o.length-1);for(;u.has(n);)n=(n+1)%o.length;u.add(n);let[r,s]=o[n],[c,p]=i(r,s);l.push(jM(`Pillar${t}`,c,p,d,f,a))}return l}function jM(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,Q(i/2),n],material:{...EM(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function MM(e,t,n,r,i){let a=2*e.cols,o=2*e.rows-1,s=Q(t*1.1),c=Q(n*1.25),l=[[0,0],[0,2],[a,o-1],[a,o+1]].map(([e,t],n)=>{let[a,o]=r(e,t);return jM(`Gate${n+1}`,a,o,s,c,i)});for(let[e,n,s]of[[`EntrancePath`,0,1],[`ExitPath`,a,o]]){let[a,o]=r(n,s);l.push({name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[Q(t*.96),.04,Q(t*.96)],position:[a,.02,o],material:{...EM(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var NM=10;function PM(e,t,n,r,i){return[...t].filter(e=>e.run>=2).sort((e,t)=>t.run-e.run||e.gz-t.gz||e.gx-t.gx).slice(0,NM).map((t,a)=>{let[,o]=i(t.gx,t.gz),[s]=i(t.gx,t.gz),[c]=i(t.gx+t.run-1,t.gz);return{name:`HedgeTop${a+1}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[Q(t.run*n*.92),Q(n*.7)],density:14,height:.35,sway:.4,colorA:`#2f5e26`,colorB:`#5d8a3c`,seed:e.int(1,1e9),position:[Q((s+c)/2),r,o]}}})}function FM(e,t,n,r,i,a){let o=[];for(let e=0;e<t.cells.length;e++)for(let n=0;n<(t.cells[e]?.length??0);n++)t.cells[e]?.[n]&&o.push([n,e]);let s=Math.min(o.length,Math.max(3,Math.floor(i*a/12))),c=[],l=new Set;for(let t=1;t<=s&&l.size<o.length;t++){let i=e.int(0,o.length-1);for(;l.has(i);)i=(i+1)%o.length;l.add(i);let[a,s]=o[i],[u,d]=r(a,s),f=Q(n*.8);c.push({name:`Grass${t}`,type:`Foliage3D`,props:{kind:`grass`,area:[f,f],density:8,seed:e.int(1,1e9),position:[u,0,d]}})}return c}function IM(e,t,n,r,i){let a=[];if(t.length===0)return a;let o=Math.min(8,t.length);for(let s=1;s<=o;s++){let o=e.pick(t),[c,l]=i(o.gx+e.int(0,o.run-1),o.gz),u=Qj(s,c,l,e,[.3,Q(n*.35)],`#8f7355`),d=u.props?.position;d[1]=Q(d[1]+r),a.push(u)}return a}var LM=`#23222b`,RM=`#5f6672`;function zM(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=bM(new b(t),n,r),o=2*n+1,s=2*r+1,c=Q(o*i),l=Q(s*i),u=[{name:`Floor`,type:`ColorRect2D`,props:{size:[c,l],color:LM}}],d=0;for(let e=0;e<s;e++){let t=0;for(;t<o;){if(a.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<o&&!a.cells[e]?.[t+n];)n++;d++;let r=[Q(n*i),i];u.push({name:`Wall${d}`,type:`StaticBody2D`,props:{position:[Q((t+n/2)*i-c/2),Q((e+.5)*i-l/2)],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:RM}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var BM=16,VM=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function HM(e){let{seed:t,count:n=10,width:r=[80,160],gapX:i=[40,120],stepY:a=[-80,40],start:o=[0,300]}=e,s=new b(t),c=[],l=Q(s.range(r[0],r[1])),u=o[0],d=o[1];for(let e=1;e<=n&&(c.push(UM(e,u,d,l,s.pick(VM))),e!==n);e++){let e=Q(s.range(r[0],r[1])),t=Q(s.range(i[0],i[1]));u=Q(u+l/2+t+e/2),d=Q(d+s.range(a[0],a[1])),l=e}return{name:`Platforms`,type:`Node2D`,children:c}}function UM(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,BM]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,BM],color:i}}]}}var WM=[3,5],GM=3,KM={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function qM(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=tM(e.area,[60,60]),o=new b(t),s=[];for(let e=1;e<=n;e++){let t=o.int(WM[0],WM[1]),n=[];for(let e=1;e<=t;e++){let r=Q(o.range(1,2.2));n.push({name:`Puff${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[Q((e-(t+1)/2)*o.range(1,1.6)),Q(o.range(-.3,.3)),Q(o.range(-.6,.6))],scale:[Q(r*o.range(1.1,1.6)),Q(r*.55),r],material:KM}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[Q(o.range(-i/2,i/2)),Q(r+o.range(-3,GM)),Q(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,children:s}}var JM=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],YM=128,XM=20,ZM=.8,QM=.12,$M={island:{splat:`island`,maxHeight:4.5,sun:`#fff4d6`,fill:`#b9d4ff`,sky:{elevationDeg:38,azimuthDeg:145,turbidity:2.6,rayleigh:1.1},fog:{near:1,far:4},iblIntensity:.72},alpine:{splat:`alpine`,maxHeight:8,roughness:.65,detail:5,sun:`#f4f7ff`,fill:`#c9d8f2`,sky:{elevationDeg:45,azimuthDeg:35,turbidity:1.4,rayleigh:1.3},fog:{near:1.8,far:6.5},sunIntensity:1.1,exposure:.92,iblIntensity:.72},plains:{splat:`plains`,maxHeight:4,sun:`#fff2cf`,fill:`#bcd3ef`,sky:{elevationDeg:36,azimuthDeg:140,turbidity:2.4,rayleigh:1},fog:{near:.9,far:4},iblIntensity:.58},desert:{splat:`desert`,maxHeight:5,sun:`#ffe3b3`,fill:`#e8c9a6`,sky:{elevationDeg:42,azimuthDeg:160,turbidity:7,rayleigh:.6},fog:{near:.8,far:3.2,color:`#e8d3ae`},sunIntensity:1.35,iblIntensity:.75},meadow:{splat:`grassland`,maxHeight:1.2,sun:`#fff8e2`,fill:`#bfe0c9`,sky:{elevationDeg:55,azimuthDeg:125,turbidity:2.4,rayleigh:.95},fog:{near:1,far:4.4},sunIntensity:2.6,exposure:1.12,iblIntensity:.62},forest:{splat:`forest`,maxHeight:2.5,sun:`#ffdca8`,fill:`#a9c8b4`,sky:{elevationDeg:29,azimuthDeg:120,turbidity:5.5,rayleigh:1},fog:{near:.22,far:1.8,color:`#9fb494`},sunIntensity:2.6,ambient:.26,iblIntensity:.55},savanna:{splat:`savanna`,maxHeight:3,sun:`#ffdca0`,fill:`#e6d2a4`,sky:{elevationDeg:34,azimuthDeg:150,turbidity:5,rayleigh:.7},fog:{near:1,far:4.2,color:`#e3cf9f`},sunIntensity:2,exposure:1.05,iblIntensity:.6},snow:{splat:`snow`,maxHeight:2.2,sun:`#dfe9ff`,fill:`#c2d2f0`,sky:{elevationDeg:22,azimuthDeg:35,turbidity:1.6,rayleigh:1.6},fog:{near:1.2,far:5,color:`#dbe6f5`},sunIntensity:1,exposure:.9,iblIntensity:.72},wetland:{splat:`wetland`,maxHeight:1.4,sun:`#d6ddc8`,fill:`#9fb29a`,sky:{elevationDeg:24,azimuthDeg:115,turbidity:9,rayleigh:1.1},fog:{near:.5,far:2,color:`#92a288`},sunIntensity:1.5,exposure:.94,ambient:.24,iblIntensity:.66},volcanic:{splat:`volcanic`,maxHeight:4,roughness:.7,sun:`#ff8a4a`,fill:`#7a4a3a`,sky:{elevationDeg:14,azimuthDeg:135,turbidity:10,rayleigh:.3},fog:{near:.18,far:1.4,color:`#2a211c`},sunIntensity:1.7,exposure:.86,ambient:.22,iblIntensity:.5}};function eN(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=$M[n];if(!a)throw new y(`BAD_FORMAT`,`generateTerrain theme must be one of [${JM.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...JM]});let o=e.maxHeight||a.maxHeight,s=new b(t),c=n===`island`,l=e=>Fx({width:r,depth:r,segsX:YM,segsZ:YM,maxHeight:e,seed:t,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},islandEdge:c}),u=l(o);if(c)for(let e=0;e<3;e++){let e=nN(u)-XM,t=u.maxHeight-u.minHeight,n=u.minHeight+QM*t;if(e+ZM<=n)break;let r=XM-ZM,i=nN(u)-u.minHeight-QM*t;o=Q(o*Math.min(r/i*.95,.9)),u=l(o)}let d=[{name:`Ground`,type:`StaticBody3D`,props:{collider:{shape:`heightfield`}},children:[{name:`Surface`,type:`Terrain3D`,props:{size:[r,r],maxHeight:o,seed:t,theme:a.splat,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail}}}]}],f=n===`wetland`;if(c)d.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,tN(u),0],opacity:1}});else if(f){let e=u.maxHeight-u.minHeight||1,t=Q(u.minHeight+.22*e);d.push({name:`Swamp`,type:`Water3D`,props:{size:[r,r],position:[0,t,0],waveHeight:.02,quality:`simple`,color:`#3a4a30`,opacity:.95}})}else if(i){let e=Q(u.minHeight+.1*(u.maxHeight-u.minHeight));d.push({name:`Lake`,type:`Water3D`,props:{size:[r,r],position:[0,e,0],waveHeight:.04}})}return d.push(...vN(n,s,u,r)),c&&d.push(qM({seed:s.int(1,1e9),count:6,area:r,altitude:Math.round(u.maxHeight+12)})),d.push(...eM(r).map((e,t)=>yN(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:d}}function tN(e){let t=nN(e)-XM,n=e.minHeight+QM*(e.maxHeight-e.minHeight);return Q(Math.max(Math.min(t+ZM,n),t+.55))}function nN(e){let t=-1/0,n=e.width/2,r=e.depth/2;for(let i=0;i<=YM;i++){let a=-n+i/YM*e.width,o=-r+i/YM*e.depth;t=Math.max(t,e.baseHeight(a,-r),e.baseHeight(a,r),e.baseHeight(-n,o),e.baseHeight(n,o))}return t}function rN(e,t,n){let r=Math.min(t.width/2-n.margin,n.within??1/0),i=t.maxHeight-t.minHeight||1,a=[];for(let o=0;o<n.count*30&&a.length<n.count;o++){let o=Q(e.range(-r,r)),s=Q(e.range(-r,r));if(n.clearing&&Math.hypot(o,s)<n.clearing||n.within&&Math.hypot(o,s)>n.within)continue;let c=t.heightAt(o,s),l=(c-t.minHeight)/i;l<n.band[0]||l>n.band[1]||t.slopeAt(o,s)>n.maxSlope||a.push({x:o,z:s,y:c})}return a}var iN=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],aN=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],oN={canopy:`#9aa052`,trunk:`#8a6a44`},sN={canopy:`#39513f`,trunk:`#5a5650`};function cN(e,t){return e===`conifer`?t.pick(iN):e===`broadleaf`?t.pick(aN):null}function lN(e,t,n,r,i){let a=i?.height??[4.5,7],o=i?.sink??(i?.count===void 0?.05:.3),s={};i?.tier!==void 0&&(s.tier=i.tier),i?.count!==void 0&&i.area!==void 0&&(s.count=i.count,s.area=[i.area,i.area]);let c=cN(r,n),l=i?.palette??c;return l&&(s.canopyColor=l.canopy,s.trunkColor=l.trunk),{name:e,type:`Tree3D`,props:{type:r,seed:n.int(1,1e9),height:Q(n.range(a[0],a[1])),position:[t.x,Q(t.y-o),t.z],...s}}}function uN(e,t,n,r,i,a=0,o){return{name:e,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[r,r],density:i,height:o?.height??.3,...o?.colors?{colorA:o.colors[0],colorB:o.colors[1]}:{},seed:n.int(1,1e9),position:[t.x,Q(t.y+.02),t.z],...a>0?{flowers:a}:{}}}}function dN(e,t,n,r,i){return{name:e,type:`Foliage3D`,props:{kind:`reeds`,style:`simple`,area:[r,r],density:i,height:.9,colorA:`#2f4a26`,colorB:`#5a6f33`,seed:n.int(1,1e9),position:[t.x,Q(t.y+.02),t.z]}}}function fN(e,t,n,r,i){return{name:e,type:`Flowers3D`,props:{density:i,area:[r,r],seed:n.int(1,1e9),position:[t.x,Q(t.y+.02),t.z]}}}function pN(e,t,n,r){return e.map((e,i)=>{let a=Qj(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=Q(o[1]+e.y),a})}function mN(e){let t=Math.round(e.range(104,128)),n=Math.round(t-e.range(10,18)),r=Math.round(t-e.range(20,30)),i=e=>e.toString(16).padStart(2,`0`);return`#${i(n)}${i(t)}${i(r)}`}function hN(e){let t=Math.round(e.range(196,224)),n=Math.min(255,t+Math.round(e.range(4,12))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(t)}${r(t)}${r(n)}`}function gN(e){let t=Math.round(e.range(34,56)),n=Math.min(255,t+Math.round(e.range(2,8))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(n)}${r(t)}${r(t)}`}var _N=[`#6f5b41`,`#7a644a`,`#665439`];function vN(e,t,n,r){let i=[];switch(e){case`island`:{let e=rN(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>lN(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=rN(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>lN(`Tree${n+1}`,e,t,`conifer`)));let r=rN(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...pN(r,t,[.6,1.8]));break}case`plains`:{let e=rN(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>lN(`Tree${n+1}`,e,t,`broadleaf`)));let r=rN(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...pN(r,t,[.4,1.2]));break}case`desert`:{let e=rN(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>lN(`Tree${n+1}`,e,t,`dead`)));let r=rN(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...pN(r,t,[.5,1.6]));break}case`meadow`:{let e=Q(r*.09),a=rN(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>uN(`Carpet${r+1}`,n,t,e,30)));let o=Q(r*.07),s=rN(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>fN(`Flowers${n+1}`,e,t,o,`sparse`)));let c=rN(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>lN(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=rN(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...pN(l,t,[.3,.9]));break}case`forest`:{let e=Q(r*.12),a=r/2-8,o=et(t.int(1,1e9)),s=(e,t,n)=>{let r=o(e/70,t/70);return r>.12?`conifer`:r<-.12?`broadleaf`:n%2==0?`conifer`:`broadleaf`},c=rN(t,n,{count:40,band:[0,1],maxSlope:.18,margin:8,clearing:e+6}),l=c.map((e,t)=>s(e.x,e.z,t));i.push(...c.map((e,n)=>lN(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(lN(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=rN(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>lN(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=rN(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>lN(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=rN(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>lN(`Bush${n+1}`,e,t,`bush`,{count:4,area:10,height:[2.1,3.1],sink:.12})));let p=0;c.forEach((e,r)=>{if(r%3==2)return;let o=t.range(0,Math.PI*2),s=t.range(2,4.5),c=t.int(1,1e9),l=Q(nM(e.x+Math.cos(o)*s,-a,a)),u=Q(nM(e.z+Math.sin(o)*s,-a,a));n.slopeAt(l,u)>.09||(p++,i.push({name:`Fern${p}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,tuftStyle:`fern`,area:[8,8],density:9,height:.4,colorA:`#4a6b34`,colorB:`#82a258`,seed:c,position:[l,Q(n.heightAt(l,u)+.02),u]}}))});let m=Q(r*.08),h=rN(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>uN(`Grass${n+1}`,e,t,m,20,0,{height:.24,colors:[`#4f7034`,`#85a154`]})));let g=u.length>0?t.int(3,5):0;for(let e=0;e<g;e++){let r=u[e%u.length],o=t.range(0,Math.PI*2),s=t.range(2.5,4.5),c=Q(nM(r.x+Math.cos(o)*s,-a,a)),l=Q(nM(r.z+Math.sin(o)*s,-a,a));i.push({name:`Log${e+1}`,type:`Tree3D`,props:{type:`dead`,seed:t.int(1,1e9),height:Q(t.range(4.2,5.6)),trunkColor:`#4a4236`,position:[c,Q(n.heightAt(c,l)+.12),l],rotation:[0,t.int(0,359),Q(t.range(81,97))]}})}rN(t,n,{count:5,band:[0,1],maxSlope:.25,margin:9,clearing:e}).forEach((e,n)=>{let r=Q(t.range(.16,.28)),a=Q(t.range(.3,.55));i.push({name:`Stump${n+1}`,type:`MeshInstance3D`,props:{mesh:`cylinder`,size:[r,a,r],position:[e.x,Q(e.y+a/2-.06),e.z],rotation:[0,t.int(0,359),0],material:{color:t.pick(_N),roughness:1},castShadow:!0}})});let _=rN(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...pN(_,t,[.3,1],mN));let v=Q(e*.75),y=rN(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-Q(v/Math.SQRT2)});i.push(...y.map((e,n)=>uN(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=Q(e*.45),x=rN(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-Q(b/Math.SQRT2)});i.push(...x.map((e,n)=>fN(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=rN(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>lN(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:oN})));let a=Q(r*.09),o=rN(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>uN(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=rN(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...pN(s,t,[.4,1.4]));let c=rN(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>lN(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=rN(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>lN(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:sN})));let r=rN(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...pN(r,t,[.5,1.8],hN));break}case`wetland`:{let e=Q(r*.08),a=rN(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>dN(`Reeds${r+1}`,n,t,e,4)));let o=Q(r*.08),s=rN(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>uN(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=rN(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>lN(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=rN(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>lN(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=rN(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...pN(u,t,[.3,1],mN));break}case`volcanic`:{let e=rN(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>lN(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=rN(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...pN(r,t,[.4,1.8],gN)),rN(t,n,{count:3,band:[0,.6],maxSlope:.18,margin:12}).forEach((e,n)=>{t.int(1,1e9),i.push({name:`Smoke${n+1}`,type:`Particles3D`,props:{preset:`smoke`,position:[e.x,Q(e.y+.2),e.z],rate:8,maxParticles:64,colorStart:`#5a5048`,colorEnd:`#2a2422`,sizeStart:18,sizeEnd:44}}),i.push({name:`Embers${n+1}`,type:`Particles3D`,props:{position:[e.x,Q(e.y+.1),e.z],rate:10,maxParticles:48,lifetime:[.8,1.8],speed:[12,34],directionDeg:-90,spreadDeg:40,gravity:[0,-18],sizeStart:4,sizeEnd:1,colorStart:`#ffce6a`,colorEnd:`#d83a14`,blend:`add`}})});break}}return i}function yN(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var bN={arena:{description:`FPS stage: floor, 4 perimeter walls, obstacles, lights — themes: boxes (crates), ruins (broken stone rows), garden (hedges, grass, pool)`,dimension:`3d`,params:{theme:{type:`string`,default:`boxes`,options:[...rM]},width:{type:`number`,default:30,min:4},depth:{type:`number`,default:30,min:4},wallHeight:{type:`number`,default:3,min:.5},obstacles:{type:`number`,default:8,min:0}}},terrain:{description:`Heightfield world: StaticBody3D{heightfield} + Terrain3D + theme dressing (trees, rocks, grass, sea/clouds on island, broad swamp water on wetland, smoke/ember emitters on volcanic; maxHeight 0 = theme default; water adds a lake to non-island themes)`,dimension:`3d`,params:{theme:{type:`string`,default:`island`,options:[...JM]},size:{type:`number`,default:200,min:40,max:400},maxHeight:{type:`number`,default:0,min:0},water:{type:`boolean`,default:!1}}},maze:{description:`Recursive-backtracker 3D maze, west→east — themes: stone, hedge (green + grass), canyon (sandstone + rim rocks)`,dimension:`3d`,params:{theme:{type:`string`,default:`stone`,options:[...xM]},width:{type:`number`,default:8,min:2,max:40},depth:{type:`number`,default:8,min:2,max:40},cellSize:{type:`number`,default:2,min:.5},wallHeight:{type:`number`,default:2.5,min:.5}}},maze2d:{description:`The same maze algorithm as 2D ColorRect2D + StaticBody2D tiles`,dimension:`2d`,params:{cols:{type:`number`,default:10,min:2,max:40},rows:{type:`number`,default:8,min:2,max:40},cellPx:{type:`number`,default:64,min:8}}},dungeon2d:{description:`Roguelike rooms + L-corridors: floor rects, wall bodies (32px tiles)`,dimension:`2d`,params:{rooms:{type:`number`,default:5,min:1,max:20},size:{type:`number`,default:960,min:256}}},platforms2d:{description:`Left-to-right 2D platform course (tune ranges via the library)`,dimension:`2d`,params:{count:{type:`number`,default:10,min:1}}}},xN={arena:cM,terrain:eN,maze:OM,maze2d:zM,dungeon2d:gM,platforms2d:HM};function SN(e,t){let n=xN[e];if(!n){let t=Object.keys(xN);throw new y(`BAD_FORMAT`,`Unknown generator '${e}'. Valid: [${t.join(`, `)}] — the old meadow/forest/island/rocks/clouds generators became themes (e.g. terrain theme: 'meadow', arena theme: 'garden'); scatter is library-only (needs item templates).`,{validOptions:t})}return n(t)}function CN(e){return Object.entries(bN).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function wN(e,t){if(e.type===`boolean`)return t===!0||t===`true`;if(e.type===`number`){let n=typeof t==`boolean`?NaN:Number(t);return(t===``||!Number.isFinite(n))&&(n=e.default),e.min!==void 0&&(n=Math.max(e.min,n)),e.max!==void 0&&(n=Math.min(e.max,n)),n}let n=String(t);return e.options&&!e.options.includes(n)?e.default:n}function TN(){return Math.floor(Math.random()*1e6)}var EN=[],DN=new Map,ON=null;function kN(e){let t=document.querySelector(`#generate`);t&&(MN(e),t.removeAttribute(`hidden`))}function AN(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function jN(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&AN()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,AN),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,AN),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>NN(e)))}function MN(e){let t=document.querySelector(`#generate-body`),n=document.querySelector(`#generate-status`);if(!t)return;n&&(n.textContent=``),t.textContent=``;let r=e.working.dimension??`2d`;EN=CN(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=rj({en:`Deterministic ${r.toUpperCase()} environment generators — the subtree inserts under the selected node (the root when nothing is selected). The same seed always generates the same level.`,ko:`결정적 ${r.toUpperCase()} 환경 생성기 — 생성된 서브트리는 선택한 노드 아래에(선택이 없으면 루트에) 들어갑니다. 같은 시드는 항상 같은 레벨을 만듭니다.`}),t.appendChild(i);let a=PN(rj({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of EN){let t=document.createElement(`option`);t.value=e,t.textContent=e,o.appendChild(t)}a.appendChild(o),t.appendChild(a);let s=document.createElement(`p`);s.className=`gen-desc`,t.appendChild(s);let c=document.createElement(`div`);c.id=`generate-params`,t.appendChild(c);let l=PN(`seed`);ON=document.createElement(`input`),ON.type=`number`,ON.step=`1`,ON.value=String(TN());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=rj({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{ON&&(ON.value=String(TN()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(ON,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=EN.find(e=>e.name===o.value)??EN[0];if(e){s.textContent=e.meta.description,c.textContent=``,DN=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=PN(t),r;if(n.type===`boolean`)r=document.createElement(`input`),r.type=`checkbox`,r.checked=n.default===!0;else if(n.type===`string`&&n.options){r=document.createElement(`select`);for(let e of n.options){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}r.value=String(n.default)}else r=document.createElement(`input`),r.type=n.type===`number`?`number`:`text`,n.type===`number`&&(r.step=`any`,n.min!==void 0&&(r.min=String(n.min)),n.max!==void 0&&(r.max=String(n.max))),r.value=String(n.default),(n.min!==void 0||n.max!==void 0)&&(r.title=`${n.min??``}–${n.max??``}`);DN.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function NN(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=EN.find(e=>e.name===n?.value);if(!r||!ON)return;let i={seed:wN({type:`number`,default:TN(),min:0},ON.value)};for(let[e,t]of DN){let n=r.meta.params[e];n&&(i[e]=wN(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=SN(r.name,i)}catch(e){t&&(t.textContent=e instanceof Error?e.message:String(e));return}let o=e.insertNode(a,e.selection??[]);if(o===null){t&&(t.textContent=rj({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),ON&&(ON.value=String(TN())),AN()}function PN(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var FN={groups:{title:{en:`groups — tag nodes for queries`,ko:`groups — 조회용 태그`},body:{en:`Free-form tags. Game code finds nodes with tree-wide queries like getNodesInGroup("coins"), and triggers can filter by group (e.g. only react to "player"). Type a name and press Enter.`,ko:`자유 형식 태그입니다. 게임 코드가 getNodesInGroup("coins")처럼 트리 전체에서 노드를 찾고, 트리거는 그룹으로 거릅니다(예: "player"에만 반응). 이름을 입력하고 Enter를 누르세요.`},example:`triggerEnter → if (other.isInGroup("player")) collect()`},script:{title:{en:`script — attach YOUR game logic`,ko:`script — 게임 로직 연결`},body:{en:`A Behavior is a TypeScript class living in YOUR game code, linked by name. The editor stores the link; the class itself must be registered in the game before loadScene. Props here are passed to the behavior instance.`,ko:`Behavior는 게임 코드에 있는 TypeScript 클래스이며 이름으로 연결됩니다. 에디터는 연결만 저장하고, 클래스 자체는 loadScene 전에 게임에서 등록되어야 합니다. 여기의 props가 비헤이비어 인스턴스로 전달됩니다.`},example:`registerBehavior('CoinCounter', CoinCounter) // in your main.ts`,copy:{label:`copy behavior boilerplate`,text:`import { Behavior, registerBehavior } from 'incanto';
|
|
8197
8225
|
|
package/editor/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Incanto Scene Editor</title>
|
|
7
7
|
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><rect width='16' height='16' rx='3' fill='%236ee7dc'/><text x='8' y='12' text-anchor='middle' font-size='11' font-family='monospace' fill='%230e1018'>i</text></svg>" />
|
|
8
|
-
<script type="module" crossorigin src="./assets/index-
|
|
8
|
+
<script type="module" crossorigin src="./assets/index-BGtXxzJn.js"></script>
|
|
9
9
|
<link rel="modulepreload" crossorigin href="./assets/GameServer-C56iOUgF.js">
|
|
10
10
|
<link rel="stylesheet" crossorigin href="./assets/index-D8QvwvOm.css">
|
|
11
11
|
</head>
|
package/package.json
CHANGED