threedog 0.7.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +411 -1
- package/README.md +8 -11
- package/core/{Animator.js → assets/Animator.js} +30 -18
- package/core/{Assets.js → assets/Assets.js} +131 -56
- package/core/{Baked.js → assets/Baked.js} +4 -4
- package/core/assets/assetEntry.js +302 -0
- package/core/{assetHot.js → assets/assetHot.js} +9 -7
- package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
- package/core/assets/assetLod.js +113 -0
- package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
- package/core/{assetReport.js → assets/assetReport.js} +7 -14
- package/core/{namedModel.js → assets/namedModel.js} +17 -13
- package/core/{Audio.js → audio/Audio.js} +47 -25
- package/core/{audioRules.js → audio/audioRules.js} +8 -5
- package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
- package/core/{Events.js → base/Events.js} +3 -3
- package/core/{I18n.js → base/I18n.js} +15 -12
- package/core/{Random.js → base/Random.js} +7 -4
- package/core/{Vars.js → base/Vars.js} +14 -4
- package/core/{easing.js → base/easing.js} +1 -1
- package/core/{errorCodes.js → base/errorCodes.js} +151 -125
- package/core/{errorHints.js → base/errorHints.js} +17 -10
- package/core/{errors.js → base/errors.js} +12 -10
- package/core/{events.generated.js → base/events.generated.js} +11 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +66 -0
- package/core/{params.js → base/params.js} +5 -6
- package/core/base/saveValues.js +81 -0
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/util.js +32 -0
- package/core/{validate.js → base/validate.js} +34 -34
- package/core/{Engine.js → engine/Engine.js} +137 -91
- package/core/{Loading.js → engine/Loading.js} +34 -5
- package/core/{copies.js → engine/copies.js} +4 -4
- package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
- package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
- package/core/{loop.js → engine/loop.js} +88 -49
- package/core/engine/moduleSlots.js +176 -0
- package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
- package/core/engine/modules.js +503 -0
- package/core/{page.js → engine/page.js} +59 -29
- package/core/{plugins.js → engine/plugins.js} +21 -12
- package/core/{services.js → engine/services.js} +50 -40
- package/core/{startup.js → engine/startup.js} +66 -54
- package/core/{Input.js → input/Input.js} +67 -39
- package/core/{inputContext.js → input/inputContext.js} +14 -5
- package/core/input/inputKeyboard.js +39 -0
- package/core/{inputPad.js → input/inputPad.js} +24 -3
- package/core/{inputPointer.js → input/inputPointer.js} +11 -3
- package/core/input/inputSeat.js +66 -0
- package/core/{inputTouch.js → input/inputTouch.js} +24 -7
- package/core/{Budget.js → inspect/Budget.js} +21 -20
- package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
- package/core/{Describe.js → inspect/Describe.js} +34 -26
- package/core/{Inspect.js → inspect/Inspect.js} +39 -10
- package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
- package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
- package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
- package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
- package/core/{UrlState.js → inspect/UrlState.js} +60 -24
- package/core/{catalog.js → inspect/catalog.js} +15 -8
- package/core/{checks.js → inspect/checks.js} +7 -5
- package/core/{debugView.js → inspect/debugView.js} +4 -4
- package/core/{describeRender.js → inspect/describeRender.js} +24 -22
- package/core/{describeText.js → inspect/describeText.js} +17 -8
- package/core/inspect/geometryWatch.js +38 -0
- package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
- package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/{Ops.js → ops/Ops.js} +44 -14
- package/core/{control.js → ops/control.js} +57 -31
- package/core/ops/holds.js +140 -0
- package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
- package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
- package/core/{opsFail.js → ops/opsFail.js} +5 -7
- package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
- package/core/{opsRun.js → ops/opsRun.js} +9 -6
- package/core/{owned.js → ops/owned.js} +33 -19
- package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
- package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
- package/core/{stacks.js → ops/stacks.js} +34 -15
- package/core/{wrap.js → ops/wrap.js} +8 -6
- package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
- package/core/{Saves.js → saves/Saves.js} +171 -54
- package/core/saves/saveApply.js +312 -0
- package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
- package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
- package/core/saves/session.js +231 -0
- package/core/saves/stateReplace.js +184 -0
- package/core/{Rays.js → scene/Rays.js} +44 -30
- package/core/{Views.js → scene/Views.js} +16 -8
- package/core/{adaptive.js → scene/adaptive.js} +19 -9
- package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/{gameLights.js → scene/gameLights.js} +17 -7
- package/core/{grayMap.js → scene/grayMap.js} +8 -2
- package/core/{grid.js → scene/grid.js} +6 -4
- package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +139 -0
- package/core/{movement.js → scene/movement.js} +3 -3
- package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
- package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
- package/core/scene/stepPoses.js +60 -0
- package/core/{targeting.js → scene/targeting.js} +4 -5
- package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
- package/core/{thingOps.js → scene/thingOps.js} +25 -16
- package/core/{things.js → scene/things.js} +18 -5
- package/core/{threePatches.js → scene/threePatches.js} +1 -1
- package/core/{tier.js → scene/tier.js} +10 -0
- package/core/scene/view.js +161 -0
- package/core/{Batching.js → stream/Batching.js} +85 -28
- package/core/{Stream.js → stream/Stream.js} +80 -38
- package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
- package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
- package/core/{scatter.js → stream/scatter.js} +7 -4
- package/core/{streamSources.js → stream/streamSources.js} +14 -8
- package/core/{Commits.js → threads/Commits.js} +17 -11
- package/core/{Jobs.js → threads/Jobs.js} +25 -13
- package/core/{Threads.js → threads/Threads.js} +21 -18
- package/core/{threadPure.js → threads/threadPure.js} +7 -5
- package/core/{threadServe.js → threads/threadServe.js} +3 -3
- package/core/{Clock.js → time/Clock.js} +20 -11
- package/core/{dayTime.js → time/dayTime.js} +5 -1
- package/core/{skip.js → time/skip.js} +28 -21
- package/core/{time.js → time/time.js} +32 -20
- package/core/{uiClock.js → time/uiClock.js} +4 -4
- package/docs/AI.md +92 -72
- package/docs/API.md +33 -28
- package/docs/CODEMAP.md +121 -200
- package/docs/COMMANDS.md +77 -70
- package/docs/CONVENTIONS.md +167 -24
- package/docs/MIGRATING-0.8.md +171 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +140 -38
- package/docs/api/assets.md +12 -13
- package/docs/api/audio.md +6 -5
- package/docs/api/budget.md +4 -4
- package/docs/api/calendar.md +10 -11
- package/docs/api/cameraRig.md +32 -29
- package/docs/api/characters.md +35 -24
- package/docs/api/clock.md +1 -1
- package/docs/api/collider3d.md +9 -0
- package/docs/api/collision.md +12 -9
- package/docs/api/content.md +18 -17
- package/docs/api/dialogue.md +5 -4
- package/docs/api/engine.md +58 -54
- package/docs/api/events.md +17 -6
- package/docs/api/flow.md +1 -1
- package/docs/api/grids.md +1 -1
- package/docs/api/ground.md +6 -7
- package/docs/api/hud.md +2 -2
- package/docs/api/i18n.md +6 -6
- package/docs/api/input.md +9 -8
- package/docs/api/interactions.md +5 -5
- package/docs/api/inventory.md +10 -10
- package/docs/api/jobs.md +5 -5
- package/docs/api/level.md +10 -9
- package/docs/api/lightPool.md +1 -6
- package/docs/api/music.md +3 -3
- package/docs/api/nav.md +14 -12
- package/docs/api/openWorld.md +1 -1
- package/docs/api/particles.md +10 -7
- package/docs/api/photo.md +4 -2
- package/docs/api/pickups.md +3 -3
- package/docs/api/post.md +21 -5
- package/docs/api/quests.md +7 -5
- package/docs/api/rays.md +7 -7
- package/docs/api/rigid.md +29 -19
- package/docs/api/saves.md +13 -11
- package/docs/api/settings.md +9 -8
- package/docs/api/sky.md +8 -7
- package/docs/api/stream.md +8 -9
- package/docs/api/swarm.md +34 -0
- package/docs/api/terrain.md +6 -8
- package/docs/api/terrainDraw.md +2 -2
- package/docs/api/timeline.md +4 -4
- package/docs/api/tools.md +27 -22
- package/docs/api/triggers.md +2 -0
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -3
- package/docs/api/vegetationDraw.md +2 -2
- package/docs/api/water.md +7 -3
- package/docs/api/weather.md +27 -12
- package/docs/api/weatherDraw.md +4 -4
- package/docs/api/world.md +6 -6
- package/docs/recipes/01-new-game.md +28 -43
- package/docs/recipes/02-npc.md +21 -23
- package/docs/recipes/03-items-pickups.md +37 -53
- package/docs/recipes/04-quests.md +5 -4
- package/docs/recipes/05-props-bake.md +34 -44
- package/docs/recipes/06-clock-events.md +31 -22
- package/docs/recipes/07-flow-scenes-pause.md +30 -32
- package/docs/recipes/08-weather-sky.md +91 -37
- package/docs/recipes/09-materials-lights-models.md +25 -39
- package/docs/recipes/10-blender-level.md +22 -11
- package/docs/recipes/11-vehicles.md +44 -24
- package/docs/recipes/12-navmesh.md +60 -15
- package/docs/recipes/13-animation.md +70 -22
- package/docs/recipes/14-custom-module.md +33 -20
- package/docs/recipes/15-perf.md +51 -28
- package/docs/recipes/16-dev-bridge.md +39 -58
- package/docs/recipes/18-world.md +49 -28
- package/docs/recipes/19-shooting-picking.md +7 -4
- package/docs/recipes/20-content-actions-save.md +55 -40
- package/docs/recipes/21-camera.md +47 -25
- package/docs/recipes/22-shop-gold.md +21 -16
- package/docs/recipes/23-ops.md +28 -24
- package/docs/recipes/26-ui-parts.md +25 -14
- package/docs/recipes/27-net.md +3 -5
- package/docs/recipes/28-terrain.md +119 -23
- package/docs/recipes/29-grid.md +3 -3
- package/docs/recipes/30-templates.md +63 -30
- package/docs/recipes/31-audio.md +7 -7
- package/docs/recipes/32-action-game.md +21 -11
- package/docs/recipes/33-stream-sources.md +6 -3
- package/docs/recipes/34-environment-lighting.md +72 -25
- package/docs/recipes/35-picture-from-reference.md +20 -23
- package/docs/recipes/36-ground-plants.md +106 -0
- package/docs/recipes/40-scene.md +18 -21
- package/docs/recipes/43-shader-patches-surfaces.md +27 -48
- package/docs/recipes/44-water-weather-hooks.md +56 -50
- package/docs/recipes/45-cascaded-shadows.md +41 -20
- package/docs/recipes/46-blender-art-route.md +9 -10
- package/docs/recipes/49-game-module-contract.md +7 -6
- package/docs/recipes/50-own-renderer.md +3 -2
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +56 -100
- package/docs/recipes/53-ground-up-close.md +61 -24
- package/docs/recipes/55-mods-time-wrap.md +17 -20
- package/docs/recipes/56-webgpu-tsl.md +28 -15
- package/docs/recipes/57-control.md +39 -12
- package/docs/recipes/58-input.md +15 -2
- package/docs/recipes/59-depth-post-effects.md +1 -1
- package/docs/recipes/60-judge-the-picture.md +30 -25
- package/docs/recipes/62-picture-code.md +129 -39
- package/docs/recipes/63-third-person-start.md +19 -5
- package/docs/recipes/64-particles.md +54 -5
- package/docs/recipes/65-swarm.md +140 -0
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/perf-island/.threedog/content-index.json +1 -0
- package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
- package/examples/{sheepisland → perf-island}/assets.js +1 -1
- package/examples/{sheepisland → perf-island}/main.js +8 -8
- package/examples/{sheepisland → perf-island}/models.js +1 -1
- package/examples/{sheepisland → perf-island}/params.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
- package/examples/{sheepisland → perf-island}/views.js +1 -1
- package/examples/plain-picture/GAMEMAP.md +4 -1
- package/examples/rc2d/GAMEMAP.md +4 -3
- package/examples/rc2d/main.js +1 -3
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +6 -5
- package/examples/techniques/contact-shadows/contactShadows.js +1 -1
- package/examples/techniques/contact-shadows/main.js +1 -1
- package/examples/techniques/interior-light/main.js +1 -1
- package/examples/techniques/modular-building/README.md +7 -6
- package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +2 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +9 -7
- package/examples/world/main.js +3 -3
- package/examples/world/picture/sky.js +1 -1
- package/index.d.ts +16 -12
- package/index.js +53 -32
- package/llms.txt +11 -14
- package/modules/ambience/Ambience.js +16 -11
- package/modules/calendar/Calendar.js +19 -19
- package/modules/calendar/index.js +18 -16
- package/modules/calendar/schedule.js +11 -6
- package/modules/calendar/seasons.js +7 -7
- package/modules/camera/FirstPersonCamera.js +5 -5
- package/modules/camera/FixedCamera.js +43 -30
- package/modules/camera/FollowCamera.js +24 -15
- package/modules/camera/RtsCamera.js +12 -11
- package/modules/camera/common.js +72 -37
- package/modules/camera/contract.js +1 -0
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +166 -70
- package/modules/characters/NPC.js +84 -44
- package/modules/characters/assetModel.js +16 -12
- package/modules/characters/astar.js +48 -27
- package/modules/characters/behaviors.js +4 -5
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +240 -226
- package/modules/characters/moveHelpers.js +88 -12
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +22 -18
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +18 -10
- package/modules/characters/movers/simple.js +26 -13
- package/modules/characters/movers/support.js +24 -13
- package/modules/characters/npcAvoid.js +19 -16
- package/modules/characters/npcSim.js +88 -32
- package/modules/characters/npcView.js +19 -11
- package/modules/characters/pathAsync.js +81 -29
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/pathWorker.js +1 -1
- package/modules/characters/player.js +120 -0
- package/modules/characters/playerStrings.js +2 -2
- package/modules/characters/proceduralRig.js +2 -2
- package/modules/characters/seat.js +56 -0
- package/modules/characters/useModel.js +3 -3
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +40 -33
- package/modules/collision/Collision.js +69 -45
- package/modules/collision/contract.js +15 -0
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +2 -3
- package/modules/content/fields.js +24 -3
- package/modules/content/ids.js +5 -3
- package/modules/content/index.js +132 -114
- package/modules/content/loader.js +117 -140
- package/modules/content/markers.js +25 -0
- package/modules/content/models.js +54 -17
- package/modules/content/packs.js +5 -4
- package/modules/content/parts.js +2 -2
- package/modules/content/places.js +36 -0
- package/modules/content/props.js +22 -17
- package/modules/content/rules.js +47 -61
- package/modules/content/stages.js +7 -7
- package/modules/content/templates.js +80 -49
- package/modules/content/words.js +47 -0
- package/modules/debug/DebugPanel.js +14 -45
- package/modules/flow/contract.js +2 -1
- package/modules/flow/index.js +30 -16
- package/modules/gameplay/Container.js +17 -13
- package/modules/gameplay/Containers.js +23 -6
- package/modules/gameplay/Dialogue.js +93 -34
- package/modules/gameplay/Interactions.js +93 -51
- package/modules/gameplay/Inventory.js +64 -22
- package/modules/gameplay/Quests.js +146 -30
- package/modules/gameplay/boxOps.js +8 -1
- package/modules/gameplay/dialogueBubbles.js +16 -12
- package/modules/gameplay/inventoryOps.js +11 -8
- package/modules/gameplay/pickups.js +63 -37
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +9 -4
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +2 -2
- package/modules/grid/Layer.js +12 -8
- package/modules/grid/index.js +28 -23
- package/modules/grid/ops.js +43 -46
- package/modules/grid/preview.js +7 -7
- package/modules/grid/tiles.js +6 -6
- package/modules/hlod/index.js +42 -57
- package/modules/hud/index.js +22 -14
- package/modules/hud/parts.js +8 -8
- package/modules/level/contract.js +16 -0
- package/modules/level/heightfield.js +29 -31
- package/modules/level/index.js +113 -161
- package/modules/level/load.js +196 -0
- package/modules/level/meshes.js +65 -0
- package/modules/level/nodes.js +40 -23
- package/modules/lights/index.js +33 -183
- package/modules/lights/slots.js +93 -0
- package/modules/lights/sources.js +90 -0
- package/modules/music/Music.js +34 -28
- package/modules/music/rules.js +1 -1
- package/modules/nav/contract.js +16 -0
- package/modules/nav/index.js +180 -49
- package/modules/nav/navPath.js +45 -10
- package/modules/net/Client.js +7 -7
- package/modules/net/Host.js +7 -7
- package/modules/net/Net.js +1 -1
- package/modules/net/index.js +6 -5
- package/modules/net/sync.js +2 -2
- package/modules/net/transports.js +2 -2
- package/modules/particles/Particles.js +95 -29
- package/modules/particles/effect.js +86 -32
- package/modules/particles/shaders.js +19 -1
- package/modules/photo/Photo.js +23 -23
- package/modules/rigid/RigidBodies.js +255 -89
- package/modules/rigid/Vehicles.js +17 -8
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +298 -0
- package/modules/rigid/ragdollBones.js +209 -0
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +51 -20
- package/modules/settings/Settings.js +177 -61
- package/modules/settings/apply.js +20 -13
- package/modules/settings/sections.js +19 -14
- package/modules/settings/strings.js +2 -2
- package/modules/settings/view.js +3 -3
- package/modules/sky/Sky.js +29 -22
- package/modules/sky/clouds.js +7 -7
- package/modules/sky/dome.js +33 -20
- package/modules/sky/domeLayers.js +9 -9
- package/modules/sky/environment.js +6 -6
- package/modules/sky/frame.js +19 -10
- package/modules/sky/season.js +7 -1
- package/modules/sky/shader.js +24 -25
- package/modules/sky/skyModule.js +17 -28
- package/modules/sky/tint.js +1 -1
- package/modules/swarm/Swarm.js +356 -0
- package/modules/swarm/draw.js +68 -0
- package/modules/swarm/grid.js +63 -0
- package/modules/terrain/ChunkManager.js +71 -59
- package/modules/terrain/chunkQueries.js +7 -24
- package/modules/terrain/chunkWorker.js +1 -1
- package/modules/terrain/draw.js +14 -11
- package/modules/terrain/index.js +42 -42
- package/modules/terrain/terrainColorMap.js +6 -3
- package/modules/terrain/terrainDefaults.js +2 -1
- package/modules/terrain/terrainEdit.js +45 -29
- package/modules/terrain/terrainGen.js +19 -12
- package/modules/terrain/terrainIsland.js +2 -2
- package/modules/terrain/terrainMesh.js +7 -6
- package/modules/terrain/terrainShape.js +8 -10
- package/modules/terrain/terrainShapeMain.js +3 -3
- package/modules/timeline/Timeline.js +83 -43
- package/modules/timeline/Tween.js +25 -19
- package/modules/timeline/shots.js +24 -17
- package/modules/triggers/index.js +95 -28
- package/modules/vegetation/Vegetation.js +34 -26
- package/modules/vegetation/densityMap.js +4 -7
- package/modules/vegetation/draw.js +39 -18
- package/modules/vegetation/groundChunks.js +21 -38
- package/modules/vegetation/index.js +37 -12
- package/modules/vegetation/modelGeometry.js +3 -6
- package/modules/vegetation/nearFade.js +1 -1
- package/modules/water/Water.js +20 -16
- package/modules/water/surface.js +3 -3
- package/modules/weather/Weather.js +52 -40
- package/modules/weather/particles.js +8 -8
- package/modules/weather/weatherDraw.js +28 -23
- package/modules/world/World.js +28 -15
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +30 -17
- package/modules/world/persist.js +90 -27
- package/modules/world/pos.js +5 -5
- package/modules/world/records.js +37 -11
- package/modules/world/sim.js +78 -27
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +43 -11
- package/modules/world/thingSource.js +20 -5
- package/modules/world/views.js +27 -14
- package/package.json +48 -7
- package/presets.js +1 -3
- package/render/PostFX.js +83 -53
- package/render/backend.js +31 -33
- package/render/cascades.js +17 -12
- package/render/cascades.tsl.js +5 -8
- package/render/daylight.js +20 -3
- package/render/detail.js +8 -7
- package/render/effects.js +28 -25
- package/render/fuse.js +3 -3
- package/render/fx/cloudShadow.tsl.js +3 -3
- package/render/fx/detail.tsl.js +1 -1
- package/render/fx/index.js +5 -10
- package/render/fx/library.tsl.js +11 -0
- package/render/fx/lighting.tsl.js +2 -1
- package/render/fx/nodeErrors.tsl.js +2 -2
- package/render/fx/objectOrigin.tsl.js +1 -2
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/patchNodes.tsl.js +5 -15
- package/render/fx/postWebGPU.tsl.js +30 -26
- package/render/fx/sky.tsl.js +15 -17
- package/render/fx/uniforms.tsl.js +4 -4
- package/render/fx/wind.tsl.js +1 -1
- package/render/fxNumbers.js +3 -0
- package/render/layers.js +2 -2
- package/render/lighting.js +5 -3
- package/render/lightmap.js +41 -21
- package/render/lights.js +6 -6
- package/render/lit.js +24 -0
- package/render/materials.js +8 -7
- package/render/mergeCommon.js +22 -0
- package/render/modeling.js +2 -2
- package/render/occlusion.js +62 -15
- package/render/ownFrame.js +4 -4
- package/render/patches.js +15 -15
- package/render/postWebGL.js +15 -12
- package/render/probes.js +41 -19
- package/render/recordSweep.js +117 -0
- package/render/shaderErrors.js +10 -9
- package/render/shadowCache.tsl.js +107 -0
- package/render/shadowTypes.js +9 -0
- package/{core → render}/shadows.js +59 -13
- package/render/slots.js +7 -7
- package/render/terms.js +22 -24
- package/render/uniformDecl.js +1 -1
- package/types/core.d.ts +336 -202
- package/types/gameplay.d.ts +254 -130
- package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
- package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
- package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
- package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
- package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
- package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
- package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
- package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
- package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
- package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
- package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
- package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
- package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
- package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
- package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
- package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
- package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
- package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
- package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
- package/types/generated/modules/calendar/Calendar.d.ts +10 -11
- package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/grid/Layer.d.ts +1 -1
- package/types/generated/modules/grid/index.d.ts +3 -3
- package/types/generated/modules/music/Music.d.ts +7 -5
- package/types/generated/modules/particles/Particles.d.ts +5 -4
- package/types/generated/modules/sky/Sky.d.ts +21 -10
- package/types/generated/modules/swarm/Swarm.d.ts +80 -0
- package/types/generated/modules/timeline/Timeline.d.ts +7 -5
- package/types/generated/modules/water/Water.d.ts +1 -0
- package/types/generated/modules/weather/Weather.d.ts +14 -16
- package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
- package/types/generated/modules/world/World.d.ts +11 -7
- package/types/generated/render/PostFX.d.ts +21 -23
- package/types/generated/render/materials.d.ts +1 -0
- package/types/generated/render/occlusion.d.ts +9 -0
- package/types/generated/render/patches.d.ts +1 -0
- package/types/generated/ui/Focus.d.ts +1 -0
- package/types/generated/ui/UI.d.ts +1 -0
- package/types/nav.d.ts +47 -15
- package/types/physics.d.ts +150 -73
- package/types/pixel.d.ts +75 -0
- package/types/tsl.d.ts +37 -4
- package/types/world.d.ts +48 -75
- package/ui/Focus.js +10 -9
- package/ui/Parts.js +13 -5
- package/ui/UI.js +7 -7
- package/ui/defaults.js +3 -2
- package/ui/theme.js +7 -5
- package/core/assetEntry.js +0 -109
- package/core/engineCamera.js +0 -32
- package/core/ground.js +0 -104
- package/core/holds.js +0 -134
- package/core/math.js +0 -48
- package/core/moduleSlots.js +0 -100
- package/core/modules.js +0 -314
- package/core/saveApply.js +0 -210
- package/core/saveValues.js +0 -46
- package/core/session.js +0 -174
- package/core/shadowTypes.js +0 -16
- package/core/util.js +0 -17
- package/core/view.js +0 -43
- package/docs/MIGRATING-0.3.md +0 -248
- package/docs/MIGRATING-0.4.md +0 -320
- package/docs/MIGRATING-0.5.md +0 -68
- package/docs/MIGRATING-0.6.md +0 -126
- package/docs/PERF.md +0 -245
- package/docs/recipes/36-sky-ground-plants.md +0 -158
- package/docs/recipes/37-terrain-hooks.md +0 -115
- package/docs/recipes/38-environment-hooks.md +0 -67
- package/docs/recipes/42-terrain-shape.md +0 -64
- package/docs/recipes/47-island-snow-backdrop.md +0 -43
- package/docs/recipes/54-three-idioms.md +0 -88
- package/examples/plain-picture/FINDINGS.md +0 -53
- package/examples/sheepisland/.threedog/content-index.json +0 -1
- package/modules/camera/projection.js +0 -21
- /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
- /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
- /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
- /package/core/{actor.js → ops/actor.js} +0 -0
- /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
- /package/core/{saveIds.js → saves/saveIds.js} +0 -0
- /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
- /package/core/{cells.js → stream/cells.js} +0 -0
- /package/core/{streamCells.js → stream/streamCells.js} +0 -0
- /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
- /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// engine.player.enter(car); car.drive(throttle, steer, brake)
|
|
9
9
|
// Native objects: car.body (rigid body), car.controller (vehicle controller).
|
|
10
10
|
import * as THREE from 'three';
|
|
11
|
-
import { vec3 } from '../../core/math.js';
|
|
11
|
+
import { vec3 } from '../../core/base/math.js';
|
|
12
12
|
|
|
13
13
|
export const VEHICLE_KEYS = ['id', 'wheels', 'mass', 'engineForce', 'brakeForce', 'maxSteer', 'suspension', 'seats', 'hideDriver', 'camera', 'size', 'friction', 'exitOffset'];
|
|
14
14
|
export const STRINGS = { 'zh-CN': { 'vehicle.enter': '上车', 'vehicle.exit': '下车' }, en: { 'vehicle.enter': 'Get in', 'vehicle.exit': 'Get out' } };
|
|
@@ -29,11 +29,10 @@ function bodyBox(mesh, wheelObjs) {
|
|
|
29
29
|
|
|
30
30
|
/** Create a vehicle (called by RigidBodies.addWheeled) */
|
|
31
31
|
export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 800, brakeForce = 20, maxSteer = 0.5, suspension = {}, seats, hideDriver = true, camera, size, friction = 1.5, exitOffset = 0.8 }, id) {
|
|
32
|
-
const e = rigid.engine, R = rigid.
|
|
32
|
+
const e = rigid.engine, R = rigid.rapier, w = rigid.world;
|
|
33
33
|
const box = bodyBox(mesh, new Set(wheels.map(x => x.object).filter(Boolean)));
|
|
34
34
|
const s = size ? new THREE.Vector3().fromArray(size) : box.getSize(new THREE.Vector3()), c = size ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());
|
|
35
35
|
const entry = rigid._add(mesh, R.ColliderDesc.cuboid(s.x / 2, s.y / 2, s.z / 2).setTranslation(c.x, c.y, c.z), { id, mass, friction: 0.5, damping: 0.1, angularDamping: 0.5 });
|
|
36
|
-
entry.volume = s.x * s.y * s.z;
|
|
37
36
|
const ctl = w.createVehicleController(entry.body);
|
|
38
37
|
ctl.indexUpAxis = 1; ctl.setIndexForwardAxis = 2; // up = Y, forward = Z
|
|
39
38
|
const { rest = 0.3, stiffness = 30, damping = 4 } = suspension;
|
|
@@ -50,7 +49,7 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
50
49
|
const drives = wheels.filter(x => x.drive).length || wheels.length;
|
|
51
50
|
// seat 0 drives, the rest ride; without seats one driver seat at the chassis center
|
|
52
51
|
const seatAt = seats?.length ? seats.map(p => vec3(p)) : [new THREE.Vector3(c.x, c.y, c.z)];
|
|
53
|
-
let throttle = 0, steerIn = 0, brake = 0;
|
|
52
|
+
let throttle = 0, steerIn = 0, brake = 0, useFrom;
|
|
54
53
|
|
|
55
54
|
const v = Object.assign(entry, {
|
|
56
55
|
controller: ctl, wheels, driver: null, camera, hideDriver, seats: seatAt.length, passengers: [],
|
|
@@ -58,10 +57,15 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
58
57
|
drive(t, st, b = 0) { throttle = t; steerIn = st; brake = b; if (t || b) entry.body.wakeUp(); },
|
|
59
58
|
/** World position of a seat (0 = driver) */
|
|
60
59
|
seatPosition(seat = 0) { return mesh.localToWorld((seatAt[seat] ?? seatAt[0]).clone()); },
|
|
61
|
-
/** Exit
|
|
62
|
-
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
|
+
},
|
|
63
66
|
/** Every fixed step: write controls to the wheels and advance the vehicle controller (called before the physics step) */
|
|
64
67
|
_update(dt) {
|
|
68
|
+
if (useFrom !== e.interactions) offerSeat();
|
|
65
69
|
wheels.forEach((wh, i) => {
|
|
66
70
|
ctl.setWheelEngineForce(i, wh.drive || drives === wheels.length ? throttle * engineForce / drives : 0);
|
|
67
71
|
ctl.setWheelSteering(i, wh.steer ? -steerIn * maxSteer : 0);
|
|
@@ -87,7 +91,10 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
87
91
|
return l.x * fwd.x + l.y * fwd.y + l.z * fwd.z;
|
|
88
92
|
} });
|
|
89
93
|
// With the interactions module installed: press the interact key near the car to get in, and again while driving to get out
|
|
90
|
-
|
|
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;
|
|
91
98
|
v._use = e.interactions.add(mesh, {
|
|
92
99
|
id: v.id,
|
|
93
100
|
label: () => e.t(e.player?.vehicle === v ? 'vehicle.exit' : 'vehicle.enter'), radius: Math.max(3, s.z / 2 + 1.5),
|
|
@@ -95,6 +102,8 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
95
102
|
enabled: () => !!e.player && (e.player.vehicle === v || !v.driver || v.passengers.length < v.seats - 1),
|
|
96
103
|
onUse: () => e.player.vehicle === v ? e.player.exit() : e.player.enter(v),
|
|
97
104
|
});
|
|
98
|
-
}
|
|
105
|
+
};
|
|
106
|
+
offerSeat();
|
|
107
|
+
v._seatBook = e.characters?.addVehicle(v); // after the use: a rider seated here finds a finished vehicle
|
|
99
108
|
return v;
|
|
100
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
|
+
};
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
// Ragdoll: one dynamic rigid body per part of a skinned character, joined by joints; every fixed step the result is written back to the plain three.js bones.
|
|
2
|
+
// const rd = engine.rigid.ragdoll(player, { impulse: [0, 2, -8], position: hitPoint });
|
|
3
|
+
// rd.remove(); // back to animation
|
|
4
|
+
// engine.mod('ragdoll.graph', { owner: 'game', id: 'wolf', set: { body: { bone: 'Spine' }, tail: { bone: 'Tail1', parent: 'body' } } }); // not a human: any graph of parts
|
|
5
|
+
//
|
|
6
|
+
// Why it is done this way:
|
|
7
|
+
// - Bodies do not use the bone's orientation but "one shared frame for the whole body in bind pose": bodyQ = boneWorldQ * inv(restQ). That way the frames on both sides of every joint coincide in bind pose,
|
|
8
|
+
// so the limit zero is the bind pose, whatever pose the animation was in at the start. Using bone orientation directly gives every joint an error the moment it is created and it blows apart on the first step.
|
|
9
|
+
// - Only the root part writes a position, other bones write rotation only: child bones keep their local offsets, so bone length cannot change and the mesh cannot stretch (the forum post this was modelled on fails right here).
|
|
10
|
+
// - Parts go through rigid's _add: buoyancy, freezing while terrain is not ready, engine.raycast and world rebuild all come for free; no second copy.
|
|
11
|
+
// - Not saved: as soon as rigid's save part is read in (new game, load and saves.load all go through it) every ragdoll ends and a normal character comes back; a refused load never gets here, so the ragdoll keeps lying there.
|
|
12
|
+
// On a world rebuild without a load, rigid carries the bodies over and this rebuilds the joints on rigid:rebuilt.
|
|
13
|
+
// - Self-collision is off: capsules of neighbouring parts overlap at the start and would push each other away; the limits keep the pose.
|
|
14
|
+
// shortcut: one collision group, so ragdolls do not collide with each other either; to pile bodies up, give each ragdoll its own group bit.
|
|
15
|
+
import * as THREE from 'three';
|
|
16
|
+
import { vec3 } from '../../core/base/math.js';
|
|
17
|
+
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
18
|
+
import { codedError } from '../../core/base/errorHints.js';
|
|
19
|
+
import { humanoidGraph, shapeParts } from './ragdollBones.js';
|
|
20
|
+
|
|
21
|
+
const KEYS = keysSchema(['impulse', 'position', 'bones', 'limits', 'mass']);
|
|
22
|
+
const GROUP = (0x8000 << 16 | 0x7fff) >>> 0; // the high 16 bits are its own group, the low 16 bits say what it can touch: everything except its own group
|
|
23
|
+
const FRICTION = 2; // damping in the joints (1/s): limbs with no muscle still do not whip around like ropes forever
|
|
24
|
+
const CALM_SPEED = 0.09, CALM_SPIN = 4, CALM_STEPS = 45; // speed squared (m²/s²), angular speed squared (rad²/s²), how many steps in a row
|
|
25
|
+
const HIT_SPEED = 6; // the speed (m/s) the hit part alone can take, see _push
|
|
26
|
+
|
|
27
|
+
const q1 = new THREE.Quaternion(), q2 = new THREE.Quaternion(), p1 = new THREE.Vector3(), s1 = new THREE.Vector3(), m1 = new THREE.Matrix4();
|
|
28
|
+
const toQ = (r, out = q1) => out.set(r.x, r.y, r.z, r.w);
|
|
29
|
+
const worldOf = (o, p, q) => { o.matrixWorld.decompose(p, q, s1); };
|
|
30
|
+
const shapes = new WeakMap(); // skeleton -> { key, parts }: the same character falling again and again is not re-measured
|
|
31
|
+
|
|
32
|
+
export class Ragdolls {
|
|
33
|
+
/** @param {import('./RigidBodies.js').RigidBodies} r */
|
|
34
|
+
constructor(r) {
|
|
35
|
+
this.r = r; this.e = r.engine;
|
|
36
|
+
/** @type {Set<any>} */ this.live = new Set();
|
|
37
|
+
// Listeners are attached on first use: a game that never uses ragdolls pays nothing
|
|
38
|
+
this._sub = this.e.events.on('rigid:rebuilt', () => { for (const rd of this.live) this._joints(rd); });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The body of engine.rigid.ragdoll */
|
|
42
|
+
start(who, o = {}) {
|
|
43
|
+
readParams('rigid.ragdoll()', KEYS, o);
|
|
44
|
+
const { ch, root } = this._find(who);
|
|
45
|
+
const old = [...this.live].find(rd => rd.root === root);
|
|
46
|
+
if (old) { this._push(old, o); return old; } // already down and hit again: do not rebuild, just push once more
|
|
47
|
+
if (ch?.vehicle) throw codedError('rigid-misuse', `rigid.ragdoll(): character '${ch.id}' sits in a vehicle. Fix: character.exit() first`);
|
|
48
|
+
const mesh = skinOf(root);
|
|
49
|
+
if (!mesh) throw codedError('rigid-misuse', `rigid.ragdoll(): no SkinnedMesh under ${ch ? `character '${ch.id}'` : `'${root.name || root.type}'`}, so there are no bones to drive. A capsule or a procedural rig cannot go limp; a model given by name loads later: await character.whenReady first`);
|
|
50
|
+
const shape = this._shape(ch, root, mesh, o.bones);
|
|
51
|
+
if (!shape) return null; // the game's rule says this one does not go limp
|
|
52
|
+
// Take control first: a remote character throws here, when nothing has been built yet
|
|
53
|
+
const hold = ch ? this.e.control.take(ch, { owner: 'ragdoll', layer: 'physics', step: () => false }) : null;
|
|
54
|
+
const rd = this._build(ch, root, mesh, shape, hold, o);
|
|
55
|
+
this.live.add(rd);
|
|
56
|
+
this._yield(rd);
|
|
57
|
+
this._push(rd, o);
|
|
58
|
+
return rd;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Accepts a Character, an NPC handle, a character id, or a model that belongs to no character */
|
|
62
|
+
_find(who) {
|
|
63
|
+
if (who?.isObject3D) return { ch: null, root: who };
|
|
64
|
+
const ch = who?.root && who?.move ? who : typeof who === 'string' ? this.e.control.characterOf(who) : who?.character;
|
|
65
|
+
if (!ch) throw codedError('rigid-misuse', `rigid.ragdoll(character): pass a Character, an NPC handle (its model must be built), a character id or a skinned Object3D, got ${String(who?.id ?? who)}`);
|
|
66
|
+
return { ch, root: ch.root };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The rule 'ragdoll.graph' for this body: 'humanoid', a graph, or false for no ragdoll. Measured once per skeleton and graph */
|
|
70
|
+
_shape(ch, root, mesh, bones = {}) {
|
|
71
|
+
const g = this.r._graph.decide(ch?.id, { character: ch, root, mesh });
|
|
72
|
+
if (g === false) return null;
|
|
73
|
+
const human = g === 'humanoid';
|
|
74
|
+
if (!human && Object.keys(bones).length) throw codedError('rigid-misuse', `rigid.ragdoll({ bones }): bones names the parts of the humanoid graph, and this body's rule 'ragdoll.graph' gives its own. Fix: name the bones in the graph`);
|
|
75
|
+
const key = JSON.stringify(human ? bones : g, (k, v) => (v?.isObject3D ? v.uuid : v));
|
|
76
|
+
const c = shapes.get(mesh.skeleton);
|
|
77
|
+
if (c?.key === key) return c.parts;
|
|
78
|
+
const parts = shapeParts(mesh, human ? humanoidGraph(mesh, bones) : g);
|
|
79
|
+
shapes.set(mesh.skeleton, { key, parts });
|
|
80
|
+
return parts;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
_build(ch, root, mesh, shape, hold, o) {
|
|
84
|
+
const { r } = this, R = r.rapier, skeleton = mesh.skeleton, top = shape[0];
|
|
85
|
+
const massK = o.mass != null ? o.mass / shape.reduce((n, s) => n + s.mass, 0) : 1; // the call's whole-body mass keeps the graph's proportions
|
|
86
|
+
root.updateWorldMatrix(true, true);
|
|
87
|
+
const holder = new THREE.Group(); // parent of the placeholder objects: _add does not add to the scene when there is a parent
|
|
88
|
+
const parts = {}, list = [];
|
|
89
|
+
// bind space to world scale: when the model is scaled (0.01 is common for Mixamo) colliders must use the real length as it is now
|
|
90
|
+
// read from the skinning matrix of the root part: bind to now is pose and scale, and pose does not change its size, whatever the body looks like
|
|
91
|
+
const k = s1.setFromMatrixScale(m1.multiplyMatrices(top.bone.matrixWorld, skeleton.boneInverses[skeleton.bones.indexOf(top.bone)])).x;
|
|
92
|
+
for (const s of shape) {
|
|
93
|
+
const proxy = new THREE.Object3D(), bq = new THREE.Quaternion();
|
|
94
|
+
holder.add(proxy);
|
|
95
|
+
worldOf(s.bone, proxy.position, bq);
|
|
96
|
+
proxy.quaternion.copy(bq).multiply(q2.copy(s.q).invert());
|
|
97
|
+
const seg = p1.subVectors(s.end, s.p).multiplyScalar(k), len = seg.length(), rad = s.radius * k;
|
|
98
|
+
const mid = seg.clone().multiplyScalar(0.5), up = q1.setFromUnitVectors(new THREE.Vector3(0, 1, 0), seg.clone().normalize());
|
|
99
|
+
const desc = R.ColliderDesc.capsule(Math.max(len / 2 - rad, len * 0.02), rad).setTranslation(mid.x, mid.y, mid.z)
|
|
100
|
+
.setRotation({ x: up.x, y: up.y, z: up.z, w: up.w }).setCollisionGroups(GROUP);
|
|
101
|
+
const entry = r._add(proxy, desc, { mass: s.mass * massK, friction: 0.8, restitution: 0, damping: 0.1, angularDamping: 0.8 });
|
|
102
|
+
entry.ragdoll = true; entry.object = s.bone; // a ray hit returns the bone: the game needs to know what was hit
|
|
103
|
+
entry.body.enableCcd(true); // limbs are thin and fast when knocked away; without it they pass through thin ground
|
|
104
|
+
const part = { name: s.name, shape: s, entry, mass: s.mass * massK, seg: seg.clone(), rad, bone: s.bone, pos0: s.bone.position.clone(), q0: s.bone.quaternion.clone() };
|
|
105
|
+
list.push(parts[s.name] = part);
|
|
106
|
+
}
|
|
107
|
+
const self = this;
|
|
108
|
+
const rd = {
|
|
109
|
+
ch, root, mesh, list, parts: Object.fromEntries(list.map(p => [p.name, p.entry])), hold, joints: [], limits: o.limits ?? {}, anchor: null, anim: null, drawn: false, void: false, calm: 0,
|
|
110
|
+
get active() { return self.live.has(rd); },
|
|
111
|
+
get settled() { return rd.active && list.every(p => !p.entry.enabled || p.entry.body.isSleeping()); },
|
|
112
|
+
remove() { self._end(rd); },
|
|
113
|
+
/** @internal character.placeAt: root follows the body, so a placement moves the body */ shift(x, y, z) { self._shift(rd, x, y, z); },
|
|
114
|
+
};
|
|
115
|
+
// Joint anchors are computed from the current pose (not the bind pose): in-between bones that are not in the part table (Spine1, clavicle) may not be at their bind position at the start, and this way the error on the first step is zero
|
|
116
|
+
for (const p of list) {
|
|
117
|
+
if (!p.shape.parent) continue;
|
|
118
|
+
p.parent = parts[p.shape.parent];
|
|
119
|
+
const t0 = p.parent.entry.body.translation(), t1 = p.entry.body.translation();
|
|
120
|
+
p.anchor = p1.set(t1.x - t0.x, t1.y - t0.y, t1.z - t0.z).applyQuaternion(toQ(p.parent.entry.body.rotation()).invert()).clone();
|
|
121
|
+
p.range = this._range(p, rd.limits);
|
|
122
|
+
}
|
|
123
|
+
this._joints(rd);
|
|
124
|
+
// falling while running keeps the original velocity
|
|
125
|
+
if (ch) for (const p of list) p.entry.body.setLinvel({ x: ch.velocity.x, y: ch.vy, z: ch.velocity.y }, true);
|
|
126
|
+
return rd;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The three-axis range of this joint. If the starting pose is already past the limit, widen the range to the starting angle: otherwise the solver yanks it back on the first step and it looks like a twitch */
|
|
130
|
+
_range(p, limits) {
|
|
131
|
+
const given = limits[p.name] ?? limits[p.shape.kind], base = p.shape.limits;
|
|
132
|
+
const lim = { twist: given?.twist ?? base.twist, side: given?.side ?? base.side, bend: given?.bend ?? base.bend };
|
|
133
|
+
const F = p.shape.frame;
|
|
134
|
+
// The child's rotation relative to the parent, read in the joint frame: the imaginary x / y / z are the three values Rapier's limits use
|
|
135
|
+
toQ(p.parent.entry.body.rotation(), q1).invert().multiply(toQ(p.entry.body.rotation(), q2));
|
|
136
|
+
const f = q1.premultiply(q2.copy(F).invert()).multiply(F);
|
|
137
|
+
const sign = f.w < 0 ? -1 : 1, ang = c => 2 * Math.asin(THREE.MathUtils.clamp(sign * c, -1, 1));
|
|
138
|
+
return [[lim.twist, f.x], [lim.side, f.y], [lim.bend, f.z]].map(([[lo, hi], c]) => { const x = ang(c); return [Math.min(lo, x - 0.02), Math.max(hi, x + 0.02)]; });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Build the joints; runs again after a world rebuild. Rapier's JS layer only exposes setLimits for single-axis joints; the three-axis limits and damping of a spherical joint (actually type Generic) go through the rawSet below it (the ragdoll test fails first when the version is upgraded) */
|
|
142
|
+
_joints(rd) {
|
|
143
|
+
const { r } = this, R = r.rapier, w = r.world, zero = { x: 0, y: 0, z: 0 };
|
|
144
|
+
rd.joints = [];
|
|
145
|
+
for (const p of rd.list) {
|
|
146
|
+
if (!p.parent) continue;
|
|
147
|
+
const j = w.createImpulseJoint(R.JointData.spherical(p.anchor, zero), p.parent.entry.body, p.entry.body, true);
|
|
148
|
+
const F = p.shape.frame, f = { x: F.x, y: F.y, z: F.z, w: F.w };
|
|
149
|
+
j.setLocalFrame1(p.anchor, f); j.setLocalFrame2(zero, f);
|
|
150
|
+
[R.JointAxis.AngX, R.JointAxis.AngY, R.JointAxis.AngZ].forEach((axis, i) => {
|
|
151
|
+
j.rawSet.jointSetLimits(j.handle, axis, p.range[i][0], p.range[i][1]);
|
|
152
|
+
j.rawSet.jointConfigureMotorVelocity(j.handle, axis, 0, FRICTION);
|
|
153
|
+
});
|
|
154
|
+
rd.joints.push(j);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The impulse hits the part nearest to position (the root part when no position is given). That part only takes HIT_SPEED worth, the rest is shared over the whole body by mass:
|
|
160
|
+
* in a real body force travels along the skeleton, but the solver cannot pass that much in one step, and the whole hit on a 5 kg head would send it flying and tear the joints apart. Total momentum is unchanged.
|
|
161
|
+
*/
|
|
162
|
+
_push(rd, { impulse, position }) {
|
|
163
|
+
if (!impulse) return;
|
|
164
|
+
const i = vec3(impulse), at = position && vec3(position);
|
|
165
|
+
let hit = rd.list[0], dist = Infinity;
|
|
166
|
+
if (at) for (const p of rd.list) {
|
|
167
|
+
const c = p.entry.collider.translation(), d = at.distanceToSquared(p1.set(c.x, c.y, c.z));
|
|
168
|
+
if (d < dist) { dist = d; hit = p; }
|
|
169
|
+
}
|
|
170
|
+
const size = i.length(), own = size ? Math.min(1, hit.mass * HIT_SPEED / size) : 1, mass = rd.list.reduce((n, p) => n + p.mass, 0);
|
|
171
|
+
const v = { x: i.x * own, y: i.y * own, z: i.z * own };
|
|
172
|
+
if (at) hit.entry.body.applyImpulseAtPoint(v, { x: at.x, y: at.y, z: at.z }, true); else hit.entry.body.applyImpulse(v, true);
|
|
173
|
+
if (own < 1) for (const p of rd.list) {
|
|
174
|
+
const k = (1 - own) * p.mass / mass;
|
|
175
|
+
p.entry.body.applyImpulse({ x: i.x * k, y: i.y * k, z: i.z * k }, true);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Make the character's animation, movement, capsule and camera yield. Control was already taken in start */
|
|
180
|
+
_yield(rd) {
|
|
181
|
+
const { ch, root } = rd, e = this.e;
|
|
182
|
+
rd.anim = ch ? ch.anim : e.assets.animatorOf(root);
|
|
183
|
+
if (rd.anim) rd.anim._held = true;
|
|
184
|
+
if (ch) {
|
|
185
|
+
ch.limp = rd;
|
|
186
|
+
ch.velocity.set(0, 0); ch.vy = 0; ch.moveAmount = 0; ch.state = ch.stateMark = 'ragdoll';
|
|
187
|
+
// the player capsule is turned off by rigid.step according to limp; an NPC's capsule belongs to its mover
|
|
188
|
+
if (ch !== e.player && ch.mover.collider && ch.mover.world === this.r.world) ch.mover.collider.setEnabled(false);
|
|
189
|
+
}
|
|
190
|
+
const rig = e.cameraRig;
|
|
191
|
+
if (rig?.target === root) {
|
|
192
|
+
// follow the root part, not the feet: the camera looks at the body, not at the air a person's height above it
|
|
193
|
+
rd.anchor = new THREE.Object3D();
|
|
194
|
+
this._anchor(rd);
|
|
195
|
+
rig.follow(rd.anchor, { height: 0 });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
_anchor(rd) { const t = rd.list[0].entry.body.translation(); rd.anchor.position.set(t.x, t.y, t.z); }
|
|
200
|
+
|
|
201
|
+
/** Every fixed step, after the world has stepped (called by RigidBodies.step) */
|
|
202
|
+
sync() {
|
|
203
|
+
for (const rd of this.live) {
|
|
204
|
+
const { ch, root } = rd;
|
|
205
|
+
if (ch?.disposed || !root.parent) { this._end(rd, true); continue; } // the character or model was deleted: only clean up the physics
|
|
206
|
+
if (rd.settled) { if (rd.drawn) continue; rd.drawn = true; } else { rd.drawn = false; this._calm(rd); } // once asleep, stop writing: saves cost and a bone the game wrote stays
|
|
207
|
+
this._pose(rd);
|
|
208
|
+
ch?.syncRecord();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Once slow enough, put the whole body to sleep together: joints resting on their limits jitter slightly, Rapier's own sleep threshold is often never reached, and the body would be simulated forever. It only counts fixed steps, so it stays deterministic */
|
|
213
|
+
_calm(rd) {
|
|
214
|
+
for (const p of rd.list) {
|
|
215
|
+
const v = p.entry.body.linvel(), w = p.entry.body.angvel();
|
|
216
|
+
if (v.x * v.x + v.y * v.y + v.z * v.z > CALM_SPEED || w.x * w.x + w.y * w.y + w.z * w.z > CALM_SPIN) { rd.calm = 0; return; }
|
|
217
|
+
}
|
|
218
|
+
if (++rd.calm >= CALM_STEPS) for (const p of rd.list) p.entry.body.sleep();
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Write the physics result back to the bones. root follows the body (triggers, streaming and saves read it), so the bones are computed after root has moved */
|
|
222
|
+
_pose(rd) {
|
|
223
|
+
const { root, list } = rd, core = list[0].entry.body.translation();
|
|
224
|
+
let low = Infinity;
|
|
225
|
+
for (const p of list) { // lowest point of the body: the soles when standing, the ground when lying, no need to ask the terrain
|
|
226
|
+
const t = p.entry.body.translation(), q = toQ(p.entry.body.rotation());
|
|
227
|
+
low = Math.min(low, t.y - p.rad, t.y + p1.copy(p.seg).applyQuaternion(q).y - p.rad);
|
|
228
|
+
}
|
|
229
|
+
p1.set(core.x, low, core.z);
|
|
230
|
+
if (root.parent) root.parent.worldToLocal(p1);
|
|
231
|
+
root.position.copy(p1);
|
|
232
|
+
root.updateWorldMatrix(true, false);
|
|
233
|
+
for (const p of list) {
|
|
234
|
+
const b = p.entry.body, parent = p.bone.parent;
|
|
235
|
+
parent.updateWorldMatrix(true, false);
|
|
236
|
+
worldOf(parent, p1, q2);
|
|
237
|
+
p.bone.quaternion.copy(q2.invert().multiply(toQ(b.rotation()).multiply(p.shape.q)));
|
|
238
|
+
if (p === list[0]) {
|
|
239
|
+
const t = b.translation();
|
|
240
|
+
p.bone.position.copy(parent.worldToLocal(p1.set(t.x, t.y, t.z)));
|
|
241
|
+
}
|
|
242
|
+
p.bone.updateMatrixWorld();
|
|
243
|
+
}
|
|
244
|
+
if (rd.anchor) this._anchor(rd);
|
|
245
|
+
const under = core.y < this.e.ground.voidY();
|
|
246
|
+
if (under && !rd.void) this.e.events.emit('terrain:void', { who: list[0].entry, position: { x: core.x, y: core.y, z: core.z } });
|
|
247
|
+
rd.void = under;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Is this character lying down (rigid.step turns the player capsule off by this) */
|
|
251
|
+
holds(ch) { return !!ch.limp; }
|
|
252
|
+
|
|
253
|
+
/** Load: position belongs to the save, so the character is not put back where the body lies */
|
|
254
|
+
load() { for (const rd of [...this.live]) this._end(rd, false, false); }
|
|
255
|
+
|
|
256
|
+
/** A placement: every part moves by the same offset, so the joints see the pose they had, and at rest, so nothing the fall carried arrives with it. Woken parts settle again */
|
|
257
|
+
_shift(rd, x, y, z) {
|
|
258
|
+
for (const p of rd.list) {
|
|
259
|
+
const b = p.entry.body, t = b.translation();
|
|
260
|
+
this.r.setPosition(p.entry, { x: t.x + x, y: t.y + y, z: t.z + z });
|
|
261
|
+
b.setAngvel({ x: 0, y: 0, z: 0 }, true);
|
|
262
|
+
}
|
|
263
|
+
rd.calm = 0;
|
|
264
|
+
if (rd.anchor) this._anchor(rd);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** End: tear down the physics and give every slot back to its owner. gone: the character no longer exists, nothing to give back; place: put the character where the body lies */
|
|
268
|
+
_end(rd, gone = false, place = true) {
|
|
269
|
+
if (!this.live.delete(rd)) return;
|
|
270
|
+
const { ch, list, anim, anchor, hold } = rd;
|
|
271
|
+
for (const j of rd.joints) if (j.isValid()) this.r.world.removeImpulseJoint(j, true);
|
|
272
|
+
rd.joints = [];
|
|
273
|
+
for (const p of list) p.entry.remove();
|
|
274
|
+
hold?.remove(); // gone too: a slot is kept by id, so an NPC whose model was torn down while limp would come back paused for good
|
|
275
|
+
if (gone) return;
|
|
276
|
+
for (const p of list) { p.bone.position.copy(p.pos0); p.bone.quaternion.copy(p.q0); } // bones no animation clip writes also go back to how they were before falling
|
|
277
|
+
if (anim) anim._held = false;
|
|
278
|
+
if (ch) {
|
|
279
|
+
ch.limp = null;
|
|
280
|
+
if (ch !== this.e.player && ch.mover.collider && ch.mover.world === this.r.world) ch.mover.collider.setEnabled(true);
|
|
281
|
+
if (ch.state === 'ragdoll') ch.state = ch.stateMark = 'idle';
|
|
282
|
+
if (place) ch.placeAt(ch.root.position);
|
|
283
|
+
}
|
|
284
|
+
// if the game switched the camera away meanwhile, do not take it back
|
|
285
|
+
const rig = this.e.cameraRig; // read now: the rig that started following may have been swapped out (architecture 8.2)
|
|
286
|
+
if (rig?.target === anchor) rig.follow(rd.root);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** The solver is going (rigid left or was replaced): every limp body gets up while its parts can still be read, or the character stays held by a physics that is gone. A dispose of the whole engine, or of the character, has nobody left to give it to */
|
|
290
|
+
dispose() { this._sub.remove(); for (const rd of [...this.live]) this._end(rd, this.e.disposed || !!rd.ch?.disposed); }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** The SkinnedMesh with the most bones: clothes and accessories are often small meshes on the same skeleton */
|
|
294
|
+
function skinOf(root) {
|
|
295
|
+
let best = null;
|
|
296
|
+
root.traverse(o => { if (o.isSkinnedMesh && o.skeleton && (!best || o.skeleton.bones.length > best.skeleton.bones.length)) best = o; });
|
|
297
|
+
return best;
|
|
298
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// Ragdoll skeleton reading: a graph of parts over a skeleton, each measured for its real length and thickness. The default graph comes from recognising each tool's bone names
|
|
2
|
+
// (Mixamo, Blender, Unreal, Bip01, VRM, Quaternius...) as the 11 parts of a human body; a game's own graph (four legs, a tail) goes through the same measuring.
|
|
3
|
+
// Why this is apart from ragdoll.js: it only reads, never writes, and never touches Rapier, so it can be tested without physics.
|
|
4
|
+
import * as THREE from 'three';
|
|
5
|
+
import { vec3 } from '../../core/base/math.js';
|
|
6
|
+
import { codedError } from '../../core/base/errorHints.js';
|
|
7
|
+
|
|
8
|
+
const PARTS = ['hips', 'chest', 'head', 'upperArmL', 'lowerArmL', 'upperArmR', 'lowerArmR', 'upperLegL', 'lowerLegL', 'upperLegR', 'lowerLegR'];
|
|
9
|
+
// Compare after dropping the prefix words an export tool adds. Trailing digits are stripped first (mixamorig1, Bip01)
|
|
10
|
+
const NOISE = new Set(['mixamorig', 'def', 'org', 'bip', 'b', 'j', 'jnt', 'joint', 'bone', 'cc', 'base', 'armature', 'rig', 'characterarmature', 'bn', 'valvebiped', 'c']);
|
|
11
|
+
// Names are in priority order. 'leg' goes last and the lower leg picks first: some skeletons use UpLeg + Leg (Leg is the lower leg), others Leg + Shin (Leg is the thigh). 'arm' counts as the upper arm only (LeftArm + LeftForeArm)
|
|
12
|
+
const NAMES = {
|
|
13
|
+
upperArm: ['upperarm', 'uparm', 'humerus', 'arm'], lowerArm: ['forearm', 'lowerarm', 'loarm', 'elbow'],
|
|
14
|
+
upperLeg: ['thigh', 'upperleg', 'upleg', 'femur', 'leg'], lowerLeg: ['shin', 'calf', 'lowerleg', 'loleg', 'knee', 'tibia', 'leg'],
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const D = Math.PI / 180;
|
|
18
|
+
// Default range of motion (radians, relative to bind pose). bend is positive forward (backward for knees), side is sideways, twist is around the bone. This is physical plausibility, not looks
|
|
19
|
+
const LIMITS = {
|
|
20
|
+
chest: { bend: [-30 * D, 40 * D], side: [-25 * D, 25 * D], twist: [-30 * D, 30 * D] },
|
|
21
|
+
head: { bend: [-40 * D, 50 * D], side: [-35 * D, 35 * D], twist: [-60 * D, 60 * D] },
|
|
22
|
+
upperArm: { bend: [-60 * D, 120 * D], side: [-100 * D, 100 * D], twist: [-70 * D, 70 * D] },
|
|
23
|
+
lowerArm: { bend: [0, 145 * D], side: [-3 * D, 3 * D], twist: [-60 * D, 60 * D] },
|
|
24
|
+
upperLeg: { bend: [-25 * D, 110 * D], side: [-45 * D, 45 * D], twist: [-35 * D, 35 * D] },
|
|
25
|
+
lowerLeg: { bend: [0, 140 * D], side: [-3 * D, 3 * D], twist: [-5 * D, 5 * D] },
|
|
26
|
+
};
|
|
27
|
+
const SHARE = { hips: 0.16, chest: 0.3, head: 0.08, upperArm: 0.03, lowerArm: 0.025, upperLeg: 0.11, lowerLeg: 0.07 }; // how the total mass is split
|
|
28
|
+
const WHOLE = 70; // kg of a body whose graph or call names none
|
|
29
|
+
const OPEN = { bend: [-45 * D, 45 * D], side: [-45 * D, 45 * D], twist: [-30 * D, 30 * D] }; // a part of a game's graph that gives no limits: loose, but no joint folds through itself
|
|
30
|
+
|
|
31
|
+
/** Bone name -> { side: 'L' | 'R' | '', word }: LeftForeArm, upperarm_l, Bip01 L Thigh, DEF-forearm.L, UpperArmR (GLTFLoader eats the dot) all split into the same shape */
|
|
32
|
+
function parse(name) {
|
|
33
|
+
const words = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[^a-zA-Z0-9]+/).map(w => w.toLowerCase().replace(/\d+$/, '')).filter(w => w && !NOISE.has(w));
|
|
34
|
+
let side = '';
|
|
35
|
+
const rest = words.filter(w => {
|
|
36
|
+
if (!side && (w === 'l' || w === 'left')) { side = 'L'; return false; }
|
|
37
|
+
if (!side && (w === 'r' || w === 'right')) { side = 'R'; return false; }
|
|
38
|
+
return true;
|
|
39
|
+
});
|
|
40
|
+
return { side, word: rest.join('') };
|
|
41
|
+
}
|
|
42
|
+
const depth = b => { let n = 0; for (let o = b; o; o = o.parent) n++; return n; };
|
|
43
|
+
const under = (b, top) => { for (let o = b.parent; o; o = o.parent) if (o === top) return true; return false; };
|
|
44
|
+
/** The nearest common ancestor of two bones. The torso is found with it, not by name: Spine / Spine2 / chest / spine_03 vary too much between tools, while "where the legs fork, where the arms fork" is the same on every skeleton */
|
|
45
|
+
function meet(a, b, bones) {
|
|
46
|
+
for (let o = a; o; o = o.parent) if (bones.has(o) && (o === b || under(b, o))) return o;
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Auto-detect bones and fill the parts still empty in the map (bones the game gave claim their place first; other parts cannot reuse them); missing ones stay empty and readBones reports them together */
|
|
51
|
+
function detect(skeleton, map) {
|
|
52
|
+
const bones = [...skeleton.bones].map(b => ({ b, ...parse(b.name), d: depth(b) })).sort((x, y) => x.d - y.d);
|
|
53
|
+
const taken = new Set(Object.values(map));
|
|
54
|
+
map.head ??= bones.find(x => x.word === 'head' && !x.side)?.b;
|
|
55
|
+
for (const side of ['L', 'R']) {
|
|
56
|
+
for (const kind of ['upperArm', 'lowerArm', 'lowerLeg', 'upperLeg']) {
|
|
57
|
+
if (map[kind + side]) continue;
|
|
58
|
+
for (const word of NAMES[kind]) {
|
|
59
|
+
const hit = bones.find(x => x.side === side && x.word === word && !taken.has(x.b));
|
|
60
|
+
if (hit) { map[kind + side] = hit.b; taken.add(hit.b); break; }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Read the skeleton. given maps a part to a bone name or bone object from the game and wins over auto-detection; if any part cannot be read it throws, naming the missing parts and the bone names the skeleton really has.
|
|
68
|
+
* @returns {Record<string, THREE.Bone>}
|
|
69
|
+
*/
|
|
70
|
+
export function readBones(skeleton, given = {}) {
|
|
71
|
+
const set = new Set(skeleton.bones), map = {}, bad = [];
|
|
72
|
+
for (const k of Object.keys(given)) if (!PARTS.includes(k)) throw codedError('rigid-misuse', `rigid.ragdoll({ bones }): '${k}' is not a part. Parts: ${PARTS.join(', ')}`);
|
|
73
|
+
for (const p of PARTS) {
|
|
74
|
+
const g = given[p];
|
|
75
|
+
if (g == null) continue;
|
|
76
|
+
const b = g.isObject3D ? g : skeleton.bones.find(x => x.name === g);
|
|
77
|
+
if (b && set.has(b)) map[p] = b; else bad.push(`${p}: '${g.name ?? g}' is not in the skeleton`);
|
|
78
|
+
}
|
|
79
|
+
detect(skeleton, map);
|
|
80
|
+
// The torso can only be worked out after the limbs are found; use the game's if it gave one
|
|
81
|
+
if (!map.hips && map.upperLegL && map.upperLegR) map.hips = meet(map.upperLegL, map.upperLegR, set) ?? undefined;
|
|
82
|
+
if (!map.chest && map.upperArmL && map.upperArmR) map.chest = meet(map.upperArmL, map.upperArmR, set) ?? undefined;
|
|
83
|
+
const missing = PARTS.filter(p => !map[p]);
|
|
84
|
+
if (bad.length || missing.length) {
|
|
85
|
+
const names = skeleton.bones.slice(0, 40).map(b => b.name).join(', ');
|
|
86
|
+
throw codedError('rigid-misuse', `rigid.ragdoll(): cannot read this skeleton. Missing: ${[...bad, ...missing.filter(p => !bad.some(s => s.startsWith(p + ':')))].join(', ')}. `
|
|
87
|
+
+ `Bones in it: ${names}${skeleton.bones.length > 40 ? ', ...' : ''}. Fix: name them, e.g. engine.rigid.ragdoll(character, { bones: { ${missing[0] ?? 'hips'}: '<bone name>' } }); a body that is not a human: the rule 'ragdoll.graph', recipe 11`);
|
|
88
|
+
}
|
|
89
|
+
if (map.hips === map.chest) throw codedError('rigid-misuse', `rigid.ragdoll(): hips and chest are the same bone ('${map.hips.name}'), so the torso has one part. Fix: pass bones: { hips: '<pelvis bone>', chest: '<upper spine bone>' }`);
|
|
90
|
+
return map;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const v1 = new THREE.Vector3(), v2 = new THREE.Vector3(), v3 = new THREE.Vector3(), sc = new THREE.Vector3(), mt = new THREE.Matrix4();
|
|
94
|
+
/** A bone's bind pose (the inverse of boneInverses): whatever pose the animation is in does not affect it, so limits and joint frames get a zero point that does not move with the pose */
|
|
95
|
+
function restOf(skeleton, bone) {
|
|
96
|
+
const i = skeleton.bones.indexOf(bone), p = new THREE.Vector3(), q = new THREE.Quaternion();
|
|
97
|
+
mt.copy(skeleton.boneInverses[i]).invert().decompose(p, q, sc);
|
|
98
|
+
return { p, q };
|
|
99
|
+
}
|
|
100
|
+
/** Distance from a point to a segment */
|
|
101
|
+
function toSegment(p, a, b) {
|
|
102
|
+
v2.subVectors(b, a); const l2 = v2.lengthSq();
|
|
103
|
+
const t = l2 > 0 ? THREE.MathUtils.clamp(v3.subVectors(p, a).dot(v2) / l2, 0, 1) : 0;
|
|
104
|
+
return v3.copy(a).addScaledVector(v2, t).distanceTo(p);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The default graph: the 11 parts of a human body, read from the skeleton. Everything that knows a body has legs lives here, so a wolf or a snake is just another graph.
|
|
109
|
+
* Beyond the data any graph has: kind names the limits a game can widen for both sides at once, end is the part a bone points at, forward the way this joint bends.
|
|
110
|
+
* @returns {Record<string, any>}
|
|
111
|
+
*/
|
|
112
|
+
export function humanoidGraph(mesh, given) {
|
|
113
|
+
const map = readBones(mesh.skeleton, given), sk = mesh.skeleton, rest = {};
|
|
114
|
+
for (const n of PARTS) rest[n] = restOf(sk, map[n]);
|
|
115
|
+
const right = v1.subVectors(rest.upperLegR.p, rest.upperLegL.p).clone().normalize();
|
|
116
|
+
const up = new THREE.Vector3().subVectors(rest.chest.p, rest.hips.p).normalize();
|
|
117
|
+
const forward = new THREE.Vector3().crossVectors(up, right).normalize();
|
|
118
|
+
return Object.fromEntries(PARTS.map(name => {
|
|
119
|
+
const kind = name.replace(/[LR]$/, ''), side = name.slice(-1);
|
|
120
|
+
let parent = null;
|
|
121
|
+
for (let o = map[name].parent; o && !parent; o = o.parent) parent = PARTS.find(n => map[n] === o) ?? null;
|
|
122
|
+
if (name !== 'hips' && !parent) throw codedError('rigid-misuse', `rigid.ragdoll(): bone '${map[name].name}' (${name}) is not under hips ('${map.hips.name}'), so nothing holds it. Fix: pass bones: { hips: '<the bone every body part hangs from>' }`);
|
|
123
|
+
const end = { hips: 'chest', chest: 'head', head: 'top', upperArm: 'lowerArm' + side, upperLeg: 'lowerLeg' + side }[kind];
|
|
124
|
+
// Knees bend backward, other joints forward
|
|
125
|
+
return [name, { bone: map[name], parent, kind, limits: LIMITS[kind], mass: WHOLE * SHARE[kind], end, forward: kind === 'lowerLeg' ? forward.clone().negate() : forward, up }];
|
|
126
|
+
}));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A graph's bone: a name or the bone itself; one outside the skeleton is refused by name */
|
|
130
|
+
function boneOf(sk, name, b) {
|
|
131
|
+
const bone = b?.isObject3D ? b : sk.bones.find(x => x.name === b);
|
|
132
|
+
if (bone && sk.bones.includes(bone)) return bone;
|
|
133
|
+
throw codedError('rigid-misuse', `ragdoll.graph: part '${name}' names bone '${b?.name ?? b}', which is not in the skeleton. Bones in it: ${sk.bones.slice(0, 40).map(x => x.name).join(', ')}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Static shape of each part of a graph { part: { bone, parent, limits, mass, end, forward, kind, up } } (all in bind space, in bind-time length units):
|
|
138
|
+
* { name, kind, bone, parent, p, q, end, radius, frame, limits, mass }, parents before children, so the one part without a parent comes first.
|
|
139
|
+
* end: the tip of this bone, from the real bone length, not guessed by proportion (a misaligned collider is where mesh deformation comes from). radius: distance from skinned vertices to this bone, so thin and heavy characters both fit.
|
|
140
|
+
* frame: joint frame, x along the bone (twist), y toward positive bend, z the hinge axis.
|
|
141
|
+
*/
|
|
142
|
+
export function shapeParts(mesh, graph) {
|
|
143
|
+
const bad = why => codedError('rigid-misuse', `ragdoll.graph: ${why}. A graph is { part: { bone, parent, limits?, mass?, end?, forward? } }, one part without a parent`);
|
|
144
|
+
if (!graph || typeof graph !== 'object') throw bad(`got ${String(graph)}`);
|
|
145
|
+
const sk = mesh.skeleton, names = Object.keys(graph), roots = names.filter(n => !graph[n].parent);
|
|
146
|
+
if (names.length < 2 || roots.length !== 1) throw bad(`${names.length} part(s) with ${roots.length} root(s) (${roots.join(', ')})`);
|
|
147
|
+
const parts = names.map(name => {
|
|
148
|
+
const g = graph[name], bone = boneOf(sk, name, g.bone), r = restOf(sk, bone);
|
|
149
|
+
if (g.parent && !graph[g.parent]) throw bad(`part '${name}' has parent '${g.parent}', which is not a part`);
|
|
150
|
+
if (g.parent && !under(bone, boneOf(sk, g.parent, graph[g.parent].bone))) throw bad(`part '${name}': bone '${bone.name}' is not under the bone of its parent '${g.parent}'`);
|
|
151
|
+
return { name, kind: g.kind, bone, parent: g.parent ?? null, p: r.p, q: r.q, end: null, radius: 0, frame: null, limits: { ...OPEN, ...g.limits }, mass: g.mass ?? WHOLE / names.length, d: depth(bone) };
|
|
152
|
+
}).sort((a, b) => a.d - b.d);
|
|
153
|
+
const byName = Object.fromEntries(parts.map(s => [s.name, s]));
|
|
154
|
+
for (const s of parts) if (graph[s.name].end !== 'top') s.end = tipOf(sk, s, parts, byName, graph[s.name].end);
|
|
155
|
+
measure(mesh, parts, graph, byName);
|
|
156
|
+
for (const s of parts) {
|
|
157
|
+
const g = graph[s.name], F = g.forward ? vec3(g.forward) : new THREE.Vector3(0, 0, 1), up = g.up ? vec3(g.up) : new THREE.Vector3(0, 1, 0);
|
|
158
|
+
const x = new THREE.Vector3().subVectors(s.end, s.p).normalize();
|
|
159
|
+
const y = F.clone().addScaledVector(x, -x.dot(F)); // the y axis is the direction the bone tip moves when bend is positive
|
|
160
|
+
if (y.lengthSq() < 1e-4) y.copy(up).addScaledVector(x, -x.dot(up)); // The bone points straight along forward (a rare bind pose)
|
|
161
|
+
y.normalize();
|
|
162
|
+
const z = new THREE.Vector3().crossVectors(x, y);
|
|
163
|
+
s.frame = new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(x, y, z));
|
|
164
|
+
}
|
|
165
|
+
return parts;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Where a part ends: the part it names; else the middle of its child parts (the one child when they meet at its own joint); else its first child bone, a hand or a foot; else on along the segment before it */
|
|
169
|
+
function tipOf(sk, s, parts, byName, end) {
|
|
170
|
+
if (end) { if (!byName[end]) throw codedError('rigid-misuse', `ragdoll.graph: part '${s.name}' has end '${end}', which is not a part`); return byName[end].p; }
|
|
171
|
+
const kids = parts.filter(c => c.parent === s.name);
|
|
172
|
+
if (kids.length) {
|
|
173
|
+
const mid = kids.reduce((m, c) => m.add(c.p), new THREE.Vector3()).divideScalar(kids.length);
|
|
174
|
+
return mid.distanceTo(s.p) > 1e-5 ? mid : kids[0].p;
|
|
175
|
+
}
|
|
176
|
+
const c = s.bone.children.find(o => o.isBone && sk.bones.includes(o));
|
|
177
|
+
return c ? restOf(sk, c).p : new THREE.Vector3().subVectors(s.p, byName[s.parent].p).add(s.p);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Measure thickness: assign each vertex to the part of its heaviest-weighted bone and take the 60th percentile of the distance to the segment (outliers such as fingers and capes do not count). A part with end: 'top' (a head) has no next bone, so its top is measured from vertices too */
|
|
181
|
+
function measure(mesh, parts, graph, byName) {
|
|
182
|
+
const g = mesh.geometry, pos = g.attributes.position, si = g.attributes.skinIndex, sw = g.attributes.skinWeight, sk = mesh.skeleton;
|
|
183
|
+
const owner = sk.bones.map(b => { for (let o = b; o; o = o.parent) { const s = parts.find(x => x.bone === o); if (s) return s; } return null; });
|
|
184
|
+
const lists = new Map(parts.map(s => [s, []]));
|
|
185
|
+
const pts = new Map(parts.map(s => [s, []]));
|
|
186
|
+
if (pos && si && sw) {
|
|
187
|
+
for (let i = 0; i < pos.count; i++) {
|
|
188
|
+
let best = 0, w = -1;
|
|
189
|
+
for (let k = 0; k < 4; k++) { const wk = sw.getComponent(i, k); if (wk > w) { w = wk; best = si.getComponent(i, k); } }
|
|
190
|
+
const s = owner[best];
|
|
191
|
+
if (s) pts.get(s).push(new THREE.Vector3().fromBufferAttribute(pos, i).applyMatrix4(mesh.bindMatrix));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
// The top: the vertex farthest up; with no vertices, estimate half the distance to the parent
|
|
195
|
+
for (const s of parts) {
|
|
196
|
+
if (graph[s.name].end !== 'top') continue;
|
|
197
|
+
const up = graph[s.name].up ? vec3(graph[s.name].up) : new THREE.Vector3(0, 1, 0);
|
|
198
|
+
let top = 0;
|
|
199
|
+
for (const v of pts.get(s)) top = Math.max(top, v1.subVectors(v, s.p).dot(up));
|
|
200
|
+
s.end = s.p.clone().addScaledVector(up, top > 0 ? top : byName[s.parent].p.distanceTo(s.p) * 0.5);
|
|
201
|
+
}
|
|
202
|
+
for (const s of parts) {
|
|
203
|
+
const list = lists.get(s), len = s.p.distanceTo(s.end);
|
|
204
|
+
for (const v of pts.get(s)) list.push(toSegment(v, s.p, s.end));
|
|
205
|
+
list.sort((a, b) => a - b);
|
|
206
|
+
const r = list.length >= 8 ? list[Math.floor(list.length * 0.6)] : len * 0.25;
|
|
207
|
+
s.radius = THREE.MathUtils.clamp(r, len * 0.08, len * 0.6);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Rapier 0.21 keeps its query structures in the broad phase, and only a step rebuilds them: World has no updateSceneQueries and no query pipeline, and
|
|
2
|
+
// propagateModifiedBodyPositionsToColliders moves colliders without touching the broad phase. So a frozen engine refreshes with a step of no time, here and nowhere else.
|
|
3
|
+
// Twice: the first leaves a moved body's collider in the old place, the second catches it up. Tools test `rapier refresh` holds each of these, per Rapier version.
|
|
4
|
+
|
|
5
|
+
/** @internal Rebuild what queries read and nothing else (velocities, positions, sleep and contacts stay); the step length comes back even if Rapier throws */
|
|
6
|
+
export function refreshQueries(world) {
|
|
7
|
+
const dt = world.timestep;
|
|
8
|
+
world.timestep = 0;
|
|
9
|
+
try { world.step(); world.step(); } finally { world.timestep = dt; }
|
|
10
|
+
}
|