threedog 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/core/Animator.js +268 -0
- package/core/Assets.js +256 -0
- package/core/Audio.js +267 -0
- package/core/Baked.js +72 -0
- package/core/Batching.js +247 -0
- package/core/Budget.js +221 -0
- package/core/Clock.js +94 -0
- package/core/Commits.js +77 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +145 -0
- package/core/Engine.js +184 -0
- package/core/Events.js +153 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +77 -0
- package/core/InspectScene.js +191 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +256 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +254 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +94 -0
- package/core/Vars.js +35 -0
- package/core/Views.js +49 -0
- package/core/actor.js +23 -0
- package/core/assetEntry.js +89 -0
- package/core/assetLoad.js +190 -0
- package/core/assetManifest.js +35 -0
- package/core/assetReport.js +83 -0
- package/core/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/dayTime.js +15 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +143 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +205 -0
- package/core/errorHints.js +208 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -0
- package/core/holds.js +106 -0
- package/core/inputContext.js +69 -0
- package/core/inputDefaults.js +22 -0
- package/core/inputPad.js +35 -0
- package/core/inputPointer.js +48 -0
- package/core/inputTouch.js +48 -0
- package/core/lifecycle.js +69 -0
- package/core/lightWatch.js +56 -0
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +200 -0
- package/core/math.js +33 -0
- package/core/modules.js +196 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +97 -0
- package/core/opsFail.js +20 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/opsRun.js +77 -0
- package/core/page.js +78 -0
- package/core/params.js +132 -0
- package/core/pureWorker.js +5 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +128 -0
- package/core/saveFiles.js +139 -0
- package/core/saveIds.js +53 -0
- package/core/saveVersions.js +97 -0
- package/core/scatter.js +92 -0
- package/core/sceneMethods.js +100 -0
- package/core/screenToGround.js +39 -0
- package/core/services.js +73 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +135 -0
- package/core/streamCells.js +24 -0
- package/core/streamSources.js +73 -0
- package/core/styleParts.js +96 -0
- package/core/targeting.js +64 -0
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +168 -0
- package/core/things.js +212 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/util.js +11 -0
- package/core/validate.js +204 -0
- package/docs/AI.md +123 -0
- package/docs/API.md +83 -0
- package/docs/CODEMAP.md +347 -0
- package/docs/COMMANDS.md +108 -0
- package/docs/CONVENTIONS.md +145 -0
- package/docs/PERF.md +217 -0
- package/docs/THREE.md +86 -0
- package/docs/api/ambience.md +15 -0
- package/docs/api/assets.md +62 -0
- package/docs/api/audio.md +53 -0
- package/docs/api/budget.md +40 -0
- package/docs/api/cameraRig.md +120 -0
- package/docs/api/characters.md +144 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +39 -0
- package/docs/api/content.md +64 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +199 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +95 -0
- package/docs/api/flow.md +27 -0
- package/docs/api/grids.md +11 -0
- package/docs/api/ground.md +16 -0
- package/docs/api/hlod.md +34 -0
- package/docs/api/hud.md +31 -0
- package/docs/api/i18n.md +10 -0
- package/docs/api/input.md +24 -0
- package/docs/api/interactions.md +31 -0
- package/docs/api/inventory.md +66 -0
- package/docs/api/jobs.md +10 -0
- package/docs/api/level.md +41 -0
- package/docs/api/lightPool.md +56 -0
- package/docs/api/music.md +34 -0
- package/docs/api/nav.md +26 -0
- package/docs/api/net.md +14 -0
- package/docs/api/openWorld.md +24 -0
- package/docs/api/particles.md +41 -0
- package/docs/api/photo.md +15 -0
- package/docs/api/post.md +10 -0
- package/docs/api/quests.md +36 -0
- package/docs/api/rays.md +26 -0
- package/docs/api/rigid.md +84 -0
- package/docs/api/saves.md +32 -0
- package/docs/api/settings.md +36 -0
- package/docs/api/sky.md +58 -0
- package/docs/api/stream.md +31 -0
- package/docs/api/style.md +134 -0
- package/docs/api/terrain.md +34 -0
- package/docs/api/timeline.md +39 -0
- package/docs/api/tools.md +57 -0
- package/docs/api/triggers.md +56 -0
- package/docs/api/vars.md +9 -0
- package/docs/api/vegetation.md +52 -0
- package/docs/api/water.md +48 -0
- package/docs/api/weather.md +29 -0
- package/docs/api/world.md +30 -0
- package/docs/recipes/01-new-game.md +148 -0
- package/docs/recipes/02-npc.md +167 -0
- package/docs/recipes/03-items-pickups.md +158 -0
- package/docs/recipes/04-quests.md +83 -0
- package/docs/recipes/05-props-bake.md +159 -0
- package/docs/recipes/06-clock-events.md +117 -0
- package/docs/recipes/07-flow-scenes-pause.md +132 -0
- package/docs/recipes/08-weather-sky.md +74 -0
- package/docs/recipes/09-style-pack.md +234 -0
- package/docs/recipes/10-blender-level.md +67 -0
- package/docs/recipes/11-vehicles.md +55 -0
- package/docs/recipes/12-navmesh.md +79 -0
- package/docs/recipes/13-animation.md +149 -0
- package/docs/recipes/14-custom-module.md +91 -0
- package/docs/recipes/15-perf.md +78 -0
- package/docs/recipes/16-dev-bridge.md +180 -0
- package/docs/recipes/18-world.md +185 -0
- package/docs/recipes/19-shooting-picking.md +76 -0
- package/docs/recipes/20-content-actions-save.md +176 -0
- package/docs/recipes/21-camera.md +153 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +175 -0
- package/docs/recipes/26-ui-parts.md +138 -0
- package/docs/recipes/27-net.md +96 -0
- package/docs/recipes/28-terrain.md +80 -0
- package/docs/recipes/29-grid.md +87 -0
- package/docs/recipes/30-templates.md +131 -0
- package/docs/recipes/31-audio.md +126 -0
- package/docs/recipes/32-action-game.md +33 -0
- package/docs/recipes/33-stream-sources.md +37 -0
- package/docs/recipes/34-environment-lighting.md +36 -0
- package/docs/recipes/35-style-from-reference.md +89 -0
- package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
- package/docs/recipes/37-terrain-look-hooks.md +97 -0
- package/docs/recipes/38-environment-look-hooks.md +83 -0
- package/docs/recipes/40-scene.md +108 -0
- package/docs/recipes/41-thing-registry.md +93 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
- package/docs/recipes/44-water-weather-look-hooks.md +135 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +114 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/DESIGN.md +3 -0
- package/examples/action/GAMEMAP.md +127 -0
- package/examples/action/content/actions.js +8 -0
- package/examples/action/content/audio.js +9 -0
- package/examples/action/content/index.js +10 -0
- package/examples/action/content/items.js +4 -0
- package/examples/action/content/places.js +4 -0
- package/examples/action/content/props.js +11 -0
- package/examples/action/content/templates.js +10 -0
- package/examples/action/content/views.js +6 -0
- package/examples/action/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +107 -0
- package/examples/sheepisland/content/index.js +6 -0
- package/examples/sheepisland/content/props.js +19 -0
- package/examples/sheepisland/content/templates.js +5 -0
- package/examples/sheepisland/content/vegetation.js +8 -0
- package/examples/sheepisland/main.js +71 -0
- package/examples/sheepisland/params.js +25 -0
- package/examples/sheepisland/style/index.js +79 -0
- package/examples/sheepisland/style/models.js +59 -0
- package/examples/sheepisland/views.js +9 -0
- package/examples/styletest/GAMEMAP.md +135 -0
- package/examples/styletest/content/index.js +9 -0
- package/examples/styletest/content/items.js +8 -0
- package/examples/styletest/content/npcs.js +8 -0
- package/examples/styletest/content/places.js +5 -0
- package/examples/styletest/content/props.js +16 -0
- package/examples/styletest/content/templates.js +9 -0
- package/examples/styletest/content/vegetation.js +31 -0
- package/examples/styletest/look.js +11 -0
- package/examples/styletest/main.js +95 -0
- package/examples/styletest/models.js +87 -0
- package/examples/styletest/overrides.js +33 -0
- package/examples/styletest/panel.js +135 -0
- package/examples/styletest/params.js +32 -0
- package/examples/styletest/views.js +31 -0
- package/examples/world/DESIGN.md +5 -0
- package/examples/world/GAMEMAP.md +171 -0
- package/examples/world/content/actions.js +8 -0
- package/examples/world/content/audio.js +25 -0
- package/examples/world/content/bodies.js +12 -0
- package/examples/world/content/containers.js +4 -0
- package/examples/world/content/dialogues.js +33 -0
- package/examples/world/content/index.js +17 -0
- package/examples/world/content/items.js +10 -0
- package/examples/world/content/npcs.js +14 -0
- package/examples/world/content/pickups.js +11 -0
- package/examples/world/content/places.js +6 -0
- package/examples/world/content/props.js +12 -0
- package/examples/world/content/quests.js +15 -0
- package/examples/world/content/rules.js +23 -0
- package/examples/world/content/templates.js +5 -0
- package/examples/world/content/vegetation.js +32 -0
- package/examples/world/main.js +168 -0
- package/examples/world/models.js +28 -0
- package/index.d.ts +306 -0
- package/index.js +122 -0
- package/llms.txt +61 -0
- package/modules/ambience/Ambience.js +186 -0
- package/modules/camera/FirstPersonCamera.js +131 -0
- package/modules/camera/FixedCamera.js +162 -0
- package/modules/camera/FollowCamera.js +91 -0
- package/modules/camera/RtsCamera.js +132 -0
- package/modules/camera/common.js +182 -0
- package/modules/camera/index.js +11 -0
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +235 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +66 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +215 -0
- package/modules/characters/moveHelpers.js +29 -0
- package/modules/characters/movers/common.js +62 -0
- package/modules/characters/movers/rapier.js +74 -0
- package/modules/characters/movers/simple.js +43 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +150 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +113 -0
- package/modules/characters/pathJob.js +62 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +58 -0
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +274 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/explain.js +13 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +154 -0
- package/modules/content/loader.js +190 -0
- package/modules/content/models.js +69 -0
- package/modules/content/packs.js +69 -0
- package/modules/content/props.js +89 -0
- package/modules/content/rules.js +134 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +174 -0
- package/modules/entities/Entities.js +243 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +101 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +219 -0
- package/modules/gameplay/Interactions.js +253 -0
- package/modules/gameplay/Inventory.js +224 -0
- package/modules/gameplay/Quests.js +205 -0
- package/modules/gameplay/boxOps.js +60 -0
- package/modules/gameplay/dialogueBox.js +48 -0
- package/modules/gameplay/interactionPrompt.js +28 -0
- package/modules/gameplay/inventoryOps.js +137 -0
- package/modules/gameplay/pickups.js +115 -0
- package/modules/gameplay/questLog.js +54 -0
- package/modules/gameplay/questSave.js +71 -0
- package/modules/grid/Grid.js +184 -0
- package/modules/grid/Layer.js +142 -0
- package/modules/grid/index.js +236 -0
- package/modules/grid/ops.js +73 -0
- package/modules/grid/preview.js +85 -0
- package/modules/grid/tiles.js +79 -0
- package/modules/hlod/index.js +167 -0
- package/modules/hud/index.js +167 -0
- package/modules/hud/parts.js +80 -0
- package/modules/level/geometry.js +46 -0
- package/modules/level/heightfield.js +160 -0
- package/modules/level/index.js +233 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +227 -0
- package/modules/music/Music.js +294 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +156 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +137 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +77 -0
- package/modules/net/sync.js +114 -0
- package/modules/net/transports.js +118 -0
- package/modules/particles/Particles.js +179 -0
- package/modules/particles/effect.js +112 -0
- package/modules/particles/shaders.js +28 -0
- package/modules/photo/Photo.js +146 -0
- package/modules/rigid/RigidBodies.js +265 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +297 -0
- package/modules/settings/apply.js +21 -0
- package/modules/settings/index.js +3 -0
- package/modules/settings/sections.js +156 -0
- package/modules/settings/strings.js +53 -0
- package/modules/settings/view.js +65 -0
- package/modules/sky/Sky.js +259 -0
- package/modules/sky/calendar.js +80 -0
- package/modules/sky/cascades.js +125 -0
- package/modules/sky/clouds.js +79 -0
- package/modules/sky/domeLayers.js +33 -0
- package/modules/sky/environment.js +141 -0
- package/modules/sky/fog.js +139 -0
- package/modules/sky/frame.js +77 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +51 -0
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +74 -0
- package/modules/sky/skyModule.js +60 -0
- package/modules/terrain/ChunkManager.js +260 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +118 -0
- package/modules/terrain/lookGround.js +61 -0
- package/modules/terrain/mountTerrain.js +32 -0
- package/modules/terrain/terrainColorMap.js +41 -0
- package/modules/terrain/terrainDefaults.js +39 -0
- package/modules/terrain/terrainEdit.js +139 -0
- package/modules/terrain/terrainGen.js +155 -0
- package/modules/terrain/terrainIsland.js +131 -0
- package/modules/terrain/terrainMesh.js +92 -0
- package/modules/terrain/terrainShape.js +108 -0
- package/modules/terrain/terrainShapeMain.js +41 -0
- package/modules/terrain/terrainTexture.js +44 -0
- package/modules/timeline/Timeline.js +253 -0
- package/modules/timeline/Tween.js +114 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +90 -0
- package/modules/triggers/index.js +268 -0
- package/modules/vegetation/Vegetation.js +256 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +43 -0
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +160 -0
- package/modules/water/look.js +80 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +242 -0
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/weather/strings.js +15 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +71 -0
- package/modules/world/persist.js +107 -0
- package/modules/world/pos.js +20 -0
- package/modules/world/records.js +89 -0
- package/modules/world/sim.js +175 -0
- package/modules/world/simFar.js +82 -0
- package/modules/world/state.js +115 -0
- package/modules/world/thingSource.js +44 -0
- package/modules/world/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +240 -0
- package/render/detail.js +105 -0
- package/render/effects.js +144 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +84 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +18 -0
- package/render/lookSurface.js +161 -0
- package/render/materials.js +220 -0
- package/render/patches.js +252 -0
- package/render/postLook.js +86 -0
- package/render/surface.js +69 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1965 -0
- package/types/gameplay.d.ts +1822 -0
- package/types/generated/core/Audio.d.ts +200 -0
- package/types/generated/core/Batching.d.ts +47 -0
- package/types/generated/core/Budget.d.ts +90 -0
- package/types/generated/core/Commits.d.ts +31 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +89 -0
- package/types/generated/core/I18n.d.ts +30 -0
- package/types/generated/core/Input.d.ts +118 -0
- package/types/generated/core/Jobs.d.ts +41 -0
- package/types/generated/core/Ops.d.ts +203 -0
- package/types/generated/core/Random.d.ts +49 -0
- package/types/generated/core/Rays.d.ts +49 -0
- package/types/generated/core/Saves.d.ts +162 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/core/audioVoice.d.ts +47 -0
- package/types/generated/core/page.d.ts +18 -0
- package/types/generated/core/session.d.ts +48 -0
- package/types/generated/modules/ambience/Ambience.d.ts +48 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
- package/types/generated/modules/flow/index.d.ts +10 -0
- package/types/generated/modules/grid/Grid.d.ts +151 -0
- package/types/generated/modules/grid/Layer.d.ts +65 -0
- package/types/generated/modules/grid/index.d.ts +86 -0
- package/types/generated/modules/hlod/index.d.ts +11 -0
- package/types/generated/modules/hud/index.d.ts +10 -0
- package/types/generated/modules/lights/index.d.ts +13 -0
- package/types/generated/modules/music/Music.d.ts +111 -0
- package/types/generated/modules/net/Net.d.ts +34 -0
- package/types/generated/modules/net/index.d.ts +53 -0
- package/types/generated/modules/net/transports.d.ts +58 -0
- package/types/generated/modules/particles/Particles.d.ts +69 -0
- package/types/generated/modules/sky/Sky.d.ts +145 -0
- package/types/generated/modules/sky/skyModule.d.ts +10 -0
- package/types/generated/modules/timeline/Timeline.d.ts +51 -0
- package/types/generated/modules/water/Water.d.ts +29 -0
- package/types/generated/modules/weather/Weather.d.ts +62 -0
- package/types/generated/modules/world/World.d.ts +242 -0
- package/types/generated/modules/world/index.d.ts +15 -0
- package/types/generated/render/PostFX.d.ts +125 -0
- package/types/generated/render/materials.d.ts +100 -0
- package/types/generated/render/patches.d.ts +41 -0
- package/types/generated/ui/Focus.d.ts +11 -0
- package/types/generated/ui/LoadingScreen.d.ts +2 -0
- package/types/generated/ui/UI.d.ts +57 -0
- package/types/nav.d.ts +52 -0
- package/types/physics.d.ts +592 -0
- package/types/style.d.ts +638 -0
- package/types/worker.d.ts +11 -0
- package/types/world.d.ts +772 -0
- package/ui/Focus.js +51 -0
- package/ui/LoadingScreen.js +42 -0
- package/ui/Parts.js +199 -0
- package/ui/UI.js +167 -0
- package/ui/defaults.js +85 -0
- package/ui/theme.js +124 -0
- package/ui/touchPart.js +49 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Host side of net(): the host owns the state. Peers only send requests; the host decides who they are, what they may do and how often.
|
|
2
|
+
// Order of checks for a peer request { name, args, seq } (why each one lives here and not in every op's can):
|
|
3
|
+
// rate limit -> op exists -> op says net: 'peer' (default deny) -> args match the op's shape (always, not only in dev: peers are untrusted)
|
|
4
|
+
// -> owner (op.owner(args) names a world record whose owner must be this peer's actor) -> ops.run with source 'net' and the actor
|
|
5
|
+
// taken from the connection, never from the message.
|
|
6
|
+
// Replies (op results) go out after the next state diff, so a client sees the new state before it hears "done".
|
|
7
|
+
import { checkArgs } from '../../core/opsCheck.js';
|
|
8
|
+
import { partKeys, diffParts, snapshotParts } from './sync.js';
|
|
9
|
+
|
|
10
|
+
const STEP = 1 / 60;
|
|
11
|
+
const isNum = v => typeof v === 'number' && Number.isFinite(v);
|
|
12
|
+
const plainScalar = v => v === null || typeof v === 'string' || typeof v === 'boolean' || isNum(v);
|
|
13
|
+
|
|
14
|
+
/** @internal */
|
|
15
|
+
export class NetHost {
|
|
16
|
+
constructor(e, t, o) {
|
|
17
|
+
this.e = e; this.t = t; this.o = o;
|
|
18
|
+
/** peer id -> { id, actor, tokens, results, posTick } */ this.peers = new Map();
|
|
19
|
+
this.n = 0; // diff counter: a client that sees a gap asks for a snapshot
|
|
20
|
+
this.base = new Map(); // shared baseline (sync.js)
|
|
21
|
+
this.keys = null;
|
|
22
|
+
this.steps = 0; this.lastSent = 0;
|
|
23
|
+
this.stats = { in: 0, out: 0, rejected: 0, diffs: 0, snapshots: 0 };
|
|
24
|
+
this.subs = [t.on('join', id => this.join(id)), t.on('leave', id => this.leave(id)), t.on('message', (m, from) => this.receive(m, from))];
|
|
25
|
+
}
|
|
26
|
+
send(msg, peer) { this.stats.out++; this.t.send(msg, peer.id); }
|
|
27
|
+
|
|
28
|
+
join(id) {
|
|
29
|
+
const e = this.e, o = this.o;
|
|
30
|
+
const peer = { id, actor: o.actorFor(id), tokens: o.burst, results: [], posTick: e.tick };
|
|
31
|
+
this.peers.set(id, peer);
|
|
32
|
+
e.ops.allow(() => o.join(e, peer)); // setting up the peer's avatar / bag is host bookkeeping, not a gameplay action
|
|
33
|
+
e.events.emit('net:join', { peer: id, actor: peer.actor });
|
|
34
|
+
this.snapshot(peer);
|
|
35
|
+
}
|
|
36
|
+
leave(id) {
|
|
37
|
+
const e = this.e, peer = this.peers.get(id);
|
|
38
|
+
if (!peer) return;
|
|
39
|
+
this.peers.delete(id);
|
|
40
|
+
e.ops.allow(() => this.o.leave(e, peer));
|
|
41
|
+
e.events.emit('net:leave', { peer: id, actor: peer.actor });
|
|
42
|
+
}
|
|
43
|
+
snapshot(peer) {
|
|
44
|
+
this.keys ??= partKeys(this.e, this.o.sync);
|
|
45
|
+
this.stats.snapshots++;
|
|
46
|
+
this.send({ t: 's', n: this.n, tick: this.e.tick, you: peer.actor, every: this.o.syncEvery, parts: snapshotParts(this.e, this.keys) }, peer);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
receive(m, from) {
|
|
50
|
+
const peer = this.peers.get(from);
|
|
51
|
+
if (!peer || !m || typeof m !== 'object') return;
|
|
52
|
+
this.stats.in++;
|
|
53
|
+
if (m.t === 'op') this.request(peer, m);
|
|
54
|
+
else if (m.t === 'p') this.position(peer, m);
|
|
55
|
+
else if (m.t === 'resync') this.snapshot(peer);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
request(peer, m) {
|
|
59
|
+
const e = this.e, seq = isNum(m.seq) ? m.seq : 0, name = typeof m.name === 'string' ? m.name : '';
|
|
60
|
+
const reply = (ok, code, value) => peer.results.push({ t: 'r', seq, name, ok, code: code ?? null, value: plain(value), tick: e.tick });
|
|
61
|
+
const d = e.ops.defs.get(name), args = m.args ?? {};
|
|
62
|
+
const reason = this.gate(peer, d, args);
|
|
63
|
+
if (reason) {
|
|
64
|
+
this.stats.rejected++;
|
|
65
|
+
if (d) e.ops._log(name, args, { source: 'net', actor: peer.actor, tick: e.tick }, false, reason, 0); // keep refusals in the op history too
|
|
66
|
+
reply(false, reason);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const r = e.ops.run(name, args, { source: 'net', actor: peer.actor });
|
|
70
|
+
reply(r.ok, r.code, r.value);
|
|
71
|
+
}
|
|
72
|
+
/** returns a reason string when the request is refused at the door */
|
|
73
|
+
gate(peer, d, args) {
|
|
74
|
+
if (peer.tokens < 1) return 'rateLimited';
|
|
75
|
+
peer.tokens--;
|
|
76
|
+
if (!d) return 'unknownOp';
|
|
77
|
+
if (d.net !== 'peer') return 'notAllowed';
|
|
78
|
+
try { checkArgs(this.e, d, args); } catch { return 'badArgs'; }
|
|
79
|
+
if (d.owner) {
|
|
80
|
+
let id; try { id = d.owner(args); } catch { return 'notOwner'; }
|
|
81
|
+
if (this.e.world?.get(id)?.owner !== peer.actor) return 'notOwner';
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** the peer's own movement (client-driven): clamp to maxSpeed so a hacked client cannot teleport */
|
|
87
|
+
position(peer, m) {
|
|
88
|
+
const e = this.e, rec = e.world?.get(peer.actor), p = m.p;
|
|
89
|
+
if (!rec || !Array.isArray(p) || p.length !== 3 || !p.every(isNum)) return;
|
|
90
|
+
const dt = Math.min(0.25, Math.max(STEP, (e.tick - peer.posTick) * STEP)); // idle time earns no long jump peer.posTick = e.tick;
|
|
91
|
+
const c = rec.position, dx = p[0] - c.x, dy = p[1] - c.y, dz = p[2] - c.z, d = Math.hypot(dx, dy, dz), max = this.o.maxSpeed * dt + 0.5;
|
|
92
|
+
const k = d > max ? max / d : 1;
|
|
93
|
+
e.ops.allow(() => {
|
|
94
|
+
e.world.move(peer.actor, { x: c.x + dx * k, y: c.y + dy * k, z: c.z + dz * k });
|
|
95
|
+
const f = m.f && typeof m.f === 'object' ? m.f : {};
|
|
96
|
+
for (const key of this.o.avatarFields) if (key in f && plainScalar(f[key])) rec[key] = f[key];
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
fixed(dt) {
|
|
101
|
+
const o = this.o;
|
|
102
|
+
for (const p of this.peers.values()) p.tokens = Math.min(o.burst, p.tokens + o.rate * dt);
|
|
103
|
+
if (++this.steps % o.syncEvery) return;
|
|
104
|
+
this.keys ??= partKeys(this.e, o.sync);
|
|
105
|
+
const parts = diffParts(this.e, this.keys, this.base);
|
|
106
|
+
if (parts) { this.n++; this.stats.diffs++; this.lastSent = this.steps; for (const p of this.peers.values()) this.send({ t: 'd', n: this.n, tick: this.e.tick, parts }, p); }
|
|
107
|
+
else if (this.steps - this.lastSent >= o.keepAlive) { this.lastSent = this.steps; for (const p of this.peers.values()) this.send({ t: 'k', n: this.n }, p); } // lets a client notice a lost last diff
|
|
108
|
+
for (const p of this.peers.values()) { for (const r of p.results) this.send(r, p); p.results.length = 0; }
|
|
109
|
+
}
|
|
110
|
+
dispose() { for (const s of this.subs) s.remove(); }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** op return values travel as plain data; anything else (a three.js object, a function) is dropped */
|
|
114
|
+
function plain(v) {
|
|
115
|
+
if (v === undefined) return undefined;
|
|
116
|
+
try { return JSON.parse(JSON.stringify(v)); } catch { return null; }
|
|
117
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// engine.net: the public face of the net() module (one host, any number of clients; host authority + state sync). Usage in recipes/27-net.md.
|
|
2
|
+
// The host runs the game as usual; clients mirror its state and send op requests. Host.js / Client.js hold each side; sync.js what is synced.
|
|
3
|
+
import { NetHost } from './Host.js';
|
|
4
|
+
import { NetClient } from './Client.js';
|
|
5
|
+
|
|
6
|
+
/** engine.net (installed by net()): role, who this machine is, connection state and counters. Changes go through engine.ops, never through net. @experimental */
|
|
7
|
+
export class Net {
|
|
8
|
+
/** @internal */
|
|
9
|
+
constructor(e, o) {
|
|
10
|
+
/** 'host' or 'client' @type {'host' | 'client'} */
|
|
11
|
+
this.role = o.role;
|
|
12
|
+
/** @internal */ this._o = o;
|
|
13
|
+
/** @internal */ this._side = o.role === 'host' ? new NetHost(e, o.transport, o) : new NetClient(e, o.transport, o);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* This machine's actor id on the host: 'player' on the host, e.g. 'guest-1' on a client (null until the first snapshot).
|
|
17
|
+
* A client calls itself 'player' locally (own avatar record, own bag), so game code rarely needs this; it is for showing names and for logs.
|
|
18
|
+
* @returns {string | null}
|
|
19
|
+
*/
|
|
20
|
+
get actor() { return this.role === 'host' ? 'player' : this._side.actor; }
|
|
21
|
+
/** Client: has a connection and an up-to-date mirror. Host: always true @returns {boolean} */
|
|
22
|
+
get connected() { return this.role === 'host' ? true : this._side.connected && this._side.synced; }
|
|
23
|
+
/**
|
|
24
|
+
* Host: connected peers [{ id, actor }] (id from the transport, actor = world record / container id of that player). Client: []
|
|
25
|
+
* @returns {{ id: number, actor: string }[]}
|
|
26
|
+
*/
|
|
27
|
+
get peers() { return this.role === 'host' ? [...this._side.peers.values()].map(p => ({ id: p.id, actor: p.actor })) : []; }
|
|
28
|
+
/** Client: requests sent and not answered yet (seq -> op name). Host: empty @returns {Map<number, string>} */
|
|
29
|
+
get pending() { return this.role === 'host' ? new Map() : this._side.pending; }
|
|
30
|
+
/** Message counters: in / out, plus diffs, snapshots, rejected (host) or gaps (client: lost diffs that forced a snapshot) @returns {Record<string, number>} */
|
|
31
|
+
get stats() { return this._side.stats; }
|
|
32
|
+
/**
|
|
33
|
+
* Client: attach a new transport after the connection dropped; the host answers with a full snapshot. Pass the old key to keep the same actor (and bag).
|
|
34
|
+
* @param {any} transport
|
|
35
|
+
* @returns {void}
|
|
36
|
+
* @example
|
|
37
|
+
* engine.events.on('net:close', () => setTimeout(() => engine.net.reconnect(webSocket(url, { key: oldKey })), 2000));
|
|
38
|
+
*/
|
|
39
|
+
reconnect(transport) {
|
|
40
|
+
if (this.role !== 'client') throw new Error('engine.net.reconnect() is for clients; the host keeps its transport');
|
|
41
|
+
this._side.connect(transport);
|
|
42
|
+
}
|
|
43
|
+
/** @internal */
|
|
44
|
+
_fixed(dt) { this._side.fixed(dt); }
|
|
45
|
+
/** @internal */
|
|
46
|
+
_frame(dt) { this._side.frame?.(dt); }
|
|
47
|
+
/** @internal */
|
|
48
|
+
_dispose() { this._side.dispose(); }
|
|
49
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// net() module: optional co-op multiplayer, host authority + state sync. Not installed = no cost (core only keeps two internal hooks in Ops.js).
|
|
2
|
+
// engine.use(net({ role: 'host', transport })) // the player whose browser owns the game
|
|
3
|
+
// engine.use(net({ role: 'client', transport })) // friends: mirror the host, send op requests
|
|
4
|
+
// Only ops defined with net: 'peer' can be requested by clients (default deny); the actor comes from the connection, not the message.
|
|
5
|
+
// Transports: fakeNetwork() (in-process, tests) and webSocket(url) (with packages/tools/net-relay.mjs); see transports.js for the shape.
|
|
6
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
7
|
+
import { Net } from './Net.js';
|
|
8
|
+
|
|
9
|
+
export { fakeNetwork, webSocket } from './transports.js';
|
|
10
|
+
|
|
11
|
+
const OPTS = ['role', 'transport', 'sync', 'syncEvery', 'keepAlive', 'rate', 'burst', 'maxSpeed', 'posEvery', 'actorFor', 'actorFields', 'avatarFields', 'interpolate', 'avatar', 'onJoin', 'onLeave'];
|
|
12
|
+
const STRINGS = {
|
|
13
|
+
role: "net({ role }): role is 'host' (owns the game) or 'client' (mirrors the host), got {got}",
|
|
14
|
+
transport: 'net(): transport is required, e.g. net({ role, transport: webSocket(url) }) or fakeNetwork().connect() in tests',
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const NET_PARAMS = keysSchema(OPTS);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Optional co-op multiplayer: one host owns the state, clients mirror it and ask for changes through ops. Installed as engine.net.
|
|
21
|
+
* Host: peers' requests run as `ops.run(name, args, { source: 'net', actor })` only for ops defined with net: 'peer', with the op's args shape
|
|
22
|
+
* checked, the optional owner check, and a per-peer rate limit; the result comes back after the state diff that contains it.
|
|
23
|
+
* State: world records, containers, vars and the other save parts are sent as a snapshot on join and as diffs every syncEvery steps.
|
|
24
|
+
* Client: ops.run of a peer op returns { ok: true, pending: true, seq } (watch state or the net:result event, not the return value);
|
|
25
|
+
* its own avatar moves locally and is sent to the host (clamped to maxSpeed); other avatars glide between updates.
|
|
26
|
+
* Defaults per peer on the host (avatar: true): a world record { id: actor, kind: 'player' } (not saved) and a container with the actor id.
|
|
27
|
+
* @param {{ role: 'host' | 'client', transport: any, sync?: 'auto' | string[], syncEvery?: number, keepAlive?: number, rate?: number, burst?: number, maxSpeed?: number, posEvery?: number,
|
|
28
|
+
* actorFor?: (peerId: number) => string, actorFields?: string[], avatarFields?: string[], interpolate?: string[], avatar?: boolean,
|
|
29
|
+
* onJoin?: (e: any, peer: { id: number, actor: string }) => void, onLeave?: (e: any, peer: { id: number, actor: string }) => void }} opts
|
|
30
|
+
* sync: save parts to sync ('auto' = world, containers, vars and every other save part except random / level); syncEvery: steps between diffs (3 = 20/s);
|
|
31
|
+
* rate / burst: op requests per second per peer and the burst allowance; actorFields: record fields holding actor ids (swapped like ids, default ['owner']);
|
|
32
|
+
* avatarFields: own-avatar fields the client sends with its position; interpolate: record kinds that glide on clients (default ['player']).
|
|
33
|
+
* @returns {import('../../types/core').ModuleDef<Net>}
|
|
34
|
+
* @example
|
|
35
|
+
* // host
|
|
36
|
+
* engine.ops.define('chest.take', { net: 'peer', args: { chest: 'id', item: 'string' },
|
|
37
|
+
* can: (e, a, ctx) => e.inventory.container(a.chest).has(a.item) || 'empty',
|
|
38
|
+
* run: (e, a, ctx) => e.inventory.transfer(a.chest, ctx.actor, a.item, 1) });
|
|
39
|
+
* engine.use(net({ role: 'host', transport: webSocket('ws://localhost:8787/farm', { host: true }) }));
|
|
40
|
+
* // client (same game code, same op definitions)
|
|
41
|
+
* engine.use(net({ role: 'client', transport: webSocket('ws://192.168.1.5:8787/farm') }));
|
|
42
|
+
* engine.ops.run('chest.take', { chest: 'chest-1', item: 'apple' }); // -> { ok: true, pending: true, seq: 1 }
|
|
43
|
+
* @experimental
|
|
44
|
+
*/
|
|
45
|
+
export function net(opts = {}) {
|
|
46
|
+
readParams('net', NET_PARAMS, opts);
|
|
47
|
+
if (opts.role !== 'host' && opts.role !== 'client') throw new Error(STRINGS.role.replace('{got}', JSON.stringify(opts.role)));
|
|
48
|
+
if (!opts.transport) throw new Error(STRINGS.transport);
|
|
49
|
+
const left = new Map(); // actor -> last position, so a peer that reconnects comes back where it left
|
|
50
|
+
const o = {
|
|
51
|
+
sync: 'auto', syncEvery: 3, keepAlive: 60, rate: 20, burst: 20, maxSpeed: 15, posEvery: 3,
|
|
52
|
+
actorFor: id => 'guest-' + id, actorFields: ['owner'], avatarFields: ['facing', 'amount', 'grounded', 'swimming'], interpolate: ['player'], avatar: true,
|
|
53
|
+
...opts,
|
|
54
|
+
};
|
|
55
|
+
o.join = (e, peer) => {
|
|
56
|
+
if (o.avatar && e.world && !e.world.get(peer.actor)) {
|
|
57
|
+
const at = left.get(peer.actor) ?? e.world.get('player')?.position ?? { x: 0, y: 0, z: 0 };
|
|
58
|
+
e.world.add({ id: peer.actor, kind: 'player', position: { ...at } }, { save: false });
|
|
59
|
+
}
|
|
60
|
+
if (o.avatar && e.inventory) e.inventory.container(peer.actor);
|
|
61
|
+
o.onJoin?.(e, { id: peer.id, actor: peer.actor });
|
|
62
|
+
};
|
|
63
|
+
o.leave = (e, peer) => {
|
|
64
|
+
o.onLeave?.(e, { id: peer.id, actor: peer.actor });
|
|
65
|
+
const rec = e.world?.get(peer.actor);
|
|
66
|
+
if (o.avatar && rec) { left.set(peer.actor, { ...rec.position }); e.world.remove(peer.actor); } // the bag stays: a reconnect gets it back
|
|
67
|
+
};
|
|
68
|
+
let n = null;
|
|
69
|
+
return {
|
|
70
|
+
name: 'net', params: NET_PARAMS, options: opts, label: 'Multiplayer', stage: 'late', optional: ['world', 'inventory'],
|
|
71
|
+
install(e) { return (n = new Net(e, o)); },
|
|
72
|
+
fixed(dt) { n._fixed(dt); },
|
|
73
|
+
frame(dt) { n._frame(dt); },
|
|
74
|
+
describe() { return { role: n.role, actor: n.actor, connected: n.connected, peers: n.peers.length, pending: n.pending.size }; },
|
|
75
|
+
dispose() { n._dispose(); },
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// State sync for net(): what the host reads into snapshots / diffs, and how a client writes them back.
|
|
2
|
+
// A "part" is a map of entries (id -> plain value). world: records by id; containers: item counts by container id (the player bag included);
|
|
3
|
+
// vars: { flags, counters }; any other save provider (quests, clock, sky...) is one entry '=' with its save() data.
|
|
4
|
+
// The host keeps one baseline (entry -> JSON text) for all peers: a diff is the entries whose JSON changed since the last sync, so
|
|
5
|
+
// changes made directly inside simulate are caught too, like saves (persist.js). A peer that missed a diff gets a full snapshot instead.
|
|
6
|
+
//
|
|
7
|
+
// Ids: each machine calls its own avatar 'player' (characters, inventory and interactions are built on that id). On the host, a peer's
|
|
8
|
+
// avatar and bag are its actor id ('guest-2'). A client sees itself as 'player' and the host's avatar as 'host', so the two names swap
|
|
9
|
+
// at the wire (toLocal / toHost). Record fields that hold actor ids (owner...) are listed in net({ actorFields }) and swapped too.
|
|
10
|
+
|
|
11
|
+
const SKIP = ['random', 'level', 'inventory', 'containers', 'world', 'vars']; // random/level stay per machine; inventory is the player bag, sent inside containers
|
|
12
|
+
const GENERIC = '=';
|
|
13
|
+
|
|
14
|
+
/** @internal parts to sync: 'auto' = world, containers, vars and every other save provider except random / level */
|
|
15
|
+
export function partKeys(e, sync) {
|
|
16
|
+
if (Array.isArray(sync)) return sync;
|
|
17
|
+
const keys = [];
|
|
18
|
+
if (e.world) keys.push('world');
|
|
19
|
+
if (e.inventory) keys.push('containers');
|
|
20
|
+
keys.push('vars');
|
|
21
|
+
for (const k of e.saves.providers.keys()) if (!SKIP.includes(k)) keys.push(k);
|
|
22
|
+
return keys;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @internal host: one part as entries { id: value } (live objects; the transport copies them) */
|
|
26
|
+
function readPart(e, key) {
|
|
27
|
+
if (key === 'world') return Object.fromEntries(e.world.records);
|
|
28
|
+
if (key === 'containers') { const out = {}; for (const [id, c] of e.inventory._containers.map) out[id] = c._save(); return out; }
|
|
29
|
+
if (key === 'vars') return { flags: e.vars.flags, counters: e.vars.counters };
|
|
30
|
+
const p = e.saves.providers.get(key);
|
|
31
|
+
return p ? { [GENERIC]: p.save() } : {};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @internal host: entries of `parts` changed since `base` (Map key -> Map id -> json); updates base. Returns null when nothing changed */
|
|
35
|
+
export function diffParts(e, keys, base) {
|
|
36
|
+
let out = null;
|
|
37
|
+
for (const key of keys) {
|
|
38
|
+
const now = readPart(e, key), b = base.get(key) ?? base.set(key, new Map()).get(key);
|
|
39
|
+
let set = null, del = null;
|
|
40
|
+
for (const id in now) {
|
|
41
|
+
const j = JSON.stringify(now[id]);
|
|
42
|
+
if (b.get(id) !== j) { b.set(id, j); (set ||= {})[id] = now[id]; }
|
|
43
|
+
}
|
|
44
|
+
for (const id of b.keys()) if (!(id in now)) { b.delete(id); (del ||= []).push(id); }
|
|
45
|
+
if (set || del) (out ||= {})[key] = { set: set ?? undefined, del: del ?? undefined };
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** @internal host: full snapshot of `keys`; also (re)fills the baseline when given */
|
|
51
|
+
export function snapshotParts(e, keys) {
|
|
52
|
+
const out = {};
|
|
53
|
+
for (const key of keys) out[key] = readPart(e, key);
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @internal id swap between the host's names and this client's names (see the top of the file) */
|
|
58
|
+
export function idMap(me) {
|
|
59
|
+
const toLocal = id => id === me ? 'player' : id === 'player' ? 'host' : id;
|
|
60
|
+
const toHost = id => id === 'player' ? me : id === 'host' ? 'player' : id;
|
|
61
|
+
return { toLocal, toHost };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @internal client: write one part (full snapshot or diff) into this engine. Runs inside ops.allow (the client guard lets it through).
|
|
66
|
+
* Position changes of interpolated kinds go to `interp(id, to)` instead of moving now; the own avatar keeps its local position (the client drives its own movement).
|
|
67
|
+
*/
|
|
68
|
+
export function applyPart(e, key, part, full, opts) {
|
|
69
|
+
const set = full ? part : part.set ?? {}, del = full ? null : part.del ?? [], { toLocal } = opts;
|
|
70
|
+
if (key === 'world') return applyWorld(e, set, del, full, opts);
|
|
71
|
+
if (key === 'containers') {
|
|
72
|
+
const inv = e.inventory, seen = new Set();
|
|
73
|
+
for (const id in set) { const c = inv.container(toLocal(id)); seen.add(c.id); c._load(set[id]); }
|
|
74
|
+
for (const id of del ?? []) { const c = inv._containers.map.get(toLocal(id)); if (c) c._load([]); }
|
|
75
|
+
if (full) for (const [id, c] of inv._containers.map) if (!seen.has(id)) c._load([]);
|
|
76
|
+
inv._refresh(); // _load is silent (as a save load): redraw the inventory UI once
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (key === 'vars') {
|
|
80
|
+
if ('flags' in set || 'counters' in set) e.vars.replace(set.flags, set.counters);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (GENERIC in set) e.saves.providers.get(key)?.load(set[GENERIC]);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function applyWorld(e, set, del, full, { toLocal, actorFields, avatarFields, smooth, glide }) {
|
|
87
|
+
const W = e.world;
|
|
88
|
+
const local = rec => {
|
|
89
|
+
const r = { ...rec, id: toLocal(rec.id) };
|
|
90
|
+
for (const f of actorFields) if (typeof r[f] === 'string') r[f] = toLocal(r[f]);
|
|
91
|
+
return r;
|
|
92
|
+
};
|
|
93
|
+
if (full) {
|
|
94
|
+
const keep = new Set(Object.keys(set).map(toLocal));
|
|
95
|
+
for (const id of [...W.records.keys()]) if (id !== 'player' && !keep.has(id)) W.remove(id);
|
|
96
|
+
}
|
|
97
|
+
for (const id of del ?? []) { const l = toLocal(id); if (l !== 'player') W.remove(l); }
|
|
98
|
+
for (const hostId in set) {
|
|
99
|
+
const rec = local(set[hostId]), have = W.get(rec.id);
|
|
100
|
+
if (!have) { W.add(rec, { save: false }); continue; } // own avatar too, when no characters module made one (it then takes this record over)
|
|
101
|
+
const { id, kind, position, ...fields } = rec, own = id === 'player', patch = {};
|
|
102
|
+
let changed = false;
|
|
103
|
+
for (const k in fields) {
|
|
104
|
+
if (own && avatarFields.includes(k)) continue; // own avatar: what we sent comes back late; the local value is newer
|
|
105
|
+
if (JSON.stringify(fields[k]) !== JSON.stringify(have[k])) { patch[k] = fields[k]; changed = true; }
|
|
106
|
+
}
|
|
107
|
+
if (!own) for (const k in have) if (!(k in rec) && have[k] !== undefined) { patch[k] = undefined; changed = true; }
|
|
108
|
+
if (changed) W.set(id, patch);
|
|
109
|
+
if (own) continue; // own avatar: position stays local (this client drives its own movement)
|
|
110
|
+
const p = have.position;
|
|
111
|
+
if (p.x === position.x && p.y === position.y && p.z === position.z) continue;
|
|
112
|
+
if (!full && smooth(have)) glide(id, position); else W.move(id, position);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Transports for net(): how messages travel between the host and its peers. net() only uses this small shape, so any carrier
|
|
2
|
+
// (a Colyseus room, a WebRTC data channel, a game server) plugs in by implementing it:
|
|
3
|
+
// send(msg, to?) deliver a plain-object message; on the host `to` is a peer id, on a client it goes to the host
|
|
4
|
+
// on(type, fn) host: 'join' (peerId), 'leave' (peerId), 'message' (msg, from); client: 'open', 'close', 'message' (msg)
|
|
5
|
+
// close()
|
|
6
|
+
// Delivery must keep order per link (WebSocket does); messages may be lost (the sync recovers with a full snapshot).
|
|
7
|
+
// Peer ids come from the transport, never from what a client says about itself: they are the identity the host's actor ids are built on.
|
|
8
|
+
// A reconnecting client presents `key` (a secret the transport handed it on first connect) to get its old peer id back.
|
|
9
|
+
import { Random } from '../../core/Random.js';
|
|
10
|
+
|
|
11
|
+
/** @internal tiny event emitter shared by the transports */
|
|
12
|
+
function emitter() {
|
|
13
|
+
const subs = {};
|
|
14
|
+
return {
|
|
15
|
+
on(type, fn) { (subs[type] ||= []).push(fn); return { remove: () => { subs[type] = subs[type].filter(f => f !== fn); } }; },
|
|
16
|
+
emit(type, ...a) { for (const fn of subs[type] || []) fn(...a); },
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* An in-process network for tests and offline demos: one host and any number of clients in the same page, with optional latency, jitter and loss.
|
|
22
|
+
* Messages are deep-copied on send (no shared objects, like a real wire). Order per link is kept, as on a WebSocket.
|
|
23
|
+
* manual: true delivers only when you call advance(ms) (deterministic tests); otherwise messages land after real time.
|
|
24
|
+
* @param {{ latency?: number, jitter?: number, loss?: number, seed?: number, manual?: boolean }} [opts] latency / jitter in ms, loss 0..1
|
|
25
|
+
* @returns {{ host(): any, connect(opts?: { key?: string }): any, advance(ms: number): void, readonly now: number, loss: number, latency: number, jitter: number }}
|
|
26
|
+
* @example
|
|
27
|
+
* const wire = fakeNetwork({ latency: 80, jitter: 30, loss: 0.05, manual: true });
|
|
28
|
+
* host.use(net({ role: 'host', transport: wire.host() }));
|
|
29
|
+
* guest.use(net({ role: 'client', transport: wire.connect() }));
|
|
30
|
+
* wire.advance(100); // deliver what is due in the next 100 ms
|
|
31
|
+
* @experimental
|
|
32
|
+
*/
|
|
33
|
+
export function fakeNetwork(opts = {}) {
|
|
34
|
+
const { seed = 1, manual = false } = opts;
|
|
35
|
+
const r = new Random(seed), rand = () => r.next(), queue = [], keys = new Map(); // seeded: loss and jitter repeat between test runs
|
|
36
|
+
let now = 0, host = null, nextId = 0, timer = null;
|
|
37
|
+
const clock = () => manual ? now : performance.now(); // wall-clock: a simulated wire delays by real time, like a real one
|
|
38
|
+
const W = {
|
|
39
|
+
latency: opts.latency ?? 0, jitter: opts.jitter ?? 0, loss: opts.loss ?? 0,
|
|
40
|
+
get now() { return clock(); },
|
|
41
|
+
/** Deliver everything due within the next ms (manual mode) */
|
|
42
|
+
advance(ms) { now += ms; flush(); },
|
|
43
|
+
host() {
|
|
44
|
+
const ev = emitter();
|
|
45
|
+
host = { ev, peers: new Map(), closed: false };
|
|
46
|
+
return { send: (msg, to) => { const c = host.peers.get(to); if (c) post(c.link, () => c.ev.emit('message', msg), msg); }, on: ev.on, close() { host.closed = true; for (const c of host.peers.values()) c.drop(); } };
|
|
47
|
+
},
|
|
48
|
+
connect({ key } = {}) {
|
|
49
|
+
const ev = emitter();
|
|
50
|
+
const id = keys.get(key) ?? ++nextId, secret = key && keys.has(key) ? key : 'k' + id + '-' + Math.floor(rand() * 1e9);
|
|
51
|
+
keys.set(secret, id);
|
|
52
|
+
const c = { ev, link: { at: 0 }, up: { at: 0 }, open: false, id };
|
|
53
|
+
c.drop = () => { if (!c.open) return; c.open = false; host.peers.delete(id); host.ev.emit('leave', id); ev.emit('close'); };
|
|
54
|
+
const t = {
|
|
55
|
+
id, key: secret,
|
|
56
|
+
send(msg) { if (c.open && !host.closed) post(c.up, () => { if (c.open) host.ev.emit('message', msg, id); }, msg); },
|
|
57
|
+
on: ev.on,
|
|
58
|
+
close: () => c.drop(),
|
|
59
|
+
/** Simulate a dropped connection (both sides notice at once) */
|
|
60
|
+
drop: () => c.drop(),
|
|
61
|
+
};
|
|
62
|
+
// the connection itself opens after one latency, like a handshake
|
|
63
|
+
post(c.link, () => { if (!host || host.closed) return; c.open = true; host.peers.set(id, c); ev.emit('open'); host.ev.emit('join', id); }, null, true);
|
|
64
|
+
return t;
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
// schedule one delivery: keep per-link order (a later message never overtakes), drop with probability loss
|
|
68
|
+
function post(link, fn, msg, reliable = false) {
|
|
69
|
+
if (!reliable && W.loss > 0 && rand() < W.loss) return;
|
|
70
|
+
const copy = msg == null ? null : structuredClone(msg);
|
|
71
|
+
const at = Math.max(clock() + W.latency + rand() * W.jitter, link.at);
|
|
72
|
+
link.at = at;
|
|
73
|
+
queue.push({ at, fn: () => fn(copy) });
|
|
74
|
+
queue.sort((a, b) => a.at - b.at);
|
|
75
|
+
if (!manual && !timer) timer = setTimeout(tick, Math.max(0, at - clock())); // wall-clock
|
|
76
|
+
}
|
|
77
|
+
function flush() { while (queue.length && queue[0].at <= clock()) queue.shift().fn(); }
|
|
78
|
+
function tick() { timer = null; flush(); if (queue.length) timer = setTimeout(tick, Math.max(0, queue[0].at - clock())); } // wall-clock
|
|
79
|
+
return W;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* WebSocket transport: talks to the relay in packages/tools/net-relay.mjs (`node packages/tools/net-relay.mjs 8787`).
|
|
84
|
+
* The host joins a room with host: true; clients join the same room. The relay assigns peer ids and remembers each client's key for reconnects.
|
|
85
|
+
* Messages are JSON. For a dedicated server or Colyseus, write another transport with the same send / on / close shape instead.
|
|
86
|
+
* @param {string} url e.g. 'ws://localhost:8787/my-room'
|
|
87
|
+
* @param {{ host?: boolean, key?: string }} [opts] key: reuse a previous peer id after a reconnect (read transport.key after 'open')
|
|
88
|
+
* @returns {{ send(msg: any, to?: number): void, on(type: string, fn: Function): { remove(): void }, close(): void, key: string | null, id: number | null }}
|
|
89
|
+
* @example
|
|
90
|
+
* engine.use(net({ role: 'host', transport: webSocket('ws://localhost:8787/farm', { host: true }) }));
|
|
91
|
+
* // on a friend's machine
|
|
92
|
+
* const t = webSocket('ws://192.168.1.5:8787/farm', { key: localStorage.netKey });
|
|
93
|
+
* t.on('open', () => { localStorage.netKey = t.key; });
|
|
94
|
+
* engine.use(net({ role: 'client', transport: t }));
|
|
95
|
+
* @experimental
|
|
96
|
+
*/
|
|
97
|
+
export function webSocket(url, { host = false, key } = {}) {
|
|
98
|
+
const ev = emitter(), q = new URL(url);
|
|
99
|
+
if (host) q.searchParams.set('host', '1');
|
|
100
|
+
if (key) q.searchParams.set('key', key);
|
|
101
|
+
const ws = new WebSocket(q.href);
|
|
102
|
+
const t = {
|
|
103
|
+
key: key ?? null, id: null,
|
|
104
|
+
send(msg, to) { if (ws.readyState === 1) ws.send(JSON.stringify(host ? { to, msg } : { msg })); },
|
|
105
|
+
on: ev.on,
|
|
106
|
+
close() { ws.close(); },
|
|
107
|
+
};
|
|
108
|
+
ws.onmessage = m => {
|
|
109
|
+
const d = JSON.parse(m.data);
|
|
110
|
+
if (d.hello) { t.id = d.hello.id; t.key = d.hello.key ?? null; if (!host) ev.emit('open'); }
|
|
111
|
+
else if (d.join != null) ev.emit('join', d.join);
|
|
112
|
+
else if (d.leave != null) ev.emit('leave', d.leave);
|
|
113
|
+
else if (d.closed) ws.close();
|
|
114
|
+
else ev.emit('message', d.msg, d.from);
|
|
115
|
+
};
|
|
116
|
+
ws.onclose = () => ev.emit('close');
|
|
117
|
+
return t;
|
|
118
|
+
}
|