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

+6 -18
View File
@@ -15,7 +15,7 @@ import { DEFAULT_PALETTE, PIXEL_CANVAS_DEFAULT } from '../model/pixelart';
import { isSoundFile } from '../model/sound';
import { removeSubtrees } from '../model/hierarchy';
import type { PropertyBag, PropertyValue } from '../model/Properties';
import { findAssetOf, objectHolders, type Project } from '../model/Project';
import { objectHolders, type Project } from '../model/Project';
import {
type Scope,
scopeOf,
@@ -29,7 +29,7 @@ import { isTextureFile } from '../model/texture';
import { coerceValue, defaultsFor, initialOf, initialPropsFor } from '../properties/PropertySchema';
import { type Removed, removeById, removeFirst, restoreAt } from '../util/list';
import { type Command, CommandError } from './Command';
import { requireAsset, requirePropDef, requireStateMachine } from './require';
import { requireAsset, requirePropDef, requireStateMachine, requireVariablesAsset } from './require';
import { SetBagValueCommand } from './SetBagValueCommand';
export function buildAsset(type: AssetType, name: string, id = newId()): Asset {
@@ -314,19 +314,13 @@ export class SetVariablesPersistentCommand implements Command {
}
execute(project: Project): void {
const asset = this.target(project);
const asset = requireVariablesAsset(project, this.assetId);
this.previous = asset.persistent === true;
setPersistent(asset, this.persistent);
}
undo(project: Project): void {
setPersistent(this.target(project), this.previous);
}
private target(project: Project): VariablesAsset {
const asset = findAssetOf(project, this.assetId, 'variables');
if (!asset) throw new CommandError(`Variables ${this.assetId} not found`);
return asset;
setPersistent(requireVariablesAsset(project, this.assetId), this.previous);
}
}
@@ -353,7 +347,7 @@ export class SetVariablesScopeCommand implements Command {
}
execute(project: Project): void {
const asset = this.target(project);
const asset = requireVariablesAsset(project, this.assetId);
this.previous = sharedScopeOf(asset);
this.wasPersistent = asset.persistent === true;
setSharedScope(asset, this.scope);
@@ -361,16 +355,10 @@ export class SetVariablesScopeCommand implements Command {
}
undo(project: Project): void {
const asset = this.target(project);
const asset = requireVariablesAsset(project, this.assetId);
setSharedScope(asset, this.previous);
setPersistent(asset, this.wasPersistent);
}
private target(project: Project): VariablesAsset {
const asset = findAssetOf(project, this.assetId, 'variables');
if (!asset) throw new CommandError(`Variables ${this.assetId} not found`);
return asset;
}
}
/**
+7
View File
@@ -10,6 +10,7 @@ import type {
TilemapAsset,
TilemapLayer,
VariableOwnerAsset,
VariablesAsset,
VectorArtAsset,
VectorShape,
} from '../model/Asset';
@@ -131,6 +132,12 @@ export function requireCurve(project: Project, assetId: string): CurveAsset {
return asset;
}
export function requireVariablesAsset(project: Project, assetId: string): VariablesAsset {
const asset = findAssetOf(project, assetId, 'variables');
if (!asset) throw new CommandError(`Variables ${assetId} not found`);
return asset;
}
export function requireStateMachine(project: Project, assetId: string): StateMachineAsset {
const asset = findAssetOf(project, assetId, 'statemachine');
if (!asset) throw new CommandError(`State machine ${assetId} not found`);
+15 -19
View File
@@ -197,6 +197,18 @@ function variableOfField(field: StructFieldDef, value: PropertyValue | undefined
return def;
}
/** A new Struct asset declaring `fields`, each at the value `values` holds for it, named after `name`. */
function structAssetFrom(
project: Project,
fields: readonly StructFieldDef[],
values: Readonly<Record<string, PropertyValue>>,
name: string,
): StructAsset {
const variables = fields.map((f) => variableOfField(f, values[f.key]));
const props = Object.fromEntries(variables.map((v) => [v.key, v.default]));
return { id: newId(), type: 'struct', name: nextAssetName(project, name), props, variables };
}
/**
* Turns the fields a struct holds by itself into a Struct asset, and types the struct with it. The
* value it holds now becomes the asset's defaults, so the place reads exactly as before.
@@ -212,11 +224,6 @@ export class MakeStructTypeCommand implements Command {
private readonly path: readonly string[],
) {}
/** The asset made, once the command ran – for the caller to select it. */
get assetId(): string {
return this.asset?.id ?? '';
}
execute(project: Project): void {
const owner = requireVariableOwner(project, this.ownerId);
const def = requireStructVariable(project, this.ownerId, this.key);
@@ -226,11 +233,8 @@ export class MakeStructTypeCommand implements Command {
throw new CommandError('This struct has a type already');
if (!this.asset) {
const value = valueAt(owner.props[def.key] ?? def.default, this.path);
const fields = isStruct(value) ? value : {};
const variables = at.fields.map((f) => variableOfField(f, fields[f.key]));
const props = Object.fromEntries(variables.map((v) => [v.key, v.default]));
const name = nextAssetName(project, this.path.at(-1) ?? this.key);
this.asset = { id: newId(), type: 'struct', name, props, variables };
const values = isStruct(value) ? value : {};
this.asset = structAssetFrom(project, at.fields, values, this.path.at(-1) ?? this.key);
}
project.assets.push(this.asset);
this.rec = new Recorder();
@@ -325,10 +329,6 @@ export class MakeListItemTypeCommand implements Command {
constructor(private readonly target: ListTarget) {}
get assetId(): string {
return this.asset?.id ?? '';
}
execute(project: Project): void {
const { def, decl } = requireListDecl(project, this.target);
if (decl.itemType && structAssetOf(project, decl.itemType))
@@ -344,10 +344,7 @@ export class MakeListItemTypeCommand implements Command {
values[field.key] = item[field.key]!;
fields.push(field);
}
const variables = fields.map((f) => variableOfField(f, values[f.key]));
const props = Object.fromEntries(variables.map((v) => [v.key, v.default]));
const name = nextAssetName(project, this.target.path.at(-1) ?? this.target.key);
this.asset = { id: newId(), type: 'struct', name, props, variables };
this.asset = structAssetFrom(project, fields, values, this.target.path.at(-1) ?? this.target.key);
}
project.assets.push(this.asset);
this.rec = new Recorder();
@@ -370,7 +367,6 @@ function itemFieldDefs(item: StructValue): StructFieldDef[] {
return { key, kind, fields: itemFieldDefs(value), ...(typeId ? { structType: typeId } : {}) };
}
if (kind === 'struct') return { key, kind, fields: [] };
if (kind === 'list') return { key, kind };
return { key, kind };
});
}
+13 -20
View File
@@ -4,8 +4,11 @@ import {
type PropertyBag,
type PropertyValue,
type StructValue,
withFieldRenamed,
withoutField,
} from '../model/Properties';
import {
type BehaviorAsset,
isKeptVariable,
isPrivateVariable,
setKeptVariable,
@@ -180,6 +183,13 @@ export class RenameVariableCommand extends RenameCommand {
}
}
/** The behavior, once it is known to declare `key`. */
function requireBehaviorVariable(project: Project, assetId: string, key: string): BehaviorAsset {
const asset = requireBehavior(project, assetId);
if (!asset.variables.some((v) => v.key === key)) throw new CommandError(`Variable "${key}" not found`);
return asset;
}
/** Whether a behavior's variable carries on from one `Run behavior` call to the next (#229). */
export class SetVariableKeptCommand implements Command {
readonly label: string;
@@ -194,9 +204,7 @@ export class SetVariableKeptCommand implements Command {
}
execute(project: Project): void {
const asset = requireBehavior(project, this.assetId);
if (!asset.variables.some((v) => v.key === this.key))
throw new CommandError(`Variable "${this.key}" not found`);
const asset = requireBehaviorVariable(project, this.assetId, this.key);
this.previous = isKeptVariable(asset, this.key);
setKeptVariable(asset, this.key, this.kept);
}
@@ -224,9 +232,7 @@ export class SetVariablePrivateCommand implements Command {
}
execute(project: Project): void {
const asset = requireBehavior(project, this.assetId);
if (!asset.variables.some((v) => v.key === this.key))
throw new CommandError(`Variable "${this.key}" not found`);
const asset = requireBehaviorVariable(project, this.assetId, this.key);
this.previous = isPrivateVariable(asset, this.key);
setPrivateVariable(asset, this.key, this.hidden);
this.overrides = this.hidden ? takeOverrides(project, this.assetId, this.key) : [];
@@ -362,19 +368,6 @@ function bagHolder(id: string, optional: boolean, bag: PropertyBag, key: string)
return { id, optional, read: () => bag[key], write: (value: PropertyValue) => (bag[key] = value) };
}
function withoutField(value: StructValue, key: string): StructValue {
const next: Record<string, FieldValue> = { ...value };
delete next[key];
return next;
}
/** Rebuilt rather than reassigned, so the field keeps its place in the value as well. */
function renameField(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;
}
export class AddStructFieldCommand implements Command {
readonly label: string;
@@ -471,6 +464,6 @@ export class RenameStructFieldCommand extends RenameCommand {
if (fields.some((f) => f.key === to)) throw new CommandError(`Field "${to}" already exists`);
owner.setFields(fields.map((f) => (f.key === from ? { ...f, key: to } : f)));
for (const site of structSites(project, this.assetId, this.key, this.path))
site.write(renameField(site.read(), from, to));
site.write(withFieldRenamed(site.read(), from, to));
}
}