mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-29 01:04:29 +00:00
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
This commit is contained in:
1 parent
f3bf0aea4b
commit
76dcab175b
14 files changed
+448
-6
No files matched your search
@@ -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<BakeRun> {
|
||||
return this.json(`scene-bake?${new URLSearchParams({ view: viewId, key })}`, { signal })
|
||||
}
|
||||
|
||||
async scene(viewId: string, key: string, variant: number, signal?: AbortSignal): Promise<BlockScene> {
|
||||
const response = await this.fetch(`scene?${new URLSearchParams({ view: viewId, key, variant: String(variant) })}`, { signal })
|
||||
return decodeScene(await response.arrayBuffer())
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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<BakeRun>, stillWanted: () => boolean): Promise<BakeRun | null> {
|
||||
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)
|
||||
}
|
||||
@@ -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<BakeRun | null>(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 (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="flex h-8 shrink-0 items-center gap-2 border-b px-4 text-[11.5px]">
|
||||
<Gauge className={cn('size-4 shrink-0', timing === null ? 'text-muted-foreground' : weight.textClass)} />
|
||||
<span className={cn('w-[62px] shrink-0 font-semibold', timing === null ? 'text-muted-foreground' : weight.textClass)}>
|
||||
{timing === null ? MEASURING_LABEL : weight.label}
|
||||
</span>
|
||||
<div className="h-1 min-w-0 flex-1 rounded-full bg-muted">
|
||||
{timing !== null && <div className={cn('h-full rounded-full', weight.fillClass)} style={{ width: `${meterFill(millis) * PERCENT}%`, minWidth: MINIMUM_FILL }} />}
|
||||
</div>
|
||||
<span className="w-[46px] shrink-0 text-right text-secondary-text tabular-nums">{timing !== null && formatMillis(millis)}</span>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="left">{timing === null ? `Baking every variant ${BAKE_RUN_COUNT} times over` : <BakeExplanation timing={timing} />}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function BakeExplanation({ timing }: { timing: BakeRun }): React.JSX.Element {
|
||||
const slowest = slowestStageIndex(timing)
|
||||
const variants = timing.variantCount === 1 ? '1 variant' : `${timing.variantCount} variants`
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span>
|
||||
{variants} in {formatMillis(runMillis(timing))} · median of {BAKE_RUN_COUNT} runs
|
||||
</span>
|
||||
<div className="grid grid-cols-[auto_auto] gap-x-4 tabular-nums">
|
||||
{timing.stages.map((stage, index) => (
|
||||
<div key={stage.label} className={cn('col-span-2 grid grid-cols-subgrid', index === slowest && 'font-semibold')}>
|
||||
<span>{stage.label}</span>
|
||||
<span className="text-right">{formatMillis(stage.nanos / NANOS_PER_MILLI)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<span>Paid once per pack load, by the first chunk placing it</span>
|
||||
<span>{weightScale()}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<JsonPath | null>(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
|
||||
</div>
|
||||
<aside className={cn('flex shrink-0 flex-col border-l bg-card', view.editable ? 'w-[300px]' : 'w-[250px]')}>
|
||||
<EntryBrowser className={selected === null ? 'flex-[7]' : 'flex-[3]'} title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, variant: 0 })} />
|
||||
{view.baked && entry !== null && <BakeMeter timing={bakeTiming} />}
|
||||
{selected !== null && editor.state !== null ? (
|
||||
<NodeInspector key={JSON.stringify(selected.path)} node={selected} state={editor.state} values={values} onEdit={editor.edit} />
|
||||
) : (
|
||||
|
||||
Reference in new issue
Block a user