threedog 0.0.0-stage → 0.2.0
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/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/core/Animator.js +268 -0
- package/core/Assets.js +256 -0
- package/core/Audio.js +267 -0
- package/core/Baked.js +72 -0
- package/core/Batching.js +247 -0
- package/core/Budget.js +221 -0
- package/core/Clock.js +94 -0
- package/core/Commits.js +77 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +145 -0
- package/core/Engine.js +184 -0
- package/core/Events.js +153 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +77 -0
- package/core/InspectScene.js +191 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +256 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +254 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +94 -0
- package/core/Vars.js +35 -0
- package/core/Views.js +49 -0
- package/core/actor.js +23 -0
- package/core/assetEntry.js +89 -0
- package/core/assetLoad.js +190 -0
- package/core/assetManifest.js +35 -0
- package/core/assetReport.js +83 -0
- package/core/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/dayTime.js +15 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +143 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +205 -0
- package/core/errorHints.js +208 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -0
- package/core/holds.js +106 -0
- package/core/inputContext.js +69 -0
- package/core/inputDefaults.js +22 -0
- package/core/inputPad.js +35 -0
- package/core/inputPointer.js +48 -0
- package/core/inputTouch.js +48 -0
- package/core/lifecycle.js +69 -0
- package/core/lightWatch.js +56 -0
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +200 -0
- package/core/math.js +33 -0
- package/core/modules.js +196 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +97 -0
- package/core/opsFail.js +20 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/opsRun.js +77 -0
- package/core/page.js +78 -0
- package/core/params.js +132 -0
- package/core/pureWorker.js +5 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +128 -0
- package/core/saveFiles.js +139 -0
- package/core/saveIds.js +53 -0
- package/core/saveVersions.js +97 -0
- package/core/scatter.js +92 -0
- package/core/sceneMethods.js +100 -0
- package/core/screenToGround.js +39 -0
- package/core/services.js +73 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +135 -0
- package/core/streamCells.js +24 -0
- package/core/streamSources.js +73 -0
- package/core/styleParts.js +96 -0
- package/core/targeting.js +64 -0
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +168 -0
- package/core/things.js +212 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/util.js +11 -0
- package/core/validate.js +204 -0
- package/docs/AI.md +123 -0
- package/docs/API.md +83 -0
- package/docs/CODEMAP.md +347 -0
- package/docs/COMMANDS.md +108 -0
- package/docs/CONVENTIONS.md +145 -0
- package/docs/PERF.md +217 -0
- package/docs/THREE.md +86 -0
- package/docs/api/ambience.md +15 -0
- package/docs/api/assets.md +62 -0
- package/docs/api/audio.md +53 -0
- package/docs/api/budget.md +40 -0
- package/docs/api/cameraRig.md +120 -0
- package/docs/api/characters.md +144 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +39 -0
- package/docs/api/content.md +64 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +199 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +95 -0
- package/docs/api/flow.md +27 -0
- package/docs/api/grids.md +11 -0
- package/docs/api/ground.md +16 -0
- package/docs/api/hlod.md +34 -0
- package/docs/api/hud.md +31 -0
- package/docs/api/i18n.md +10 -0
- package/docs/api/input.md +24 -0
- package/docs/api/interactions.md +31 -0
- package/docs/api/inventory.md +66 -0
- package/docs/api/jobs.md +10 -0
- package/docs/api/level.md +41 -0
- package/docs/api/lightPool.md +56 -0
- package/docs/api/music.md +34 -0
- package/docs/api/nav.md +26 -0
- package/docs/api/net.md +14 -0
- package/docs/api/openWorld.md +24 -0
- package/docs/api/particles.md +41 -0
- package/docs/api/photo.md +15 -0
- package/docs/api/post.md +10 -0
- package/docs/api/quests.md +36 -0
- package/docs/api/rays.md +26 -0
- package/docs/api/rigid.md +84 -0
- package/docs/api/saves.md +32 -0
- package/docs/api/settings.md +36 -0
- package/docs/api/sky.md +58 -0
- package/docs/api/stream.md +31 -0
- package/docs/api/style.md +134 -0
- package/docs/api/terrain.md +34 -0
- package/docs/api/timeline.md +39 -0
- package/docs/api/tools.md +57 -0
- package/docs/api/triggers.md +56 -0
- package/docs/api/vars.md +9 -0
- package/docs/api/vegetation.md +52 -0
- package/docs/api/water.md +48 -0
- package/docs/api/weather.md +29 -0
- package/docs/api/world.md +30 -0
- package/docs/recipes/01-new-game.md +148 -0
- package/docs/recipes/02-npc.md +167 -0
- package/docs/recipes/03-items-pickups.md +158 -0
- package/docs/recipes/04-quests.md +83 -0
- package/docs/recipes/05-props-bake.md +159 -0
- package/docs/recipes/06-clock-events.md +117 -0
- package/docs/recipes/07-flow-scenes-pause.md +132 -0
- package/docs/recipes/08-weather-sky.md +74 -0
- package/docs/recipes/09-style-pack.md +234 -0
- package/docs/recipes/10-blender-level.md +67 -0
- package/docs/recipes/11-vehicles.md +55 -0
- package/docs/recipes/12-navmesh.md +79 -0
- package/docs/recipes/13-animation.md +149 -0
- package/docs/recipes/14-custom-module.md +91 -0
- package/docs/recipes/15-perf.md +78 -0
- package/docs/recipes/16-dev-bridge.md +180 -0
- package/docs/recipes/18-world.md +185 -0
- package/docs/recipes/19-shooting-picking.md +76 -0
- package/docs/recipes/20-content-actions-save.md +176 -0
- package/docs/recipes/21-camera.md +153 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +175 -0
- package/docs/recipes/26-ui-parts.md +138 -0
- package/docs/recipes/27-net.md +96 -0
- package/docs/recipes/28-terrain.md +80 -0
- package/docs/recipes/29-grid.md +87 -0
- package/docs/recipes/30-templates.md +131 -0
- package/docs/recipes/31-audio.md +126 -0
- package/docs/recipes/32-action-game.md +33 -0
- package/docs/recipes/33-stream-sources.md +37 -0
- package/docs/recipes/34-environment-lighting.md +36 -0
- package/docs/recipes/35-style-from-reference.md +89 -0
- package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
- package/docs/recipes/37-terrain-look-hooks.md +97 -0
- package/docs/recipes/38-environment-look-hooks.md +83 -0
- package/docs/recipes/40-scene.md +108 -0
- package/docs/recipes/41-thing-registry.md +93 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
- package/docs/recipes/44-water-weather-look-hooks.md +135 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +114 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/DESIGN.md +3 -0
- package/examples/action/GAMEMAP.md +127 -0
- package/examples/action/content/actions.js +8 -0
- package/examples/action/content/audio.js +9 -0
- package/examples/action/content/index.js +10 -0
- package/examples/action/content/items.js +4 -0
- package/examples/action/content/places.js +4 -0
- package/examples/action/content/props.js +11 -0
- package/examples/action/content/templates.js +10 -0
- package/examples/action/content/views.js +6 -0
- package/examples/action/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +107 -0
- package/examples/sheepisland/content/index.js +6 -0
- package/examples/sheepisland/content/props.js +19 -0
- package/examples/sheepisland/content/templates.js +5 -0
- package/examples/sheepisland/content/vegetation.js +8 -0
- package/examples/sheepisland/main.js +71 -0
- package/examples/sheepisland/params.js +25 -0
- package/examples/sheepisland/style/index.js +79 -0
- package/examples/sheepisland/style/models.js +59 -0
- package/examples/sheepisland/views.js +9 -0
- package/examples/styletest/GAMEMAP.md +135 -0
- package/examples/styletest/content/index.js +9 -0
- package/examples/styletest/content/items.js +8 -0
- package/examples/styletest/content/npcs.js +8 -0
- package/examples/styletest/content/places.js +5 -0
- package/examples/styletest/content/props.js +16 -0
- package/examples/styletest/content/templates.js +9 -0
- package/examples/styletest/content/vegetation.js +31 -0
- package/examples/styletest/look.js +11 -0
- package/examples/styletest/main.js +95 -0
- package/examples/styletest/models.js +87 -0
- package/examples/styletest/overrides.js +33 -0
- package/examples/styletest/panel.js +135 -0
- package/examples/styletest/params.js +32 -0
- package/examples/styletest/views.js +31 -0
- package/examples/world/DESIGN.md +5 -0
- package/examples/world/GAMEMAP.md +171 -0
- package/examples/world/content/actions.js +8 -0
- package/examples/world/content/audio.js +25 -0
- package/examples/world/content/bodies.js +12 -0
- package/examples/world/content/containers.js +4 -0
- package/examples/world/content/dialogues.js +33 -0
- package/examples/world/content/index.js +17 -0
- package/examples/world/content/items.js +10 -0
- package/examples/world/content/npcs.js +14 -0
- package/examples/world/content/pickups.js +11 -0
- package/examples/world/content/places.js +6 -0
- package/examples/world/content/props.js +12 -0
- package/examples/world/content/quests.js +15 -0
- package/examples/world/content/rules.js +23 -0
- package/examples/world/content/templates.js +5 -0
- package/examples/world/content/vegetation.js +32 -0
- package/examples/world/main.js +168 -0
- package/examples/world/models.js +28 -0
- package/index.d.ts +306 -0
- package/index.js +122 -0
- package/llms.txt +61 -0
- package/modules/ambience/Ambience.js +186 -0
- package/modules/camera/FirstPersonCamera.js +131 -0
- package/modules/camera/FixedCamera.js +162 -0
- package/modules/camera/FollowCamera.js +91 -0
- package/modules/camera/RtsCamera.js +132 -0
- package/modules/camera/common.js +182 -0
- package/modules/camera/index.js +11 -0
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +235 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +66 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +215 -0
- package/modules/characters/moveHelpers.js +29 -0
- package/modules/characters/movers/common.js +62 -0
- package/modules/characters/movers/rapier.js +74 -0
- package/modules/characters/movers/simple.js +43 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +150 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +113 -0
- package/modules/characters/pathJob.js +62 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +58 -0
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +274 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/explain.js +13 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +154 -0
- package/modules/content/loader.js +190 -0
- package/modules/content/models.js +69 -0
- package/modules/content/packs.js +69 -0
- package/modules/content/props.js +89 -0
- package/modules/content/rules.js +134 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +174 -0
- package/modules/entities/Entities.js +243 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +101 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +219 -0
- package/modules/gameplay/Interactions.js +253 -0
- package/modules/gameplay/Inventory.js +224 -0
- package/modules/gameplay/Quests.js +205 -0
- package/modules/gameplay/boxOps.js +60 -0
- package/modules/gameplay/dialogueBox.js +48 -0
- package/modules/gameplay/interactionPrompt.js +28 -0
- package/modules/gameplay/inventoryOps.js +137 -0
- package/modules/gameplay/pickups.js +115 -0
- package/modules/gameplay/questLog.js +54 -0
- package/modules/gameplay/questSave.js +71 -0
- package/modules/grid/Grid.js +184 -0
- package/modules/grid/Layer.js +142 -0
- package/modules/grid/index.js +236 -0
- package/modules/grid/ops.js +73 -0
- package/modules/grid/preview.js +85 -0
- package/modules/grid/tiles.js +79 -0
- package/modules/hlod/index.js +167 -0
- package/modules/hud/index.js +167 -0
- package/modules/hud/parts.js +80 -0
- package/modules/level/geometry.js +46 -0
- package/modules/level/heightfield.js +160 -0
- package/modules/level/index.js +233 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +227 -0
- package/modules/music/Music.js +294 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +156 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +137 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +77 -0
- package/modules/net/sync.js +114 -0
- package/modules/net/transports.js +118 -0
- package/modules/particles/Particles.js +179 -0
- package/modules/particles/effect.js +112 -0
- package/modules/particles/shaders.js +28 -0
- package/modules/photo/Photo.js +146 -0
- package/modules/rigid/RigidBodies.js +265 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +297 -0
- package/modules/settings/apply.js +21 -0
- package/modules/settings/index.js +3 -0
- package/modules/settings/sections.js +156 -0
- package/modules/settings/strings.js +53 -0
- package/modules/settings/view.js +65 -0
- package/modules/sky/Sky.js +259 -0
- package/modules/sky/calendar.js +80 -0
- package/modules/sky/cascades.js +125 -0
- package/modules/sky/clouds.js +79 -0
- package/modules/sky/domeLayers.js +33 -0
- package/modules/sky/environment.js +141 -0
- package/modules/sky/fog.js +139 -0
- package/modules/sky/frame.js +77 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +51 -0
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +74 -0
- package/modules/sky/skyModule.js +60 -0
- package/modules/terrain/ChunkManager.js +260 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +118 -0
- package/modules/terrain/lookGround.js +61 -0
- package/modules/terrain/mountTerrain.js +32 -0
- package/modules/terrain/terrainColorMap.js +41 -0
- package/modules/terrain/terrainDefaults.js +39 -0
- package/modules/terrain/terrainEdit.js +139 -0
- package/modules/terrain/terrainGen.js +155 -0
- package/modules/terrain/terrainIsland.js +131 -0
- package/modules/terrain/terrainMesh.js +92 -0
- package/modules/terrain/terrainShape.js +108 -0
- package/modules/terrain/terrainShapeMain.js +41 -0
- package/modules/terrain/terrainTexture.js +44 -0
- package/modules/timeline/Timeline.js +253 -0
- package/modules/timeline/Tween.js +114 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +90 -0
- package/modules/triggers/index.js +268 -0
- package/modules/vegetation/Vegetation.js +256 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +43 -0
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +160 -0
- package/modules/water/look.js +80 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +242 -0
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/weather/strings.js +15 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +71 -0
- package/modules/world/persist.js +107 -0
- package/modules/world/pos.js +20 -0
- package/modules/world/records.js +89 -0
- package/modules/world/sim.js +175 -0
- package/modules/world/simFar.js +82 -0
- package/modules/world/state.js +115 -0
- package/modules/world/thingSource.js +44 -0
- package/modules/world/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +240 -0
- package/render/detail.js +105 -0
- package/render/effects.js +144 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +84 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +18 -0
- package/render/lookSurface.js +161 -0
- package/render/materials.js +220 -0
- package/render/patches.js +252 -0
- package/render/postLook.js +86 -0
- package/render/surface.js +69 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1965 -0
- package/types/gameplay.d.ts +1822 -0
- package/types/generated/core/Audio.d.ts +200 -0
- package/types/generated/core/Batching.d.ts +47 -0
- package/types/generated/core/Budget.d.ts +90 -0
- package/types/generated/core/Commits.d.ts +31 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +89 -0
- package/types/generated/core/I18n.d.ts +30 -0
- package/types/generated/core/Input.d.ts +118 -0
- package/types/generated/core/Jobs.d.ts +41 -0
- package/types/generated/core/Ops.d.ts +203 -0
- package/types/generated/core/Random.d.ts +49 -0
- package/types/generated/core/Rays.d.ts +49 -0
- package/types/generated/core/Saves.d.ts +162 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/core/audioVoice.d.ts +47 -0
- package/types/generated/core/page.d.ts +18 -0
- package/types/generated/core/session.d.ts +48 -0
- package/types/generated/modules/ambience/Ambience.d.ts +48 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
- package/types/generated/modules/flow/index.d.ts +10 -0
- package/types/generated/modules/grid/Grid.d.ts +151 -0
- package/types/generated/modules/grid/Layer.d.ts +65 -0
- package/types/generated/modules/grid/index.d.ts +86 -0
- package/types/generated/modules/hlod/index.d.ts +11 -0
- package/types/generated/modules/hud/index.d.ts +10 -0
- package/types/generated/modules/lights/index.d.ts +13 -0
- package/types/generated/modules/music/Music.d.ts +111 -0
- package/types/generated/modules/net/Net.d.ts +34 -0
- package/types/generated/modules/net/index.d.ts +53 -0
- package/types/generated/modules/net/transports.d.ts +58 -0
- package/types/generated/modules/particles/Particles.d.ts +69 -0
- package/types/generated/modules/sky/Sky.d.ts +145 -0
- package/types/generated/modules/sky/skyModule.d.ts +10 -0
- package/types/generated/modules/timeline/Timeline.d.ts +51 -0
- package/types/generated/modules/water/Water.d.ts +29 -0
- package/types/generated/modules/weather/Weather.d.ts +62 -0
- package/types/generated/modules/world/World.d.ts +242 -0
- package/types/generated/modules/world/index.d.ts +15 -0
- package/types/generated/render/PostFX.d.ts +125 -0
- package/types/generated/render/materials.d.ts +100 -0
- package/types/generated/render/patches.d.ts +41 -0
- package/types/generated/ui/Focus.d.ts +11 -0
- package/types/generated/ui/LoadingScreen.d.ts +2 -0
- package/types/generated/ui/UI.d.ts +57 -0
- package/types/nav.d.ts +52 -0
- package/types/physics.d.ts +592 -0
- package/types/style.d.ts +638 -0
- package/types/worker.d.ts +11 -0
- package/types/world.d.ts +772 -0
- package/ui/Focus.js +51 -0
- package/ui/LoadingScreen.js +42 -0
- package/ui/Parts.js +199 -0
- package/ui/UI.js +167 -0
- package/ui/defaults.js +85 -0
- package/ui/theme.js +124 -0
- package/ui/touchPart.js +49 -0
package/core/Audio.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// Audio core: buses (master, music, sfx, ambience, ui + the game's own), sounds by name, ducking, and the condition table for rule lists.
|
|
2
|
+
// Sounds are the game's: createEngine({ audio: { sounds, ambience, music, footsteps, levels } }) or a content pack's audio table (contentPack,
|
|
3
|
+
// audioRules.js), merged into engine.audio.config. The engine ships none and plays nothing the game did not ask for: modules register built-in
|
|
4
|
+
// synths with { builtIn: true }, silent until audio.sounds names them. A sound src may be a file or a sound name from an asset pack.
|
|
5
|
+
// Usage: recipes/31-audio.md.
|
|
6
|
+
// Browsers only allow sound after the first click/keypress; this waits for it automatically.
|
|
7
|
+
|
|
8
|
+
/** @import { SynthFn, SoundDef, AudioCondition, AudioVolume } from '../types/core' */
|
|
9
|
+
import { codedError } from './errorHints.js';
|
|
10
|
+
import { missingText, warnOnce, checkOptions } from './validate.js';
|
|
11
|
+
import { SoundHandle, playSound, placeListener, synthNoise, synthTone, loadSound, playFile } from './audioVoice.js';
|
|
12
|
+
import { matchesWhen, volumeOf, checkRuleName, packAudio, applyDucks, audioInfo } from './audioRules.js';
|
|
13
|
+
const AUDIO_KEYS = ['levels', 'sounds', 'ambience', 'music', 'footsteps'];
|
|
14
|
+
const DEFAULT_LEVELS = { master: 0.8, music: 0.5, sfx: 0.8, ambience: 0.7, ui: 0.8 };
|
|
15
|
+
|
|
16
|
+
/** engine.audio: buses, sounds by name, ducking. Sfx play by name from the game's audio.sounds (file, variants or synth). */
|
|
17
|
+
export class Audio {
|
|
18
|
+
/** @internal */
|
|
19
|
+
constructor(engine, opts = {}) {
|
|
20
|
+
checkOptions('createEngine({ audio })', opts, AUDIO_KEYS);
|
|
21
|
+
const { levels = {}, sounds = {}, ambience = [], music = {}, footsteps = {} } = opts;
|
|
22
|
+
// a typo (trakcs) would just play nothing
|
|
23
|
+
checkOptions('createEngine({ audio: { music } })', music, ['tracks', 'rules', 'fade', 'duckDialogue', 'duckFade', 'hold', 'interval']);
|
|
24
|
+
/** @internal */ this.engine = engine;
|
|
25
|
+
/** The browser AudioContext (exists only after the first click) @type {any} */
|
|
26
|
+
this.ctx = null;
|
|
27
|
+
/** Volume per bus 0-1 ('master' is the total). Every key is a bus: levels: { voice: 1 } adds a 'voice' bus @type {Record<string, number>} */
|
|
28
|
+
this.levels = { ...DEFAULT_LEVELS, ...levels };
|
|
29
|
+
/**
|
|
30
|
+
* The game's sound config from createEngine({ audio }); sounds and footsteps also hold content packs' (copies: the game's object is never changed).
|
|
31
|
+
* Content packs' ambience / music rules go to ambience() / music(), not here
|
|
32
|
+
* @type {import('../types/core').AudioConfig}
|
|
33
|
+
*/
|
|
34
|
+
this.config = { sounds: { ...sounds }, ambience, music, footsteps: { ...footsteps } };
|
|
35
|
+
/** Bus input GainNodes by name (connect your own nodes here); empty until audio unlocks @type {Record<string, any>} */
|
|
36
|
+
this.buses = {};
|
|
37
|
+
/** The game's current mode for rule lists, e.g. 'combat' / 'explore' (condition `state` in music and ambience rules) @type {string | null} */
|
|
38
|
+
this.state = null;
|
|
39
|
+
/** @internal */ this.buffers = new Map();
|
|
40
|
+
/** @internal */ this.synths = new Map();
|
|
41
|
+
/** @internal */ this.conditions = new Map([['state', v => [].concat(v).includes(this.state)]]);
|
|
42
|
+
/** @internal name -> (engine) => number: values rule data compares ({ daylight: { gt: 0.15 } }) and data volumes add up */
|
|
43
|
+
this.measures = new Map();
|
|
44
|
+
// names defined in code: the same name in a content pack is an error (one name, one place)
|
|
45
|
+
/** @internal */ this._code = { sounds: new Set(Object.keys(sounds)), footsteps: new Set(Object.keys(footsteps)), tracks: new Set(Object.keys(music.tracks || {})) };
|
|
46
|
+
/** @internal content packs' audio: pack key -> { ambience, music } (ambience() / music() read it at install and follow it after) */
|
|
47
|
+
this.packs = new Map();
|
|
48
|
+
/** @internal */ this._packWatch = new Set();
|
|
49
|
+
/** @internal */ this._duckNodes = {};
|
|
50
|
+
/** @internal */ this._ducks = new Set();
|
|
51
|
+
/** @internal */ this._voices = new Map(); // name -> live voices (voice limit, info)
|
|
52
|
+
/** @internal */ this._last = new Map(); // name -> { at, variant } (cooldown, no-repeat)
|
|
53
|
+
/** @internal */ this._spatial = new Set(); // positional voices: the listener and followed objects update only while any exist
|
|
54
|
+
/** @internal */ this._readySent = false;
|
|
55
|
+
// Create or resume audio on the first click/keypress (a context created earlier is suspended and must be resumed inside a user gesture)
|
|
56
|
+
const stop = new AbortController(), signal = AbortSignal.any([stop.signal, engine.signal]); // remove after unlocking once, or when the engine is disposed
|
|
57
|
+
const unlock = () => { this._init(); this.ctx?.resume(); stop.abort(); };
|
|
58
|
+
addEventListener('pointerdown', unlock, { signal }); addEventListener('keydown', unlock, { signal });
|
|
59
|
+
}
|
|
60
|
+
/** @internal Close the audio context (engine.dispose calls it): playing sounds and nodes modules attached stop together */
|
|
61
|
+
dispose() { this.ctx?.close(); this.ctx = null; }
|
|
62
|
+
|
|
63
|
+
/** @internal */
|
|
64
|
+
_init() {
|
|
65
|
+
if (this.ctx || this.engine.disposed) return;
|
|
66
|
+
const AC = window.AudioContext || window.webkitAudioContext;
|
|
67
|
+
if (!AC) return;
|
|
68
|
+
const ctx = this.ctx = new AC();
|
|
69
|
+
/** The master GainNode (every bus ends here) @type {any} */
|
|
70
|
+
this.master = ctx.createGain(); this.master.gain.value = this.levels.master; this.master.connect(ctx.destination);
|
|
71
|
+
for (const name of Object.keys(this.levels)) if (name !== 'master') this._makeBus(name);
|
|
72
|
+
this._applyDucks(0);
|
|
73
|
+
const len = ctx.sampleRate * 2, buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0);
|
|
74
|
+
for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1; // presentation
|
|
75
|
+
/** 2 s of white noise, reused by synthesized sounds @type {any} */
|
|
76
|
+
this.noise = buf;
|
|
77
|
+
const ready = () => { if (ctx.state === 'running' && !this._readySent) { this._readySent = true; this.engine.events.emit('audio:ready'); } };
|
|
78
|
+
ctx.addEventListener('statechange', ready); ready();
|
|
79
|
+
}
|
|
80
|
+
/** @internal a bus is two gains: its level (what setVolume sets) then its duck (what duck() lowers), so the two never fight */
|
|
81
|
+
_makeBus(name) {
|
|
82
|
+
const ctx = this.ctx, g = ctx.createGain(), d = ctx.createGain();
|
|
83
|
+
g.gain.value = this.levels[name]; g.connect(d).connect(this.master);
|
|
84
|
+
this.buses[name] = g; this._duckNodes[name] = d;
|
|
85
|
+
}
|
|
86
|
+
/** Is audio usable (the player has clicked/pressed a key)? @returns {boolean} */
|
|
87
|
+
get running() { return this.ctx?.state === 'running'; }
|
|
88
|
+
/** @internal */
|
|
89
|
+
_warn(msg) { warnOnce(msg); }
|
|
90
|
+
/** @internal */
|
|
91
|
+
_bus(name) {
|
|
92
|
+
if (name in this.levels && name !== 'master') return this.buses[name];
|
|
93
|
+
throw codedError('unknown-name', missingText('bus', name, Object.keys(this.levels).filter(n => n !== 'master'))
|
|
94
|
+
+ '. Add a bus with createEngine({ audio: { levels: { name: 1 } } }) or engine.audio.addBus(name)');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Add a bus of your own (routed to master). It gets a settings slider like the others (label key settings.vol.<name>)
|
|
99
|
+
* @param {string} name
|
|
100
|
+
* @param {number} [level]
|
|
101
|
+
* @returns {this}
|
|
102
|
+
* @example engine.audio.addBus('voice', 1); engine.audio.sfx('line-01', { bus: 'voice' });
|
|
103
|
+
*/
|
|
104
|
+
addBus(name, level = 1) {
|
|
105
|
+
if (!(name in this.levels)) { this.levels[name] = level; if (this.ctx) this._makeBus(name); }
|
|
106
|
+
return this;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Set a bus volume 0-1 ('master' for the total)
|
|
110
|
+
* @param {string} bus
|
|
111
|
+
* @param {number} v
|
|
112
|
+
* @returns {void}
|
|
113
|
+
* @example engine.audio.setVolume('music', 0.3);
|
|
114
|
+
*/
|
|
115
|
+
setVolume(bus, v) {
|
|
116
|
+
if (bus !== 'master') this._bus(bus);
|
|
117
|
+
this.levels[bus] = v; if (!this.ctx) return;
|
|
118
|
+
(bus === 'master' ? this.master : this.buses[bus]).gain.value = v;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Lower buses until the handle is removed (dialogue, pause menu, a cutscene). Several ducks stack (their levels multiply).
|
|
123
|
+
* @param {Record<string, number>} levels bus -> multiplier 0-1
|
|
124
|
+
* @param {{ fade?: number }} [opts] fade seconds both ways (0.3)
|
|
125
|
+
* @returns {{ remove(fade?: number): void }}
|
|
126
|
+
* @example const d = engine.audio.duck({ music: 0.3, ambience: 0.5 }); engine.events.once('dialogue:end', () => d.remove());
|
|
127
|
+
*/
|
|
128
|
+
duck(levels, opts = {}) {
|
|
129
|
+
checkOptions('audio.duck()', opts, ['fade']);
|
|
130
|
+
for (const b of Object.keys(levels)) if (b === 'master' || !(b in this.levels)) this._bus(b);
|
|
131
|
+
const { fade = 0.3 } = opts, entry = { levels };
|
|
132
|
+
this._ducks.add(entry); this._applyDucks(fade);
|
|
133
|
+
return { remove: (f = fade) => { if (this._ducks.delete(entry)) this._applyDucks(f); } };
|
|
134
|
+
}
|
|
135
|
+
/** @internal */
|
|
136
|
+
_applyDucks(fade) { applyDucks(this, fade); }
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Register a synthesized sound: synthFn(audio, params, out) connects its nodes to `out` and returns its length in seconds
|
|
140
|
+
* (or { stop(time) } for a loop). Plays for sounds entries that name it ('synth' or { synth: name }); a name with no sounds entry
|
|
141
|
+
* plays it too unless builtIn (engine modules pass builtIn: true so their synths stay silent until the game asks).
|
|
142
|
+
* @param {string} name
|
|
143
|
+
* @param {SynthFn} synthFn
|
|
144
|
+
* @param {{ builtIn?: boolean, bus?: string, params?: Record<string, any> }} [opts] bus: default bus ('sfx'); params: default params
|
|
145
|
+
* @returns {this}
|
|
146
|
+
* @example engine.audio.register('ding', (a, p, out) => { a.tone({ freq: 880 * p.pitch, dur: 0.2, out }); return 0.2; });
|
|
147
|
+
*/
|
|
148
|
+
register(name, synthFn, opts = {}) {
|
|
149
|
+
checkOptions('audio.register()', opts, ['builtIn', 'bus', 'params']);
|
|
150
|
+
this.synths.set(name, { fn: synthFn, builtIn: !!opts.builtIn, bus: opts.bus, params: opts.params || {} }); return this;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Add a condition key for music / ambience rule lists: `when: { [name]: value }` calls test(value, engine). Modules add theirs
|
|
155
|
+
* (sky: time, weather: weather, triggers: zone); the engine has `state` (engine.audio.state).
|
|
156
|
+
* @param {string} name
|
|
157
|
+
* @param {(value: any, e: any) => boolean} test
|
|
158
|
+
* @returns {{ remove(): void }}
|
|
159
|
+
* @example engine.audio.condition('inside', v => engine.vars.flag('indoors') === v);
|
|
160
|
+
*/
|
|
161
|
+
condition(name, test) { checkRuleName(this, name, false); this.conditions.set(name, test); return { remove: () => this.conditions.delete(name) }; }
|
|
162
|
+
/**
|
|
163
|
+
* Add a measure: a number rule data compares (`when: { daylight: { gt: 0.15 } }`; gt / gte / lt / lte) and adds up (`volume: { add: { wind: 0.08 } }`).
|
|
164
|
+
* sky adds daylight, weather rain / snow / wind, ambience nearWater / altitude. A name is a condition or a measure, not both
|
|
165
|
+
* @param {string} name
|
|
166
|
+
* @param {(e: any) => number} fn
|
|
167
|
+
* @returns {{ remove(): void }}
|
|
168
|
+
* @example engine.audio.measure('danger', e => e.vars.counter('alarm') / 10); // data: when: { danger: { gt: 0.5 } }
|
|
169
|
+
*/
|
|
170
|
+
measure(name, fn) { checkRuleName(this, name, true); this.measures.set(name, fn); return { remove: () => this.measures.delete(name) }; }
|
|
171
|
+
/**
|
|
172
|
+
* The current value of a measure (debug, tests); undefined when none is registered under that name
|
|
173
|
+
* @param {string} name
|
|
174
|
+
* @returns {number | undefined}
|
|
175
|
+
*/
|
|
176
|
+
value(name) { return this.measures.get(name)?.(this.engine); }
|
|
177
|
+
/**
|
|
178
|
+
* Does a rule's `when` hold now? An object needs every key to hold (condition keys, or measure comparisons); a function gets
|
|
179
|
+
* (engine, ...extra); missing = always.
|
|
180
|
+
* @param {AudioCondition | undefined} when
|
|
181
|
+
* @param {...any} extra
|
|
182
|
+
* @returns {boolean}
|
|
183
|
+
* @example engine.audio.matches({ time: 'night', zone: 'forest', rain: { lt: 0.2 } });
|
|
184
|
+
*/
|
|
185
|
+
matches(when, ...extra) { return matchesWhen(this, when, extra); }
|
|
186
|
+
/**
|
|
187
|
+
* A rule's volume now: a number, a function (engine, ...extra), or data { base, add: { measure: factor }, min, max }; missing = 1
|
|
188
|
+
* @param {AudioVolume | undefined} volume
|
|
189
|
+
* @param {...any} extra
|
|
190
|
+
* @returns {number}
|
|
191
|
+
* @example engine.audio.volumeOf({ base: 0, add: { rain: 0.22 } }); // 0.22 in full rain
|
|
192
|
+
*/
|
|
193
|
+
volumeOf(volume, ...extra) { return volumeOf(this, volume, extra); }
|
|
194
|
+
/**
|
|
195
|
+
* @internal content.load hands each pack's audio table here (audioRules.js packAudio): sounds / footsteps merge into config, rules go to
|
|
196
|
+
* ambience() / music() through onPack; a pack loaded again under the same key replaces its rules
|
|
197
|
+
* @param {any} key 'pack:<name>', or the pack's data object for an unnamed pack (loading the same object again replaces its rules)
|
|
198
|
+
* @param {string} from 'pack "forest"' for messages
|
|
199
|
+
* @param {any} data
|
|
200
|
+
*/
|
|
201
|
+
contentPack(key, from, data) {
|
|
202
|
+
const p = packAudio(this, data, from);
|
|
203
|
+
Object.assign(this.config.sounds, p.sounds); Object.assign(this.config.footsteps, p.footsteps);
|
|
204
|
+
const pack = { from, ambience: p.ambience, music: p.music };
|
|
205
|
+
this.packs.set(key, pack);
|
|
206
|
+
for (const fn of this._packWatch) fn(key, pack);
|
|
207
|
+
}
|
|
208
|
+
/** @internal ambience() / music() follow content packs' rules: fn(key, pack) per pack, now for each loaded one and later for new ones */
|
|
209
|
+
onPack(fn) {
|
|
210
|
+
for (const [k, p] of this.packs) fn(k, p);
|
|
211
|
+
this._packWatch.add(fn); return { remove: () => this._packWatch.delete(fn) };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Play a sound by name from audio.sounds (file, variants, or a synth). Returns a SoundHandle (stop, fade, setPosition), or null when it is
|
|
216
|
+
* silent: not configured, audio still locked, or held back by the sound's cooldown. Over its `voices` limit the oldest voice stops.
|
|
217
|
+
* @param {string} name
|
|
218
|
+
* @param {{ volume?: number, pitch?: number, at?: any, bus?: string, loop?: boolean, params?: Record<string, any>, fadeIn?: number }} [opts]
|
|
219
|
+
* at: a position or an Object3D to follow (3D sound); params: extra synth params
|
|
220
|
+
* @returns {SoundHandle | null}
|
|
221
|
+
* @example engine.audio.sfx('hit', { at: enemy.root, volume: 0.8 });
|
|
222
|
+
*/
|
|
223
|
+
sfx(name, opts = {}) { return playSound(this, name, opts); }
|
|
224
|
+
/** @internal per frame (loop.js): positional voices follow their objects and the listener follows the camera; nothing to do without them */
|
|
225
|
+
_tick() {
|
|
226
|
+
if (!this._spatial.size || !this.ctx) return;
|
|
227
|
+
placeListener(this.ctx, this.engine.camera);
|
|
228
|
+
for (const v of this._spatial) { if (!v.playing) this._spatial.delete(v); else if (v.follow) v.setPosition(v.follow); }
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* What is playing (for describe and tests): bus levels, the duck multiplier per bus, live voices per sound name
|
|
232
|
+
* @returns {{ running: boolean, state: string | null, levels: Record<string, number>, ducks: Record<string, number>, voices: Record<string, number> }}
|
|
233
|
+
*/
|
|
234
|
+
get info() { return audioInfo(this); }
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Synth building block: a burst of filtered noise (footsteps, shutter, rain, thunder). dur seconds, freq Hz, vol 0-1; out: the node to
|
|
238
|
+
* connect to (a synth's `out`), else the named bus
|
|
239
|
+
* @param {{ dur?: number, type?: string, freq?: number, vol?: number, bus?: string, out?: any, rate?: number, delay?: number }} [opts]
|
|
240
|
+
* @returns {void}
|
|
241
|
+
*/
|
|
242
|
+
noiseBurst(opts = {}) { synthNoise(this, opts); }
|
|
243
|
+
/**
|
|
244
|
+
* Synth building block: a short tone (bird call, notification). freq/to Hz, dur seconds, pan -1..1; out as in noiseBurst
|
|
245
|
+
* @param {{ freq?: number, to?: number | null, dur?: number, vol?: number, type?: string, bus?: string, out?: any, delay?: number, pan?: number }} [opts]
|
|
246
|
+
* @returns {void}
|
|
247
|
+
* @example engine.audio.tone({ freq: 660, to: 880, dur: 0.15, bus: 'ui' });
|
|
248
|
+
*/
|
|
249
|
+
tone(opts = {}) { synthTone(this, opts); }
|
|
250
|
+
|
|
251
|
+
// ---------- audio files ----------
|
|
252
|
+
/**
|
|
253
|
+
* Download and decode an audio file (cached). A sound name registered in an asset pack (manifest sounds) loads that file as an
|
|
254
|
+
* engine.loading task, so sounds entries and music tracks may name assets instead of paths
|
|
255
|
+
* @param {string} url a file path or an asset pack sound name
|
|
256
|
+
* @returns {Promise<any>}
|
|
257
|
+
*/
|
|
258
|
+
load(url) { return loadSound(this, url); }
|
|
259
|
+
/**
|
|
260
|
+
* Play an audio file by path (no sounds entry needed); resolves to a SoundHandle once the file is decoded
|
|
261
|
+
* @param {string} url
|
|
262
|
+
* @param {{ bus?: string, volume?: number, loop?: boolean, fadeIn?: number, pitch?: number, at?: any }} [opts]
|
|
263
|
+
* @returns {Promise<SoundHandle | null>} null only without Web Audio; called before the first click it still resolves and the sound starts once audio unlocks
|
|
264
|
+
* @example const h = await engine.audio.play('/sfx/door.ogg', { bus: 'ui' }); h.stop(0.5);
|
|
265
|
+
*/
|
|
266
|
+
play(url, opts = {}) { return playFile(this, url, opts); }
|
|
267
|
+
}
|
package/core/Baked.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Code-generated model <-> GLB file (shared by the auto-cache and npm run bake).
|
|
2
|
+
// toGLB(object or geometry) -> ArrayBuffer: uses three's GLTFExporter; names and userData (marker params) are kept as-is
|
|
3
|
+
// fromGLTF(gltf) -> object or geometry: restores the shadow flags, visibility and materials recorded at export
|
|
4
|
+
// What glTF cannot record goes in userData (glTF extras):
|
|
5
|
+
// object userData.threedog = { cast, receive, hidden }; material userData.threedogMat = material JSON (no textures).
|
|
6
|
+
// A material with userData.purpose (made by makeMaterial) is rebuilt by purpose, so style-pack texture swaps and shader injections (wind etc.) still apply;
|
|
7
|
+
// otherwise it is rebuilt as-is from the recorded type and params (a MeshLambertMaterial stays Lambert, not glTF's default Standard).
|
|
8
|
+
import * as THREE from 'three';
|
|
9
|
+
import { makeMaterial } from '../render/materials.js';
|
|
10
|
+
|
|
11
|
+
// When rebuilding by purpose, keep these per-material settings from the recorded params (look params such as roughness and shininess still come from the style pack)
|
|
12
|
+
const KEEP_KEYS = ['flatShading', 'emissive', 'emissiveIntensity', 'transparent', 'opacity', 'side', 'alphaTest', 'depthWrite', 'wireframe'];
|
|
13
|
+
const TEX_KEYS = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap', 'bumpMap', 'lightMap', 'specularMap', 'envMap', 'gradientMap', 'displacementMap'];
|
|
14
|
+
|
|
15
|
+
/** Object (or geometry) -> GLB. Marks are written on a copy; the original is untouched. */
|
|
16
|
+
export async function toGLB(value, engine) {
|
|
17
|
+
const { GLTFExporter } = await import('three/addons/exporters/GLTFExporter.js');
|
|
18
|
+
const geo = value.isBufferGeometry;
|
|
19
|
+
const root = geo ? new THREE.Mesh(value, makeMaterial('default', { vertexColors: !!value.attributes.color }, engine)) : value.clone();
|
|
20
|
+
if (geo) root.userData.threedogGeometry = true;
|
|
21
|
+
const mats = new Map();
|
|
22
|
+
// Export with glTF's standard material (color, textures, vertex colors); the original type and params go in userData.threedogMat and are rebuilt as-is on read-back
|
|
23
|
+
const tag = m => {
|
|
24
|
+
if (!mats.has(m)) {
|
|
25
|
+
const j = m.toJSON();
|
|
26
|
+
for (const k of ['textures', 'images', 'uuid', 'metadata', 'userData', ...TEX_KEYS]) delete j[k];
|
|
27
|
+
const c = new THREE.MaterialLoader().parse({ type: 'MeshStandardMaterial', name: m.name, color: m.color?.getHex() ?? 0xffffff, vertexColors: m.vertexColors,
|
|
28
|
+
transparent: m.transparent, opacity: m.opacity, side: m.side, roughness: 1, metalness: 0 });
|
|
29
|
+
for (const k of TEX_KEYS) if (m[k] && k in c) c[k] = m[k];
|
|
30
|
+
c.userData = { ...m.userData, threedogMat: j }; mats.set(m, c);
|
|
31
|
+
}
|
|
32
|
+
return mats.get(m);
|
|
33
|
+
};
|
|
34
|
+
root.traverse(o => {
|
|
35
|
+
o.userData = { ...o.userData, threedog: { cast: o.castShadow, receive: o.receiveShadow, hidden: !o.visible } };
|
|
36
|
+
if (o.material) o.material = Array.isArray(o.material) ? o.material.map(tag) : tag(o.material);
|
|
37
|
+
});
|
|
38
|
+
return new GLTFExporter().parseAsync(root, { binary: true, onlyVisible: false });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The part of a GLTFLoader result that toGLB exported: restores shadow flags, visibility and materials in place (other glTF files are unaffected). Returns the gltf. */
|
|
42
|
+
export function restoreBaked(gltf, engine) {
|
|
43
|
+
const mats = new Map();
|
|
44
|
+
const rebuild = m => {
|
|
45
|
+
const spec = m.userData.threedogMat; if (!spec) return m;
|
|
46
|
+
if (!mats.has(m)) {
|
|
47
|
+
const { purpose } = m.userData;
|
|
48
|
+
const keep = {};
|
|
49
|
+
for (const k of KEEP_KEYS) if (spec[k] !== undefined) keep[k] = spec[k];
|
|
50
|
+
const out = purpose ? makeMaterial(purpose, { color: m.color, vertexColors: m.vertexColors, ...keep }, engine) : new THREE.MaterialLoader().parse(spec);
|
|
51
|
+
for (const k of TEX_KEYS) if (m[k] && k in out) out[k] = m[k];
|
|
52
|
+
out.name = m.name;
|
|
53
|
+
mats.set(m, out);
|
|
54
|
+
}
|
|
55
|
+
return mats.get(m);
|
|
56
|
+
};
|
|
57
|
+
gltf.scene.traverse(o => {
|
|
58
|
+
const t = o.userData.threedog;
|
|
59
|
+
if (!t) return;
|
|
60
|
+
o.castShadow = t.cast; o.receiveShadow = t.receive; o.visible = !t.hidden; delete o.userData.threedog;
|
|
61
|
+
if (o.material) o.material = Array.isArray(o.material) ? o.material.map(rebuild) : rebuild(o.material);
|
|
62
|
+
});
|
|
63
|
+
return gltf;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A GLTFLoader result (already restoreBaked) -> the object that was exported (a geometry if toGLB was given one). */
|
|
67
|
+
export function fromGLTF(gltf) {
|
|
68
|
+
const kids = gltf.scene.children, root = kids.length === 1 ? kids[0] : gltf.scene;
|
|
69
|
+
if (root.userData.threedogGeometry) { let g = null; root.traverse(o => { if (!g && o.isMesh) g = o.geometry; }); return g; }
|
|
70
|
+
root.removeFromParent();
|
|
71
|
+
return root;
|
|
72
|
+
}
|
package/core/Batching.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// Automatic batching, engine.batching: the same static model placed many times is drawn as one THREE.InstancedMesh per (cell, geometry, material),
|
|
2
|
+
// with no work from the game. It watches what is added directly to the scene (engine.add, world.present views, stream builds, grid items, props, rigid
|
|
3
|
+
// meshes...), so every source of placed models goes through it without knowing about it.
|
|
4
|
+
// Rule: once at least minCount meshes with the same geometry, material and shadow flags sit in one cell (cell meters, default engine.stream.cellSize),
|
|
5
|
+
// they become instances of one InstancedMesh; below that they stay plain meshes. A batch dissolves when it drops under half of minCount.
|
|
6
|
+
// The placed object stays in the scene as it was (its userData, record, colliders, interactions are untouched): only its meshes are hidden and marked
|
|
7
|
+
// moved to layer 31 (BATCH_LAYER: not drawn, not in shadows; visible stays the game's). engine.raycast / pick / photo still hit the original and
|
|
8
|
+
// return it, never an instance index (engine.rays tests layer 31 too). Your own THREE.Raycaster: batching.item(hit.object, hit.instanceId).
|
|
9
|
+
// Moving / hiding / removing the object updates its instance next frame (checked each frame on the object's own transform); recolor with tint().
|
|
10
|
+
// Never batched: skinned / instanced / morphing meshes, objects with animations, multi-material, transparent, ShaderMaterial, custom renderOrder /
|
|
11
|
+
// layers / onBeforeRender, meshes with children, anything hlod registered (userData.hlod), and anything marked userData.batch = false (itself or a parent).
|
|
12
|
+
// Safety net: a batched object whose meshes are changed afterwards (material swapped, shown, re-parented, a child part animated) goes back to plain meshes
|
|
13
|
+
// and its geometry is not batched again (dev warns once: mark such models userData.batch = false).
|
|
14
|
+
// Ownership with hlod: batching owns repeated things that are near enough to be built (props, views, stream entries); hlod owns the level geometry it was
|
|
15
|
+
// given and swaps it for merged proxies far away. A mesh belongs to whichever took it first, so they never fight over visibility.
|
|
16
|
+
// createEngine({ batching: false }) turns it off (nothing is watched, zero cost); engine.batching.enabled = false at runtime dissolves every batch.
|
|
17
|
+
/** @import { BatchingOptions, BatchingStats, BatchInfo } from '../types/core' */
|
|
18
|
+
import * as THREE from 'three';
|
|
19
|
+
import { warnOnce } from './validate.js';
|
|
20
|
+
import { BATCH_LAYER, build, join, leave, dissolve, color, localTint, bounds, snap, same, stored, under } from './batchGroups.js';
|
|
21
|
+
|
|
22
|
+
const OPTS = ['minCount', 'cell'];
|
|
23
|
+
const STRINGS = {
|
|
24
|
+
evicted: '[batching] a batched copy of "{name}" changed after batching ({why}); it is drawn on its own from now on. Mark models that animate parts or swap materials with userData.batch = false',
|
|
25
|
+
opts: 'createEngine({ batching }) takes false or { minCount, cell }; unknown key "{key}"',
|
|
26
|
+
};
|
|
27
|
+
const PROTO_BEFORE = THREE.Object3D.prototype.onBeforeRender;
|
|
28
|
+
const HIDDEN = (1 << BATCH_LAYER) >>> 0; // three keeps layer masks unsigned
|
|
29
|
+
|
|
30
|
+
/** engine.batching: draws repeated static models as InstancedMesh batches (see the top of core/Batching.js). */
|
|
31
|
+
export class Batching {
|
|
32
|
+
/** @internal @param {any} engine @param {BatchingOptions | false} [opts] */
|
|
33
|
+
constructor(engine, opts = {}) {
|
|
34
|
+
for (const k of Object.keys(opts || {})) if (!OPTS.includes(k)) throw new Error(STRINGS.opts.replace('{key}', k));
|
|
35
|
+
/** @internal */ this.engine = engine;
|
|
36
|
+
/** Same model at least this many times in one cell becomes a batch (default 8) @type {number} */
|
|
37
|
+
this.minCount = (opts && opts.minCount) || 8;
|
|
38
|
+
/** @internal */ this._cell = (opts && opts.cell) || null;
|
|
39
|
+
/** @internal key -> group */ this.groups = new Map();
|
|
40
|
+
/** @internal root -> info */ this.roots = new Map();
|
|
41
|
+
/** @internal roots with at least one batched mesh (checked every frame) */ this.live = new Set();
|
|
42
|
+
/** @internal */ this.list = [];
|
|
43
|
+
/** @internal */ this.cursor = 0;
|
|
44
|
+
/** @internal roots added since the last update */ this.incoming = new Set();
|
|
45
|
+
/** @internal mesh -> its original material while a local tint clone is on it */ this.orig = new Map();
|
|
46
|
+
/** @internal mesh -> tint color */ this.tints = new WeakMap();
|
|
47
|
+
/** @internal geometries evicted once (never batched again) */ this.banned = new WeakSet();
|
|
48
|
+
/** @internal batch InstancedMesh -> group */ this.byMesh = new WeakMap();
|
|
49
|
+
/** Geometries and materials a live batch draws (engine.remove does not dispose these) @type {Map<any, number>} */ this.held = new Map();
|
|
50
|
+
/** Parent of every batch InstancedMesh (in the scene) @type {THREE.Group} */
|
|
51
|
+
this.root = new THREE.Group();
|
|
52
|
+
this.root.name = 'batching'; this.root.matrixAutoUpdate = false; this.root.userData.batch = false;
|
|
53
|
+
/** @internal */ this._on = false;
|
|
54
|
+
/** @internal */ this._add = ev => { if (ev.child !== this.root) this.incoming.add(ev.child); };
|
|
55
|
+
/** @internal */ this._rem = ev => { this.incoming.delete(ev.child); this._untrack(ev.child); };
|
|
56
|
+
if (opts !== false) this.enabled = true;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Global switch: false dissolves every batch and stops watching; true starts again (scans what is already in the scene) @type {boolean} */
|
|
60
|
+
get enabled() { return this._on; }
|
|
61
|
+
set enabled(on) {
|
|
62
|
+
if (on === this._on) return;
|
|
63
|
+
const s = this.engine.scene;
|
|
64
|
+
this._on = on;
|
|
65
|
+
if (on) {
|
|
66
|
+
s.addEventListener('childadded', this._add); s.addEventListener('childremoved', this._rem);
|
|
67
|
+
s.add(this.root);
|
|
68
|
+
for (const c of s.children) if (c !== this.root) this.incoming.add(c);
|
|
69
|
+
} else {
|
|
70
|
+
s.removeEventListener('childadded', this._add); s.removeEventListener('childremoved', this._rem);
|
|
71
|
+
for (const r of [...this.roots.keys()]) this._untrack(r);
|
|
72
|
+
this.incoming.clear(); this.root.removeFromParent();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Cell edge in meters (default engine.stream.cellSize) @type {number} */
|
|
76
|
+
get cell() { return this._cell ?? this.engine.stream.cellSize; }
|
|
77
|
+
set cell(v) { this._cell = v; this._rescan(); }
|
|
78
|
+
|
|
79
|
+
/** Every batch: { mesh: InstancedMesh, cell, count, items } (items[i] is the placed object drawn by instance i) @returns {BatchInfo[]} */
|
|
80
|
+
get batches() {
|
|
81
|
+
const out = [];
|
|
82
|
+
for (const g of this.groups.values()) if (g.mesh) out.push({ mesh: g.mesh, cell: g.cell, count: g.items.length, items: g.items.map(e => e.info.root) });
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
/** batches: InstancedMesh count, instances: meshes drawn through them, saved: draw calls saved per pass (instances - batches) @returns {BatchingStats} */
|
|
86
|
+
get stats() {
|
|
87
|
+
let batches = 0, instances = 0;
|
|
88
|
+
for (const g of this.groups.values()) if (g.mesh) { batches++; instances += g.items.length; }
|
|
89
|
+
return { batches, instances, saved: instances - batches };
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Where an object is drawn: [{ mesh, index }] for each of its meshes that is batched ([] when drawn on its own).
|
|
93
|
+
* @param {THREE.Object3D} obj placed object (or one of its meshes)
|
|
94
|
+
* @returns {{ mesh: THREE.InstancedMesh, index: number }[]}
|
|
95
|
+
*/
|
|
96
|
+
of(obj) {
|
|
97
|
+
const info = this._infoOf(obj), out = [];
|
|
98
|
+
if (info) for (const e of info.entries) if (e.slot >= 0 && (obj === info.root || e.mesh === obj)) out.push({ mesh: e.group.mesh, index: e.slot });
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The placed object drawn by instance `index` of a batch mesh (for a three.js Raycaster you run yourself; engine.raycast already returns the original).
|
|
103
|
+
* @param {THREE.Object3D} mesh batch InstancedMesh
|
|
104
|
+
* @param {number} index instanceId
|
|
105
|
+
* @returns {THREE.Object3D | null}
|
|
106
|
+
*/
|
|
107
|
+
item(mesh, index) { return this.byMesh.get(mesh)?.items[index]?.info.root ?? null; }
|
|
108
|
+
/**
|
|
109
|
+
* Recolor one placed object: its color is multiplied by `color` (instance color when batched, a cloned material otherwise); null restores it.
|
|
110
|
+
* @param {THREE.Object3D} obj
|
|
111
|
+
* @param {THREE.ColorRepresentation | null} c
|
|
112
|
+
* @example engine.batching.tint(engine.world.view('crate_3'), 0xff8080)
|
|
113
|
+
*/
|
|
114
|
+
tint(obj, c) {
|
|
115
|
+
obj.traverse(m => {
|
|
116
|
+
if (!m.isMesh) return;
|
|
117
|
+
if (c == null) this.tints.delete(m); else this.tints.set(m, new THREE.Color(c));
|
|
118
|
+
const e = this._entryOf(m);
|
|
119
|
+
if (e && e.slot >= 0) color(this, e); else localTint(this, m);
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/** Re-check one object now (after you changed its parts by hand); normally automatic @param {THREE.Object3D} obj */
|
|
123
|
+
refresh(obj) { const info = this._infoOf(obj); if (info) { this._detach(info); this._untrack(info.root); } if (obj.parent === this.engine.scene) this.incoming.add(obj); }
|
|
124
|
+
|
|
125
|
+
/** @internal Called by the engine each frame after frame hooks / stream / jobs, before rendering */
|
|
126
|
+
update() {
|
|
127
|
+
if (!this._on) return;
|
|
128
|
+
if (this.incoming.size) { for (const r of this.incoming) if (r.parent === this.engine.scene) this._track(r); this.incoming.clear(); }
|
|
129
|
+
for (const info of this.live) this._check(info);
|
|
130
|
+
// round robin: look for parts changed behind our back (bounded per frame)
|
|
131
|
+
const L = this.list, n = Math.min(L.length, 256);
|
|
132
|
+
for (let i = 0; i < n; i++) { if (this.cursor >= L.length) this.cursor = 0; this._verify(L[this.cursor++]); }
|
|
133
|
+
for (const g of this.groups.values()) if (g.dirty) { g.dirty = false; bounds(g); }
|
|
134
|
+
}
|
|
135
|
+
/** @internal */
|
|
136
|
+
dispose() { this.enabled = false; this.groups.clear(); }
|
|
137
|
+
|
|
138
|
+
// ---------- tracking ----------
|
|
139
|
+
/** @internal */
|
|
140
|
+
_track(root) {
|
|
141
|
+
if (this.roots.has(root) || root.userData.batch === false || root.animations?.length) return;
|
|
142
|
+
const meshes = [];
|
|
143
|
+
let ok = true;
|
|
144
|
+
const walk = (o, top) => {
|
|
145
|
+
if (!ok) return;
|
|
146
|
+
if (o.isSkinnedMesh || o.isInstancedMesh || o.isBatchedMesh) { ok = false; return; }
|
|
147
|
+
const u = o.userData;
|
|
148
|
+
if (u.batched) { o.layers.set(0); delete u.batched; } // a clone of a batched mesh: draw it again
|
|
149
|
+
if (!top && (u.batch === false || !o.visible)) return; // a hidden root is tracked anyway (it joins when shown)
|
|
150
|
+
if (o.isMesh && this._eligible(o)) meshes.push(o);
|
|
151
|
+
for (const c of o.children) walk(c, false);
|
|
152
|
+
};
|
|
153
|
+
walk(root, true);
|
|
154
|
+
if (!ok || !meshes.length) return;
|
|
155
|
+
const info = { root, entries: [], snap: [], cell: null, shown: false, idx: this.list.length };
|
|
156
|
+
for (const mesh of meshes) info.entries.push({ mesh, info, group: null, slot: -1 });
|
|
157
|
+
this.roots.set(root, info); this.list.push(info);
|
|
158
|
+
snap(root, info.snap);
|
|
159
|
+
if (root.visible) this._attach(info);
|
|
160
|
+
}
|
|
161
|
+
/** @internal */
|
|
162
|
+
_eligible(m) {
|
|
163
|
+
const mat = this.orig.get(m) ?? m.material;
|
|
164
|
+
return !m.children.length && !Array.isArray(mat) && mat && !mat.transparent && !mat.isShaderMaterial && m.geometry?.attributes.position
|
|
165
|
+
&& !m.morphTargetInfluences && !Object.keys(m.geometry.morphAttributes).length && !m.userData.hlod && !this.banned.has(m.geometry)
|
|
166
|
+
&& m.renderOrder === 0 && m.layers.mask === 1 && m.frustumCulled && m.onBeforeRender === PROTO_BEFORE;
|
|
167
|
+
}
|
|
168
|
+
/** @internal */
|
|
169
|
+
_untrack(root) {
|
|
170
|
+
const info = this.roots.get(root); if (!info) return;
|
|
171
|
+
this._detach(info);
|
|
172
|
+
this.roots.delete(root);
|
|
173
|
+
const last = this.list.pop(); if (last !== info) { this.list[info.idx] = last; last.idx = info.idx; }
|
|
174
|
+
}
|
|
175
|
+
/** @internal */
|
|
176
|
+
_infoOf(obj) { for (let o = obj; o; o = o.parent) { const i = this.roots.get(o); if (i) return i; } return null; }
|
|
177
|
+
/** @internal */
|
|
178
|
+
_entryOf(m) { return this._infoOf(m)?.entries.find(e => e.mesh === m) ?? null; }
|
|
179
|
+
/** @internal */
|
|
180
|
+
_rescan() { if (!this._on) return; this.enabled = false; this.enabled = true; }
|
|
181
|
+
|
|
182
|
+
/** @internal put a root's meshes into the groups of its cell */
|
|
183
|
+
_attach(info) {
|
|
184
|
+
const p = info.root.position, cs = this.cell;
|
|
185
|
+
info.cell = Math.floor(p.x / cs) + ',' + Math.floor(p.z / cs); info.shown = true;
|
|
186
|
+
info.root.updateMatrixWorld(true);
|
|
187
|
+
for (const e of info.entries) {
|
|
188
|
+
const m = e.mesh, mat = this.orig.get(m) ?? m.material;
|
|
189
|
+
const key = `${info.cell}|${m.geometry.id}|${mat.id}|${+m.castShadow}${+m.receiveShadow}`;
|
|
190
|
+
let g = this.groups.get(key);
|
|
191
|
+
if (!g) this.groups.set(key, g = { key, cell: info.cell, geometry: m.geometry, material: mat, cast: m.castShadow, receive: m.receiveShadow, members: new Set(), items: [], mesh: null, dirty: false, colored: false });
|
|
192
|
+
e.group = g; g.members.add(e);
|
|
193
|
+
if (g.mesh) join(this, e);
|
|
194
|
+
else if (g.members.size >= this.minCount) build(this, g);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/** @internal take a root's meshes out of their groups (they draw on their own again) */
|
|
198
|
+
_detach(info) {
|
|
199
|
+
info.shown = false;
|
|
200
|
+
for (const e of info.entries) {
|
|
201
|
+
const g = e.group; if (!g) continue;
|
|
202
|
+
e.group = null; g.members.delete(e);
|
|
203
|
+
if (e.slot >= 0) leave(this, g, e);
|
|
204
|
+
if (g.mesh && g.members.size < Math.ceil(this.minCount / 2)) dissolve(this, g);
|
|
205
|
+
if (!g.members.size) this.groups.delete(g.key);
|
|
206
|
+
}
|
|
207
|
+
this.live.delete(info);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ---------- per-frame checks ----------
|
|
211
|
+
/** @internal the object's own transform / visibility changed: move its instances (or regroup when it changed cell) */
|
|
212
|
+
_check(info) {
|
|
213
|
+
const r = info.root;
|
|
214
|
+
if (same(r, info.snap)) return;
|
|
215
|
+
snap(r, info.snap);
|
|
216
|
+
if (!r.visible) { this._detach(info); return; }
|
|
217
|
+
const cs = this.cell, cell = Math.floor(r.position.x / cs) + ',' + Math.floor(r.position.z / cs);
|
|
218
|
+
if (cell !== info.cell || !info.shown) { this._detach(info); this._attach(info); return; }
|
|
219
|
+
r.updateMatrixWorld(true);
|
|
220
|
+
for (const e of info.entries) if (e.slot >= 0) { e.group.mesh.setMatrixAt(e.slot, e.mesh.matrixWorld); e.group.mesh.instanceMatrix.needsUpdate = true; e.group.dirty = true; }
|
|
221
|
+
}
|
|
222
|
+
/** @internal slow round robin: hidden roots coming back, pending roots that moved cell, batched parts changed behind our back */
|
|
223
|
+
_verify(info) {
|
|
224
|
+
const r = info.root;
|
|
225
|
+
if (!this.live.has(info)) { // not batched: only keep its cell right (so counting stays honest)
|
|
226
|
+
if (!same(r, info.snap)) { snap(r, info.snap); this._detach(info); if (r.visible) this._attach(info); }
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
for (const e of info.entries) {
|
|
230
|
+
if (e.slot < 0) continue;
|
|
231
|
+
const m = e.mesh, g = e.group;
|
|
232
|
+
let why = m.layers.mask !== HIDDEN ? 'layers' : !m.visible ? 'hidden' : m.material !== g.material ? 'material' : m.geometry !== g.geometry ? 'geometry' : m.children.length ? 'children'
|
|
233
|
+
: m.castShadow !== g.cast || m.receiveShadow !== g.receive ? 'shadow flags' : !under(m, r) ? 're-parented' : '';
|
|
234
|
+
if (!why) {
|
|
235
|
+
m.updateWorldMatrix(true, false);
|
|
236
|
+
if (!stored(g.mesh.instanceMatrix.array, e.slot, m.matrixWorld) && same(r, info.snap)) why = 'a part moved';
|
|
237
|
+
}
|
|
238
|
+
if (why) { this._evict(info, why); return; }
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** @internal */
|
|
242
|
+
_evict(info, why) {
|
|
243
|
+
warnOnce(STRINGS.evicted.replace('{name}', info.root.name || info.entries[0].mesh.name || 'model').replace('{why}', why));
|
|
244
|
+
for (const e of info.entries) this.banned.add(e.mesh.geometry);
|
|
245
|
+
this._untrack(info.root);
|
|
246
|
+
}
|
|
247
|
+
}
|