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,235 @@
|
|
|
1
|
+
// Character: procedural rig (from the style pack, gray capsule without one) or glTF model + procedural animation (walk, run, swim, idle breathing)
|
|
2
|
+
// + movement control (ground snap, collision, slope limit, swimming).
|
|
3
|
+
// Used by both player and NPCs. To switch to a skeletal glTF model later, pass model + clips (or an animation state machine config); control logic stays the same.
|
|
4
|
+
// The mover owns position: only the mover (movers/) changes a character's position inside move(); other systems (pathfinding, triggers, vehicles, loading)
|
|
5
|
+
// request movement via placeAt (teleport), move (direction), enter / exit (vehicles).
|
|
6
|
+
// Characters backed by a world record (the player, recordId = 'player') write position and motion state back to the record after every move / placeAt / enter / exit;
|
|
7
|
+
// the record is saved, world splits near/far by it, the model is just its look.
|
|
8
|
+
// Radius and step height default to engine.movement (the single source of "can walk through" parameters); passing radius / stepHeight overrides it for this character only.
|
|
9
|
+
// How to walk is decided by the mover (movers/: 'simple' default, 'rapier' character controller); feel parameters are identical for both.
|
|
10
|
+
// The procedural body (capsule, style-pack rig, limb swing) is in proceduralRig.js.
|
|
11
|
+
import * as THREE from 'three';
|
|
12
|
+
import { xzOf } from '../../core/math.js';
|
|
13
|
+
import { placeY } from '../../core/ground.js';
|
|
14
|
+
import { warnOnce, warnMissing } from '../../core/validate.js';
|
|
15
|
+
import { reportError } from '../../core/errors.js';
|
|
16
|
+
import { simpleMover } from './movers/simple.js';
|
|
17
|
+
import { rapierMover } from './movers/rapier.js';
|
|
18
|
+
import { loadAssetModel } from './assetModel.js';
|
|
19
|
+
import { NO_CHARACTER, capsule, useRig, animateRig } from './proceduralRig.js';
|
|
20
|
+
import { walkTo } from './walkTo.js';
|
|
21
|
+
import { useModel } from './useModel.js';
|
|
22
|
+
|
|
23
|
+
const STRINGS = { noClip: 'character has no skeletal animation; playAction(\'{name}\') skipped (the model needs this action)' };
|
|
24
|
+
const MOVERS = { simple: simpleMover, rapier: rapierMover };
|
|
25
|
+
// Default action names for the clips shorthand (character state -> glTF action name)
|
|
26
|
+
|
|
27
|
+
// Options Character understands (shared by player and NPC)
|
|
28
|
+
export const CHARACTER_KEYS = ['colors', 'speed', 'runSpeed', 'radius', 'canSwim', 'swimDepth', 'swimSpeed', 'turnSpeed', 'acceleration', 'gravity',
|
|
29
|
+
'jumpSpeed', 'stepHeight', 'airControl', 'coyoteTime', 'canJump', 'model', 'clips', 'animation', 'mover', 'faceMode', 'faceTarget', 'rig'];
|
|
30
|
+
const FACE_MODES = ['move', 'camera', 'target', 'manual'];
|
|
31
|
+
|
|
32
|
+
export class Character {
|
|
33
|
+
/**
|
|
34
|
+
* @param engine
|
|
35
|
+
* @param o colors: { body, skin, legs, hair } (default from style pack style.character.colors)
|
|
36
|
+
* speed walk speed, runSpeed run speed (m/s), radius collision radius
|
|
37
|
+
* canSwim whether it can swim (false: never enters water), swimDepth water depth at which swimming starts, swimSpeed swim speed multiplier
|
|
38
|
+
* turnSpeed how fast it turns, acceleration how fast it starts/stops
|
|
39
|
+
* jump and gravity: gravity (negative), jumpSpeed takeoff speed, stepHeight step height it can climb directly, airControl air steering 0-1,
|
|
40
|
+
* coyoteTime how long after leaving a ledge a jump is still allowed, canJump
|
|
41
|
+
* model + clips: optional glTF model and action-name map { idle, walk, run, swim, jump, fall, drive } (shorthand for animation)
|
|
42
|
+
* animation: animation state machine config (see core/Animator.js), state names are character state names;
|
|
43
|
+
* without walk/run, move (blend tree, param speed) is used
|
|
44
|
+
* rig: a ready body in the format style.character.create returns (proceduralRig.js), used instead of the style pack's (hand-built guard / pet)
|
|
45
|
+
* mover: 'simple' (default) | 'rapier' (Rapier character controller, needs the rigid module)
|
|
46
|
+
* faceMode which way it turns each move: 'move' (default, toward its velocity) | 'camera' (along cameraRig.forward(), over-the-shoulder aiming)
|
|
47
|
+
* | 'target' (toward faceTarget: Object3D / Vector3 / { x, z }, lock-on strafing) | 'manual' (only face() turns it);
|
|
48
|
+
* both are plain properties, change them at any time
|
|
49
|
+
* model may be a registered asset name (default style.character.model): placeholder body until it loads, then swapped in (assetModel.js)
|
|
50
|
+
* without model: style pack style.character.create(engine, colors) may return a custom procedural character (rig format below), else a gray capsule
|
|
51
|
+
*/
|
|
52
|
+
constructor(engine, { colors = {}, speed = 4.5, runSpeed = 7, radius = engine.movement.radius, canSwim = true, swimDepth = 1.0, swimSpeed = 0.45,
|
|
53
|
+
turnSpeed = 10, acceleration = 12, gravity = -24, jumpSpeed = 8, stepHeight = engine.movement.stepHeight, airControl = 0.35, coyoteTime = 0.12,
|
|
54
|
+
canJump = true,
|
|
55
|
+
model = null, clips = null, animation = null, mover = 'simple', faceMode = 'move', faceTarget = null, rig = null } = {}) {
|
|
56
|
+
this.engine = engine;
|
|
57
|
+
Object.assign(this, { speed, runSpeed, radius, canSwim, swimDepth, swimSpeedFactor: swimSpeed, turnSpeed, acceleration, gravity, jumpSpeed, stepHeight,
|
|
58
|
+
airControl, coyoteTime, canJump });
|
|
59
|
+
if (!FACE_MODES.includes(faceMode)) warnMissing('faceMode', faceMode, FACE_MODES);
|
|
60
|
+
this.faceMode = faceMode; this.faceTarget = faceTarget;
|
|
61
|
+
this.vy = 0; this.grounded = true; this._coyote = 0; this._jumpBuffer = 0; this._push = 0;
|
|
62
|
+
this.onStep = null; this.onLand = null;
|
|
63
|
+
this.root = new THREE.Group();
|
|
64
|
+
this.velocity = new THREE.Vector2();
|
|
65
|
+
this.facing = 0; this.phase = 0; this.moveAmount = 0;
|
|
66
|
+
this.swimming = false; this.state = 'idle';
|
|
67
|
+
this.vehicle = null; this.anim = null;
|
|
68
|
+
/** false while a model named by asset loads (placeholder shows); await whenReady */
|
|
69
|
+
this.ready = true;
|
|
70
|
+
/**
|
|
71
|
+
* id of the world record ('player' for the player); once set, position, facing and motion state are written back to it.
|
|
72
|
+
* Do not world.move this record directly; use placeAt
|
|
73
|
+
* @type {string | null}
|
|
74
|
+
*/
|
|
75
|
+
this.recordId = null;
|
|
76
|
+
if (!MOVERS[mover]) warnMissing('mover', mover, Object.keys(MOVERS));
|
|
77
|
+
const simple = simpleMover(this);
|
|
78
|
+
this.mover = mover === 'rapier' ? rapierMover(this, simple) : simple;
|
|
79
|
+
// default look comes from style pack style.character.colors; neutral gray without a style pack
|
|
80
|
+
const c = { body: 0x8a8a8a, skin: 0xc8bfb5, legs: 0x5a5a5a, hair: 0x4a4a4a, ...(engine.style.character?.colors || {}), ...colors };
|
|
81
|
+
|
|
82
|
+
model ??= engine.style.character?.model ?? null;
|
|
83
|
+
if (model && typeof model !== 'string') { this._useModel(model, clips, animation); return; }
|
|
84
|
+
// style-pack procedural character: the rig format is in proceduralRig.js
|
|
85
|
+
rig ??= engine.style.character?.create?.(engine, c);
|
|
86
|
+
if (!rig && !model) warnOnce(NO_CHARACTER);
|
|
87
|
+
useRig(this, rig || capsule(c.body, engine));
|
|
88
|
+
if (model) this._whenReady = loadAssetModel(this, model, m => this._useModel(m, clips, animation));
|
|
89
|
+
}
|
|
90
|
+
_useModel(model, clips, animation) { useModel(this, model, clips, animation); }
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Walk to a point along characters.findPath on fixed steps (turn rate, skips passed points, re-plans when stuck). Returns a promise of
|
|
94
|
+
* { status: 'arrived' | 'noPath' | 'stuck' | 'cancelled' } (never rejects) with remove() to cancel; a new walkTo, dispose() or a save load cancels it (not saved). speed m/s, arrive metres, turnRate rad/s
|
|
95
|
+
* @example await guard.walkTo(player.position, { arrive: 1.5 })
|
|
96
|
+
*/
|
|
97
|
+
walkTo(target, opts) { return walkTo(this, target, opts); }
|
|
98
|
+
|
|
99
|
+
/** Request a jump (call when the jump key is pressed; has a jump buffer, so pressing slightly before landing counts) */
|
|
100
|
+
jump() { if (this.canJump) this._jumpBuffer = 0.12; }
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Move at a fixed velocity (m/s, world x/z) for `seconds`, ignoring the direction passed to move() and without turning: knockback, dodge-roll displacement, lunges.
|
|
104
|
+
* Gravity, collision and ground snap still apply; move() must still be called every fixed step (the default player control does)
|
|
105
|
+
* @example player.push(-toEnemy.x * 6, -toEnemy.z * 6, 0.15) // knocked back, still facing the attacker
|
|
106
|
+
*/
|
|
107
|
+
push(vx, vz, seconds) { this._pushX = vx; this._pushZ = vz; this._push = seconds; }
|
|
108
|
+
|
|
109
|
+
/** Settles (never rejects) once a model named by asset is swapped in or failed; already settled otherwise */
|
|
110
|
+
get whenReady() { return this._whenReady ?? Promise.resolve(); }
|
|
111
|
+
get position() { return this.root.position; }
|
|
112
|
+
/** The character's three.js root object (= root): add children, set visible, scale on it */
|
|
113
|
+
get object() { return this.root; }
|
|
114
|
+
addTo(scene = this.engine.scene) { scene.add(this.root); return this; }
|
|
115
|
+
/** Place on the ground at a position (Vector3 / Object3D / [x, y, z] / { x, z }) */
|
|
116
|
+
placeAt(position) { const [x, z] = xzOf(position); this.root.position.set(x, placeY(this.engine, 'character.placeAt()', x, z, undefined, this.root.position.y), z); this._store(); return this; }
|
|
117
|
+
/** Write position and motion state back to the world record (only if recordId is set; saveMotion writes into the record without allocating) @internal */
|
|
118
|
+
_store() { const id = this.recordId; if (id) { const W = this.engine.world; this.saveMotion(W.get(id)); W.move(id, this.root.position); } }
|
|
119
|
+
/** After moving root yourself (a cutscene path, a scripted pose): write position and motion back to the world record, so a save right after has it */
|
|
120
|
+
syncRecord() { this._store(); return this; }
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Move along a direction (call once per fixed step). dirX/dirZ is a world-space direction (length 0-1), run toggles running.
|
|
124
|
+
* How it walks is decided by this.mover ('simple' default / 'rapier'); while driving it follows the seat.
|
|
125
|
+
*/
|
|
126
|
+
move(dirX, dirZ, run, dt, speedOverride) {
|
|
127
|
+
if (this.vehicle) { this.root.position.copy(this.vehicle.seatPosition()); this.moveAmount = Math.abs(this.vehicle.speed); this.state = 'drive'; }
|
|
128
|
+
else this.mover.move(dirX, dirZ, run, dt, speedOverride);
|
|
129
|
+
this._store();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Enter a vehicle (returned by rigid.addVehicle): hides the character and stops movement; the camera follows the car. No-op if the vehicle already has a driver */
|
|
133
|
+
enter(vehicle) {
|
|
134
|
+
if (this.vehicle || vehicle.driver) return;
|
|
135
|
+
const e = this.engine;
|
|
136
|
+
this.vehicle = vehicle; vehicle.driver = this;
|
|
137
|
+
if (e.player === this) this._driveCtx = e.input.push('vehicle', { pass: true }); // driving: brake lives in this context, walking-only keys are shadowed
|
|
138
|
+
if (e.player === this && !e.input.actions.has('brake')) warnOnce("[input-keys] the player drives without a brake key: no module binds one by itself. characters({ ...presets.keys.brake }) (B / gamepad LT) or characters({ brakeKeys: ['KeyX'], brakePad: ['PadLT'] })");
|
|
139
|
+
this.root.visible = false; this.velocity.set(0, 0); this.vy = 0; this.swimming = false; this.state = 'drive'; this._store();
|
|
140
|
+
// only when the game asked the camera to follow the player (createPlayer({ cameraFollow }))
|
|
141
|
+
if (e.player === this && this.cameraFollow) e.cameraRig?.follow(vehicle.object, vehicle.camera);
|
|
142
|
+
e.events.emit('vehicle:enter', { character: this, vehicle });
|
|
143
|
+
}
|
|
144
|
+
/** Exit: step out beside the door, camera returns to the character */
|
|
145
|
+
exit() {
|
|
146
|
+
const v = this.vehicle, e = this.engine;
|
|
147
|
+
if (!v) return;
|
|
148
|
+
v.drive(0, 0, 1); v.driver = null; this.vehicle = null;
|
|
149
|
+
this._driveCtx?.remove(); this._driveCtx = null;
|
|
150
|
+
this.placeAt(v.exitPosition()); this.root.visible = true; this.grounded = true; this.state = 'idle';
|
|
151
|
+
if (e.player === this && this.cameraFollow) e.cameraRig?.follow(this.root);
|
|
152
|
+
e.events.emit('vehicle:exit', { character: this, vehicle: v });
|
|
153
|
+
}
|
|
154
|
+
/** Dispose this character completely: exit the vehicle first, release animation and mover, remove from the scene and dispose geometries and materials */
|
|
155
|
+
dispose() {
|
|
156
|
+
this._disposed = true; // a model still loading by asset name is dropped on arrival
|
|
157
|
+
this._walk?.remove(); // a walk in progress ends 'cancelled' (walkTo.js)
|
|
158
|
+
this.exit();
|
|
159
|
+
this.anim?.dispose();
|
|
160
|
+
this.mover.dispose?.();
|
|
161
|
+
this.engine.remove(this.root);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Copy motion state into a plain object (written into out, in place, no allocation): velocity, vertical speed, facing, move amount, grounded, swimming
|
|
165
|
+
* (animation state is stored by the caller).
|
|
166
|
+
* Why: the model is only a presentation of world data, torn down when far and rebuilt on load; keeping these in data lets loadMotion continue after a rebuild,
|
|
167
|
+
* so running continuously and "save -> load -> continue" give the same result (NPCs, future enemies and zombies all use it).
|
|
168
|
+
*/
|
|
169
|
+
saveMotion(out = {}) {
|
|
170
|
+
out.vx = this.velocity.x; out.vz = this.velocity.y; out.vy = this.vy; out.facing = this.facing; out.amount = this.moveAmount;
|
|
171
|
+
out.grounded = this.grounded; out.swimming = this.swimming; out.coyote = this._coyote;
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
/** Restore motion state from a saveMotion plain object (call after building the model / loading; missing fields keep defaults) */
|
|
175
|
+
loadMotion(m) {
|
|
176
|
+
if (!m) return this;
|
|
177
|
+
this.velocity.set(m.vx ?? 0, m.vz ?? 0); this.vy = m.vy ?? 0; this.facing = m.facing ?? 0; this.root.rotation.y = this.facing;
|
|
178
|
+
this.moveAmount = m.amount ?? 0; this.grounded = m.grounded ?? true; this.swimming = !!m.swimming; this._coyote = m.coyote ?? 0;
|
|
179
|
+
return this;
|
|
180
|
+
}
|
|
181
|
+
/** Play a one-shot action (e.g. 'wave', returns to the previous state when done); procedural characters have no actions, warn once and skip */
|
|
182
|
+
playAction(name) {
|
|
183
|
+
if (this.anim) this.anim.action(name);
|
|
184
|
+
else warnOnce(STRINGS.noClip.replace('{name}', name));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Ground type under the feet (terrain groundType or level material name); 'water' while swimming. Footstep sounds map it via audio.footsteps */
|
|
188
|
+
groundType() {
|
|
189
|
+
if (this.swimming) return 'water';
|
|
190
|
+
const p = this.root.position;
|
|
191
|
+
return this.engine.groundType(p.x, p.z);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Turn at once to face a point (Object3D / Vector3 / { x, z }) or an angle in radians (0 = +Z, PI / 2 = +X).
|
|
196
|
+
* With faceMode 'manual' this is the only thing that turns the character
|
|
197
|
+
* @example npc.face(engine.player); player.face(Math.PI)
|
|
198
|
+
*/
|
|
199
|
+
face(target) {
|
|
200
|
+
if (typeof target === 'number') this.facing = target;
|
|
201
|
+
else { const [x, z] = xzOf(target); this.facing = Math.atan2(x - this.root.position.x, z - this.root.position.z); }
|
|
202
|
+
this.root.rotation.y = this.facing;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Run fn(character, dt) every frame right after this character's animation pose is applied (model clips or procedural rig), so a game can attach things to bones
|
|
207
|
+
* or adjust bones on top of the pose. Returns a handle; h.remove() stops it. Presentation only: never read it for gameplay timing.
|
|
208
|
+
* @param {(character: Character, dt: number) => void} fn
|
|
209
|
+
* @returns {{ remove(): void }}
|
|
210
|
+
* @example const h = player.onPose(() => sword.position.copy(player.object.getObjectByName('Hand_R').getWorldPosition(v)));
|
|
211
|
+
*/
|
|
212
|
+
onPose(fn) { (this._poseFns ??= new Set()).add(fn); return { remove: () => this._poseFns.delete(fn) }; }
|
|
213
|
+
/** @internal */
|
|
214
|
+
_firePose(dt) { if (this._poseFns?.size) for (const f of [...this._poseFns]) { try { f(this, dt); } catch (err) { reportError(this.engine, err, 'character.onPose callback'); } } }
|
|
215
|
+
/** @internal Call every frame: play animation */
|
|
216
|
+
animate(dt) { this._animate(dt); if (!this.anim) this._firePose(dt); }
|
|
217
|
+
/** @internal */
|
|
218
|
+
_animate(dt) {
|
|
219
|
+
const sp = this.moveAmount, t = this.engine.elapsed, st = this.state;
|
|
220
|
+
this.phase += dt * (2.2 + sp * 1.25);
|
|
221
|
+
const s = Math.sin(this.phase);
|
|
222
|
+
// footstep event: fires once per foot landing (swing direction flips); model and procedural animation share this rhythm
|
|
223
|
+
if (this.onStep && this.grounded && sp > 0.4 && Math.sign(s) !== Math.sign(this._lastS ?? s)) this.onStep(this.groundType());
|
|
224
|
+
this._lastS = s;
|
|
225
|
+
if (this.anim) {
|
|
226
|
+
const a = this.anim;
|
|
227
|
+
a.set('speed', sp);
|
|
228
|
+
// state missing in the model: walk/run fall back to move (blend tree), then to idle
|
|
229
|
+
a.go(a.states[st] ? st : (st === 'walk' || st === 'run') && a.states.move ? 'move' : 'idle');
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (st === 'drive') return;
|
|
233
|
+
animateRig(this, sp, t, st);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// NPC: what it does is decided by a behavior (default schedule: go to different places by time of day; also wander, or register your own);
|
|
2
|
+
// avoids water, steep slopes, trees and houses (pathfinding via engine.characters.findPath); stops and turns to face the player when talking.
|
|
3
|
+
//
|
|
4
|
+
// const fisher = engine.npcs.add({
|
|
5
|
+
// id: 'fisher', name: '老渔夫', colors: { body: 0x4f6d8f },
|
|
6
|
+
// schedule: [ { at: '06:00', position: [10, 0, 20] }, // 早上 6 点去河边(at 也可写 0–1 时刻)
|
|
7
|
+
// { at: '13:00', position: [40, 0, -5] } ], // 中午回家
|
|
8
|
+
// talk: '老渔夫', // 对话脚本名,靠近按 E 触发
|
|
9
|
+
// });
|
|
10
|
+
//
|
|
11
|
+
// Facts and presentation are separate: an NPC's fact is a record in engine.world (kind 'npc', stable id: the given id, else the name),
|
|
12
|
+
// the model (Character: mesh + mover + animation) is just a presentation built when near: torn down when far, rebuilt when near;
|
|
13
|
+
// changing level only tears down models (data carries zone, so it is rebuilt on return), saves follow world.
|
|
14
|
+
// The NPC returned by npcs.add is a handle that finds the data / current model by id; it holds no model, so it stays usable after the model is torn down.
|
|
15
|
+
// Who owns position: with a model, the mover moves the model and the data follows (positionFrom: 'view', world copies it back at the end of each fixed step);
|
|
16
|
+
// without a model, simulation edits the data directly; building a model reads from the data (npcView.js builds and tears down the model).
|
|
17
|
+
// Simulation: world.simulate('npc') dispatches by rec.behavior to registered behaviors { near, far } (built-ins in behaviors.js, schedule details in npcSim.js):
|
|
18
|
+
// near runs once per fixed step (pathfinding + mover + mutual avoidance npcAvoid.js), far simulates on data (schedule walks in a straight line).
|
|
19
|
+
// Near / far is by distance to the focus; far -> near first catches up owed time (world handles it).
|
|
20
|
+
//
|
|
21
|
+
// One NPC record (all plain values, inspectable via engine.world.get(id)):
|
|
22
|
+
// name, behavior (behavior name), mind (behavior params and memory, plain values the behavior reads/writes), schedule [{ at: 0-1, x, z }],
|
|
23
|
+
// talk (dialogue id), talkLabel (when text), talkRadius, pathStep, repath, arriveDistance, speed,
|
|
24
|
+
// look (look and feel params: colors, runSpeed...), zone (which level it belongs to; null = everywhere),
|
|
25
|
+
// state (animation state), busy (in dialogue), nav { stop (current stop index), path (remaining waypoints), repath (re-path countdown) },
|
|
26
|
+
// motion (motion state from Character.saveMotion)
|
|
27
|
+
// model given as an asset name ('villager') is plain and goes into look (saved); a model object, animation, clips and function-form talkLabel
|
|
28
|
+
// are not plain values and stay in memory only (by id); game code supplies them again via add after loading.
|
|
29
|
+
import * as THREE from 'three';
|
|
30
|
+
import { CHARACTER_KEYS } from './Character.js';
|
|
31
|
+
import { buildNpcView, unbuildNpcView } from './npcView.js';
|
|
32
|
+
import { checkOptions, warnOnce, fmt, DEV } from '../../core/validate.js';
|
|
33
|
+
import { NpcAvoid } from './npcAvoid.js';
|
|
34
|
+
import { parseClock } from '../../core/dayTime.js';
|
|
35
|
+
import { xzOf } from '../../core/math.js';
|
|
36
|
+
import { placeY } from '../../core/ground.js';
|
|
37
|
+
import { stopIndex, timeOfDay } from './npcSim.js';
|
|
38
|
+
import { Behaviors } from './behaviors.js';
|
|
39
|
+
|
|
40
|
+
const STRINGS = {
|
|
41
|
+
noTalk: 'NPC "{name}" has talk set, but the interactions() and dialogue() modules are not installed: this NPC cannot be talked to',
|
|
42
|
+
noWorld: 'NPCs need the world() module (facts live in engine.world): engine.use(world(), …, characters()); openWorld() already installs it. '
|
|
43
|
+
+ 'If you do not want NPCs, use characters({ npcs: false })',
|
|
44
|
+
notNpc: 'npcs.add(): id "{id}" is already used by a "{kind}" in world; give this NPC a different id',
|
|
45
|
+
sameName: 'npcs.add(): an NPC named "{name}" already exists (without id the name is the id, so the two would merge). '
|
|
46
|
+
+ 'Give each different NPC its own id, e.g. npcs.add({ id: "{name}_2", name: "{name}", … }); to update an existing NPC, add again with the same id',
|
|
47
|
+
};
|
|
48
|
+
const KIND = 'npc';
|
|
49
|
+
// Params that cannot go into saves: kept in memory only, used when building the model
|
|
50
|
+
const RUNTIME_KEYS = ['model', 'animation', 'clips'];
|
|
51
|
+
const NPC_KEYS = [...CHARACTER_KEYS, 'id', 'initial', 'zone', 'name', 'schedule', 'talk', 'talkLabel', 'talkRadius', 'pathStep', 'repath', 'arriveDistance',
|
|
52
|
+
'position', 'behavior', 'mind'];
|
|
53
|
+
|
|
54
|
+
/** NPC handle: finds the data and current model by id. Stays usable after the model is torn down or the data is replaced by loading (does not cache the data object) */
|
|
55
|
+
export class NPC {
|
|
56
|
+
/** @param {NPCManager} mgr @param {string} id */
|
|
57
|
+
constructor(mgr, id) {
|
|
58
|
+
this.id = id;
|
|
59
|
+
/** @internal */ this._m = mgr;
|
|
60
|
+
/** @internal */ this._p = new THREE.Vector3();
|
|
61
|
+
}
|
|
62
|
+
/** The record in world (plain object; undefined after removal). Change fields with engine.world.set(npc.id, {...}) */
|
|
63
|
+
get data() { return this._m.world.get(this.id); }
|
|
64
|
+
get name() { return this.data?.name; }
|
|
65
|
+
get schedule() { return this.data?.schedule ?? []; }
|
|
66
|
+
get talk() { return this.data?.talk ?? null; }
|
|
67
|
+
/** Current behavior name */
|
|
68
|
+
get behavior() { return this.data?.behavior; }
|
|
69
|
+
/**
|
|
70
|
+
* Switch behavior (stored in data, restored by saves). mind is the new behavior's params / memory (plain values); omitted = cleared.
|
|
71
|
+
* @example npc.setBehavior('wander', { radius: 12 }); // in 12 m around the current position; setBehavior('schedule') returns to the schedule
|
|
72
|
+
* @param {string} name registered behavior name @param {object} [mind]
|
|
73
|
+
*/
|
|
74
|
+
setBehavior(name, mind = {}) {
|
|
75
|
+
this._m._b.check(name);
|
|
76
|
+
const rec = this.data; if (!rec) return this;
|
|
77
|
+
this._m.world.set(this.id, { behavior: name, mind });
|
|
78
|
+
rec.nav.path = null; rec.nav.repath = 0;
|
|
79
|
+
return this;
|
|
80
|
+
}
|
|
81
|
+
get state() { return this.data?.state ?? 'idle'; }
|
|
82
|
+
get busy() { return !!this.data?.busy; }
|
|
83
|
+
/** Current character model (Character): only exists when near; null when far, in another level or not built yet */
|
|
84
|
+
get character() { return this._m.character(this.id); }
|
|
85
|
+
/** three.js root of the current model (= character.root); null without a model */
|
|
86
|
+
get root() { return this.character?.root ?? null; }
|
|
87
|
+
get object() { return this.root; }
|
|
88
|
+
/** Position: with a model it is the model's position (read-only, use placeAt to move); without a model a copy of the data position */
|
|
89
|
+
get position() {
|
|
90
|
+
const ch = this.character; if (ch) return ch.root.position;
|
|
91
|
+
const r = this.data; if (r) this._p.set(r.position.x, r.position.y, r.position.z);
|
|
92
|
+
return this._p;
|
|
93
|
+
}
|
|
94
|
+
/** The stop it should go to now ({ at, x, z }); null without a schedule */
|
|
95
|
+
currentStop() { const s = this.schedule, i = stopIndex(s, timeOfDay(this._m.engine)); return i == null ? null : s[i]; }
|
|
96
|
+
/** Teleport onto the ground at a position (the mover handles it with a model, else edits data), re-paths */
|
|
97
|
+
placeAt(position) {
|
|
98
|
+
const e = this._m.engine, W = this._m.world, rec = this.data; if (!rec) return this;
|
|
99
|
+
const [x, z] = xzOf(position), ch = this.character;
|
|
100
|
+
if (ch) ch.placeAt({ x, z });
|
|
101
|
+
W.move(this.id, { x, y: ch ? ch.root.position.y : placeY(e, `npc.placeAt() (${this.id})`, x, z, undefined, rec.position.y), z });
|
|
102
|
+
rec.nav.path = null; rec.nav.repath = 0;
|
|
103
|
+
return this;
|
|
104
|
+
}
|
|
105
|
+
/** Face a position (only turns with a model) */
|
|
106
|
+
face(position) { const ch = this.character; if (ch) { ch.face(position); if (this.data?.motion) this.data.motion.facing = ch.facing; } return this; }
|
|
107
|
+
/** Remove this NPC (data and model together) */
|
|
108
|
+
remove() { return this._m.remove(this); }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export class NPCManager {
|
|
112
|
+
/** @internal Every option add() reads: content npcs (modules/content/loader.js) are checked against the same table, without importing this module */
|
|
113
|
+
get optionKeys() { return NPC_KEYS; }
|
|
114
|
+
constructor(engine) {
|
|
115
|
+
this.engine = engine;
|
|
116
|
+
/** @internal */ this._handles = new Map(); // id -> NPC handle (just a cache, can be rebuilt any time)
|
|
117
|
+
/** @internal */ this._runtime = new Map(); // id -> non-saveable params (model, animation, clips, function talkLabel)
|
|
118
|
+
/** @internal */ this._views = new WeakMap(); // model root -> { ch, talk }
|
|
119
|
+
/** @internal */ this._ready = false;
|
|
120
|
+
/** Near NPCs avoid each other (on by default): avoid.set(false) turns it off, see npcAvoid.js */
|
|
121
|
+
this.avoid = new NpcAvoid(engine);
|
|
122
|
+
/** @internal */ this._b = new Behaviors(); // behavior name -> { near, far } (code, not saved)
|
|
123
|
+
/** @internal */ this._byName = new Set(); // NPCs added this run without id, using the name as id (to detect same names in dev)
|
|
124
|
+
}
|
|
125
|
+
get world() { const W = this.engine.world; if (!W) throw new Error(STRINGS.noWorld); return W; }
|
|
126
|
+
|
|
127
|
+
/** Register the NPC model and simulation with world (called in characters init; add calls it first if npcs.add comes earlier)@internal */
|
|
128
|
+
setup() {
|
|
129
|
+
if (this._ready) return;
|
|
130
|
+
const e = this.engine, W = this.world;
|
|
131
|
+
this._ready = true;
|
|
132
|
+
W.present(KIND, {
|
|
133
|
+
positionFrom: 'view', // with a model the mover decides; world copies the model position back to data at the end of each fixed step
|
|
134
|
+
build: rec => buildNpcView(this, rec),
|
|
135
|
+
update: (rec, obj, dt) => this._views.get(obj)?.ch.animate(dt),
|
|
136
|
+
dispose: (rec, obj) => unbuildNpcView(this, rec, obj),
|
|
137
|
+
});
|
|
138
|
+
this._b.addBuiltin(e, W);
|
|
139
|
+
W.simulate(KIND, {
|
|
140
|
+
near: (rec, dt) => {
|
|
141
|
+
if (rec.busy && !e.dialogue?.active) rec.busy = false; // self-heal: after loading, dialogue is gone, so do not stand still forever
|
|
142
|
+
this.avoid.stamp(rec);
|
|
143
|
+
this._b.of(rec)?.near?.(rec, dt, this._handle(rec.id));
|
|
144
|
+
},
|
|
145
|
+
far: (rec, dt) => {
|
|
146
|
+
this._b.of(rec)?.far?.(rec, dt, this._handle(rec.id));
|
|
147
|
+
const ch = this.character(rec.id); // already far but the model is not torn down yet: let the model catch up with the data
|
|
148
|
+
if (ch) { ch.placeAt(rec.position); ch.loadMotion(rec.motion); }
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Register an NPC behavior (what it does); data selects it via behavior: npcs.add({ behavior: name }) or npc.setBehavior(name).
|
|
155
|
+
* Built-in 'schedule' (default), 'wander' (mind: { radius, pause, home }).
|
|
156
|
+
* near(rec, dt, npc): once per fixed step when near (npc.character is the model, null if not built);
|
|
157
|
+
* far(rec, dt): simulate on data when far, dt is accumulated seconds (can be large), far -> near catches up owed time; no far = does not move when far.
|
|
158
|
+
* Keep state in rec.mind (plain values, saved); move via world.move(rec.id, {x, y, z}), with a model use npc.character.move(dx, dz, false, dt).
|
|
159
|
+
* @example // chase the player: stop within 2 m of the player
|
|
160
|
+
* engine.npcs.behavior('chase', { near(rec, dt, npc) {
|
|
161
|
+
* const p = npc.position, t = engine.player.position, dx = t.x - p.x, dz = t.z - p.z, d = Math.hypot(dx, dz) || 1;
|
|
162
|
+
* npc.character?.move(d > 2 ? dx / d : 0, d > 2 ? dz / d : 0, false, dt);
|
|
163
|
+
* engine.world.move(rec.id, npc.position);
|
|
164
|
+
* } });
|
|
165
|
+
* @param {string} name @param {{ near?: (rec: any, dt: number, npc: NPC) => void, far?: (rec: any, dt: number) => void }} impl
|
|
166
|
+
*/
|
|
167
|
+
behavior(name, impl) {
|
|
168
|
+
checkOptions(`npcs.behavior('${name}')`, impl, ['near', 'far']);
|
|
169
|
+
this._b.set(name, impl);
|
|
170
|
+
return this;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Add an NPC, returns a handle. Position: opts.position (Vector3 / object / [x, y, z] / { x, z }), defaults to the schedule's current stop.
|
|
174
|
+
* For behavior (default 'schedule') and mind see behavior().
|
|
175
|
+
* id is the stable identity (saves, quest targets, npcs.get all use it), defaults to name (two NPCs with the same name and no id throw).
|
|
176
|
+
* Adding the same id again updates the definition (schedule, dialogue...) and keeps position and state.
|
|
177
|
+
* initial: true = NPC authored in content (everything content adds): saves record only changes, removed ones do not reappear after loading.
|
|
178
|
+
*/
|
|
179
|
+
add(opts) {
|
|
180
|
+
checkOptions('npcs.add()', opts, NPC_KEYS);
|
|
181
|
+
for (const s of opts.schedule || []) checkOptions('npcs.add() schedule', s, ['at', 'position']);
|
|
182
|
+
this.setup();
|
|
183
|
+
const e = this.engine, W = this.world;
|
|
184
|
+
const { id: given, name = 'NPC', schedule = [], talk = null, talkLabel, talkRadius = 3.2, pathStep = 2, repath = 2, arriveDistance = 1.2,
|
|
185
|
+
position, zone = null, speed = 2.6, initial = false, behavior = 'schedule', mind = {}, ...rest } = opts;
|
|
186
|
+
const id = given ?? name, look = {}, runtime = {};
|
|
187
|
+
if (DEV && given == null) { if (this._byName.has(id)) throw new Error(fmt(STRINGS.sameName, { name })); this._byName.add(id); }
|
|
188
|
+
// an asset name is data (saved); a model object, animation and clips stay in memory
|
|
189
|
+
for (const [k, v] of Object.entries(rest)) (RUNTIME_KEYS.includes(k) && !(k === 'model' && typeof v === 'string') ? runtime : look)[k] = v;
|
|
190
|
+
if (typeof talkLabel === 'function') runtime.talkLabel = talkLabel;
|
|
191
|
+
this._b.check(behavior);
|
|
192
|
+
this._runtime.set(id, runtime);
|
|
193
|
+
const hpd = e.sky?.hoursPerDay ?? 24;
|
|
194
|
+
// at may be 'HH:MM' or 0-1
|
|
195
|
+
const sched = schedule.map(s => { const [x, z] = xzOf(s.position); return { at: parseClock(s.at, hpd), x, z }; }).sort((a, b) => a.at - b.at);
|
|
196
|
+
if (talk && !(e.interactions && e.dialogue)) warnOnce(fmt(STRINGS.noTalk, { name }));
|
|
197
|
+
const def = { name, behavior, mind, schedule: sched, talk, talkLabel: typeof talkLabel === 'string' ? talkLabel : null,
|
|
198
|
+
talkRadius, pathStep, repath, arriveDistance, speed, look, zone };
|
|
199
|
+
const old = W.get(id);
|
|
200
|
+
if (old) {
|
|
201
|
+
if (old.kind !== KIND) throw new Error(fmt(STRINGS.notNpc, { id, kind: old.kind }));
|
|
202
|
+
// re-add overrides only fields passed explicitly (unpassed zone, schedule etc. keep their values)
|
|
203
|
+
const patch = {};
|
|
204
|
+
const keys = ['name', 'talk', 'talkRadius', 'pathStep', 'repath', 'arriveDistance', 'speed', 'zone', 'schedule', 'talkLabel'];
|
|
205
|
+
for (const k of keys) if (opts[k] !== undefined) patch[k] = k === 'schedule' ? sched : def[k];
|
|
206
|
+
if (opts.behavior !== undefined) { patch.behavior = behavior; patch.mind = mind; } else if (opts.mind !== undefined) patch.mind = mind;
|
|
207
|
+
if (Object.keys(look).length) patch.look = { ...old.look, ...look };
|
|
208
|
+
W.set(id, patch);
|
|
209
|
+
} else {
|
|
210
|
+
const i = stopIndex(sched, timeOfDay(e)), [x, z] = xzOf(position ?? (i != null ? sched[i] : { x: 0, z: 0 }));
|
|
211
|
+
const nav = { stop: null, path: null, repath: 0 };
|
|
212
|
+
W.add({ id, kind: KIND, position: [x, placeY(e, `npcs.${id}`, x, z), z], ...def, state: 'idle', busy: false, nav, motion: null }, { initial });
|
|
213
|
+
}
|
|
214
|
+
return this._handle(id);
|
|
215
|
+
}
|
|
216
|
+
/** Remove an NPC (pass handle, id or name): deletes data and tears down the model, dialogue interaction and crowd agent. Returns false if not found */
|
|
217
|
+
remove(npc) {
|
|
218
|
+
const id = typeof npc === 'string' ? this.get(npc)?.id : npc?.id;
|
|
219
|
+
if (id == null || this.world.get(id)?.kind !== KIND) return false;
|
|
220
|
+
this.world.remove(id);
|
|
221
|
+
this._runtime.delete(id); this._handles.delete(id); this._byName.delete(id);
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
/** Find by id or name (id first) */
|
|
225
|
+
get(idOrName) {
|
|
226
|
+
const W = this.engine.world; if (!W) return undefined;
|
|
227
|
+
if (W.get(idOrName)?.kind === KIND) return this._handle(idOrName);
|
|
228
|
+
for (const r of W.records.values()) if (r.kind === KIND && r.name === idOrName) return this._handle(r.id);
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
/** All NPCs (kind 'npc' records in world, including far ones and those in other levels) */
|
|
232
|
+
list() {
|
|
233
|
+
const W = this.engine.world, out = [];
|
|
234
|
+
if (W) for (const r of W.records.values()) if (r.kind === KIND) out.push(this._handle(r.id));
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
/** Current character model (Character) of an NPC; null if none */
|
|
238
|
+
character(id) { const o = this.engine.world?.view(id); return (o && this._views.get(o)?.ch) || null; }
|
|
239
|
+
|
|
240
|
+
/** @internal */
|
|
241
|
+
_handle(id) { let h = this._handles.get(id); if (!h) this._handles.set(id, h = new NPC(this, id)); return h; }
|
|
242
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Character model named by asset (Character({ model: 'hero' }) or style.character.model): construction is synchronous, loading is not.
|
|
2
|
+
// A model already loaded is swapped in at once (engine.assets.modelNow); otherwise the character keeps its placeholder body (style create() or the gray capsule) until engine.assets.model(name) resolves, then the copy
|
|
3
|
+
// (SkeletonUtils clone, so many characters share one asset) replaces the body under the same root: position, facing, state and every
|
|
4
|
+
// reference to the character or its root (collision, interactions, world view) stay valid. Loaded only when a string model is used.
|
|
5
|
+
import { warnOnce } from '../../core/validate.js';
|
|
6
|
+
import { fmt } from '../../core/opsCheck.js';
|
|
7
|
+
|
|
8
|
+
const STRINGS = {
|
|
9
|
+
unknown: 'Character model "{name}" is not a registered model asset (registered: {list}). Fix: use one of those names, or register it first: engine.assets.manifest({ models: { {name}: \'/models/{name}.glb\' } })',
|
|
10
|
+
failed: 'Character model "{name}" did not load ({why}); the character keeps its placeholder body. Registered models: {list}; engine.loading has the error',
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Start loading the asset model for ch; returns the promise stored as ch.whenReady (never rejects).
|
|
15
|
+
* Throws at once when a manifest is registered and lacks the name (paths with / or . load as files).
|
|
16
|
+
* @param {import('./Character.js').Character} ch
|
|
17
|
+
* @param {string} name
|
|
18
|
+
* @param {(model: any) => void} use builds the model and Animator on ch
|
|
19
|
+
*/
|
|
20
|
+
export function loadAssetModel(ch, name, use) {
|
|
21
|
+
const e = ch.engine, A = e.assets;
|
|
22
|
+
const names = [...A.entries].filter(([, x]) => x.type === 'model' && x.named).map(([n]) => n);
|
|
23
|
+
const list = names.join(', ') || 'none; register them with engine.assets.manifest({ models })';
|
|
24
|
+
if (names.length && !names.includes(name) && !/[/.]/.test(name)) throw new Error(fmt(STRINGS.unknown, { name, list }));
|
|
25
|
+
const fail = why => warnOnce(fmt(STRINGS.failed, { name, why, list }));
|
|
26
|
+
const swap = m => {
|
|
27
|
+
if (ch._disposed || e.disposed) { e.remove(m); return; } // removed before loading finished: never reaches the scene, the copy is released
|
|
28
|
+
// a registered file that failed resolves to the assets gray box: the character's own placeholder body is the better stand-in
|
|
29
|
+
if (m.name === 'placeholder' && e.loading.get(name, 'model')?.phase === 'failed') { e.remove(m); fail('load failed'); return; }
|
|
30
|
+
const rig = ch._rig; // drop the placeholder body and the joint properties it put on the character
|
|
31
|
+
for (const k in rig.joints || {}) if (ch[k] === rig.joints[k]) delete ch[k];
|
|
32
|
+
e.remove(rig.root);
|
|
33
|
+
ch._rig = ch.hips = ch.head = null; ch.limbs = [];
|
|
34
|
+
use(m);
|
|
35
|
+
e.events.emit('character:model', { character: ch, model: m });
|
|
36
|
+
};
|
|
37
|
+
// already loaded (another NPC uses it, or this one was built before): swap now, so a character rebuilt far -> near never shows the placeholder
|
|
38
|
+
const now = A.modelNow(name);
|
|
39
|
+
if (now) { swap(now); return Promise.resolve(); }
|
|
40
|
+
ch.ready = false;
|
|
41
|
+
return A.model(name).then(swap).catch(err => { if (!ch._disposed) fail(err.message); }).finally(() => { ch.ready = true; });
|
|
42
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Grid A* pathfinding (fallback when no navmesh is installed or it is not ready yet). The one A* in the engine:
|
|
2
|
+
// engine.characters.findPath calls it with the collision module's walkability, the pathfinding worker (pathJob.js) with a snapshot of it.
|
|
3
|
+
// In games use engine.characters.findPath / findPathAsync, do not import this directly. Worker-safe: no imports.
|
|
4
|
+
|
|
5
|
+
/** Default cell size from the character radius: a small character gets finer cells (never below the 1 m ground raster, never above the old 2 m); no radius = 2 */
|
|
6
|
+
const defaultStep = r => r == null ? 2 : Math.min(2, Math.max(1, r * 4));
|
|
7
|
+
const defaultNodes = step => Math.round(6000 * Math.max(1, 2 / step) ** 2); // finer cells need more of them to cover the same distance
|
|
8
|
+
/** The step / maxNodes findPath uses for a character radius when the caller gives none (pathAsync sizes its ground raster with the same numbers) */
|
|
9
|
+
export const astarDefaults = radius => { const step = defaultStep(radius); return { step, maxNodes: defaultNodes(step) }; };
|
|
10
|
+
|
|
11
|
+
class MinHeap {
|
|
12
|
+
constructor() { this.a = []; }
|
|
13
|
+
push(n, f) { const a = this.a; a.push([f, n]); let i = a.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (a[p][0] <= a[i][0]) break; [a[p], a[i]] = [a[i], a[p]]; i = p; } }
|
|
14
|
+
pop() { const a = this.a, top = a[0], last = a.pop(); if (a.length) { a[0] = last; let i = 0; for (;;) { const l = i * 2 + 1, r = l + 1; let m = i; if (l < a.length && a[l][0] < a[m][0]) m = l; if (r < a.length && a[r][0] < a[m][0]) m = r; if (m === i) break; [a[m], a[i]] = [a[i], a[m]]; i = m; } } return top[1]; }
|
|
15
|
+
get size() { return this.a.length; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Grid A*: cells of step meters, searches at most maxNodes cells; returns [{ x, z }...] or null if no path.
|
|
20
|
+
* @param {(x: number, z: number) => boolean} walkable can a character stand here (radius already applied)
|
|
21
|
+
*/
|
|
22
|
+
export function findPath(walkable, sx, sz, gx, gz, { radius, step = defaultStep(radius), maxNodes = defaultNodes(step) } = {}) {
|
|
23
|
+
const sample = Math.min(0.75, Math.max(0.15, radius ?? 0.4)); // smoothing samples a segment at most one radius apart: walkable() already grows colliders by radius, so nothing 2r wide is stepped over
|
|
24
|
+
const key = (i, j) => i * 100003 + j;
|
|
25
|
+
const si = Math.round(sx / step), sj = Math.round(sz / step), gi = Math.round(gx / step), gj = Math.round(gz / step);
|
|
26
|
+
const open = new MinHeap(), g = new Map(), from = new Map(), walk = new Map();
|
|
27
|
+
const ok = (i, j) => { const k = key(i, j); let v = walk.get(k); if (v === undefined) { v = walkable(i * step, j * step); walk.set(k, v); } return v; };
|
|
28
|
+
const h = (i, j) => Math.hypot(i - gi, j - gj);
|
|
29
|
+
g.set(key(si, sj), 0); open.push([si, sj], h(si, sj));
|
|
30
|
+
let n = 0;
|
|
31
|
+
const dirs = [[1, 0, 1], [-1, 0, 1], [0, 1, 1], [0, -1, 1], [1, 1, 1.414], [1, -1, 1.414], [-1, 1, 1.414], [-1, -1, 1.414]];
|
|
32
|
+
while (open.size && n++ < maxNodes) {
|
|
33
|
+
const [i, j] = open.pop();
|
|
34
|
+
if (i === gi && j === gj) {
|
|
35
|
+
const path = []; let k = key(i, j), cur = [i, j];
|
|
36
|
+
while (cur) { path.push({ x: cur[0] * step, z: cur[1] * step }); cur = from.get(k); if (cur) k = key(cur[0], cur[1]); }
|
|
37
|
+
path.reverse(); path[0] = { x: sx, z: sz }; path[path.length - 1] = { x: gx, z: gz }; // real start, not the snapped cell centre (which may even lie behind a wall)
|
|
38
|
+
return simplify(walkable, path, sample);
|
|
39
|
+
}
|
|
40
|
+
const gc = g.get(key(i, j));
|
|
41
|
+
for (const [di, dj, c] of dirs) {
|
|
42
|
+
const ni = i + di, nj = j + dj;
|
|
43
|
+
if (!ok(ni, nj) && !(ni === gi && nj === gj)) continue;
|
|
44
|
+
const nk = key(ni, nj), ng = gc + c;
|
|
45
|
+
if (ng < (g.get(nk) ?? Infinity)) { g.set(nk, ng); from.set(nk, [i, j]); open.push([ni, nj], ng + h(ni, nj)); }
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
// drop redundant corners: go straight when two points are directly walkable
|
|
51
|
+
function simplify(walkable, path, sample) {
|
|
52
|
+
if (path.length < 3) return path;
|
|
53
|
+
const out = [path[0]];
|
|
54
|
+
let a = 0;
|
|
55
|
+
while (a < path.length - 1) {
|
|
56
|
+
let b = path.length - 1;
|
|
57
|
+
while (b > a + 1 && !lineClear(walkable, path[a], path[b], sample)) b--;
|
|
58
|
+
out.push(path[b]); a = b;
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
function lineClear(walkable, p, q, sample) {
|
|
63
|
+
const d = Math.hypot(q.x - p.x, q.z - p.z), n = Math.ceil(d / sample);
|
|
64
|
+
for (let i = 1; i < n; i++) { const t = i / n; if (!walkable(p.x + (q.x - p.x) * t, p.z + (q.z - p.z) * t)) return false; }
|
|
65
|
+
return true;
|
|
66
|
+
}
|