Refactoring round 7: split BehaviorSystem, fewer copies (#85)
Recurring cleanup round over the code since round 6 (056a622), 105
commits. Behaviour is unchanged. Duplicated code in src went from 29
clones with 229 lines (0.32 %) to 14 clones with 109 lines (0.15 %),
measured with jscpd and the same settings as round 6.
- BehaviorSystem.ts shrinks from 941 to 589 lines. Collecting the
pulses (keys, timers, collisions, animations) moved to
behaviorPulses.ts. The NodeContext the nodes receive moved to
behaviorContext.ts. Imports from outside stay the same, TimeScaled
is still exported from BehaviorSystem.ts.
- PointKindButton and drawPointGrip replace the "Point:" button with
its menu and the point and handle drawing that the curve and the
vector art tab each had on their own.
- lerpVec, cubicAt and splitCubic in src/core/util/vec.ts replace four
copies of the cubic curve and two de Casteljau splits.
- mapNested in Properties.ts is the one walk over lists and structs
that liveObjects and objectRefs did separately. withFieldRenamed
and withoutField replace three copies of renaming a struct field
and two of removing one.
- jsonBody and staleRevision build the JSON body and turn a 409 into
StaleRevisionError for all stores. The auth store turns a 401 into
its error in one place.
- Smaller helpers: structAssetFrom for the two "Make struct type"
commands, shownObject in the inspector, selectedItem for the size
gizmo and the polygon corners, solidTiles in the tilemap collision,
requireVariablesAsset and requireBehaviorVariable.
- Left as is on purpose: the plain forwarding from the collision and
physics systems to Solids, the pointer wiring of the canvases and
the identical last lines of the two make commands.
- Removed unused code: tilemapTileIds and tilemapsUsing were never
called since #128 and #131. EditorState.runtimeProject became unused
with GameRun in #266. The assetId getter of the make commands was
read only by a test.
- 60 values used only in their own file lost their export. The shader
and particle node catalogues stay exported as in round 6.
- Five comments that told history now describe the current state. The
doc comment of BehaviorSystem sits on the class again.
- README lists the struct, clip area and curve assets and mentions the
game link from #266.
Findings:
- Deleting a tile that is painted on a tilemap leaves its cells in
place, and they draw nothing. The delete dialog does not mention the
tilemaps. That was probably the job of the unused tilemapsUsing.
Left as is, because fixing it changes behaviour.
- The solid filter for tile surfaces was untested. A bent filter
stayed green. A new test in tests/core/surface.test.ts now fails
against it.
Tests:
- ./check.sh: 195 files, 2815 tests, exit 0 (one test removed with
tilemapsUsing, one added for tile surfaces).
- Full e2e run: ALL PASSED, 1580 checks.
- Smokes jumprun, tetris, actor: 24, 19 and 21 checks, all passed.
The example project files were restored byte for byte afterwards.
- Counter-checks, 12, all fail as expected: 10 in unit tests (among
them mapNested, splitCubic, cubicAt, staleRevision, the stay pulse,
the late timer and the time scale), 2 in the browser (Point button
always enabled fails 47, selectedItem without a hit fails 29).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dded62b9f9
commit
bc688f3efc
93 files changed
+914
-902
No files matched your search
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* What a behavior's graph reaches of the running game, as the `NodeContext` its nodes are handed:
|
||||
* the world, the keyboard, collisions and rays, physics, sound, the clock and the shared values.
|
||||
* Handles arriving from a graph are resolved to the world's entities here, so no node holds one.
|
||||
*/
|
||||
import type { EntityHandle, NodeContext, PhysicsControl, SharedState } from '../../core/graph';
|
||||
import type { Vec2 } from '../../core/model/Properties';
|
||||
import { findAssetOf, findScene, type Project } from '../../core/model/Project';
|
||||
import { soundFileOf } from '../../core/model/sound';
|
||||
import { resolveAssetProps } from '../../core/properties/resolve';
|
||||
import { loopsOf, volumeOf } from '../../core/properties/sounds';
|
||||
import type { Entity } from '../Entity';
|
||||
import { PhysicsSystem } from '../physics/PhysicsSystem';
|
||||
import type { World } from '../World';
|
||||
import type { AudioSink } from './Audio';
|
||||
import type { Instance } from './behaviorPulses';
|
||||
import type { Input } from './Input';
|
||||
import { bodyOf, type CollisionSource, NOT_BLOCKED } from './solids';
|
||||
|
||||
export interface TimeScaled {
|
||||
scale: number;
|
||||
}
|
||||
|
||||
/** What the running `BehaviorSystem` lends every context it makes. */
|
||||
export interface ContextSources {
|
||||
project: Project;
|
||||
input: Input;
|
||||
collisions: CollisionSource | null;
|
||||
audio: AudioSink;
|
||||
clock: TimeScaled | null;
|
||||
shared: SharedState;
|
||||
/** A graph moved one of this instance's machines; its events follow between exec flows. */
|
||||
stateChanged(machineId: string, from: string, to: string): void;
|
||||
}
|
||||
|
||||
const NO_DYNAMIC_BODY =
|
||||
'has no dynamic rigidbody, so Apply force, Apply impulse and Set velocity do nothing on it.';
|
||||
|
||||
export function behaviorContext(
|
||||
instance: Instance,
|
||||
world: World,
|
||||
dt: number,
|
||||
run: ContextSources,
|
||||
): NodeContext {
|
||||
const { entity, states } = instance;
|
||||
const { project, collisions, clock } = run;
|
||||
// Handles arriving from the graph are the entities themselves, or test doubles with the same id.
|
||||
const resolve = (handle: EntityHandle | null): Entity | undefined =>
|
||||
handle ? world.entities.find((e) => e === handle || e.id === handle.id) : undefined;
|
||||
return {
|
||||
self: entity,
|
||||
owner: entity.parent,
|
||||
variables: entity.props,
|
||||
states,
|
||||
shared: run.shared,
|
||||
stateChanged: (machineId, from, to) => run.stateChanged(machineId, from, to),
|
||||
time: world.time,
|
||||
dt,
|
||||
findByName: (name) => world.findByName(name) ?? null,
|
||||
// By identity, not by id: a restarted scene builds new entities under the same ids.
|
||||
isAlive: (target) => world.entities.some((e) => e === target),
|
||||
findReferenced: (from, ref) => {
|
||||
const found = resolve(from);
|
||||
return (found && world.findReferenced(found, ref)) ?? null;
|
||||
},
|
||||
childByName: (parent, name) => {
|
||||
const found = resolve(parent);
|
||||
return (found && world.childByName(found, name)) ?? null;
|
||||
},
|
||||
objects: () => world.entities,
|
||||
isKeyDown: (key) => run.input.isDown(key),
|
||||
pointer: world.pointer,
|
||||
hitTest: (target, x, y) => {
|
||||
const found = resolve(target);
|
||||
return Boolean(found && world.hitTest(found, x, y));
|
||||
},
|
||||
isTouching: (a, b) => {
|
||||
const ea = resolve(a);
|
||||
const eb = resolve(b);
|
||||
return Boolean(collisions && ea && eb && collisions.touching(world, ea, eb));
|
||||
},
|
||||
moveAndSlide: (target, dx, dy) => {
|
||||
const found = resolve(target);
|
||||
if (!found) return NOT_BLOCKED;
|
||||
if (collisions) return collisions.moveAndSlide(world, found, dx, dy);
|
||||
found.x += dx;
|
||||
found.y += dy;
|
||||
return NOT_BLOCKED;
|
||||
},
|
||||
raycast: (from, direction, length, { ignore, triggers, layers }) => {
|
||||
const hit = collisions?.raycast(world, from, direction, length, {
|
||||
ignore: resolve(ignore) ?? null,
|
||||
triggers,
|
||||
layers,
|
||||
});
|
||||
world.noteRay(from, hit?.point ?? pointAlong(from, direction, length), Boolean(hit));
|
||||
return hit ? { ...hit, object: bodyOf(hit.collider) } : null;
|
||||
},
|
||||
raycastAll: (from, direction, length, { ignore, triggers, layers, maxHits }) => {
|
||||
const hits =
|
||||
collisions?.raycastAll(
|
||||
world,
|
||||
from,
|
||||
direction,
|
||||
length,
|
||||
{ ignore: resolve(ignore) ?? null, triggers, layers },
|
||||
maxHits,
|
||||
) ?? [];
|
||||
// Drawn to the last thing it met, not to the first: that is how far this ray looked.
|
||||
const last = hits[hits.length - 1];
|
||||
const end = last ? last.point : pointAlong(from, direction, length);
|
||||
world.noteRay(from, end, hits.length > 0);
|
||||
return hits.map((hit) => ({ ...hit, object: bodyOf(hit.collider) }));
|
||||
},
|
||||
ignoreOneWay: (target, seconds) => {
|
||||
const found = resolve(target);
|
||||
if (found) world.ignoreOneWay(found, seconds);
|
||||
},
|
||||
isTilemap: (target) => {
|
||||
const found = resolve(target);
|
||||
return found ? world.isTilemap(found) : false;
|
||||
},
|
||||
tileAt: (target, layer, cell) => {
|
||||
const found = resolve(target);
|
||||
return found ? world.tileAt(found, layer, cell) : null;
|
||||
},
|
||||
setTile: (target, layer, cell, tileId) => {
|
||||
const found = resolve(target);
|
||||
return found ? world.setTile(found, layer, cell, tileId) : false;
|
||||
},
|
||||
physics: collisions instanceof PhysicsSystem ? physicsControl(world, collisions, resolve) : undefined,
|
||||
log: (message) => {
|
||||
world.log.push(message);
|
||||
// The `Log` node's whole purpose: the author wants this in the browser console.
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`[behavior ${entity.name}]`, message);
|
||||
},
|
||||
playSound: (assetId, volume, loop, detached) =>
|
||||
playSound(run, assetId, volume, loop, detached ? '' : entity.id),
|
||||
// An id nothing resolves stops nothing, rather than silencing the whole run by accident;
|
||||
// only the empty id means "everything", which is what the node promises.
|
||||
stopSound: (assetId) => {
|
||||
const file = assetId === '' ? '' : soundFileOf(project, assetId);
|
||||
if (assetId === '' || file) run.audio.stop(file);
|
||||
},
|
||||
spawn: (assetId, position, parent) => world.spawn(assetId, position, resolve(parent) ?? null),
|
||||
destroy: (target, keepChildren) => {
|
||||
const found = resolve(target);
|
||||
if (!found) return [];
|
||||
if (keepChildren) return world.removeKeepingChildren(found);
|
||||
world.remove(found);
|
||||
return [];
|
||||
},
|
||||
loadScene: (sceneId) => {
|
||||
// An id naming no scene is dropped here rather than half way through the swap, where the
|
||||
// run would already have torn down the world it is still standing in.
|
||||
if (findScene(project, sceneId)) world.loadSceneRequested = sceneId;
|
||||
else world.log.push(`Load scene: no scene ${sceneId}`);
|
||||
},
|
||||
stop: () => {
|
||||
world.stopRequested = true;
|
||||
},
|
||||
restart: () => {
|
||||
world.restartRequested = true;
|
||||
},
|
||||
timeScale: () => clock?.scale ?? 1,
|
||||
setTimeScale: (scale) => {
|
||||
if (clock) clock.scale = scale;
|
||||
else world.log.push(`Set time scale is ignored in the editor run (${scale})`);
|
||||
},
|
||||
isPaused: () => world.paused,
|
||||
setPaused: (paused) => {
|
||||
world.paused = paused;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What the graph asked for, as the sink understands it: the asset's own volume scaled by the
|
||||
* node's, and its loop flag unless the node overrules it either way. The asset is what a sound
|
||||
* *is* – a node that says nothing therefore plays it as the project describes it.
|
||||
*/
|
||||
function playSound(
|
||||
{ project, audio }: ContextSources,
|
||||
assetId: string,
|
||||
volume: number,
|
||||
loop: boolean | undefined,
|
||||
owner: string,
|
||||
): void {
|
||||
const asset = findAssetOf(project, assetId, 'sound');
|
||||
if (!asset?.file) return;
|
||||
const props = resolveAssetProps(project, asset);
|
||||
const level = Math.max(0, Math.min(1, volumeOf(props) * volume));
|
||||
audio.play(asset.file, level, loop ?? loopsOf(props), owner);
|
||||
}
|
||||
|
||||
/** Where a ray of that length ends; where it has no direction, where it starts. */
|
||||
function pointAlong(from: Vec2, direction: Vec2, length: number): Vec2 {
|
||||
const d = Math.hypot(direction.x, direction.y);
|
||||
if (!(d > 0) || !(length > 0)) return from;
|
||||
return { x: from.x + (direction.x / d) * length, y: from.y + (direction.y / d) * length };
|
||||
}
|
||||
|
||||
/** The physics nodes' way into the played game's engine, with the handles of the graph resolved. */
|
||||
function physicsControl(
|
||||
world: World,
|
||||
physics: PhysicsSystem,
|
||||
resolve: (handle: EntityHandle | null) => Entity | undefined,
|
||||
): PhysicsControl {
|
||||
const act = (handle: EntityHandle, action: (entity: Entity) => boolean): boolean => {
|
||||
const found = resolve(handle);
|
||||
if (!found) return false;
|
||||
if (action(found)) return true;
|
||||
physics.hint(world, found, NO_DYNAMIC_BODY);
|
||||
return false;
|
||||
};
|
||||
return {
|
||||
velocityOf: (handle) => {
|
||||
const found = resolve(handle);
|
||||
const v = found ? physics.velocityOf(found) : null;
|
||||
return found && v ? { ...v, angular: physics.angularVelocityOf(found) ?? 0 } : null;
|
||||
},
|
||||
setVelocity: (handle, x, y) => act(handle, (e) => physics.setVelocity(e, { x, y })),
|
||||
setAngularVelocity: (handle, degrees) => act(handle, (e) => physics.setAngularVelocity(e, degrees)),
|
||||
applyImpulse: (handle, x, y) => act(handle, (e) => physics.applyImpulse(e, { x, y })),
|
||||
setGravity: (x, y) => physics.setGravity(world, { x, y }),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user