threedog 0.0.0-stage → 0.1.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 +267 -0
- package/core/Assets.js +240 -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/Describe.js +134 -0
- package/core/Engine.js +221 -0
- package/core/Events.js +95 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +97 -0
- package/core/InspectScene.js +187 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/Ops.js +272 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +253 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +93 -0
- package/core/Vars.js +34 -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/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/dayTime.js +15 -0
- package/core/describeText.js +136 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +172 -0
- package/core/errorHints.js +203 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -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 +68 -0
- package/core/lightWatch.js +36 -0
- package/core/loop.js +199 -0
- package/core/math.js +33 -0
- package/core/modules.js +182 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsCheck.js +86 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/page.js +78 -0
- package/core/pureWorker.js +5 -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 +125 -0
- package/core/screenToGround.js +39 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +133 -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/thingOps.js +157 -0
- package/core/things.js +198 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/validate.js +188 -0
- package/docs/AI.md +149 -0
- package/docs/API.md +84 -0
- package/docs/CODEMAP.md +335 -0
- package/docs/COMMANDS.md +96 -0
- package/docs/CONVENTIONS.md +134 -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 +60 -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 +142 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +35 -0
- package/docs/api/content.md +63 -0
- package/docs/api/debug.md +10 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +190 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +91 -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 +9 -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 +31 -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 +55 -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 +151 -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 +104 -0
- package/docs/recipes/07-flow-scenes-pause.md +128 -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 +57 -0
- package/docs/recipes/13-animation.md +146 -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 +146 -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 +104 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +139 -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 +35 -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 +81 -0
- package/docs/recipes/40-scene.md +79 -0
- package/docs/recipes/41-thing-registry.md +64 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +118 -0
- package/docs/recipes/44-water-weather-look-hooks.md +133 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +92 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -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 +9 -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/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +108 -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 +279 -0
- package/index.js +120 -0
- package/llms.txt +56 -0
- package/modules/ambience/Ambience.js +183 -0
- package/modules/camera/FirstPersonCamera.js +133 -0
- package/modules/camera/FixedCamera.js +155 -0
- package/modules/camera/FollowCamera.js +85 -0
- package/modules/camera/RtsCamera.js +134 -0
- package/modules/camera/common.js +152 -0
- package/modules/camera/index.js +11 -0
- package/modules/characters/Character.js +223 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +59 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +212 -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 +38 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +144 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +107 -0
- package/modules/characters/pathJob.js +61 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +54 -0
- package/modules/collision/Collision.js +176 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +152 -0
- package/modules/content/loader.js +187 -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 +133 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +168 -0
- package/modules/entities/Entities.js +239 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +98 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +216 -0
- package/modules/gameplay/Interactions.js +243 -0
- package/modules/gameplay/Inventory.js +214 -0
- package/modules/gameplay/Quests.js +195 -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 +113 -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 +75 -0
- package/modules/hlod/index.js +164 -0
- package/modules/hud/index.js +164 -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 +231 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +224 -0
- package/modules/music/Music.js +290 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +154 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +136 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +75 -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 +143 -0
- package/modules/rigid/RigidBodies.js +262 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +294 -0
- package/modules/settings/apply.js +20 -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 +257 -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 +115 -0
- package/modules/sky/fog.js +136 -0
- package/modules/sky/frame.js +76 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +50 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +80 -0
- package/modules/sky/skyModule.js +59 -0
- package/modules/terrain/ChunkManager.js +291 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +110 -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 +249 -0
- package/modules/timeline/Tween.js +118 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +88 -0
- package/modules/triggers/index.js +261 -0
- package/modules/vegetation/Vegetation.js +255 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +40 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +144 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +251 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/index.js +64 -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/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +243 -0
- package/render/detail.js +105 -0
- package/render/effects.js +142 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +72 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +16 -0
- package/render/materials.js +203 -0
- package/render/patches.js +252 -0
- package/render/surface.js +67 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1773 -0
- package/types/gameplay.d.ts +1812 -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/Events.d.ts +46 -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 +162 -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 +161 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -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 +64 -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 +152 -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 +72 -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 +128 -0
- package/types/generated/render/materials.d.ts +90 -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 +584 -0
- package/types/style.d.ts +628 -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 +195 -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/Budget.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// Performance budget, engine.budget: the game sets limits (only categories given are checked); on overrun it reports which category and who uses the most.
|
|
2
|
+
// createEngine({ budget: { drawCalls: 250, fps: 55 } }) or engine.budget.enable({ drawCalls: 250 })
|
|
3
|
+
// engine.budget.report() // { ok, over: [{ category, value, limit, top }] }; null when off
|
|
4
|
+
// Off by default; when off, sample() returns immediately and costs nothing. The engine presets no limit numbers.
|
|
5
|
+
// Categories: drawCalls, triangles, textures, cpuMs, fps, low1 (the last two are lower bounds) + module-registered metrics (chunkApplyMs, rigidBodies...)
|
|
6
|
+
// + the apply-cost stages (applyTransitMs, applyBuildMs, applyColliderMs, applyUploadMs, applyStreamMs: ms per frame, see ApplyCost).
|
|
7
|
+
// "Who uses the most": draw calls are estimated by the userData.budgetTag of an object (or its parent); untagged counts as 'other'.
|
|
8
|
+
/** @import { Handle } from '../types/common' */
|
|
9
|
+
/** @import { BudgetLimits, BudgetReport, BudgetTagStat } from '../types/world' */
|
|
10
|
+
import { coded } from './errorHints.js';
|
|
11
|
+
import { fmt } from './validate.js';
|
|
12
|
+
import { r1 } from './math.js';
|
|
13
|
+
import { SHADOW_TYPES } from './shadowTypes.js';
|
|
14
|
+
import * as THREE from 'three';
|
|
15
|
+
|
|
16
|
+
const STRINGS = {
|
|
17
|
+
startup: 'Startup took {value} ms, over budget startupMs {limit} ms; slowest module: {top}',
|
|
18
|
+
module: 'Module {name} took {value} ms to start, over budget moduleMs {limit} ms (init + waiting for ready)',
|
|
19
|
+
over: 'Performance budget exceeded: {category} = {value} ({dir} {limit}). Most draw calls: {top}',
|
|
20
|
+
min: 'minimum', max: 'maximum',
|
|
21
|
+
};
|
|
22
|
+
const LOWER = new Set(['fps', 'low1']); // these two are lower bounds ("not below")
|
|
23
|
+
const WINDOW = 300; // how many recent frames the frame-rate stats use
|
|
24
|
+
|
|
25
|
+
/** Cost stages of bringing a background result into the frame, in the order a chunk goes through them */
|
|
26
|
+
const STAGES = ['transit', 'build', 'collider', 'upload', 'stream'];
|
|
27
|
+
const EMA = 0.1; // per-frame smoothing, the same factor chunkApplyMs always used
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* engine.budget.cost: where the main thread pays for background results (terrain chunks, vegetation, colliders, stream builds), split in stages.
|
|
31
|
+
* Always on (a few performance.now() calls per applied result). Stages: transit = worker round trip minus the worker's own compute (queueing,
|
|
32
|
+
* structured clone, waiting for a busy main thread: an async wait, not main-thread blocking, so it is an approximation); build = creating the
|
|
33
|
+
* three.js objects (geometry, meshes, instanced meshes); collider = physics colliders; upload = GPU upload and shader compile, approximated as the
|
|
34
|
+
* extra render time of frames that first draw new objects over the average render time of other frames; stream = the synchronous part of a stream
|
|
35
|
+
* build() callback.
|
|
36
|
+
*/
|
|
37
|
+
export class ApplyCost {
|
|
38
|
+
/** @internal */
|
|
39
|
+
constructor() {
|
|
40
|
+
/** @internal */ this.t = {};
|
|
41
|
+
for (const k of STAGES) this.t[k] = { n: 0, totalMs: 0, maxMs: 0, frameMs: 0, bytes: 0, _cur: 0 };
|
|
42
|
+
/** @internal */ this._fresh = 0;
|
|
43
|
+
/** @internal */ this._base = -1;
|
|
44
|
+
}
|
|
45
|
+
/** @internal Add ms to a stage (bytes: payload size, transit only) */
|
|
46
|
+
add(stage, ms, bytes = 0) {
|
|
47
|
+
const s = this.t[stage];
|
|
48
|
+
s.n++; s.totalMs += ms; s._cur += ms; s.bytes += bytes;
|
|
49
|
+
if (ms > s.maxMs) s.maxMs = ms;
|
|
50
|
+
}
|
|
51
|
+
/** @internal Close a span started with performance.now(); build and stream spans create objects the next render uploads */
|
|
52
|
+
end(stage, t0) {
|
|
53
|
+
this.add(stage, performance.now() - t0); // measure
|
|
54
|
+
if (stage === 'build' || stage === 'stream') this._fresh++;
|
|
55
|
+
}
|
|
56
|
+
/** @internal A worker result arrived: t0 is when its job was sent, r.ms what the worker spent computing it */
|
|
57
|
+
transit(t0, r) {
|
|
58
|
+
const t = r.terrain, bytes = t ? t.pos.byteLength + t.nor.byteLength + t.col.byteLength + t.uv.byteLength : 0;
|
|
59
|
+
this.add('transit', Math.max(0, performance.now() - t0 - (r.ms ?? 0)), bytes); // measure
|
|
60
|
+
}
|
|
61
|
+
/** @internal One render finished (ms): a frame that drew new objects pays the upload, the others set the baseline. Also rolls the per-frame smoothing */
|
|
62
|
+
rendered(ms) {
|
|
63
|
+
if (this._fresh) { if (this._base >= 0) this.add('upload', Math.max(0, ms - this._base)); this._fresh = 0; }
|
|
64
|
+
else this._base = this._base < 0 ? ms : this._base + (ms - this._base) * EMA;
|
|
65
|
+
for (const k of STAGES) { const s = this.t[k]; s.frameMs += (s._cur - s.frameMs) * EMA; s._cur = 0; }
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Per stage: n results, totalMs, maxMs of one result, frameMs (smoothed ms per frame), bytes (transit only)
|
|
69
|
+
* @returns {Record<string, { n: number, totalMs: number, maxMs: number, frameMs: number, bytes: number }>}
|
|
70
|
+
* @example engine.budget.cost.report().build // { n: 12, totalMs: 9.4, maxMs: 1.8, frameMs: 0.2, bytes: 0 }
|
|
71
|
+
*/
|
|
72
|
+
report() {
|
|
73
|
+
const out = /** @type {any} */ ({});
|
|
74
|
+
for (const k of STAGES) { const s = this.t[k]; out[k] = { n: s.n, totalMs: r1(s.totalMs), maxMs: r1(s.maxMs), frameMs: r1(s.frameMs), bytes: s.bytes }; }
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
/** Forget what was counted so far (to measure one scene on its own) */
|
|
78
|
+
reset() { for (const k of STAGES) Object.assign(this.t[k], { n: 0, totalMs: 0, maxMs: 0, frameMs: 0, bytes: 0, _cur: 0 }); }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** engine.budget: performance budget (turned on by createEngine({ budget }) or enable(); off by default, costs nothing). */
|
|
82
|
+
export class Budget {
|
|
83
|
+
/** @internal */
|
|
84
|
+
constructor(engine) {
|
|
85
|
+
/** @internal */ this.engine = engine;
|
|
86
|
+
/** Is it on? */
|
|
87
|
+
this.enabled = false;
|
|
88
|
+
/** Current limits @type {BudgetLimits} */
|
|
89
|
+
this.limits = {};
|
|
90
|
+
/** @internal Module-defined categories: name -> { read, limit } @type {Map<string, { read: () => number, limit?: number }>} */
|
|
91
|
+
this.metrics = new Map();
|
|
92
|
+
/** @internal */ this._dts = [];
|
|
93
|
+
/** @internal */ this._cpu = [];
|
|
94
|
+
/** @internal */ this._t = 0;
|
|
95
|
+
/** @internal @type {any} */ this._last = null;
|
|
96
|
+
/** Cost of applying background results, split in stages (see ApplyCost) */
|
|
97
|
+
this.cost = new ApplyCost();
|
|
98
|
+
for (const k of STAGES) this.metric('apply' + k[0].toUpperCase() + k.slice(1) + 'Ms', () => this.cost.t[k].frameMs);
|
|
99
|
+
/** @internal */ this._warned = new Set();
|
|
100
|
+
/** @internal */ this._frustum = new THREE.Frustum();
|
|
101
|
+
/** @internal */ this._m = new THREE.Matrix4();
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Turn on and set limits (only categories given are checked)
|
|
105
|
+
* @param {BudgetLimits} [limits]
|
|
106
|
+
* @returns {this}
|
|
107
|
+
* @example engine.budget.enable({ drawCalls: 250, fps: 55 });
|
|
108
|
+
*/
|
|
109
|
+
enable(limits = {}) { this.enabled = true; this.limits = { ...limits }; this._dts = []; this._cpu = []; this._last = null; return this; }
|
|
110
|
+
/** Turn off */
|
|
111
|
+
disable() { this.enabled = false; this._last = null; }
|
|
112
|
+
/**
|
|
113
|
+
* Module-defined category: read() returns the current value, opts.limit is the limit (the game's enable() takes precedence). Returns a handle { remove() }
|
|
114
|
+
* @param {string} name
|
|
115
|
+
* @param {() => number} read
|
|
116
|
+
* @param {{ limit?: number }} [opts]
|
|
117
|
+
* @returns {Handle}
|
|
118
|
+
*/
|
|
119
|
+
metric(name, read, opts = {}) {
|
|
120
|
+
const m = { read, limit: opts.limit };
|
|
121
|
+
this.metrics.set(name, m);
|
|
122
|
+
return { remove: () => { if (this.metrics.get(name) === m) this.metrics.delete(name); } };
|
|
123
|
+
}
|
|
124
|
+
/** Limit of a category; undefined if none was given (not checked) @param {string} name @returns {number | undefined} */
|
|
125
|
+
limitOf(name) { return this.limits[name] ?? this.metrics.get(name)?.limit; }
|
|
126
|
+
|
|
127
|
+
/** @internal Called by the engine after each rendered frame: records frame time, checks once a second, and warns once per category over its limit */
|
|
128
|
+
sample(dt) {
|
|
129
|
+
if (!this.enabled) return;
|
|
130
|
+
this._dts.push(dt); this._cpu.push(this.engine.cpuMs ?? 0);
|
|
131
|
+
if (this._dts.length > WINDOW) { this._dts.shift(); this._cpu.shift(); }
|
|
132
|
+
if ((this._t += dt) < 1) return;
|
|
133
|
+
this._t = 0;
|
|
134
|
+
const r = this._last = this._evaluate();
|
|
135
|
+
for (const o of r.over) {
|
|
136
|
+
if (this._warned.has(o.category)) continue;
|
|
137
|
+
this._warned.add(o.category);
|
|
138
|
+
console.warn(coded('budget-over', fmt(STRINGS.over, { ...o, dir: LOWER.has(o.category) ? STRINGS.min : STRINGS.max, top: o.top.map(t => `${t.tag} ${t.drawCalls}`).join(', ') })));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/** Budget report; null when off. In the real-time loop it returns the last second's result; in step() mode it is computed on demand @returns {BudgetReport | null} */
|
|
142
|
+
report() {
|
|
143
|
+
if (!this.enabled) return null;
|
|
144
|
+
return this._last && this._dts.length ? this._last : this._evaluate();
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Called by the engine when startup finishes: warns if startupMs / moduleMs is exceeded and returns the offenders (empty array if none)
|
|
148
|
+
* @param {{ totalMs: number, modules: Record<string, { init?: number, ready?: number }> }} s
|
|
149
|
+
* @returns {{ category: 'startupMs' | 'moduleMs', value: number, limit: number, top: { tag: string, ms: number }[] }[]}
|
|
150
|
+
*/
|
|
151
|
+
checkStartup(s) {
|
|
152
|
+
if (!this.enabled) return [];
|
|
153
|
+
const { startupMs, moduleMs } = this.limits, /** @type {any[]} */ over = [];
|
|
154
|
+
const mods = Object.entries(s.modules).map(([tag, v]) => ({ tag, ms: (v.init ?? 0) + (v.ready ?? 0) })).sort((a, b) => b.ms - a.ms);
|
|
155
|
+
const top = mods.slice(0, 3);
|
|
156
|
+
if (startupMs != null && s.totalMs > startupMs) {
|
|
157
|
+
console.warn(coded('budget-over', fmt(STRINGS.startup, { value: s.totalMs, limit: startupMs, top: top.map(t => `${t.tag} ${t.ms}`).join(', ') })));
|
|
158
|
+
over.push({ category: 'startupMs', value: s.totalMs, limit: startupMs, top });
|
|
159
|
+
}
|
|
160
|
+
if (moduleMs != null) for (const m of mods) if (m.ms > moduleMs) {
|
|
161
|
+
console.warn(coded('budget-over', fmt(STRINGS.module, { name: m.tag, value: m.ms, limit: moduleMs })));
|
|
162
|
+
over.push({ category: 'moduleMs', value: m.ms, limit: moduleMs, top: [m] });
|
|
163
|
+
}
|
|
164
|
+
return over;
|
|
165
|
+
}
|
|
166
|
+
/** Current value per category (fps/low1/cpuMs exist only once there are frame times) @returns {Record<string, number>} */
|
|
167
|
+
values() {
|
|
168
|
+
const info = this.engine.renderer.info, v = /** @type {Record<string, number>} */ ({ drawCalls: info.render.calls, triangles: info.render.triangles, textures: info.memory.textures });
|
|
169
|
+
const d = this._dts;
|
|
170
|
+
if (d.length) {
|
|
171
|
+
const sum = d.reduce((a, b) => a + b, 0), worst = d.slice().sort((a, b) => b - a), n = Math.max(1, Math.floor(d.length * 0.01));
|
|
172
|
+
v.fps = r1(d.length / sum);
|
|
173
|
+
v.low1 = r1(n / worst.slice(0, n).reduce((a, b) => a + b, 0));
|
|
174
|
+
v.cpuMs = r1(this._cpu.reduce((a, b) => a + b, 0) / this._cpu.length);
|
|
175
|
+
}
|
|
176
|
+
for (const [name, m] of this.metrics) v[name] = r1(m.read());
|
|
177
|
+
return v;
|
|
178
|
+
}
|
|
179
|
+
/** @internal */
|
|
180
|
+
_evaluate() {
|
|
181
|
+
const v = this.values(), over = [];
|
|
182
|
+
let top = null;
|
|
183
|
+
for (const [category, value] of Object.entries(v)) {
|
|
184
|
+
const limit = this.limitOf(category);
|
|
185
|
+
if (limit == null || value == null) continue;
|
|
186
|
+
if (LOWER.has(category) ? value >= limit : value <= limit) continue;
|
|
187
|
+
over.push({ category, value, limit, top: top ??= this.byTag().slice(0, 5) });
|
|
188
|
+
}
|
|
189
|
+
return { ok: !over.length, over };
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Estimate draw calls and triangles by userData.budgetTag (visible meshes inside the frustum; shadow casters count a second shadow draw).
|
|
193
|
+
* Returns [{ tag, drawCalls, triangles }], largest first. Called only on overrun (at most once a second) or when debugging
|
|
194
|
+
* @returns {BudgetTagStat[]}
|
|
195
|
+
*/
|
|
196
|
+
byTag() {
|
|
197
|
+
const e = this.engine, cam = e.camera, out = new Map(), shadows = e.renderer.shadowMap.enabled, shadowCost = SHADOW_TYPES[e.shadowType]?.cost ?? 1;
|
|
198
|
+
// shadow passes a caster is drawn in: one per shadow-casting light (cascaded shadows add a light per cascade), six for a point light
|
|
199
|
+
let passes = 0;
|
|
200
|
+
e.scene.traverseVisible(o => { if (o.isLight && o.castShadow) passes += o.isPointLight ? 6 : 1; });
|
|
201
|
+
passes = Math.max(1, passes);
|
|
202
|
+
cam.updateMatrixWorld();
|
|
203
|
+
this._frustum.setFromProjectionMatrix(this._m.multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse));
|
|
204
|
+
const walk = (o, tag) => {
|
|
205
|
+
if (!o.visible) return;
|
|
206
|
+
tag = o.userData.budgetTag ?? tag;
|
|
207
|
+
if ((o.isMesh || o.isPoints || o.isLine || o.isSprite) && (!o.frustumCulled || this._frustum.intersectsObject(o))) {
|
|
208
|
+
const g = o.geometry, groups = Array.isArray(o.material) ? Math.max(1, g?.groups.length ?? 1) : 1;
|
|
209
|
+
// a caster adds a shadow draw, scaled by the filter's rough cost (estimate: vsm ~1.6x, basic ~0.8x of pcf), once per pass
|
|
210
|
+
// (an upper bound: each light culls to its own shadow box, so a near cascade skips most of the scene)
|
|
211
|
+
const calls = groups * (shadows && o.castShadow ? 1 + shadowCost * passes : 1);
|
|
212
|
+
const n = g ? (g.index ? g.index.count : g.attributes.position?.count ?? 0) : 0;
|
|
213
|
+
const s = out.get(tag) || out.set(tag, { tag, drawCalls: 0, triangles: 0 }).get(tag);
|
|
214
|
+
s.drawCalls += calls; s.triangles += o.isMesh ? Math.round(n / 3) * (o.count ?? 1) : 0;
|
|
215
|
+
}
|
|
216
|
+
for (const c of o.children) walk(c, tag);
|
|
217
|
+
};
|
|
218
|
+
walk(e.scene, 'other');
|
|
219
|
+
return [...out.values()].sort((a, b) => b.drawCalls - a.drawCalls);
|
|
220
|
+
}
|
|
221
|
+
}
|
package/core/Clock.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Game clock, engine.clock: game seconds `now` + "after a delay / every interval" timers.
|
|
2
|
+
// Game seconds = fixed-step seconds x clock.timeScale (default 1; the sky's time of day follows it too); it does not run while paused / frozen, and is saved with the save;
|
|
3
|
+
// a sky day = sky.dayLength game seconds, so one sky hour = dayLength / 24 game seconds (independent of timeScale: the time scale only makes game seconds run faster).
|
|
4
|
+
// Clock-time / season timers (daily 18:00, time-window switches, season change) belong to the sky: engine.sky.at / between / daily / onSeason.
|
|
5
|
+
// engine.clock.after(120, 'bread:ready') // emit an event after 120 game seconds (saveable: still fires after a load)
|
|
6
|
+
// engine.clock.after(5, () => door.close()) // a function works too, but functions cannot be saved
|
|
7
|
+
// engine.clock.every(30, () => spawnBird()) // every 30 game seconds
|
|
8
|
+
// For fixed seconds (ignore the time scale; cooldowns, action timing): accumulate dt in engine.onFixed(dt => ...). Which time to use for what: the table in recipes/06-clock-events.md. All timers return a handle { remove() }.
|
|
9
|
+
// A timer callback that throws is a gameplay error (errors.js: frozen with engine.error in dev); the other timers still run.
|
|
10
|
+
import { reportError } from './errors.js';
|
|
11
|
+
import { codedError } from './errorHints.js';
|
|
12
|
+
|
|
13
|
+
const STRINGS = {
|
|
14
|
+
after: 'clock.after(seconds): seconds must be a finite number of game seconds, got {got}',
|
|
15
|
+
every: 'clock.every(seconds): seconds must be a finite number of game seconds > 0, got {got}; for every fixed step use engine.onFixed(dt => ...)',
|
|
16
|
+
where: 'clock timer',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export class Clock {
|
|
20
|
+
constructor(engine) {
|
|
21
|
+
this.engine = engine;
|
|
22
|
+
this.now = 0; // game seconds
|
|
23
|
+
/** Game seconds per fixed-step second: 0 stops game time (sky included), 60 = a minute per second. Fixed-step dt and engine.elapsed ignore it @type {number} */
|
|
24
|
+
this.timeScale = 1;
|
|
25
|
+
/** @internal after / every: { due, fn?, event?, data?, every? } */ this._timers = [];
|
|
26
|
+
/** @internal earliest due among the timers (ticks with nothing due return early) */ this._next = Infinity;
|
|
27
|
+
engine.saves.register('clock', {
|
|
28
|
+
save: () => ({ now: this.now, timers: this._timers.filter(t => t.event).map(({ due, event, data }) => ({ due, event, data })) }),
|
|
29
|
+
// On load: event timers use the saved due time; function timers (not saveable, still attached to the running game) are shifted onto the new clock by their remaining time
|
|
30
|
+
load: d => {
|
|
31
|
+
const old = this.now;
|
|
32
|
+
this.now = d?.now ?? 0;
|
|
33
|
+
const fnTimers = this._timers.filter(t => !t.event);
|
|
34
|
+
for (const t of fnTimers) t.due = this.now + (t.due - old);
|
|
35
|
+
this._set(fnTimers.concat((d?.timers || []).map(t => ({ ...t }))));
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Call fn after `seconds` game seconds; when fnOrEvent is an event name, emit that event (with data) when due, which can be saved */
|
|
41
|
+
after(seconds, fnOrEvent, data) {
|
|
42
|
+
if (!Number.isFinite(seconds)) throw codedError('clock-interval', STRINGS.after.replace('{got}', String(seconds)));
|
|
43
|
+
const t = typeof fnOrEvent === 'string' ? { due: this.now + seconds, event: fnOrEvent, data } : { due: this.now + seconds, fn: fnOrEvent };
|
|
44
|
+
return this._add(t);
|
|
45
|
+
}
|
|
46
|
+
/** Call fn every `seconds` game seconds (seconds > 0) */
|
|
47
|
+
every(seconds, fn) {
|
|
48
|
+
if (!(seconds > 0) || !Number.isFinite(seconds)) throw codedError('clock-interval', STRINGS.every.replace('{got}', String(seconds)));
|
|
49
|
+
return this._add({ due: this.now + seconds, fn, every: seconds });
|
|
50
|
+
}
|
|
51
|
+
/** @internal */
|
|
52
|
+
_add(t) {
|
|
53
|
+
this._timers.push(t);
|
|
54
|
+
if (t.due < this._next) this._next = t.due;
|
|
55
|
+
return { remove: () => { this._set(this._timers.filter(x => x !== t)); } };
|
|
56
|
+
}
|
|
57
|
+
/** @internal replace the timer list and recompute the next due time */
|
|
58
|
+
_set(list) { this._timers = list; this._next = Infinity; for (const t of list) if (t.due < this._next) this._next = t.due; }
|
|
59
|
+
/** Game seconds until the next timer is due (Infinity with none); engine.skip ends a segment there so timers fire in time order @internal */
|
|
60
|
+
untilNext() { return Math.max(0, this._next - this.now); }
|
|
61
|
+
/** Number of registered timers (after / every), used by engine.counts() */
|
|
62
|
+
get size() { return this._timers.length; }
|
|
63
|
+
/** Clear all timers (engine.dispose calls it) */
|
|
64
|
+
dispose() { this._set([]); }
|
|
65
|
+
/**
|
|
66
|
+
* @internal For engine.session: the function timers now, each with its remaining delay (what a new playthrough starts with).
|
|
67
|
+
* @returns {{ t: object, rem: number }[]}
|
|
68
|
+
*/
|
|
69
|
+
snapshotFnTimers() { return this._timers.filter(t => !t.event).map(t => ({ t, rem: t.due - this.now })); }
|
|
70
|
+
/**
|
|
71
|
+
* @internal For engine.session: keep the event timers (they came with the save) and put back exactly the snapshotted function timers, each with its original delay.
|
|
72
|
+
* A function timer removed during play comes back too: a new playthrough starts as if the page had just opened.
|
|
73
|
+
* @param {{ t: object, rem: number }[]} list
|
|
74
|
+
*/
|
|
75
|
+
restoreFnTimers(list) { this._set(this._timers.filter(t => t.event).concat(list.map(({ t, rem }) => Object.assign(t, { due: this.now + rem })))); }
|
|
76
|
+
|
|
77
|
+
/** @internal Called by the engine every fixed step (after module hooks) */
|
|
78
|
+
tick(dt) {
|
|
79
|
+
this.now += dt * this.timeScale;
|
|
80
|
+
if (this._next <= this.now) this._runTimers();
|
|
81
|
+
}
|
|
82
|
+
/** @internal */
|
|
83
|
+
_runTimers() {
|
|
84
|
+
const due = this._timers.filter(t => t.due <= this.now).sort((a, b) => a.due - b.due);
|
|
85
|
+
for (const t of due) {
|
|
86
|
+
if (t.every) { while (t.due <= this.now) { t.due += t.every; this._call(t); } continue; }
|
|
87
|
+
this._timers = this._timers.filter(x => x !== t);
|
|
88
|
+
if (t.event) this.engine.events.emit(t.event, t.data); else this._call(t);
|
|
89
|
+
}
|
|
90
|
+
this._set(this._timers);
|
|
91
|
+
}
|
|
92
|
+
/** @internal a callback that throws is a gameplay error; the other timers still run */
|
|
93
|
+
_call(t) { try { t.fn(); } catch (err) { reportError(this.engine, err, STRINGS.where); } }
|
|
94
|
+
}
|
package/core/Commits.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// How background results take effect: engine.commits.
|
|
2
|
+
// Background results that affect gameplay (chunk collision, spread-over-frames jobs that change gameplay state, future navmesh, entity spawns...) do not take effect "whenever they finish" --
|
|
3
|
+
// that depends on machine speed and background-thread queueing -- but on a fixed-step tick decided when the request is made:
|
|
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
|
+
// 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):
|
|
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
|
|
9
|
+
// (terrain colliders survive a load because the terrain is the same; pass valid when your result belongs to state a load replaces).
|
|
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
|
+
// 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.
|
|
12
|
+
// Results that only affect visuals (model upload, far scenery, particles) need not go through here; show them when ready.
|
|
13
|
+
const STRINGS = { noFallback: 'commits.request() needs a fallback: it is computed on the main thread when due and the result is not ready (so the outcome never depends on machine speed); pass fallback: () => ...' };
|
|
14
|
+
|
|
15
|
+
/**
|
|
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
|
+
* 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
|
+
*/
|
|
19
|
+
import { codedError } from './errorHints.js';
|
|
20
|
+
|
|
21
|
+
export class Commits {
|
|
22
|
+
/** @internal */
|
|
23
|
+
constructor(engine) {
|
|
24
|
+
/** @internal */ this.engine = engine;
|
|
25
|
+
/** Default delay (fixed steps); 30 = 0.5 s */
|
|
26
|
+
this.lag = 30;
|
|
27
|
+
/** @internal sorted by due, then seq */ this.queue = [];
|
|
28
|
+
/** @internal */ this._seq = 0;
|
|
29
|
+
/** @internal bumped by invalidate (save load, level change); requests without valid from an older epoch are dropped */ this.epoch = 0;
|
|
30
|
+
/** Totals: applied, fallbacks used because not finished when due, dropped because valid() was false */
|
|
31
|
+
this.stats = { applied: 0, late: 0, dropped: 0 };
|
|
32
|
+
}
|
|
33
|
+
/** Number of requests not yet applied @returns {number} */
|
|
34
|
+
get pending() { return this.queue.length; }
|
|
35
|
+
/**
|
|
36
|
+
* Register a request: resolve(result) when the background work finishes, remove() if no longer wanted. apply changes gameplay state with the result; fallback computes the same result on the main thread (required); valid says whether it is still wanted when due
|
|
37
|
+
* @template [T=any]
|
|
38
|
+
* @param {{ apply: (result: T) => void, fallback: () => T, valid?: (() => boolean) | null, lag?: number }} opts
|
|
39
|
+
* @returns {{ due: number, resolve: (result: T) => void, remove: () => void }}
|
|
40
|
+
* @example const t = engine.commits.request({ apply: r => { state.path = r; }, fallback: () => computePath() });
|
|
41
|
+
* pathWorker.then(r => t.resolve(r));
|
|
42
|
+
*/
|
|
43
|
+
request(opts) {
|
|
44
|
+
const { apply, fallback, valid = null, lag = this.lag } = opts;
|
|
45
|
+
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
|
+
this._insert(t);
|
|
48
|
+
const remove = () => { t.canceled = true; };
|
|
49
|
+
return { due: t.due, resolve: r => { if (!t.done) { t.done = true; t.result = r; } }, remove };
|
|
50
|
+
}
|
|
51
|
+
/** @internal */
|
|
52
|
+
_insert(t) {
|
|
53
|
+
let i = this.queue.length;
|
|
54
|
+
while (i > 0 && (this.queue[i - 1].due > t.due || (this.queue[i - 1].due === t.due && this.queue[i - 1].seq > t.seq))) i--;
|
|
55
|
+
this.queue.splice(i, 0, t);
|
|
56
|
+
}
|
|
57
|
+
/** @internal Called by the engine at the start of each fixed step: due requests take effect in order */
|
|
58
|
+
tick(now) {
|
|
59
|
+
while (this.queue.length && this.queue[0].due <= now) {
|
|
60
|
+
const t = this.queue.shift();
|
|
61
|
+
if (t.canceled || (t.valid ? !t.valid() : t.epoch !== this.epoch)) { this.stats.dropped++; continue; }
|
|
62
|
+
if (!t.done) { t.result = t.fallback(); t.done = true; this.stats.late++; }
|
|
63
|
+
t.apply(t.result);
|
|
64
|
+
this.stats.applied++;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** @internal Called when start() finishes loading: pending requests restart timing from now (due = now + lag); lag 0 takes effect immediately */
|
|
68
|
+
rebase() {
|
|
69
|
+
const now = this.engine.tick, list = this.queue.splice(0);
|
|
70
|
+
for (const t of list) { t.due = now + t.lag; this._insert(t); }
|
|
71
|
+
this.tick(now);
|
|
72
|
+
}
|
|
73
|
+
/** @internal Drop all requests (engine.dispose calls it) */
|
|
74
|
+
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
|
+
invalidate() { this.epoch++; }
|
|
77
|
+
}
|
package/core/Describe.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Game state description: engine.describe() returns a plain object (JSON.stringify-able); engine.describeText() returns multi-line text.
|
|
2
|
+
// For AI and test scripts: learn "what time it is, what the weather is, where the player is, what is nearby, which windows are open" without a screenshot.
|
|
3
|
+
//
|
|
4
|
+
// The core fills in only what it knows (time in seconds, player position, camera, windows, performance); the rest comes from modules' optional hooks:
|
|
5
|
+
// describe(e, ctx) {
|
|
6
|
+
// ctx.out.time.clock = '18:30'; // you may add info to the standard fields
|
|
7
|
+
// ctx.near(obj3D or {x,z}, { name, kind: 'npc' }); // report a "nearby thing"; the core computes distance, bearing and ordering
|
|
8
|
+
// return { ... }; // the return value goes into the result under the module name as key (omitted if nothing is returned)
|
|
9
|
+
// }
|
|
10
|
+
//
|
|
11
|
+
// A small game that does not want a full module: engine.describe.add(name, fn) registers the game's own state in one line; the return value goes into describe().<name> (fn gets the same arguments as a module hook).
|
|
12
|
+
// const h = engine.describe.add('range', () => ({ score, targets: targets.length })); h.remove() to cancel
|
|
13
|
+
// A big game writes its systems as modules and uses the module's describe hook.
|
|
14
|
+
// ctx.near(at, info, weak): reports for the same `at` (same object) are merged; with weak = true only missing fields are filled (used by the interaction module).
|
|
15
|
+
// Display names (ground type, weather name) are not hard-coded here: they come from the string table, ground.<type> and weather.<name> (registered by the terrain and weather modules), and go into groundName / label.
|
|
16
|
+
// describeText, which turns this into text, lives in describeText.js.
|
|
17
|
+
import { describeText } from './describeText.js';
|
|
18
|
+
import { inspect, explain } from './Inspect.js';
|
|
19
|
+
import { inspectScene } from './InspectScene.js';
|
|
20
|
+
import { codedError } from './errorHints.js';
|
|
21
|
+
import { r1 } from './math.js';
|
|
22
|
+
import { describeScene } from './thingOps.js';
|
|
23
|
+
|
|
24
|
+
const NEAR_RADIUS = 30, NEAR_MAX = 15;
|
|
25
|
+
const COMPASS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; // north = -Z, east = +X
|
|
26
|
+
const RELATIVE = ['front', 'front-right', 'right', 'back-right', 'back', 'back-left', 'left', 'front-left']; // relative to the camera heading
|
|
27
|
+
const STANDARD = new Set(['ready', 'error', 'disabledModules', 'moduleStates', 'loading', 'time', 'player', 'camera', 'nearbyRadius', 'nearby', 'actions', 'ui', 'cutscene', 'modules', 'perf', 'scene']);
|
|
28
|
+
const ACTIONS_MAX = 8; // what the player can do now, with why not: saves the AI a guess for a few dozen characters // the core's own fields
|
|
29
|
+
const sector = a => Math.round(((a % (Math.PI * 2)) + Math.PI * 2) / (Math.PI / 4)) % 8;
|
|
30
|
+
|
|
31
|
+
/** Display name from the string table (prefix + key); null if missing (the text then uses the raw name) */
|
|
32
|
+
const nameOf = (e, prefix, key) => (key != null && e.i18n.has(prefix + key) ? e.t(prefix + key) : null);
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The engine's state questions, assigned onto the engine: describe (call it for the state object; .add registers the game's own state),
|
|
36
|
+
* describeText, inspect and explain (Inspect.js)
|
|
37
|
+
* @param {any} e
|
|
38
|
+
*/
|
|
39
|
+
export function describeApi(e) {
|
|
40
|
+
const extras = new Map();
|
|
41
|
+
/**
|
|
42
|
+
* Current game state (plain object, JSON.stringify-able). radius: how far counts as "nearby" (meters), default 30
|
|
43
|
+
* @param {{ radius?: number, center?: { x: number, z: number } }} [opts] center: measure "nearby" from here instead of the player (inspect uses it)
|
|
44
|
+
*/
|
|
45
|
+
const api = opts => describe(e, opts, extras);
|
|
46
|
+
/**
|
|
47
|
+
* Register the game's own state: the return value of fn(engine, ctx) (must be JSON-able) goes into describe().<name>; undefined is omitted
|
|
48
|
+
* @param {string} name key in the result; must not match an existing field or module name
|
|
49
|
+
* @param {(e: any, ctx: any) => any} fn
|
|
50
|
+
* @returns {{ remove(): void }}
|
|
51
|
+
* @example engine.describe.add('range', () => ({ score: vars.get('score'), targets: targets.length }));
|
|
52
|
+
*/
|
|
53
|
+
api.add = (name, fn) => {
|
|
54
|
+
if (extras.has(name) || STANDARD.has(name) || e.modules.has(name)) throw codedError('describe-name', `describe.add('${name}'): this name is already taken; pick another (existing fields, module names and previously registered names cannot be reused)`);
|
|
55
|
+
extras.set(name, fn);
|
|
56
|
+
return { remove: () => { extras.delete(name); } };
|
|
57
|
+
};
|
|
58
|
+
/** Text of describe(): a summary by default; { path: 'world' } one part as JSON; { full: true } everything (see describeText.js) */
|
|
59
|
+
const text = ({ full, path, ...opts } = {}) => describeText(api(opts), { full, path });
|
|
60
|
+
const inspectApi = Object.assign((at, opts) => inspect(e, at, opts), { scene: opts => inspectScene(e, opts) });
|
|
61
|
+
return { describe: api, describeText: text, inspect: inspectApi, explain: q => explain(e, q) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Only the modules that are not running normally (initializing / failed) appear in describe, so the common case adds nothing; engine.moduleStates has all of them */
|
|
65
|
+
function pendingModules(e) {
|
|
66
|
+
const out = {};
|
|
67
|
+
for (const [name, st] of e._modState) if (st === 'initializing' || st === 'failed') out[name] = st;
|
|
68
|
+
return Object.keys(out).length ? { moduleStates: out } : {};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Build the state object. radius: how far counts as "nearby"; extras: those registered by describe.add */
|
|
72
|
+
function describe(e, { radius = NEAR_RADIUS, center: at } = {}, extras) {
|
|
73
|
+
const p = e.player?.position, center = at || p || e.focus, cam = e.camera;
|
|
74
|
+
const dir = cam.getWorldDirection(new e.THREE.Vector3()), camYaw = Math.atan2(dir.x, -dir.z);
|
|
75
|
+
const out = {
|
|
76
|
+
ready: e.ready,
|
|
77
|
+
error: e.error, // gameplay error in dev / tests (gameplay is frozen)
|
|
78
|
+
disabledModules: [...e.disabledModules], // presentation modules disabled after an error
|
|
79
|
+
...pendingModules(e), // { moduleStates } while a module is initializing or failed
|
|
80
|
+
loading: e.loading.view(), // what is pending / failed and whether it blocks the start (Loading.js)
|
|
81
|
+
time: { elapsed: r1(e.elapsed), paused: e.paused, frozen: e.frozen, headless: e.headless },
|
|
82
|
+
player: p ? {
|
|
83
|
+
x: r1(p.x), y: r1(p.y), z: r1(p.z),
|
|
84
|
+
ground: e.groundType(p.x, p.z),
|
|
85
|
+
groundName: nameOf(e, 'ground.', e.groundType(p.x, p.z)),
|
|
86
|
+
inWater: e.waterAt(p.x, p.z) > p.y,
|
|
87
|
+
state: e.player.state ?? null,
|
|
88
|
+
running: e.player.state === 'run',
|
|
89
|
+
jumping: e.player.state === 'jump' || e.player.state === 'fall',
|
|
90
|
+
} : null,
|
|
91
|
+
camera: { type: null, x: r1(cam.position.x), y: r1(cam.position.y), z: r1(cam.position.z),
|
|
92
|
+
focus: { x: r1(e.focus.x), z: r1(e.focus.z) }, override: e.cameraOverride?.owner ?? null },
|
|
93
|
+
nearbyRadius: radius,
|
|
94
|
+
nearby: [],
|
|
95
|
+
ui: { windows: [...e.openWindows], inputLocked: !e.input.enabled, inputContexts: e.input.contexts, dialogue: null, parts: e.ui.describe() }, // windows include full-screen UI parts (title); parts: default / custom / off
|
|
96
|
+
cutscene: null,
|
|
97
|
+
modules: [...e.modules.keys()],
|
|
98
|
+
scene: describeScene(e), // engine.add / world things: counts by save tier and what will not survive a load (thingOps.js)
|
|
99
|
+
perf: {
|
|
100
|
+
fps: e.paused ? null : Math.round(e.fps), cpuMs: e.paused ? null : r1(e.cpuMs),
|
|
101
|
+
cpu: e.paused ? null : Object.fromEntries(Object.entries(e.cpuPhases).map(([k, v]) => [k, r1(v)])),
|
|
102
|
+
apply: e.budget.cost.report(),
|
|
103
|
+
drawCalls: e.renderer.info.render.calls, triangles: e.renderer.info.render.triangles, pixelRatio: e.renderer.getPixelRatio(),
|
|
104
|
+
budget: e.budget.report(), startup: e.startup, stream: e.stream.stats, batching: e.batching.stats, jobs: e.jobs.pending, commits: { pending: e.commits.pending, ...e.commits.stats },
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
// Nearby things: collect first, then sort and truncate once at the end
|
|
108
|
+
const found = new Map(), v = new e.THREE.Vector3();
|
|
109
|
+
const ctx = {
|
|
110
|
+
out, radius, center,
|
|
111
|
+
near(at, info, weak = false) {
|
|
112
|
+
const pos = at.isObject3D ? at.getWorldPosition(v) : at;
|
|
113
|
+
const dx = pos.x - center.x, dz = pos.z - center.z, dist = Math.hypot(dx, dz);
|
|
114
|
+
if (dist > radius) return;
|
|
115
|
+
const old = found.get(at);
|
|
116
|
+
if (old) { for (const k in info) if (!weak || old[k] == null) old[k] = info[k]; return; }
|
|
117
|
+
const bearing = Math.atan2(dx, -dz);
|
|
118
|
+
found.set(at, { ...info, dist: r1(dist), dir: COMPASS[sector(bearing)], rel: RELATIVE[sector(bearing - camYaw)], x: r1(pos.x), z: r1(pos.z) });
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
for (const m of e.modules.values()) {
|
|
122
|
+
if (!m.describe) continue;
|
|
123
|
+
const part = m.describe(e, ctx);
|
|
124
|
+
if (part !== undefined) out[m.name] = part;
|
|
125
|
+
}
|
|
126
|
+
for (const [name, fn] of extras) {
|
|
127
|
+
try { const part = fn(e, ctx); if (part !== undefined) out[name] = part; } catch (err) { out[name] = { error: String(err.message || err) }; } // an error in the game's own description must not take down the whole describe
|
|
128
|
+
}
|
|
129
|
+
out.nearby = [...found.values()].sort((a, b) => a.dist - b.dist).slice(0, NEAR_MAX);
|
|
130
|
+
// ops on offer for the player (engine.ops.list({ available: true })): possible ones first; omitted when the game has none
|
|
131
|
+
const acts = e.ops.list({ available: true }).sort((a, b) => b.ok - a.ok).slice(0, ACTIONS_MAX);
|
|
132
|
+
if (acts.length) out.actions = acts.map(a => ({ op: a.name, args: a.args, ok: a.ok, ...(a.ok ? {} : { reason: a.reason }) }));
|
|
133
|
+
return out;
|
|
134
|
+
}
|