Refactoring round 7: split BehaviorSystem, fewer copies (#85)
game-maker / gate (push) Successful in 3m50s
game-maker / suite (push) Successful in 12m3s

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:
adminandClaude Opus 5.5 committed 2026-09-29 16:16:37 +02:00
1 parent dded62b9f9
commit bc688f3efc
93 files changed
+914 -902

No files matched your search

+1 -1
View File
@@ -113,7 +113,7 @@ export function findGraphAsset(project: Project, assetId: string): GraphAsset |
*/
export type ObjectHolder = SceneAsset | ContainerAsset;
export function isObjectHolder(asset: Asset): asset is ObjectHolder {
function isObjectHolder(asset: Asset): asset is ObjectHolder {
return asset.type === 'scene' || asset.type === 'container';
}
+32
View File
@@ -60,6 +60,38 @@ export function withItemType(value: StructValue, typeId: string): StructValue {
return typeId ? { ...fields, [ITEM_TYPE_KEY]: typeId } : fields;
}
export function withoutField(value: StructValue, key: string): StructValue {
const { [key]: _dropped, ...rest } = value;
return rest;
}
/** Rebuilt rather than reassigned, so the field keeps its place in the value. */
export function withFieldRenamed(value: StructValue, from: string, to: string): StructValue {
const next: Record<string, FieldValue> = {};
for (const [key, item] of Object.entries(value)) next[key === from ? to : key] = item;
return next;
}
/**
* `value` with each part `swap` answers for replaced by the answer, through lists and untagged
* structs to any depth; `undefined` keeps a part and looks inside it. What is untouched keeps its
* identity, so a caller can tell whether anything changed.
*/
export function mapNested(value: unknown, swap: (part: unknown) => unknown): unknown {
const swapped = swap(value);
if (swapped !== undefined) return swapped;
if (isList(value)) {
const items = value.map((item) => mapNested(item, swap));
return items.some((item, i) => item !== value[i]) ? items : value;
}
if (isStruct(value) && tagOf(value) === undefined) {
const entries = Object.entries(value);
const mapped = entries.map(([key, field]) => [key, mapNested(field, swap)] as const);
return mapped.some(([, field], i) => field !== entries[i]![1]) ? Object.fromEntries(mapped) : value;
}
return value;
}
/** The value as a run holds it: every item-type mark taken out, at any depth. */
export function withoutItemTypes<T extends PropertyValue | undefined>(value: T): T {
if (isList(value)) return (value.some(holdsItemType) ? value.map(withoutItemTypes) : value) as T;
+1 -1
View File
@@ -20,7 +20,7 @@ import type { SceneObject } from './SceneObject';
import { mixColor } from '../util/color';
/** `once` holds the last value when it ends, `once-reset` puts back what was there before it started. */
export const PLAYBACKS = ['loop', 'once', 'once-reset', 'pingpong'] as const;
const PLAYBACKS = ['loop', 'once', 'once-reset', 'pingpong'] as const;
export type Playback = (typeof PLAYBACKS)[number];
/** What an animation can be built over: something placed, or a whole scene. */
+1 -1
View File
@@ -45,7 +45,7 @@ export function easeCurve(shape: EasingShape, direction: EasingDirection): Vecto
return curveFromEase((t) => easedShare(interpolation, t));
}
export function curveFromEase(ease: (t: number) => number): VectorPoint[] {
function curveFromEase(ease: (t: number) => number): VectorPoint[] {
let at = [0, 1];
let points = traced(ease, at);
for (let round = 0; round < MAX_ROUNDS; round++) {
+1 -1
View File
@@ -54,7 +54,7 @@ export function removeSubtrees(tree: ObjectTree, rootIds: readonly string[]): Re
}
/** An object and every parent above it, nearest first. */
export function chainOf(tree: ObjectTree, object: SceneObject): SceneObject[] {
function chainOf(tree: ObjectTree, object: SceneObject): SceneObject[] {
return [...parentChain(object, (o) => parentOf(tree, o))];
}
+1 -1
View File
@@ -70,7 +70,7 @@ function mergeEdits(
};
}
export function containerAssetOf(project: Project, object: SceneObject): ContainerAsset | undefined {
function containerAssetOf(project: Project, object: SceneObject): ContainerAsset | undefined {
return findAssetOf(project, object.assetId, 'container');
}
+1 -1
View File
@@ -90,7 +90,7 @@ export function angleOf(m: Mat): number {
return Math.atan2(m.b, m.a);
}
export function isMirrored(m: Mat): boolean {
function isMirrored(m: Mat): boolean {
return determinant(m) < 0;
}
+6 -15
View File
@@ -6,7 +6,7 @@
import { findAsset, type Project } from './Project';
import { treeOrder, type ObjectTree } from './hierarchy';
import { resolveObjects } from './instance';
import { isList, isStruct, type PropertyBag, type PropertyValue, tagged, tagOf, untag } from './Properties';
import { mapNested, type PropertyBag, type PropertyValue, tagged, tagOf, untag } from './Properties';
import type { SceneObject } from './SceneObject';
import { Recorder } from '../util/recorder';
@@ -108,19 +108,10 @@ export function anchorReferences(objects: readonly SceneObject[]): void {
* keep their identity, so a caller can tell whether anything changed.
*/
function withReferences(value: PropertyValue, swap: (ref: string) => string | undefined): PropertyValue {
if (tagOf(value) === 'object') {
const ref = referencedId(value);
return mapNested(value, (part) => {
if (tagOf(part) !== 'object') return undefined;
const ref = referencedId(part as PropertyValue);
const next = ref ? swap(ref) : undefined;
return next === undefined || next === ref ? value : objectReference(next);
}
if (isList(value)) {
const items = value.map((item) => withReferences(item, swap));
return items.some((item, i) => item !== value[i]) ? items : value;
}
if (isStruct(value) && tagOf(value) === undefined) {
const entries = Object.entries(value);
const mapped = entries.map(([key, field]) => [key, withReferences(field, swap)] as const);
return mapped.some(([, field], i) => field !== entries[i]![1]) ? Object.fromEntries(mapped) : value;
}
return value;
return next === undefined || next === ref ? part : objectReference(next);
}) as PropertyValue;
}
+1 -1
View File
@@ -16,7 +16,7 @@ export const GAME_SCALE_STEPS = [0.25, 0.5, 1, 2, 3, 4, 5, 6];
export const DEFAULT_GAME_SCALE: GameScale = 1;
export function isGameScale(value: unknown): value is GameScale {
function isGameScale(value: unknown): value is GameScale {
return value === 'auto' || value === 'fit' || GAME_SCALE_STEPS.includes(value as number);
}
+1 -1
View File
@@ -37,7 +37,7 @@ export function visibilityParts(type: PlaceableAssetType): VisibilityPart[] {
}
/** What a type shows until it is switched: all of it, except a name nothing showed before. */
export function defaultVisibility(type: PlaceableAssetType): TypeVisibility {
function defaultVisibility(type: PlaceableAssetType): TypeVisibility {
return { symbol: true, label: hasSceneIcon(type), shape: true };
}
+8 -13
View File
@@ -49,12 +49,13 @@ import {
type StructValue,
tagOf,
textOf,
withFieldRenamed,
withItemType,
} from './Properties';
import { findAsset, findAssetOf, type Project } from './Project';
export const PACK_STRUCT = 'PackStruct';
export const EXPAND_STRUCT = 'ExpandStruct';
const PACK_STRUCT = 'PackStruct';
const EXPAND_STRUCT = 'ExpandStruct';
/** Deeper than this only a cycle written by hand can go; it is cut there. */
const MAX_DEPTH = 32;
@@ -72,7 +73,7 @@ export function nodeStructType(node: GraphNode): string {
}
/** A declared variable as the struct field it becomes in every value of the type. */
export function fieldOfVariable(def: PropertyDef): StructFieldDef | undefined {
function fieldOfVariable(def: PropertyDef): StructFieldDef | undefined {
if (def.kind === 'struct')
return {
key: def.key,
@@ -90,7 +91,7 @@ export function typeFields(asset: StructAsset): StructFieldDef[] {
}
/** A new value of the type: every field at the default the asset declares for it. */
export function typeDefault(asset: StructAsset): StructValue {
function typeDefault(asset: StructAsset): StructValue {
return structOf(typeFields(asset), asset.props);
}
@@ -196,7 +197,7 @@ function holdersOf(
* `value` in the shape of `fields`: what it has keeps its value (brought to the field's kind), what
* it lacks takes the type's default, and what the type does not declare falls away.
*/
export function shapedStruct(
function shapedStruct(
project: Project,
fields: readonly StructFieldDef[],
value: PropertyValue | undefined,
@@ -280,7 +281,7 @@ function renamedItems(project: Project, value: PropertyValue, rename: FieldRenam
const path = [...inside, ...rename.path];
const at = valueAt(next, path);
if (isStruct(at) && rename.from in at)
next = withValueAt(next, path, renamedKey(at, rename.from, rename.to)) ?? next;
next = withValueAt(next, path, withFieldRenamed(at, rename.from, rename.to)) ?? next;
}
const out: Record<string, PropertyValue> = {};
for (const [key, item] of Object.entries(next as StructValue))
@@ -375,12 +376,6 @@ export interface FieldRename {
to: string;
}
function renamedKey(value: StructValue, from: string, to: string): StructValue {
const next: Record<string, FieldValue> = {};
for (const [key, item] of Object.entries(value)) next[key === from ? to : key] = item;
return next;
}
/** Carries a renamed field's values over, before the shapes are rebuilt – which would drop them. */
function applyRename(project: Project, rec: Recorder, rename: FieldRename): void {
const { from, to } = rename;
@@ -391,7 +386,7 @@ function applyRename(project: Project, rec: Recorder, rename: FieldRename): void
const value = holder.read();
const at = valueAt(value, path);
if (!isStruct(at) || !(from in at)) continue;
holder.write(withValueAt(value, path, renamedKey(at, from, to)) ?? value!);
holder.write(withValueAt(value, path, withFieldRenamed(at, from, to)) ?? value!);
}
}
for (const variable of everyVariable(project))
-8
View File
@@ -175,14 +175,6 @@ export function tilemapLayerNames(project: Project): string[] {
return [...new Set(names)];
}
/** The tiles a tilemap paints with, in the order they first appear – its palette in use. */
export function tilemapTileIds(asset: { layers: TilemapLayer[] }): string[] {
const ids: string[] = [];
for (const layer of asset.layers)
for (const id of Object.values(layer.cells)) if (id && !ids.includes(id)) ids.push(id);
return ids;
}
/**
* The cell a point in the tilemap's own frame falls into. The grid is centred on the object's
* position, as every footprint is, so the top-left corner lies half a map up and to the left.
+15 -19
View File
@@ -244,6 +244,15 @@ function passesFilter(tile: TileAsset, oneWay: OneWayFilter, material?: TileMate
return oneWay === true || tileOneWayAngle(tile) === oneWay;
}
/** The solid tiles painted on the map, each once, in the order the layers first name them. */
function solidTiles(project: Project, asset: TilemapAsset): TileAsset[] {
const ids = new Set(asset.layers.flatMap((layer) => cellsTileIds(layer.cells)));
return [...ids].flatMap((id) => {
const tile = findAssetOf(project, id, 'tile');
return tile && isTileSolid(tile) ? [tile] : [];
});
}
/** The surfaces of the solid tiles painted on the map that pass `oneWay`, each once. */
export function tileMaterials(
project: Project,
@@ -251,30 +260,17 @@ export function tileMaterials(
oneWay: OneWayFilter = false,
): TileMaterial[] {
const materials: TileMaterial[] = [];
const seen = new Set<string>();
for (const layer of asset.layers)
for (const tileId of cellsTileIds(layer.cells)) {
if (seen.has(tileId)) continue;
seen.add(tileId);
const tile = findAssetOf(project, tileId, 'tile');
if (!tile || !isTileSolid(tile) || !passesFilter(tile, oneWay)) continue;
const material = tileMaterial(tile);
if (!materials.some((known) => sameMaterial(known, material))) materials.push(material);
}
for (const tile of solidTiles(project, asset)) {
if (!passesFilter(tile, oneWay)) continue;
const material = tileMaterial(tile);
if (!materials.some((known) => sameMaterial(known, material))) materials.push(material);
}
return materials.sort((a, b) => a.friction - b.friction || a.bounciness - b.bounciness);
}
/** The angles of the solid one-way tiles painted on the map, each once, smallest first. */
export function oneWayAngles(project: Project, asset: TilemapAsset): number[] {
const angles = new Set<number>();
const seen = new Set<string>();
for (const layer of asset.layers)
for (const tileId of cellsTileIds(layer.cells)) {
if (seen.has(tileId)) continue;
seen.add(tileId);
const tile = findAssetOf(project, tileId, 'tile');
if (tile && isTileSolid(tile) && isTileOneWay(tile)) angles.add(tileOneWayAngle(tile));
}
const angles = new Set(solidTiles(project, asset).filter(isTileOneWay).map(tileOneWayAngle));
return [...angles].sort((a, b) => a - b);
}
+1 -10
View File
@@ -6,7 +6,7 @@
import { isKindWith } from '../properties/kinds';
import { schemaForAsset } from '../properties/PropertySchema';
import { referencesAny, trackDef } from './animation';
import type { AnimationAsset, Asset, TileAsset, TilemapAsset } from './Asset';
import type { AnimationAsset, Asset, TileAsset } from './Asset';
import { overrideSites } from './instance';
import { type ObjectHolder, objectHolders, type Project } from './Project';
import type { SceneObject } from './SceneObject';
@@ -68,15 +68,6 @@ export function tilesUsing(project: Project, ids: readonly string[]): TileAsset[
);
}
/** The tilemaps painted with any of these tiles – intrinsic data, like a tile's pictures. */
export function tilemapsUsing(project: Project, ids: readonly string[]): TilemapAsset[] {
const wanted = new Set(ids);
return project.assets.filter(
(a): a is TilemapAsset =>
a.type === 'tilemap' && a.layers.some((l) => Object.values(l.cells).some((id) => wanted.has(id))),
);
}
/** The animations keying any of these ids – intrinsic data, which `findPropertyUsages` does not see. */
export function animationsUsing(project: Project, ids: readonly string[]): AnimationAsset[] {
const wanted = new Set(ids);
+1 -9
View File
@@ -17,6 +17,7 @@ import { ClipType, FillRule, type PathD, type PathsD } from 'clipper2-ts/dist/Co
import { ClipperD, type PolyPathD, PolyTreeD } from 'clipper2-ts/dist/Engine.js';
import type { VectorRing, VectorShape } from './Asset';
import type { Vec2 } from './Properties';
import { cubicAt } from '../util/vec';
import { handleAt, isDrawableRing } from './vectorart';
import {
addCurve,
@@ -162,12 +163,3 @@ function curveSteps(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2): number {
);
return Math.min(MAX_CURVE_STEPS, Math.max(1, Math.ceil(Math.sqrt((0.75 * m) / FLATTEN_TOLERANCE))));
}
function cubicAt(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec2 {
const u = 1 - t;
const a = u * u * u;
const b = 3 * u * u * t;
const c = 3 * u * t * t;
const d = t * t * t;
return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
}
+7 -30
View File
@@ -11,6 +11,7 @@
*/
import type { VectorPoint } from './Asset';
import type { Vec2 } from './Properties';
import { cubicAt, splitCubic } from '../util/vec';
/** How far a sampled curve may stray from the true one, in canvas pixels. */
export const FLATTEN_TOLERANCE = 0.2;
@@ -149,10 +150,11 @@ function edgeOn(from: PointOnCurve[], to: PointOnCurve[], table: CurveTable): Cu
/** Whether the piece of `segment` from `t0` to `t1` hugs the straight line between its two ends. */
function staysOnCurve(segment: CurveSegment, t0: number, t1: number): boolean {
const a = cubicAt(segment, t0);
const b = cubicAt(segment, t1);
const at = (t: number) => cubicAt(segment.p0, segment.p1, segment.p2, segment.p3, t);
const a = at(t0);
const b = at(t1);
for (let step = 1; step < 4; step++) {
const point = cubicAt(segment, t0 + (t1 - t0) * (step / 4));
const point = at(t0 + (t1 - t0) * (step / 4));
const along = onChord(a, b, point);
if (!along || along.gap > CHORD_SLACK) return false;
}
@@ -203,31 +205,6 @@ function build(
function subCurve(segment: CurveSegment, t0: number, t1: number): Vec2[] {
if (t0 > t1) return subCurve(segment, t1, t0).reverse();
const whole = [segment.p0, segment.p1, segment.p2, segment.p3];
const left = t1 >= 1 ? whole : split(whole, t1).left;
return t1 <= 0 ? left : split(left, t0 / t1).right;
}
/** de Casteljau: the cubic cut in two at `t`, both halves as control points. */
function split(p: Vec2[], t: number): { left: Vec2[]; right: Vec2[] } {
const a = lerp(p[0]!, p[1]!, t);
const b = lerp(p[1]!, p[2]!, t);
const c = lerp(p[2]!, p[3]!, t);
const d = lerp(a, b, t);
const e = lerp(b, c, t);
const mid = lerp(d, e, t);
return { left: [p[0]!, a, d, mid], right: [mid, e, c, p[3]!] };
}
function lerp(a: Vec2, b: Vec2, t: number): Vec2 {
return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
}
function cubicAt(segment: { p0: Vec2; p1: Vec2; p2: Vec2; p3: Vec2 }, t: number): Vec2 {
const u = 1 - t;
const a = u * u * u;
const b = 3 * u * u * t;
const c = 3 * u * t * t;
const d = t * t * t;
const { p0, p1, p2, p3 } = segment;
return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
const left = t1 >= 1 ? whole : splitCubic(whole, t1).left;
return t1 <= 0 ? left : splitCubic(left, t0 / t1).right;
}