From 76dcab175b9016d878f730c91417dae2f5f5e972 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 10 Nov 2026 11:22:51 +0100 Subject: [PATCH] Time procedural bakes in the studio with a median-of-five meter Authors could not see what a procedural object costs generation. The Procedural view now bakes the chosen entry five times in the background, keeps the median run, and rates it Light, Moderate or Heavy against a server tick, with each stage's time in the tooltip. SceneView gains isBaked and timeBake (one run, a BakeRun); the studio asks five times so a newer choice stops the rest. No pins moved: generation bakes with BakeProfile.NONE and nothing in packs changed. v3: 9e30508e3 7d240ddf8 --- api/CONTRACTS.md | 2 +- api/README.md | 3 + .../main/java/com/volmit/tooling/BakeRun.java | 36 ++++++++ .../java/com/volmit/tooling/SceneView.java | 14 +++ .../java/com/volmit/tooling/BakeRunTest.java | 67 ++++++++++++++ .../iris/core/studio/bridge/StudioBridge.java | 21 ++++- .../iris/core/studio/scene/StudioScenes.java | 15 ++++ .../objects/ProceduralObjectScenes.java | 22 +++++ .../src/renderer/src/bridge/BridgeClient.ts | 6 ++ studio/src/renderer/src/bridge/types.ts | 9 +- .../src/renderer/src/scene/bakeTiming.test.ts | 81 +++++++++++++++++ studio/src/renderer/src/scene/bakeTiming.ts | 87 +++++++++++++++++++ studio/src/renderer/src/studio/BakeMeter.tsx | 87 +++++++++++++++++++ .../src/renderer/src/studio/SceneStudio.tsx | 4 + 14 files changed, 448 insertions(+), 6 deletions(-) create mode 100644 api/api/src/main/java/com/volmit/tooling/BakeRun.java create mode 100644 api/api/src/test/java/com/volmit/tooling/BakeRunTest.java create mode 100644 studio/src/renderer/src/scene/bakeTiming.test.ts create mode 100644 studio/src/renderer/src/scene/bakeTiming.ts create mode 100644 studio/src/renderer/src/studio/BakeMeter.tsx diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index 9b36ee862..4c78a7916 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -46,7 +46,7 @@ types that carry them and lists what the Iris adapter still owes. | Dense chunk output | `Hunk`, `GenerationContext.blocks`, reference `ArrayHunk` | | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | | Sparse geometry | `GeneratedObject` | -| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | +| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `BakeRun` (`Stage`), `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | | Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender`, `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`), host `CommandRegistration` in `FeatureCatalog.commands()` | | Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | | Typed generation and persistent storage | `mantle` package | diff --git a/api/README.md b/api/README.md index f8b95b127..55dcc472d 100644 --- a/api/README.md +++ b/api/README.md @@ -518,6 +518,9 @@ final class RuinScenes implements SceneView { - A `SceneView` lists entries (`SceneEntry`) and gives each variant's blocks as a `GeneratedObject`, drawn in 3D. A `PatternView` lists entries (`PatternEntry`) and gives the blocks one lays over a `PatternArea` at a depth as a `BlockPattern`, drawn from above. `StudioView` is sealed to these two kinds: the studio draws nothing else. +- A `SceneView` whose entries are baked from settings says so (`isBaked`) and times a bake on request (`timeBake`, a + `BakeRun` with a time per stage). One call is one run; the studio asks five times off the server's threads and keeps + the median. - A view's id is the module's id or starts with it and `/`. A second view with an id already registered fails the pack load, naming both modules. - The studio asks from its own threads, several at once, for a world of the pack it shows. A view keeps what it diff --git a/api/api/src/main/java/com/volmit/tooling/BakeRun.java b/api/api/src/main/java/com/volmit/tooling/BakeRun.java new file mode 100644 index 000000000..ea10fd2eb --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/BakeRun.java @@ -0,0 +1,36 @@ +package com.volmit.tooling; + +import java.util.List; +import java.util.Objects; + +/** + * One timed bake of everything an entry is built from, as {@link SceneView#timeBake} reports it. + * + * @param variantCount how many variants the run baked + * @param stages the steps a variant is baked in, in order, each with its time added up over every variant + */ +public record BakeRun(int variantCount, List stages) { + public BakeRun { + Objects.requireNonNull(stages, "stages"); + if (variantCount < 0) { + throw new IllegalArgumentException("A bake run cannot have " + variantCount + " variants"); + } + stages = List.copyOf(stages); + } + + /** + * @param label what the studio calls the step, such as {@code Paint} + * @param nanos how long the step took, in nanoseconds + */ + public record Stage(String label, long nanos) { + public Stage { + Objects.requireNonNull(label, "label"); + if (label.isBlank()) { + throw new IllegalArgumentException("A bake stage needs a label"); + } + if (nanos < 0L) { + throw new IllegalArgumentException("Bake stage " + label + " took " + nanos + " ns; a time is never negative"); + } + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/SceneView.java b/api/api/src/main/java/com/volmit/tooling/SceneView.java index 3edf8e00a..dfbbaa7ea 100644 --- a/api/api/src/main/java/com/volmit/tooling/SceneView.java +++ b/api/api/src/main/java/com/volmit/tooling/SceneView.java @@ -21,4 +21,18 @@ public non-sealed interface SceneView extends StudioView { * @param variant from 0 to the entry's {@link SceneEntry#variants()}, exclusive */ Optional scene(PackWorld world, String key, int variant); + + /** Whether the entries are baked from settings, which costs generation time {@link #timeBake} can measure. */ + default boolean isBaked() { + return false; + } + + /** + * Bakes the entry named {@code key} once more the way generation does, without keeping the result, and times each + * step. The studio asks several times and keeps the median, so one call is one run. Asked off the server's threads; + * empty when the pack has no such entry or the view does not bake. + */ + default Optional timeBake(PackWorld world, String key) { + return Optional.empty(); + } } diff --git a/api/api/src/test/java/com/volmit/tooling/BakeRunTest.java b/api/api/src/test/java/com/volmit/tooling/BakeRunTest.java new file mode 100644 index 000000000..f27cc9d71 --- /dev/null +++ b/api/api/src/test/java/com/volmit/tooling/BakeRunTest.java @@ -0,0 +1,67 @@ +package com.volmit.tooling; + +import com.volmit.object.GeneratedObject; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BakeRunTest { + @Test + void keepsItsStagesInOrderAndApartFromTheListItWasGiven() { + List given = new ArrayList<>(List.of(new BakeRun.Stage("Parts", 5L), new BakeRun.Stage("Build", 7L))); + BakeRun run = new BakeRun(3, given); + given.clear(); + + assertEquals(List.of("Parts", "Build"), run.stages().stream().map(BakeRun.Stage::label).toList()); + assertThrows(UnsupportedOperationException.class, () -> run.stages().clear()); + } + + @Test + void refusesATimeBelowZeroAndAStageWithoutALabel() { + assertThrows(IllegalArgumentException.class, () -> new BakeRun.Stage("Parts", -1L)); + assertThrows(IllegalArgumentException.class, () -> new BakeRun.Stage(" ", 1L)); + assertThrows(IllegalArgumentException.class, () -> new BakeRun(-1, List.of())); + } + + @Test + void aViewThatDoesNotBakeSaysSoAndTimesNothing() { + SceneView plain = new SceneView() { + @Override + public ResourceId id() { + return ResourceId.parse("test:plain"); + } + + @Override + public String label() { + return "Plain"; + } + + @Override + public String description() { + return "Plain"; + } + + @Override + public List entries(PackWorld world) { + return List.of(); + } + + @Override + public Optional scene(PackWorld world, String key, int variant) { + return Optional.empty(); + } + }; + + assertFalse(plain.isBaked()); + assertTrue(plain.timeBake(null, "any").isEmpty()); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java index c372a184b..a03fde2c6 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java @@ -53,6 +53,7 @@ import com.volmit.object.GeneratedObject; import com.volmit.tooling.BlockPattern; import com.volmit.tooling.PatternArea; import com.volmit.tooling.PatternEntry; +import com.volmit.tooling.BakeRun; import com.volmit.tooling.SceneEntry; import java.io.IOException; @@ -235,6 +236,7 @@ public final class StudioBridge implements AutoCloseable { case "scene-edit" -> sendJson(exchange, STATUS_OK, sceneEdit(exchange, query)); case "scene-write" -> sendJson(exchange, STATUS_OK, sceneWrite(exchange, query)); case "scene-entries" -> sendJson(exchange, STATUS_OK, sceneEntries(get(exchange).engine(), query)); + case "scene-bake" -> sendJson(exchange, STATUS_OK, sceneBake(get(exchange).engine(), query)); case "scene" -> sendBytes(exchange, "application/octet-stream", scene(get(exchange).engine(), query)); case "saved-worlds" -> sendJson(exchange, STATUS_OK, savedWorlds(exchange)); case "saved-start" -> sendJson(exchange, STATUS_OK, savedStart(exchange, query)); @@ -335,8 +337,9 @@ public final class StudioBridge implements AutoCloseable { private static List sceneViews(Engine engine) { StudioEditors editors = StudioEditors.of(engine); - return StudioScenes.of(engine).views().stream() - .map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id()))) + StudioScenes scenes = StudioScenes.of(engine); + return scenes.views().stream() + .map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id()), scenes.isBaked(view.id()))) .toList(); } @@ -398,6 +401,16 @@ public final class StudioBridge implements AutoCloseable { } } + private static BakeRun sceneBake(Engine engine, Query query) { + String key = query.text("key"); + try { + return StudioScenes.of(engine).timeBake(query.text("view"), key) + .orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No bake to time for " + key)); + } catch (NoSuchElementException unknown) { + throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage()); + } + } + private byte[] scene(Engine engine, Query query) { String key = query.text("key"); Optional scene; @@ -738,8 +751,8 @@ public final class StudioBridge implements AutoCloseable { private record ErrorBody(String error) { } - /** A scene view as the studio lists it; {@code editable} when its entries can be edited as nodes. */ - private record SceneViewInfo(String id, String label, String description, boolean editable) { + /** A scene view as the studio lists it; {@code editable} when its entries can be edited as nodes, {@code baked} when their bake can be timed. */ + private record SceneViewInfo(String id, String label, String description, boolean editable, boolean baked) { } /** A {@link SceneEntry} as the studio reads it, with a blank group for none. */ diff --git a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java index 3423641ab..55bfe9448 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java +++ b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java @@ -20,6 +20,7 @@ package art.arcane.iris.core.studio.scene; import art.arcane.iris.engine.framework.Engine; import com.volmit.object.GeneratedObject; +import com.volmit.tooling.BakeRun; import com.volmit.tooling.SceneEntry; import com.volmit.tooling.SceneView; @@ -56,4 +57,18 @@ public final class StudioScenes { public Optional scene(String viewId, String key, int variant) { return views.ask(viewId, "build " + key, view -> view.scene(views.world(), key, variant)); } + + /** @throws NoSuchElementException when no module registered a scene view {@code viewId} */ + public boolean isBaked(String viewId) { + return views.ask(viewId, "say whether it bakes", SceneView::isBaked); + } + + /** + * One timed bake of an entry; empty when the view has no such entry or does not bake. + * + * @throws NoSuchElementException when no module registered a scene view {@code viewId} + */ + public Optional timeBake(String viewId, String key) { + return views.ask(viewId, "time the bake of " + key, view -> view.timeBake(views.world(), key)); + } } diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java index ea1c2dd29..8bb14c674 100644 --- a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java +++ b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java @@ -18,12 +18,14 @@ package art.arcane.iris.modules.objects; +import art.arcane.iris.engine.procedural.BakeProfile; import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.engine.procedural.ProceduralVariants; import art.arcane.iris.engine.procedural.part.ProceduralObject; import com.volmit.object.GeneratedObject; import com.volmit.object.PlaceableObject; import com.volmit.resource.ResourceId; +import com.volmit.tooling.BakeRun; import com.volmit.tooling.EditableSceneView; import com.volmit.tooling.JsonText; import com.volmit.tooling.NodeGraph; @@ -31,6 +33,7 @@ import com.volmit.tooling.SceneEntry; import com.volmit.tooling.SceneFile; import com.volmit.world.PackWorld; +import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -73,6 +76,18 @@ public final class ProceduralObjectScenes implements EditableSceneView { .map(PlaceableObject::geometry); } + @Override + public boolean isBaked() { + return true; + } + + @Override + public Optional timeBake(PackWorld world, String key) { + return ProceduralObjectCatalog.of(world).variants(ProceduralObjectCatalog.KEY_PREFIX + key) + .map(ProceduralVariants::profileBake) + .map(ProceduralObjectScenes::runOf); + } + @Override public Optional fileOf(PackWorld world, String key) { ResourceId id = world.resources().idOf(key); @@ -89,6 +104,13 @@ public final class ProceduralObjectScenes implements EditableSceneView { return ProceduralObjectGraph.of(key.substring(key.lastIndexOf(FOLDER_SEPARATOR) + 1), text, read); } + private static BakeRun runOf(BakeProfile profile) { + List stages = Arrays.stream(BakeProfile.Stage.values()) + .map(stage -> new BakeRun.Stage(stage.label(), profile.nanos(stage))) + .toList(); + return new BakeRun(profile.variantCount(), stages); + } + private static SceneEntry entryOf(ProceduralVariants variants) { String path = variants.path(); int lastSeparator = path.lastIndexOf(FOLDER_SEPARATOR); diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index f094118a5..ff6752e69 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -4,6 +4,7 @@ import { decodePattern } from './patternDecoding' import { decodeSavedTile } from './savedTileDecoding' import { decodeTile } from './tileDecoding' import type { + BakeRun, EditorState, GraphEdit, MapHover, @@ -161,6 +162,11 @@ export class BridgeClient { return this.json(`scene-entries?${new URLSearchParams({ view: viewId })}`) } + /** Bakes the entry once more and times each step; one run of the median the studio shows. */ + sceneBake(viewId: string, key: string, signal?: AbortSignal): Promise { + return this.json(`scene-bake?${new URLSearchParams({ view: viewId, key })}`, { signal }) + } + async scene(viewId: string, key: string, variant: number, signal?: AbortSignal): Promise { const response = await this.fetch(`scene?${new URLSearchParams({ view: viewId, key, variant: String(variant) })}`, { signal }) return decodeScene(await response.arrayBuffer()) diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index a428efa21..c6ccfbf54 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -33,9 +33,16 @@ export interface SceneEntry { variants: number } -/** A scene view as the server lists it; `editable` when its entries can be edited as nodes. */ +/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `baked` when their bake can be timed. */ export interface SceneViewInfo extends ModuleViewInfo { editable: boolean + baked: boolean +} + +/** One timed bake of a scene entry (IrisApi BakeRun): a time per step, added up over every variant. */ +export interface BakeRun { + variantCount: number + stages: { label: string; nanos: number }[] } /** Where a value sits in a JSON file: member names and element indices from the root. */ diff --git a/studio/src/renderer/src/scene/bakeTiming.test.ts b/studio/src/renderer/src/scene/bakeTiming.test.ts new file mode 100644 index 000000000..7c1e4c283 --- /dev/null +++ b/studio/src/renderer/src/scene/bakeTiming.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest' +import type { BakeRun } from '../bridge/types' +import { BAKE_RUN_COUNT, bakeWeightOf, formatMillis, measureBake, medianRun, meterFill, runMillis, slowestStageIndex } from './bakeTiming' + +const NANOS_PER_MILLI = 1_000_000 + +function runOf(...stageMillis: number[]): BakeRun { + return { variantCount: 4, stages: stageMillis.map((millis, index) => ({ label: `Stage ${index}`, nanos: millis * NANOS_PER_MILLI })) } +} + +describe('bake timing', () => { + it('adds the stages of a run up to its time in milliseconds', () => { + expect(runMillis(runOf(2, 3, 5))).toBe(10) + }) + + it('keeps the run in the middle by time, not the fastest, the slowest or the first', () => { + const slowFirstRun = runOf(900) + const median = runOf(40) + const runs = [slowFirstRun, runOf(10), runOf(300), median, runOf(25)] + expect(medianRun(runs)).toBe(median) + expect(runs[0]).toBe(slowFirstRun) + }) + + it('times five runs one after the other and keeps the median', async () => { + const times = [90, 10, 50, 30, 70] + let asked = 0 + const median = await measureBake(async () => runOf(times[asked++]), () => true) + expect(asked).toBe(BAKE_RUN_COUNT) + expect(median === null ? null : runMillis(median)).toBe(50) + }) + + it('stops asking once another entry is opened', async () => { + let asked = 0 + const median = await measureBake( + async () => runOf(asked++), + () => asked < 2 + ) + expect(median).toBeNull() + expect(asked).toBe(2) + }) + + it('drops the result of runs that finished after the entry was left', async () => { + let wanted = true + const median = await measureBake( + async () => { + wanted = false + return runOf(1) + }, + () => wanted + ) + expect(median).toBeNull() + }) + + it('rates a bake against a server tick of 50 ms', () => { + expect(bakeWeightOf(0.4).label).toBe('Light') + expect(bakeWeightOf(49.9).label).toBe('Light') + expect(bakeWeightOf(50).label).toBe('Moderate') + expect(bakeWeightOf(500).label).toBe('Heavy') + expect(bakeWeightOf(60_000).label).toBe('Heavy') + }) + + it('fills the meter on a logarithmic scale, a third for each weight', () => { + expect(meterFill(0)).toBe(0) + expect(meterFill(50)).toBeCloseTo(1 / 3) + expect(meterFill(500)).toBeCloseTo(2 / 3) + expect(meterFill(5000)).toBeCloseTo(1) + expect(meterFill(1_000_000)).toBeCloseTo(1) + expect(meterFill(Math.sqrt(50))).toBeCloseTo(1 / 6) + }) + + it('formats times with the digits they need', () => { + expect(formatMillis(2.34)).toBe('2.3 ms') + expect(formatMillis(48.6)).toBe('49 ms') + expect(formatMillis(1250)).toBe('1.3 s') + }) + + it('points at the slowest stage, the first when none took time', () => { + expect(slowestStageIndex(runOf(1, 9, 4))).toBe(1) + expect(slowestStageIndex(runOf(0, 0))).toBe(0) + }) +}) diff --git a/studio/src/renderer/src/scene/bakeTiming.ts b/studio/src/renderer/src/scene/bakeTiming.ts new file mode 100644 index 000000000..0c38f7ade --- /dev/null +++ b/studio/src/renderer/src/scene/bakeTiming.ts @@ -0,0 +1,87 @@ +import type { BakeRun } from '../bridge/types' + +const NANOS_PER_MILLI = 1_000_000 +const SECOND_IN_MILLIS = 1000 +const FINE_MILLIS_DIGITS_BELOW = 10 + +/** How many times a bake is timed; the run in the middle is the one shown. */ +export const BAKE_RUN_COUNT = 5 + +/** How long a bake stalls the chunk that first places it, against a server tick of 50 ms (v3 BakeWeight). */ +export interface BakeWeight { + label: string + /** Where the weight starts, in milliseconds. */ + fromMillis: number + /** Where the meter is full within the weight, in milliseconds. */ + meterFullAtMillis: number + /** The text colour class of the weight. */ + textClass: string + /** The fill colour class of the weight. */ + fillClass: string +} + +export const BAKE_WEIGHTS: readonly BakeWeight[] = [ + { label: 'Light', fromMillis: 1, meterFullAtMillis: 50, textClass: 'text-success', fillClass: 'bg-success' }, + { label: 'Moderate', fromMillis: 50, meterFullAtMillis: 500, textClass: 'text-warning', fillClass: 'bg-warning' }, + { label: 'Heavy', fromMillis: 500, meterFullAtMillis: 5000, textClass: 'text-destructive', fillClass: 'bg-destructive' } +] + +export function bakeWeightIndex(millis: number): number { + const index = BAKE_WEIGHTS.findIndex((weight) => millis < weight.meterFullAtMillis) + return index < 0 ? BAKE_WEIGHTS.length - 1 : index +} + +export function bakeWeightOf(millis: number): BakeWeight { + return BAKE_WEIGHTS[bakeWeightIndex(millis)] +} + +/** How full the meter is, from 0 to 1: each weight takes an equal share, filled on a logarithmic scale since bakes span thousands of times. */ +export function meterFill(millis: number): number { + const index = bakeWeightIndex(millis) + const weight = BAKE_WEIGHTS[index] + const clamped = Math.min(Math.max(millis, weight.fromMillis), weight.meterFullAtMillis) + const withinWeight = Math.log(clamped / weight.fromMillis) / Math.log(weight.meterFullAtMillis / weight.fromMillis) + return (index + withinWeight) / BAKE_WEIGHTS.length +} + +export function runMillis(run: BakeRun): number { + return run.stages.reduce((total, stage) => total + stage.nanos, 0) / NANOS_PER_MILLI +} + +/** The run in the middle by total time. The first run is slow while the JIT compiles the baker, and the garbage collector or chunk generation can slow any other, so neither ends up in the middle. */ +export function medianRun(runs: readonly BakeRun[]): BakeRun { + const byTime = [...runs].sort((first, second) => runMillis(first) - runMillis(second)) + return byTime[Math.floor(byTime.length / 2)] +} + +/** + * Times a bake {@link BAKE_RUN_COUNT} times, one run after the other, and keeps the median; null once {@code stillWanted} + * says another entry was opened. + */ +export async function measureBake(bakeOnce: () => Promise, stillWanted: () => boolean): Promise { + const runs: BakeRun[] = [] + while (runs.length < BAKE_RUN_COUNT) { + if (!stillWanted()) { + return null + } + runs.push(await bakeOnce()) + } + return stillWanted() ? medianRun(runs) : null +} + +export function formatMillis(millis: number): string { + if (millis >= SECOND_IN_MILLIS) { + return `${(millis / SECOND_IN_MILLIS).toFixed(1)} s` + } + return `${millis.toFixed(millis < FINE_MILLIS_DIGITS_BELOW ? 1 : 0)} ms` +} + +/** Where light turns to heavy, as the tooltip tells it. */ +export function weightScale(): string { + return `Light under ${formatMillis(BAKE_WEIGHTS[1].fromMillis)}, heavy from ${formatMillis(BAKE_WEIGHTS[2].fromMillis)}` +} + +/** The index of the stage that took longest; the first when none took any time. */ +export function slowestStageIndex(run: BakeRun): number { + return run.stages.reduce((slowest, stage, index) => (stage.nanos > run.stages[slowest].nanos ? index : slowest), 0) +} diff --git a/studio/src/renderer/src/studio/BakeMeter.tsx b/studio/src/renderer/src/studio/BakeMeter.tsx new file mode 100644 index 000000000..e6bbc6459 --- /dev/null +++ b/studio/src/renderer/src/studio/BakeMeter.tsx @@ -0,0 +1,87 @@ +import { Gauge } from 'lucide-react' +import { useEffect, useState } from 'react' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { BakeRun } from '../bridge/types' +import { BAKE_RUN_COUNT, bakeWeightOf, formatMillis, measureBake, meterFill, runMillis, slowestStageIndex, weightScale } from '../scene/bakeTiming' + +const MINIMUM_FILL = '4px' +const MEASURING_LABEL = 'Timing' +const NANOS_PER_MILLI = 1_000_000 +const PERCENT = 100 + +/** + * The chosen entry's bake timed {@link BAKE_RUN_COUNT} times in the background, kept as the median run; null while it is + * timed. Opening another entry, or a pack reload, stops the runs under way. + */ +export function useBakeTiming(client: BridgeClient, viewId: string, key: string | null, baked: boolean, packRevision: number, tell: (message: string) => void): BakeRun | null { + const [timing, setTiming] = useState(null) + + useEffect(() => { + setTiming(null) + if (!baked || key === null) { + return + } + const stop = new AbortController() + measureBake( + () => client.sceneBake(viewId, key, stop.signal), + () => !stop.signal.aborted + ) + .then((median) => median !== null && setTiming(median)) + .catch((failure: Error) => !stop.signal.aborted && tell(failure.message)) + return () => stop.abort() + }, [client, viewId, key, baked, packRevision, tell]) + + return timing +} + +interface BakeMeterProps { + /** The median bake of the chosen entry, or null while it is timed. */ + timing: BakeRun | null +} + +/** How heavy the chosen entry's bake is for the chunk that first places it: a rating, a meter and the time, with each step's time in the tooltip. */ +export function BakeMeter({ timing }: BakeMeterProps): React.JSX.Element { + const millis = timing === null ? 0 : runMillis(timing) + const weight = bakeWeightOf(millis) + return ( + + +
+ + + {timing === null ? MEASURING_LABEL : weight.label} + +
+ {timing !== null &&
} +
+ {timing !== null && formatMillis(millis)} +
+ + {timing === null ? `Baking every variant ${BAKE_RUN_COUNT} times over` : } + + ) +} + +function BakeExplanation({ timing }: { timing: BakeRun }): React.JSX.Element { + const slowest = slowestStageIndex(timing) + const variants = timing.variantCount === 1 ? '1 variant' : `${timing.variantCount} variants` + return ( +
+ + {variants} in {formatMillis(runMillis(timing))} ยท median of {BAKE_RUN_COUNT} runs + +
+ {timing.stages.map((stage, index) => ( +
+ {stage.label} + {formatMillis(stage.nanos / NANOS_PER_MILLI)} +
+ ))} +
+ Paid once per pack load, by the first chunk placing it + {weightScale()} +
+ ) +} diff --git a/studio/src/renderer/src/studio/SceneStudio.tsx b/studio/src/renderer/src/studio/SceneStudio.tsx index 79f5077e3..a7c220733 100644 --- a/studio/src/renderer/src/studio/SceneStudio.tsx +++ b/studio/src/renderer/src/studio/SceneStudio.tsx @@ -12,6 +12,7 @@ import { BlockModels } from '../scene/blockModels' import { BridgeAssets } from '../scene/BridgeAssets' import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding' import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh' +import { BakeMeter, useBakeTiming } from './BakeMeter' import { EntryBrowser } from './EntryBrowser' import { NodeInspector } from './NodeInspector' import { NodePane } from './NodePane' @@ -49,6 +50,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce } } + const bakeTiming = useBakeTiming(client, view.id, entry?.key ?? null, view.baked, packRevision, tell) + const editor = useNodeEditor(client, view.id, view.editable ? (entry?.key ?? null) : null, packRevision, tell) const [selectedPath, setSelectedPath] = useState(null) const selected = editor.state?.roots != null && selectedPath !== null ? nodeWithPath(editor.state.roots, selectedPath) : null @@ -74,6 +77,7 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce