oda-engine 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -2
- package/bin/nowhere.mjs +352 -0
- package/lib/account.mjs +57 -0
- package/lib/agentModules.mjs +57 -0
- package/lib/devServer.mjs +351 -0
- package/lib/headless.mjs +231 -0
- package/lib/headlessPreview.mjs +212 -0
- package/lib/keys.mjs +517 -0
- package/lib/make.mjs +855 -0
- package/lib/mcp.mjs +537 -0
- package/lib/open.mjs +22 -0
- package/lib/preview.mjs +87 -0
- package/lib/previewRpc.mjs +134 -0
- package/lib/project.mjs +359 -0
- package/lib/publishFlow.mjs +131 -0
- package/lib/resources.mjs +50 -0
- package/lib/rules.mjs +60 -0
- package/lib/scaffold.mjs +42 -0
- package/lib/setup.mjs +59 -0
- package/lib/tools.mjs +668 -0
- package/package.json +51 -4
- package/template/game.config.json +9 -0
- package/template/scene.json +4 -0
- package/template/src/main.ts +11 -0
- package/vendor/DOCS.md +447 -0
- package/vendor/agent/appRun.mjs +520 -0
- package/vendor/agent/assets/brief.mjs +242 -0
- package/vendor/agent/assets/collider.mjs +531 -0
- package/vendor/agent/assets/environments/index.mjs +12 -0
- package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
- package/vendor/agent/assets/fetch.mjs +168 -0
- package/vendor/agent/assets/footprint.mjs +13 -0
- package/vendor/agent/assets/gltf.mjs +547 -0
- package/vendor/agent/assets/hdr.mjs +269 -0
- package/vendor/agent/assets/imageOps.mjs +171 -0
- package/vendor/agent/assets/images/codex.mjs +307 -0
- package/vendor/agent/assets/images/fal.mjs +75 -0
- package/vendor/agent/assets/images/gemini.mjs +84 -0
- package/vendor/agent/assets/images/index.mjs +25 -0
- package/vendor/agent/assets/images/openai.mjs +75 -0
- package/vendor/agent/assets/images/stability.mjs +71 -0
- package/vendor/agent/assets/images/views.mjs +31 -0
- package/vendor/agent/assets/import.mjs +1352 -0
- package/vendor/agent/assets/inspect.mjs +465 -0
- package/vendor/agent/assets/jobs.mjs +196 -0
- package/vendor/agent/assets/ktx2.mjs +290 -0
- package/vendor/agent/assets/ledger.mjs +466 -0
- package/vendor/agent/assets/net.mjs +254 -0
- package/vendor/agent/assets/prices.json +39 -0
- package/vendor/agent/assets/providers/fal.mjs +115 -0
- package/vendor/agent/assets/providers/index.mjs +22 -0
- package/vendor/agent/assets/providers/meshy.mjs +119 -0
- package/vendor/agent/assets/providers/tripo.mjs +188 -0
- package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
- package/vendor/agent/assets/sources/index.mjs +23 -0
- package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
- package/vendor/agent/assets/sources/polypizza.mjs +121 -0
- package/vendor/agent/assets/splat.mjs +631 -0
- package/vendor/agent/assets/targets.mjs +122 -0
- package/vendor/agent/assets/tile.mjs +261 -0
- package/vendor/agent/assets/unzip.mjs +180 -0
- package/vendor/agent/blender/cleanup.py +360 -0
- package/vendor/agent/blender/convert.py +167 -0
- package/vendor/agent/blender/find.mjs +192 -0
- package/vendor/agent/blender/nw_export.py +104 -0
- package/vendor/agent/blender/nw_rubric.py +426 -0
- package/vendor/agent/blender/run.mjs +193 -0
- package/vendor/agent/blender/runner.py +252 -0
- package/vendor/agent/blender/sheet.py +743 -0
- package/vendor/agent/depth.mjs +134 -0
- package/vendor/agent/director/board.mjs +451 -0
- package/vendor/agent/director/contracts.mjs +663 -0
- package/vendor/agent/director/director.mjs +2365 -0
- package/vendor/agent/director/estimate.mjs +200 -0
- package/vendor/agent/director/gate.mjs +802 -0
- package/vendor/agent/director/limits.json +16 -0
- package/vendor/agent/director/methods.mjs +457 -0
- package/vendor/agent/director/policy.json +33 -0
- package/vendor/agent/director/prompts.mjs +244 -0
- package/vendor/agent/director/reading.mjs +341 -0
- package/vendor/agent/director/router.mjs +184 -0
- package/vendor/agent/director/seams.mjs +243 -0
- package/vendor/agent/director/session.mjs +643 -0
- package/vendor/agent/director/store.mjs +119 -0
- package/vendor/agent/director/taskGate.mjs +110 -0
- package/vendor/agent/director/teamLedger.mjs +118 -0
- package/vendor/agent/director/triage.mjs +63 -0
- package/vendor/agent/downloads.cjs +363 -0
- package/vendor/agent/flow.mjs +78 -0
- package/vendor/agent/guard.mjs +613 -0
- package/vendor/agent/host.mjs +1736 -0
- package/vendor/agent/language.mjs +58 -0
- package/vendor/agent/ledger.mjs +360 -0
- package/vendor/agent/locale.cjs +186 -0
- package/vendor/agent/loop/capacity.mjs +74 -0
- package/vendor/agent/loop/compose.mjs +127 -0
- package/vendor/agent/loop/gate.mjs +205 -0
- package/vendor/agent/loop/judge.mjs +189 -0
- package/vendor/agent/loop/levels.mjs +273 -0
- package/vendor/agent/loop/state.mjs +358 -0
- package/vendor/agent/notes.cjs +278 -0
- package/vendor/agent/pace.mjs +258 -0
- package/vendor/agent/panels.mjs +431 -0
- package/vendor/agent/prompt.mjs +342 -0
- package/vendor/agent/reference/board.mjs +410 -0
- package/vendor/agent/reference/compose.mjs +364 -0
- package/vendor/agent/reference/decode.mjs +56 -0
- package/vendor/agent/reference/facts.mjs +1874 -0
- package/vendor/agent/reference/png.mjs +107 -0
- package/vendor/agent/reference/records.mjs +63 -0
- package/vendor/agent/reference/web.mjs +252 -0
- package/vendor/agent/roles/artist.mjs +69 -0
- package/vendor/agent/roles/builder.mjs +79 -0
- package/vendor/agent/roles/checks.mjs +223 -0
- package/vendor/agent/roles/common.mjs +188 -0
- package/vendor/agent/roles/critic.mjs +171 -0
- package/vendor/agent/roles/index.mjs +39 -0
- package/vendor/agent/roles/modeller.mjs +142 -0
- package/vendor/agent/roles/qa.mjs +58 -0
- package/vendor/agent/roles/rubrics.mjs +79 -0
- package/vendor/agent/roles/sound.mjs +69 -0
- package/vendor/agent/rounds.cjs +333 -0
- package/vendor/agent/shared.mjs +284 -0
- package/vendor/agent/stopGate.mjs +574 -0
- package/vendor/agent/subagents.mjs +129 -0
- package/vendor/agent/tools/assets.mjs +499 -0
- package/vendor/agent/tools/blender.mjs +754 -0
- package/vendor/agent/tools/cards.mjs +479 -0
- package/vendor/agent/tools/choices.mjs +479 -0
- package/vendor/agent/tools/compose.mjs +74 -0
- package/vendor/agent/tools/environment.mjs +488 -0
- package/vendor/agent/tools/eyes.mjs +733 -0
- package/vendor/agent/tools/generate.mjs +338 -0
- package/vendor/agent/tools/guide.mjs +46 -0
- package/vendor/agent/tools/harness.mjs +193 -0
- package/vendor/agent/tools/image.mjs +643 -0
- package/vendor/agent/tools/index.mjs +162 -0
- package/vendor/agent/tools/look.mjs +578 -0
- package/vendor/agent/tools/loop.mjs +858 -0
- package/vendor/agent/tools/others.mjs +123 -0
- package/vendor/agent/tools/pictures.mjs +535 -0
- package/vendor/agent/tools/reference.mjs +366 -0
- package/vendor/agent/transcripts.mjs +118 -0
- package/vendor/agent-loop.mjs +602 -0
- package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
- package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
- package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
- package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
- package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
- package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
- package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
- package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
- package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
- package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
- package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
- package/vendor/auth.cjs +570 -0
- package/vendor/build.cjs +953 -0
- package/vendor/catalog.json +455 -0
- package/vendor/connectors.cjs +688 -0
- package/vendor/eyes.mjs +733 -0
- package/vendor/gameExports.json +1390 -0
- package/vendor/git.cjs +222 -0
- package/vendor/models.json +57 -0
- package/vendor/publish.cjs +1018 -0
- package/vendor/refBoard.cjs +301 -0
- package/vendor/schema/dist/assets.d.ts +335 -0
- package/vendor/schema/dist/assets.js +439 -0
- package/vendor/schema/dist/brief.d.ts +357 -0
- package/vendor/schema/dist/brief.js +302 -0
- package/vendor/schema/dist/common.d.ts +9 -0
- package/vendor/schema/dist/common.js +13 -0
- package/vendor/schema/dist/config.d.ts +406 -0
- package/vendor/schema/dist/config.js +355 -0
- package/vendor/schema/dist/contract.d.ts +599 -0
- package/vendor/schema/dist/contract.js +1146 -0
- package/vendor/schema/dist/index.d.ts +14 -0
- package/vendor/schema/dist/index.js +21 -0
- package/vendor/schema/dist/look.d.ts +463 -0
- package/vendor/schema/dist/look.js +681 -0
- package/vendor/schema/dist/lookStats.d.ts +230 -0
- package/vendor/schema/dist/lookStats.js +768 -0
- package/vendor/schema/dist/pilot.d.ts +32 -0
- package/vendor/schema/dist/pilot.js +44 -0
- package/vendor/schema/dist/publish.d.ts +214 -0
- package/vendor/schema/dist/publish.js +291 -0
- package/vendor/schema/dist/scene.d.ts +75 -0
- package/vendor/schema/dist/scene.js +120 -0
- package/vendor/schema/dist/skyLight.d.ts +141 -0
- package/vendor/schema/dist/skyLight.js +436 -0
- package/vendor/schema/dist/style.d.ts +131 -0
- package/vendor/schema/dist/style.js +155 -0
- package/vendor/schema/package.json +1 -0
- package/vendor/selectionPrompt.mjs +51 -0
- package/vendor/useTools.mjs +195 -0
- package/vendor/userMessage.mjs +26 -0
- package/web-dist/assets/GaussianSplatUtils-CptQkDVX.js +1 -0
- package/web-dist/assets/KTX2Loader-C53LJqss.js +2 -0
- package/web-dist/assets/SPZLoader-BQ3tjaTv.js +1 -0
- package/web-dist/assets/gaussianSplat-_9tcWegB.js +1 -0
- package/web-dist/assets/index-Baka-ZO7.js +693 -0
- package/web-dist/assets/index-CcjyyQco.css +1 -0
- package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
- package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
- package/web-dist/index.html +34 -0
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
// The planet's look, as tools: setting a look in game.config.json
|
|
2
|
+
// (look_apply), and measuring a view against a reference picture
|
|
3
|
+
// (look_compare). There are no presets: every value comes from the game's
|
|
4
|
+
// brief, which comes from the request and its reference, so two games never
|
|
5
|
+
// start from the same stock mood.
|
|
6
|
+
//
|
|
7
|
+
// The look is data in game.config.json (schema look.ts) and every host draws it
|
|
8
|
+
// through the SDK's createLook, so what these tools set is what the studio
|
|
9
|
+
// shows and what the planet shows a visitor. look_compare turns "a bit dark,
|
|
10
|
+
// a bit warm" into numbers (palette deltaE, mean L*, contrast, chroma, warmth)
|
|
11
|
+
// and the numbers into look_apply values, which is what lets a look converge
|
|
12
|
+
// on a reference instead of wandering around it.
|
|
13
|
+
//
|
|
14
|
+
// look_compare judges only a picture of the space as it will look: the view
|
|
15
|
+
// waits for the space's files and placed models to arrive, and a picture drawn
|
|
16
|
+
// before they had (createPreviewScene's LoadingReport says so) is shown but
|
|
17
|
+
// never judged. A one-shot preview once judged Laputa v1 without its castle
|
|
18
|
+
// and tree, and the Red Arch as sky and ground alone.
|
|
19
|
+
//
|
|
20
|
+
// Electron-free and host-agnostic: the CLI vendors this file and answers the
|
|
21
|
+
// same 'view' rpc from its preview page.
|
|
22
|
+
|
|
23
|
+
import { createHash } from 'node:crypto'
|
|
24
|
+
import fs from 'node:fs'
|
|
25
|
+
import fsp from 'node:fs/promises'
|
|
26
|
+
import path from 'node:path'
|
|
27
|
+
import { z } from 'zod'
|
|
28
|
+
import {
|
|
29
|
+
FOG_HEIGHT_DENSITY_THICK,
|
|
30
|
+
LookSpecStrict,
|
|
31
|
+
compareLook,
|
|
32
|
+
deltaE2000,
|
|
33
|
+
hexToLab,
|
|
34
|
+
physicalSkyColors,
|
|
35
|
+
resolveLook,
|
|
36
|
+
suggestLook,
|
|
37
|
+
validateConfig,
|
|
38
|
+
} from '../../schema/dist/index.js'
|
|
39
|
+
import { fromBlockedSite, lookOnly, recordsFor } from '../reference/records.mjs'
|
|
40
|
+
import { BLOCKED_HOSTS, isInside } from '../shared.mjs'
|
|
41
|
+
import { stillOut, viewTimeout } from './eyes.mjs'
|
|
42
|
+
|
|
43
|
+
export const RPC_METHODS = ['view']
|
|
44
|
+
|
|
45
|
+
const CONFIG = 'game.config.json'
|
|
46
|
+
const LEDGER = 'assets.lock.json'
|
|
47
|
+
const QUARANTINE_MANIFEST = '.nowhere/quarantine/index.json'
|
|
48
|
+
const BOARD = 'refs/board.json'
|
|
49
|
+
/** A reference bigger than this is not a picture anyone attached. */
|
|
50
|
+
const REFERENCE_MAX_BYTES = 20 * 1024 * 1024
|
|
51
|
+
/** How long look_compare waits for the space's files before it looks. */
|
|
52
|
+
export const LOOK_SETTLE_MS = 20_000
|
|
53
|
+
|
|
54
|
+
const HEX = /^#[0-9a-fA-F]{6}$/
|
|
55
|
+
const Hex = z.string().regex(HEX, 'must be a #rrggbb hex colour')
|
|
56
|
+
const vec3 = z.array(z.number()).length(3)
|
|
57
|
+
|
|
58
|
+
// ---- shapes ----------------------------------------------------------------
|
|
59
|
+
|
|
60
|
+
/** One camera, as nw_view takes it (eyes.mjs), so a look_compare view is any view. */
|
|
61
|
+
const shotSpec = z.object({
|
|
62
|
+
view: z.enum(['player', 'orbit', 'closeup', 'overview', 'free']),
|
|
63
|
+
target: z.union([z.string(), vec3]).optional().describe('orbit and closeup: "player", a placement id or kind, a world kind, an object name, or [x, y, z].'),
|
|
64
|
+
yaw: z.number().optional().describe('Degrees around the target: 0 looks from +Z toward -Z.'),
|
|
65
|
+
pitch: z.number().optional().describe('Degrees above the horizon.'),
|
|
66
|
+
distance: z.number().optional().describe('Metres from the target.'),
|
|
67
|
+
fov: z.number().optional().describe('Vertical field of view in degrees.'),
|
|
68
|
+
position: vec3.optional().describe('free: where the camera stands.'),
|
|
69
|
+
lookAt: vec3.optional().describe('free: the point it looks at.'),
|
|
70
|
+
fog: z.boolean().optional().describe("Draw the world's fog (default on, off for closeup and overview)."),
|
|
71
|
+
longEdge: z.number().int().optional().describe("The picture's long side in pixels, 256 to 1568."),
|
|
72
|
+
aspect: z.enum(['wide', 'square', 'tall']).optional(),
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
// The parts of a config look_apply merges. Loose on purpose (no bounds, no
|
|
76
|
+
// defaults): the merged document is validated whole afterwards, so a bound is
|
|
77
|
+
// said once, by the schema, and nothing absent is filled in by a default.
|
|
78
|
+
const SET_SHAPE = z
|
|
79
|
+
.object({
|
|
80
|
+
sky: z
|
|
81
|
+
.object({ kind: z.enum(['none', 'color', 'gradient', 'hdri', 'physical']) })
|
|
82
|
+
.passthrough()
|
|
83
|
+
.describe('The whole sky: { kind: "gradient", top, bottom } | { kind: "color", color } | { kind: "none" } | { kind: "hdri", asset: "assets/x.hdr", top?, bottom?, intensity?, rotation?, blur?, background?, ground?: { height, radius? } } | { kind: "physical", turbidity, rayleigh, mieCoefficient?, mieDirectionalG?, sunDisc?, top?, bottom? }. An HDRI\'s top and bottom come from asset_import\'s measure when left out, a physical sky\'s from its model under lighting.sun. ground lays an HDRI\'s lower half on the ground (height: the camera\'s height above it when it was shot, metres). A physical sky is lit by lighting.sun and scaled to its intensity.'),
|
|
84
|
+
fog: z
|
|
85
|
+
.object({
|
|
86
|
+
color: Hex,
|
|
87
|
+
near: z.number(),
|
|
88
|
+
far: z.number(),
|
|
89
|
+
mode: z.enum(['range', 'exp2', 'height']),
|
|
90
|
+
density: z.number(),
|
|
91
|
+
height: z.number(),
|
|
92
|
+
heightDensity: z.number(),
|
|
93
|
+
})
|
|
94
|
+
.partial()
|
|
95
|
+
.nullable()
|
|
96
|
+
.describe('Merged into the fog there is (near and far in metres; mode range, exp2 or height); null turns fog off.'),
|
|
97
|
+
lighting: z
|
|
98
|
+
.object({
|
|
99
|
+
ambient: z.object({ color: Hex, intensity: z.number() }).partial(),
|
|
100
|
+
sun: z.object({ color: Hex, intensity: z.number(), direction: vec3, shadows: z.boolean() }).partial().nullable(),
|
|
101
|
+
})
|
|
102
|
+
.partial()
|
|
103
|
+
.describe('Merged deep: { sun: { intensity: 4 } } changes only that.'),
|
|
104
|
+
bloom: z
|
|
105
|
+
.object({ enabled: z.boolean(), strength: z.number(), radius: z.number(), threshold: z.number() })
|
|
106
|
+
.partial()
|
|
107
|
+
.describe('Glow of emissive surfaces: strength 0 to 3, radius 0 to 1, threshold 0 to 2.'),
|
|
108
|
+
look: LookSpecStrict.describe(
|
|
109
|
+
'Merged deep: style { outline { width, color, depth, crease }, bands { count, softness }, hatch { amount, spacing, color, angle }, halftone { amount, spacing, color, angle }, paint { radius }, paper { amount, color, grain }, pixel { size } } (the drawing techniques, copied from style.json\'s look; null turns one off), toneMapping (agx, neutral, aces, none), exposure, grade { temperature, tint, saturation, contrast, cdl { slope, offset, power }, lut, posterize }, ao { enabled, radius, strength }, shadows { quality, softness, cascades, distance }, ssr { enabled, distance, thickness, intensity } (reflections, high tier), vignette { amount, smoothness }, grain, environment { intensity }, aa (traa, smaa, fxaa, msaa, none: technical, best left to its default), gi { kind: "probes", spacing, intensity, box { center, size } } (light from what is round the shade, baked as the space loads, over the box or what stands on the map; WebGPU and WebGL2; what moves takes userData.gi = false), tiers (low, medium: ao, bloom, grain, aa, cascades, ssr, gi).',
|
|
110
|
+
),
|
|
111
|
+
})
|
|
112
|
+
.partial()
|
|
113
|
+
|
|
114
|
+
const APPLY_SHAPE = {
|
|
115
|
+
set: SET_SHAPE.optional().describe(
|
|
116
|
+
"Values to merge into the config, deep for look and lighting; null turns fog off. Each comes from the brief (its light, atmosphere, values and palette) or from look_compare's suggestions.",
|
|
117
|
+
),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const COMPARE_SHAPE = {
|
|
121
|
+
reference: z.string().describe('A reference picture in the project: .nowhere/refs/<file> (from the studio context) or refs/<file>.'),
|
|
122
|
+
views: z.array(shotSpec).min(1).max(4).optional().describe('Default: one player view.'),
|
|
123
|
+
palette: z.array(Hex).min(2).max(8).optional().describe("The brief's palette, compared too."),
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ---- helpers ---------------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
129
|
+
const fmt = (n, digits = 2) => (typeof n === 'number' && Number.isFinite(n) ? String(Number(n.toFixed(digits))) : '?')
|
|
130
|
+
const pct = (n) => `${fmt(n * 100, 1)}%`
|
|
131
|
+
const signed = (n, digits = 1) => (typeof n === 'number' && Number.isFinite(n) ? `${n > 0 ? '+' : ''}${n.toFixed(digits)}` : '?')
|
|
132
|
+
|
|
133
|
+
/** Deep merge for plain objects: arrays and other values replace, null is kept as a value. */
|
|
134
|
+
function deepMerge(into, patch) {
|
|
135
|
+
if (!isObj(into) || !isObj(patch)) return patch
|
|
136
|
+
const out = { ...into }
|
|
137
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
138
|
+
if (v === undefined) continue
|
|
139
|
+
out[k] = isObj(v) && isObj(out[k]) ? deepMerge(out[k], v) : v
|
|
140
|
+
}
|
|
141
|
+
return out
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Every leaf of a document by its dotted path; arrays are leaves. */
|
|
145
|
+
function leaves(value, prefix = '', out = new Map()) {
|
|
146
|
+
if (isObj(value)) {
|
|
147
|
+
const keys = Object.keys(value)
|
|
148
|
+
if (keys.length === 0 && prefix) out.set(prefix, '{}')
|
|
149
|
+
for (const k of keys) leaves(value[k], prefix ? `${prefix}.${k}` : k, out)
|
|
150
|
+
} else if (prefix) out.set(prefix, JSON.stringify(value))
|
|
151
|
+
return out
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** What changed between two documents, one line a path: `look.exposure: 1 -> 1.2`. */
|
|
155
|
+
export function changedPaths(before, after) {
|
|
156
|
+
const a = leaves(before)
|
|
157
|
+
const b = leaves(after)
|
|
158
|
+
const under = (map, p) => [...map.keys()].some((k) => k.startsWith(`${p}.`))
|
|
159
|
+
const over = (map, p) => p.split('.').some((_, i, parts) => i < parts.length - 1 && map.has(parts.slice(0, i + 1).join('.')))
|
|
160
|
+
const lines = []
|
|
161
|
+
for (const [p, v] of b) {
|
|
162
|
+
if (!a.has(p)) lines.push(`${p}: ${under(a, p) ? '(object)' : '(none)'} -> ${v}`)
|
|
163
|
+
else if (a.get(p) !== v) lines.push(`${p}: ${a.get(p)} -> ${v}`)
|
|
164
|
+
}
|
|
165
|
+
// A value that became an object (fog null to a fog) is said by its fields
|
|
166
|
+
// above, and one an object became (a fog to null) by the line for it.
|
|
167
|
+
for (const [p, v] of a) if (!b.has(p) && !under(b, p) && !over(b, p)) lines.push(`${p}: ${v} -> (none)`)
|
|
168
|
+
return lines
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** A resolved look in one line. */
|
|
172
|
+
export function lookSummary(look) {
|
|
173
|
+
const parts = [
|
|
174
|
+
look.legacy ? 'legacy look (no look block: Neutral, as before)' : 'its own look',
|
|
175
|
+
`${look.toneMapping}, exposure ${fmt(look.exposure)}`,
|
|
176
|
+
]
|
|
177
|
+
const g = look.grade
|
|
178
|
+
const grade = []
|
|
179
|
+
if (g.temperature) grade.push(`temperature ${fmt(g.temperature)}`)
|
|
180
|
+
if (g.tint) grade.push(`tint ${fmt(g.tint)}`)
|
|
181
|
+
if (g.saturation !== 1) grade.push(`saturation ${fmt(g.saturation)}`)
|
|
182
|
+
if (g.contrast !== 1) grade.push(`contrast ${fmt(g.contrast)}`)
|
|
183
|
+
if (g.lut) grade.push(`LUT ${g.lut.asset} at ${fmt(g.lut.intensity)}`)
|
|
184
|
+
if (g.posterize) grade.push(`posterize ${g.posterize}`)
|
|
185
|
+
if (grade.length) parts.push(grade.join(', '))
|
|
186
|
+
parts.push(look.ao.enabled ? `AO ${fmt(look.ao.radius)} m at ${fmt(look.ao.strength)}` : 'no AO')
|
|
187
|
+
parts.push(look.bloom.enabled ? `bloom ${fmt(look.bloom.strength)}/${fmt(look.bloom.radius)}/${fmt(look.bloom.threshold)}` : 'no bloom')
|
|
188
|
+
if (look.fog) {
|
|
189
|
+
const f = look.fog
|
|
190
|
+
parts.push(
|
|
191
|
+
f.mode === 'exp2'
|
|
192
|
+
? `fog exp2 density ${fmt(f.density, 4)}`
|
|
193
|
+
: f.mode === 'height'
|
|
194
|
+
? `fog ${fmt(f.near)} to ${fmt(f.far)} m with ground fog below ${fmt(f.height)} m (${fmt(f.heightDensity, 3)})`
|
|
195
|
+
: `fog ${fmt(f.near)} to ${fmt(f.far)} m`,
|
|
196
|
+
)
|
|
197
|
+
} else parts.push('no fog')
|
|
198
|
+
if (look.vignette.amount) parts.push(`vignette ${fmt(look.vignette.amount)}`)
|
|
199
|
+
if (look.grain) parts.push(`grain ${fmt(look.grain, 3)}`)
|
|
200
|
+
parts.push(`shadows ${look.shadows.mapSize}, ${fmt(look.shadows.softness, 3)} m soft${look.shadows.cascades ? ` in ${look.shadows.cascades} cascades to ${fmt(look.shadows.distance, 0)} m` : ''}`)
|
|
201
|
+
if (look.ssr) parts.push(`reflections to ${fmt(look.ssr.distance)} m`)
|
|
202
|
+
parts.push(`sky light ${fmt(look.environment.intensity)}`)
|
|
203
|
+
return parts.join('; ')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** A height fog thick enough to swallow the ground, said with the answer:
|
|
207
|
+
* its factor squares heightDensity x depth below the top x distance, so
|
|
208
|
+
* 0.08 (the old default) turned everything under the top to fog colour
|
|
209
|
+
* within ten metres. Valid, so written; but nobody means it. */
|
|
210
|
+
function fogWarning(look) {
|
|
211
|
+
const f = look.fog
|
|
212
|
+
if (!f || f.mode !== 'height' || !(f.heightDensity > FOG_HEIGHT_DENSITY_THICK)) return ''
|
|
213
|
+
return `\nCareful: fog.heightDensity ${fmt(f.heightDensity, 3)} is thick. Height fog grows with depth below fog.height AND with distance (the factor squares heightDensity x metres below x metres away): above ${FOG_HEIGHT_DENSITY_THICK} everything under ${fmt(f.height)} m is fog colour within a few metres. 0.005 to 0.02 reads as ground fog (0.01 is 0.19 at 20 m and 0.57 at 40 m, 2.3 m under the top).`
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const readJson = async (file) => {
|
|
217
|
+
try {
|
|
218
|
+
return JSON.parse(await fsp.readFile(file, 'utf8'))
|
|
219
|
+
} catch {
|
|
220
|
+
return null
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Writes a file whole or not at all: a temp file beside it, then a rename. */
|
|
225
|
+
async function writeAtomic(file, text) {
|
|
226
|
+
const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`)
|
|
227
|
+
await fsp.writeFile(tmp, text, 'utf8')
|
|
228
|
+
try {
|
|
229
|
+
await fsp.rename(tmp, file)
|
|
230
|
+
} catch (err) {
|
|
231
|
+
await fsp.rm(tmp, { force: true }).catch(() => {})
|
|
232
|
+
throw err
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** An HDRI's two measured colours, from the asset ledger asset_import keeps. */
|
|
237
|
+
async function hdriMeasure(projectRoot, asset) {
|
|
238
|
+
const lock = await readJson(path.join(projectRoot, LEDGER))
|
|
239
|
+
const meta = lock?.files?.[asset]?.meta?.hdri
|
|
240
|
+
return isObj(meta) && HEX.test(meta.top ?? '') && HEX.test(meta.bottom ?? '') ? { top: meta.top, bottom: meta.bottom } : null
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ---- the reference ---------------------------------------------------------
|
|
244
|
+
|
|
245
|
+
/** What a picture is, by its first bytes. */
|
|
246
|
+
function mimeOf(bytes) {
|
|
247
|
+
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'image/png'
|
|
248
|
+
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg'
|
|
249
|
+
if (bytes.length >= 12 && bytes.toString('latin1', 0, 4) === 'RIFF' && bytes.toString('latin1', 8, 12) === 'WEBP') return 'image/webp'
|
|
250
|
+
return null
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const blocked = (v) => typeof v === 'string' && BLOCKED_HOSTS.test(v)
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The reference as bytes the probe can measure, or why it cannot be used:
|
|
257
|
+
* not a URL, inside the project, a picture, and not recorded as coming from
|
|
258
|
+
* ArtStation, Pinterest or Behance (the quarantine manifest, the asset
|
|
259
|
+
* ledger, the reference board's grade C). `tool` is the name the answers
|
|
260
|
+
* give (nw_reference and nw_compare read references the same way).
|
|
261
|
+
*/
|
|
262
|
+
export async function readReference(projectRoot, reference, tool = 'look_compare') {
|
|
263
|
+
const given = String(reference ?? '').trim()
|
|
264
|
+
if (!given) return { error: 'Name the reference picture: .nowhere/refs/<file> or refs/<file>.' }
|
|
265
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(given) || given.startsWith('//')) {
|
|
266
|
+
return { error: `${tool} takes a picture in the project, not a URL. Ask the creator to attach it (it lands in .nowhere/refs/).` }
|
|
267
|
+
}
|
|
268
|
+
const abs = path.resolve(projectRoot, given)
|
|
269
|
+
if (!isInside(projectRoot, abs)) return { error: `${given} is outside the project; ${tool} reads only pictures in it.` }
|
|
270
|
+
let stat
|
|
271
|
+
try {
|
|
272
|
+
stat = await fsp.stat(abs)
|
|
273
|
+
} catch {
|
|
274
|
+
return { error: `There is no ${given} in the project.` }
|
|
275
|
+
}
|
|
276
|
+
if (!stat.isFile()) return { error: `${given} is not a file.` }
|
|
277
|
+
if (stat.size > REFERENCE_MAX_BYTES) return { error: `${given} is ${Math.round(stat.size / 1048576)} MB; a reference is at most 20 MB.` }
|
|
278
|
+
const bytes = await fsp.readFile(abs)
|
|
279
|
+
const mime = mimeOf(bytes)
|
|
280
|
+
if (!mime) return { error: `${given} is not a PNG, JPEG or WebP picture.` }
|
|
281
|
+
const rel = path.relative(fs.realpathSync(projectRoot), fs.realpathSync(abs)).split(path.sep).join('/')
|
|
282
|
+
const name = path.basename(abs)
|
|
283
|
+
const sha = createHash('sha256').update(bytes).digest('hex')
|
|
284
|
+
const refused = (await referenceRules(projectRoot, tool))({ given, rel, name, sha })
|
|
285
|
+
if (refused) return { error: refused }
|
|
286
|
+
return { ok: true, rel, data: bytes.toString('base64'), mime }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* The reference rules of a project, read once: a function that says why a
|
|
291
|
+
* picture in it may not be fed to a model (its name, the quarantine's
|
|
292
|
+
* record, the ledger's, its grade on refs/board.json), or null when it may.
|
|
293
|
+
* readReference asks it of each picture it reads; the reference board asks
|
|
294
|
+
* it of a picture it measured before, by the sha256 it kept, without
|
|
295
|
+
* reading the picture again.
|
|
296
|
+
*/
|
|
297
|
+
export async function referenceRules(projectRoot, tool = 'look_compare') {
|
|
298
|
+
const [quarantine, ledger, board] = await Promise.all([QUARANTINE_MANIFEST, LEDGER, BOARD].map((f) => readJson(path.join(projectRoot, f))))
|
|
299
|
+
const BLOCKED = `ArtStation, Pinterest and Behance pictures are for the creator's eyes only: their terms forbid feeding them to AI tools, so ${tool} will not measure it. Ask the creator to describe it, or use a CC0 or public-domain reference.`
|
|
300
|
+
return ({ given, rel, name, sha }) => {
|
|
301
|
+
if (blocked(rel)) return `${given} is named after a blocked site. ${BLOCKED}`
|
|
302
|
+
if (quarantine && recordsFor(quarantine, { rel, name, sha }).some(fromBlockedSite)) {
|
|
303
|
+
return `${given} was downloaded from a blocked site (the quarantine's record says so). ${BLOCKED}`
|
|
304
|
+
}
|
|
305
|
+
const entry = ledger?.files?.[rel]
|
|
306
|
+
if ((isObj(entry) && fromBlockedSite(entry)) || (ledger && recordsFor(ledger, { rel, name, sha }).some(fromBlockedSite))) {
|
|
307
|
+
return `${given} is recorded in ${LEDGER} as coming from a blocked site. ${BLOCKED}`
|
|
308
|
+
}
|
|
309
|
+
if (board && lookOnly(recordsFor(board, { rel, name, sha }))) {
|
|
310
|
+
return `${given} is graded C on ${BOARD} (look only, never fed to a model). ${BLOCKED}`
|
|
311
|
+
}
|
|
312
|
+
return null
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Why a picture cannot be judged, or null when it can: one drawn before
|
|
317
|
+
* the space's files had all arrived, or by a preview that does not say. */
|
|
318
|
+
export function notJudged(shot) {
|
|
319
|
+
const loading = shot?.loading
|
|
320
|
+
if (!loading) return 'the preview did not say whether the space had finished loading (it is older than this tool): reopen it, then compare again'
|
|
321
|
+
if (!loading.mounted) return 'no space was mounted when it was drawn'
|
|
322
|
+
if (loading.settled) return null
|
|
323
|
+
const out = stillOut(loading)
|
|
324
|
+
return out
|
|
325
|
+
? `it was drawn while the space was still loading ${out}`
|
|
326
|
+
: `it was drawn ${loading.quietMs} ms after the last file arrived, before the space had settled`
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** The mean of several comparisons, for one set of suggestions. */
|
|
330
|
+
function meanComparison(list) {
|
|
331
|
+
const avg = (f) => list.reduce((s, c) => s + f(c), 0) / list.length
|
|
332
|
+
const avg3 = (f) => [0, 1, 2].map((i) => avg((c) => f(c)[i]))
|
|
333
|
+
return {
|
|
334
|
+
...list[0],
|
|
335
|
+
paletteDeltaE: avg((c) => c.paletteDeltaE),
|
|
336
|
+
deltaMeanL: avg((c) => c.deltaMeanL),
|
|
337
|
+
contrastRatio: avg((c) => c.contrastRatio),
|
|
338
|
+
chromaRatio: avg((c) => c.chromaRatio),
|
|
339
|
+
warmthDelta: avg((c) => c.warmthDelta),
|
|
340
|
+
tintDelta: avg((c) => c.tintDelta),
|
|
341
|
+
thirds: { shot: avg3((c) => c.thirds.shot), ref: avg3((c) => c.thirds.ref) },
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// ---- the tools -------------------------------------------------------------
|
|
346
|
+
|
|
347
|
+
const lookApply = {
|
|
348
|
+
name: 'look_apply',
|
|
349
|
+
description:
|
|
350
|
+
'Sets the planet\'s look in game.config.json: set is merged into the config (deep for look and lighting; fog null turns it off). Every value comes from the brief (its light, atmosphere, values and palette, which come from the request and the reference) or from look_compare\'s suggestions; there is no stock mood to start from. The look block holds the tone curve (agx by default, neutral, aces, none), exposure, the grade (white balance, CDL, contrast, saturation, a .cube LUT, posterize), ambient occlusion, shadow quality and softness, vignette and grain. The whole config is validated first and nothing is written if any value is out of range or unknown. Answers with what changed and the look as it resolves. The studio and the published planet draw the same look.',
|
|
351
|
+
shape: APPLY_SHAPE,
|
|
352
|
+
async handler(args, ctx) {
|
|
353
|
+
const root = ctx?.projectRoot
|
|
354
|
+
if (!root) return { text: 'There is no project open.', isError: true }
|
|
355
|
+
const file = path.join(root, CONFIG)
|
|
356
|
+
let before
|
|
357
|
+
try {
|
|
358
|
+
before = JSON.parse(await fsp.readFile(file, 'utf8'))
|
|
359
|
+
} catch (err) {
|
|
360
|
+
return { text: `${CONFIG} could not be read (${err.code === 'ENOENT' ? 'there is none' : 'it is not valid JSON'}): fix it by hand first.`, isError: true }
|
|
361
|
+
}
|
|
362
|
+
if (!isObj(before)) return { text: `${CONFIG} is not a JSON object.`, isError: true }
|
|
363
|
+
|
|
364
|
+
// A call with nothing in set (an old habit: a preset name, which the
|
|
365
|
+
// shape no longer has and so arrives as nothing) is refused with the way.
|
|
366
|
+
const set = args.set ?? {}
|
|
367
|
+
if (Object.values(set).every((v) => v === undefined)) {
|
|
368
|
+
return {
|
|
369
|
+
text: 'Nothing was written: look_apply takes set, the values to write. There are no presets; take each value from the brief (light: sun elevation, azimuth and colour temperature; atmosphere: fog colour and distances; values: exposure and contrast; palette: sky and grade) or from look_compare\'s suggestions.',
|
|
370
|
+
isError: true,
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
let next = structuredClone(before)
|
|
375
|
+
if (set.look !== undefined) {
|
|
376
|
+
const strict = LookSpecStrict.safeParse(set.look)
|
|
377
|
+
if (!strict.success) {
|
|
378
|
+
const problems = strict.error.issues.map((i) => `look.${i.path.join('.')}: ${i.message}`)
|
|
379
|
+
return { text: `Nothing was written. The look is not valid:\n${problems.map((p) => `- ${p}`).join('\n')}`, isError: true }
|
|
380
|
+
}
|
|
381
|
+
next.look = deepMerge(isObj(next.look) ? next.look : {}, set.look)
|
|
382
|
+
}
|
|
383
|
+
if (set.lighting !== undefined) next.lighting = deepMerge(isObj(next.lighting) ? next.lighting : {}, set.lighting)
|
|
384
|
+
if (set.bloom !== undefined) next.bloom = { ...(isObj(next.bloom) ? next.bloom : {}), ...set.bloom }
|
|
385
|
+
if (set.fog !== undefined) next.fog = set.fog === null ? null : { ...(isObj(next.fog) ? next.fog : {}), ...set.fog }
|
|
386
|
+
if (set.sky !== undefined) next.sky = structuredClone(set.sky)
|
|
387
|
+
|
|
388
|
+
// A physical sky's two colours are its model's under the config's sun:
|
|
389
|
+
// filled when left out, and again whenever this call moves the sun, so
|
|
390
|
+
// what reads the sky by two (a figure's glow, the stand-in dome) follows
|
|
391
|
+
// it. Colours this call gives are kept.
|
|
392
|
+
if (isObj(next.sky) && next.sky.kind === 'physical') {
|
|
393
|
+
const given = isObj(set.sky) ? set.sky : {}
|
|
394
|
+
const sunMoved = isObj(set.lighting) && set.lighting.sun !== undefined
|
|
395
|
+
const keeps = (key) => HEX.test(given[key] ?? '') || (!sunMoved && HEX.test(next.sky[key] ?? ''))
|
|
396
|
+
if (!keeps('top') || !keeps('bottom')) {
|
|
397
|
+
const sun = isObj(next.lighting) && next.lighting.sun !== undefined ? next.lighting.sun : { direction: [0.85, -1, -0.35], intensity: 3.4 }
|
|
398
|
+
const colors = physicalSkyColors(next.sky, isObj(sun) ? sun : null)
|
|
399
|
+
next.sky = { ...next.sky, top: keeps('top') ? next.sky.top : colors.top, bottom: keeps('bottom') ? next.sky.bottom : colors.bottom }
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
// An HDRI sky carries its two colours; the ledger has them when the agent left them out.
|
|
403
|
+
if (isObj(next.sky) && next.sky.kind === 'hdri' && (!HEX.test(next.sky.top ?? '') || !HEX.test(next.sky.bottom ?? ''))) {
|
|
404
|
+
const measured = typeof next.sky.asset === 'string' ? await hdriMeasure(root, next.sky.asset) : null
|
|
405
|
+
if (!measured) {
|
|
406
|
+
return {
|
|
407
|
+
text: `Nothing was written. An HDRI sky needs its top and bottom colours, and ${LEDGER} has no measure for ${next.sky.asset ?? 'that file'}: bring it in with asset_import (which measures them), or give top and bottom.`,
|
|
408
|
+
isError: true,
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
next.sky = { ...next.sky, top: HEX.test(next.sky.top ?? '') ? next.sky.top : measured.top, bottom: HEX.test(next.sky.bottom ?? '') ? next.sky.bottom : measured.bottom }
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
if (next.look !== undefined) {
|
|
415
|
+
const strict = LookSpecStrict.safeParse(next.look)
|
|
416
|
+
if (!strict.success) {
|
|
417
|
+
const problems = strict.error.issues.map((i) => `look.${i.path.join('.')}: ${i.message}`)
|
|
418
|
+
return { text: `Nothing was written. The look is not valid:\n${problems.map((p) => `- ${p}`).join('\n')}`, isError: true }
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
const checked = validateConfig(next)
|
|
422
|
+
if (!checked.ok) {
|
|
423
|
+
const problems = checked.findings.map((f) => `${f.path.replace(/^game\.config\.json:?/, '') || '(the file)'}: ${f.message}`)
|
|
424
|
+
return { text: `Nothing was written. The config would not be valid:\n${problems.map((p) => `- ${p}`).join('\n')}`, isError: true }
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const changes = changedPaths(before, next)
|
|
428
|
+
if (changes.length === 0) {
|
|
429
|
+
const look = resolveLook(checked.config)
|
|
430
|
+
return { text: `Nothing changed: the config already says that.\nThe look: ${lookSummary(look)}.${fogWarning(look)}` }
|
|
431
|
+
}
|
|
432
|
+
try {
|
|
433
|
+
await writeAtomic(file, `${JSON.stringify(next, null, 2)}\n`)
|
|
434
|
+
} catch (err) {
|
|
435
|
+
return { text: `${CONFIG} could not be written: ${err.message}`, isError: true }
|
|
436
|
+
}
|
|
437
|
+
const shown = changes.slice(0, 40)
|
|
438
|
+
const more = changes.length > shown.length ? `\n(and ${changes.length - shown.length} more)` : ''
|
|
439
|
+
const look = resolveLook(checked.config)
|
|
440
|
+
return {
|
|
441
|
+
text: `Wrote ${CONFIG}:\n${shown.map((c) => `- ${c}`).join('\n')}${more}\nThe look: ${lookSummary(look)}.${fogWarning(look)}\nLook with nw_view (player) and look_compare.`,
|
|
442
|
+
}
|
|
443
|
+
},
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const lookCompare = {
|
|
447
|
+
name: 'look_compare',
|
|
448
|
+
description:
|
|
449
|
+
'Measures views of the running space against a reference picture in the project and says, in numbers, how far the look is from it: the palette (deltaE2000 between main colours; 6 or less matches, 10 or less is close), mean L* (brightness), contrast and chroma ratios, warmth and tint, clipped highlights and shadows, the brightness of the top, middle and bottom thirds, and by region: the shade (the darkest fifth) and the lit (the brightest fifth) against the reference\'s, the sky band (the top 30%) and the subject below it, and where the edges sit. The verdict (matches, close, far) is the worse of the tone and the shade; the rest is said to steer by. It holds only at the reference\'s framing: take a view from where the reference\'s camera stands (nw_reference\'s camera guess and horizon, the brief\'s camera), since a view from elsewhere (from below, or of a corner) can read close for a space that is far. A uniform border on either picture (a letterbox, a mat) is cut off before measuring. It waits for the space\'s files, the look\'s sky and LUT and the placed models to arrive first, and never judges a picture drawn before they had. Also the look_apply set values that would move it closer. Takes a reference attached by the creator (.nowhere/refs/) or under refs/; never a URL or a picture from ArtStation, Pinterest or Behance. With palette, also how close each of the brief\'s colours comes in the view. Returns the views, never the reference.',
|
|
450
|
+
shape: COMPARE_SHAPE,
|
|
451
|
+
readOnly: true,
|
|
452
|
+
async handler(args, ctx) {
|
|
453
|
+
const root = ctx?.projectRoot
|
|
454
|
+
if (!root) return { text: 'There is no project open.', isError: true }
|
|
455
|
+
const ref = await readReference(root, args.reference)
|
|
456
|
+
if (ref.error) return { text: ref.error, isError: true }
|
|
457
|
+
const shots = (args.views?.length ? args.views : [{ view: 'player' }]).slice(0, 4).map((s) =>
|
|
458
|
+
Object.fromEntries(Object.entries(s).filter(([, v]) => v !== undefined)),
|
|
459
|
+
)
|
|
460
|
+
const rpc = typeof ctx?.rpc === 'function' ? ctx.rpc : async () => ({ ok: false, error: 'The studio is not connected.' })
|
|
461
|
+
const r = await rpc(
|
|
462
|
+
'view',
|
|
463
|
+
// record: false: nw_view's sameAsLast and frozen stay measured from the agent's own last look.
|
|
464
|
+
{ shots, stats: { reference: { data: ref.data, mime: ref.mime } }, settle: { waitMs: LOOK_SETTLE_MS }, record: false },
|
|
465
|
+
viewTimeout(shots.length) + LOOK_SETTLE_MS,
|
|
466
|
+
)
|
|
467
|
+
if (!r?.ok || !Array.isArray(r.shots)) return { text: `No pictures: ${r?.error ?? 'the viewport did not answer.'}`, isError: true }
|
|
468
|
+
|
|
469
|
+
const images = []
|
|
470
|
+
const lines = [`Reference: ${ref.rel}.`]
|
|
471
|
+
const refStats = r.referenceStats ?? null
|
|
472
|
+
const compared = []
|
|
473
|
+
const refused = []
|
|
474
|
+
let stillLoading = false
|
|
475
|
+
r.shots.forEach((s, i) => {
|
|
476
|
+
const n = `${i + 1}. ${s.view ?? shots[i]?.view ?? 'view'}`
|
|
477
|
+
if (!s.ok || !s.image) {
|
|
478
|
+
lines.push(`${n}: no picture: ${s.error ?? 'nothing came back.'}`)
|
|
479
|
+
return
|
|
480
|
+
}
|
|
481
|
+
images.push({ data: s.image.data, mime: s.image.mime ?? 'image/jpeg' })
|
|
482
|
+
// A picture of the space before its files arrived is a picture of
|
|
483
|
+
// another space: shown, so it can be looked at, and not judged.
|
|
484
|
+
const why = notJudged(s)
|
|
485
|
+
if (why) {
|
|
486
|
+
refused.push(n)
|
|
487
|
+
stillLoading ||= s.loading?.mounted === true
|
|
488
|
+
lines.push(`${n}: not judged: ${why}.`)
|
|
489
|
+
} else if (s.stats && refStats) compared.push({ n, stats: s.stats, cmp: compareLook(s.stats, refStats) })
|
|
490
|
+
else lines.push(`${n}: no numbers for this picture${r.statsError ? `: ${r.statsError}` : ''}.`)
|
|
491
|
+
})
|
|
492
|
+
if (!refStats) lines.push(`The reference could not be measured${r.statsError ? `: ${r.statsError}` : ''}.`)
|
|
493
|
+
// Its letterbox or mat is not its look: said, so the numbers read as they are.
|
|
494
|
+
const border = refStats?.border ? Object.entries(refStats.border).filter(([, v]) => v > 0) : []
|
|
495
|
+
if (border.length > 0) lines.push(`The reference's uniform border was cut off before measuring (${border.map(([k, v]) => `${k} ${pct(v)}`).join(', ')}): only the picture inside it is compared.`)
|
|
496
|
+
if (stillLoading) {
|
|
497
|
+
const waited = r.settle ? ` after waiting ${fmt(r.settle.waitedMs / 1000, 1)} s` : ''
|
|
498
|
+
lines.push(`The space had not finished loading${waited}. Check nw_status (loading) and nw_logs for a file that never arrives, then compare again.`)
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
if (compared.length > 0 && refStats) {
|
|
502
|
+
const head = ['', ...compared.map((c) => c.n), 'reference']
|
|
503
|
+
const row = (label, shot, refValue) => [label, ...compared.map(shot), refValue]
|
|
504
|
+
const lab = (v) => (Array.isArray(v) ? `L* ${fmt(v[0], 0)} a* ${fmt(v[1], 0)} b* ${fmt(v[2], 0)}` : '?')
|
|
505
|
+
const region = (g) => (g ? `${fmt(g.paletteDeltaE, 1)} deltaE, L* ${signed(g.deltaMeanL)} (${g.verdict})` : '?')
|
|
506
|
+
const rows = [
|
|
507
|
+
row('verdict', (c) => c.cmp.verdict, ''),
|
|
508
|
+
row('judged by', (c) => Object.entries(c.cmp.verdicts ?? { tone: c.cmp.verdict }).map(([k, v]) => `${k} ${v}`).join(', '), ''),
|
|
509
|
+
row('palette deltaE', (c) => fmt(c.cmp.paletteDeltaE, 1), ''),
|
|
510
|
+
row('mean L*', (c) => `${fmt(c.stats.meanL, 1)} (${signed(c.cmp.deltaMeanL)})`, fmt(refStats.meanL, 1)),
|
|
511
|
+
row('contrast (L* spread)', (c) => `${fmt(c.stats.stdL, 1)} (x${fmt(c.cmp.contrastRatio)})`, fmt(refStats.stdL, 1)),
|
|
512
|
+
row('chroma', (c) => `${fmt(c.stats.meanChroma, 1)} (x${fmt(c.cmp.chromaRatio)})`, fmt(refStats.meanChroma, 1)),
|
|
513
|
+
row('warmth b*', (c) => `${fmt(c.stats.warmth, 1)} (${signed(c.cmp.warmthDelta)})`, fmt(refStats.warmth, 1)),
|
|
514
|
+
row('tint a*', (c) => `${fmt(c.stats.tint, 1)} (${signed(c.cmp.tintDelta)})`, fmt(refStats.tint, 1)),
|
|
515
|
+
row('clipped highlights', (c) => pct(c.stats.clipHigh), pct(refStats.clipHigh)),
|
|
516
|
+
row('crushed shadows', (c) => pct(c.stats.clipLow), pct(refStats.clipLow)),
|
|
517
|
+
row('thirds L* (top/mid/bottom)', (c) => c.stats.thirds.map((v) => fmt(v, 0)).join('/'), refStats.thirds.map((v) => fmt(v, 0)).join('/')),
|
|
518
|
+
row('palette', (c) => c.stats.palette.slice(0, 4).map((p) => `${p.hex} ${pct(p.share)}`).join(', '), refStats.palette.slice(0, 4).map((p) => `${p.hex} ${pct(p.share)}`).join(', ')),
|
|
519
|
+
row('shade, darkest fifth (judged)', (c) => (c.cmp.shade ? `${fmt(c.cmp.shade.deltaE, 1)} deltaE: ${lab(c.cmp.shade.shot)}` : '?'), lab(refStats.shade)),
|
|
520
|
+
row('lit, brightest fifth', (c) => (c.cmp.lit ? `${fmt(c.cmp.lit.deltaE, 1)} deltaE: ${lab(c.cmp.lit.shot)}` : '?'), lab(refStats.lit)),
|
|
521
|
+
row('lit to shade turn (a*b* apart)', (c) => fmt(c.cmp.shadeTurn, 1), ''),
|
|
522
|
+
row('sky band, top 30%', (c) => region(c.cmp.regions?.sky), ''),
|
|
523
|
+
row('subject, below it', (c) => region(c.cmp.regions?.subject), ''),
|
|
524
|
+
row('edge layout (correlation)', (c) => fmt(c.cmp.layout), ''),
|
|
525
|
+
]
|
|
526
|
+
lines.push(`| ${head.join(' | ')} |`, `|${head.map(() => '---').join('|')}|`, ...rows.map((cells) => `| ${cells.join(' | ')} |`))
|
|
527
|
+
|
|
528
|
+
const config = (await readJson(path.join(root, CONFIG))) ?? {}
|
|
529
|
+
const checked = validateConfig(config)
|
|
530
|
+
const current = resolveLook(checked.ok ? checked.config : config)
|
|
531
|
+
const suggestions = suggestLook(meanComparison(compared.map((c) => c.cmp)), current)
|
|
532
|
+
if (suggestions.length) {
|
|
533
|
+
lines.push('Suggested, as look_apply set values (apply, look again, compare again):')
|
|
534
|
+
for (const s of suggestions) lines.push(`- ${s.path} ${fmt(s.from)} -> ${fmt(s.to)}: ${s.why}`)
|
|
535
|
+
} else lines.push('No knob stands out: the remaining difference is in the scene itself (what is in it, its materials, the camera).')
|
|
536
|
+
// The shade is judged but has no one knob: its value and hue come from
|
|
537
|
+
// the fill and the bounce, the sky, the fog and the materials' darks.
|
|
538
|
+
const shadeOff = compared.filter((c) => c.cmp.verdicts?.shade && c.cmp.verdicts.shade !== 'matches')
|
|
539
|
+
if (shadeOff.length > 0) {
|
|
540
|
+
const c = shadeOff[0].cmp
|
|
541
|
+
const dL = c.shade.shot[0] - c.shade.ref[0]
|
|
542
|
+
const dC = Math.hypot(c.shade.shot[1], c.shade.shot[2]) - Math.hypot(c.shade.ref[1], c.shade.ref[2])
|
|
543
|
+
const dB = c.shade.shot[2] - c.shade.ref[2]
|
|
544
|
+
const warmth = Math.abs(dB) < 5 ? '' : `, and ${dB > 0 ? 'warmer' : 'bluer'} (b* ${signed(dB, 0)})`
|
|
545
|
+
lines.push(
|
|
546
|
+
`The shadows are off (shade ${fmt(c.shade.deltaE, 1)} deltaE from the reference's): they are ${Math.abs(dL) < 3 ? 'as light as' : dL > 0 ? `${fmt(dL, 0)} L* lighter than` : `${fmt(-dL, 0)} L* darker than`} the reference's, ${Math.abs(dC) < 3 ? 'about as colourful' : dC > 0 ? 'more colourful' : 'greyer'}${warmth}. Their value and hue come from the fill (lighting.ambient, look.environment, the sky), the fog and the materials' own darks, not from exposure: set them from the reference's shade.`,
|
|
547
|
+
)
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
if (args.palette?.length) {
|
|
551
|
+
lines.push("The brief's palette, nearest colour in each view (deltaE2000; 10 or less reads as that colour):")
|
|
552
|
+
for (const hex of args.palette) {
|
|
553
|
+
const lab = hexToLab(hex)
|
|
554
|
+
const near = compared.map((c) => {
|
|
555
|
+
let best = null
|
|
556
|
+
for (const p of c.stats.palette) {
|
|
557
|
+
const d = deltaE2000(lab, p.lab)
|
|
558
|
+
if (!best || d < best.d) best = { d, hex: p.hex }
|
|
559
|
+
}
|
|
560
|
+
return best ? `${fmt(best.d, 1)} (${best.hex})` : 'none'
|
|
561
|
+
})
|
|
562
|
+
lines.push(`- ${hex}: ${near.join('; ')}`)
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
const verdicts = compared.map((c) => c.cmp.verdict)
|
|
566
|
+
const overall = verdicts.includes('far') ? 'far' : verdicts.includes('close') ? 'close' : 'matches'
|
|
567
|
+
const unjudged = refused.length > 0 ? ` (${refused.length} view${refused.length === 1 ? '' : 's'} not judged)` : ''
|
|
568
|
+
lines.push(`Overall: ${overall}${unjudged}.${overall === 'far' ? ' Fix the biggest difference first.' : ''}`)
|
|
569
|
+
} else if (refused.length > 0) lines.push('Overall: not judged.')
|
|
570
|
+
|
|
571
|
+
// Only pictures that came back are a look at the game, and only judged
|
|
572
|
+
// ones are a comparison.
|
|
573
|
+
const failed = images.length === 0 || (compared.length === 0 && refused.length > 0)
|
|
574
|
+
return { text: lines.join('\n'), images, verifies: images.length > 0 ? 'view' : null, ...(failed ? { isError: true } : {}) }
|
|
575
|
+
},
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
export const TOOLS = [lookApply, lookCompare]
|