threedog 0.7.0 → 1.0.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 +411 -1
- package/README.md +8 -11
- package/core/{Animator.js → assets/Animator.js} +30 -18
- package/core/{Assets.js → assets/Assets.js} +131 -56
- package/core/{Baked.js → assets/Baked.js} +4 -4
- package/core/assets/assetEntry.js +302 -0
- package/core/{assetHot.js → assets/assetHot.js} +9 -7
- package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
- package/core/assets/assetLod.js +113 -0
- package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
- package/core/{assetReport.js → assets/assetReport.js} +7 -14
- package/core/{namedModel.js → assets/namedModel.js} +17 -13
- package/core/{Audio.js → audio/Audio.js} +47 -25
- package/core/{audioRules.js → audio/audioRules.js} +8 -5
- package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
- package/core/{Events.js → base/Events.js} +3 -3
- package/core/{I18n.js → base/I18n.js} +15 -12
- package/core/{Random.js → base/Random.js} +7 -4
- package/core/{Vars.js → base/Vars.js} +14 -4
- package/core/{easing.js → base/easing.js} +1 -1
- package/core/{errorCodes.js → base/errorCodes.js} +151 -125
- package/core/{errorHints.js → base/errorHints.js} +17 -10
- package/core/{errors.js → base/errors.js} +12 -10
- package/core/{events.generated.js → base/events.generated.js} +11 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +66 -0
- package/core/{params.js → base/params.js} +5 -6
- package/core/base/saveValues.js +81 -0
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/util.js +32 -0
- package/core/{validate.js → base/validate.js} +34 -34
- package/core/{Engine.js → engine/Engine.js} +137 -91
- package/core/{Loading.js → engine/Loading.js} +34 -5
- package/core/{copies.js → engine/copies.js} +4 -4
- package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
- package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
- package/core/{loop.js → engine/loop.js} +88 -49
- package/core/engine/moduleSlots.js +176 -0
- package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
- package/core/engine/modules.js +503 -0
- package/core/{page.js → engine/page.js} +59 -29
- package/core/{plugins.js → engine/plugins.js} +21 -12
- package/core/{services.js → engine/services.js} +50 -40
- package/core/{startup.js → engine/startup.js} +66 -54
- package/core/{Input.js → input/Input.js} +67 -39
- package/core/{inputContext.js → input/inputContext.js} +14 -5
- package/core/input/inputKeyboard.js +39 -0
- package/core/{inputPad.js → input/inputPad.js} +24 -3
- package/core/{inputPointer.js → input/inputPointer.js} +11 -3
- package/core/input/inputSeat.js +66 -0
- package/core/{inputTouch.js → input/inputTouch.js} +24 -7
- package/core/{Budget.js → inspect/Budget.js} +21 -20
- package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
- package/core/{Describe.js → inspect/Describe.js} +34 -26
- package/core/{Inspect.js → inspect/Inspect.js} +39 -10
- package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
- package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
- package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
- package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
- package/core/{UrlState.js → inspect/UrlState.js} +60 -24
- package/core/{catalog.js → inspect/catalog.js} +15 -8
- package/core/{checks.js → inspect/checks.js} +7 -5
- package/core/{debugView.js → inspect/debugView.js} +4 -4
- package/core/{describeRender.js → inspect/describeRender.js} +24 -22
- package/core/{describeText.js → inspect/describeText.js} +17 -8
- package/core/inspect/geometryWatch.js +38 -0
- package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
- package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/{Ops.js → ops/Ops.js} +44 -14
- package/core/{control.js → ops/control.js} +57 -31
- package/core/ops/holds.js +140 -0
- package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
- package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
- package/core/{opsFail.js → ops/opsFail.js} +5 -7
- package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
- package/core/{opsRun.js → ops/opsRun.js} +9 -6
- package/core/{owned.js → ops/owned.js} +33 -19
- package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
- package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
- package/core/{stacks.js → ops/stacks.js} +34 -15
- package/core/{wrap.js → ops/wrap.js} +8 -6
- package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
- package/core/{Saves.js → saves/Saves.js} +171 -54
- package/core/saves/saveApply.js +312 -0
- package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
- package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
- package/core/saves/session.js +231 -0
- package/core/saves/stateReplace.js +184 -0
- package/core/{Rays.js → scene/Rays.js} +44 -30
- package/core/{Views.js → scene/Views.js} +16 -8
- package/core/{adaptive.js → scene/adaptive.js} +19 -9
- package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/{gameLights.js → scene/gameLights.js} +17 -7
- package/core/{grayMap.js → scene/grayMap.js} +8 -2
- package/core/{grid.js → scene/grid.js} +6 -4
- package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +139 -0
- package/core/{movement.js → scene/movement.js} +3 -3
- package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
- package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
- package/core/scene/stepPoses.js +60 -0
- package/core/{targeting.js → scene/targeting.js} +4 -5
- package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
- package/core/{thingOps.js → scene/thingOps.js} +25 -16
- package/core/{things.js → scene/things.js} +18 -5
- package/core/{threePatches.js → scene/threePatches.js} +1 -1
- package/core/{tier.js → scene/tier.js} +10 -0
- package/core/scene/view.js +161 -0
- package/core/{Batching.js → stream/Batching.js} +85 -28
- package/core/{Stream.js → stream/Stream.js} +80 -38
- package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
- package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
- package/core/{scatter.js → stream/scatter.js} +7 -4
- package/core/{streamSources.js → stream/streamSources.js} +14 -8
- package/core/{Commits.js → threads/Commits.js} +17 -11
- package/core/{Jobs.js → threads/Jobs.js} +25 -13
- package/core/{Threads.js → threads/Threads.js} +21 -18
- package/core/{threadPure.js → threads/threadPure.js} +7 -5
- package/core/{threadServe.js → threads/threadServe.js} +3 -3
- package/core/{Clock.js → time/Clock.js} +20 -11
- package/core/{dayTime.js → time/dayTime.js} +5 -1
- package/core/{skip.js → time/skip.js} +28 -21
- package/core/{time.js → time/time.js} +32 -20
- package/core/{uiClock.js → time/uiClock.js} +4 -4
- package/docs/AI.md +92 -72
- package/docs/API.md +33 -28
- package/docs/CODEMAP.md +121 -200
- package/docs/COMMANDS.md +77 -70
- package/docs/CONVENTIONS.md +167 -24
- package/docs/MIGRATING-0.8.md +171 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +140 -38
- package/docs/api/assets.md +12 -13
- package/docs/api/audio.md +6 -5
- package/docs/api/budget.md +4 -4
- package/docs/api/calendar.md +10 -11
- package/docs/api/cameraRig.md +32 -29
- package/docs/api/characters.md +35 -24
- package/docs/api/clock.md +1 -1
- package/docs/api/collider3d.md +9 -0
- package/docs/api/collision.md +12 -9
- package/docs/api/content.md +18 -17
- package/docs/api/dialogue.md +5 -4
- package/docs/api/engine.md +58 -54
- package/docs/api/events.md +17 -6
- package/docs/api/flow.md +1 -1
- package/docs/api/grids.md +1 -1
- package/docs/api/ground.md +6 -7
- package/docs/api/hud.md +2 -2
- package/docs/api/i18n.md +6 -6
- package/docs/api/input.md +9 -8
- package/docs/api/interactions.md +5 -5
- package/docs/api/inventory.md +10 -10
- package/docs/api/jobs.md +5 -5
- package/docs/api/level.md +10 -9
- package/docs/api/lightPool.md +1 -6
- package/docs/api/music.md +3 -3
- package/docs/api/nav.md +14 -12
- package/docs/api/openWorld.md +1 -1
- package/docs/api/particles.md +10 -7
- package/docs/api/photo.md +4 -2
- package/docs/api/pickups.md +3 -3
- package/docs/api/post.md +21 -5
- package/docs/api/quests.md +7 -5
- package/docs/api/rays.md +7 -7
- package/docs/api/rigid.md +29 -19
- package/docs/api/saves.md +13 -11
- package/docs/api/settings.md +9 -8
- package/docs/api/sky.md +8 -7
- package/docs/api/stream.md +8 -9
- package/docs/api/swarm.md +34 -0
- package/docs/api/terrain.md +6 -8
- package/docs/api/terrainDraw.md +2 -2
- package/docs/api/timeline.md +4 -4
- package/docs/api/tools.md +27 -22
- package/docs/api/triggers.md +2 -0
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -3
- package/docs/api/vegetationDraw.md +2 -2
- package/docs/api/water.md +7 -3
- package/docs/api/weather.md +27 -12
- package/docs/api/weatherDraw.md +4 -4
- package/docs/api/world.md +6 -6
- package/docs/recipes/01-new-game.md +28 -43
- package/docs/recipes/02-npc.md +21 -23
- package/docs/recipes/03-items-pickups.md +37 -53
- package/docs/recipes/04-quests.md +5 -4
- package/docs/recipes/05-props-bake.md +34 -44
- package/docs/recipes/06-clock-events.md +31 -22
- package/docs/recipes/07-flow-scenes-pause.md +30 -32
- package/docs/recipes/08-weather-sky.md +91 -37
- package/docs/recipes/09-materials-lights-models.md +25 -39
- package/docs/recipes/10-blender-level.md +22 -11
- package/docs/recipes/11-vehicles.md +44 -24
- package/docs/recipes/12-navmesh.md +60 -15
- package/docs/recipes/13-animation.md +70 -22
- package/docs/recipes/14-custom-module.md +33 -20
- package/docs/recipes/15-perf.md +51 -28
- package/docs/recipes/16-dev-bridge.md +39 -58
- package/docs/recipes/18-world.md +49 -28
- package/docs/recipes/19-shooting-picking.md +7 -4
- package/docs/recipes/20-content-actions-save.md +55 -40
- package/docs/recipes/21-camera.md +47 -25
- package/docs/recipes/22-shop-gold.md +21 -16
- package/docs/recipes/23-ops.md +28 -24
- package/docs/recipes/26-ui-parts.md +25 -14
- package/docs/recipes/27-net.md +3 -5
- package/docs/recipes/28-terrain.md +119 -23
- package/docs/recipes/29-grid.md +3 -3
- package/docs/recipes/30-templates.md +63 -30
- package/docs/recipes/31-audio.md +7 -7
- package/docs/recipes/32-action-game.md +21 -11
- package/docs/recipes/33-stream-sources.md +6 -3
- package/docs/recipes/34-environment-lighting.md +72 -25
- package/docs/recipes/35-picture-from-reference.md +20 -23
- package/docs/recipes/36-ground-plants.md +106 -0
- package/docs/recipes/40-scene.md +18 -21
- package/docs/recipes/43-shader-patches-surfaces.md +27 -48
- package/docs/recipes/44-water-weather-hooks.md +56 -50
- package/docs/recipes/45-cascaded-shadows.md +41 -20
- package/docs/recipes/46-blender-art-route.md +9 -10
- package/docs/recipes/49-game-module-contract.md +7 -6
- package/docs/recipes/50-own-renderer.md +3 -2
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +56 -100
- package/docs/recipes/53-ground-up-close.md +61 -24
- package/docs/recipes/55-mods-time-wrap.md +17 -20
- package/docs/recipes/56-webgpu-tsl.md +28 -15
- package/docs/recipes/57-control.md +39 -12
- package/docs/recipes/58-input.md +15 -2
- package/docs/recipes/59-depth-post-effects.md +1 -1
- package/docs/recipes/60-judge-the-picture.md +30 -25
- package/docs/recipes/62-picture-code.md +129 -39
- package/docs/recipes/63-third-person-start.md +19 -5
- package/docs/recipes/64-particles.md +54 -5
- package/docs/recipes/65-swarm.md +140 -0
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/perf-island/.threedog/content-index.json +1 -0
- package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
- package/examples/{sheepisland → perf-island}/assets.js +1 -1
- package/examples/{sheepisland → perf-island}/main.js +8 -8
- package/examples/{sheepisland → perf-island}/models.js +1 -1
- package/examples/{sheepisland → perf-island}/params.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
- package/examples/{sheepisland → perf-island}/views.js +1 -1
- package/examples/plain-picture/GAMEMAP.md +4 -1
- package/examples/rc2d/GAMEMAP.md +4 -3
- package/examples/rc2d/main.js +1 -3
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +6 -5
- package/examples/techniques/contact-shadows/contactShadows.js +1 -1
- package/examples/techniques/contact-shadows/main.js +1 -1
- package/examples/techniques/interior-light/main.js +1 -1
- package/examples/techniques/modular-building/README.md +7 -6
- package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +2 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +9 -7
- package/examples/world/main.js +3 -3
- package/examples/world/picture/sky.js +1 -1
- package/index.d.ts +16 -12
- package/index.js +53 -32
- package/llms.txt +11 -14
- package/modules/ambience/Ambience.js +16 -11
- package/modules/calendar/Calendar.js +19 -19
- package/modules/calendar/index.js +18 -16
- package/modules/calendar/schedule.js +11 -6
- package/modules/calendar/seasons.js +7 -7
- package/modules/camera/FirstPersonCamera.js +5 -5
- package/modules/camera/FixedCamera.js +43 -30
- package/modules/camera/FollowCamera.js +24 -15
- package/modules/camera/RtsCamera.js +12 -11
- package/modules/camera/common.js +72 -37
- package/modules/camera/contract.js +1 -0
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +166 -70
- package/modules/characters/NPC.js +84 -44
- package/modules/characters/assetModel.js +16 -12
- package/modules/characters/astar.js +48 -27
- package/modules/characters/behaviors.js +4 -5
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +240 -226
- package/modules/characters/moveHelpers.js +88 -12
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +22 -18
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +18 -10
- package/modules/characters/movers/simple.js +26 -13
- package/modules/characters/movers/support.js +24 -13
- package/modules/characters/npcAvoid.js +19 -16
- package/modules/characters/npcSim.js +88 -32
- package/modules/characters/npcView.js +19 -11
- package/modules/characters/pathAsync.js +81 -29
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/pathWorker.js +1 -1
- package/modules/characters/player.js +120 -0
- package/modules/characters/playerStrings.js +2 -2
- package/modules/characters/proceduralRig.js +2 -2
- package/modules/characters/seat.js +56 -0
- package/modules/characters/useModel.js +3 -3
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +40 -33
- package/modules/collision/Collision.js +69 -45
- package/modules/collision/contract.js +15 -0
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +2 -3
- package/modules/content/fields.js +24 -3
- package/modules/content/ids.js +5 -3
- package/modules/content/index.js +132 -114
- package/modules/content/loader.js +117 -140
- package/modules/content/markers.js +25 -0
- package/modules/content/models.js +54 -17
- package/modules/content/packs.js +5 -4
- package/modules/content/parts.js +2 -2
- package/modules/content/places.js +36 -0
- package/modules/content/props.js +22 -17
- package/modules/content/rules.js +47 -61
- package/modules/content/stages.js +7 -7
- package/modules/content/templates.js +80 -49
- package/modules/content/words.js +47 -0
- package/modules/debug/DebugPanel.js +14 -45
- package/modules/flow/contract.js +2 -1
- package/modules/flow/index.js +30 -16
- package/modules/gameplay/Container.js +17 -13
- package/modules/gameplay/Containers.js +23 -6
- package/modules/gameplay/Dialogue.js +93 -34
- package/modules/gameplay/Interactions.js +93 -51
- package/modules/gameplay/Inventory.js +64 -22
- package/modules/gameplay/Quests.js +146 -30
- package/modules/gameplay/boxOps.js +8 -1
- package/modules/gameplay/dialogueBubbles.js +16 -12
- package/modules/gameplay/inventoryOps.js +11 -8
- package/modules/gameplay/pickups.js +63 -37
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +9 -4
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +2 -2
- package/modules/grid/Layer.js +12 -8
- package/modules/grid/index.js +28 -23
- package/modules/grid/ops.js +43 -46
- package/modules/grid/preview.js +7 -7
- package/modules/grid/tiles.js +6 -6
- package/modules/hlod/index.js +42 -57
- package/modules/hud/index.js +22 -14
- package/modules/hud/parts.js +8 -8
- package/modules/level/contract.js +16 -0
- package/modules/level/heightfield.js +29 -31
- package/modules/level/index.js +113 -161
- package/modules/level/load.js +196 -0
- package/modules/level/meshes.js +65 -0
- package/modules/level/nodes.js +40 -23
- package/modules/lights/index.js +33 -183
- package/modules/lights/slots.js +93 -0
- package/modules/lights/sources.js +90 -0
- package/modules/music/Music.js +34 -28
- package/modules/music/rules.js +1 -1
- package/modules/nav/contract.js +16 -0
- package/modules/nav/index.js +180 -49
- package/modules/nav/navPath.js +45 -10
- package/modules/net/Client.js +7 -7
- package/modules/net/Host.js +7 -7
- package/modules/net/Net.js +1 -1
- package/modules/net/index.js +6 -5
- package/modules/net/sync.js +2 -2
- package/modules/net/transports.js +2 -2
- package/modules/particles/Particles.js +95 -29
- package/modules/particles/effect.js +86 -32
- package/modules/particles/shaders.js +19 -1
- package/modules/photo/Photo.js +23 -23
- package/modules/rigid/RigidBodies.js +255 -89
- package/modules/rigid/Vehicles.js +17 -8
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +298 -0
- package/modules/rigid/ragdollBones.js +209 -0
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +51 -20
- package/modules/settings/Settings.js +177 -61
- package/modules/settings/apply.js +20 -13
- package/modules/settings/sections.js +19 -14
- package/modules/settings/strings.js +2 -2
- package/modules/settings/view.js +3 -3
- package/modules/sky/Sky.js +29 -22
- package/modules/sky/clouds.js +7 -7
- package/modules/sky/dome.js +33 -20
- package/modules/sky/domeLayers.js +9 -9
- package/modules/sky/environment.js +6 -6
- package/modules/sky/frame.js +19 -10
- package/modules/sky/season.js +7 -1
- package/modules/sky/shader.js +24 -25
- package/modules/sky/skyModule.js +17 -28
- package/modules/sky/tint.js +1 -1
- package/modules/swarm/Swarm.js +356 -0
- package/modules/swarm/draw.js +68 -0
- package/modules/swarm/grid.js +63 -0
- package/modules/terrain/ChunkManager.js +71 -59
- package/modules/terrain/chunkQueries.js +7 -24
- package/modules/terrain/chunkWorker.js +1 -1
- package/modules/terrain/draw.js +14 -11
- package/modules/terrain/index.js +42 -42
- package/modules/terrain/terrainColorMap.js +6 -3
- package/modules/terrain/terrainDefaults.js +2 -1
- package/modules/terrain/terrainEdit.js +45 -29
- package/modules/terrain/terrainGen.js +19 -12
- package/modules/terrain/terrainIsland.js +2 -2
- package/modules/terrain/terrainMesh.js +7 -6
- package/modules/terrain/terrainShape.js +8 -10
- package/modules/terrain/terrainShapeMain.js +3 -3
- package/modules/timeline/Timeline.js +83 -43
- package/modules/timeline/Tween.js +25 -19
- package/modules/timeline/shots.js +24 -17
- package/modules/triggers/index.js +95 -28
- package/modules/vegetation/Vegetation.js +34 -26
- package/modules/vegetation/densityMap.js +4 -7
- package/modules/vegetation/draw.js +39 -18
- package/modules/vegetation/groundChunks.js +21 -38
- package/modules/vegetation/index.js +37 -12
- package/modules/vegetation/modelGeometry.js +3 -6
- package/modules/vegetation/nearFade.js +1 -1
- package/modules/water/Water.js +20 -16
- package/modules/water/surface.js +3 -3
- package/modules/weather/Weather.js +52 -40
- package/modules/weather/particles.js +8 -8
- package/modules/weather/weatherDraw.js +28 -23
- package/modules/world/World.js +28 -15
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +30 -17
- package/modules/world/persist.js +90 -27
- package/modules/world/pos.js +5 -5
- package/modules/world/records.js +37 -11
- package/modules/world/sim.js +78 -27
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +43 -11
- package/modules/world/thingSource.js +20 -5
- package/modules/world/views.js +27 -14
- package/package.json +48 -7
- package/presets.js +1 -3
- package/render/PostFX.js +83 -53
- package/render/backend.js +31 -33
- package/render/cascades.js +17 -12
- package/render/cascades.tsl.js +5 -8
- package/render/daylight.js +20 -3
- package/render/detail.js +8 -7
- package/render/effects.js +28 -25
- package/render/fuse.js +3 -3
- package/render/fx/cloudShadow.tsl.js +3 -3
- package/render/fx/detail.tsl.js +1 -1
- package/render/fx/index.js +5 -10
- package/render/fx/library.tsl.js +11 -0
- package/render/fx/lighting.tsl.js +2 -1
- package/render/fx/nodeErrors.tsl.js +2 -2
- package/render/fx/objectOrigin.tsl.js +1 -2
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/patchNodes.tsl.js +5 -15
- package/render/fx/postWebGPU.tsl.js +30 -26
- package/render/fx/sky.tsl.js +15 -17
- package/render/fx/uniforms.tsl.js +4 -4
- package/render/fx/wind.tsl.js +1 -1
- package/render/fxNumbers.js +3 -0
- package/render/layers.js +2 -2
- package/render/lighting.js +5 -3
- package/render/lightmap.js +41 -21
- package/render/lights.js +6 -6
- package/render/lit.js +24 -0
- package/render/materials.js +8 -7
- package/render/mergeCommon.js +22 -0
- package/render/modeling.js +2 -2
- package/render/occlusion.js +62 -15
- package/render/ownFrame.js +4 -4
- package/render/patches.js +15 -15
- package/render/postWebGL.js +15 -12
- package/render/probes.js +41 -19
- package/render/recordSweep.js +117 -0
- package/render/shaderErrors.js +10 -9
- package/render/shadowCache.tsl.js +107 -0
- package/render/shadowTypes.js +9 -0
- package/{core → render}/shadows.js +59 -13
- package/render/slots.js +7 -7
- package/render/terms.js +22 -24
- package/render/uniformDecl.js +1 -1
- package/types/core.d.ts +336 -202
- package/types/gameplay.d.ts +254 -130
- package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
- package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
- package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
- package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
- package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
- package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
- package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
- package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
- package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
- package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
- package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
- package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
- package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
- package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
- package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
- package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
- package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
- package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
- package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
- package/types/generated/modules/calendar/Calendar.d.ts +10 -11
- package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/grid/Layer.d.ts +1 -1
- package/types/generated/modules/grid/index.d.ts +3 -3
- package/types/generated/modules/music/Music.d.ts +7 -5
- package/types/generated/modules/particles/Particles.d.ts +5 -4
- package/types/generated/modules/sky/Sky.d.ts +21 -10
- package/types/generated/modules/swarm/Swarm.d.ts +80 -0
- package/types/generated/modules/timeline/Timeline.d.ts +7 -5
- package/types/generated/modules/water/Water.d.ts +1 -0
- package/types/generated/modules/weather/Weather.d.ts +14 -16
- package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
- package/types/generated/modules/world/World.d.ts +11 -7
- package/types/generated/render/PostFX.d.ts +21 -23
- package/types/generated/render/materials.d.ts +1 -0
- package/types/generated/render/occlusion.d.ts +9 -0
- package/types/generated/render/patches.d.ts +1 -0
- package/types/generated/ui/Focus.d.ts +1 -0
- package/types/generated/ui/UI.d.ts +1 -0
- package/types/nav.d.ts +47 -15
- package/types/physics.d.ts +150 -73
- package/types/pixel.d.ts +75 -0
- package/types/tsl.d.ts +37 -4
- package/types/world.d.ts +48 -75
- package/ui/Focus.js +10 -9
- package/ui/Parts.js +13 -5
- package/ui/UI.js +7 -7
- package/ui/defaults.js +3 -2
- package/ui/theme.js +7 -5
- package/core/assetEntry.js +0 -109
- package/core/engineCamera.js +0 -32
- package/core/ground.js +0 -104
- package/core/holds.js +0 -134
- package/core/math.js +0 -48
- package/core/moduleSlots.js +0 -100
- package/core/modules.js +0 -314
- package/core/saveApply.js +0 -210
- package/core/saveValues.js +0 -46
- package/core/session.js +0 -174
- package/core/shadowTypes.js +0 -16
- package/core/util.js +0 -17
- package/core/view.js +0 -43
- package/docs/MIGRATING-0.3.md +0 -248
- package/docs/MIGRATING-0.4.md +0 -320
- package/docs/MIGRATING-0.5.md +0 -68
- package/docs/MIGRATING-0.6.md +0 -126
- package/docs/PERF.md +0 -245
- package/docs/recipes/36-sky-ground-plants.md +0 -158
- package/docs/recipes/37-terrain-hooks.md +0 -115
- package/docs/recipes/38-environment-hooks.md +0 -67
- package/docs/recipes/42-terrain-shape.md +0 -64
- package/docs/recipes/47-island-snow-backdrop.md +0 -43
- package/docs/recipes/54-three-idioms.md +0 -88
- package/examples/plain-picture/FINDINGS.md +0 -53
- package/examples/sheepisland/.threedog/content-index.json +0 -1
- package/modules/camera/projection.js +0 -21
- /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
- /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
- /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
- /package/core/{actor.js → ops/actor.js} +0 -0
- /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
- /package/core/{saveIds.js → saves/saveIds.js} +0 -0
- /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
- /package/core/{cells.js → stream/cells.js} +0 -0
- /package/core/{streamCells.js → stream/streamCells.js} +0 -0
- /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
- /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// camera focus, a teleport destination)
|
|
3
3
|
// and the result unloads when far from all of them. Ten thousand entries build only the nearby ones.
|
|
4
4
|
// const h = engine.stream.add({ position: [40, 0, -20], radius: 8, build: () => makeHouse() }); // the object build returns is added to the scene automatically
|
|
5
|
-
// engine.stream.
|
|
5
|
+
// engine.stream.radius = 200; // how far from each stream source to build (meters); defaults to the terrain view distance, or the signal uViewDistance
|
|
6
6
|
// without terrain
|
|
7
7
|
// h.remove(); // no longer needed (a built one is unloaded)
|
|
8
8
|
// Stream sources (stream.player, stream.camera, stream.source(...), stream.teleport(...)) are the one list every distance-based loader reads: stream entries,
|
|
@@ -13,29 +13,28 @@
|
|
|
13
13
|
// unloads.
|
|
14
14
|
// At startup start() waits for everything registered within radius to finish building before the loading screen goes away. The grid cell size cellSize is
|
|
15
15
|
// shared with hlod.
|
|
16
|
-
/** @import { StreamEntryOptions, StreamHandle, StreamSource, StreamSourceOptions } from '
|
|
17
|
-
import { readParams, keysSchema } from '
|
|
18
|
-
import { xzOf } from '
|
|
19
|
-
import { reportError } from '
|
|
20
|
-
import { codedError } from '
|
|
16
|
+
/** @import { StreamEntryOptions, StreamHandle, StreamSource, StreamSourceOptions } from '../../types/core' */
|
|
17
|
+
import { readParams, keysSchema } from '../base/params.js';
|
|
18
|
+
import { xzOf } from '../base/math.js';
|
|
19
|
+
import { reportError } from '../base/errors.js';
|
|
20
|
+
import { codedError } from '../base/errorHints.js';
|
|
21
|
+
import { fmt } from '../base/validate.js';
|
|
22
|
+
import { surfaceOr } from '../scene/ground.js';
|
|
21
23
|
import { Source, SOURCE_KEYS, SOURCE_STRINGS } from './streamSources.js';
|
|
22
24
|
|
|
23
25
|
const KEYS = ['position', 'radius', 'build', 'dispose', 'keep', 'priority'];
|
|
24
26
|
const FULL = { detail: 'full' };
|
|
27
|
+
const UNLOAD = -1e6; // job priority: behind any build (a build runs at its entry's priority minus 0..1)
|
|
25
28
|
|
|
26
29
|
/** engine.stream builds on demand by space: only entries near the focus get built. */
|
|
27
30
|
export class Stream {
|
|
28
31
|
/** @internal */
|
|
29
32
|
constructor(engine) {
|
|
30
33
|
/** @internal */ this.engine = engine;
|
|
31
|
-
/**
|
|
32
|
-
* Build radius in meters around each full-detail stream source (a source radius caps it); null = follow the terrain view distance (the fog distance
|
|
33
|
-
* the fog distance without terrain) @type {number | null}
|
|
34
|
-
*/
|
|
35
|
-
this.radius = null;
|
|
34
|
+
/** @internal */ this._radius = null;
|
|
36
35
|
/** Grid cell edge in meters, shared with hlod, default 64 */
|
|
37
36
|
this.cellSize = 64;
|
|
38
|
-
/** Unload only beyond radius x this (walking back and forth does not rebuild), default 1.25 */
|
|
37
|
+
/** Unload only beyond radius x this (walking back and forth does not rebuild), default 1.25 @experimental */
|
|
39
38
|
this.unloadFactor = 1.25;
|
|
40
39
|
/** @internal */ this.entries = new Set();
|
|
41
40
|
/** @internal 'cx,cz' -> Set<handle> */ this.cells = new Map();
|
|
@@ -46,16 +45,18 @@ export class Stream {
|
|
|
46
45
|
/** @internal */ this._radiusDirty = false;
|
|
47
46
|
/** @internal what the sources looked like at the last check */ this._memo = {};
|
|
48
47
|
/** @internal */ this._dirty = true;
|
|
48
|
+
/** @internal the radius the last pass reached with */ this._passR = null;
|
|
49
49
|
/** @internal */ this._sources = new Set();
|
|
50
50
|
/** @internal Bumps when a source is added, removed or moved with at() */ this._version = 0;
|
|
51
51
|
/** @internal name -> (source) => boolean */ this._checks = new Map();
|
|
52
|
-
/** Built-in source at the
|
|
52
|
+
/** Built-in source at the player (engine.focus without one): full detail and physics @type {StreamSource} */
|
|
53
53
|
this.player = this.source(() => engine.player?.position ?? engine.focus, { name: 'player' });
|
|
54
54
|
/** Built-in source at the camera focus engine.focus: full detail, no physics @type {StreamSource} */
|
|
55
55
|
this.camera = this.source(engine.focus, { name: 'camera', physics: false });
|
|
56
|
-
this.
|
|
56
|
+
this.addReadyCheck('stream', s => s.detail !== 'full' || this.ready);
|
|
57
|
+
this.addReadyCheck('state', s => !s._waitsForLoad || !engine.saves.replacing);
|
|
57
58
|
}
|
|
58
|
-
/** The build radius actually in use, in meters @returns {number} */
|
|
59
|
+
/** The build radius actually in use, in meters @returns {number} @experimental */
|
|
59
60
|
get activeRadius() {
|
|
60
61
|
return this.radius ?? this.engine.ground.viewRange?.() ?? this.engine.uniforms.uViewDistance.value; // the ground's view range (terrain sets it), else the view-distance signal: not the fog, which is the game's
|
|
61
62
|
}
|
|
@@ -79,15 +80,24 @@ export class Stream {
|
|
|
79
80
|
this._dirty = true;
|
|
80
81
|
return h;
|
|
81
82
|
}
|
|
82
|
-
/** @internal Clear all entries and
|
|
83
|
+
/** @internal Clear all entries and remove every source, so no whenReady is left waiting for a frame (called by engine.dispose; built objects are released with the scene) */
|
|
83
84
|
dispose() {
|
|
84
85
|
this.entries.clear(); this.cells.clear(); this.live.clear(); this.queued = 0;
|
|
85
|
-
for (const s of [...this._sources])
|
|
86
|
+
for (const s of [...this._sources]) s.remove();
|
|
86
87
|
this._checks.clear();
|
|
87
88
|
}
|
|
88
|
-
/**
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Build radius in meters around each full-detail stream source (a source radius caps it); null = follow the terrain view distance (the uViewDistance signal
|
|
91
|
+
* without terrain).
|
|
92
|
+
* @type {number | null}
|
|
93
|
+
*/
|
|
94
|
+
get radius() { return this._radius; }
|
|
95
|
+
set radius(m) {
|
|
96
|
+
// Infinity would hang _update's cell walk and NaN would build nothing, without a word
|
|
97
|
+
if (m != null && !(m >= 0 && Number.isFinite(m))) throw codedError('stream-option', `stream.radius is a finite number of meters >= 0, or null to follow the view distance; got ${m}`);
|
|
98
|
+
this._radius = m;
|
|
99
|
+
}
|
|
100
|
+
/** No build within radius is still waiting (start() waits for it before the loading screen goes away). Nothing pending, not everything built: a build that failed is reported and left out; a game that needs a thing built checks it itself (handle.built) @returns {boolean} */
|
|
91
101
|
get ready() { return this.queued === 0; }
|
|
92
102
|
/** entries is the registered count, built the built count, queued the queued count @returns {{ entries: number, built: number, queued: number }} */
|
|
93
103
|
get stats() { return { entries: this.entries.size, built: this.live.size - this.queued, queued: this.queued }; }
|
|
@@ -107,9 +117,10 @@ export class Stream {
|
|
|
107
117
|
*/
|
|
108
118
|
source(position, opts = {}) {
|
|
109
119
|
readParams('stream.source()', keysSchema(SOURCE_KEYS), opts);
|
|
110
|
-
if (opts.detail != null && opts.detail !== 'full' && opts.detail !== 'simple') throw codedError('stream-option', SOURCE_STRINGS.detail
|
|
120
|
+
if (opts.detail != null && opts.detail !== 'full' && opts.detail !== 'simple') throw codedError('stream-option', fmt(SOURCE_STRINGS.detail, { got: String(JSON.stringify(opts.detail)) }));
|
|
111
121
|
const s = new Source(this, position, opts);
|
|
112
122
|
this._sources.add(s); this._version++;
|
|
123
|
+
if (this.engine.disposed) s.remove(); // no frame will ever settle it
|
|
113
124
|
return /** @type {any} */ (s);
|
|
114
125
|
}
|
|
115
126
|
|
|
@@ -118,6 +129,10 @@ export class Stream {
|
|
|
118
129
|
* (terrain chunks, collision, nearby models) the player stays where it is. move replaces the default placement (for a vehicle or a custom character).
|
|
119
130
|
* timeout (seconds of frame time, default 60; Infinity waits forever): when the destination is still not ready, the Promise rejects (code stream-timeout,
|
|
120
131
|
* naming the loaders still waiting) and the player is not moved.
|
|
132
|
+
* Ready means nothing is pending, not that everything built: a stream entry or world model whose build failed is reported and left out, and the trip still lands. A terrain chunk that
|
|
133
|
+
* failed stays not ready, as there is no ground to stand on, so that trip ends in stream-timeout. A game that needs a thing built checks it itself (handle.built, engine.world.view(id)).
|
|
134
|
+
* A trip belongs to the state it was asked in: it does not land while a load runs, and a newGame, load or saves.load that goes through abandons it (it rejects with
|
|
135
|
+
* code stream-removed and the player stays where the new state put it). A load that fails leaves it going.
|
|
121
136
|
* @example await engine.stream.teleport([800, 0, 300]);
|
|
122
137
|
* @example await engine.stream.teleport(door.target, { radius: 40, move: p => engine.player.placeAt(p) });
|
|
123
138
|
* @param {any} position
|
|
@@ -128,19 +143,25 @@ export class Stream {
|
|
|
128
143
|
async teleport(position, opts = {}) {
|
|
129
144
|
readParams('stream.teleport()', keysSchema(['radius', 'move', 'timeout']), opts);
|
|
130
145
|
const e = this.engine, s = this.source(position, { radius: opts.radius ?? 64, name: 'teleport' }), limit = opts.timeout ?? 60;
|
|
146
|
+
// session.id would miss saves.load. A load under way may still fail and give this state back, so the move waits for its end; one asked inside the load (a part's load awaiting it) cannot wait for itself.
|
|
147
|
+
// Rejecting, not resolving: the caller's next line belongs to the old state too
|
|
148
|
+
s._waitsForLoad = !e.saves.replacing;
|
|
149
|
+
const generation = e.saves.generation, abandoned = () => codedError('stream-removed', fmt(SOURCE_STRINGS.abandoned, { x: s.x.toFixed(1), z: s.z.toFixed(1) }));
|
|
131
150
|
let waited = 0;
|
|
132
151
|
const watch = e.onFrame(dt => {
|
|
152
|
+
if (e.saves.generation !== generation && !e.saves.replacing) { s._settle(abandoned()); return; } // no reason to keep loading a place nobody is going to
|
|
133
153
|
if ((waited += dt) <= limit || s.ready) return;
|
|
134
154
|
const checks = [...this._checks].filter(([, fn]) => !fn(s)).map(([n]) => n).join(', ') || 'one more frame';
|
|
135
|
-
s._settle(codedError('stream-timeout', SOURCE_STRINGS.timeout
|
|
155
|
+
s._settle(codedError('stream-timeout', fmt(SOURCE_STRINGS.timeout, { x: s.x.toFixed(1), z: s.z.toFixed(1), t: String(limit), checks })));
|
|
136
156
|
});
|
|
137
157
|
try {
|
|
138
158
|
await s.whenReady;
|
|
159
|
+
if (e.saves.generation !== generation) throw abandoned();
|
|
139
160
|
// the move lands frames after the call (and after the op that asked for it has returned): it finishes that request, so the ops guard lets it through
|
|
140
161
|
e.ops.allow(() => {
|
|
141
162
|
if (opts.move) opts.move(position);
|
|
142
163
|
else if (e.player) e.player.placeAt(position);
|
|
143
|
-
else { const [x, z] = xzOf(position); e.focus.set(x, e
|
|
164
|
+
else { const [x, z] = xzOf(position); e.focus.set(x, surfaceOr(e, x, z), z); }
|
|
144
165
|
});
|
|
145
166
|
} finally { watch.remove(); s.remove(); } // the player (or camera) source covers the place from now on
|
|
146
167
|
}
|
|
@@ -148,13 +169,13 @@ export class Stream {
|
|
|
148
169
|
/**
|
|
149
170
|
* Register a readiness check for loaders: fn(source) returns whether this loader finished what that source asks for.
|
|
150
171
|
* For module authors whose loader reads stream sources; games only read source.ready.
|
|
151
|
-
* @example engine.stream.
|
|
172
|
+
* @example engine.stream.addReadyCheck('props', s => s.detail !== 'full' || props.queued === 0)
|
|
152
173
|
* @param {string} name
|
|
153
174
|
* @param {(source: StreamSource) => boolean} fn
|
|
154
175
|
* @returns {{ remove(): void }}
|
|
155
176
|
* @experimental
|
|
156
177
|
*/
|
|
157
|
-
|
|
178
|
+
addReadyCheck(name, fn) { this._checks.set(name, fn); return { remove: () => { if (this._checks.get(name) === fn) this._checks.delete(name); } }; }
|
|
158
179
|
|
|
159
180
|
/**
|
|
160
181
|
* Sources with fresh positions, filtered: { detail: 'full' } for models and stream entries, { physics: true } for colliders, no filter for terrain
|
|
@@ -228,15 +249,15 @@ export class Stream {
|
|
|
228
249
|
this._radiusDirty = false; this._maxRadius = 0;
|
|
229
250
|
for (const h of this.entries) this._maxRadius = Math.max(this._maxRadius, h.def.radius ?? 0);
|
|
230
251
|
}
|
|
231
|
-
const cs = this.cellSize;
|
|
232
|
-
|
|
233
|
-
this._dirty
|
|
252
|
+
const cs = this.cellSize, R = this.activeRadius;
|
|
253
|
+
// the radius follows the view distance, which a settings menu moves while the player stands still
|
|
254
|
+
if (!this.changed(this._memo, cs / 8, FULL) && !this._dirty && R === this._passR) return;
|
|
255
|
+
this._dirty = false; this._passR = R;
|
|
234
256
|
// full-detail sources only: a 'simple' source (far view) gets terrain and hlod proxies, not props
|
|
235
|
-
const src = this.sources(FULL)
|
|
236
|
-
|
|
237
|
-
const dist = h => { let d = Infinity; for (const s of src) d = Math.min(d, Math.hypot(h.x - s.x, h.z - s.z) - (h.def.radius ?? 0) - s.reach(R) + R); return d; };
|
|
257
|
+
const src = this.sources(FULL);
|
|
258
|
+
const dist = h => this._dist(h, src, R);
|
|
238
259
|
// unload what is far from every source
|
|
239
|
-
for (const h of this.live) if (!h.def.keep && dist(h) > R * this.unloadFactor) this.
|
|
260
|
+
for (const h of this.live) if (!h.def.keep && dist(h) > R * this.unloadFactor) this._leave(h);
|
|
240
261
|
// build what is near: look only at cells within each source's reach
|
|
241
262
|
for (const s of src) {
|
|
242
263
|
const r = s.reach(R), n = Math.ceil((r + this._maxRadius) / cs), cx = Math.floor(s.x / cs), cz = Math.floor(s.z / cs);
|
|
@@ -247,24 +268,45 @@ export class Stream {
|
|
|
247
268
|
}
|
|
248
269
|
}
|
|
249
270
|
|
|
271
|
+
/** @internal Distance past each source's reach, shifted so it compares against R (a source radius below R shrinks its reach) */
|
|
272
|
+
_dist(h, src, R) { let d = Infinity; for (const s of src) d = Math.min(d, Math.hypot(h.x - s.x, h.z - s.z) - (h.def.radius ?? 0) - s.reach(R) + R); return d; }
|
|
273
|
+
/**
|
|
274
|
+
* @internal A built entry out of range goes through engine.jobs, behind every build: crossing a street puts a whole row of blocks out of range in one frame, and each unload is
|
|
275
|
+
* real work (meshes leave their batches, the object leaves the scene), so that one frame paid for all of them. Nothing waits for an unload, so it can take its turn; engine.step
|
|
276
|
+
* still drains it in the same frame. Checked again when its turn comes: the source may have come back.
|
|
277
|
+
*/
|
|
278
|
+
_leave(h) {
|
|
279
|
+
if (!h.built) { this._unload(h); return; } // still queued: only the wish changes
|
|
280
|
+
if (h.leaving) return;
|
|
281
|
+
h.leaving = true;
|
|
282
|
+
this.engine.jobs.add(() => {
|
|
283
|
+
h.leaving = false;
|
|
284
|
+
const R = this.activeRadius;
|
|
285
|
+
if (h.built && !h.def.keep && this._dist(h, this.sources(FULL), R) > R * this.unloadFactor) this._unload(h);
|
|
286
|
+
}, { priority: UNLOAD }).catch(err => reportError(this.engine, err, 'stream unload', { soft: true }));
|
|
287
|
+
}
|
|
288
|
+
|
|
250
289
|
/** @internal */
|
|
251
290
|
_build(h, near) {
|
|
252
291
|
h.want = true;
|
|
253
292
|
if (this.live.has(h)) return; // still queued (was cancelled earlier, then came back in range)
|
|
254
293
|
this.live.add(h); this.queued++;
|
|
255
294
|
// a failed build is tried again the next time a stream source moves (want goes back to false); reported once, the game goes on without it
|
|
256
|
-
|
|
295
|
+
// counted down once: engine.add or a game dispose can throw after _built counted, and queued below 0 means ready is false for good
|
|
296
|
+
let open = true;
|
|
297
|
+
const settle = () => { if (open) { open = false; this.queued--; } };
|
|
298
|
+
const fail = err => { settle(); this.live.delete(h); h.want = false; reportError(this.engine, err, 'stream build', { soft: true }); };
|
|
257
299
|
this.engine.jobs.add(() => {
|
|
258
|
-
if (!h.want || !this.entries.has(h)) return this._built(h, null);
|
|
300
|
+
if (!h.want || !this.entries.has(h)) return this._built(h, null, settle);
|
|
259
301
|
const t0 = performance.now(), r = h.def.build(); // measure: the 'stream' stage of engine.budget.cost
|
|
260
302
|
this.engine.budget.cost.end('stream', t0);
|
|
261
|
-
if (r && typeof r.then === 'function') return r.then(obj => this._built(h, obj), fail);
|
|
262
|
-
this._built(h, r); // synchronous build: attach to the scene on the spot
|
|
303
|
+
if (r && typeof r.then === 'function') return r.then(obj => this._built(h, obj, settle), fail);
|
|
304
|
+
this._built(h, r, settle); // synchronous build: attach to the scene on the spot
|
|
263
305
|
}, { priority: (h.def.priority ?? 0) - near }).catch(fail);
|
|
264
306
|
}
|
|
265
307
|
/** @internal Build finished (obj null means nothing was built): discard it if no longer wanted, otherwise attach to the scene */
|
|
266
|
-
_built(h, obj) {
|
|
267
|
-
|
|
308
|
+
_built(h, obj, settle) {
|
|
309
|
+
settle();
|
|
268
310
|
if (!h.want || !this.entries.has(h)) { if (obj) this._dispose(h, obj); this.live.delete(h); return; }
|
|
269
311
|
h.object = obj; h.built = true;
|
|
270
312
|
if (obj && !obj.parent) this.engine.add(obj, { owner: 'stream' });
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
// InstancedMesh side of engine.batching (core/Batching.js): build / join / leave / dissolve / grow a batch, instance colors, bounds,
|
|
1
|
+
// InstancedMesh side of engine.batching (core/stream/Batching.js): build / join / leave / dissolve / grow a batch, instance colors, bounds,
|
|
2
2
|
// and the transform snapshots the per-frame check compares. B is the Batching instance; g a group (one cell + geometry + material + shadow flags);
|
|
3
3
|
// e an entry (one mesh of one placed object). Hidden instances are swap-removed, not zero-scaled (vegetation's way), so batch bounds stay tight.
|
|
4
4
|
import * as THREE from 'three';
|
|
5
|
-
import { copyPatches } from '
|
|
6
|
-
import { RESERVED_LAYERS } from '
|
|
5
|
+
import { copyPatches } from '../../render/patches.js';
|
|
6
|
+
import { RESERVED_LAYERS } from '../../render/layers.js';
|
|
7
|
+
import { noRaycast } from '../../render/occlusion.js';
|
|
7
8
|
|
|
8
|
-
const noRaycast = () => {};
|
|
9
9
|
/** Layer a batched original is moved to: the camera does not draw it (nor its shadow), engine.rays still tests it */
|
|
10
10
|
export const BATCH_LAYER = RESERVED_LAYERS.batched;
|
|
11
11
|
const WHITE = new THREE.Color(1, 1, 1);
|
|
@@ -14,11 +14,12 @@ const hold = (B, x, d) => { const n = (B.held.get(x) ?? 0) + d; if (n > 0) B.hel
|
|
|
14
14
|
|
|
15
15
|
function makeMesh(B, g, capacity) {
|
|
16
16
|
const im = new THREE.InstancedMesh(g.geometry, g.material, capacity);
|
|
17
|
-
|
|
17
|
+
// No DynamicDrawUsage: on WebGPURenderer it means a full refresh of every batch, every pass, every frame, and a batch rests almost always. three sees a write by the attribute's version either way
|
|
18
18
|
im.castShadow = g.cast; im.receiveShadow = g.receive;
|
|
19
19
|
im.matrixAutoUpdate = false; im.raycast = noRaycast; // rays hit the originals (on BATCH_LAYER), never the batch
|
|
20
20
|
im.userData = { budgetTag: 'batch', cell: g.cell };
|
|
21
21
|
g.mesh = im; B.byMesh.set(im, g); B.root.add(im);
|
|
22
|
+
if (!B.root.parent) B.engine.scene.add(B.root); // joins at the first batch: a scene with none is the game's alone
|
|
22
23
|
g.watch?.remove();
|
|
23
24
|
let version = -1; // the box follows the instances: a stale one would hide what stands elsewhere now
|
|
24
25
|
g.watch = B.engine.occlusion.watch([im], () => {
|
|
@@ -48,7 +49,7 @@ export function join(B, e) {
|
|
|
48
49
|
im.setMatrixAt(e.slot, m.matrixWorld); im.instanceMatrix.needsUpdate = true;
|
|
49
50
|
if (g.colored || B.tints.has(m)) color(B, e);
|
|
50
51
|
m.layers.set(BATCH_LAYER); m.userData.batched = true; // not visible = false: visibility stays the game's
|
|
51
|
-
g.dirty = true; B.live.add(e.info);
|
|
52
|
+
g.dirty = true; B.live.add(e.info); B._skipChanged(e);
|
|
52
53
|
}
|
|
53
54
|
/** Swap-remove an entry from its InstancedMesh and show its mesh again */
|
|
54
55
|
export function leave(B, g, e) {
|
|
@@ -60,7 +61,7 @@ export function leave(B, g, e) {
|
|
|
60
61
|
}
|
|
61
62
|
im.count = g.items.length; im.instanceMatrix.needsUpdate = true; g.dirty = true;
|
|
62
63
|
e.slot = -1;
|
|
63
|
-
const m = e.mesh; m.layers.set(0); delete m.userData.batched;
|
|
64
|
+
const m = e.mesh; m.layers.set(0); delete m.userData.batched; B._skipChanged(e);
|
|
64
65
|
localTint(B, m);
|
|
65
66
|
if (!e.info.entries.some(x => x.slot >= 0)) B.live.delete(e.info);
|
|
66
67
|
}
|
|
@@ -84,7 +85,7 @@ function grow(B, g) {
|
|
|
84
85
|
/** Write an entry's tint (white when none) into the batch's instance colors */
|
|
85
86
|
export function color(B, e) {
|
|
86
87
|
const g = e.group, im = g.mesh;
|
|
87
|
-
if (!im.instanceColor) { im.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(im.instanceMatrix.count * 3).fill(1), 3); g.colored = true; }
|
|
88
|
+
if (!im.instanceColor) { im.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(im.instanceMatrix.count * 3).fill(1), 3); g.colored = true; im.material.needsUpdate = true; } // three built this batch's shader (and its vertex buffers) before any instance color existed; without a rebuild the color never reaches the GPU
|
|
88
89
|
im.setColorAt(e.slot, B.tints.get(e.mesh) ?? WHITE); im.instanceColor.needsUpdate = true;
|
|
89
90
|
}
|
|
90
91
|
/** An unbatched mesh shows its tint through a cloned material (patches carried over); the original is kept for grouping and restored on clear */
|
|
@@ -121,4 +122,5 @@ export function same(o, s) {
|
|
|
121
122
|
}
|
|
122
123
|
/** Instance matrices are float32: compare against the float32 rounding of matrixWorld */
|
|
123
124
|
export function stored(a, slot, mw) { const el = mw.elements, o = slot * 16; for (let i = 0; i < 16; i++) if (a[o + i] !== Math.fround(el[i])) return false; return true; }
|
|
124
|
-
|
|
125
|
+
/** Is o inside a THREE.BundleGroup? three replays a bundle as recorded, so what is inside belongs to it: hiding a child from outside (a batch, an hlod swap) would do nothing */
|
|
126
|
+
export function inBundle(o) { for (let p = o; p; p = p.parent) if (p.isBundleGroup) return true; return false; }
|
|
@@ -9,6 +9,46 @@
|
|
|
9
9
|
// (make + register a queued chunk), _dispose(c) (release a chunk's content). Hooks passed here: show(c, visible), level(c, ring) (near-only
|
|
10
10
|
// detail per ring), count(c, ring) (instances drawn, for stats).
|
|
11
11
|
import * as THREE from 'three';
|
|
12
|
+
import { xzOf } from '../base/math.js';
|
|
13
|
+
|
|
14
|
+
const COLLIDER_LAG = 30; // fixed steps before a chunk's collision counts (30 = 0.5 s), times (1 + ring)
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Book the tick a queued chunk's collision takes effect (engine.commits): set from gameplay alone, so machine speed never changes it. Ring 1, which the
|
|
18
|
+
* loading screen waits for, counts the moment play starts. A table gives gen (bumped on a rebuild), so a ticket of a replaced chunk does nothing.
|
|
19
|
+
* @param {any} table @param {any} c @param {number} ring @param {{ apply: Function, fallback: Function }} steps
|
|
20
|
+
*/
|
|
21
|
+
export function bookCollision(table, c, ring, { apply, fallback }) {
|
|
22
|
+
c.ticket = table.engine.commits.request({
|
|
23
|
+
lag: !table.engine.ready && ring <= 1 ? 0 : COLLIDER_LAG * (1 + ring),
|
|
24
|
+
apply, fallback,
|
|
25
|
+
valid: () => table.chunks.get(c.key) === c && c.gen === table.gen,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Collision circles of solid chunks near (x, z): fn(cx, cz, r) @param {Map<string, any>} chunks @param {number} size chunk size */
|
|
30
|
+
export function collidersNear(chunks, size, x, z, range, fn) {
|
|
31
|
+
const x0 = Math.floor((x - range) / size), x1 = Math.floor((x + range) / size), z0 = Math.floor((z - range) / size), z1 = Math.floor((z + range) / size);
|
|
32
|
+
for (let cz = z0; cz <= z1; cz++) for (let cx = x0; cx <= x1; cx++) {
|
|
33
|
+
const c = chunks.get(cx + ',' + cz);
|
|
34
|
+
if (!c?.solid) continue;
|
|
35
|
+
for (const n in c.colliders) {
|
|
36
|
+
const k = c.colliders[n];
|
|
37
|
+
for (let i = 0; i < k.length; i += 3) {
|
|
38
|
+
const dx = k[i] - x, dz = k[i + 1] - z, rr = range + k[i + 2];
|
|
39
|
+
if (dx * dx + dz * dz < rr * rr) fn(k[i], k[i + 1], k[i + 2]);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Does ok(chunk or undefined, cx, cz) hold for every chunk within `rings` rings of a position? @param {Map<string, any>} chunks @param {number} size chunk size */
|
|
46
|
+
export function ringsReady(chunks, size, position, rings, ok) {
|
|
47
|
+
const [x, z] = xzOf(position), pcx = Math.floor(x / size), pcz = Math.floor(z / size);
|
|
48
|
+
for (let cz = pcz - rings; cz <= pcz + rings; cz++) for (let cx = pcx - rings; cx <= pcx + rings; cx++)
|
|
49
|
+
if (!ok(chunks.get(cx + ',' + cz), cx, cz)) return false;
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
12
52
|
|
|
13
53
|
export class ChunkStream {
|
|
14
54
|
/** @param {any} table @param {{ show: Function, level: Function, count: Function, inArea?: Function }} hooks */
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
// mulberry32 whose state can be reset: each placement attempt gets its own stream, so skipping an attempt (edited ground, failed rule)
|
|
6
6
|
// never shifts the random numbers of later attempts -- the other trees stay put and felled-tree ids stay valid
|
|
7
|
-
import { mulberry32 } from '
|
|
7
|
+
import { mulberry32 } from '../base/mulberry32.js';
|
|
8
8
|
|
|
9
9
|
function stream() {
|
|
10
10
|
const st = { state: 0 };
|
|
@@ -55,12 +55,15 @@ function bucketsOf(rule, CHUNK) {
|
|
|
55
55
|
/**
|
|
56
56
|
* Placement over one ground. chunk: edge length (m); seed: placement seed; surface / slope / typeAt (x, z): the ground;
|
|
57
57
|
* skip(x, z): true where nothing may grow (edited terrain cells, flattened plots when the rule says avoidFlat), optional.
|
|
58
|
-
* place(cx, cz, rule, density) returns instance matrices (column-major, chunk-local x / z), instance colors, collision circles (world x, z, radius)
|
|
58
|
+
* place(cx, cz, rule, density) (density thins only rules without a collider: blocking plants are the same at every quality) returns instance matrices (column-major, chunk-local x / z), instance colors, collision circles (world x, z, radius)
|
|
59
59
|
* and stable ids (the attempt index, independent of density; with rule.positions the index in that list).
|
|
60
60
|
* rule.positions replaces the random attempts: every listed spot in this chunk gets one instance at the ground height (scale / yaw from the entry
|
|
61
61
|
* or the rule's random ranges); the scatter filters (perChunk, chance, cluster, heights, slope, biomes, avoidFlat) and density do not apply --
|
|
62
62
|
* the game already chose the spot. skip still applies: dug or raised ground loses what grew there either way.
|
|
63
63
|
*/
|
|
64
|
+
/** How many attempts of a scatter rule a density keeps. One formula, because the vegetation draw side cuts by the same number: placing and drawing must agree on which plants a density means */
|
|
65
|
+
export const scatterAttempts = (rule, density) => Math.round((rule.perChunk ?? RULE.perChunk) * density);
|
|
66
|
+
|
|
64
67
|
export function makePlacer({ chunk: CHUNK, seed, surface, slope, typeAt, fbm, skip = null, flat = null }) {
|
|
65
68
|
const SEED = seed | 0;
|
|
66
69
|
return function place(cx, cz, rule, density = 1) {
|
|
@@ -68,7 +71,7 @@ export function makePlacer({ chunk: CHUNK, seed, surface, slope, typeAt, fbm, sk
|
|
|
68
71
|
const base = Math.imul(cx, 92821) ^ Math.imul(cz, 68917) ^ SEED ^ Math.imul(r.salt + 1, 40503), rnd = stream();
|
|
69
72
|
const ox = cx * CHUNK, oz = cz * CHUNK;
|
|
70
73
|
const listed = rule?.positions ? bucketsOf(rule, CHUNK).get(cx + ',' + cz) ?? [] : null;
|
|
71
|
-
const attempts = listed ? listed.length :
|
|
74
|
+
const attempts = listed ? listed.length : scatterAttempts(r, r.collider ? 1 : density); // a plant that blocks (or is felled by id) is part of the world: quality density thins only what is decoration
|
|
72
75
|
const m = new Float32Array(attempts * 16), c = new Float32Array(attempts * 3), k = new Float32Array(r.collider ? attempts * 3 : 0), ids = new Uint32Array(attempts);
|
|
73
76
|
let n = 0;
|
|
74
77
|
// one instance at local (lx, lz) on height h; s / yaw null = drawn from the rule's ranges. The same code for both paths, so a listed plant
|
|
@@ -111,7 +114,7 @@ export function makePlacer({ chunk: CHUNK, seed, surface, slope, typeAt, fbm, sk
|
|
|
111
114
|
if (roll > t * t * 0.9 + 0.03) continue;
|
|
112
115
|
} else if (roll > (r.chance ?? 1)) continue;
|
|
113
116
|
const h = surface(wx, wz), sl = slope(wx, wz);
|
|
114
|
-
if (h < r.minHeight || h > r.maxHeight || sl > r.maxSlope) continue;
|
|
117
|
+
if (!Number.isFinite(h) || h < r.minHeight || h > r.maxHeight || sl > r.maxSlope) continue; // a provider's -Infinity is no ground: a plant there is a NaN matrix
|
|
115
118
|
if (r.biomes) { const b = typeAt(wx, wz, h, sl); const w = r.biomes[b]; if (!w || rnd() > w) continue; }
|
|
116
119
|
if (r.avoidFlat && flat?.(wx, wz)) continue;
|
|
117
120
|
put(a, lx, lz, h, null, null); // stable id: attempt index. Independent of density under one seed (density only sets how many attempts), felled-tree records rely on it
|
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
// Stream sources (internal half of engine.stream): the places the world must be loaded around (the streaming-source idea of Unreal World Partition).
|
|
2
2
|
// Every distance-based loader reads this list and nothing else: stream entries, world models (present), terrain chunks, hlod near/far and rigid-body terrain colliders.
|
|
3
|
-
// engine.stream.player built in: the
|
|
3
|
+
// engine.stream.player built in: the player (engine.focus without one); full detail + physics
|
|
4
4
|
// engine.stream.camera built in: engine.focus; full detail, no physics (a cutscene or photo camera far away gets a picture, not colliders)
|
|
5
5
|
// const s = engine.stream.source([800, 0, 300], { radius: 64 }); await s.whenReady; ... s.remove();
|
|
6
6
|
// await engine.stream.teleport([800, 0, 300]); // the player moves only after the destination is loaded (terrain, collision, nearby models)
|
|
7
7
|
// Display, physics and world data are three separate things: a source decides what is shown and what has colliders; world records are never deleted by unloading,
|
|
8
|
-
// and near / far simulation follows world.anchor (recipe 18). Readiness is per source: each loader registers a check with
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
8
|
+
// and near / far simulation follows world.anchor (recipe 18). Readiness is per source: each loader registers a check with addReadyCheck.
|
|
9
|
+
import { xzOf } from '../base/math.js';
|
|
10
|
+
import { codedError } from '../base/errorHints.js';
|
|
11
|
+
import { fmt } from '../base/validate.js';
|
|
12
|
+
|
|
13
|
+
const removedError = s => codedError('stream-removed', fmt(SOURCE_STRINGS.removed, { name: s.name }));
|
|
12
14
|
|
|
13
15
|
export const SOURCE_KEYS = ['radius', 'detail', 'physics', 'until', 'name'];
|
|
14
16
|
export const SOURCE_STRINGS = {
|
|
15
17
|
detail: 'stream.source(): detail must be \'full\' (models, stream entries, physics) or \'simple\' (terrain and hlod proxies only), got {got}',
|
|
16
|
-
removed: 'stream source "{name}" was removed before it was ready (remove()
|
|
18
|
+
removed: 'stream source "{name}" was removed before it was ready (remove(), its until, or engine.dispose()); nothing waits for it any more',
|
|
19
|
+
abandoned: 'stream.teleport(): the game state was replaced (new game, load) before the destination ({x}, {z}) was ready; the trip was abandoned and the player was not moved',
|
|
17
20
|
timeout: 'stream.teleport(): the destination ({x}, {z}) was not ready after {t} s; still waiting on: {checks}. The player was not moved',
|
|
18
21
|
};
|
|
19
22
|
|
|
@@ -41,7 +44,10 @@ export class Source {
|
|
|
41
44
|
/** Everything this source asks for is loaded (checked once per frame, at the end of the frame) @type {boolean} */
|
|
42
45
|
get ready() { return this._ready; }
|
|
43
46
|
/** Promise that resolves when ready becomes true @type {Promise<void>} */
|
|
44
|
-
get whenReady() {
|
|
47
|
+
get whenReady() {
|
|
48
|
+
if (this._ready) return Promise.resolve();
|
|
49
|
+
return new Promise((res, rej) => { this._waiters.push({ res, rej }); if (this.removed) this._settle(removedError(this)); }); // asked after remove(): nothing would settle it
|
|
50
|
+
}
|
|
45
51
|
/** @internal settle every waiter: resolve, or reject with err */
|
|
46
52
|
_settle(err) { for (const w of this._waiters.splice(0)) if (err) w.rej(err); else w.res(); }
|
|
47
53
|
/**
|
|
@@ -57,6 +63,6 @@ export class Source {
|
|
|
57
63
|
remove() {
|
|
58
64
|
if (this.removed) return;
|
|
59
65
|
this.removed = true; this.stream._sources.delete(this); this.stream._version++;
|
|
60
|
-
this._settle(
|
|
66
|
+
this._settle(removedError(this)); // an await on whenReady never hangs
|
|
61
67
|
}
|
|
62
68
|
}
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
// that depends on machine speed and background-thread queueing -- but on a fixed-step tick decided when the request is made:
|
|
4
4
|
// const t = engine.commits.request({ apply: r => change gameplay state with the result, fallback: () => compute the same result on the main thread now, valid: () => still wanted? });
|
|
5
5
|
// when the background work finishes: t.resolve(result); when no longer wanted: t.remove()
|
|
6
|
-
// At the due tick (engine.tick at request + lag, default 30 steps = 0.5 s) requests take effect in a stable order (due tick, then request order):
|
|
6
|
+
// At the due tick (engine.time.tick at request + lag, default 30 steps = 0.5 s) requests take effect in a stable order (due tick, then request order):
|
|
7
7
|
// finished -> apply(result); not finished -> apply(fallback()) (stats.late +1; a background result that arrives later is ignored); valid() false -> dropped.
|
|
8
|
-
// A save load or level change (invalidate) drops the requests that have no valid: they were made for the old world. A request with valid decides itself
|
|
8
|
+
// A save load or level change (invalidate) drops the requests that have no valid: they were made for the old world (a load that fails gives them back: the old world stays). A request with valid decides itself
|
|
9
9
|
// (terrain colliders survive a load because the terrain is the same; pass valid when your result belongs to state a load replaces).
|
|
10
10
|
// So sync, async, delayed or out-of-order returns all give the same gameplay state at the same tick for the same input. Fixed steps do not run while frozen, so due time stops too.
|
|
11
11
|
// Requests registered during loading (before engine.ready): start() calls rebase() when done and timing restarts from the playable moment (load time varies by machine and must not count); lag 0 takes effect right then.
|
|
@@ -16,7 +16,8 @@ const STRINGS = { noFallback: 'commits.request() needs a fallback: it is compute
|
|
|
16
16
|
* engine.commits: background results that affect gameplay take effect on a fixed-step tick decided at request time, in a stable order; if not finished when due, the fallback is computed on the main thread.
|
|
17
17
|
* Sync, async, delayed and out-of-order returns give the same gameplay state at the same tick for the same input. Results that only affect visuals need not go through here.
|
|
18
18
|
*/
|
|
19
|
-
import { codedError } from '
|
|
19
|
+
import { codedError } from '../base/errorHints.js';
|
|
20
|
+
import { reportError } from '../base/errors.js';
|
|
20
21
|
|
|
21
22
|
export class Commits {
|
|
22
23
|
/** @internal */
|
|
@@ -43,7 +44,7 @@ export class Commits {
|
|
|
43
44
|
request(opts) {
|
|
44
45
|
const { apply, fallback, valid = null, lag = this.lag } = opts;
|
|
45
46
|
if (typeof fallback !== 'function') throw codedError('commit-fallback', STRINGS.noFallback);
|
|
46
|
-
const t = { due: this.engine.tick + Math.max(1, lag), lag, seq: this._seq++, apply, fallback, valid, epoch: this.epoch, done: false, result: undefined, canceled: false };
|
|
47
|
+
const t = { due: this.engine.time.tick + Math.max(1, lag), lag, seq: this._seq++, apply, fallback, valid, epoch: this.epoch, done: false, result: undefined, canceled: false };
|
|
47
48
|
this._insert(t);
|
|
48
49
|
const remove = () => { t.canceled = true; };
|
|
49
50
|
return { due: t.due, resolve: r => { if (!t.done) { t.done = true; t.result = r; } }, remove };
|
|
@@ -59,19 +60,24 @@ export class Commits {
|
|
|
59
60
|
while (this.queue.length && this.queue[0].due <= now) {
|
|
60
61
|
const t = this.queue.shift();
|
|
61
62
|
if (t.canceled || (t.valid ? !t.valid() : t.epoch !== this.epoch)) { this.stats.dropped++; continue; }
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
63
|
+
// each request on its own: one that throws must not push the next ones due to a later tick, or to never, in a frozen dev game
|
|
64
|
+
try {
|
|
65
|
+
if (!t.done) { t.result = t.fallback(); t.done = true; this.stats.late++; }
|
|
66
|
+
if (t.canceled) { this.stats.dropped++; continue; } // the fallback itself gave up on the request (a job that failed): nothing to apply
|
|
67
|
+
t.apply(t.result);
|
|
68
|
+
this.stats.applied++;
|
|
69
|
+
} catch (err) { reportError(this.engine, err, 'background result apply (commits)'); }
|
|
65
70
|
}
|
|
66
71
|
}
|
|
67
|
-
/** @internal Called when start() finishes loading: pending requests restart timing from now (due = now + lag); lag 0 takes effect immediately */
|
|
72
|
+
/** @internal Called when start() finishes loading and when a new playthrough restarts the tick: pending requests restart timing from now (due = now + lag); lag 0 takes effect immediately */
|
|
68
73
|
rebase() {
|
|
69
|
-
const now = this.engine.tick, list = this.queue.splice(0);
|
|
74
|
+
const now = this.engine.time.tick, list = this.queue.splice(0);
|
|
70
75
|
for (const t of list) { t.due = now + t.lag; this._insert(t); }
|
|
71
76
|
this.tick(now);
|
|
72
77
|
}
|
|
73
78
|
/** @internal Drop all requests (engine.dispose calls it) */
|
|
74
79
|
dispose() { this.queue.length = 0; }
|
|
75
|
-
/** @internal A save load or level change replaced the world: results requested for the old one must not land on the new one (counted as dropped)
|
|
76
|
-
|
|
80
|
+
/** @internal A save load or level change replaced the world: results requested for the old one must not land on the new one (counted as dropped).
|
|
81
|
+
* Returns undo() for a load that failed; a level change since then keeps them dropped, the world they were for has been rebuilt */
|
|
82
|
+
invalidate() { const was = this.epoch, mine = ++this.epoch; return () => { if (this.epoch === mine) this.epoch = was; }; }
|
|
77
83
|
}
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// Jobs that change gameplay state pass apply: the result takes effect on a fixed tick through engine.commits, not on whichever frame the work finished (machine speed must not affect gameplay):
|
|
7
7
|
// engine.jobs.add(function* () { ...compute...; yield; ...; return result; }, { apply: result => changeGameplayState })
|
|
8
8
|
// If the job is not done by the due tick, the remaining steps run to completion on the spot, so such a job must be a plain function or generator (it cannot return a Promise).
|
|
9
|
+
// Those steps are capped by maxSteps too: a generator that never ends would hang the fixed step, so past the cap its promise rejects with jobs-endless and apply does not run.
|
|
9
10
|
// With apply, the returned Promise resolves when the work finishes, which may be before apply runs (it waits for the fixed tick); put anything that needs "state already changed" inside apply, do not assume it after await.
|
|
10
11
|
// A single step that is too slow (one next() over slowStepMs in the real-time loop) warns once in dev: add more yields to a loop to slice it, since the budget only limits how many steps run, it cannot split one step.
|
|
11
12
|
// Two ways to advance:
|
|
@@ -13,10 +14,13 @@
|
|
|
13
14
|
// Deterministic (engine.step(), headless loading): ignores real time and drains the queue on each run (generators run to the end);
|
|
14
15
|
// to stop jobs that keep adding jobs from hanging, one run takes at most maxSteps steps (default 100000), warns once past that, and continues next frame.
|
|
15
16
|
// The queue is a binary heap (priority, then insertion order), so thousands of queued builds stay fast.
|
|
16
|
-
import { warnOnce } from '
|
|
17
|
-
import { codedError, coded } from '
|
|
17
|
+
import { warnOnce, fmt } from '../base/validate.js';
|
|
18
|
+
import { codedError, coded } from '../base/errorHints.js';
|
|
18
19
|
|
|
19
|
-
const STRINGS = { slow: 'engine.jobs:
|
|
20
|
+
const STRINGS = { slow: 'engine.jobs: a step of {who} took {ms} ms (over {max}) and will hitch the frame; add more yield calls in its loop to slice it, or give the function a name so this line can say which', async: 'engine.jobs.add(..., { apply }): a job that changes gameplay state cannot return a Promise (it must be finishable on the spot when due); make it a plain function or generator', endless: 'engine.jobs: {who} with apply was due and did not finish within {n} steps (engine.jobs.maxSteps), so it was stopped and its apply will not run. Make the generator end, or give it a later lag', tooMany: 'engine.jobs: deterministic advance (step / headless) did not finish within {n} steps, next up {who}; the rest continues next frame. If that job adds new jobs each time, end the chain' };
|
|
21
|
+
|
|
22
|
+
/** A job as a message names it: the function it was given */
|
|
23
|
+
const jobName = j => j.work?.name ? `job ${j.work.name}` : 'an unnamed job';
|
|
20
24
|
|
|
21
25
|
// a runs before b: higher priority first, then earlier insertion
|
|
22
26
|
const before = (a, b) => a.priority > b.priority || (a.priority === b.priority && a.seq < b.seq);
|
|
@@ -29,19 +33,19 @@ export class Jobs {
|
|
|
29
33
|
/** @internal */
|
|
30
34
|
constructor(engine) {
|
|
31
35
|
/** @internal */ this.engine = engine;
|
|
32
|
-
/** Milliseconds allowed per frame, default 3 */
|
|
36
|
+
/** Milliseconds allowed per frame, default 3 @experimental */
|
|
33
37
|
this.budgetMs = 3;
|
|
34
|
-
/** Milliseconds allowed per frame while the loading screen is up, default 12 */
|
|
38
|
+
/** Milliseconds allowed per frame while the loading screen is up, default 12 @experimental */
|
|
35
39
|
this.loadingMs = 12;
|
|
36
|
-
/** Max steps per deterministic run (stops jobs that keep adding jobs from hanging), default 100000 */
|
|
40
|
+
/** Max steps per deterministic run (stops jobs that keep adding jobs from hanging), default 100000 @experimental */
|
|
37
41
|
this.maxSteps = 100000;
|
|
38
|
-
/** A step slower than this many ms warns in dev (default 8) */
|
|
42
|
+
/** A step slower than this many ms warns in dev (default 8) @experimental */
|
|
39
43
|
this.slowStepMs = 8;
|
|
40
44
|
/** @internal */ this.heap = [];
|
|
41
45
|
/** @internal */ this._seq = 0;
|
|
42
46
|
/** @internal Total finished jobs (for describe) */ this.doneCount = 0;
|
|
43
47
|
}
|
|
44
|
-
/** Number of jobs not yet finished @returns {number} */
|
|
48
|
+
/** Number of jobs not yet finished @returns {number} @experimental */
|
|
45
49
|
get pending() { return this.heap.length; }
|
|
46
50
|
/** @internal Drop queued jobs (called by engine.dispose; their Promises never settle) */
|
|
47
51
|
dispose() { this.heap.length = 0; }
|
|
@@ -67,8 +71,14 @@ export class Jobs {
|
|
|
67
71
|
}
|
|
68
72
|
/** @internal Not done by the due tick: run the remaining steps now and return the result */
|
|
69
73
|
_finishNow(j) {
|
|
70
|
-
|
|
71
|
-
|
|
74
|
+
// same cap as run(): the fixed step cannot wait for "next frame", so an endless generator fails here instead of hanging the page
|
|
75
|
+
for (let n = 0; !j.finished && !j.failed; n++) {
|
|
76
|
+
if (n >= this.maxSteps) { this._fail(j, codedError('jobs-endless', fmt(STRINGS.endless, { who: jobName(j), n: this.maxSteps }))); break; }
|
|
77
|
+
this._step(j);
|
|
78
|
+
}
|
|
79
|
+
// A job that fails here already told its caller through the promise (j.rej). Throwing again from the fixed step would freeze the game a second time
|
|
80
|
+
// for the same error, and apply(undefined) must not run: cancel the ticket, and Commits.tick drops a canceled request after its fallback
|
|
81
|
+
if (j.failed) { j.ticket?.remove(); return undefined; }
|
|
72
82
|
return j.value;
|
|
73
83
|
}
|
|
74
84
|
/**
|
|
@@ -81,7 +91,7 @@ export class Jobs {
|
|
|
81
91
|
if (deterministic) {
|
|
82
92
|
let n = 0;
|
|
83
93
|
while (this.heap.length && n++ < this.maxSteps) this._stepTop();
|
|
84
|
-
if (this.heap.length) warnOnce(coded('jobs-slow', STRINGS.tooMany
|
|
94
|
+
if (this.heap.length) warnOnce(coded('jobs-slow', fmt(STRINGS.tooMany, { n: this.maxSteps, who: jobName(this.heap[0]) })));
|
|
85
95
|
return;
|
|
86
96
|
}
|
|
87
97
|
const end = performance.now() + (this.engine.ready ? this.budgetMs : Math.max(this.budgetMs, this.loadingMs)); // measure: frame budget
|
|
@@ -101,11 +111,13 @@ export class Jobs {
|
|
|
101
111
|
}
|
|
102
112
|
const s = j.it.next();
|
|
103
113
|
if (s.done) this._finish(j, s.value);
|
|
104
|
-
} catch (err) { this.
|
|
114
|
+
} catch (err) { this._fail(j, err); }
|
|
105
115
|
const ms = performance.now() - t0; // measure: step time
|
|
106
|
-
if (ms > this.slowStepMs && this.engine.ready) warnOnce(coded('jobs-slow', STRINGS.slow
|
|
116
|
+
if (ms > this.slowStepMs && this.engine.ready) warnOnce(coded('jobs-slow', fmt(STRINGS.slow, { who: jobName(j), ms: Math.round(ms), max: this.slowStepMs })));
|
|
107
117
|
}
|
|
108
118
|
/** @internal */
|
|
119
|
+
_fail(j, err) { this._removeJob(j); j.failed = true; j.error = err; j.rej(err); }
|
|
120
|
+
/** @internal */
|
|
109
121
|
_finish(j, v) {
|
|
110
122
|
if (j.ticket && typeof v?.then === 'function') throw codedError('engine-misuse', STRINGS.async);
|
|
111
123
|
this._removeJob(j); this.doneCount++; j.finished = true; j.value = v; j.ticket?.resolve(v); j.res(v);
|