threedog 0.8.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +219 -4
- package/README.md +6 -6
- package/core/assets/Animator.js +2 -0
- package/core/assets/Assets.js +44 -13
- package/core/assets/assetEntry.js +87 -22
- package/core/assets/assetHot.js +2 -1
- package/core/assets/assetReport.js +1 -2
- package/core/audio/Audio.js +24 -5
- package/core/base/I18n.js +6 -3
- package/core/base/Random.js +3 -1
- package/core/base/Vars.js +14 -4
- package/core/base/errorCodes.js +54 -16
- package/core/base/errorHints.js +12 -1
- package/core/base/errors.js +6 -4
- package/core/base/events.generated.js +10 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +15 -8
- package/core/base/params.js +2 -2
- package/core/{saves → base}/saveValues.js +24 -6
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/validate.js +8 -29
- package/core/engine/Engine.js +61 -18
- package/core/engine/Loading.js +30 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +30 -13
- package/core/engine/lifecycle.js +30 -25
- package/core/engine/loop.js +22 -4
- package/core/engine/moduleSlots.js +91 -15
- package/core/engine/moduleTypes.js +13 -0
- package/core/engine/modules.js +248 -62
- package/core/engine/page.js +25 -8
- package/core/engine/plugins.js +15 -3
- package/core/engine/services.js +3 -0
- package/core/engine/startup.js +46 -36
- package/core/input/Input.js +39 -19
- package/core/input/inputKeyboard.js +39 -0
- package/core/input/inputPad.js +23 -2
- package/core/input/inputPointer.js +3 -1
- package/core/input/inputSeat.js +66 -0
- package/core/input/inputTouch.js +23 -6
- package/core/inspect/DebugOverrides.js +13 -2
- package/core/inspect/Describe.js +10 -6
- package/core/inspect/Inspect.js +31 -4
- package/core/inspect/UrlState.js +14 -10
- package/core/inspect/catalog.js +12 -5
- package/core/inspect/describeRender.js +3 -2
- package/core/inspect/describeText.js +6 -2
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/inspect/pictureWriters.js +117 -33
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/ops/Ops.js +32 -7
- package/core/ops/control.js +48 -23
- package/core/ops/holds.js +4 -3
- package/core/ops/opsAtomic.js +18 -6
- package/core/ops/opsCheck.js +7 -5
- package/core/ops/opsFail.js +5 -7
- package/core/ops/opsRun.js +2 -2
- package/core/ops/owned.js +20 -3
- package/core/ops/sharedPoint.js +7 -10
- package/core/ops/stacks.js +22 -1
- package/core/saves/SaveStore.js +52 -26
- package/core/saves/Saves.js +122 -27
- package/core/saves/saveApply.js +159 -61
- package/core/saves/saveFiles.js +30 -25
- package/core/saves/saveVersions.js +20 -6
- package/core/saves/session.js +76 -33
- package/core/saves/stateReplace.js +184 -0
- package/core/scene/Rays.js +21 -5
- package/core/scene/Views.js +6 -6
- package/core/scene/adaptive.js +13 -10
- package/core/scene/canvasBox.js +2 -0
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/scene/grid.js +2 -0
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +52 -17
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/scene/sceneDelta.js +3 -3
- package/core/scene/sceneMethods.js +11 -6
- package/core/scene/stepPoses.js +6 -1
- package/core/scene/thingExplain.js +1 -1
- package/core/scene/thingOps.js +22 -14
- package/core/scene/things.js +1 -1
- package/core/scene/tier.js +10 -0
- package/core/scene/view.js +126 -9
- package/core/stream/Batching.js +0 -1
- package/core/stream/Stream.js +24 -12
- package/core/stream/batchGroups.js +1 -0
- package/core/stream/scatter.js +5 -2
- package/core/stream/streamSources.js +2 -1
- package/core/threads/Commits.js +12 -7
- package/core/threads/Jobs.js +15 -5
- package/core/threads/Threads.js +5 -2
- package/core/time/Clock.js +3 -1
- package/core/time/skip.js +10 -4
- package/core/time/time.js +16 -10
- package/docs/AI.md +89 -72
- package/docs/API.md +18 -14
- package/docs/CODEMAP.md +68 -40
- package/docs/COMMANDS.md +22 -23
- package/docs/CONVENTIONS.md +120 -17
- package/docs/MIGRATING-0.8.md +2 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +65 -12
- package/docs/api/cameraRig.md +3 -0
- package/docs/api/characters.md +13 -7
- package/docs/api/collider3d.md +9 -0
- package/docs/api/content.md +16 -15
- package/docs/api/dialogue.md +2 -1
- package/docs/api/engine.md +18 -16
- package/docs/api/events.md +14 -4
- package/docs/api/ground.md +2 -2
- package/docs/api/i18n.md +1 -1
- package/docs/api/input.md +2 -1
- package/docs/api/interactions.md +1 -1
- package/docs/api/inventory.md +1 -1
- package/docs/api/level.md +3 -2
- package/docs/api/nav.md +4 -2
- package/docs/api/particles.md +8 -5
- package/docs/api/pickups.md +1 -1
- package/docs/api/post.md +3 -4
- package/docs/api/quests.md +4 -2
- package/docs/api/rays.md +2 -0
- package/docs/api/rigid.md +3 -2
- package/docs/api/saves.md +8 -7
- package/docs/api/stream.md +4 -5
- package/docs/api/terrain.md +3 -4
- package/docs/api/terrainDraw.md +1 -1
- package/docs/api/timeline.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/triggers.md +2 -0
- package/docs/api/vegetationDraw.md +1 -1
- package/docs/api/water.md +6 -2
- package/docs/api/weather.md +19 -4
- package/docs/api/weatherDraw.md +1 -1
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +3 -3
- package/docs/recipes/02-npc.md +3 -4
- package/docs/recipes/03-items-pickups.md +11 -11
- package/docs/recipes/04-quests.md +2 -0
- package/docs/recipes/05-props-bake.md +9 -9
- package/docs/recipes/06-clock-events.md +6 -6
- package/docs/recipes/07-flow-scenes-pause.md +18 -15
- package/docs/recipes/08-weather-sky.md +5 -5
- package/docs/recipes/09-materials-lights-models.md +3 -3
- package/docs/recipes/10-blender-level.md +16 -4
- package/docs/recipes/11-vehicles.md +18 -6
- package/docs/recipes/12-navmesh.md +52 -8
- package/docs/recipes/13-animation.md +34 -8
- package/docs/recipes/14-custom-module.md +20 -8
- package/docs/recipes/15-perf.md +4 -4
- package/docs/recipes/16-dev-bridge.md +9 -8
- package/docs/recipes/18-world.md +13 -5
- package/docs/recipes/19-shooting-picking.md +3 -2
- package/docs/recipes/20-content-actions-save.md +26 -6
- package/docs/recipes/21-camera.md +17 -23
- package/docs/recipes/22-shop-gold.md +21 -12
- package/docs/recipes/23-ops.md +19 -15
- package/docs/recipes/26-ui-parts.md +3 -2
- package/docs/recipes/27-net.md +3 -3
- package/docs/recipes/28-terrain.md +3 -3
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/30-templates.md +10 -13
- package/docs/recipes/31-audio.md +2 -2
- package/docs/recipes/32-action-game.md +6 -5
- package/docs/recipes/33-stream-sources.md +4 -1
- package/docs/recipes/34-environment-lighting.md +7 -8
- package/docs/recipes/35-picture-from-reference.md +13 -9
- package/docs/recipes/36-ground-plants.md +3 -2
- package/docs/recipes/40-scene.md +11 -10
- package/docs/recipes/43-shader-patches-surfaces.md +7 -7
- package/docs/recipes/44-water-weather-hooks.md +9 -8
- package/docs/recipes/45-cascaded-shadows.md +3 -4
- package/docs/recipes/46-blender-art-route.md +3 -3
- package/docs/recipes/49-game-module-contract.md +2 -1
- package/docs/recipes/50-own-renderer.md +1 -0
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +4 -4
- package/docs/recipes/55-mods-time-wrap.md +5 -4
- package/docs/recipes/56-webgpu-tsl.md +12 -1
- package/docs/recipes/57-control.md +30 -10
- package/docs/recipes/58-input.md +13 -0
- package/docs/recipes/60-judge-the-picture.md +1 -1
- package/docs/recipes/62-picture-code.md +106 -48
- package/docs/recipes/63-third-person-start.md +2 -1
- package/docs/recipes/64-particles.md +53 -4
- package/docs/recipes/65-swarm.md +2 -2
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +3 -3
- package/examples/perf-island/.threedog/content-index.json +1 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/main.js +2 -2
- package/examples/plain-picture/GAMEMAP.md +3 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +5 -4
- package/examples/world/main.js +3 -3
- package/index.d.ts +8 -5
- package/index.js +22 -1
- package/llms.txt +2 -1
- package/modules/ambience/Ambience.js +5 -3
- package/modules/calendar/index.js +7 -5
- package/modules/camera/FirstPersonCamera.js +3 -3
- package/modules/camera/FixedCamera.js +34 -20
- package/modules/camera/FollowCamera.js +20 -11
- package/modules/camera/RtsCamera.js +1 -0
- package/modules/camera/common.js +33 -22
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +136 -43
- package/modules/characters/NPC.js +60 -28
- package/modules/characters/assetModel.js +2 -2
- package/modules/characters/astar.js +47 -28
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +94 -34
- package/modules/characters/moveHelpers.js +80 -15
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +6 -4
- package/modules/characters/movers/rapier.js +12 -5
- package/modules/characters/movers/simple.js +25 -12
- package/modules/characters/movers/support.js +18 -7
- package/modules/characters/npcAvoid.js +15 -12
- package/modules/characters/npcSim.js +75 -25
- package/modules/characters/npcView.js +13 -6
- package/modules/characters/pathAsync.js +74 -24
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/player.js +59 -47
- package/modules/characters/seat.js +56 -0
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +31 -18
- package/modules/collision/Collision.js +44 -26
- package/modules/collision/contract.js +2 -2
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +1 -1
- package/modules/content/fields.js +3 -3
- package/modules/content/ids.js +3 -1
- package/modules/content/index.js +83 -27
- package/modules/content/loader.js +110 -130
- package/modules/content/markers.js +1 -1
- package/modules/content/models.js +48 -14
- package/modules/content/packs.js +2 -1
- package/modules/content/places.js +5 -4
- package/modules/content/props.js +8 -6
- package/modules/content/rules.js +29 -47
- package/modules/content/templates.js +66 -35
- package/modules/content/words.js +19 -6
- package/modules/debug/DebugPanel.js +4 -2
- package/modules/flow/contract.js +1 -0
- package/modules/flow/index.js +24 -14
- package/modules/gameplay/Container.js +5 -2
- package/modules/gameplay/Containers.js +9 -1
- package/modules/gameplay/Dialogue.js +82 -25
- package/modules/gameplay/Interactions.js +61 -32
- package/modules/gameplay/Inventory.js +56 -13
- package/modules/gameplay/Quests.js +133 -24
- package/modules/gameplay/boxOps.js +7 -0
- package/modules/gameplay/dialogueBubbles.js +14 -9
- package/modules/gameplay/inventoryOps.js +11 -7
- package/modules/gameplay/pickups.js +43 -16
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +6 -1
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +1 -1
- package/modules/grid/Layer.js +8 -4
- package/modules/grid/index.js +21 -15
- package/modules/grid/ops.js +43 -46
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +6 -3
- package/modules/hud/index.js +6 -4
- package/modules/hud/parts.js +4 -4
- package/modules/level/contract.js +2 -2
- package/modules/level/heightfield.js +17 -21
- package/modules/level/index.js +83 -26
- package/modules/level/load.js +165 -48
- package/modules/level/nodes.js +34 -16
- package/modules/lights/index.js +6 -3
- package/modules/lights/sources.js +3 -1
- package/modules/music/Music.js +4 -2
- package/modules/nav/contract.js +7 -5
- package/modules/nav/index.js +174 -44
- package/modules/nav/navPath.js +45 -10
- package/modules/net/index.js +1 -1
- package/modules/particles/Particles.js +85 -22
- package/modules/particles/effect.js +80 -28
- package/modules/particles/shaders.js +17 -0
- package/modules/photo/Photo.js +12 -10
- package/modules/rigid/RigidBodies.js +200 -57
- package/modules/rigid/Vehicles.js +15 -5
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +55 -44
- package/modules/rigid/ragdollBones.js +83 -33
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +46 -15
- package/modules/settings/Settings.js +84 -37
- package/modules/settings/apply.js +15 -8
- package/modules/settings/sections.js +7 -4
- package/modules/settings/strings.js +2 -2
- package/modules/sky/skyModule.js +3 -1
- package/modules/swarm/Swarm.js +16 -6
- package/modules/terrain/ChunkManager.js +10 -16
- package/modules/terrain/index.js +17 -11
- package/modules/terrain/terrainEdit.js +13 -2
- package/modules/terrain/terrainGen.js +5 -3
- package/modules/terrain/terrainShape.js +1 -1
- package/modules/timeline/Timeline.js +58 -26
- package/modules/timeline/Tween.js +19 -13
- package/modules/timeline/shots.js +19 -10
- package/modules/triggers/index.js +87 -20
- package/modules/vegetation/Vegetation.js +4 -3
- package/modules/vegetation/draw.js +16 -0
- package/modules/vegetation/groundChunks.js +10 -7
- package/modules/vegetation/index.js +30 -7
- package/modules/water/Water.js +6 -2
- package/modules/weather/Weather.js +16 -15
- package/modules/weather/weatherDraw.js +7 -6
- package/modules/world/World.js +20 -7
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +13 -6
- package/modules/world/persist.js +23 -8
- package/modules/world/pos.js +4 -4
- package/modules/world/records.js +13 -7
- package/modules/world/sim.js +74 -23
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +31 -6
- package/modules/world/thingSource.js +16 -3
- package/modules/world/views.js +19 -8
- package/package.json +7 -1
- package/render/PostFX.js +47 -29
- package/render/backend.js +5 -1
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/postWebGPU.tsl.js +3 -3
- package/render/layers.js +1 -1
- package/render/lightmap.js +23 -3
- package/render/occlusion.js +43 -12
- package/render/patches.js +2 -2
- package/render/postWebGL.js +4 -3
- package/render/probes.js +25 -0
- package/render/shadows.js +2 -2
- package/types/core.d.ts +142 -55
- package/types/gameplay.d.ts +92 -40
- package/types/generated/core/base/I18n.d.ts +2 -2
- package/types/generated/core/input/Input.d.ts +16 -2
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
- package/types/generated/core/ops/Ops.d.ts +2 -1
- package/types/generated/core/ops/control.d.ts +12 -2
- package/types/generated/core/saves/Saves.d.ts +26 -6
- package/types/generated/core/saves/session.d.ts +1 -1
- package/types/generated/core/scene/Views.d.ts +1 -1
- package/types/generated/core/stream/Stream.d.ts +6 -4
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/particles/Particles.d.ts +4 -3
- package/types/generated/modules/timeline/Timeline.d.ts +5 -4
- package/types/generated/modules/weather/Weather.d.ts +1 -7
- package/types/generated/modules/world/World.d.ts +6 -4
- package/types/generated/render/PostFX.d.ts +6 -14
- package/types/nav.d.ts +36 -4
- package/types/physics.d.ts +55 -7
- package/types/pixel.d.ts +75 -0
- package/types/world.d.ts +14 -8
- package/ui/Parts.js +9 -2
- package/ui/theme.js +2 -2
- package/core/scene/engineCamera.js +0 -32
- package/modules/camera/projection.js +0 -21
|
@@ -8,25 +8,68 @@
|
|
|
8
8
|
// const ball = engine.rigid.addBall(mesh, { radius: 0.4, restitution: 0.6 });
|
|
9
9
|
// engine.rigid.impulse(ball, [0, 3, 5]); // kick (impulse vector: Vector3 / [x, y, z] / { x, y, z })
|
|
10
10
|
// Returns an entry (handle) { body, collider, mesh (= object, position written by physics), remove() }: remove only deletes the body; the model is yours
|
|
11
|
-
// (shadow settings are untouched too)
|
|
11
|
+
// (shadow settings are untouched too). The other way round a body follows its model: engine.remove of the model, or of a parent such as a level's root, takes the body too
|
|
12
12
|
// const car = engine.rigid.addWheeled(carMesh, { wheels: [...] }); // vehicle, see Vehicles.js; engine.player.enter(car) to board; car.remove()
|
|
13
13
|
// Ray: once installed, engine.raycast(origin, direction, { targets: 'all' }) also hits rigid bodies (hit carries entry, kind: 'rigid'); no separate entry
|
|
14
14
|
// point.
|
|
15
15
|
//
|
|
16
16
|
// Rapier is downloaded on demand at start() (about 1.5MB); games without physics never load it.
|
|
17
|
+
import { FALL_Y } from '../../core/scene/ground.js';
|
|
17
18
|
import * as THREE from 'three';
|
|
18
19
|
import { vec3, xzOf } from '../../core/base/math.js';
|
|
19
20
|
|
|
20
21
|
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
21
22
|
import { cellsChanged } from '../../core/stream/streamCells.js';
|
|
22
23
|
import { createVehicle, VEHICLE_KEYS, STRINGS } from './Vehicles.js';
|
|
23
|
-
import { syncTerrain, syncTrees, treesChanged, syncGroundTrees, syncStatics, syncLevel, recordLocks, carryBody, carryCollider } from './sync.js';
|
|
24
|
+
import { syncTerrain, syncTrees, treesChanged, syncGroundTrees, syncStatics, restandStatics, syncLevel, syncFloor, dropChunks, wantsFloor, recordLocks, carryBody, carryCollider } from './sync.js';
|
|
25
|
+
import { refreshQueries } from './refresh.js';
|
|
24
26
|
import { Ragdolls } from './ragdoll.js';
|
|
25
27
|
import { codedError, coded } from '../../core/base/errorHints.js';
|
|
26
|
-
import { refuseSave, saveNumberOk, SAVE_MAX } from '../../core/
|
|
28
|
+
import { refuseSave, saveNumberOk, SAVE_MAX } from '../../core/base/saveValues.js';
|
|
27
29
|
import { warnOnce, DEV } from '../../core/base/validate.js';
|
|
30
|
+
import { follows } from '../../core/base/follows.js';
|
|
28
31
|
// Params of addBox / addBall / addHull
|
|
32
|
+
// A body lives in world space, a mesh's position in its parent's: register the world pose and write the pose back through the parent. A parent whose scale differs
|
|
33
|
+
// between axes would shear the rotation (and no body can follow it), so that is refused by name instead of drifting.
|
|
34
|
+
const _p = new THREE.Vector3(), _q = new THREE.Quaternion(), _s = new THREE.Vector3(), _pq = new THREE.Quaternion();
|
|
35
|
+
function worldPose(mesh, who) {
|
|
36
|
+
const P = mesh.parent;
|
|
37
|
+
if (P) {
|
|
38
|
+
P.updateWorldMatrix(true, false); P.matrixWorld.decompose(_p, _pq, _s);
|
|
39
|
+
if (Math.abs(_s.x - _s.y) > 1e-4 || Math.abs(_s.x - _s.z) > 1e-4)
|
|
40
|
+
throw codedError('rigid-misuse', `${who}: '${mesh.name || mesh.type}' sits under '${P.name || P.type}' whose world scale (${_s.x.toFixed(3)}, ${_s.y.toFixed(3)}, ${_s.z.toFixed(3)}) differs between axes; a body cannot follow a sheared parent. Make the parent's scale equal on all axes, or give the body a mesh outside it`);
|
|
41
|
+
}
|
|
42
|
+
mesh.updateWorldMatrix(true, false); mesh.matrixWorld.decompose(_p, _q, _s);
|
|
43
|
+
return { p: _p, q: _q };
|
|
44
|
+
}
|
|
45
|
+
function setLocalPose(mesh, t, r) {
|
|
46
|
+
const P = mesh.parent;
|
|
47
|
+
if (!P || P.matrixWorld.equals(_I)) { mesh.position.set(t.x, t.y, t.z); mesh.quaternion.set(r.x, r.y, r.z, r.w); return; }
|
|
48
|
+
P.matrixWorld.decompose(_p, _pq, _s);
|
|
49
|
+
mesh.position.copy(P.worldToLocal(_p.set(t.x, t.y, t.z)));
|
|
50
|
+
mesh.quaternion.copy(_pq.invert().multiply(_q.set(r.x, r.y, r.z, r.w)));
|
|
51
|
+
}
|
|
52
|
+
const _I = new THREE.Matrix4(), _eu = new THREE.Euler(), _box = new THREE.Box3(), _part = new THREE.Box3(), _inv = new THREE.Matrix4(), _rel = new THREE.Matrix4();
|
|
53
|
+
/**
|
|
54
|
+
* The size a body gets from its model, as [x, y, z]: measured in the mesh's own axes, since the body takes its rotation, and at its world scale, parents included.
|
|
55
|
+
* The box around it in the world grew with the turn, so a turned crate got a larger body turned on top of that
|
|
56
|
+
*/
|
|
57
|
+
function ownSize(mesh) {
|
|
58
|
+
mesh.updateWorldMatrix(true, true);
|
|
59
|
+
mesh.matrixWorld.decompose(_p, _q, _s);
|
|
60
|
+
_inv.copy(mesh.matrixWorld).invert(); _box.makeEmpty();
|
|
61
|
+
mesh.traverse(o => {
|
|
62
|
+
const g = o.geometry; if (!g) return;
|
|
63
|
+
if (!g.boundingBox) g.computeBoundingBox();
|
|
64
|
+
_box.union(_part.copy(g.boundingBox).applyMatrix4(_rel.multiplyMatrices(_inv, o.matrixWorld)));
|
|
65
|
+
});
|
|
66
|
+
return _box.getSize(_p).multiply(_s).toArray();
|
|
67
|
+
}
|
|
68
|
+
const NO_TURN = { x: 0, y: 0, z: 0, w: 1 };
|
|
69
|
+
|
|
29
70
|
const PHYSICS = { physics: true }; // stream source filter (shared, not rebuilt every step)
|
|
71
|
+
/** A body this far down over the ground fell through it: the rule 'fall' is asked. Deep enough that no walkable level reaches it by accident; a level below it sets the rule to false */
|
|
72
|
+
const SOLID_PARAMS = keysSchema(['position', 'size', 'radius', 'rotation', 'friction']);
|
|
30
73
|
const BODY_KEYS = ['id', 'mass', 'friction', 'restitution', 'damping', 'angularDamping', 'fixed'];
|
|
31
74
|
|
|
32
75
|
/**
|
|
@@ -63,9 +106,10 @@ export class RigidBodies {
|
|
|
63
106
|
/** terrainRing = chunk rings around each physics stream source that get terrain collision; buoyancyForce = buoyancy strength (1 = exactly floats); waterDrag = drag in water;
|
|
64
107
|
* floatLine / floatDepth: buoyancy starts when the body center is below floatLine meters above the surface and peaks floatDepth meters deeper;
|
|
65
108
|
* treeColliderHeight = trunk collision cylinder height; treeRadius = trunks get cylinders only in chunks within this many meters of the player or a non-fixed body;
|
|
66
|
-
* playerCapsule { halfHeight, radius } = player capsule size (default derived from engine.movement radius / height)
|
|
109
|
+
* playerCapsule { halfHeight, radius } = player capsule size (default derived from engine.movement radius / height);
|
|
110
|
+
* fallbackFloor = the flat plane at y = 0 when the ground has no collision of its own (default true; false for a game with only its own bodies and solids) */
|
|
67
111
|
constructor(engine, { gravity = -9.81, terrainRing = 1, buoyancy = true, buoyancyForce = 1.6, waterDrag = 2.5, floatLine = 0.3, floatDepth = 0.8,
|
|
68
|
-
treeColliderHeight = 6, treeRadius = 16, playerCapsule } = {}) {
|
|
112
|
+
treeColliderHeight = 6, treeRadius = 16, playerCapsule, fallbackFloor = true } = {}) {
|
|
69
113
|
const mv = engine.movement; // default capsule uses the shared character radius / height: total height = 2 * halfHeight + 2 * radius
|
|
70
114
|
playerCapsule ??= { halfHeight: Math.max(0.05, (mv.height - 2 * mv.radius) / 2), radius: mv.radius };
|
|
71
115
|
this.engine = engine;
|
|
@@ -73,6 +117,7 @@ export class RigidBodies {
|
|
|
73
117
|
this.terrainRing = terrainRing;
|
|
74
118
|
this.buoyancy = buoyancy; this.buoyancyForce = buoyancyForce; this.waterDrag = waterDrag; this.playerCapsule = playerCapsule;
|
|
75
119
|
this.floatLine = floatLine; this.floatDepth = floatDepth; this.treeColliderHeight = treeColliderHeight; this.treeRadius = treeRadius;
|
|
120
|
+
this.fallbackFloor = fallbackFloor;
|
|
76
121
|
this.rapier = null; this.world = null;
|
|
77
122
|
this.bodies = []; // { body, mesh, enabled }
|
|
78
123
|
/** @internal body handle -> entry for rays, rebuilt only after bodies changed (null): a ray cast every frame (aim, a camera probe) built a new Map each time */ this._byHandle = null;
|
|
@@ -81,7 +126,10 @@ export class RigidBodies {
|
|
|
81
126
|
this.trees = new Map(); // chunk key -> { token, colliders }: trunk cylinders of the chunks near the player / bodies (see sync.js)
|
|
82
127
|
this._anchors = []; this._treeMemo = [];
|
|
83
128
|
this.groundTrees = new Map(); // 'x,z,r' -> cylinder collider: circles from ground.forEachCollider when the ground has no chunked collision
|
|
84
|
-
/** @internal houses / pillars of the collision module as colliders (engine.collision.mirror, built on the first step: sync.js syncStatics) */ this._statics = null;
|
|
129
|
+
/** @internal houses / pillars of the collision module as colliders (engine.collision.mirror, built on the first step: sync.js syncStatics) */ this._statics = null; /** @internal mirror data -> collider, for those standing on the ground */ this._onGround = new Map();
|
|
130
|
+
/** @internal the sources of the copies above, checked on every read (_current) */ this._collision = follows(() => engine.collision); this._level = follows(() => engine.ground.staticTrimeshes ?? null, () => engine.ground.staticVersion?.() ?? 0); this._standOn = follows(() => engine.ground, G => G.staticVersion?.() ?? 0); this._floor = follows(() => wantsFloor(this));
|
|
131
|
+
/** @internal the world changed since Rapier last built its query structures, which it does only in a step */ this._behind = false;
|
|
132
|
+
/** @internal fixed solids of the collider3d contract: what they are, so every new world (init, _fresh) builds them; a collider only lives as long as its world */ this._solids = new Set();
|
|
85
133
|
this.vehicles = [];
|
|
86
134
|
/** @internal numbers vehicles added without an id */ this._vehicleSeq = 0;
|
|
87
135
|
/** @internal id -> saved physics state of a body not built yet (the save part 'rigid'; claimed when a body with that id is added) */ this._saved = new Map();
|
|
@@ -104,16 +152,26 @@ export class RigidBodies {
|
|
|
104
152
|
/** @internal A fresh Rapier world with the player capsule (and the flat plane without chunked ground): what init builds, and what _fresh rebuilds */
|
|
105
153
|
_newWorld() {
|
|
106
154
|
const R = this.rapier;
|
|
107
|
-
/** @internal bumps with every world: a character mover holding a controller of an older world builds a new one (movers/rapier.js) */
|
|
108
|
-
this.gen = (this.gen ?? 0) + 1;
|
|
109
155
|
this.world = new R.World({ x: 0, y: this.gravity, z: 0 });
|
|
110
156
|
// Player capsule (kinematic: the character controller decides position; physics only pushes other things away)
|
|
111
157
|
this.playerBody = this.world.createRigidBody(R.RigidBodyDesc.kinematicPositionBased());
|
|
112
158
|
const pc = this.playerCapsule;
|
|
113
159
|
this.playerCollider = this.world.createCollider(R.ColliderDesc.capsule(pc.halfHeight, pc.radius).setTranslation(0, pc.halfHeight + pc.radius, 0), this.playerBody);
|
|
114
|
-
//
|
|
115
|
-
const
|
|
116
|
-
|
|
160
|
+
this._floorCollider = null; this._floor.reset(); syncFloor(this); // a new world has none. Here, so colliders keep the order a fresh page builds them in
|
|
161
|
+
for (const s of this._solids) this._buildSolid(s);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** @internal Copies of what others own are current, as any read needs them. Every step runs it; a frozen engine runs no step, and queries still ask */
|
|
165
|
+
_upkeep() { if (syncStatics(this) | syncLevel(this) | syncFloor(this) | dropChunks(this)) this._behind = true; }
|
|
166
|
+
/**
|
|
167
|
+
* @internal Every query starts here, and answers whether physics can be asked. Rapier has no call that refreshes its query structures alone (refresh.js), so a step of no time does, twice (one leaves a moved body or a reused collider slot out, measured in `refresh while frozen`): nothing
|
|
168
|
+
* moves, and it runs only when something changed, so a ray pays three compares.
|
|
169
|
+
*/
|
|
170
|
+
_current() {
|
|
171
|
+
if (!this.ready) return false;
|
|
172
|
+
this._upkeep();
|
|
173
|
+
if (this._behind) { refreshQueries(this.world); this._behind = false; }
|
|
174
|
+
return true;
|
|
117
175
|
}
|
|
118
176
|
|
|
119
177
|
/**
|
|
@@ -125,7 +183,7 @@ export class RigidBodies {
|
|
|
125
183
|
* body or collider itself (gravityScale, axis locks, ccd, dominance, sensor, groups, enabled) is carried onto the rebuilt one (carryBody / carryCollider in sync.js). Joints are not carried: Rapier has no getters for a joint's
|
|
126
184
|
* whole description (rope length, motor settings), and copying one would mean patching Rapier. The game re-creates its own joints on rigid:rebuilt,
|
|
127
185
|
* emitted once the bodies are back (the coordination point); a dev warning names a game whose joints vanished with no re-creation. Movers'
|
|
128
|
-
* character controllers are freed with the old world (World.free frees them; movers/rapier.js sees
|
|
186
|
+
* character controllers are freed with the old world (World.free frees them; movers/rapier.js sees another world object and builds new ones).
|
|
129
187
|
* Vehicles hold a controller built for one world: with a vehicle present only the bodies are stopped and put to sleep (no rebuild).
|
|
130
188
|
*/
|
|
131
189
|
_fresh() {
|
|
@@ -137,8 +195,8 @@ export class RigidBodies {
|
|
|
137
195
|
}
|
|
138
196
|
const old = this.world, R = this.rapier, hadJoints = old.impulseJoints.len();
|
|
139
197
|
this._newWorld();
|
|
140
|
-
this.terrain.clear(); this.trees.clear(); this.groundTrees.clear(); this._statics?.clear();
|
|
141
|
-
this.
|
|
198
|
+
this.terrain.clear(); this.trees.clear(); this.groundTrees.clear(); this._statics?.clear(); this._onGround.clear();
|
|
199
|
+
this._level.reset(); this._levelColliders = [];
|
|
142
200
|
this._srcMemo = null; this._srcPending = false; this._syncT = 0; this._anchors = []; this._treeMemo = [];
|
|
143
201
|
for (const b of this.bodies) {
|
|
144
202
|
const t = b.body.translation(), q = b.body.rotation();
|
|
@@ -150,7 +208,7 @@ export class RigidBodies {
|
|
|
150
208
|
// what the game wrote on the Rapier body / collider (gravityScale, locks, ccd, sensor, groups, enabled...) is its own and survives the rebuild
|
|
151
209
|
carryBody(b, ob, b.body); carryCollider(oc, b.collider);
|
|
152
210
|
// b.enabled stays: it is the engine's own freeze flag (no ground under it), which the step loop compares with; a game's setEnabled(false) was carried
|
|
153
|
-
b.wet = false; b._void = false;
|
|
211
|
+
b.wet = false; b._void = false; b._fell = false;
|
|
154
212
|
}
|
|
155
213
|
old.free(); this._byHandle = null; // every body has a new handle
|
|
156
214
|
// the old world's joints (every one is the game's: the engine makes none) went with it. The game re-creates them here, between the rebuilt bodies
|
|
@@ -174,7 +232,7 @@ export class RigidBodies {
|
|
|
174
232
|
_add(mesh, desc, { id, mass = 1, friction = 0.7, restitution = 0.1, damping = 0.05, angularDamping = 0.1, fixed = false } = {}) {
|
|
175
233
|
// id names the body in the save part 'rigid': two live bodies with one id would load into each other
|
|
176
234
|
if (id != null && this.bodies.some(b => b.id === id)) throw codedError('rigid-misuse', `rigid: id '${id}' is already used by another body or vehicle; ids name the body in saves, pick a unique one (e.g. the world record id)`);
|
|
177
|
-
const R = this.rapier, p
|
|
235
|
+
const R = this.rapier, { p, q } = worldPose(mesh, 'rigid');
|
|
178
236
|
const bd = (fixed ? R.RigidBodyDesc.fixed() : R.RigidBodyDesc.dynamic())
|
|
179
237
|
.setTranslation(p.x, p.y, p.z).setRotation({ x: q.x, y: q.y, z: q.z, w: q.w })
|
|
180
238
|
.setLinearDamping(damping).setAngularDamping(angularDamping).setCanSleep(true);
|
|
@@ -185,25 +243,26 @@ export class RigidBodies {
|
|
|
185
243
|
const entry = { id, body, collider, mesh, object: mesh, enabled: true, volume: 0, damping, angularDamping, fixed, _x: p.x, _z: p.z, _desc: desc }; // _x / _z: where sync.js looks for trunks to give it
|
|
186
244
|
entry.remove = () => this._remove(entry);
|
|
187
245
|
recordLocks(entry, body);
|
|
188
|
-
this.bodies.push(entry); this._byHandle = null;
|
|
189
|
-
this.
|
|
246
|
+
this.bodies.push(entry); this._byHandle = null; this._behind = true;
|
|
247
|
+
// a write to the record of this model lands here (world/views.js placed); with rigid gone first at dispose the model is on its own
|
|
248
|
+
// entry.place: a template's copy says what a written place means for it (content/templates.js)
|
|
249
|
+
this.engine._poses.add(mesh, at => { if (this.world) this.setPosition(entry, entry.place?.(at) ?? at); }, () => entry.remove());
|
|
190
250
|
// a loaded save holds this body's state (it is built after the load, e.g. by a world presenter): it continues from there, not from the record's pose
|
|
191
|
-
|
|
192
|
-
if (s) { this._saved.delete(id); putState(entry, s); }
|
|
251
|
+
this._claim(entry);
|
|
193
252
|
return entry;
|
|
194
253
|
}
|
|
195
254
|
/** Box. When size is omitted it is computed from the model bounding box */
|
|
196
255
|
addBox(mesh, o = {}) {
|
|
197
256
|
readParams('rigid.addBox()', keysSchema([...BODY_KEYS, 'size']), o);
|
|
198
257
|
if (!this._ready('addBox')) return null;
|
|
199
|
-
const s = o.size ||
|
|
258
|
+
const s = o.size || ownSize(mesh);
|
|
200
259
|
return this._add(mesh, this.rapier.ColliderDesc.cuboid(s[0] / 2, s[1] / 2, s[2] / 2), o);
|
|
201
260
|
}
|
|
202
261
|
/** Ball */
|
|
203
262
|
addBall(mesh, o = {}) {
|
|
204
263
|
readParams('rigid.addBall()', keysSchema([...BODY_KEYS, 'radius']), o);
|
|
205
264
|
if (!this._ready('addBall')) return null;
|
|
206
|
-
const r = o.radius ??
|
|
265
|
+
const r = o.radius ?? ownSize(mesh)[0] / 2;
|
|
207
266
|
return this._add(mesh, this.rapier.ColliderDesc.ball(r), o);
|
|
208
267
|
}
|
|
209
268
|
/** Convex hull: auto-wrapped around the model shape (irregular objects such as rocks, barrels) */
|
|
@@ -212,8 +271,10 @@ export class RigidBodies {
|
|
|
212
271
|
if (!this._ready('addHull')) return null;
|
|
213
272
|
const g = mesh.geometry, pts = new Float32Array(g.attributes.position.array.length);
|
|
214
273
|
const v = new THREE.Vector3();
|
|
274
|
+
mesh.updateWorldMatrix(true, false); mesh.matrixWorld.decompose(_p, _q, _s); // the world scale: a parent's counts as much as the mesh's own
|
|
275
|
+
const scale = _s.clone();
|
|
215
276
|
for (let i = 0; i < g.attributes.position.count; i++) {
|
|
216
|
-
v.fromBufferAttribute(g.attributes.position, i).multiply(
|
|
277
|
+
v.fromBufferAttribute(g.attributes.position, i).multiply(scale); pts.set([v.x, v.y, v.z], i * 3);
|
|
217
278
|
}
|
|
218
279
|
return this._add(mesh, this.rapier.ColliderDesc.convexHull(pts), o);
|
|
219
280
|
}
|
|
@@ -236,8 +297,8 @@ export class RigidBodies {
|
|
|
236
297
|
/** Remove a vehicle (the occupant exits first): called by vehicle.remove() */
|
|
237
298
|
_removeVehicle(v) {
|
|
238
299
|
if (!this.vehicles.includes(v)) return;
|
|
239
|
-
for (const p of [...v.passengers]) p.exit();
|
|
240
|
-
v.driver?.exit(); v._use?.remove();
|
|
300
|
+
for (const p of [...v.passengers]) p.exit({ force: true });
|
|
301
|
+
v.driver?.exit({ force: true }); v._use?.remove(); v.gone = true; v._seatBook?.remove();
|
|
241
302
|
this.vehicles = this.vehicles.filter(x => x !== v);
|
|
242
303
|
this.world.removeVehicleController(v.controller);
|
|
243
304
|
this._remove(v);
|
|
@@ -245,8 +306,9 @@ export class RigidBodies {
|
|
|
245
306
|
/**
|
|
246
307
|
* Turn a skinned character limp, one call; rd.remove() returns it to animation. Its mover, animation, capsule and camera yield until then. @experimental
|
|
247
308
|
* @param {any} who a Character, an NPC handle, a character id or a skinned Object3D
|
|
248
|
-
*
|
|
249
|
-
* @
|
|
309
|
+
* The rule 'ragdoll.graph' says which parts it has: 'humanoid' (default), a graph { part: { bone, parent, limits, mass } }, or false for none (returns null).
|
|
310
|
+
* @param {{ impulse?: any, position?: any, bones?: Record<string, any>, limits?: Record<string, any>, mass?: number }} [o] impulse: a push (kg*m/s) on the part nearest position, else on the root part; bones: humanoid part -> bone name or bone, over the auto-detection; limits: part or kind ('lowerLeg') -> { bend, side, twist } as [min, max] radians from the bind pose; mass: whole body, default the graph's (humanoid 70 kg)
|
|
311
|
+
* @example const rd = engine.rigid.ragdoll(player, { impulse: [0, 200, -300], position: hit.point }); engine.clock.after(4, () => rd.remove(), { channel: 'real' });
|
|
250
312
|
*/
|
|
251
313
|
ragdoll(who, o) {
|
|
252
314
|
if (!this._ready('ragdoll')) return null;
|
|
@@ -268,7 +330,8 @@ export class RigidBodies {
|
|
|
268
330
|
/** Delete the body (called by entry.remove()); the model stays */
|
|
269
331
|
_remove(entry) {
|
|
270
332
|
const i = this.bodies.indexOf(entry); if (i < 0) return;
|
|
271
|
-
this.world
|
|
333
|
+
this.world?.removeRigidBody(entry.body); // no world: rigid left first at dispose and freed its bodies with it
|
|
334
|
+
this.bodies.splice(i, 1); this._byHandle = null; this._behind = true;
|
|
272
335
|
this.engine._poses.remove(entry.mesh);
|
|
273
336
|
}
|
|
274
337
|
/** Push: impulse vector v (Vector3 / [x, y, z] / { x, y, z }) */
|
|
@@ -277,12 +340,56 @@ export class RigidBodies {
|
|
|
277
340
|
setPosition(entry, position) {
|
|
278
341
|
const { x, y, z } = vec3(position);
|
|
279
342
|
entry._x = x; entry._z = z;
|
|
280
|
-
entry.body.setTranslation({ x, y, z }, true); entry.body.setLinvel({ x: 0, y: 0, z: 0 }, true);
|
|
343
|
+
entry.body.setTranslation({ x, y, z }, true); entry.body.setLinvel({ x: 0, y: 0, z: 0 }, true); this._behind = true;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ---------- The collider3d contract (collider3d.contract.js): engine.collider3d is this object ----------
|
|
347
|
+
/**
|
|
348
|
+
* A fixed solid turned any way: size [x, y, z] for a box or radius for a ball, rotation [x, y, z] radians or a quaternion. Returns { remove() }. Callable before start();
|
|
349
|
+
* newGame and a load keep it. Bodies and the rapier mover hit it; engine.collision does not know it, so a simple-mover walker walks through.
|
|
350
|
+
* @example const ramp = engine.collider3d.addSolid({ position: [0, 2, 0], size: [8, 0.5, 3], rotation: [0, 0, 0.4] });
|
|
351
|
+
*/
|
|
352
|
+
addSolid(o) {
|
|
353
|
+
readParams('collider3d.addSolid()', SOLID_PARAMS, o);
|
|
354
|
+
if ((o.size == null) === (o.radius == null)) throw codedError('rigid-misuse', `collider3d.addSolid(): give exactly one of size ([x, y, z], a box) or radius (a ball)`);
|
|
355
|
+
const s = { o, collider: null, remove: () => { if (this._solids.delete(s) && this.world && s.collider) { this.world.removeCollider(s.collider, false); this._behind = true; } } };
|
|
356
|
+
this._solids.add(s);
|
|
357
|
+
if (this.world) this._buildSolid(s);
|
|
358
|
+
return s;
|
|
359
|
+
}
|
|
360
|
+
/** @internal */
|
|
361
|
+
_buildSolid(s) {
|
|
362
|
+
const R = this.rapier, { position, size, radius, rotation, friction = 0.9 } = s.o, p = vec3(position);
|
|
363
|
+
const q = Array.isArray(rotation) ? _q.setFromEuler(_eu.fromArray(rotation)) : rotation ? _q.set(rotation.x, rotation.y, rotation.z, rotation.w) : _q.identity();
|
|
364
|
+
const desc = size ? R.ColliderDesc.cuboid(size[0] / 2, size[1] / 2, size[2] / 2) : R.ColliderDesc.ball(radius);
|
|
365
|
+
s.collider = this.world.createCollider(desc.setTranslation(p.x, p.y, p.z).setRotation({ x: q.x, y: q.y, z: q.z, w: q.w }).setFriction(friction));
|
|
366
|
+
this._behind = true;
|
|
367
|
+
}
|
|
368
|
+
/** Is a ball here inside something solid (false before physics is ready). Sees the world as it stands now, also while frozen; skips the player's capsule */
|
|
369
|
+
overlap(position, radius = 0.01) {
|
|
370
|
+
if (!this._current()) return false;
|
|
371
|
+
const R = this.rapier, { x, y, z } = vec3(position);
|
|
372
|
+
return !!this.world.intersectionWithShape({ x, y, z }, NO_TURN, new R.Ball(radius), R.QueryFilterFlags.EXCLUDE_SENSORS, undefined, undefined, this.playerBody);
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Move a ball from there to there: null when clear, else the first hit { point, normal, distance }: point is the ball's center at the hit, normal the world direction out of what it hit.
|
|
376
|
+
* A ball that starts touching or inside a solid and moves out of it is clear: a flyer taking off from the ground must not be held by the ground it stands on.
|
|
377
|
+
* @example const hit = engine.collider3d.sweep(drone.position, next, 0.4); if (hit) drone.position.copy(hit.point);
|
|
378
|
+
*/
|
|
379
|
+
sweep(from, to, radius = 0.01) {
|
|
380
|
+
if (!this._current()) return null;
|
|
381
|
+
const R = this.rapier, a = vec3(from), d = vec3(to).sub(a), len = d.length();
|
|
382
|
+
if (!len) return null;
|
|
383
|
+
d.divideScalar(len);
|
|
384
|
+
const hit = this.world.castShape({ x: a.x, y: a.y, z: a.z }, NO_TURN, { x: d.x, y: d.y, z: d.z }, new R.Ball(radius), 0, len, false, R.QueryFilterFlags.EXCLUDE_SENSORS, undefined, undefined, this.playerBody);
|
|
385
|
+
if (!hit) return null;
|
|
386
|
+
const n = hit.normal1; // world space on World.castShape (the tilted-box test fails first if an upgrade changes that)
|
|
387
|
+
return { point: a.addScaledVector(d, hit.time_of_impact), normal: new THREE.Vector3(n.x, n.y, n.z), distance: hit.time_of_impact };
|
|
281
388
|
}
|
|
282
389
|
|
|
283
390
|
/** Ray (provider for engine.rays, called by engine.raycast when targets: 'all'): hits dynamic bodies only, returns RayHit (with entry, kind: 'rigid') */
|
|
284
391
|
_raycast(origin, dir, far) {
|
|
285
|
-
if (!this.
|
|
392
|
+
if (!this._current() || !this.bodies.length) return null;
|
|
286
393
|
let byHandle = this._byHandle;
|
|
287
394
|
if (!byHandle) { byHandle = this._byHandle = new Map(); for (const b of this.bodies) byHandle.set(b.body.handle, b); }
|
|
288
395
|
const max = Number.isFinite(far) ? far : 1e6;
|
|
@@ -299,12 +406,14 @@ export class RigidBodies {
|
|
|
299
406
|
// ---------- Save part 'rigid' ----------
|
|
300
407
|
/**
|
|
301
408
|
* @internal What a save keeps of each body with an id (addBox / addBall / addHull({ id }), vehicles always): pose, velocities, asleep. Without it a
|
|
302
|
-
* load put a toppling crate back upright and at rest wherever its record was, so the game after the load was not the game that was saved.
|
|
303
|
-
*
|
|
409
|
+
* load put a toppling crate back upright and at rest wherever its record was, so the game after the load was not the game that was saved. A template
|
|
410
|
+
* body carries its record id, and atRest (content/templates.js): while it stands where content put it, content is its state and it stays out of the save.
|
|
411
|
+
* Bodies not built yet keep their loaded state (it is still the saved game). Not kept: Rapier's contact / warm-start caches (docs/recipes/11-vehicles.md, section 3).
|
|
304
412
|
*/
|
|
305
413
|
_saveState() {
|
|
306
|
-
const out =
|
|
307
|
-
for (const
|
|
414
|
+
const out = {};
|
|
415
|
+
for (const [id, s] of this._saved) if (!this._outrun(id, s)) out[id] = s;
|
|
416
|
+
for (const b of this.bodies) if (b.id != null && !b.atRest) out[b.id] = stateOf(b.body);
|
|
308
417
|
return out;
|
|
309
418
|
}
|
|
310
419
|
/** @internal Load: bodies here now take their state in afterLoad (after _fresh rebuilt them); the rest when they are added */
|
|
@@ -316,7 +425,24 @@ export class RigidBodies {
|
|
|
316
425
|
}
|
|
317
426
|
/** @internal afterLoad: hand the loaded state to the bodies that exist (vehicles, bodies the game keeps across a load) */
|
|
318
427
|
_claimSaved() {
|
|
319
|
-
for (const b of this.bodies)
|
|
428
|
+
for (const b of this.bodies) this._claim(b);
|
|
429
|
+
}
|
|
430
|
+
/** @internal A body takes its loaded state, the one way in */
|
|
431
|
+
_claim(entry) {
|
|
432
|
+
if (entry.id == null) return;
|
|
433
|
+
const s = this.stateFor(entry.id);
|
|
434
|
+
this._saved.delete(entry.id);
|
|
435
|
+
if (s) putState(entry, s);
|
|
436
|
+
}
|
|
437
|
+
/** @internal The loaded state a body built now with this id takes, or null. Asked before the build too: a copy about to take a state is not where content put it (content/templates.js addBody) */
|
|
438
|
+
stateFor(id) {
|
|
439
|
+
const s = this._saved.get(id);
|
|
440
|
+
return s && !this._outrun(id, s) ? s : null;
|
|
441
|
+
}
|
|
442
|
+
/** @internal The world record of a body not built yet was moved after this state was saved (no body was there to take the write): the newer write wins, as in views.pull */
|
|
443
|
+
_outrun(id, s) {
|
|
444
|
+
const W = this.engine.world, rec = W?.records.get(id), p = rec?.position;
|
|
445
|
+
return !!p && W.presents(rec.kind) && Math.max(Math.abs(p.x - s[0]), Math.abs(p.y - s[1]), Math.abs(p.z - s[2])) > 1e-3; // presented: a record that only shares its id with a game's body follows nothing
|
|
320
446
|
}
|
|
321
447
|
|
|
322
448
|
// ---------- Every fixed step ----------
|
|
@@ -340,8 +466,7 @@ export class RigidBodies {
|
|
|
340
466
|
if (chunked) { pending = syncTerrain(this, src); pending = syncTrees(this, focus, CH) || pending; } else syncGroundTrees(this, src, CH);
|
|
341
467
|
this._srcPending = pending; this._syncT = 0; // pending: chunks still waiting for their turn, sync again next step
|
|
342
468
|
}
|
|
343
|
-
|
|
344
|
-
syncLevel(this);
|
|
469
|
+
this._upkeep();
|
|
345
470
|
if (this._jointsGone) { // dev only (set in _fresh): the old world had the game's joints and nothing re-created one since the rebuild
|
|
346
471
|
if (!this.world.impulseJoints.len()) warnOnce(coded('rigid-misuse', `rigid: ${this._jointsGone} joint(s) were freed with the old physics world by newGame / load and none was re-created. The engine rebuilds the world and does not copy joints: re-create them in a rigid:rebuilt listener ({ world }), between entry.body of the rebuilt bodies (recipes/11-vehicles.md, Joints)`));
|
|
347
472
|
this._jointsGone = 0;
|
|
@@ -361,27 +486,25 @@ export class RigidBodies {
|
|
|
361
486
|
const ok = !chunked || this._chunkReady(t.x, t.z);
|
|
362
487
|
if (ok !== b.enabled) { if (DEV && !ok) this._tellFrozen(b, t, CH); b.body.setEnabled(ok); b.enabled = ok; }
|
|
363
488
|
// buoyancy: the submerged part gets an upward force, and water adds drag
|
|
364
|
-
const water = this.buoyancy ? e.waterAt(t.x, t.z) : -Infinity;
|
|
489
|
+
const water = this.buoyancy ? e.waterAt(t.x, t.z, t.y) : -Infinity; // at its own height: a game's water body may be a pool upstairs or a falling column
|
|
365
490
|
if (ok && this.buoyancy && t.y < water + this.floatLine && b.body.isDynamic()) {
|
|
366
491
|
const depth = Math.min(1, (water + this.floatLine - t.y) / this.floatDepth);
|
|
367
492
|
const m = b.body.mass();
|
|
368
|
-
b.body.
|
|
369
|
-
b.body.addForce({ x: 0, y: -this.gravity * m * (this.buoyancyForce * depth), z: 0 }, true);
|
|
493
|
+
b.body.applyImpulse({ x: 0, y: -this.gravity * m * (this.buoyancyForce * depth) * worldDt, z: 0 }, true); // an impulse, not addForce: Rapier keeps forces until reset, and a reset would wipe the game's own thrust / wind on the same body
|
|
370
494
|
b.body.setLinearDamping(this.waterDrag); b.body.setAngularDamping(this.waterDrag);
|
|
371
495
|
b.wet = true;
|
|
372
496
|
} else if (b.wet) {
|
|
373
|
-
b.body.
|
|
497
|
+
b.body.setLinearDamping(b.damping); b.body.setAngularDamping(b.angularDamping); b.wet = false;
|
|
374
498
|
}
|
|
375
499
|
}
|
|
376
500
|
|
|
377
|
-
if (worldDt > 0) { this.world.timestep = worldDt; this.world.step(); }
|
|
501
|
+
if (worldDt > 0) { this.world.timestep = worldDt; this.world.step(); this._behind = false; }
|
|
378
502
|
|
|
379
503
|
for (const b of this.bodies) {
|
|
380
504
|
if (!b.enabled || b.body.isSleeping() || b.ragdoll) continue; // ragdoll parts are drawn by ragdoll.js, through the bones
|
|
381
505
|
const t = b.body.translation(), r = b.body.rotation();
|
|
382
|
-
b.mesh
|
|
383
|
-
|
|
384
|
-
if (t.y < -200 && e.ground.has(t.x, t.z)) this.setPosition(b, [t.x, e.surface(t.x, t.z) + 2, t.z]); // fell through the ground
|
|
506
|
+
setLocalPose(b.mesh, t, r);
|
|
507
|
+
this._fallen(b, t);
|
|
385
508
|
// fell off terrain({ shape }): one terrain:void per fall, the game decides what next
|
|
386
509
|
const under = t.y < e.ground.voidY();
|
|
387
510
|
if (under && !b._void) e.events.emit('terrain:void', { who: b, position: { x: t.x, y: t.y, z: t.z } });
|
|
@@ -391,6 +514,18 @@ export class RigidBodies {
|
|
|
391
514
|
this._ragdolls?.sync();
|
|
392
515
|
}
|
|
393
516
|
|
|
517
|
+
/**
|
|
518
|
+
* @internal Fell through the ground: the rule 'fall' decides (nothing happens until the game sets one; 'rescue' is the built-in), asked once per fall so a game's function sees one event, not one per step; b._fell stays set
|
|
519
|
+
* while a body it left down there is still down. Only over ground: out past the map edge there is nothing to put it back on.
|
|
520
|
+
*/
|
|
521
|
+
_fallen(b, t) {
|
|
522
|
+
const e = this.engine, out = t.y < FALL_Y && e.ground.has(t.x, t.z);
|
|
523
|
+
if (!out) { b._fell = false; return; }
|
|
524
|
+
if (b._fell) return;
|
|
525
|
+
b._fell = this._fall.decide(b.id, { kind: 'body', who: b, position: { x: t.x, y: t.y, z: t.z } }) !== 'rescue';
|
|
526
|
+
if (!b._fell) this.setPosition(b, [t.x, e.surface(t.x, t.z, t.y) + 2, t.z]); // from below every floor the height picks the lowest: the one it went through, not a deck or a mountain over a cave
|
|
527
|
+
}
|
|
528
|
+
|
|
394
529
|
get stats() {
|
|
395
530
|
const active = this.bodies.filter(b => b.enabled && !b.body.isSleeping()).length;
|
|
396
531
|
return { bodies: this.bodies.length, active, colliders: this.world ? this.world.colliders.len() : 0 };
|
|
@@ -404,35 +539,40 @@ function stateOf(b) {
|
|
|
404
539
|
}
|
|
405
540
|
function putState(entry, s) {
|
|
406
541
|
const b = entry.body, m = entry.mesh;
|
|
542
|
+
entry.atRest = false;
|
|
543
|
+
// sleep first: Rapier's sleep() clears speed, and a body falls asleep with the speed it last had, which it moves off with when woken
|
|
544
|
+
if (s[13]) b.sleep(); else b.wakeUp();
|
|
407
545
|
b.setTranslation({ x: s[0], y: s[1], z: s[2] }, false); b.setRotation({ x: s[3], y: s[4], z: s[5], w: s[6] }, false);
|
|
408
546
|
b.setLinvel({ x: s[7], y: s[8], z: s[9] }, false); b.setAngvel({ x: s[10], y: s[11], z: s[12] }, false);
|
|
409
|
-
|
|
410
|
-
m.position.set(s[0], s[1], s[2]); m.quaternion.set(s[3], s[4], s[5], s[6]);
|
|
547
|
+
setLocalPose(m, { x: s[0], y: s[1], z: s[2] }, { x: s[3], y: s[4], z: s[5], w: s[6] });
|
|
411
548
|
entry._x = s[0]; entry._z = s[2];
|
|
412
549
|
}
|
|
413
550
|
|
|
414
|
-
const RIGID_PARAMS = keysSchema(['gravity', 'terrainRing', 'buoyancy', 'buoyancyForce', 'waterDrag', 'floatLine', 'floatDepth', 'treeColliderHeight', 'treeRadius', 'playerCapsule']);
|
|
551
|
+
const RIGID_PARAMS = keysSchema(['gravity', 'terrainRing', 'buoyancy', 'buoyancyForce', 'waterDrag', 'floatLine', 'floatDepth', 'treeColliderHeight', 'treeRadius', 'playerCapsule', 'fallbackFloor']);
|
|
415
552
|
|
|
416
553
|
/** Real physics module (Rapier). Installs as engine.rigid. Requires collision() to be installed first */
|
|
417
554
|
export function rigid(opts = {}) {
|
|
418
555
|
readParams('rigid', RIGID_PARAMS, opts);
|
|
419
556
|
let r = null;
|
|
420
557
|
return {
|
|
421
|
-
name: 'rigid', type: 'world', provides: ['rigid'], params: RIGID_PARAMS, options: opts, label: 'Physics', noSkip: 'bodies rest while time jumps (stepping seconds of physics would only scatter them)', optional: ['interactions', 'cameraRig'], requires: ['collision'],
|
|
558
|
+
name: 'rigid', skipKind: 'none', type: 'world', provides: ['rigid', 'collider3d'], params: RIGID_PARAMS, options: opts, label: 'Physics', noSkip: 'bodies rest while time jumps (stepping seconds of physics would only scatter them)', optional: ['interactions', 'cameraRig', 'characters'], requires: ['collision'],
|
|
422
559
|
install(e, ctx) {
|
|
423
560
|
e.i18n.add(STRINGS); e.i18n.add({ 'zh-CN': { 'module.rigid': '物理引擎' }, en: { 'module.rigid': 'physics' } }); r = new RigidBodies(e, opts);
|
|
561
|
+
r._fall = ctx.rule('fall', false, ['rescue']); // shared with characters: one rule for everything that falls out of the world; no rescue unless the game chose it
|
|
562
|
+
r._graph = ctx.rule('ragdoll.graph', 'humanoid');
|
|
424
563
|
r._wasm().catch(() => {}); // start loading now (see _wasm); a failure surfaces in init, which awaits the same promise
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
e.rays.addProvider((o, d, far) => r._raycast(o, d, far)); // engine.raycast(..., { targets: 'all' }) includes rigid bodies
|
|
564
|
+
ctx.budget.metric('rigidBodies', () => r.bodies.length);
|
|
565
|
+
ctx.stream.addReadyCheck('rigid', s => !s.physics || r.ready && r.readyAt(s)); // a physics stream source waits for the collider under it
|
|
566
|
+
ctx.track(e.rays.addProvider((o, d, far) => r._raycast(o, d, far))); // engine.raycast(..., { targets: 'all' }) includes rigid bodies
|
|
428
567
|
// a new playthrough / a load is a fresh page for physics too (_fresh), rebuilt once per load: session:end only marks it due. With the world
|
|
429
568
|
// module the rebuild runs on world:load, after the load removed the records' bodies, so the rebuilt world gets them back in view order; without
|
|
430
569
|
// it, afterLoad (newGame / load / quit all apply a save) runs it. Rebuilding on both events built the world twice per new game.
|
|
431
|
-
// A refused load (session:failed) leaves the game as it was, physics included.
|
|
570
|
+
// A refused load (session:failed) leaves the game as it was, physics included: no afterLoad runs after a rollback, so the state its rigid part read back is claimed here.
|
|
571
|
+
ctx.track(e.events.on('ground:change', b => { r._srcPending = true; restandStatics(r, b); })); // dug or raised ground: colliders follow on the next step, not at the half-second check a body could fall through
|
|
432
572
|
ctx.track(e.events.on('session:end', () => { r._freshDue = true; }));
|
|
433
|
-
ctx.track(e.events.on('session:failed', () => { r._freshDue = false; }));
|
|
573
|
+
ctx.track(e.events.on('session:failed', () => { r._freshDue = false; r._claimSaved(); }));
|
|
434
574
|
ctx.track(e.events.on('world:load', () => r._fresh()));
|
|
435
|
-
|
|
575
|
+
ctx.saves.register('rigid', { notAtomic: 'the physics world is stepped, not written: a load cannot rewind what the bodies did', save: () => r._saveState(), load: d => r._loadState(d) });
|
|
436
576
|
return r;
|
|
437
577
|
},
|
|
438
578
|
afterLoad() { if (r._freshDue) r._fresh(); r._claimSaved(); }, // after every part loaded and _fresh rebuilt the world (world:load is emitted inside the world part's load)
|
|
@@ -442,9 +582,12 @@ export function rigid(opts = {}) {
|
|
|
442
582
|
describe() {
|
|
443
583
|
const B = r.bodies, n = f => B.filter(f).length;
|
|
444
584
|
return { ready: r.ready, bodies: B.length, dynamic: n(b => !b.fixed), fixed: n(b => b.fixed), sleeping: n(b => b.enabled && b.body.isSleeping()),
|
|
445
|
-
frozen: n(b => !b.enabled), vehicles: r.vehicles.length, colliders: r.world ? r.world.colliders.len() : 0, ...(r._ragdolls?.live.size && { ragdolls: r._ragdolls.live.size }) };
|
|
585
|
+
frozen: n(b => !b.enabled), vehicles: r.vehicles.length, colliders: r.world ? r.world.colliders.len() : 0, ...(r._ragdolls?.live.size && { ragdolls: r._ragdolls.live.size }), ...(r._solids.size && { solids: r._solids.size }) };
|
|
446
586
|
},
|
|
447
587
|
fixed(dt) { r.step(dt); },
|
|
448
|
-
|
|
588
|
+
// a vehicle lives in this world: its riders get out while the seat and the exit can still be read, or they would read a freed solver every step
|
|
589
|
+
dispose() { for (const v of [...r.vehicles]) r._removeVehicle(v); r._ragdolls?.dispose(); r.world?.free(); r.world = null; },
|
|
449
590
|
};
|
|
450
591
|
}
|
|
592
|
+
|
|
593
|
+
export const handRolled = [{ kind: 'physics', seen: 'a physics library of its own', use: 'rigid(): bodies, joints and vehicles on the engine step, shared with collision and saves (recipe 11)', quiet: /\b(engine|e|eng|ctx)\.rigid\b|\brigid\(\s*[{)]/, raw: /\bfrom\s+['"](?:cannon-es|cannon|ammo\.js|@dimforge\/rapier3d(?:-compat)?|oimo|matter-js)['"]/ }];
|
|
@@ -49,7 +49,7 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
49
49
|
const drives = wheels.filter(x => x.drive).length || wheels.length;
|
|
50
50
|
// seat 0 drives, the rest ride; without seats one driver seat at the chassis center
|
|
51
51
|
const seatAt = seats?.length ? seats.map(p => vec3(p)) : [new THREE.Vector3(c.x, c.y, c.z)];
|
|
52
|
-
let throttle = 0, steerIn = 0, brake = 0;
|
|
52
|
+
let throttle = 0, steerIn = 0, brake = 0, useFrom;
|
|
53
53
|
|
|
54
54
|
const v = Object.assign(entry, {
|
|
55
55
|
controller: ctl, wheels, driver: null, camera, hideDriver, seats: seatAt.length, passengers: [],
|
|
@@ -57,10 +57,15 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
57
57
|
drive(t, st, b = 0) { throttle = t; steerIn = st; brake = b; if (t || b) entry.body.wakeUp(); },
|
|
58
58
|
/** World position of a seat (0 = driver) */
|
|
59
59
|
seatPosition(seat = 0) { return mesh.localToWorld((seatAt[seat] ?? seatAt[0]).clone()); },
|
|
60
|
-
/** Exit
|
|
61
|
-
exitPosition(seat = 0
|
|
60
|
+
/** Exit n of a seat, null past the last: exitOffset meters (default 0.8) outside its own door, the other door, behind, in front */
|
|
61
|
+
exitPosition(seat = 0, n = 0) {
|
|
62
|
+
const a = seatAt[seat] ?? seatAt[0], x = (a.x >= c.x ? 1 : -1) * (s.x / 2 + exitOffset), z = s.z / 2 + exitOffset;
|
|
63
|
+
const at = [[c.x + x, a.z], [c.x - x, a.z], [c.x, c.z - z], [c.x, c.z + z]][n];
|
|
64
|
+
return at ? mesh.localToWorld(new THREE.Vector3(at[0], c.y, at[1])) : null;
|
|
65
|
+
},
|
|
62
66
|
/** Every fixed step: write controls to the wheels and advance the vehicle controller (called before the physics step) */
|
|
63
67
|
_update(dt) {
|
|
68
|
+
if (useFrom !== e.interactions) offerSeat();
|
|
64
69
|
wheels.forEach((wh, i) => {
|
|
65
70
|
ctl.setWheelEngineForce(i, wh.drive || drives === wheels.length ? throttle * engineForce / drives : 0);
|
|
66
71
|
ctl.setWheelSteering(i, wh.steer ? -steerIn * maxSteer : 0);
|
|
@@ -86,7 +91,10 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
86
91
|
return l.x * fwd.x + l.y * fwd.y + l.z * fwd.z;
|
|
87
92
|
} });
|
|
88
93
|
// With the interactions module installed: press the interact key near the car to get in, and again while driving to get out
|
|
89
|
-
|
|
94
|
+
const offerSeat = () => {
|
|
95
|
+
v._use?.remove(); v._use = null;
|
|
96
|
+
useFrom = e.interactions; // the use lives in that module: another one starts empty, so _update offers the seat again
|
|
97
|
+
if (!e.interactions) return;
|
|
90
98
|
v._use = e.interactions.add(mesh, {
|
|
91
99
|
id: v.id,
|
|
92
100
|
label: () => e.t(e.player?.vehicle === v ? 'vehicle.exit' : 'vehicle.enter'), radius: Math.max(3, s.z / 2 + 1.5),
|
|
@@ -94,6 +102,8 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
94
102
|
enabled: () => !!e.player && (e.player.vehicle === v || !v.driver || v.passengers.length < v.seats - 1),
|
|
95
103
|
onUse: () => e.player.vehicle === v ? e.player.exit() : e.player.enter(v),
|
|
96
104
|
});
|
|
97
|
-
}
|
|
105
|
+
};
|
|
106
|
+
offerSeat();
|
|
107
|
+
v._seatBook = e.characters?.addVehicle(v); // after the use: a rider seated here finds a finished vehicle
|
|
98
108
|
return v;
|
|
99
109
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// What a three-axis collision provider must give (an object contract, shared check @threedog/tools/contract). engine.collision answers on the ground plane, with a height;
|
|
2
|
+
// a tilted solid, a floating island or a flying character needs all three axes. rigid is the first holder (provides: ['collider3d'], so engine.collider3d is it);
|
|
3
|
+
// a game's own voxel grid or BVH that passes this contract takes the slot with engine.use(mine(), { replaces: 'collider3d' }), and nothing else needs to know.
|
|
4
|
+
// addSolid({ position, size | radius, rotation?, friction? }) a fixed solid, turned any way: size = [x, y, z] box, radius = ball; rotation = [x, y, z] radians or a quaternion.
|
|
5
|
+
// Returns { remove() }. Works before start() (rigid builds it with the world), and outlives newGame and a load
|
|
6
|
+
// overlap(position, radius?) is a ball here inside something solid? true / false
|
|
7
|
+
// sweep(from, to, radius?) move a ball from there to there: null when clear, else the first hit { point, normal, distance }; point is the ball's center at the
|
|
8
|
+
// hit, normal the world direction out of what it hit. What a flying mover or a path source steps with
|
|
9
|
+
// Starting in contact and moving out is clear. Sweep from the middle of a body, not its feet: a center exactly on a mesh surface has no side, and that reads as a hit at 0
|
|
10
|
+
// All three see every collider of the holder and skip the player's own capsule. Not here: walking (engine.collision), volumetric paths (rule characters.path).
|
|
11
|
+
export default {
|
|
12
|
+
name: 'collider3d',
|
|
13
|
+
kind: 'object',
|
|
14
|
+
api: ['addSolid', 'overlap', 'sweep'],
|
|
15
|
+
// Who may write where a dynamic body is (design.md section 9). The solver holds it, so the record and the model follow the body and not the other way round
|
|
16
|
+
position: {
|
|
17
|
+
authority: 'solver',
|
|
18
|
+
writers: {
|
|
19
|
+
step: 'the solver, on a fixed step; the record follows through world views',
|
|
20
|
+
setPosition: 'rigid.setPosition or body.setTranslation: a placement, by anyone; it reaches the record on the next fixed step, so a read while frozen is one step late',
|
|
21
|
+
vehicle: 'a seat rides its body: it reads the body and never writes it',
|
|
22
|
+
load: 'a save puts it back',
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
calls: [['addSolid', { position: [0, 0, 0], size: [1, 1, 1], rotation: [0, 0, 1] }], ['addSolid', { position: [0, 5, 0], radius: 1 }], ['overlap', [0, 0, 0], 0.5], ['sweep', [0, 9, 0], [0, -9, 0], 0.5]],
|
|
26
|
+
};
|