Files
feuerwerk/src/core/model/hierarchy.ts
T
adminandClaude Opus 5.5 bc688f3efc
game-maker / gate (push) Successful in 3m50s
game-maker / suite (push) Successful in 12m3s
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>
2026-09-29 16:16:37 +02:00

209 lines
7.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { type Removed, removeWhere } from '../util/list';
import type { ObjectGroup, SceneObject } from './SceneObject';
import { descendantsBelow, parentChain } from './walk';
/**
* `objects` stays a flat list in creation order; the tree is implied by `SceneObject.parentId`.
* Anything holding such a list fits – a scene, or the template inside a container asset.
*/
export interface ObjectTree {
objects: SceneObject[];
/** Hierarchy folders for top-level objects (#241) – they order the tree but never shape it. */
groups?: ObjectGroup[];
}
export function findObject(tree: ObjectTree, id: string): SceneObject | undefined {
return tree.objects.find((o) => o.id === id);
}
function childrenOf(tree: ObjectTree, parentId: string): SceneObject[] {
return tree.objects.filter((o) => o.parentId === parentId);
}
/** Children of `parentId` (`''` = top level) in sibling order – what a reorder rearranges. */
export function childIdsOf(tree: ObjectTree, parentId: string): string[] {
return childrenOf(tree, parentId).map((o) => o.id);
}
function parentOf(tree: ObjectTree, object: SceneObject): SceneObject | undefined {
return object.parentId ? findObject(tree, object.parentId) : undefined;
}
/** Depth-first, parents before children. */
export function descendantsOf(tree: ObjectTree, id: string): SceneObject[] {
return descendantsBelow(
id,
(parentId) => childrenOf(tree, parentId),
(o) => o.id,
);
}
export function subtreeIds(tree: ObjectTree, rootIds: Iterable<string>): Set<string> {
const ids = new Set<string>();
for (const rootId of rootIds) {
ids.add(rootId);
for (const child of descendantsOf(tree, rootId)) ids.add(child.id);
}
return ids;
}
/** Returns the removed objects with their former indices (see `restoreAt`). */
export function removeSubtrees(tree: ObjectTree, rootIds: readonly string[]): Removed<SceneObject>[] {
const ids = subtreeIds(tree, rootIds);
return removeWhere(tree.objects, (o) => ids.has(o.id));
}
/** An object and every parent above it, nearest first. */
function chainOf(tree: ObjectTree, object: SceneObject): SceneObject[] {
return [...parentChain(object, (o) => parentOf(tree, o))];
}
/** Nearest parent first. */
export function ancestorIdsOf(tree: ObjectTree, id: string): string[] {
const object = findObject(tree, id);
return object
? chainOf(tree, object)
.slice(1)
.map((o) => o.id)
: [];
}
export function isSelfOrAncestor(tree: ObjectTree, ancestorId: string, objectId: string): boolean {
const object = findObject(tree, objectId);
return object !== undefined && chainOf(tree, object).some((o) => o.id === ancestorId);
}
/** Of the given ids, those with no ancestor among the ids themselves. */
export function subtreeRoots(tree: ObjectTree, ids: readonly string[]): string[] {
const set = new Set(ids);
return ids.filter((id) => !ancestorIdsOf(tree, id).some((ancestorId) => set.has(ancestorId)));
}
export interface TreeEntry {
object: SceneObject;
depth: number;
}
/**
* The stored list with the members of each group moved up behind the first of them: a group is
* listed – and drawn at equal `z` – as one block wherever its first member stands (#241).
*/
export function groupedOrder(objects: readonly SceneObject[]): readonly SceneObject[] {
const blocks = new Map<string, SceneObject[]>();
for (const object of objects) {
if (object.parentId || !object.groupId) continue;
const block = blocks.get(object.groupId);
if (block) block.push(object);
else blocks.set(object.groupId, [object]);
}
if (blocks.size === 0) return objects;
const result: SceneObject[] = [];
for (const object of objects) {
const block = object.parentId || !object.groupId ? undefined : blocks.get(object.groupId);
if (!block) result.push(object);
else if (block[0] === object) result.push(...block);
}
return result;
}
/**
* Top-level objects in storage order, groups kept together, each followed by its subtree – the
* order the hierarchy panel shows and the tie-break order for equal `z`.
*/
export function treeOrder(tree: ObjectTree): TreeEntry[] {
const result: TreeEntry[] = [];
const ordered = groupedOrder(tree.objects);
const ids = new Set(tree.objects.map((o) => o.id));
const visit = (parentId: string, depth: number) => {
for (const object of ordered) {
if (object.parentId !== parentId) continue;
result.push({ object, depth });
visit(object.id, depth + 1);
}
};
visit('', 0);
// Objects whose parent is missing are listed at the top level rather than dropped.
for (const object of ordered) {
if (object.parentId && !ids.has(object.parentId) && !result.some((e) => e.object === object))
result.push({ object, depth: 0 });
}
return result;
}
export function findGroup(tree: ObjectTree, groupId: string): ObjectGroup | undefined {
return tree.groups?.find((g) => g.id === groupId);
}
/**
* The first group of that name, made at the end of the list when there is none – where a run puts
* the objects it spawns at the top level (#265), so hundreds of them fold into one row.
*/
export function groupNamed(tree: ObjectTree, name: string, newGroupId: () => string): ObjectGroup {
const found = tree.groups?.find((g) => g.name === name);
if (found) return found;
const group = { id: newGroupId(), name };
tree.groups = [...(tree.groups ?? []), group];
return group;
}
/** The top-level objects listed in the group, in tree order. */
export function groupMemberIds(tree: ObjectTree, groupId: string): string[] {
return groupedOrder(tree.objects)
.filter((o) => !o.parentId && o.groupId === groupId)
.map((o) => o.id);
}
/** Only top-level objects go into a group – a child is listed under its parent. */
export function canGroup(tree: ObjectTree, ids: readonly string[]): boolean {
return ids.length > 0 && ids.every((id) => findObject(tree, id)?.parentId === '');
}
/** The list id of a group's row: never an object id, which has no colon. */
export function groupRowId(groupId: string): string {
return `group:${groupId}`;
}
export function groupIdOfRow(rowId: string): string | null {
return rowId.startsWith('group:') ? rowId.slice('group:'.length) : null;
}
export type HierarchyRow =
| { kind: 'object'; object: SceneObject; depth: number; hasChildren: boolean }
| { kind: 'group'; group: ObjectGroup; memberIds: string[]; depth: number };
/**
* Tree order with a row in front of each group and the subtrees of collapsed objects and groups
* left out. `expanded` holds object ids and group row ids; anything not in it counts as collapsed,
* so a freshly loaded scene shows only its top level.
*/
export function hierarchyRows(tree: ObjectTree, expanded: ReadonlySet<string>): HierarchyRow[] {
const parents = new Set(tree.objects.map((o) => o.parentId).filter(Boolean));
const groups = new Map((tree.groups ?? []).map((g) => [g.id, g]));
const result: HierarchyRow[] = [];
// Depth of the collapsed row whose subtree is being skipped (-1 = showing rows).
let collapsedAt = -1;
// The group of the top-level object the current entries belong to, and whether it is folded.
let group: ObjectGroup | undefined;
let groupFolded = false;
for (const { object, depth } of treeOrder(tree)) {
if (depth === 0) {
const next = object.parentId ? undefined : groups.get(object.groupId ?? '');
if (next && next !== group) {
const rowId = groupRowId(next.id);
result.push({ kind: 'group', group: next, memberIds: groupMemberIds(tree, next.id), depth: 0 });
groupFolded = !expanded.has(rowId);
}
group = next;
}
if (group && groupFolded) continue;
if (collapsedAt >= 0) {
if (depth > collapsedAt) continue;
collapsedAt = -1;
}
const hasChildren = parents.has(object.id);
result.push({ kind: 'object', object, depth: depth + (group ? 1 : 0), hasChildren });
if (hasChildren && !expanded.has(object.id)) collapsedAt = depth;
}
return result;
}