threedog 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/core/Animator.js +268 -0
- package/core/Assets.js +256 -0
- package/core/Audio.js +267 -0
- package/core/Baked.js +72 -0
- package/core/Batching.js +247 -0
- package/core/Budget.js +221 -0
- package/core/Clock.js +94 -0
- package/core/Commits.js +77 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +145 -0
- package/core/Engine.js +184 -0
- package/core/Events.js +153 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +77 -0
- package/core/InspectScene.js +191 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +256 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +254 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +94 -0
- package/core/Vars.js +35 -0
- package/core/Views.js +49 -0
- package/core/actor.js +23 -0
- package/core/assetEntry.js +89 -0
- package/core/assetLoad.js +190 -0
- package/core/assetManifest.js +35 -0
- package/core/assetReport.js +83 -0
- package/core/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/dayTime.js +15 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +143 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +205 -0
- package/core/errorHints.js +208 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -0
- package/core/holds.js +106 -0
- package/core/inputContext.js +69 -0
- package/core/inputDefaults.js +22 -0
- package/core/inputPad.js +35 -0
- package/core/inputPointer.js +48 -0
- package/core/inputTouch.js +48 -0
- package/core/lifecycle.js +69 -0
- package/core/lightWatch.js +56 -0
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +200 -0
- package/core/math.js +33 -0
- package/core/modules.js +196 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +97 -0
- package/core/opsFail.js +20 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/opsRun.js +77 -0
- package/core/page.js +78 -0
- package/core/params.js +132 -0
- package/core/pureWorker.js +5 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +128 -0
- package/core/saveFiles.js +139 -0
- package/core/saveIds.js +53 -0
- package/core/saveVersions.js +97 -0
- package/core/scatter.js +92 -0
- package/core/sceneMethods.js +100 -0
- package/core/screenToGround.js +39 -0
- package/core/services.js +73 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +135 -0
- package/core/streamCells.js +24 -0
- package/core/streamSources.js +73 -0
- package/core/styleParts.js +96 -0
- package/core/targeting.js +64 -0
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +168 -0
- package/core/things.js +212 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/util.js +11 -0
- package/core/validate.js +204 -0
- package/docs/AI.md +123 -0
- package/docs/API.md +83 -0
- package/docs/CODEMAP.md +347 -0
- package/docs/COMMANDS.md +108 -0
- package/docs/CONVENTIONS.md +145 -0
- package/docs/PERF.md +217 -0
- package/docs/THREE.md +86 -0
- package/docs/api/ambience.md +15 -0
- package/docs/api/assets.md +62 -0
- package/docs/api/audio.md +53 -0
- package/docs/api/budget.md +40 -0
- package/docs/api/cameraRig.md +120 -0
- package/docs/api/characters.md +144 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +39 -0
- package/docs/api/content.md +64 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +199 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +95 -0
- package/docs/api/flow.md +27 -0
- package/docs/api/grids.md +11 -0
- package/docs/api/ground.md +16 -0
- package/docs/api/hlod.md +34 -0
- package/docs/api/hud.md +31 -0
- package/docs/api/i18n.md +10 -0
- package/docs/api/input.md +24 -0
- package/docs/api/interactions.md +31 -0
- package/docs/api/inventory.md +66 -0
- package/docs/api/jobs.md +10 -0
- package/docs/api/level.md +41 -0
- package/docs/api/lightPool.md +56 -0
- package/docs/api/music.md +34 -0
- package/docs/api/nav.md +26 -0
- package/docs/api/net.md +14 -0
- package/docs/api/openWorld.md +24 -0
- package/docs/api/particles.md +41 -0
- package/docs/api/photo.md +15 -0
- package/docs/api/post.md +10 -0
- package/docs/api/quests.md +36 -0
- package/docs/api/rays.md +26 -0
- package/docs/api/rigid.md +84 -0
- package/docs/api/saves.md +32 -0
- package/docs/api/settings.md +36 -0
- package/docs/api/sky.md +58 -0
- package/docs/api/stream.md +31 -0
- package/docs/api/style.md +134 -0
- package/docs/api/terrain.md +34 -0
- package/docs/api/timeline.md +39 -0
- package/docs/api/tools.md +57 -0
- package/docs/api/triggers.md +56 -0
- package/docs/api/vars.md +9 -0
- package/docs/api/vegetation.md +52 -0
- package/docs/api/water.md +48 -0
- package/docs/api/weather.md +29 -0
- package/docs/api/world.md +30 -0
- package/docs/recipes/01-new-game.md +148 -0
- package/docs/recipes/02-npc.md +167 -0
- package/docs/recipes/03-items-pickups.md +158 -0
- package/docs/recipes/04-quests.md +83 -0
- package/docs/recipes/05-props-bake.md +159 -0
- package/docs/recipes/06-clock-events.md +117 -0
- package/docs/recipes/07-flow-scenes-pause.md +132 -0
- package/docs/recipes/08-weather-sky.md +74 -0
- package/docs/recipes/09-style-pack.md +234 -0
- package/docs/recipes/10-blender-level.md +67 -0
- package/docs/recipes/11-vehicles.md +55 -0
- package/docs/recipes/12-navmesh.md +79 -0
- package/docs/recipes/13-animation.md +149 -0
- package/docs/recipes/14-custom-module.md +91 -0
- package/docs/recipes/15-perf.md +78 -0
- package/docs/recipes/16-dev-bridge.md +180 -0
- package/docs/recipes/18-world.md +185 -0
- package/docs/recipes/19-shooting-picking.md +76 -0
- package/docs/recipes/20-content-actions-save.md +176 -0
- package/docs/recipes/21-camera.md +153 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +175 -0
- package/docs/recipes/26-ui-parts.md +138 -0
- package/docs/recipes/27-net.md +96 -0
- package/docs/recipes/28-terrain.md +80 -0
- package/docs/recipes/29-grid.md +87 -0
- package/docs/recipes/30-templates.md +131 -0
- package/docs/recipes/31-audio.md +126 -0
- package/docs/recipes/32-action-game.md +33 -0
- package/docs/recipes/33-stream-sources.md +37 -0
- package/docs/recipes/34-environment-lighting.md +36 -0
- package/docs/recipes/35-style-from-reference.md +89 -0
- package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
- package/docs/recipes/37-terrain-look-hooks.md +97 -0
- package/docs/recipes/38-environment-look-hooks.md +83 -0
- package/docs/recipes/40-scene.md +108 -0
- package/docs/recipes/41-thing-registry.md +93 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
- package/docs/recipes/44-water-weather-look-hooks.md +135 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +114 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/DESIGN.md +3 -0
- package/examples/action/GAMEMAP.md +127 -0
- package/examples/action/content/actions.js +8 -0
- package/examples/action/content/audio.js +9 -0
- package/examples/action/content/index.js +10 -0
- package/examples/action/content/items.js +4 -0
- package/examples/action/content/places.js +4 -0
- package/examples/action/content/props.js +11 -0
- package/examples/action/content/templates.js +10 -0
- package/examples/action/content/views.js +6 -0
- package/examples/action/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +107 -0
- package/examples/sheepisland/content/index.js +6 -0
- package/examples/sheepisland/content/props.js +19 -0
- package/examples/sheepisland/content/templates.js +5 -0
- package/examples/sheepisland/content/vegetation.js +8 -0
- package/examples/sheepisland/main.js +71 -0
- package/examples/sheepisland/params.js +25 -0
- package/examples/sheepisland/style/index.js +79 -0
- package/examples/sheepisland/style/models.js +59 -0
- package/examples/sheepisland/views.js +9 -0
- package/examples/styletest/GAMEMAP.md +135 -0
- package/examples/styletest/content/index.js +9 -0
- package/examples/styletest/content/items.js +8 -0
- package/examples/styletest/content/npcs.js +8 -0
- package/examples/styletest/content/places.js +5 -0
- package/examples/styletest/content/props.js +16 -0
- package/examples/styletest/content/templates.js +9 -0
- package/examples/styletest/content/vegetation.js +31 -0
- package/examples/styletest/look.js +11 -0
- package/examples/styletest/main.js +95 -0
- package/examples/styletest/models.js +87 -0
- package/examples/styletest/overrides.js +33 -0
- package/examples/styletest/panel.js +135 -0
- package/examples/styletest/params.js +32 -0
- package/examples/styletest/views.js +31 -0
- package/examples/world/DESIGN.md +5 -0
- package/examples/world/GAMEMAP.md +171 -0
- package/examples/world/content/actions.js +8 -0
- package/examples/world/content/audio.js +25 -0
- package/examples/world/content/bodies.js +12 -0
- package/examples/world/content/containers.js +4 -0
- package/examples/world/content/dialogues.js +33 -0
- package/examples/world/content/index.js +17 -0
- package/examples/world/content/items.js +10 -0
- package/examples/world/content/npcs.js +14 -0
- package/examples/world/content/pickups.js +11 -0
- package/examples/world/content/places.js +6 -0
- package/examples/world/content/props.js +12 -0
- package/examples/world/content/quests.js +15 -0
- package/examples/world/content/rules.js +23 -0
- package/examples/world/content/templates.js +5 -0
- package/examples/world/content/vegetation.js +32 -0
- package/examples/world/main.js +168 -0
- package/examples/world/models.js +28 -0
- package/index.d.ts +306 -0
- package/index.js +122 -0
- package/llms.txt +61 -0
- package/modules/ambience/Ambience.js +186 -0
- package/modules/camera/FirstPersonCamera.js +131 -0
- package/modules/camera/FixedCamera.js +162 -0
- package/modules/camera/FollowCamera.js +91 -0
- package/modules/camera/RtsCamera.js +132 -0
- package/modules/camera/common.js +182 -0
- package/modules/camera/index.js +11 -0
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +235 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +66 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +215 -0
- package/modules/characters/moveHelpers.js +29 -0
- package/modules/characters/movers/common.js +62 -0
- package/modules/characters/movers/rapier.js +74 -0
- package/modules/characters/movers/simple.js +43 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +150 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +113 -0
- package/modules/characters/pathJob.js +62 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +58 -0
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +274 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/explain.js +13 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +154 -0
- package/modules/content/loader.js +190 -0
- package/modules/content/models.js +69 -0
- package/modules/content/packs.js +69 -0
- package/modules/content/props.js +89 -0
- package/modules/content/rules.js +134 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +174 -0
- package/modules/entities/Entities.js +243 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +101 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +219 -0
- package/modules/gameplay/Interactions.js +253 -0
- package/modules/gameplay/Inventory.js +224 -0
- package/modules/gameplay/Quests.js +205 -0
- package/modules/gameplay/boxOps.js +60 -0
- package/modules/gameplay/dialogueBox.js +48 -0
- package/modules/gameplay/interactionPrompt.js +28 -0
- package/modules/gameplay/inventoryOps.js +137 -0
- package/modules/gameplay/pickups.js +115 -0
- package/modules/gameplay/questLog.js +54 -0
- package/modules/gameplay/questSave.js +71 -0
- package/modules/grid/Grid.js +184 -0
- package/modules/grid/Layer.js +142 -0
- package/modules/grid/index.js +236 -0
- package/modules/grid/ops.js +73 -0
- package/modules/grid/preview.js +85 -0
- package/modules/grid/tiles.js +79 -0
- package/modules/hlod/index.js +167 -0
- package/modules/hud/index.js +167 -0
- package/modules/hud/parts.js +80 -0
- package/modules/level/geometry.js +46 -0
- package/modules/level/heightfield.js +160 -0
- package/modules/level/index.js +233 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +227 -0
- package/modules/music/Music.js +294 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +156 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +137 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +77 -0
- package/modules/net/sync.js +114 -0
- package/modules/net/transports.js +118 -0
- package/modules/particles/Particles.js +179 -0
- package/modules/particles/effect.js +112 -0
- package/modules/particles/shaders.js +28 -0
- package/modules/photo/Photo.js +146 -0
- package/modules/rigid/RigidBodies.js +265 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +297 -0
- package/modules/settings/apply.js +21 -0
- package/modules/settings/index.js +3 -0
- package/modules/settings/sections.js +156 -0
- package/modules/settings/strings.js +53 -0
- package/modules/settings/view.js +65 -0
- package/modules/sky/Sky.js +259 -0
- package/modules/sky/calendar.js +80 -0
- package/modules/sky/cascades.js +125 -0
- package/modules/sky/clouds.js +79 -0
- package/modules/sky/domeLayers.js +33 -0
- package/modules/sky/environment.js +141 -0
- package/modules/sky/fog.js +139 -0
- package/modules/sky/frame.js +77 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +51 -0
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +74 -0
- package/modules/sky/skyModule.js +60 -0
- package/modules/terrain/ChunkManager.js +260 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +118 -0
- package/modules/terrain/lookGround.js +61 -0
- package/modules/terrain/mountTerrain.js +32 -0
- package/modules/terrain/terrainColorMap.js +41 -0
- package/modules/terrain/terrainDefaults.js +39 -0
- package/modules/terrain/terrainEdit.js +139 -0
- package/modules/terrain/terrainGen.js +155 -0
- package/modules/terrain/terrainIsland.js +131 -0
- package/modules/terrain/terrainMesh.js +92 -0
- package/modules/terrain/terrainShape.js +108 -0
- package/modules/terrain/terrainShapeMain.js +41 -0
- package/modules/terrain/terrainTexture.js +44 -0
- package/modules/timeline/Timeline.js +253 -0
- package/modules/timeline/Tween.js +114 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +90 -0
- package/modules/triggers/index.js +268 -0
- package/modules/vegetation/Vegetation.js +256 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +43 -0
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +160 -0
- package/modules/water/look.js +80 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +242 -0
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/weather/strings.js +15 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +71 -0
- package/modules/world/persist.js +107 -0
- package/modules/world/pos.js +20 -0
- package/modules/world/records.js +89 -0
- package/modules/world/sim.js +175 -0
- package/modules/world/simFar.js +82 -0
- package/modules/world/state.js +115 -0
- package/modules/world/thingSource.js +44 -0
- package/modules/world/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +240 -0
- package/render/detail.js +105 -0
- package/render/effects.js +144 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +84 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +18 -0
- package/render/lookSurface.js +161 -0
- package/render/materials.js +220 -0
- package/render/patches.js +252 -0
- package/render/postLook.js +86 -0
- package/render/surface.js +69 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1965 -0
- package/types/gameplay.d.ts +1822 -0
- package/types/generated/core/Audio.d.ts +200 -0
- package/types/generated/core/Batching.d.ts +47 -0
- package/types/generated/core/Budget.d.ts +90 -0
- package/types/generated/core/Commits.d.ts +31 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +89 -0
- package/types/generated/core/I18n.d.ts +30 -0
- package/types/generated/core/Input.d.ts +118 -0
- package/types/generated/core/Jobs.d.ts +41 -0
- package/types/generated/core/Ops.d.ts +203 -0
- package/types/generated/core/Random.d.ts +49 -0
- package/types/generated/core/Rays.d.ts +49 -0
- package/types/generated/core/Saves.d.ts +162 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/core/audioVoice.d.ts +47 -0
- package/types/generated/core/page.d.ts +18 -0
- package/types/generated/core/session.d.ts +48 -0
- package/types/generated/modules/ambience/Ambience.d.ts +48 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
- package/types/generated/modules/flow/index.d.ts +10 -0
- package/types/generated/modules/grid/Grid.d.ts +151 -0
- package/types/generated/modules/grid/Layer.d.ts +65 -0
- package/types/generated/modules/grid/index.d.ts +86 -0
- package/types/generated/modules/hlod/index.d.ts +11 -0
- package/types/generated/modules/hud/index.d.ts +10 -0
- package/types/generated/modules/lights/index.d.ts +13 -0
- package/types/generated/modules/music/Music.d.ts +111 -0
- package/types/generated/modules/net/Net.d.ts +34 -0
- package/types/generated/modules/net/index.d.ts +53 -0
- package/types/generated/modules/net/transports.d.ts +58 -0
- package/types/generated/modules/particles/Particles.d.ts +69 -0
- package/types/generated/modules/sky/Sky.d.ts +145 -0
- package/types/generated/modules/sky/skyModule.d.ts +10 -0
- package/types/generated/modules/timeline/Timeline.d.ts +51 -0
- package/types/generated/modules/water/Water.d.ts +29 -0
- package/types/generated/modules/weather/Weather.d.ts +62 -0
- package/types/generated/modules/world/World.d.ts +242 -0
- package/types/generated/modules/world/index.d.ts +15 -0
- package/types/generated/render/PostFX.d.ts +125 -0
- package/types/generated/render/materials.d.ts +100 -0
- package/types/generated/render/patches.d.ts +41 -0
- package/types/generated/ui/Focus.d.ts +11 -0
- package/types/generated/ui/LoadingScreen.d.ts +2 -0
- package/types/generated/ui/UI.d.ts +57 -0
- package/types/nav.d.ts +52 -0
- package/types/physics.d.ts +592 -0
- package/types/style.d.ts +638 -0
- package/types/worker.d.ts +11 -0
- package/types/world.d.ts +772 -0
- package/ui/Focus.js +51 -0
- package/ui/LoadingScreen.js +42 -0
- package/ui/Parts.js +199 -0
- package/ui/UI.js +167 -0
- package/ui/defaults.js +85 -0
- package/ui/theme.js +124 -0
- package/ui/touchPart.js +49 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# engine.world — world()
|
|
2
|
+
|
|
3
|
+
World data (world() module): things that must be saved, survive level changes and keep changing while far away; the model is built only when nearby
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
## Methods and properties
|
|
7
|
+
- `world.add(def: { kind, id?, position?, … }, opts?: { initial?, save? }) → WorldRecord | null` — Add a record and return it (a plain object). kind is required; without id one is numbered automatically (kind#1, kind#2…, saved; `#` never appears in an authored id, so the two can never collide). opts.initial: initial record written in content (needs an id); saves only keep its changes and removal; if the id already exists the existing one is returned (content may load twice); returns null if the save removed it (it is not added back). opts.save: false: not saved (temporary things). Example: `engine.world.add({ id: 'shop_owner', kind: 'npc', position: [12, 0, -30], name: '店主', mood: 'calm' }, { initial: true })`
|
|
8
|
+
- `world.origin(id: string) → { definedAt?, level?, node?, template?, spawned? } | null | …` — Where a record comes from (filled in dev and test builds; null in release): { definedAt: 'content/props.js:14' } for a content entry, { level, node } for a level-model node, { template } when it is a template instance, { spawned: { op, tick } } for a record created during play. engine.inspect(id) and engine.pick(...).thing show it, so you know which file to edit to change the level for good. Example: `engine.world.origin('chest-home') // { definedAt: 'content/props.js:14', template: 'chest' }`
|
|
9
|
+
- `world.idOf(obj: any) → string | null` — The id of the record whose model contains obj (obj itself or one of its parents is a built model), else null. A ray hit on a model names its record this way. Example: `const h = engine.pick(0, 0); const id = h && engine.world.idOf(h.object);`
|
|
10
|
+
- `world.get(id: string) → WorldRecord | undefined` — Get a record by id (undefined if missing, like a Map)
|
|
11
|
+
- `world.set(id: string, patch: Record<string, any>) → WorldRecord` — Merge fields into a record and emit the world:change event; a position in patch also moves it. Returns the record. For discrete changes (chest opened, growth stage, picked up); if present has show, it is re-evaluated after the change. id / kind cannot be changed. Example: `engine.world.set('crate_1', { opened: true })`
|
|
12
|
+
- `world.move(id: string, position: any)` — Move a record (no event; use it in simulate for things that move every step); still saved (saves diff against content). The model of a positionFrom 'record' (default) record follows this frame; to do something else with the position in presentation, compare in update. Example: `engine.world.move(rec.id, { x: rec.position.x + 1, z: rec.position.z })`
|
|
13
|
+
- `world.remove(id: string)` — Remove a record (its model is torn down too) and emit the world:remove event. Does nothing if the id does not exist. Removing an initial record is saved, so it stays gone after loading
|
|
14
|
+
- `world.query(opts?: { kind?, near?, radius?, where?, zone? }) → WorldRecord[]` — Query records; returns an array. With near only nearby cells are scanned and results are sorted nearest first (radius defaults to 30 m); where filters further. For neighbor queries every step use forEachNear. Example: `engine.world.query({ kind: 'zombie', near: engine.player, radius: 30, where: z => !z.dead })`
|
|
15
|
+
- `world.forEachNear(center: any, radius: number, fn: (rec, d2) => void)` — Call fn(rec, d2) for each record within radius meters (horizontal distance) of center; d2 is the squared distance. Unsorted, no allocation: use it for per-step neighbor queries (hundreds of zombies avoiding each other). Don't add / remove / move in the callback (moving into a cell not yet visited visits it again): record the change and apply it after the loop. Example: `engine.world.forEachNear(rec.position, 5, (o, d2) => { if (o !== rec && o.kind === 'zombie') n++; })`
|
|
16
|
+
- `world.present(kind: string, opts: { build, update?, dispose?, show?, radius?, positionFrom? }) → { remove(): void }` — Register how a kind of thing looks: models are built automatically within radius meters of any full-detail stream source (engine.stream: player, camera focus, teleport destination) and torn down when far from all of them (radius × 1.25); tearing down never touches the record. Callbacks: build(rec) → three.js object (may be async). world adds it to the scene and places it at rec.position; if it throws / fails / returns a non-object: reported once, does not block ready, retried when you leave and come back. update(rec, obj, dt): called every frame for records that have a model (change the look from the data, e.g. an opened chest swaps texture). dispose(rec, obj): called on teardown (record first, model second); if omitted, engine.remove(obj). show(rec) → false: this record has no model right now (picked up, waiting to respawn); re-evaluated when world.set changes records of this kind. Example: `engine.world.present('chest', { build: rec => new THREE.Mesh(boxGeo, makeMaterial('prop')), dispose: (rec, obj) => engine.remove(obj), show: rec => !rec.looted })`
|
|
17
|
+
- `world.view(id: string) → any` — The current model of this record (only exists nearby; null if not built yet or far away)
|
|
18
|
+
- `world.refresh()` — Build / tear down models for the stream sources right now (normally automatic every frame, with a per-frame limit). Use it right after add when you need the model: sync builds are available via view(id) after the call, for async ones also await world.whenReady. Example: `engine.world.add({ id: 'gate', kind: 'gate', position: p }); engine.world.refresh(); engine.world.view('gate')`
|
|
19
|
+
- `world.simulate(kind: string, opts: { near?, far?, farEvery?, radius?, worker? }) → { remove(): void }` — Register how a kind of thing changes (gameplay logic goes here, runs in the fixed step); near / far is split by distance from world.anchor (default: the player): near(rec, dt, obj): within radius, once per fixed step (obj is the model, may be null if not built yet; gameplay must not depend on it); far(rec, dt): farther away, once every farEvery seconds; dt is the seconds accumulated since the last simulation (can catch up a long time at once); on the far → near step, far runs first to pay back the owed time. With only far (crops), near also advances via far; with only near, far records are not simulated and owed time is not made up. Both dt are accumulated fixed-step seconds (not multiplied by clock.timeScale). For things measured in game clock (grows over days) store engine.clock.now and compare. Example: `engine.world.simulate('zombie', { near: (rec, dt) => chase(rec, dt), far: (rec, dt) => wander(rec, dt), farEvery: 2 })`
|
|
20
|
+
- Properties:
|
|
21
|
+
- `records: Map<string, WorldRecord>` All records: id → record (read-only; use set to change fields, move to change position)
|
|
22
|
+
- `radius: number` Default distance (meters) for building models and counting as near; present / simulate can override it. Changing it at runtime affects those without their own radius
|
|
23
|
+
- `farEvery: number` Default interval (seconds) between far simulations, same unit as dt
|
|
24
|
+
- `farMaxPerTick: number` Max far simulations per fixed step; the rest queue for the next step (dt accumulates, no time is lost). Counted by records, not milliseconds, so results do not depend on machine speed
|
|
25
|
+
- `buildPerFrame: number` Max models built per frame; the rest continue next frame (ready waits for all of them; loading is not limited)
|
|
26
|
+
- `anchor: any` Gameplay simulation center (near / far is measured from it): null (default) = where engine.actor is (engine.actorPosition(): the player, or engine.focus when there is no player). The built-in stream source engine.stream.player follows the player too (models and colliders around it); the camera source engine.stream.camera adds models only. Example: `engine.world.anchor = baseObject`
|
|
27
|
+
- `zone: string | null` Current zone (e.g. level name, set by the level module on level change): once set, records of another zone get no model and no near simulation; null = no zoning
|
|
28
|
+
- `ready: boolean` All models that should exist near the stream sources are built (async ones too; failed builds do not count as pending). The loading screen waits for it; to wait yourself, await world.whenReady
|
|
29
|
+
- `whenReady: Promise<void>` Promise that resolves when ready becomes true
|
|
30
|
+
- `steps: number` Number of fixed steps simulated
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# Starting a new game (a workspace under games/)
|
|
2
|
+
|
|
3
|
+
Goal: create `games/farm/` (pick your own name) with its own page, modules, content data and tests, independent of other games. Start from the
|
|
4
|
+
template (`npx threedog new-game farm`, section 0); the engine's own example is `examples/world/` in the package.
|
|
5
|
+
|
|
6
|
+
## 0. One-command setup (preferred)
|
|
7
|
+
```
|
|
8
|
+
npm run new-game my-farm # minimal open world
|
|
9
|
+
npm run new-game my-farm --blank # flat ground, a player and a follow camera only
|
|
10
|
+
```
|
|
11
|
+
(npm treats `--blank` as its own config and the script reads it from the `npm_config_blank` environment variable, so write it exactly like this,
|
|
12
|
+
without `-- --blank`. The CLI form takes the flag directly: `npx threedog new-game my-farm --blank`.)
|
|
13
|
+
The name may only contain lowercase letters, digits and dashes; an existing directory under `games/` with the same name is refused. What it does:
|
|
14
|
+
1. Copies `packages/tools/templates/game/` to `games/my-farm/` (`__NAME__` in the files is replaced by the name).
|
|
15
|
+
2. Creates the `node_modules/@threedog/my-farm` link and updates the workspace entry in `package-lock.json` (if offline, only a warning).
|
|
16
|
+
3. Runs `map` (generates GAMEMAP.md), `check` and the game's smoke test in turn. Any failing step stops and says why.
|
|
17
|
+
|
|
18
|
+
The generated game is a minimal open world: `openWorld` + `interactions / inventory / content / hud`, 3 apples on the ground and one stash (a template
|
|
19
|
+
in `content/templates.js` placed by `content/props.js`, searched through the op `stash.search`); its `main.js` also shows the game's own state
|
|
20
|
+
registered with `describe.add` and `saves.register`, an op with `can` / `run`, and the `onFixed` / `onFrame` split; `--blank` copies the same template
|
|
21
|
+
without `content/` and replaces `main.js` with `templates/blank/main.js` (no inventory, no content). The structure is the same as the manual one below.
|
|
22
|
+
**Start clean from the full template** (when you did not use `--blank`): keep `createEngine`, `openWorld`, `start` and `window.engine`; replace the
|
|
23
|
+
contents of `content/items.js pickups.js props.js templates.js actions.js`; in `main.js` delete the `game` object (hp / hunger), the
|
|
24
|
+
`player.rest` op, the `onFixed` hunger timer, the HP counter in `onFrame` and the `stash.search` op; remove `sky: presets.calendar.cycle` if the
|
|
25
|
+
game has no day cycle. `spawn` and `places` take any `{ x, z }` (or `{ x, y, z }`); `findSpawn` is only for generated terrain.
|
|
26
|
+
To change the camera: `openWorld({ camera: 'firstPerson' })` (`follow` / `firstPerson` / `rts` / `fixed`, or pass a camera module directly; there is
|
|
27
|
+
no default).
|
|
28
|
+
- The comments in `main.js` list further gameplay modules you can add; usage is in `../api/<module>.md`.
|
|
29
|
+
- To change the starting point of new games, edit the real files in `packages/tools/templates/game/`.
|
|
30
|
+
- `DESIGN.md` is an empty template: write your gameplay ideas there. `CLAUDE.md` only points the way (read `node_modules/threedog/docs/AI.md` first,
|
|
31
|
+
then GAMEMAP, DESIGN) and does not copy engine rules.
|
|
32
|
+
- There is no `tests/`: when `tests/specs.mjs` does not exist, `npm test -w games/my-farm` runs a smoke test automatically.
|
|
33
|
+
|
|
34
|
+
## 1. Creating the files by hand (to learn what each file is, or when the template doesn't fit)
|
|
35
|
+
| File | Content |
|
|
36
|
+
|---|---|
|
|
37
|
+
| `games/farm/package.json` | Copy `package.json` from the game template (or run `npx threedog new-game farm`) and set `name` to `@threedog/farm` (dependencies `threedog`, `@threedog/tools`, plus `@threedog/style-lowpoly` (it needs `@threedog/post-effects` too) and `@threedog/terrain-noise` when `main.js` imports them; scripts dev/build/preview/test/check/map) |
|
|
38
|
+
| `games/farm/vite.config.js` | One line: `export default gameConfig(import.meta.dirname)` (imported from `@threedog/tools/vite`); *.html files in the directory are bundled automatically, no `input` needed. Without `@threedog/tools`, a plain vite config needs `worker: { format: 'es' }` (the engine's Workers are ES modules) or `vite build` fails; `threedog dev / build` on a folder with no vite config uses the preset |
|
|
39
|
+
| `games/farm/index.html` | The page: one `<canvas id="view">` with a CSS size + `/main.js` (for more pages put `xxx.html` in the same directory); see §5 for embedding |
|
|
40
|
+
| `games/farm/main.js` | Install modules, compute places, `content.load`, game-specific logic |
|
|
41
|
+
| `games/farm/content/index.js` | Combines the content files into one object |
|
|
42
|
+
| `games/farm/content/*.js` | Only these names are read: items pickups containers npcs dialogues quests actions places triggers level vegetation props templates audio grids renames rules, plus the game's own kinds (rules.js) |
|
|
43
|
+
| `games/farm/DESIGN.md` | Hand-written design decisions (a few lines of `- **decision**: reason`), copied into GAMEMAP.md |
|
|
44
|
+
| `games/farm/CLAUDE.md` | A few lines: read `node_modules/threedog/docs/AI.md`, then this directory's GAMEMAP.md and DESIGN.md (copy the template's) |
|
|
45
|
+
| `games/farm/public/` | This game's art assets (URL `/models/...`); keep Blender source files in `games/farm/art/models/`, `npm run assets -- -w farm` compresses them over |
|
|
46
|
+
|
|
47
|
+
After creating them, run `npm install` once at the repository root (this links the new game into the workspaces so `threedog` can find it).
|
|
48
|
+
|
|
49
|
+
Outside the engine repository, a game installs `threedog` and `three` (plus `@threedog/style-lowpoly` + `@threedog/post-effects` / `@threedog/terrain-noise` if it imports them,
|
|
50
|
+
and `@threedog/tools` as a dev dependency for the CLI and the vite preset). To use an engine folder on disk instead of npm, install it with
|
|
51
|
+
`npm install --install-links <folder>`: a plain link skips the engine's own dependencies (Rapier, Recast) and the build cannot resolve them.
|
|
52
|
+
|
|
53
|
+
In a game's own repository, `threedog check`, `types` and `map` read only the game's sources: `node_modules`, a `vendor/` folder and every `file:` /
|
|
54
|
+
`link:` dependency are skipped. To narrow it further, list the sources in the game's `package.json`:
|
|
55
|
+
`"threedog": { "src": ["main.js", "src", "content"], "exclude": ["notes"] }` (paths relative to the game folder; `src` defaults to the whole folder).
|
|
56
|
+
The template's `tsconfig.json` checks the game files only (`checkJs`), with `lib` ESNext + DOM (dependency typings such as Rapier's use
|
|
57
|
+
`Symbol.dispose`) and `skipLibCheck: true`; without a tsconfig, `threedog types` writes the same settings to `.threedog/tsconfig.types.json`.
|
|
58
|
+
|
|
59
|
+
`games/farm/index.html` (minimal; the template's `index.html` has the same page with loading styles):
|
|
60
|
+
```html
|
|
61
|
+
<!doctype html>
|
|
62
|
+
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
63
|
+
<title>农场</title><style>html,body{height:100%;margin:0;overflow:hidden;background:#141a17}#view{position:fixed;inset:0;width:100%;height:100%;display:block;outline:none}</style>
|
|
64
|
+
</head><body><canvas id="view" tabindex="0"></canvas><script type="module" src="/main.js"></script></body></html>
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`games/farm/main.js`:
|
|
68
|
+
```js
|
|
69
|
+
// Farm example: ... (this first comment line appears in the file table of GAMEMAP.md)
|
|
70
|
+
import { createEngine, presets, openWorld, interactions, dialogue, inventory, quests, entities, content } from 'threedog';
|
|
71
|
+
import lowpoly from '@threedog/style-lowpoly'; // optional style pack (the engine ships no art)
|
|
72
|
+
import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain generator (nor a world shape)
|
|
73
|
+
import data from './content/index.js';
|
|
74
|
+
|
|
75
|
+
const engine = createEngine({ canvas: document.getElementById('view'), style: lowpoly, ui: { loading: { title: '农场' } }, saveKey: 'farm' });
|
|
76
|
+
// the preset only covers world and environment; the debug panel is installed in dev builds only (debug: true forces it in release too)
|
|
77
|
+
engine.use(openWorld({ camera: 'follow', seed: 42, terrain: terrainPreset(), time: 0.3 }),
|
|
78
|
+
// add gameplay modules as the game needs (a shooter has no inventory)
|
|
79
|
+
interactions({ ...presets.interactions.nearest }), dialogue(), inventory({ ...presets.keys.inventory }), quests({ ...presets.keys.quests }), entities(),
|
|
80
|
+
content());
|
|
81
|
+
// the terrain is generated: find flat ground as "home" at the start (give your own height range to avoid beach and peaks)
|
|
82
|
+
const home = engine.characters.findSpawn([0, 0, 0], { minH: 3, maxH: 14 });
|
|
83
|
+
engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: home });
|
|
84
|
+
engine.content.load(data, { places: { home } }); // content places things relative to it with { place: 'home', x, z }
|
|
85
|
+
// tests, screenshots and the console all rely on it (before start, so the dev bridge can wait for it)
|
|
86
|
+
window.engine = engine;
|
|
87
|
+
await engine.start();
|
|
88
|
+
```
|
|
89
|
+
Every `openWorld` part takes `false` (leave it out) or its module's own options object, so you never have to drop the preset for one setting:
|
|
90
|
+
`openWorld({ seed: 42, camera: 'follow', sky: { seasons: ['wet', 'dry'], daysPerSeason: 28 }, characters: { npcs: false }, rigid: false, ambience:
|
|
91
|
+
false, debug: false })`;
|
|
92
|
+
`camera` is required (no default camera) and takes `'follow'` / `'firstPerson'` / `'rts'` / `'fixed'`, a camera module such as
|
|
93
|
+
`followCamera({ shoulder: 0.7 })`, or `false`. A game that wants only a few parts (an arena without terrain) turns the rest off the same way:
|
|
94
|
+
`openWorld({ camera: 'follow', terrain: false, vegetation: false, weather: false, water: false })`.
|
|
95
|
+
`saveKey` must differ per game, otherwise saves overwrite each other. The UI language follows the player's browser (Chinese browser -> Chinese,
|
|
96
|
+
otherwise English) unless you set `createEngine({ locale })`. A game without terrain (the city test page in the engine repository does this): register
|
|
97
|
+
the level generator function under `models` in `engine.assets.manifest({ name, models })`, use `level({ url: name })` and pick your own modules, then
|
|
98
|
+
create the player and install content in `level:loaded`.
|
|
99
|
+
|
|
100
|
+
`games/farm/content/index.js`:
|
|
101
|
+
```js
|
|
102
|
+
import items, { startItems } from './items.js';
|
|
103
|
+
import places from './places.js';
|
|
104
|
+
export default { items, startItems, places };
|
|
105
|
+
```
|
|
106
|
+
`content/places.js`: `export default { home: 'flat ground found at the start (coordinates computed in main.js)' };`
|
|
107
|
+
|
|
108
|
+
## 2. Verify
|
|
109
|
+
1. `npm run map` -> generates `games/farm/GAMEMAP.md`; check the "engine modules" and "page /" sections.
|
|
110
|
+
2. `npm run check` -> content validation points out wrong file names, ids and clock-time formats; `npm run types` finds misused engine APIs.
|
|
111
|
+
3. `npm run shot -- -w farm / --describe-only` -> the text has a `player` line with its position, the module list, and no "still loading".
|
|
112
|
+
4. `npm test -w games/farm` -> without `tests/specs.mjs` it runs a smoke test (the page opens, the engine is ready, the console has no errors); to
|
|
113
|
+
test gameplay, write `games/farm/tests/specs.mjs` in the style of the engine repository's `packages/engine/tests/specs.mjs`.
|
|
114
|
+
5. To see the picture: `npm run shot -- -w farm /` (one image in `games/farm/.threedog/shots/`); while developing run `npm run dev -w games/farm` (or
|
|
115
|
+
`npm run dev -- farm`) and open the printed address; read errors in `games/farm/.threedog/errors.log`.
|
|
116
|
+
|
|
117
|
+
## 3. Preset parts
|
|
118
|
+
Every `openWorld()` part takes `false` or its module's options object, for example
|
|
119
|
+
`openWorld({ camera: 'follow', sky: { seasons: ['wet', 'dry'], daysPerSeason: 28 }, debug: false })`. Gameplay modules (interactions, dialogue,
|
|
120
|
+
inventory, quests) are not in the preset: add them with `engine.use`. The debug panel is dev-only by default.
|
|
121
|
+
|
|
122
|
+
## 4. Feel presets (opt-in)
|
|
123
|
+
The engine applies no gameplay feel by itself: `weather()` alone has only a calm `clear`, `sky()` has no seasons, and the calls that need a feel
|
|
124
|
+
refuse to guess: `createPlayer()` throws `[player-control]` without `control`, `interactions()` throws `[interaction-setup]` without `pick` and keys,
|
|
125
|
+
`openWorld()` throws `[open-world-camera]` without `camera`. The core key table holds only movement and menu confirm / cancel; run, jump and interact
|
|
126
|
+
keys come from the game. `presets` holds named option objects a game picks on purpose; each only bundles options you could write yourself, so spread
|
|
127
|
+
and override:
|
|
128
|
+
```js
|
|
129
|
+
import { presets, weather, sky, followCamera, interactions } from 'threedog';
|
|
130
|
+
engine.use(sky(presets.calendar.fourSeasons), weather({ ...presets.weather.temperate, autoPool: ['clear', 'rain'] }), followCamera(presets.camera.overShoulder));
|
|
131
|
+
engine.use(interactions({ ...presets.interactions.facing })); // nearest / facing / aim, each with E
|
|
132
|
+
const player = engine.characters.createPlayer({ ...presets.player.lockOn, faceTarget: boss }); // none / thirdPerson / lockOn / aim / sideScroller
|
|
133
|
+
```
|
|
134
|
+
`presets.player.thirdPerson` is `{ control: 'camera', faceMode: 'move', runKeys: Shift, jumpKeys: Space, cameraFollow: true }`; written out by hand
|
|
135
|
+
the same player is `createPlayer({ control: 'camera', faceMode: 'move', runKeys: ['ShiftLeft', 'ShiftRight', 'PadLB'], jumpKeys: ['Space', 'PadA'],
|
|
136
|
+
cameraFollow: true })`.
|
|
137
|
+
Keys for any action can also come from `createEngine({ bindings: { interact: ['KeyF'] } })`; those win over the keys a module or preset passes.
|
|
138
|
+
|
|
139
|
+
## 5. Canvas size: full window, a page section, a split layout or an editor panel
|
|
140
|
+
The engine follows the canvas's own CSS box (a `ResizeObserver` on the canvas), not the window: renderer size, camera aspect, `input.pointer` (`x / y`
|
|
141
|
+
pixels and `ndcX / ndcY` relative to the canvas), `engine.pick`, `screenToGround`, `worldToScreen` and the HUD all use that box, and the engine's UI
|
|
142
|
+
root is laid exactly over it. So the layout decides:
|
|
143
|
+
```html
|
|
144
|
+
<style>#view{position:fixed;inset:0;width:100%;height:100%;display:block}</style> <!-- full window (the template) -->
|
|
145
|
+
<section style="position:relative;width:640px;height:360px"><canvas id="view" style="width:100%;height:100%;display:block"></canvas></section> <!-- in a page -->
|
|
146
|
+
```
|
|
147
|
+
A canvas with no CSS size takes its size from its own pixel buffer, which would grow on every resize; the engine then sizes it to the window and warns
|
|
148
|
+
once in dev. The pixel ratio (`createEngine({ pixelRatio })`, adaptive resolution) works as before on top of the CSS size.
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# Adding an NPC (schedule + dialogue)
|
|
2
|
+
|
|
3
|
+
Modules needed: `characters()` (NPCs on by default), `interactions({ ...presets.interactions.nearest })`, `dialogue()`; clock-time schedules need
|
|
4
|
+
`sky()` with a day cycle (`dayLength`, e.g. `presets.calendar.cycle`: without one the clock never moves and the NPC keeps to one stop). The
|
|
5
|
+
`openWorld()` preset already installs `characters()` and `sky()` but not `interactions({ ...presets.interactions.nearest })` or `dialogue()`, so add
|
|
6
|
+
them yourself: `engine.use(openWorld({ camera: 'follow', sky: presets.calendar.cycle, ...}), interactions({ ...presets.interactions.nearest }),
|
|
7
|
+
dialogue(), content())`.
|
|
8
|
+
|
|
9
|
+
## 1. Write data (recommended)
|
|
10
|
+
`games/<game>/content/npcs.js`:
|
|
11
|
+
```js
|
|
12
|
+
export default {
|
|
13
|
+
baker: {
|
|
14
|
+
name: '面包师',
|
|
15
|
+
colors: { body: 0xc89a5a, legs: 0x5b4a3a, hair: 0x3a2a1a }, // omit to use the style pack's default colors
|
|
16
|
+
start: { place: 'home', x: 6, z: -3 }, // starting position; omitted = the first stop of the schedule
|
|
17
|
+
schedule: [ // at is a clock time 'HH:MM'; at that time the NPC walks there (pathfinding is automatic)
|
|
18
|
+
{ at: '07:00', place: 'home', x: 6, z: -3 },
|
|
19
|
+
{ at: '13:00', place: 'river' },
|
|
20
|
+
{ at: '18:30', place: 'home', x: 2, z: 4 },
|
|
21
|
+
],
|
|
22
|
+
talk: 'baker', // a dialogue id in dialogues.js; press E when near
|
|
23
|
+
},
|
|
24
|
+
cat: { name: '猫', start: { place: 'home' }, behavior: 'wander', mind: { radius: 6 } }, // no schedule: write behavior + start, omit schedule
|
|
25
|
+
};
|
|
26
|
+
```
|
|
27
|
+
A content NPC takes every `npcs.add` option (`speed`, `talkRadius`, `arriveDistance`, `pathStep`, `repath`, `talkLabel`, `model`...) written as a
|
|
28
|
+
field; a misspelt one errors with the closest name. `start` and `schedule` are the content forms (clock strings, places); the key is the id.
|
|
29
|
+
`content/dialogues.js`:
|
|
30
|
+
```js
|
|
31
|
+
export default {
|
|
32
|
+
baker: {
|
|
33
|
+
speaker: '面包师',
|
|
34
|
+
nodes: {
|
|
35
|
+
start: {
|
|
36
|
+
text: [ // several variants: the first whose condition holds is used
|
|
37
|
+
{ if: { flag: 'metBaker' }, text: '又来啦?' },
|
|
38
|
+
{ text: '你好,第一次见。' },
|
|
39
|
+
],
|
|
40
|
+
do: { setFlag: 'metBaker' },
|
|
41
|
+
next: 'ask',
|
|
42
|
+
},
|
|
43
|
+
ask: { text: '要面包吗?', choices: [
|
|
44
|
+
{ text: '要一个', next: 'buy', if: { has: { coin: 1 } } },
|
|
45
|
+
{ text: '不用了' }, // a choice with no next = the dialogue ends; a plain node with no next waits for one more interact press, then ends
|
|
46
|
+
] },
|
|
47
|
+
buy: { text: '刚出炉的。', do: [{ take: { coin: 1 } }, { give: { bread: 1 } }], next: 'end' },
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
```
|
|
52
|
+
The words usable in conditions / effects are in the comment at the top of `modules/content/rules.js` (flag notFlag has lacks counter can / setFlag
|
|
53
|
+
give take bump startQuest toast particles marker clearMarker op).
|
|
54
|
+
The items used (coin, bread) must be defined in `items.js`, otherwise validation fails. A `place` name comes from `content.load(data, { places })` or
|
|
55
|
+
from a level marker (such as `npc_baker`). Add a new content file to `content/index.js`.
|
|
56
|
+
|
|
57
|
+
## 2. Add in code (temporary NPCs, dynamic schedules)
|
|
58
|
+
```js
|
|
59
|
+
engine.dialogue.define('passerby', { start: { text: '今天天气不错。', speaker: '路人' } });
|
|
60
|
+
const npc = engine.npcs.add({ id: 'passerby', name: '路人', position: [10, 0, 5], schedule: [{ at: '08:00', position: [20, 0, 5] }], talk: 'passerby' }); // at: 'HH:MM' or 0-1; without id the name is used
|
|
61
|
+
engine.npcs.remove('passerby'); // remove by id, name or handle
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**An NPC that stands still** (a quest giver): give `start` and omit both `schedule` and `behavior`; the default `schedule` behavior with no stops
|
|
65
|
+
has no goal, so it stays at `start`: `elder: { name: 'Elder', start: { x: 4, z: 6 }, talk: 'elder-hello' }`.
|
|
66
|
+
|
|
67
|
+
## NPC data and model (why npc.root is sometimes null)
|
|
68
|
+
The fact of an NPC is one record in the world data `engine.world` (kind `'npc'`, the id is the id above / the key in content): position, schedule,
|
|
69
|
+
current stop, in-dialogue, animation state and movement state are plain fields and are saved.
|
|
70
|
+
The character model is just an appearance built only near the player (world radius, default 60 meters): removed when you walk away and rebuilt when
|
|
71
|
+
you come near; changing level only removes the model, and it is rebuilt automatically when you return to that level.
|
|
72
|
+
- `npcs.add` returns a **handle**: `npc.data` (the record), `npc.position` (the model position when there is a model, otherwise the data position),
|
|
73
|
+
`npc.character` / `npc.root` (the current model, `null` if none), `npc.placeAt(p)`, `npc.remove()`.
|
|
74
|
+
- **Arrival tolerance**: within 1.2 meters of a stop (`arriveDistance`, default 1.2, can be set per NPC) counts as arrived and the NPC stops, without
|
|
75
|
+
stepping exactly on the stop center; for an exact position put the stop a bit away from obstacles, or `placeAt` yourself.
|
|
76
|
+
- Far away with no model, an NPC follows its schedule in a straight line (stops at the stop if reachable, otherwise on the line); when it comes back,
|
|
77
|
+
the model is built at the computed position; nearby it paths around obstacles as usual.
|
|
78
|
+
- Add things to the model (a hat, a name tag) after every model build; don't call `npc.root.add(...)` right after add (the first model is built in the
|
|
79
|
+
next fixed step; for one immediately use `engine.world.refresh()`).
|
|
80
|
+
- When two NPCs share a name, give each an `id` (without an id the name is the id, and in development a duplicate name throws). NPCs in content are
|
|
81
|
+
the world's **initial data**: the save records only changes such as position and state; schedule and name follow the content.
|
|
82
|
+
- Change data with `engine.world.set(npc.id, { mood: 'happy' })` (emits the world:change event); only plain values go in the data, models and
|
|
83
|
+
functions stay in code.
|
|
84
|
+
|
|
85
|
+
## Changing behavior / custom behavior
|
|
86
|
+
What an NPC "does" is a swappable **behavior**: the `behavior` field in the data picks it, and the schedule (`'schedule'`, the default) is just one of
|
|
87
|
+
them. Built in there is also `'wander'` (random wandering near home, using `engine.random`, same seed same result).
|
|
88
|
+
```js
|
|
89
|
+
npc.setBehavior('wander', { radius: 12 }); // home = current position, wander within 12 meters (pause: [2, 6] pause seconds, home: { x, z } sets the center)
|
|
90
|
+
npc.setBehavior('schedule'); // back to the schedule
|
|
91
|
+
engine.npcs.add({ id: 'dog', name: '小狗', position: [5, 0, 5], behavior: 'wander', mind: { radius: 8 } }); // wanders from the start
|
|
92
|
+
```
|
|
93
|
+
The behavior name and `mind` (the behavior's parameters and memory) are in the NPC data and are saved; after changing behavior or loading, the NPC
|
|
94
|
+
carries on with the new behavior. A wrong behavior name throws and lists the registered ones. NPCs in content can also write `behavior` + `mind`
|
|
95
|
+
directly (see the cat above); to change behavior at runtime use `npc.setBehavior`.
|
|
96
|
+
|
|
97
|
+
**An enemy that chases the player**: the `chase` behavior below is the example; in `near`, after your own `character.move`, call
|
|
98
|
+
`engine.npcs.avoid.push(rec, npc.character, dt)` once so several enemies don't pile into one clump (see "Avoidance" below). Things that are not NPCs
|
|
99
|
+
(monsters, crops) are written as world data, see recipe 18 section 5.
|
|
100
|
+
|
|
101
|
+
To write your own: `engine.npcs.behavior(name, { near(rec, dt, npc), far(rec, dt) })`, with the same rules as `world.simulate`: `near` is called once
|
|
102
|
+
per fixed step while nearby (`npc.character` is the model, `null` if not yet built), `far` simulates from data while far away (`dt` is accumulated
|
|
103
|
+
seconds and can be large; on the far -> near step `far` is used first to make up the owed time; without `far` the NPC stands still when far). The
|
|
104
|
+
behavior keeps no variables of its own; what must be remembered goes in `rec.mind` (plain values), otherwise it won't match after the model is removed
|
|
105
|
+
or after loading.
|
|
106
|
+
```js
|
|
107
|
+
// Chase the player: chase in a straight line when near, stand still within 2 meters of the player; do not chase when far. Register before npcs.add / setBehavior
|
|
108
|
+
engine.npcs.behavior('chase', {
|
|
109
|
+
near(rec, dt, npc) {
|
|
110
|
+
const p = npc.position, t = engine.player.position, dx = t.x - p.x, dz = t.z - p.z, d = Math.hypot(dx, dz) || 1;
|
|
111
|
+
npc.character?.move(d > 2 ? dx / d : 0, d > 2 ? dz / d : 0, false, dt); // no model: don't move
|
|
112
|
+
engine.world.move(rec.id, npc.position); // write the position back to the data
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
npc.setBehavior('chase');
|
|
116
|
+
```
|
|
117
|
+
To path around obstacles, use `engine.characters.findPath(from, to)` to get waypoints and walk them one by one (the schedule behavior does exactly
|
|
118
|
+
this, see `goTo` in `modules/characters/npcSim.js`).
|
|
119
|
+
|
|
120
|
+
## Avoidance (NPCs don't clump or pass through each other)
|
|
121
|
+
NPCs with models nearby avoid each other by default: when closer than the sum of two radii (`engine.movement.radius` x 2, about 0.8 meters) they push
|
|
122
|
+
each other apart, harder the more they overlap, at most 3 meters per second; the player counts as an obstacle that only NPCs yield to, and the
|
|
123
|
+
player's position is never pushed. After pushing, `engine.collision` (if installed) constrains them back to walkable ground, so they are not pushed
|
|
124
|
+
into walls. The built-in `schedule` and `wander` both avoid.
|
|
125
|
+
- Deterministic and cheap: done only in the fixed step, no random numbers, neighbors computed from "the positions at the start of this step", so after
|
|
126
|
+
save and load, or with a different `frameEvery`, positions are identical bit for bit; 400 NPCs with models cost less than 1 ms per step (a tight
|
|
127
|
+
clump only a few ms).
|
|
128
|
+
- Tune or turn off:
|
|
129
|
+
```js
|
|
130
|
+
engine.npcs.avoid.set({ radius: 0.6, strength: 2 }); // stand sparser (radius in meters), push slower (strength in meters/second)
|
|
131
|
+
engine.npcs.avoid.set(false); // turn off (ghosts, crowds passing through); set(true) turns it on again
|
|
132
|
+
```
|
|
133
|
+
- Far away (no model) NPCs are simulated from data without per-NPC avoidance; a few steps after a model is built on approach they get pushed apart.
|
|
134
|
+
- Difference from `nav({ crowd: true })`: when crowd is installed the Recast crowd agents take over and this is not applied on top. Crowd routes more
|
|
135
|
+
cleverly (around obstacles along the navmesh, yields to others) but does not guarantee identical results after loading; the simple push here does
|
|
136
|
+
not route around anything and only keeps NPCs from overlapping, with results identical after loading. For save replay and determinism use this; for
|
|
137
|
+
crowds going around big obstacles use crowd.
|
|
138
|
+
- Behaviors you write are not avoided automatically: after your own `character.move`, call `engine.npcs.avoid.push(rec, npc.character, dt)` once
|
|
139
|
+
(inside `near`, before writing back to the data).
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
## A guard you build yourself (`Character` + `walkTo`)
|
|
143
|
+
|
|
144
|
+
For a one-off (guard, pet, follower) that `schedule` / `wander` do not cover: `new Character(engine, { rig })` takes a ready body (same shape as
|
|
145
|
+
`style.character.create` returns: `{ root, body?, head?, limbs?, joints? }`) instead of the style pack's; call `character.animate(dt)` each frame.
|
|
146
|
+
`character.walkTo(target, { speed, arrive, turnRate, run })` follows `characters.findPath` on fixed steps (turns at `turnRate` rad/s, skips passed
|
|
147
|
+
points, re-plans when it makes no progress for `stuckSeconds`, up to `maxRepaths`). It returns a promise of `{ status }`: `'arrived'` | `'noPath'` |
|
|
148
|
+
`'stuck'` | `'cancelled'` (never rejects), with `remove()` to cancel.
|
|
149
|
+
|
|
150
|
+
```js
|
|
151
|
+
const guard = new Character(engine, { rig: { root: myGuardMesh } }).addTo();
|
|
152
|
+
guard.placeAt(post);
|
|
153
|
+
const walk = guard.walkTo(player.position, { arrive: 1.5 });
|
|
154
|
+
if ((await walk).status === 'noPath') guard.face(player); // walk.remove() cancels
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## 3. Verify
|
|
158
|
+
- `npm run check`: content validation catches "dialogue id does not exist", "bad clock-time format", "node next points to a missing node". After
|
|
159
|
+
`npm run map` it shows up in the NPC table and dialogue graph of GAMEMAP.md.
|
|
160
|
+
- State: `npm run shot -- / --time 13:10 --wait 20 --describe-only`; the "nearby" list has an entry for `面包师` tagged as an NPC with its distance in
|
|
161
|
+
meters (only listed within 30 meters; add `--pos x,z` to stand by the river).
|
|
162
|
+
- Console / tests: `engine.npcs.get('面包师').position`, `.currentStop()`; during a dialogue `engine.describe().ui.dialogue` = `{ speaker, text, typing, choices: [labels], lock }` (absent when no dialogue runs; the text version prints it as a `Dialogue:` line). `describe` does NOT expose the node id or the NPC id: `speaker` is the display name; to inspect the node, read the content file or listen to `engine.events.on("dialogue:line", ({ script, node, speaker, text }) => ...)` (also `dialogue:start` / `dialogue:end`).
|
|
163
|
+
- Advancing a dialogue in a headless test (typing and "keys ignored right after opening" both run on game time): press E when near -> `engine.step(1)`
|
|
164
|
+
to finish typing -> press a number key or run `engine.ops.run('dialogue.choose', { index: i })` (while typing it completes the sentence first) ->
|
|
165
|
+
`engine.step(0.3)`. No real-time waiting.
|
|
166
|
+
- Related tests: `npm test -- 小城` (the shopkeeper's schedule and dialogue), `npm test -- "S1 NPC"` (far-away simulation, changing level, saving,
|
|
167
|
+
identical results after loading).
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# Adding items and pickups
|
|
2
|
+
|
|
3
|
+
Modules needed: `inventory()` (inventory; the window is the UI part `inventory`, opened with the key the game gives:
|
|
4
|
+
`inventory({ ...presets.keys.inventory })` is I / gamepad Y, `keys: []` none; no module binds a key by itself) +
|
|
5
|
+
`interactions({ ...presets.interactions.nearest })` (walk up to an item on the ground and press E to pick it up). "Already picked up / how long until
|
|
6
|
+
it grows back" is data in world (needs the world module that `openWorld()` includes) and is saved with the game.
|
|
7
|
+
|
|
8
|
+
## 1. Write data (recommended)
|
|
9
|
+
`games/<game>/content/items.js`:
|
|
10
|
+
```js
|
|
11
|
+
// Items: id -> name, icon, description. stack = how many fit in one slot (default 99; more spill into further slots), weight (optional), color = color when dropped on the ground
|
|
12
|
+
export default {
|
|
13
|
+
mushroom: { name: '蘑菇', icon: '🍄', desc: '林子里捡的', color: 0xc0504d },
|
|
14
|
+
coin: { name: '铜币', icon: '🪙', stack: 99999 }, // currency: one slot however much you carry; full buying/selling in recipe 22
|
|
15
|
+
};
|
|
16
|
+
export const startItems = { coin: 3 }; // what the inventory holds at the start (optional)
|
|
17
|
+
```
|
|
18
|
+
`content/pickups.js` (a list):
|
|
19
|
+
```js
|
|
20
|
+
export default [
|
|
21
|
+
{ item: 'mushroom', place: 'home', x: 8, z: 3, respawn: 120 }, // respawn: after how many game seconds it grows back (omitted = never again)
|
|
22
|
+
{ item: 'coin', x: 40, z: -12, count: 5, auto: true }, // without place it is a world coordinate; count = how many at once; auto = taken by walking into it
|
|
23
|
+
{ item: 'sword', x: 12, z: 4, data: { durability: 60 } }, // data = this piece's own data (see "Single pieces"); radius = reach in meters (default 2)
|
|
24
|
+
];
|
|
25
|
+
```
|
|
26
|
+
Remember to `import items, { startItems } from './items.js'` and `import pickups from './pickups.js'` in `content/index.js` and put them in the exported object.
|
|
27
|
+
|
|
28
|
+
**Data and stable ids**: each pickup is a plain `kind: 'pickup'` record in `engine.world` (needs `world()`, which `openWorld()` includes); the model
|
|
29
|
+
is built only near the player and removed when far.
|
|
30
|
+
Id: if you write an `id` it is used; otherwise it is `pickup:<item>:<index in the pickups array>`, the same every time for the same content, and
|
|
31
|
+
distinguishes the same item placed at the same coordinates. **Write an `id` if the content will keep changing** (inserting a new one in the middle
|
|
32
|
+
shifts the later indices).
|
|
33
|
+
When picked up, the record is removed from world; one with `respawn` stays and gets an `until` (respawn time, game seconds); while waiting it has no
|
|
34
|
+
model, and at that time (also when far away with no model) `until` is cleared and it returns to the ground.
|
|
35
|
+
Pickups in content are the world's **initial data**: the save records only what was picked up and what is waiting to respawn; it makes no difference
|
|
36
|
+
whether `content.load` runs before or after loading, and picked-up items do not reappear; positions that use a level marker carry a `zone`, so after
|
|
37
|
+
changing level and coming back they are still picked up.
|
|
38
|
+
`engine.world.remove(id)` deletes one directly.
|
|
39
|
+
|
|
40
|
+
## 2. In code (dynamic drops, custom models)
|
|
41
|
+
```js
|
|
42
|
+
engine.inventory.define('gem', { name: '宝石', icon: '💎', color: 0x66ccff }); // shape: add mesh: (item, { color, size }, e) => Object3D | geometry, or model: 'generatorName', to set it on the item (wins over style.pickup.model; spawnPickup { mesh } wins over both)
|
|
43
|
+
const gem = engine.inventory.spawnPickup('gem', engine.player.position, { count: 1, respawnSeconds: 0 }); // returns a handle; gem.remove() deletes data and model together
|
|
44
|
+
// handle: { id: item, worldId: id in world, object: current model (null when far), remove() }; opts.id lets you write a stable id (spawning again with the same id reuses the existing one)
|
|
45
|
+
engine.inventory.add('coin', 2); // give directly; returns the entry key ('coin'), false if it doesn't fit
|
|
46
|
+
engine.inventory.remove('coin', 1); // returns false if there isn't enough
|
|
47
|
+
engine.inventory.has('coin', 2); // at least 2?
|
|
48
|
+
engine.inventory.spawnPickup('ammo', [8, 0, 2], { count: 30, auto: true, radius: 1.2 }); // taken on touch, no key, no prompt
|
|
49
|
+
engine.events.on('item:pickup', ({ id, x, z }) => engine.particles?.emit('dust', { x, y: engine.surface(x, z), z }, { count: 10 })); // events: item:add / item:remove / item:pickup / item:use ('dust' = a particle the game defined)
|
|
50
|
+
```
|
|
51
|
+
The default reach of pickups is `inventory({ pickupRadius: 2 })`; each pickup can set its own `radius`.
|
|
52
|
+
|
|
53
|
+
## Single pieces: durability, upgrade level, ammo in the magazine, freshness
|
|
54
|
+
An item can carry its own data (a plain object). Pieces with different data never mix; stackable pieces with equal data share an entry; a `stack: 1`
|
|
55
|
+
item with data is one entry per piece.
|
|
56
|
+
Each entry has a **key**: the item id for plain items (`'arrow'`), `'<item>#<n>'` for pieces with data (`'sword#3'`). Every call that takes an item
|
|
57
|
+
also takes a key.
|
|
58
|
+
```js
|
|
59
|
+
const I = engine.inventory;
|
|
60
|
+
I.define('sword', { name: 'Sword', stack: 1 });
|
|
61
|
+
const key = I.add('sword', 1, { data: { durability: 80, level: 3 } }); // 'sword#7'
|
|
62
|
+
I.count('sword'); // every sword, with or without data
|
|
63
|
+
I.get(key); // { key, id: 'sword', count: 1, data: { durability: 80, level: 3 }, def }
|
|
64
|
+
I.list(); // every entry: [{ key, id, count, data, def }] for your own UI
|
|
65
|
+
// change it inside an op or fixed step (data objects are frozen: always pass a new one; the key stays the same)
|
|
66
|
+
const s = I.get(key); I.setData(key, { ...s.data, durability: s.data.durability - 1 });
|
|
67
|
+
I.transfer('player', 'chest-1', key); // exactly this sword; it keeps its data and key
|
|
68
|
+
I.remove(key); // exactly this one; I.remove('sword') takes plain ones first, then the oldest
|
|
69
|
+
I.add('tomato', 5, { data: { quality: 2 } }); // stackable: equal data joins the same entry
|
|
70
|
+
I.setData('tomato#4', { quality: 1 }, 2); // only 2 of that stack change: they split off under a new key (returned)
|
|
71
|
+
```
|
|
72
|
+
Data and keys are saved with the container. Which piece a player means is chosen by key (a click on a row of `list()`), so ops take `item` as an id or a key.
|
|
73
|
+
|
|
74
|
+
## Limits (all optional, none by default)
|
|
75
|
+
`inventory({ ...presets.keys.inventory, capacity, maxWeight })` for the player and `inventory.container(id, { capacity, maxWeight })` for others:
|
|
76
|
+
`capacity` = slots (an entry uses `ceil(count / stack)`), `maxWeight` = sum of item `weight` × count. `room(item)` says how many more fit; `weight`
|
|
77
|
+
and `slotsUsed` read the totals. Locks, prices and "only one equipped" are game rules: check them in your op's `can`.
|
|
78
|
+
|
|
79
|
+
## Using and dropping (ops)
|
|
80
|
+
```js
|
|
81
|
+
I.define('potion', { name: 'Potion', consume: true, use: (e, { actor, key, data }) => heal(actor, 30), canUse: (e, { actor }) => hp(actor) < 100 || 'full' });
|
|
82
|
+
engine.ops.run('inventory.use', { item: 'potion' }); // runs canUse / use; consume removes one first; emits item:use
|
|
83
|
+
engine.ops.run('inventory.drop', { item: 'sword#7' }); // a pickup at the actor's feet, keeps its data
|
|
84
|
+
```
|
|
85
|
+
Both act on `ctx.actor`'s container (`'player'` by default).
|
|
86
|
+
|
|
87
|
+
**Replace an item when the bag is full**: `inventory.trade` takes A and gives B as one all-or-nothing step (it checks that B fits once A is gone), and
|
|
88
|
+
can be undone.
|
|
89
|
+
```js
|
|
90
|
+
const r = engine.ops.run('inventory.trade', { take: 'rusty_key', give: 'gold_key' }); // also takeN / giveN; take may be an entry key ('sword#3')
|
|
91
|
+
if (!r.ok) say(r.reason); // 'notEnough' (A missing) | 'full' (B does not fit even after A leaves)
|
|
92
|
+
engine.ops.undo('inventory.trade', { take: 'rusty_key', give: 'gold_key' }, r.value); // gives A back (with its data), takes B away
|
|
93
|
+
engine.inventory.trade('rusty_key', 'gold_key'); // the same from code; a container has .trade() too
|
|
94
|
+
```
|
|
95
|
+
**Why a pickup failed**: a pickup's `interaction.use` returns the reason as the op value:
|
|
96
|
+
`const r = engine.ops.run('interaction.use'); if (r.ok && r.value?.ok === false) say(r.value.reason); // 'full'` (the item stays on the ground).
|
|
97
|
+
|
|
98
|
+
## The inventory window (UI part `inventory`)
|
|
99
|
+
`inventory({ ...presets.keys.inventory, pauseGame: true })` freezes gameplay (`engine.freeze`, the same mechanism as flow's `paused`) while the window
|
|
100
|
+
is open; default `false` (the world keeps running behind the window). Switchable at runtime: `engine.inventory.pauseGame = true`.
|
|
101
|
+
|
|
102
|
+
The window is a UI part (recipe 26): the engine opens and closes it (the key from `inventory({ keys })`, Esc, input lock), the part only draws
|
|
103
|
+
`{ title, hint, items: list(), capacity, used, weight, maxWeight }`.
|
|
104
|
+
```js
|
|
105
|
+
engine.ui.set('inventory', false); // no window at all (the key does nothing, no DOM)
|
|
106
|
+
engine.ui.set('inventory', { drop: true }); // default window plus a Drop button per row (Use appears for items with use)
|
|
107
|
+
engine.ui.set('inventory', (engine) => { // your own: grid, drag and drop, anything
|
|
108
|
+
const el = document.createElement('div'); engine.uiRoot.appendChild(el);
|
|
109
|
+
el.onclick = ev => { const key = ev.target.dataset.key; if (key) engine.ops.run('inventory.use', { item: key }); }; // buttons run ops
|
|
110
|
+
return { show: d => { el.hidden = false; el.innerHTML = d.items.map(i => `<button data-key="${i.key}">${i.def.name} ×${i.count}</button>`).join(''); },
|
|
111
|
+
update: d => { el.innerHTML = d.items.map(i => `<button data-key="${i.key}">${i.def.name} ×${i.count}</button>`).join(''); },
|
|
112
|
+
hide: () => { el.hidden = true; }, dispose: () => el.remove() };
|
|
113
|
+
});
|
|
114
|
+
engine.ui.open('inventory'); engine.ui.close('inventory'); // open / close from code
|
|
115
|
+
```
|
|
116
|
+
The default look of items on the ground comes from the style pack's `style.pickup` (color, glow, size); a single item uses its own `color`; for a
|
|
117
|
+
custom model pass `{ mesh }` (a three.js object cannot go into a save, so after loading it falls back to the default look).
|
|
118
|
+
To give / take items in content use the effect words: `{ give: { coin: 2 } }`, `{ take: { mushroom: 3 } }`; condition words:
|
|
119
|
+
`{ has: { mushroom: 3 } }`, `{ lacks: { coin: 1 } }`.
|
|
120
|
+
|
|
121
|
+
## Chests / corpses / shelves (multiple containers)
|
|
122
|
+
The player inventory is just one container (id `'player'`). Chests, corpses, shelves and ammo boxes all use `inventory.container(id, { capacity })` to
|
|
123
|
+
get or create one (calling again with the same id returns the same one); limits as above. A container has the same
|
|
124
|
+
`add / remove / count / has / get / list / setData` as the inventory, plus `room(id)` (how many more fit) and `on('add' | 'remove', fn)` (returns a handle).
|
|
125
|
+
```js
|
|
126
|
+
const I = engine.inventory;
|
|
127
|
+
const chest = I.container('chest-1', { capacity: 8 });
|
|
128
|
+
chest.add('bandage', 2); // returns false if it doesn't fit (if part fits, that part is added)
|
|
129
|
+
I.transfer(chest, 'player', 'bandage', 1); // a container or a container id both work; returns how many were actually moved (fewer / 0 if the inventory is full)
|
|
130
|
+
I.transfer('player', chest, 'coin', 5); // shelves and money boxes work the same way
|
|
131
|
+
chest.on('remove', ({ id, count }) => console.log('taken', id, count)); // changes to the player inventory are item:add / item:remove; other containers emit container:add / container:remove (with an extra container id)
|
|
132
|
+
```
|
|
133
|
+
- **Relation to world**: a container id can be a world record's id directly (for example `'prop:chest:3'`, a zombie's id). Containers do not depend on
|
|
134
|
+
models: a far-away chest has no model but its contents still exist; contents are saved (containers that hold something, and those that were given
|
|
135
|
+
initial goods). Loading creates the containers first, and a later `container(id, { capacity })` in code just fills in the slot count, in either order.
|
|
136
|
+
- **Deleting a world record does not delete its container automatically** (whether to keep a searched corpse is up to the game). To clear both:
|
|
137
|
+
`engine.events.on('world:remove', ({ id }) => I.removeContainer(id))`.
|
|
138
|
+
- **Pre-filled contents (initial semantics)**: goods are placed only the **first** time; on load the save wins, and a searched-empty container is not
|
|
139
|
+
refilled after loading. Write `content/containers.js` in content (`export default { 'chest-1': { capacity: 8, items: { bandage: 2 } } }`, and put it
|
|
140
|
+
in the export of `content/index.js`), or in code `I.container('chest-1', { capacity: 8, items: { bandage: 2 } })`. For an already existing container
|
|
141
|
+
(created first by loading, or already created this session) `items` is not placed again; a container that was given goods goes into the save even
|
|
142
|
+
when searched empty (`{}`), so after a refresh and load it is empty and not refilled. Don't fill with `container(id).add(...)` at startup: a
|
|
143
|
+
container with nothing in it is not saved, so after a refresh it would be treated as new and filled again. A container id is any string and all are
|
|
144
|
+
saved ('shop-bakery' and 'prop:chest:3' alike).
|
|
145
|
+
- **UI**: the engine only makes the player inventory window; for a chest UI draw `chest.list()` yourself, and clicking an entry runs
|
|
146
|
+
`engine.ops.run('inventory.transfer', { from: 'chest-1', to: 'player', item: entry.key })`.
|
|
147
|
+
- Non-empty containers appear in `describe()` under `inventory.containers`.
|
|
148
|
+
|
|
149
|
+
## 3. Verify
|
|
150
|
+
- `npm run check`: an undefined item id in pickups or a missing place name is an error. After `npm run map`, GAMEMAP.md has the item table and the pickup count.
|
|
151
|
+
- Find the nearest of an item: `engine.inventory.nearestPickup('berry')` (world data, found even when far); all of them:
|
|
152
|
+
`engine.world.query({ kind: 'pickup' })`.
|
|
153
|
+
- `describe()`: `inventory.items` (key -> count, or `{ count, data }` for pieces with data), `inventory.slots`; items still on the ground appear in
|
|
154
|
+
`nearby` with `kind: 'pickup'` and `id`.
|
|
155
|
+
Text version: `npm run shot -- / --pos x,z --describe-only` shows the pickup entries in "nearby" and an `inventory: {...}` line.
|
|
156
|
+
- Simulate picking up (in tests): put the player next to the item with `engine.player.placeAt({ x, z })`, run `engine.ops.run('interaction.use')` (no
|
|
157
|
+
id = the nearest interaction) after `engine.step(0.2)`, then check `engine.inventory.count(id)`. Auto pickups need only `engine.step(0.2)` with the
|
|
158
|
+
player inside the radius.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Adding quests (with HUD objective markers)
|
|
2
|
+
|
|
3
|
+
Modules needed: `quests({ ...presets.keys.quests })` (quest log; the preset opens it with J / gamepad Select, or pass your own `keys`, `keys: []` for
|
|
4
|
+
none); objective markers need `hud()` (neither is in openWorld, add them yourself:
|
|
5
|
+
`engine.use(openWorld({ camera: 'follow', ...}), quests({ ...presets.keys.quests }), hud())`).
|
|
6
|
+
A quest is a list of steps completed in order; each step has one completion condition (or several parallel goals), checked every half second; a quest
|
|
7
|
+
may also fail. When the current step has a `target`, hud shows a marker and distance above it automatically, and an edge arrow when it is off-screen.
|
|
8
|
+
|
|
9
|
+
## 1. Write data (recommended)
|
|
10
|
+
`games/<game>/content/quests.js`:
|
|
11
|
+
```js
|
|
12
|
+
export default {
|
|
13
|
+
'mushroom-soup': {
|
|
14
|
+
title: '蘑菇汤',
|
|
15
|
+
desc: '面包师想要一锅蘑菇汤。',
|
|
16
|
+
startOn: 'engine:ready', // the event that starts it automatically (or use { startQuest: 'mushroom-soup' } in a dialogue)
|
|
17
|
+
steps: [
|
|
18
|
+
{ id: 'talk', text: '和面包师聊聊', done: { flag: 'metBaker' }, target: { npc: 'baker' } }, // the marker follows the NPC
|
|
19
|
+
{ id: 'gather', text: '采 3 个蘑菇', done: { has: { mushroom: 3 } }, target: 'forest' }, // a place name
|
|
20
|
+
{ id: 'return', text: '回到小屋门口', done: { flag: 'soupDone' }, target: { place: 'home', x: 0, z: 3 } },
|
|
21
|
+
],
|
|
22
|
+
reward: [{ take: { mushroom: 3 } }, { give: { coin: 5 } }, { toast: '蘑菇汤做好了!' }],
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
```
|
|
26
|
+
`target` forms: a place name, `{ place, x, z }`, `{ x, z }` (world coordinates; any of these may add `floor` / `y` for a storey on multi-layer ground,
|
|
27
|
+
as in props), `{ npc: 'id in npcs.js' }`, `{ nearest: 'itemId' }` (the closest not-yet-picked-up pickup of that kind to the player; hidden
|
|
28
|
+
automatically once picked up).
|
|
29
|
+
In code you can also write a function `target: () => target or null` (evaluated every frame); to change the target of a manual marker use
|
|
30
|
+
`engine.hud.marker(...).setTarget(newTarget)`.
|
|
31
|
+
Give every step (and every part of a parallel step) a stable `id`: saves store progress by it, so inserting or reordering steps after release never
|
|
32
|
+
moves a player's progress (without ids the position is the id). A save that names a step id the quest no longer has restarts that quest from its first
|
|
33
|
+
step, with a dev warning (code `quest-step`).
|
|
34
|
+
Completion conditions use the condition words (flag has counter...); to count "how many times", call `engine.vars.bump('name')` in code and write the
|
|
35
|
+
condition as `{ counter: { name: 3 } }`.
|
|
36
|
+
|
|
37
|
+
### Parallel goals, optional goals, failing
|
|
38
|
+
Not every quest is a straight line. A step can hold several goals done in any order (`all`); a goal marked `optional` never holds the step back;
|
|
39
|
+
`fail` ends the quest early:
|
|
40
|
+
```js
|
|
41
|
+
'defend-camp': {
|
|
42
|
+
title: '守住营地',
|
|
43
|
+
startOn: 'engine:ready',
|
|
44
|
+
steps: [
|
|
45
|
+
{ text: '赶到营地', done: { flag: 'atCamp' }, target: 'camp' },
|
|
46
|
+
{ all: [ // text defaults to the required goals: "守住北门 / 守住南门"
|
|
47
|
+
{ text: '守住北门', done: { counter: { northWaves: 3 } }, target: 'northGate' },
|
|
48
|
+
{ text: '守住南门', done: { counter: { southWaves: 3 } }, target: 'southGate' },
|
|
49
|
+
{ text: '没有村民受伤', done: { notFlag: 'villagerHurt' }, optional: true }, // a bonus: never blocks, shown done if met in time
|
|
50
|
+
] },
|
|
51
|
+
],
|
|
52
|
+
fail: { flag: 'campBurned' }, // checked while the quest is active
|
|
53
|
+
onFail: [{ toast: '营地失守了' }, { setFlag: 'mayRetryCamp' }],
|
|
54
|
+
reward: { give: { coin: 20 } },
|
|
55
|
+
},
|
|
56
|
+
```
|
|
57
|
+
- hud marks every unfinished goal of the current parallel step; `quests.list()` gives that step `parts: [{ text, target, optional, done }]`.
|
|
58
|
+
- Events: `quest:part` `{ id, step, part }` when one goal is met (give a bonus for an optional goal here), `quest:fail` `{ id }`.
|
|
59
|
+
- A failed quest is not active (`isFailed(id)`); `quests.start(id)` (or `{ startQuest }`) takes it again from step 1 — daily orders, retries.
|
|
60
|
+
|
|
61
|
+
## 2. In code (complex conditions, or when you need functions)
|
|
62
|
+
```js
|
|
63
|
+
engine.quests.define('fish3', {
|
|
64
|
+
title: '钓三条鱼',
|
|
65
|
+
steps: [{ text: '钓到 3 条鱼', done: e => e.vars.counter('fish') >= 3, target: () => engine.npcs.get('面包师')?.position }], // the function returns a position every frame: when the NPC is far away and has no model, root is null, so read position from the data
|
|
66
|
+
reward: e => e.inventory.add('coin', 3),
|
|
67
|
+
});
|
|
68
|
+
engine.quests.start('fish3');
|
|
69
|
+
engine.vars.bump('fish'); // each time a fish is caught
|
|
70
|
+
engine.events.on('quest:done', ({ id }) => { /* quest completed */ }); // there are also quest:start, quest:step, quest:part and quest:fail
|
|
71
|
+
```
|
|
72
|
+
To turn off automatic markers: `hud({ questMarkers: false })`. To add a marker by hand: `const m = engine.hud.marker('river', { label: '河边' }); m.remove();`;
|
|
73
|
+
content effects can add them too: `{ marker: 'river' }` / `{ clearMarker: 'river' }`. A counter in the screen corner:
|
|
74
|
+
`engine.hud.counter('fish', { icon: '🐟', label: '鱼', value: 2, max: 3 })`.
|
|
75
|
+
|
|
76
|
+
## 3. Verify
|
|
77
|
+
- `npm run check`: a wrong item / flag / place name / NPC id in a step is an error; "flag is only checked but never set" is a warning. After
|
|
78
|
+
`npm run map`, GAMEMAP.md has the quest step table.
|
|
79
|
+
- `describe().quests`: `active: [{ id, title, step: current step text }]`, `done: number completed`, `failed: number failed` (in describeText it is a
|
|
80
|
+
`quests: {...}` line).
|
|
81
|
+
In more detail: `engine.quests.list()` (each step has `current/done/target`), `engine.quests.isActive(id)`; story flags in `engine.vars.flags`.
|
|
82
|
+
- Objective markers: `describe().hud.markers` has `{ label: quest title, distance: meters, onScreen }`; counters are in `describe().hud.counters`.
|
|
83
|
+
- After advancing a condition you don't have to wait: `engine.quests.check()` checks immediately. Related test: `npm test -- 目标指示`.
|