@playcanvas/supersplat-viewer 1.29.3 → 1.30.0

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/module/render-html.ts","../src/module/index.ts"],"sourcesContent":["import css from '../../public/index.css';\nimport html from '../../public/index.html';\nimport js from '../../public/index.js';\n\n/**\n * Asset urls and settings the embedder supplies to the viewer.\n *\n * Url params on the served page take precedence over every url here, so an embed stays\n * overridable per instance. Inline {@link ViewerBootstrap.settings} is the exception: it wins\n * over `?settings=`, so a published experience cannot be repointed at another settings file.\n */\ntype ViewerBootstrap = {\n /**\n * Experience settings as an object, avoiding a round trip. When omitted the viewer\n * fetches {@link ViewerBootstrap.settingsUrl}.\n */\n settings?: unknown;\n /** Where to fetch settings from. Defaults to `./settings.json`. */\n settingsUrl?: string;\n /** Splat url. May be a `data:` uri, for a document with no sibling files. */\n contentUrl?: string;\n /** Poster image shown, blurred, while the splat loads. */\n posterUrl?: string;\n /** Equirectangular skybox texture url. */\n skyboxUrl?: string;\n /** Collision data url, for walk mode. A `.glb` is treated as a mesh, otherwise voxels. */\n collisionUrl?: string;\n};\n\n/** Options for {@link renderViewerHtml}. */\ntype RenderViewerHtmlOptions = {\n /** Asset urls and settings for the viewer to boot with. */\n bootstrap?: ViewerBootstrap;\n /** Value for the document's `<base href>`, for a viewer served from a sub-path. */\n baseHref?: string;\n /**\n * Page background, applied before the first frame renders to avoid a flash. Components\n * are normalized 0..1, not 0..255, matching `background.color` in the settings format —\n * so an experience's own colour can be passed straight through.\n */\n backgroundColor?: readonly [number, number, number];\n /** Raw markup injected before `</head>`, for analytics or error reporting. */\n headExtras?: string;\n /**\n * Raw markup injected immediately after `<body>`, for content that must precede the\n * canvas — a marker element a screenshot pipeline waits on, for example.\n */\n bodyStartExtras?: string;\n /** Inline the stylesheet into a `<style>` block instead of linking `./index.css`. */\n inlineCss?: boolean;\n /**\n * Inline the module bundle instead of importing `./index.js`. Independent of\n * {@link RenderViewerHtmlOptions.inlineCss}: a host serving the bundle from its own route\n * wants the css inlined to avoid a round trip before first paint, but not a megabyte of\n * js in every page.\n */\n inlineJs?: boolean;\n};\n\ntype Replacer = (match: string, ...groups: string[]) => string;\n\n// The seams below are matched against this package's own `index.html`, so a miss means the\n// document and this function have drifted apart within one release — a build-time invariant,\n// not a bad caller. Throw rather than return a half-rendered document.\n//\n// Every replacement is a function, so `$&`-style sequences in settings json, urls or the\n// bundle are inserted literally instead of being interpreted as replacement patterns.\n// Annotation text is user-authored, so this matters.\nconst replaceOnce = (source: string, pattern: RegExp, replacement: Replacer) => {\n if (!pattern.test(source)) {\n throw new Error(`renderViewerHtml: no match for ${String(pattern)} in the viewer html`);\n }\n return source.replace(pattern, replacement);\n};\n\n// Serialize for embedding in a `<script type=\"application/json\">` block. Every `<` is\n// escaped with its json unicode escape (so the payload round-trips byte-exact), which\n// neutralises all of the parser's script-content hazards at once: `</script` ending\n// the block early, and `<!--` followed by `<script` switching the tokenizer into the\n// double-escaped state, where the block's own close tag is consumed as text and the rest of\n// the document is swallowed. U+2028/U+2029 are escaped because they are legal in json\n// strings but terminate a line in some js parsers.\nconst jsonForScriptBlock = (value: unknown) => {\n return JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n};\n\n// Escape for use inside a double-quoted html attribute. `headExtras` is documented as raw\n// markup and is deliberately not escaped, but scalar options like `baseHref` are not an\n// injection channel and a caller passing one through from user input should be safe.\nconst escapeAttribute = (value: string) => {\n return value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n};\n\nconst indent = (text: string, spaces: number) => {\n const whitespace = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => whitespace + line)\n .join('\\n');\n};\n\nconst BOOTSTRAP = /<script type=\"application\\/json\" id=\"sse-bootstrap\">[\\s\\S]*?<\\/script>/;\nconst BASE_HREF = /<base\\b[^>]*>/;\nconst STYLESHEET = /<link\\b[^>]*href=\"\\.\\/index\\.css\"[^>]*>/;\nconst MODULE_IMPORT = /import \\{ main \\} from '\\.\\/index\\.js';/;\nconst HEAD_CLOSE = /^([ \\t]*)<\\/head>/m;\nconst BODY_OPEN = /<body\\b[^>]*>/;\n\n/**\n * Render a standalone viewer document.\n *\n * This is the supported way to embed the viewer in a page you generate. Called with no\n * options it returns the document this package ships, unmodified.\n *\n * @param options - Embedding options; see {@link RenderViewerHtmlOptions}.\n * @returns The rendered html document.\n */\nconst renderViewerHtml = (options: RenderViewerHtmlOptions = {}) => {\n const { bootstrap, baseHref, backgroundColor, headExtras, bodyStartExtras, inlineCss, inlineJs } = options;\n\n let result = html;\n\n // Order matters. Each seam is matched with a non-global regex, so the *first* occurrence\n // in the document wins — and caller-controlled content (the bootstrap json, `headExtras`)\n // can contain text that looks like a seam. Settings carry user-authored annotation text,\n // so treat that as hostile. Every seam is therefore replaced before any caller content is\n // inserted, and the two insertions go last, in document order.\n\n if (baseHref !== undefined) {\n result = replaceOnce(result, BASE_HREF, () => `<base href=\"${escapeAttribute(baseHref)}\">`);\n }\n\n if (inlineCss) {\n // A `<style>` element is rawtext: it ends at the first `</style` regardless of css\n // syntax, so a stylesheet containing that sequence cannot be inlined. The built css\n // contains no `<` at all today; fail loudly if that ever changes.\n if (/<\\/style/i.test(css)) {\n throw new Error('renderViewerHtml: the viewer stylesheet contains \"</style\" and cannot be inlined');\n }\n result = replaceOnce(result, STYLESHEET, () => `<style>\\n${indent(css, 12)}\\n </style>`);\n }\n\n if (inlineJs) {\n // The bundle's trailing sourceMappingURL comment points at a sibling index.js.map\n // that an inlined document does not sit next to, so devtools would 404 on it (or\n // bind whatever stranger's map the host serves at that path).\n const inlineJsSource = js.replace(/\\n\\/\\/# sourceMappingURL=\\S+\\s*$/, '\\n');\n\n // An inline module script ends at the first `</script`, and `<!--` followed by\n // `<script` switches the tokenizer into a state where that close tag is consumed as\n // text instead — either way the symptom is an exported file that renders nothing.\n // The bundle contains none of these today; fail loudly if that ever changes.\n // Case-insensitive, because the html parser is.\n if (/<\\/script|<!--|<script/i.test(inlineJsSource)) {\n throw new Error(\n 'renderViewerHtml: the viewer bundle contains markup the html parser acts on and cannot be inlined'\n );\n }\n result = replaceOnce(result, MODULE_IMPORT, () => inlineJsSource);\n }\n\n if (bodyStartExtras !== undefined) {\n result = replaceOnce(result, BODY_OPEN, (bodyTag) => `${bodyTag}\\n ${bodyStartExtras}`);\n }\n\n const headAppend: string[] = [];\n if (headExtras !== undefined) {\n headAppend.push(headExtras);\n }\n if (backgroundColor) {\n const rgb = backgroundColor.map((c) => Math.round(c * 255)).join(', ');\n headAppend.push(`<style>body { background-color: rgb(${rgb}); }</style>`);\n }\n\n // Emitted at the end of head, so the background rule wins over the stylesheet on equal\n // specificity. Only the first line gains indentation: `headExtras` is raw markup, and\n // reindenting its interior lines would rewrite whitespace-sensitive content (a template\n // literal in an inline script, for instance).\n if (headAppend.length > 0) {\n result = replaceOnce(result, HEAD_CLOSE, (_match, ws) => `${ws} ${headAppend.join('\\n')}\\n${ws}</head>`);\n }\n\n // Last: the bootstrap block sits earlier in the document than `</head>`, so its own seam\n // still matches ahead of anything `headExtras` added.\n if (bootstrap) {\n const json = jsonForScriptBlock(bootstrap);\n result = replaceOnce(\n result,\n BOOTSTRAP,\n () => `<script type=\"application/json\" id=\"sse-bootstrap\">${json}</script>`\n );\n }\n\n return result;\n};\n\nexport type { RenderViewerHtmlOptions, ViewerBootstrap };\nexport { renderViewerHtml };\n","import cssSource from '../../public/index.css';\nimport htmlSource from '../../public/index.html';\nimport jsSource from '../../public/index.js';\n\n/**\n * The viewer's html document.\n *\n * @deprecated Use {@link renderViewerHtml} instead. Pattern-matching this string is\n * unsupported — its formatting is not part of this package's api and changes between\n * releases.\n */\nconst html: string = htmlSource;\n\n/**\n * The viewer's stylesheet.\n *\n * @deprecated Use {@link renderViewerHtml} instead, which can inline it for you.\n */\nconst css: string = cssSource;\n\n/** The viewer's module bundle, for serving alongside a rendered document. */\nconst js: string = jsSource;\n\nexport type { RenderViewerHtmlOptions, ViewerBootstrap } from './render-html';\nexport { renderViewerHtml } from './render-html';\n\nexport { html, css, js };\n"],"names":["html","css","js"],"mappings":";;;;;;AA6DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,CAAC,MAAc,EAAE,OAAe,EAAE,WAAqB,KAAI;IAC3E,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;QACvB,MAAM,IAAI,KAAK,CAAC,CAAA,+BAAA,EAAkC,MAAM,CAAC,OAAO,CAAC,CAAA,mBAAA,CAAqB,CAAC;IAC3F;IACA,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,WAAW,CAAC;AAC/C,CAAC;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,kBAAkB,GAAG,CAAC,KAAc,KAAI;AAC1C,IAAA,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK;AACtB,SAAA,OAAO,CAAC,IAAI,EAAE,SAAS;AACvB,SAAA,OAAO,CAAC,SAAS,EAAE,SAAS;AAC5B,SAAA,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;AACtC,CAAC;AAED;AACA;AACA;AACA,MAAM,eAAe,GAAG,CAAC,KAAa,KAAI;AACtC,IAAA,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;AAC3G,CAAC;AAED,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,MAAc,KAAI;IAC5C,MAAM,UAA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jMA;;;;;;AAMG;AACH,MAAM,IAAI,GAAW;AAErB;;;;AAIG;AACH,MAAM,GAAG,GAAW;AAEpB;AACA,MAAM,EAAE,GAAW;;;;"}
@@ -1,4 +1,5 @@
1
- export type AnimTrack = {
1
+ /** A camera animation track. Only the first track in a settings file is played. */
2
+ type AnimTrack = {
2
3
  name: string;
3
4
  duration: number;
4
5
  frameRate: number;
@@ -14,26 +15,26 @@ export type AnimTrack = {
14
15
  };
15
16
  };
16
17
  };
17
-
18
- export type CameraPose = {
18
+ /** A camera position, look-at target and vertical field of view in degrees. */
19
+ type CameraPose = {
19
20
  position: [number, number, number];
20
21
  target: [number, number, number];
21
22
  fov: number;
22
23
  };
23
-
24
- export type Camera = {
24
+ /** A camera. Only the first camera in a settings file is used. */
25
+ type Camera = {
25
26
  initial: CameraPose;
26
27
  };
27
-
28
- export type Annotation = {
28
+ /** A point of interest in the scene, with the camera framing used to view it. */
29
+ type Annotation = {
29
30
  position: [number, number, number];
30
31
  title: string;
31
32
  text: string;
32
33
  extras?: unknown;
33
34
  camera: Camera;
34
35
  };
35
-
36
- export type PostEffectSettings = {
36
+ /** Post-processing applied to the rendered image. Each effect is independently toggled. */
37
+ type PostEffectSettings = {
37
38
  sharpness: {
38
39
  enabled: boolean;
39
40
  amount: number;
@@ -62,8 +63,13 @@ export type PostEffectSettings = {
62
63
  intensity: number;
63
64
  };
64
65
  };
65
-
66
- export type ExperienceSettings = {
66
+ /**
67
+ * A published experience: what is in the scene and how it is presented.
68
+ *
69
+ * This is the wire format of `settings.json`. Read it with {@link importSettings}, which
70
+ * migrates older versions forward.
71
+ */
72
+ type ExperienceSettings = {
67
73
  version: 2;
68
74
  tonemapping: 'none' | 'linear' | 'filmic' | 'hejl' | 'aces' | 'aces2' | 'neutral';
69
75
  highPrecisionRendering: boolean;
@@ -79,5 +85,128 @@ export type ExperienceSettings = {
79
85
  startMode: 'default' | 'animTrack' | 'annotation';
80
86
  };
81
87
 
82
- export function importSettings(settings: unknown): ExperienceSettings;
83
- export function validateSettings(settings: unknown): void;
88
+ /** An inclusive numeric bound. `step` is UI granularity, not a constraint. */
89
+ type NumericRange = {
90
+ readonly min: number;
91
+ readonly max: number;
92
+ readonly step: number;
93
+ };
94
+ /**
95
+ * Bounds for each post-processing parameter, taken from the PlayCanvas engine's documented
96
+ * ranges (`CameraFrame`, and `RenderPassBloom` for `blurLevel`).
97
+ */
98
+ type PostEffectRanges = {
99
+ readonly sharpness: {
100
+ readonly amount: NumericRange;
101
+ };
102
+ readonly bloom: {
103
+ readonly intensity: NumericRange;
104
+ readonly blurLevel: NumericRange;
105
+ };
106
+ readonly grading: {
107
+ readonly brightness: NumericRange;
108
+ readonly contrast: NumericRange;
109
+ readonly saturation: NumericRange;
110
+ };
111
+ readonly vignette: {
112
+ readonly intensity: NumericRange;
113
+ readonly inner: NumericRange;
114
+ readonly outer: NumericRange;
115
+ readonly curvature: NumericRange;
116
+ };
117
+ readonly fringing: {
118
+ readonly intensity: NumericRange;
119
+ };
120
+ };
121
+ /** Bounds for a camera's vertical field of view, in degrees. */
122
+ declare const CAMERA_FOV_RANGE: NumericRange;
123
+ /** Bounds for each post-processing parameter. */
124
+ declare const POST_EFFECT_RANGES: PostEffectRanges;
125
+ /** An inclusive bound with no UI step. */
126
+ type Bounds = {
127
+ readonly min: number;
128
+ readonly max: number;
129
+ };
130
+ /** Bounds and size limits for camera animation tracks. */
131
+ type AnimTrackLimits = {
132
+ readonly duration: Bounds;
133
+ readonly frameRate: Bounds;
134
+ readonly smoothness: Bounds;
135
+ readonly maxKeyframes: number;
136
+ readonly nameMax: number;
137
+ readonly maxTracks: number;
138
+ };
139
+ /** Size limits for annotations. */
140
+ type AnnotationLimits = {
141
+ readonly maxCount: number;
142
+ readonly titleMax: number;
143
+ readonly textMax: number;
144
+ };
145
+ /** Bounds and size limits for camera animation tracks. Intentionally tight for now. */
146
+ declare const ANIM_TRACK_LIMITS: AnimTrackLimits;
147
+ /** Size limits for annotations. Intentionally tight for now. */
148
+ declare const ANNOTATION_LIMITS: AnnotationLimits;
149
+ /**
150
+ * Test a field of view against {@link CAMERA_FOV_RANGE}.
151
+ *
152
+ * @param fov - Vertical field of view in degrees.
153
+ * @returns Whether the value is within the authoring bounds.
154
+ */
155
+ declare const isCameraFovInRange: (fov: number) => boolean;
156
+
157
+ /** Default page and scene background, as normalized 0..1 rgb components. */
158
+ declare const DEFAULT_BACKGROUND_COLOR: readonly [number, number, number];
159
+ /** Default tonemapping curve. */
160
+ declare const DEFAULT_TONEMAPPING: ExperienceSettings['tonemapping'];
161
+ /** Default vertical field of view, in degrees. */
162
+ declare const DEFAULT_CAMERA_FOV: number;
163
+ /**
164
+ * How the default camera is placed: `environment` frames a captured space from inside it,
165
+ * `object` frames a subject from outside.
166
+ */
167
+ type CameraFit = 'environment' | 'object';
168
+ /**
169
+ * Default post-processing settings, with every effect disabled.
170
+ *
171
+ * @returns A fresh object; callers may mutate it freely.
172
+ */
173
+ declare const defaultPostEffectSettings: () => PostEffectSettings;
174
+ /**
175
+ * Default experience settings, shared by every tool that writes a settings file.
176
+ *
177
+ * @param fit - How to place the default camera. Defaults to `environment`.
178
+ * @returns A fresh object; callers may mutate it freely.
179
+ */
180
+ declare const defaultSettings: (fit?: CameraFit) => ExperienceSettings;
181
+
182
+ /**
183
+ * Migrate settings of any supported version to the latest schema.
184
+ *
185
+ * Assumes valid input — call {@link validateSettings} first if the source is untrusted. Does
186
+ * not mutate the object passed in.
187
+ *
188
+ * @param settings - Parsed contents of a settings file.
189
+ * @returns The settings at the latest version.
190
+ * @throws If the version is not supported.
191
+ */
192
+ declare const importSettings: (settings: unknown) => ExperienceSettings;
193
+ /** Options for {@link validateSettings}. */
194
+ type ValidateOptions = {
195
+ /**
196
+ * Also check the exported authoring bounds. Off by default: those bounds are stricter
197
+ * than what the viewer will render, and some settings in the wild fail them. Producers
198
+ * writing new settings should turn this on.
199
+ */
200
+ limits?: boolean;
201
+ };
202
+ /**
203
+ * Validate unknown data against any supported settings schema version.
204
+ *
205
+ * @param settings - Data to validate.
206
+ * @param options - See {@link ValidateOptions}.
207
+ * @throws If the data is not valid settings, with a message naming the offending field.
208
+ */
209
+ declare const validateSettings: (settings: unknown, options?: ValidateOptions) => void;
210
+
211
+ export { ANIM_TRACK_LIMITS, ANNOTATION_LIMITS, CAMERA_FOV_RANGE, DEFAULT_BACKGROUND_COLOR, DEFAULT_CAMERA_FOV, DEFAULT_TONEMAPPING, POST_EFFECT_RANGES, defaultPostEffectSettings, defaultSettings, importSettings, isCameraFovInRange, validateSettings };
212
+ export type { AnimTrack, AnimTrackLimits, Annotation, AnnotationLimits, Bounds, Camera, CameraFit, CameraPose, ExperienceSettings, NumericRange, PostEffectRanges, PostEffectSettings, ValidateOptions };
package/dist/settings.js CHANGED
@@ -1,3 +1,79 @@
1
+ // The single source of default experience settings, so every tool that writes a settings file
2
+ // agrees. Several independent copies of these values had drifted apart; these are the ones
3
+ // matching the settings already published in the wild, which means some producers change:
4
+ // `tonemapping` is 'linear' rather than 'none', `background.color` is black rather than 0.4
5
+ // grey, `bloom.intensity` is 0.1 rather than 1 (1 falls outside the authoring range in
6
+ // ranges.ts) and `grading.brightness` is 1 rather than 0.
7
+ // Frozen: `defaultSettings()` copies this, so a consumer mutating it would otherwise change
8
+ // every later call's result.
9
+ /** Default page and scene background, as normalized 0..1 rgb components. */
10
+ const DEFAULT_BACKGROUND_COLOR = Object.freeze([0, 0, 0]);
11
+ /** Default tonemapping curve. */
12
+ const DEFAULT_TONEMAPPING = 'linear';
13
+ /** Default vertical field of view, in degrees. */
14
+ // Annotated so the published declaration widens to `number`; without it the emitted type is
15
+ // the literal `75`, which bakes the value into the api.
16
+ // eslint-disable-next-line @typescript-eslint/no-inferrable-types
17
+ const DEFAULT_CAMERA_FOV = 85;
18
+ const defaultCameraPose = (fit = 'environment') => {
19
+ return fit === 'environment'
20
+ ? { position: [0, 2, 0], target: [2, 2, 0], fov: DEFAULT_CAMERA_FOV }
21
+ : { position: [2, 2, -2], target: [0, 0, 0], fov: DEFAULT_CAMERA_FOV };
22
+ };
23
+ /**
24
+ * Default post-processing settings, with every effect disabled.
25
+ *
26
+ * @returns A fresh object; callers may mutate it freely.
27
+ */
28
+ const defaultPostEffectSettings = () => ({
29
+ sharpness: {
30
+ enabled: false,
31
+ amount: 0
32
+ },
33
+ bloom: {
34
+ enabled: false,
35
+ intensity: 0.1,
36
+ blurLevel: 2
37
+ },
38
+ grading: {
39
+ enabled: false,
40
+ brightness: 1,
41
+ contrast: 1,
42
+ saturation: 1,
43
+ tint: [1, 1, 1]
44
+ },
45
+ vignette: {
46
+ enabled: false,
47
+ intensity: 0.5,
48
+ inner: 0.3,
49
+ outer: 0.75,
50
+ curvature: 1
51
+ },
52
+ fringing: {
53
+ enabled: false,
54
+ intensity: 0.5
55
+ }
56
+ });
57
+ /**
58
+ * Default experience settings, shared by every tool that writes a settings file.
59
+ *
60
+ * @param fit - How to place the default camera. Defaults to `environment`.
61
+ * @returns A fresh object; callers may mutate it freely.
62
+ */
63
+ const defaultSettings = (fit = 'environment') => ({
64
+ version: 2,
65
+ tonemapping: DEFAULT_TONEMAPPING,
66
+ highPrecisionRendering: false,
67
+ background: {
68
+ color: [...DEFAULT_BACKGROUND_COLOR]
69
+ },
70
+ postEffectSettings: defaultPostEffectSettings(),
71
+ animTracks: [],
72
+ cameras: [{ initial: defaultCameraPose(fit) }],
73
+ annotations: [],
74
+ startMode: 'default'
75
+ });
76
+
1
77
  const assertObject = (value, path) => {
2
78
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
3
79
  throw new Error(`${path} must be an object`);
@@ -72,17 +148,19 @@ const validateV1 = (data) => {
72
148
  const camera = assertObject(obj.camera, 'settings.camera');
73
149
  if (camera.fov !== undefined)
74
150
  assertNumber(camera.fov, 'settings.camera.fov');
151
+ // Exactly 3 elements: migration casts these straight into v2 tuples, so any other arity
152
+ // would validate here yet produce output that fails v2 validation.
75
153
  if (camera.position !== undefined)
76
- assertNumberArray(camera.position, 'settings.camera.position');
154
+ assertTuple3(camera.position, 'settings.camera.position');
77
155
  if (camera.target !== undefined)
78
- assertNumberArray(camera.target, 'settings.camera.target');
156
+ assertTuple3(camera.target, 'settings.camera.target');
79
157
  if (camera.startAnim !== undefined)
80
158
  assertEnum(camera.startAnim, ['none', 'orbit', 'animTrack'], 'settings.camera.startAnim');
81
159
  if (camera.animTrack != null)
82
160
  assertString(camera.animTrack, 'settings.camera.animTrack');
83
161
  const bg = assertObject(obj.background, 'settings.background');
84
162
  if (bg.color !== undefined)
85
- assertNumberArray(bg.color, 'settings.background.color');
163
+ assertTuple3(bg.color, 'settings.background.color');
86
164
  if (obj.animTracks !== undefined) {
87
165
  const tracks = assertArray(obj.animTracks, 'settings.animTracks');
88
166
  tracks.forEach((t, i) => validateAnimTrack$1(t, `settings.animTracks[${i}]`));
@@ -176,7 +254,200 @@ const validateV2 = (data) => {
176
254
  return data;
177
255
  };
178
256
 
179
- const migrateV1 = (settings) => {
257
+ // Authoring bounds for experience settings, shared by the settings validators and by editor
258
+ // UIs that need slider ranges. Pure data with no imports, so a consumer can take these
259
+ // without pulling in the schema.
260
+ //
261
+ // These are *authoring* limits, not read limits: the viewer renders values outside them
262
+ // perfectly well, and settings in the wild contain some (see validate-limits.ts).
263
+ // `step` is UI granularity, not a constraint.
264
+ // These are published constants that the validators themselves read, so a consumer mutating
265
+ // one would silently change validation for everyone in the realm. Freeze rather than rely on
266
+ // `as const`, which is erased at runtime.
267
+ const deepFreeze = (value) => {
268
+ if (value !== null && typeof value === 'object') {
269
+ Object.values(value).forEach(deepFreeze);
270
+ Object.freeze(value);
271
+ }
272
+ return value;
273
+ };
274
+ /** Bounds for a camera's vertical field of view, in degrees. */
275
+ const CAMERA_FOV_RANGE = deepFreeze({
276
+ min: 10,
277
+ max: 120,
278
+ step: 1
279
+ });
280
+ /** Bounds for each post-processing parameter. */
281
+ const POST_EFFECT_RANGES = deepFreeze({
282
+ sharpness: {
283
+ amount: { min: 0, max: 1, step: 0.01 }
284
+ },
285
+ bloom: {
286
+ intensity: { min: 0, max: 0.1, step: 0.01 },
287
+ blurLevel: { min: 1, max: 16, step: 1 }
288
+ },
289
+ grading: {
290
+ brightness: { min: 0, max: 3, step: 0.01 },
291
+ contrast: { min: 0.5, max: 1.5, step: 0.01 },
292
+ saturation: { min: 0, max: 2, step: 0.01 }
293
+ },
294
+ vignette: {
295
+ intensity: { min: 0, max: 1, step: 0.01 },
296
+ inner: { min: 0, max: 3, step: 0.01 },
297
+ outer: { min: 0, max: 3, step: 0.01 },
298
+ curvature: { min: 0.01, max: 10, step: 0.01 }
299
+ },
300
+ fringing: {
301
+ intensity: { min: 0, max: 100, step: 1 }
302
+ }
303
+ });
304
+ // Annotated rather than `as const`: the annotation keeps them readonly while widening the
305
+ // values, so the published types do not bake in numbers we may want to relax later.
306
+ /** Bounds and size limits for camera animation tracks. Intentionally tight for now. */
307
+ const ANIM_TRACK_LIMITS = deepFreeze({
308
+ duration: { min: 0.1, max: 600 },
309
+ frameRate: { min: 1, max: 120 },
310
+ smoothness: { min: 0, max: 1 },
311
+ maxKeyframes: 1000,
312
+ nameMax: 120,
313
+ maxTracks: 10
314
+ });
315
+ /** Size limits for annotations. Intentionally tight for now. */
316
+ const ANNOTATION_LIMITS = deepFreeze({
317
+ maxCount: 25,
318
+ titleMax: 60,
319
+ textMax: 280
320
+ });
321
+ /**
322
+ * Test a field of view against {@link CAMERA_FOV_RANGE}.
323
+ *
324
+ * @param fov - Vertical field of view in degrees.
325
+ * @returns Whether the value is within the authoring bounds.
326
+ */
327
+ const isCameraFovInRange = (fov) => {
328
+ return fov >= CAMERA_FOV_RANGE.min && fov <= CAMERA_FOV_RANGE.max;
329
+ };
330
+
331
+ // Authoring-limit checks, deliberately separate from the shape validation in v2.ts.
332
+ //
333
+ // Shape validation answers "can the viewer read this" and must keep accepting every settings
334
+ // file ever written. These limits answer "is this sane input from an editor" and are stricter
335
+ // — strictly enough that some existing data fails them. `bloom.intensity` is the known case:
336
+ // the range caps it at 0.1, while several older default objects wrote 1. So this runs only on
337
+ // request, via `validateSettings(x, { limits: true })`, and never on the viewer's read path.
338
+ const range = (value, bounds, path) => {
339
+ if (value < bounds.min || value > bounds.max) {
340
+ throw new Error(`${path} must be between ${bounds.min} and ${bounds.max}, got ${value}`);
341
+ }
342
+ };
343
+ const maxLength = (value, max, path) => {
344
+ if (value.length > max) {
345
+ throw new Error(`${path} must be at most ${max} characters, got ${value.length}`);
346
+ }
347
+ };
348
+ const maxCount = (value, max, path) => {
349
+ if (value.length > max) {
350
+ throw new Error(`${path} must have at most ${max} entries, got ${value.length}`);
351
+ }
352
+ };
353
+ const validateLimitsV2 = (settings) => {
354
+ const fx = settings.postEffectSettings;
355
+ range(fx.sharpness.amount, POST_EFFECT_RANGES.sharpness.amount, 'settings.postEffectSettings.sharpness.amount');
356
+ range(fx.bloom.intensity, POST_EFFECT_RANGES.bloom.intensity, 'settings.postEffectSettings.bloom.intensity');
357
+ range(fx.bloom.blurLevel, POST_EFFECT_RANGES.bloom.blurLevel, 'settings.postEffectSettings.bloom.blurLevel');
358
+ range(fx.grading.brightness, POST_EFFECT_RANGES.grading.brightness, 'settings.postEffectSettings.grading.brightness');
359
+ range(fx.grading.contrast, POST_EFFECT_RANGES.grading.contrast, 'settings.postEffectSettings.grading.contrast');
360
+ range(fx.grading.saturation, POST_EFFECT_RANGES.grading.saturation, 'settings.postEffectSettings.grading.saturation');
361
+ range(fx.vignette.intensity, POST_EFFECT_RANGES.vignette.intensity, 'settings.postEffectSettings.vignette.intensity');
362
+ range(fx.vignette.inner, POST_EFFECT_RANGES.vignette.inner, 'settings.postEffectSettings.vignette.inner');
363
+ range(fx.vignette.outer, POST_EFFECT_RANGES.vignette.outer, 'settings.postEffectSettings.vignette.outer');
364
+ range(fx.vignette.curvature, POST_EFFECT_RANGES.vignette.curvature, 'settings.postEffectSettings.vignette.curvature');
365
+ range(fx.fringing.intensity, POST_EFFECT_RANGES.fringing.intensity, 'settings.postEffectSettings.fringing.intensity');
366
+ // no count limit on cameras — the viewer only reads cameras[0], but the format allows more
367
+ settings.cameras.forEach((camera, i) => {
368
+ range(camera.initial.fov, CAMERA_FOV_RANGE, `settings.cameras[${i}].initial.fov`);
369
+ });
370
+ maxCount(settings.animTracks, ANIM_TRACK_LIMITS.maxTracks, 'settings.animTracks');
371
+ settings.animTracks.forEach((track, i) => {
372
+ const path = `settings.animTracks[${i}]`;
373
+ maxLength(track.name, ANIM_TRACK_LIMITS.nameMax, `${path}.name`);
374
+ range(track.duration, ANIM_TRACK_LIMITS.duration, `${path}.duration`);
375
+ range(track.frameRate, ANIM_TRACK_LIMITS.frameRate, `${path}.frameRate`);
376
+ if (!Number.isInteger(track.frameRate)) {
377
+ throw new Error(`${path}.frameRate must be an integer, got ${track.frameRate}`);
378
+ }
379
+ range(track.smoothness, ANIM_TRACK_LIMITS.smoothness, `${path}.smoothness`);
380
+ // Keyframe times are frame numbers: non-negative integers, strictly ascending, since
381
+ // the spline is built from them in order.
382
+ const { times, values } = track.keyframes;
383
+ maxCount(times, ANIM_TRACK_LIMITS.maxKeyframes, `${path}.keyframes.times`);
384
+ // At least one: `CubicSpline.calcKnots` derives its dimension as
385
+ // `points.length / times.length`, so an empty track computes 0/0 and allocates
386
+ // `new Array(NaN)`, which throws. A track the viewer cannot load is not valid input.
387
+ if (times.length === 0) {
388
+ throw new Error(`${path}.keyframes.times must have at least one keyframe`);
389
+ }
390
+ times.forEach((time, k) => {
391
+ const at = `${path}.keyframes.times[${k}]`;
392
+ if (time < 0) {
393
+ throw new Error(`${at} must be non-negative, got ${time}`);
394
+ }
395
+ if (!Number.isInteger(time)) {
396
+ throw new Error(`${at} must be an integer, got ${time}`);
397
+ }
398
+ if (k > 0 && time <= times[k - 1]) {
399
+ throw new Error(`${at} must be greater than the previous frame, got ${time}`);
400
+ }
401
+ });
402
+ // The track is flattened into one spline, so a mis-sized array silently stops the
403
+ // animation rather than failing loudly at runtime.
404
+ const vectorValues = times.length * 3;
405
+ if (values.position.length !== vectorValues) {
406
+ throw new Error(`${path}.keyframes.values.position must have 3 values per keyframe (${vectorValues}), got ${values.position.length}`);
407
+ }
408
+ if (values.target.length !== vectorValues) {
409
+ throw new Error(`${path}.keyframes.values.target must have 3 values per keyframe (${vectorValues}), got ${values.target.length}`);
410
+ }
411
+ if (values.fov.length !== times.length) {
412
+ throw new Error(`${path}.keyframes.values.fov must have 1 value per keyframe (${times.length}), got ${values.fov.length}`);
413
+ }
414
+ // No CAMERA_FOV_RANGE check on keyframes.values.fov: the validator this reaches parity
415
+ // with does not bound those either, and they are splined rather than set directly.
416
+ });
417
+ maxCount(settings.annotations, ANNOTATION_LIMITS.maxCount, 'settings.annotations');
418
+ settings.annotations.forEach((annotation, i) => {
419
+ const path = `settings.annotations[${i}]`;
420
+ maxLength(annotation.title, ANNOTATION_LIMITS.titleMax, `${path}.title`);
421
+ maxLength(annotation.text, ANNOTATION_LIMITS.textMax, `${path}.text`);
422
+ range(annotation.camera.initial.fov, CAMERA_FOV_RANGE, `${path}.camera.initial.fov`);
423
+ });
424
+ };
425
+ // The v1 -> v2 migration substitutes defaults for falsy values — `frameRate: 0` becomes 30,
426
+ // `camera.fov: 0` becomes the default fov — so a post-migration check cannot see them and an
427
+ // explicitly invalid zero would pass. Check those fields as the caller supplied them.
428
+ //
429
+ // Only the coerced fields are checked here; everything else survives migration unchanged and
430
+ // is covered by validateLimitsV2.
431
+ const validateLimitsV1 = (settings) => {
432
+ if (settings.camera.fov !== undefined) {
433
+ range(settings.camera.fov, CAMERA_FOV_RANGE, 'settings.camera.fov');
434
+ }
435
+ settings.animTracks?.forEach((track, i) => {
436
+ if (track.frameRate === undefined) {
437
+ return;
438
+ }
439
+ const path = `settings.animTracks[${i}].frameRate`;
440
+ range(track.frameRate, ANIM_TRACK_LIMITS.frameRate, path);
441
+ if (!Number.isInteger(track.frameRate)) {
442
+ throw new Error(`${path} must be an integer, got ${track.frameRate}`);
443
+ }
444
+ });
445
+ };
446
+
447
+ const migrateV1 = (input) => {
448
+ // Copy first: callers own the object they pass in, and an API consumer holding a
449
+ // reference should not see it rewritten underneath them.
450
+ const settings = structuredClone(input);
180
451
  if (settings.animTracks) {
181
452
  settings.animTracks?.forEach((track) => {
182
453
  // some early settings did not have frameRate set on anim tracks
@@ -222,42 +493,20 @@ const migrateAnimTrackV2 = (animTrackV1, fov) => {
222
493
  const migrateV2 = (v1) => {
223
494
  return {
224
495
  version: 2,
496
+ // Not the shared default ('linear'): tonemapping applies unconditionally, so changing
497
+ // it here would alter how existing v1 content renders.
225
498
  tonemapping: 'none',
226
499
  highPrecisionRendering: false,
227
500
  background: {
228
501
  color: v1.background.color || [0, 0, 0]
229
502
  },
230
- postEffectSettings: {
231
- sharpness: {
232
- enabled: false,
233
- amount: 0
234
- },
235
- bloom: {
236
- enabled: false,
237
- intensity: 1,
238
- blurLevel: 2
239
- },
240
- grading: {
241
- enabled: false,
242
- brightness: 0,
243
- contrast: 1,
244
- saturation: 1,
245
- tint: [1, 1, 1]
246
- },
247
- vignette: {
248
- enabled: false,
249
- intensity: 0.5,
250
- inner: 0.3,
251
- outer: 0.75,
252
- curvature: 1
253
- },
254
- fringing: {
255
- enabled: false,
256
- intensity: 0.5
257
- }
258
- },
503
+ // Shared defaults rather than a private copy, so a migrated document lands inside the
504
+ // authoring bounds and `validateSettings(v1, { limits: true })` reports the caller's
505
+ // data instead of values invented here. Every effect is `enabled: false`, so which
506
+ // numbers they carry is inert.
507
+ postEffectSettings: defaultPostEffectSettings(),
259
508
  animTracks: v1.animTracks.map((animTrackV1) => {
260
- return migrateAnimTrackV2(animTrackV1, v1.camera.fov || 60);
509
+ return migrateAnimTrackV2(animTrackV1, v1.camera.fov || DEFAULT_CAMERA_FOV);
261
510
  }),
262
511
  cameras: v1.camera.position && v1.camera.target
263
512
  ? [
@@ -265,7 +514,7 @@ const migrateV2 = (v1) => {
265
514
  initial: {
266
515
  position: v1.camera.position,
267
516
  target: v1.camera.target,
268
- fov: v1.camera.fov || 75
517
+ fov: v1.camera.fov || DEFAULT_CAMERA_FOV
269
518
  }
270
519
  }
271
520
  ]
@@ -274,7 +523,16 @@ const migrateV2 = (v1) => {
274
523
  startMode: v1.camera.startAnim === 'animTrack' ? 'animTrack' : 'default'
275
524
  };
276
525
  };
277
- // migrate a JSON object to the latest settings schema (assumes valid input)
526
+ /**
527
+ * Migrate settings of any supported version to the latest schema.
528
+ *
529
+ * Assumes valid input — call {@link validateSettings} first if the source is untrusted. Does
530
+ * not mutate the object passed in.
531
+ *
532
+ * @param settings - Parsed contents of a settings file.
533
+ * @returns The settings at the latest version.
534
+ * @throws If the version is not supported.
535
+ */
278
536
  const importSettings = (settings) => {
279
537
  let result;
280
538
  const version = settings.version;
@@ -291,15 +549,45 @@ const importSettings = (settings) => {
291
549
  }
292
550
  return result;
293
551
  };
294
- // validate unknown data against any supported settings schema version, throwing on invalid input
295
- const validateSettings = (settings) => {
552
+ /**
553
+ * Validate unknown data against any supported settings schema version.
554
+ *
555
+ * @param settings - Data to validate.
556
+ * @param options - See {@link ValidateOptions}.
557
+ * @throws If the data is not valid settings, with a message naming the offending field.
558
+ */
559
+ const validateSettings = (settings, options = {}) => {
296
560
  const obj = assertObject(settings, 'settings');
297
561
  const version = obj.version;
298
562
  if (version === undefined) {
299
563
  validateV1(settings);
564
+ if (options.limits) {
565
+ // Fields the migration would coerce, as the caller wrote them.
566
+ validateLimitsV1(settings);
567
+ // Everything else has to be checked against the migrated result, so a value the
568
+ // migration derived can fail — v1 keyframe times in seconds are rescaled to
569
+ // frames, for instance, and may land on a fraction. Say so, rather than reporting
570
+ // a path and number the caller never wrote.
571
+ let migrated;
572
+ try {
573
+ migrated = migrateV2(migrateV1(settings));
574
+ }
575
+ catch (err) {
576
+ throw new Error(`settings could not be migrated for validation: ${err.message}`);
577
+ }
578
+ try {
579
+ validateLimitsV2(migrated);
580
+ }
581
+ catch (err) {
582
+ throw new Error(`${err.message} (checked after migrating from v1)`);
583
+ }
584
+ }
300
585
  }
301
586
  else if (version === 2) {
302
587
  validateV2(settings);
588
+ if (options.limits) {
589
+ validateLimitsV2(settings);
590
+ }
303
591
  }
304
592
  else if (typeof version !== 'number') {
305
593
  throw new Error(`settings.version must be a number, got ${typeof version}`);
@@ -309,5 +597,5 @@ const validateSettings = (settings) => {
309
597
  }
310
598
  };
311
599
 
312
- export { importSettings, validateSettings };
600
+ export { ANIM_TRACK_LIMITS, ANNOTATION_LIMITS, CAMERA_FOV_RANGE, DEFAULT_BACKGROUND_COLOR, DEFAULT_CAMERA_FOV, DEFAULT_TONEMAPPING, POST_EFFECT_RANGES, defaultPostEffectSettings, defaultSettings, importSettings, isCameraFovInRange, validateSettings };
313
601
  //# sourceMappingURL=settings.js.map