@wildshard/sdk 0.2.13 → 0.3.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/GUIDE.md +16 -11
- package/bin/wildshard.mjs +2 -1
- package/docs/api/EXPORT-TIERS.md +12 -3
- package/lint/export-tiers.json +9 -0
- package/package.json +17 -5
- package/scripts/build-shardfiles.mjs +7 -2
- package/scripts/prepare-product.mjs +2 -2
- package/scripts/scratch-sweep.mjs +180 -0
- package/scripts/wildshard.mjs +1 -1
- package/skills/wildshard-mockup-to-model/SKILL.md +5 -3
- package/skills/wildshard-upgrade/SKILL.md +4 -4
- package/src/cli/help.ts +9 -5
- package/src/cli/upload/validate.ts +7 -5
- package/src/sharddev/assets.ts +1 -1
- package/src/sharddev/bake/compactGlb.ts +1 -1
- package/src/sharddev/bake/glbCompression.ts +1 -1
- package/src/sharddev/bake/gltfSource.ts +1 -1
- package/src/sharddev/bake/placeholders.ts +1 -1
- package/src/sharddev/bake/terrain.ts +1 -1
- package/src/sharddev/blobBytes.ts +1 -1
- package/src/sharddev/blobs.ts +2 -2
- package/src/sharddev/cli.ts +17 -4
- package/src/sharddev/formatJsonSchema.ts +1 -1
- package/src/sharddev/materialGraphFiles.ts +1 -1
- package/src/sharddev/newProject.ts +18 -10
- package/src/sharddev/outputProduct.ts +2 -2
- package/src/sharddev/productOutput.ts +2 -2
- package/src/sharddev/project.ts +1 -1
- package/src/sharddev/projectMap.ts +1 -1
- package/src/sharddev/refusals.ts +4 -2
- package/src/sharddev/reportCard.ts +1 -1
- package/src/sharddev/scene/author.ts +79 -0
- package/src/sharddev/scene/canvas.ts +213 -0
- package/src/sharddev/scene/description.ts +170 -0
- package/src/sharddev/scene/hash.ts +23 -0
- package/src/sharddev/scene/lower.ts +226 -0
- package/src/sharddev/scene/shard.ts +38 -0
- package/src/sharddev/scene/shardfile.ts +328 -0
- package/src/sharddev/threeGate.mjs +14 -0
- package/src/sharddev/threePin.mjs +40 -0
- package/src/sharddev/watch/page.ts +197 -0
- package/src/sharddev/watch/pageEntry.ts +23 -0
- package/src/sharddev/watch/proof.mjs +92 -0
- package/src/sharddev/watch/protocol.ts +108 -0
- package/src/sharddev/watch/socket.ts +57 -0
- package/src/sharddev/watch/watch.ts +209 -0
- package/src/shards/authoring-slice/generators/shard.ts +6 -0
- package/src/shards/authoring-slice/generators/textures.ts +173 -0
- package/src/shards/authoring-slice/generators/world.ts +415 -0
- package/src/shards/authoring-slice/shard.config.ts +7 -0
package/src/sharddev/cli.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { existsSync } from 'node:fs';
|
|
|
5
5
|
import { buildProject, readProjectAssets, validateProject } from './project';
|
|
6
6
|
import { ShardfileSchema, type Shardfile } from '@wildshard/format/shardSchema';
|
|
7
7
|
import { devProject } from './dev';
|
|
8
|
+
import { watchProject } from './watch/watch';
|
|
8
9
|
import { devClient } from './devClient';
|
|
9
10
|
import { proveAuthorSimulation, measureSimulation, validateSimulation } from '@wildshard/engine/host/headless';
|
|
10
11
|
import { performanceReport, performanceReportLines, type PerformanceObservations } from './reportCard';
|
|
@@ -51,7 +52,7 @@ async function writeShardfileOf(options: CliOptions, folder: string, source: str
|
|
|
51
52
|
catch (error) { throw new ShardfileRefusalError(error instanceof Error ? error.message : String(error), { cause: error }); }
|
|
52
53
|
}
|
|
53
54
|
/** The verbs whose first operand is a shard source (or, for validate and prove, a built folder). */
|
|
54
|
-
const SOURCE_VERBS: ReadonlySet<string> = new Set(['check', 'synth', 'build', 'dev', 'validate', 'prove']);
|
|
55
|
+
const SOURCE_VERBS: ReadonlySet<string> = new Set(['check', 'synth', 'build', 'dev', 'watch', 'validate', 'prove']);
|
|
55
56
|
interface CliOptions { readonly decisionLegacyLines?: number; readonly manifest?: ProjectManifestSource; readonly writeShardfile?: ShardfileWriter }
|
|
56
57
|
async function runCommand(given: readonly string[], options: CliOptions): Promise<void> {
|
|
57
58
|
// SA16 (J317): a verb given a repo finds its shard source at `src/` or its one `src/shards/<slug>/`.
|
|
@@ -97,9 +98,9 @@ async function runCommand(given: readonly string[], options: CliOptions): Promis
|
|
|
97
98
|
for (const line of updateShardRepo(resolve(positional[0] ?? '.'))) console.info(line);
|
|
98
99
|
return;
|
|
99
100
|
}
|
|
100
|
-
if (input === undefined) throw new Error('usage: wildshard new <dir> | check <source> [folder] [--json] | synth <source> | build <source> [folder] [--shardfile-only|--folder-only] [--no-placeholders] [--output=<slug>] | build <source> --behaviour-only | validate <source|shard.json> | dev <source> [port] (wildshard --help lists them all)');
|
|
101
|
+
if (input === undefined) throw new Error('usage: wildshard new <dir> | check <source> [folder] [--json] | synth <source> | build <source> [folder] [--shardfile-only|--folder-only] [--no-placeholders] [--output=<slug>] | build <source> --behaviour-only | validate <source|shard.json> | dev <source> [port] | watch <source> [port] (wildshard --help lists them all)');
|
|
101
102
|
// SA16 (J314): a hand-written src/ (--template blender) has no shard.config.ts to build, synth or serve; check settles it.
|
|
102
|
-
if ((command === 'build' || command === 'synth' || command === 'dev') && isRepoSource(resolve(input)) && isHandwrittenSource(resolve(input))) throw new Error(`${command}: ${input} is a hand-written shard file (--template blender): run wildshard check on the repo, which settles and builds it`);
|
|
103
|
+
if ((command === 'build' || command === 'synth' || command === 'dev') && isRepoSource(resolve(input)) && isHandwrittenSource(resolve(input))) throw new Error(`${command}: ${input} is a hand-written shard file (the retired --template blender): run wildshard check on the repo, which settles and builds it`);
|
|
103
104
|
if (command === 'synth') {
|
|
104
105
|
if (output !== undefined) throw new Error('usage: wildshard synth <source>');
|
|
105
106
|
const result = await synthProject(resolve(input));
|
|
@@ -117,13 +118,25 @@ async function runCommand(given: readonly string[], options: CliOptions): Promis
|
|
|
117
118
|
else if (value.startsWith('--')) unknown = true;
|
|
118
119
|
else names.push(value);
|
|
119
120
|
}
|
|
120
|
-
if (input.startsWith('--') || names.length > 1 || unknown || empty > 1 || templates.length > 1) throw new Error('usage: wildshard new <dir> [slug] [--template sdk
|
|
121
|
+
if (input.startsWith('--') || names.length > 1 || unknown || empty > 1 || templates.length > 1) throw new Error('usage: wildshard new <dir> [slug] [--template sdk] [--empty]');
|
|
121
122
|
// An unknown template refuses here, before anything is written.
|
|
122
123
|
const template = templateNamed(templates[0] ?? 'sdk');
|
|
123
124
|
const slug = names[0] ?? input.split('/').reverse().find((part) => part !== '') ?? '';
|
|
124
125
|
writeShardRepo(resolve(input), slug, { template, empty: empty === 1 });
|
|
125
126
|
return;
|
|
126
127
|
}
|
|
128
|
+
if (command === 'watch') {
|
|
129
|
+
// SHARD-SOURCE AP6: a scene shard's edits swap into the running page, no reload (`dev` is unchanged)
|
|
130
|
+
const port = output === undefined ? 0 : Number(output);
|
|
131
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('watch port must be 0..65535');
|
|
132
|
+
const server = await watchProject(resolve(input), { port, client: await devClient() });
|
|
133
|
+
const onSignal = (): void => {
|
|
134
|
+
// oxlint-disable-next-line unicorn/no-process-exit -- the signal handler replaced Node's default exit; ending is its job.
|
|
135
|
+
void server.close().finally(() => { process.exit(0); });
|
|
136
|
+
};
|
|
137
|
+
process.on('SIGINT', onSignal); process.on('SIGTERM', onSignal);
|
|
138
|
+
console.info(`wildshard watch: ${server.url}?skipintro`); return;
|
|
139
|
+
}
|
|
127
140
|
if (command === 'dev') {
|
|
128
141
|
const port = output === undefined ? 0 : Number(output);
|
|
129
142
|
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('dev port must be 0..65535');
|
|
@@ -119,7 +119,7 @@ import { AudioRoutingSchema } from '@wildshard/format/audioRouting';
|
|
|
119
119
|
import { AudioDataSchema } from '@wildshard/format/audio';
|
|
120
120
|
import { LedgerFactSchema, LedgerRulesSchema } from '@wildshard/format/ledger';
|
|
121
121
|
import { DirectorSchema } from '@wildshard/format/director';
|
|
122
|
-
import { DirectorProductSchema } from '@wildshard/format/
|
|
122
|
+
import { DirectorDocumentSchema as DirectorProductSchema } from '@wildshard/format/directorDocument';
|
|
123
123
|
import { DirectorStagesSchema } from '@wildshard/format/directorStages';
|
|
124
124
|
import { LogicalStateSchema, MigrationsSchema } from '@wildshard/format/migrations';
|
|
125
125
|
import { TraversalSchema } from '@wildshard/format/traversal';
|
|
@@ -31,19 +31,24 @@ function writeInstallScriptPolicy(project: string): void {
|
|
|
31
31
|
writeFileSync(resolve(project, 'pnpm-workspace.yaml'), INSTALL_SCRIPT_POLICY);
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
/** SA16 (J314, J317): `new --template <name>`. `sdk` is Mossgate (sharddev's `_template`)
|
|
35
|
-
*
|
|
36
|
-
export const TEMPLATES = ['sdk'
|
|
34
|
+
/** SA16 (J314, J317): `new --template <name>`. `sdk` is Mossgate (sharddev's `_template`), the only template since
|
|
35
|
+
* SS5 (J341): a shard is TypeScript three.js scene source, and Blender makes the models it loads. */
|
|
36
|
+
export const TEMPLATES = ['sdk'] as const;
|
|
37
37
|
export type TemplateName = (typeof TEMPLATES)[number];
|
|
38
|
+
/** What `writeShardRepo` can still lay out. `blender` is the retired hand-written shape (shard-format's
|
|
39
|
+
* `blender-template`, a shard file folder held by hand): `new` refuses it, but repos made that way still check and upload,
|
|
40
|
+
* so tests keep making one to prove that. */
|
|
41
|
+
export type RepoShape = TemplateName | 'blender';
|
|
38
42
|
/** The template `new` makes with no flag. */
|
|
39
43
|
export const DEFAULT_TEMPLATE: TemplateName = 'sdk';
|
|
40
44
|
/** J317: a repo with one shard keeps its shard source at `src/`. */
|
|
41
45
|
export const SHARD_SOURCE_FOLDER = 'src';
|
|
42
46
|
|
|
43
|
-
/** The template named by `--template`, or a refusal
|
|
47
|
+
/** The template named by `--template`, or a refusal, thrown before anything is written. */
|
|
44
48
|
export function templateNamed(name: string): TemplateName {
|
|
49
|
+
if (name === 'blender') throw new Error('new: --template blender is retired (J341): a shard is TypeScript three.js scene source, and Blender makes the .glb models that code loads; leave out --template. Repos made with it still check and upload');
|
|
45
50
|
const found = TEMPLATES.find(template => template === name);
|
|
46
|
-
if (found === undefined) throw new Error(`new: unknown template ${name}:
|
|
51
|
+
if (found === undefined) throw new Error(`new: unknown template ${name}: leave out --template, or pass --template sdk`);
|
|
47
52
|
return found;
|
|
48
53
|
}
|
|
49
54
|
|
|
@@ -60,6 +65,9 @@ function sdkPackage(): SdkPackage {
|
|
|
60
65
|
|| !('dependencies' in parsed) || typeof parsed.dependencies !== 'object' || parsed.dependencies === null) throw new Error('new: the installed @wildshard/sdk has no package.json version');
|
|
61
66
|
const dependencies: Record<string, string> = {};
|
|
62
67
|
for (const [name, spec] of Object.entries(parsed.dependencies)) if (typeof spec === 'string') dependencies[name] = spec;
|
|
68
|
+
// SA8: `three` is the sdk's peer, pinned exact; a repo lists it at that pin like the others (dependencies win, as in updatePins).
|
|
69
|
+
const peers: unknown = 'peerDependencies' in parsed ? parsed.peerDependencies : undefined;
|
|
70
|
+
if (typeof peers === 'object' && peers !== null) for (const [name, spec] of Object.entries(peers)) if (typeof spec === 'string') dependencies[name] ??= spec;
|
|
63
71
|
const node = 'engines' in parsed && typeof parsed.engines === 'object' && parsed.engines !== null && 'node' in parsed.engines && typeof parsed.engines.node === 'string' ? parsed.engines.node : undefined;
|
|
64
72
|
if (node === undefined) throw new Error('new: the installed @wildshard/sdk names no Node engine');
|
|
65
73
|
return { version: parsed.version, node, dependencies };
|
|
@@ -73,7 +81,7 @@ export const REPO_DEPENDENCIES = ['@wildshard/engine', '@wildshard/format', 'thr
|
|
|
73
81
|
export const HANDWRITTEN_DEPENDENCIES = ['@wildshard/format'] as const;
|
|
74
82
|
|
|
75
83
|
/** A new repo's package.json: the shard's slug, SA39's pnpm pin, and each Wildshard package pinned exactly. */
|
|
76
|
-
export function repoPackageJson(slug: string, template:
|
|
84
|
+
export function repoPackageJson(slug: string, template: RepoShape = DEFAULT_TEMPLATE): string {
|
|
77
85
|
const sdk = sdkPackage(), dependencies: Record<string, string> = { '@wildshard/sdk': sdk.version };
|
|
78
86
|
for (const name of template === 'blender' ? HANDWRITTEN_DEPENDENCIES : REPO_DEPENDENCIES) {
|
|
79
87
|
const spec = sdk.dependencies[name];
|
|
@@ -115,7 +123,7 @@ const HANDWRITTEN_LAYOUT = `- \`src/\` is the shard source, written by hand: a s
|
|
|
115
123
|
nothing here imports code, so no engine and no three.js. Its \`version\` is
|
|
116
124
|
the version \`wildshard upload\` sends.`;
|
|
117
125
|
|
|
118
|
-
function repoReadme(slug: string, template:
|
|
126
|
+
function repoReadme(slug: string, template: RepoShape, empty: boolean): string {
|
|
119
127
|
const handwritten = template === 'blender' && !empty;
|
|
120
128
|
const world = empty ? 'a bare shard source (`--empty`)' : template === 'sdk' ? 'the reference world, Mossgate (Template 1)' : 'the hand-written Blender template (`blender-template`)';
|
|
121
129
|
const files = empty ? '`data/`, `generators/`,\n `behaviour/` and `assets/`' : '`data/`,\n `generators/`, `behaviour/`, `assets/` and `manifest.json` (the card)';
|
|
@@ -148,7 +156,7 @@ ${layout}
|
|
|
148
156
|
|
|
149
157
|
/** Write the repo files around a shard source at `src/`: package.json, tsconfig, ignores, README, and the agent files
|
|
150
158
|
* (GUIDE.md, the four skills, their `.agents/skills` links, AGENTS.md and CLAUDE.md; SA28). */
|
|
151
|
-
function writeRepoFiles(project: string, slug: string, template:
|
|
159
|
+
function writeRepoFiles(project: string, slug: string, template: RepoShape, empty: boolean): void {
|
|
152
160
|
writeFileSync(resolve(project, 'package.json'), repoPackageJson(slug, empty ? DEFAULT_TEMPLATE : template));
|
|
153
161
|
// A hand-written repo holds no TypeScript to check.
|
|
154
162
|
if (template !== 'blender' || empty) writeFileSync(resolve(project, 'tsconfig.json'), TSCONFIG);
|
|
@@ -199,8 +207,8 @@ export function writeEmptyShardSource(source: string, slug: string): void {
|
|
|
199
207
|
writeEmptySource(source, slug);
|
|
200
208
|
}
|
|
201
209
|
|
|
202
|
-
/** `wildshard new <dir> [slug] [--template sdk
|
|
203
|
-
export function writeShardRepo(project: string, slug: string, options: { readonly template?:
|
|
210
|
+
/** `wildshard new <dir> [slug] [--template sdk] [--empty]` (and the retired `blender` shape, for tests): a whole single-shard repo, its shard source at `src/`. */
|
|
211
|
+
export function writeShardRepo(project: string, slug: string, options: { readonly template?: RepoShape; readonly empty?: boolean } = {}): void {
|
|
204
212
|
const template = options.template ?? DEFAULT_TEMPLATE;
|
|
205
213
|
assertTarget(project, slug);
|
|
206
214
|
mkdirSync(project, { recursive: true });
|
|
@@ -12,7 +12,7 @@ import { outputSectionPayloads, OUTPUT_SECTIONS } from '@wildshard/format/output
|
|
|
12
12
|
import { decisionScriptsFromSections, scriptAdmissionRows, type ScriptAdmissionRows } from '@wildshard/format/scriptContract';
|
|
13
13
|
import type { DecisionScripts } from '@wildshard/format/decisionScripts';
|
|
14
14
|
import { structuralGridEvidence } from '@wildshard/format/gridReadiness';
|
|
15
|
-
import { offlineMemoryAdmission } from '@wildshard/format/
|
|
15
|
+
import { offlineMemoryAdmission } from '@wildshard/format/shardfileAssets';
|
|
16
16
|
import { validationRevision, validationSourceBytes } from '@wildshard/format/validationReceipt';
|
|
17
17
|
import { preflightDeclaredCosts } from '@wildshard/format/assetAdmission';
|
|
18
18
|
import { admitProduct, readmitted, rememberAdmitted } from './productOutput';
|
|
@@ -26,7 +26,7 @@ import { COOK_DATA_PATH, cookMountPath } from '@wildshard/format/cookData';
|
|
|
26
26
|
import type { CookInput } from './cookInput';
|
|
27
27
|
import { validateDefinedJson, type EmittedSections } from './sections';
|
|
28
28
|
import { parseDiscoveryValues, type DiscoveryValues } from '@wildshard/format/discoveryValues';
|
|
29
|
-
import { checkWorldTargets, outputBlobExtension as blobExtension, outputBlobKind as blobKind, readCanonicalJson as readJson, validateShardfileProduct, type ProductFiles, type ValidatedProduct } from '@wildshard/format/
|
|
29
|
+
import { checkWorldTargets, outputBlobExtension as blobExtension, outputBlobKind as blobKind, readCanonicalJson as readJson, validateShardfileFolder as validateShardfileProduct, type ShardfileFiles as ProductFiles, type ValidatedShardfile as ValidatedProduct } from '@wildshard/format/shardfileValidation';
|
|
30
30
|
|
|
31
31
|
const encoder = new TextEncoder();
|
|
32
32
|
function jsonBytes(value: unknown): Uint8Array { return encoder.encode(encodeCanonicalJson(value)); }
|
|
@@ -4,8 +4,8 @@ import { mkdirSync, writeFileSync } from 'node:fs';
|
|
|
4
4
|
import { resolve } from 'node:path';
|
|
5
5
|
import type { ScriptAdmissionRows } from '@wildshard/format/scriptContract';
|
|
6
6
|
import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
|
|
7
|
-
import { admitShardfileProduct,
|
|
8
|
-
import { offlineMemoryAdmission, prepareAssetDecoders } from '@wildshard/format/
|
|
7
|
+
import { admitShardfileFolder as admitShardfileProduct, assertShardfileTargets as assertTargets } from '@wildshard/format/shardfileValidation';
|
|
8
|
+
import { offlineMemoryAdmission, prepareAssetDecoders } from '@wildshard/format/shardfileAssets';
|
|
9
9
|
import { validationRevision, validationSourceBytes } from '@wildshard/format/validationReceipt';
|
|
10
10
|
import { preflightDeclaredCosts } from '@wildshard/format/assetAdmission';
|
|
11
11
|
import { CLIENT_FEATURE_SIDES, unsidedKinds } from '@wildshard/format/featureSides';
|
package/src/sharddev/project.ts
CHANGED
|
@@ -16,7 +16,7 @@ import process from 'node:process';
|
|
|
16
16
|
import { build } from 'vite';
|
|
17
17
|
import ts from '@typescript/typescript6';
|
|
18
18
|
import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
|
|
19
|
-
import { preflightAssetGraph, offlineMemoryAdmission, prepareAssetDecoders } from "@wildshard/format/
|
|
19
|
+
import { preflightAssetGraph, offlineMemoryAdmission, prepareAssetDecoders } from "@wildshard/format/shardfileAssets";
|
|
20
20
|
import { preflightDeclaredCosts } from '@wildshard/format/assetAdmission';
|
|
21
21
|
import { preflightShardfile } from '@wildshard/format/preflight';
|
|
22
22
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
|
|
2
|
-
import { assetCost } from '@wildshard/format/
|
|
2
|
+
import { assetCost } from '@wildshard/format/shardfileAssets';
|
|
3
3
|
import { hashAssetBytes } from './assetHandle';
|
|
4
4
|
|
|
5
5
|
/** Build input for a baked map; paths and URLs never enter the authored product. */
|
package/src/sharddev/refusals.ts
CHANGED
|
@@ -37,13 +37,15 @@ export const GUIDE_FILE = 'GUIDE.md';
|
|
|
37
37
|
|
|
38
38
|
/** The refusals that are not lint rules, most specific first; each step has one catch-all (no `match`). */
|
|
39
39
|
export const REFUSAL_RULES: readonly RefusalRule[] = [
|
|
40
|
+
{ id: 'three-version', anchor: 'three-version', steps: 'any', match: /^\[three-version\] /,
|
|
41
|
+
fix: 'Install the three the sdk pins: pnpm add three@<the version named> --save-exact.' },
|
|
40
42
|
{ id: 'usage', anchor: 'usage', steps: 'any', match: /^usage: |^unknown (?:wildshard command|build flag|command)|unknown or incomplete build map flag|^Unknown schema root|accepts no pointer|^dev port must be|^invalid --port\b|^(?:validate|prove) requires a format-2 shard\.json or (?:shard source|author project)/u,
|
|
41
43
|
fix: 'Run `wildshard --help` and give the verb the arguments and flags it lists.' },
|
|
42
44
|
// new
|
|
43
45
|
{ id: 'new-target', anchor: 'new-target', steps: ['new'], match: /new requires a fresh directory and kebab-case slug/u,
|
|
44
46
|
fix: 'Name a folder that does not exist yet and a kebab-case slug: `wildshard new my-isle`.' },
|
|
45
|
-
{ id: 'new-template', anchor: 'new-template', steps: ['new'], match: /^new: unknown template /u,
|
|
46
|
-
fix: 'Leave out --template
|
|
47
|
+
{ id: 'new-template', anchor: 'new-template', steps: ['new'], match: /^new: (?:unknown template |--template blender is retired)/u,
|
|
48
|
+
fix: 'Leave out --template (sdk is the only one). blender is retired: write three.js scene source; Blender makes models.' },
|
|
47
49
|
{ id: 'new-refused', anchor: 'new-refused', steps: ['new'],
|
|
48
50
|
fix: 'Reinstall @wildshard/sdk (`pnpm install`); `new` copies the reference world shipped with it.' },
|
|
49
51
|
// update (SA28)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { performanceReport as report, performanceReportLines as lines, performanceTargetIssues as targets, type PerformanceReport as GameReport, type PerformanceObservations as GameObservations } from '@wildshard/format/
|
|
1
|
+
import { performanceReport as report, performanceReportLines as lines, performanceTargetIssues as targets, type PerformanceReport as GameReport, type PerformanceObservations as GameObservations } from '@wildshard/format/shardfileAssets';
|
|
2
2
|
import type { Shardfile } from '@wildshard/format/shardSchema';
|
|
3
3
|
|
|
4
4
|
/** Author-facing report: declared bounds, measured scripts and explicit cold-network assumptions. */
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { DataTexture, LinearFilter, LinearMipmapLinearFilter, Mesh, MeshStandardMaterial, RepeatWrapping, SRGBColorSpace, ShapeGeometry, LinearSRGBColorSpace, type ColorRepresentation, type Group, type Object3D, type Scene, type Shape } from 'three';
|
|
2
|
+
import type { Rgb, ScenePost } from './description';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* AUTHORING-PARITY AP1: what an author's scene module calls besides three.js itself. Everything here runs at compile time
|
|
6
|
+
* only (on the author's machine or CI), never in a player's page or on the server.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** The world a `defineShard` build function receives. `scene` is a plain three.js `Scene`: add to it as in a cleanroom. */
|
|
10
|
+
export interface ShardWorld {
|
|
11
|
+
readonly scene: Scene;
|
|
12
|
+
/** A named piece of the world, the unit `watch` swaps. Objects added to `scene` outside a part belong to part `scene`. */
|
|
13
|
+
part: (name: string, build: (part: Group) => void) => Group;
|
|
14
|
+
/** The ground: its height everywhere in the 500 m cell, and optionally its colour (linear RGB). */
|
|
15
|
+
ground: (heightAt: (x: number, z: number) => number, options?: { colourAt?: (x: number, z: number) => Rgb }) => void;
|
|
16
|
+
/** The cleanroom's composer, as numbers. */
|
|
17
|
+
post: (settings: Partial<Omit<ScenePost, 'bloom'>> & { bloom?: ScenePost['bloom'] }) => void;
|
|
18
|
+
/** Where a player enters. */
|
|
19
|
+
spawn: (x: number, y: number, z: number, yaw?: number) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Painted pixels by texture source: `clone()` shares the source, so a clone with its own `repeat` still lowers. */
|
|
23
|
+
/** as a canvas `ImageData` stores a value: clamped to 0..255 and rounded */
|
|
24
|
+
export const byte = (value: number): number => Math.min(255, Math.max(0, Math.round(value)));
|
|
25
|
+
const PAINTED = new WeakMap<object, { width: number; height: number; rgba: Uint8Array }>();
|
|
26
|
+
export const paintedPixels = (source: object): { width: number; height: number; rgba: Uint8Array } | undefined => PAINTED.get(source);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* `paint(w, h, fn)`: a texture painted per pixel, the cleanroom's `paint` without a canvas. `fn(u, v, x, y)` returns
|
|
30
|
+
* `[r, g, b, a?]` in 0..255 with row 0 at the top, as a canvas draws; the texture samples as a `CanvasTexture` would
|
|
31
|
+
* (sRGB, repeat, mipmapped). This is J338's procedural path: the shardfile ships the pixels, no image file is authored.
|
|
32
|
+
*/
|
|
33
|
+
export function paint(width: number, height: number, fn: (u: number, v: number, x: number, y: number) => readonly number[], options: { colourSpace?: 'srgb' | 'linear' } = {}): DataTexture {
|
|
34
|
+
checkSize(width, height);
|
|
35
|
+
const top = new Uint8Array(width * height * 4);
|
|
36
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
37
|
+
const [r = 0, g = 0, b = 0, a = 255] = fn(x / width, y / height, x, y), i = (y * width + x) * 4;
|
|
38
|
+
top[i] = byte(r); top[i + 1] = byte(g); top[i + 2] = byte(b); top[i + 3] = byte(a);
|
|
39
|
+
}
|
|
40
|
+
return paintedTexture(width, height, top, options);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A texture size from 1 to 4096 a side, or a refusal. */
|
|
44
|
+
export function checkSize(width: number, height: number): void {
|
|
45
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 4096 || height > 4096) throw new Error(`paint: ${width}x${height} is not a texture size from 1 to 4096`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** RGBA8 rows top first (as a canvas holds them) as the texture a `CanvasTexture` of that canvas would be. */
|
|
49
|
+
export function paintedTexture(width: number, height: number, top: Uint8Array, options: { colourSpace?: 'srgb' | 'linear' } = {}): DataTexture {
|
|
50
|
+
// canvas row y (top = 0) is texture row height-1-y: a CanvasTexture flips Y on upload, a DataTexture does not
|
|
51
|
+
const rgba = new Uint8Array(width * height * 4);
|
|
52
|
+
for (let y = 0; y < height; y++) rgba.set(top.subarray(y * width * 4, (y + 1) * width * 4), (height - 1 - y) * width * 4);
|
|
53
|
+
const texture = new DataTexture(rgba, width, height);
|
|
54
|
+
texture.colorSpace = options.colourSpace === 'linear' ? LinearSRGBColorSpace : SRGBColorSpace;
|
|
55
|
+
texture.wrapS = texture.wrapT = RepeatWrapping;
|
|
56
|
+
texture.magFilter = LinearFilter; texture.minFilter = LinearMipmapLinearFilter; texture.generateMipmaps = true;
|
|
57
|
+
texture.needsUpdate = true;
|
|
58
|
+
PAINTED.set(texture.source, { width, height, rgba });
|
|
59
|
+
return texture;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const SOLID = new WeakSet<Object3D>();
|
|
63
|
+
/** `solid(mesh)`: the mesh is also a collider, its own box in its own frame. Said once, beside the mesh. */
|
|
64
|
+
export function solid<T extends Object3D>(object: T): T { SOLID.add(object); return object; }
|
|
65
|
+
export const isSolid = (object: Object3D): boolean => SOLID.has(object);
|
|
66
|
+
|
|
67
|
+
/** A water surface: an outline in the XZ plane (as `ShapeGeometry` makes it, then laid flat), a tint, a reflection. */
|
|
68
|
+
export class Water extends Mesh<ShapeGeometry, MeshStandardMaterial> {
|
|
69
|
+
readonly tint: ColorRepresentation;
|
|
70
|
+
readonly reflect: 'planar' | 'sky';
|
|
71
|
+
readonly shape: Shape;
|
|
72
|
+
constructor(shape: Shape, options: { tint?: ColorRepresentation; reflect?: 'planar' | 'sky'; segments?: number } = {}) {
|
|
73
|
+
const material = new MeshStandardMaterial({ color: options.tint ?? '#3a3458', roughness: 0.08, metalness: 0.2, transparent: true, opacity: 0.86 });
|
|
74
|
+
super(new ShapeGeometry(shape, options.segments ?? 24), material);
|
|
75
|
+
this.shape = shape; this.tint = options.tint ?? '#3a3458'; this.reflect = options.reflect ?? 'planar';
|
|
76
|
+
this.rotation.x = -Math.PI / 2;
|
|
77
|
+
this.name = 'water';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import type { DataTexture } from 'three';
|
|
2
|
+
import { byte, checkSize, paintedTexture } from './author';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* AUTHORING-PARITY AP1: `paintCanvas(w, h, draw)`, the part of the Canvas 2D API the cleanrooms paint with, in plain
|
|
6
|
+
* JavaScript at compile time. A cleanroom painter (`const [c, ctx] = canvas(w, h); ...; return new CanvasTexture(c)`)
|
|
7
|
+
* ports by swapping its first and last lines. Fills sample each pixel centre (no antialiasing; the mip chain softens);
|
|
8
|
+
* the nonzero rule, source-over and destination-out compositing, transforms, linear and radial gradients and a 5x7
|
|
9
|
+
* bitmap `fillText` are what the cleanroom textures use. Anything else throws, so a missing call is never silent.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
type Colour = [number, number, number, number];
|
|
13
|
+
interface Gradient { readonly kind: 'linear' | 'radial'; readonly at: readonly number[]; readonly stops: [number, Colour][]; addColorStop: (offset: number, colour: string) => void }
|
|
14
|
+
type Style = string | Gradient;
|
|
15
|
+
type Matrix = [number, number, number, number, number, number];
|
|
16
|
+
interface State { transform: Matrix; fillStyle: Style; strokeStyle: Style; lineWidth: number; globalAlpha: number; globalCompositeOperation: 'source-over' | 'destination-out'; font: string; textAlign: 'left' | 'center' | 'right' | 'start'; textBaseline: 'alphabetic' | 'middle' | 'top' | 'bottom' }
|
|
17
|
+
|
|
18
|
+
function parseColour(text: string): Colour {
|
|
19
|
+
const s = text.trim().toLowerCase();
|
|
20
|
+
if (s.startsWith('#')) {
|
|
21
|
+
const hex = s.length === 4 ? Array.from(s.slice(1), (c) => c + c).join('') : s.slice(1, 7);
|
|
22
|
+
return [Number.parseInt(hex.slice(0, 2), 16), Number.parseInt(hex.slice(2, 4), 16), Number.parseInt(hex.slice(4, 6), 16), 1];
|
|
23
|
+
}
|
|
24
|
+
const match = /^rgba?\(([^)]*)\)$/u.exec(s);
|
|
25
|
+
if (match?.[1] !== undefined) { const [r = 0, g = 0, b = 0, a = 1] = match[1].split(',').map((part) => Number.parseFloat(part)); return [r, g, b, a]; }
|
|
26
|
+
if (s === 'transparent') return [0, 0, 0, 0];
|
|
27
|
+
if (s === 'white') return [255, 255, 255, 1];
|
|
28
|
+
if (s === 'black') return [0, 0, 0, 1];
|
|
29
|
+
throw new Error(`paintCanvas: colour ${text} is not #hex, rgb() or rgba()`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 5x7 capitals, digits and `x`, one string of 7 rows per glyph. */
|
|
33
|
+
const GLYPHS: Readonly<Record<string, string>> = {
|
|
34
|
+
A: '01110100011000111111100011000110001', B: '11110100011000111110100011000111110', C: '01110100011000010000100001000101110',
|
|
35
|
+
D: '11110100011000110001100011000111110', E: '11111100001000011110100001000011111', F: '11111100001000011110100001000010000',
|
|
36
|
+
G: '01110100011000010111100011000101111', H: '10001100011000111111100011000110001', I: '01110001000010000100001000010001110',
|
|
37
|
+
J: '00111000100001000010000101001001100', K: '10001100101010011000101001001010001', L: '10000100001000010000100001000011111',
|
|
38
|
+
M: '10001110111010110101100011000110001', N: '10001110011010110011100011000110001', O: '01110100011000110001100011000101110',
|
|
39
|
+
P: '11110100011000111110100001000010000', Q: '01110100011000110001101011001001101', R: '11110100011000111110101001001010001',
|
|
40
|
+
S: '01111100001000001110000010000111110', T: '11111001000010000100001000010000100', U: '10001100011000110001100011000101110',
|
|
41
|
+
V: '10001100011000110001100010101000100', W: '10001100011000110101101011010101010', X: '10001100010101000100010101000110001',
|
|
42
|
+
Y: '10001100010101000100001000010000100', Z: '11111000010001000100010001000011111', x: '00000000001000101010001000101010001',
|
|
43
|
+
0: '01110100011001110101110011000101110', 1: '00100011000010000100001000010001110', 2: '01110100010000100010001000100011111',
|
|
44
|
+
3: '11111000100010000010000011000101110', 4: '00010001100101010010111110001000010', 5: '11111100001111000001000011000101110',
|
|
45
|
+
6: '00110010001000011110100011000101110', 7: '11111000010001000100010000100001000', 8: '01110100011000101110100011000101110',
|
|
46
|
+
9: '01110100011000101111000010001001100', '-': '00000000000000011111000000000000000', '.': '00000000000000000000000000110001100',
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** A canvas-like 2D context over an RGBA buffer (rows top first). */
|
|
50
|
+
export class PaintContext {
|
|
51
|
+
readonly width: number;
|
|
52
|
+
readonly height: number;
|
|
53
|
+
/** straight (non-premultiplied) RGBA, 0..255 colour, 0..1 alpha */
|
|
54
|
+
private readonly pixels: Float32Array;
|
|
55
|
+
private state: State = { transform: [1, 0, 0, 1, 0, 0], fillStyle: '#000', strokeStyle: '#000', lineWidth: 1, globalAlpha: 1, globalCompositeOperation: 'source-over', font: '10px monospace', textAlign: 'start', textBaseline: 'alphabetic' };
|
|
56
|
+
private readonly stack: State[] = [];
|
|
57
|
+
private path: [number, number][][] = [];
|
|
58
|
+
constructor(width: number, height: number) { this.width = width; this.height = height; this.pixels = new Float32Array(width * height * 4); }
|
|
59
|
+
|
|
60
|
+
get fillStyle(): Style { return this.state.fillStyle; } set fillStyle(value: Style) { this.state.fillStyle = value; }
|
|
61
|
+
get strokeStyle(): Style { return this.state.strokeStyle; } set strokeStyle(value: Style) { this.state.strokeStyle = value; }
|
|
62
|
+
get lineWidth(): number { return this.state.lineWidth; } set lineWidth(value: number) { this.state.lineWidth = value; }
|
|
63
|
+
get globalAlpha(): number { return this.state.globalAlpha; } set globalAlpha(value: number) { this.state.globalAlpha = value; }
|
|
64
|
+
get globalCompositeOperation(): string { return this.state.globalCompositeOperation; }
|
|
65
|
+
set globalCompositeOperation(value: string) { if (value !== 'source-over' && value !== 'destination-out') throw new Error(`paintCanvas: globalCompositeOperation ${value} is not supported`); this.state.globalCompositeOperation = value; }
|
|
66
|
+
get font(): string { return this.state.font; } set font(value: string) { this.state.font = value; }
|
|
67
|
+
get textAlign(): string { return this.state.textAlign; } set textAlign(value: string) { this.state.textAlign = value as State['textAlign']; }
|
|
68
|
+
get textBaseline(): string { return this.state.textBaseline; } set textBaseline(value: string) { this.state.textBaseline = value as State['textBaseline']; }
|
|
69
|
+
|
|
70
|
+
save(): void { this.stack.push({ ...this.state, transform: [...this.state.transform] }); }
|
|
71
|
+
restore(): void { const state = this.stack.pop(); if (state !== undefined) this.state = state; }
|
|
72
|
+
translate(x: number, y: number): void { this.multiply([1, 0, 0, 1, x, y]); }
|
|
73
|
+
rotate(angle: number): void { const c = Math.cos(angle), s = Math.sin(angle); this.multiply([c, s, -s, c, 0, 0]); }
|
|
74
|
+
scale(x: number, y: number): void { this.multiply([x, 0, 0, y, 0, 0]); }
|
|
75
|
+
private multiply([a2, b2, c2, d2, e2, f2]: Matrix): void {
|
|
76
|
+
const [a, b, c, d, e, f] = this.state.transform;
|
|
77
|
+
this.state.transform = [a * a2 + c * b2, b * a2 + d * b2, a * c2 + c * d2, b * c2 + d * d2, a * e2 + c * f2 + e, b * e2 + d * f2 + f];
|
|
78
|
+
}
|
|
79
|
+
private point(x: number, y: number): [number, number] { const [a, b, c, d, e, f] = this.state.transform; return [a * x + c * y + e, b * x + d * y + f]; }
|
|
80
|
+
|
|
81
|
+
beginPath(): void { this.path = []; }
|
|
82
|
+
moveTo(x: number, y: number): void { this.path.push([this.point(x, y)]); }
|
|
83
|
+
lineTo(x: number, y: number): void { const sub = this.path.at(-1); if (sub === undefined) this.moveTo(x, y); else sub.push(this.point(x, y)); }
|
|
84
|
+
closePath(): void { const sub = this.path.at(-1); const first = sub?.[0]; if (sub !== undefined && first !== undefined) { sub.push(first); this.path.push([first]); } }
|
|
85
|
+
private last(): [number, number] { const sub = this.path.at(-1), point = sub?.at(-1); if (point === undefined) throw new Error('paintCanvas: a curve needs a current point'); return this.inverse(point); }
|
|
86
|
+
private inverse([x, y]: [number, number]): [number, number] {
|
|
87
|
+
const [a, b, c, d, e, f] = this.state.transform, det = a * d - b * c;
|
|
88
|
+
return [(d * (x - e) - c * (y - f)) / det, (-b * (x - e) + a * (y - f)) / det];
|
|
89
|
+
}
|
|
90
|
+
quadraticCurveTo(cx: number, cy: number, x: number, y: number): void {
|
|
91
|
+
const [x0, y0] = this.last();
|
|
92
|
+
for (let i = 1; i <= 16; i++) { const t = i / 16, u = 1 - t; this.lineTo(u * u * x0 + 2 * u * t * cx + t * t * x, u * u * y0 + 2 * u * t * cy + t * t * y); }
|
|
93
|
+
}
|
|
94
|
+
bezierCurveTo(c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): void {
|
|
95
|
+
const [x0, y0] = this.last();
|
|
96
|
+
for (let i = 1; i <= 20; i++) { const t = i / 20, u = 1 - t; this.lineTo(u * u * u * x0 + 3 * u * u * t * c1x + 3 * u * t * t * c2x + t * t * t * x, u * u * u * y0 + 3 * u * u * t * c1y + 3 * u * t * t * c2y + t * t * t * y); }
|
|
97
|
+
}
|
|
98
|
+
arc(x: number, y: number, r: number, a0: number, a1: number, ccw = false): void { this.ellipse(x, y, r, r, 0, a0, a1, ccw); }
|
|
99
|
+
ellipse(x: number, y: number, rx: number, ry: number, rotation: number, a0: number, a1: number, ccw = false): void {
|
|
100
|
+
let sweep = a1 - a0;
|
|
101
|
+
if (!ccw && sweep < 0) sweep = (sweep % (2 * Math.PI)) + 2 * Math.PI; if (ccw && sweep > 0) sweep = (sweep % (2 * Math.PI)) - 2 * Math.PI;
|
|
102
|
+
if (Math.abs(a1 - a0) >= 2 * Math.PI) sweep = ccw ? -2 * Math.PI : 2 * Math.PI;
|
|
103
|
+
const steps = Math.max(8, Math.ceil(Math.abs(sweep) / (2 * Math.PI) * 48)), c = Math.cos(rotation), s = Math.sin(rotation);
|
|
104
|
+
for (let i = 0; i <= steps; i++) {
|
|
105
|
+
const a = a0 + sweep * (i / steps), px = Math.cos(a) * rx, py = Math.sin(a) * ry;
|
|
106
|
+
this.lineTo(x + px * c - py * s, y + px * s + py * c);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
rect(x: number, y: number, w: number, h: number): void { this.moveTo(x, y); this.lineTo(x + w, y); this.lineTo(x + w, y + h); this.lineTo(x, y + h); this.closePath(); }
|
|
110
|
+
fillRect(x: number, y: number, w: number, h: number): void { const saved = this.path; this.path = []; this.rect(x, y, w, h); this.fill(); this.path = saved; }
|
|
111
|
+
clearRect(x: number, y: number, w: number, h: number): void {
|
|
112
|
+
for (let py = Math.max(0, Math.floor(y)); py < Math.min(this.height, Math.ceil(y + h)); py++) for (let px = Math.max(0, Math.floor(x)); px < Math.min(this.width, Math.ceil(x + w)); px++) this.pixels.fill(0, (py * this.width + px) * 4, (py * this.width + px) * 4 + 4);
|
|
113
|
+
}
|
|
114
|
+
fill(): void { this.cover(this.path, this.state.fillStyle); }
|
|
115
|
+
stroke(): void {
|
|
116
|
+
const half = this.state.lineWidth / 2, polygons: [number, number][][] = [];
|
|
117
|
+
const [a, b, c, d] = this.state.transform, scale = Math.sqrt(Math.abs(a * d - b * c)) * half;
|
|
118
|
+
for (const sub of this.path) for (let i = 0; i + 1 < sub.length; i++) {
|
|
119
|
+
const p = sub[i], q = sub[i + 1]; if (p === undefined || q === undefined) continue;
|
|
120
|
+
const dx = q[0] - p[0], dy = q[1] - p[1], len = Math.hypot(dx, dy); if (len === 0) continue;
|
|
121
|
+
const nx = -dy / len * scale, ny = dx / len * scale;
|
|
122
|
+
polygons.push([[p[0] + nx, p[1] + ny], [q[0] + nx, q[1] + ny], [q[0] - nx, q[1] - ny], [p[0] - nx, p[1] - ny], [p[0] + nx, p[1] + ny]]);
|
|
123
|
+
}
|
|
124
|
+
for (const polygon of polygons) this.cover([polygon], this.state.strokeStyle);
|
|
125
|
+
}
|
|
126
|
+
createLinearGradient(x0: number, y0: number, x1: number, y1: number): Gradient { return this.gradient('linear', [x0, y0, x1, y1]); }
|
|
127
|
+
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): Gradient { return this.gradient('radial', [x0, y0, r0, x1, y1, r1]); }
|
|
128
|
+
private gradient(kind: Gradient['kind'], at: number[]): Gradient {
|
|
129
|
+
const stops: [number, Colour][] = [];
|
|
130
|
+
return { kind, at, stops, addColorStop: (offset, colour) => { stops.push([offset, parseColour(colour)]); stops.sort((p, q) => p[0] - q[0]); } };
|
|
131
|
+
}
|
|
132
|
+
createImageData(w: number, h: number): { width: number; height: number; data: Uint8ClampedArray } { return { width: w, height: h, data: new Uint8ClampedArray(w * h * 4) }; }
|
|
133
|
+
putImageData(image: { width: number; height: number; data: Uint8ClampedArray }, dx: number, dy: number): void {
|
|
134
|
+
for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
|
|
135
|
+
const tx = x + dx, ty = y + dy; if (tx < 0 || ty < 0 || tx >= this.width || ty >= this.height) continue;
|
|
136
|
+
const from = (y * image.width + x) * 4, to = (ty * this.width + tx) * 4;
|
|
137
|
+
this.pixels[to] = image.data[from] ?? 0; this.pixels[to + 1] = image.data[from + 1] ?? 0; this.pixels[to + 2] = image.data[from + 2] ?? 0; this.pixels[to + 3] = (image.data[from + 3] ?? 0) / 255;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** 5x7 bitmap capitals; the font's pixel size sets the cap height. */
|
|
141
|
+
fillText(text: string, x: number, y: number): void {
|
|
142
|
+
const size = Number.parseFloat(/(\d+(?:\.\d+)?)px/u.exec(this.state.font)?.[1] ?? '10'), cell = size * 0.7 / 7, advance = cell * 6, width = text.length * advance - cell;
|
|
143
|
+
const left = this.state.textAlign === 'center' ? x - width / 2 : this.state.textAlign === 'right' ? x - width : x;
|
|
144
|
+
const top = this.state.textBaseline === 'middle' ? y - cell * 3.5 : this.state.textBaseline === 'top' ? y : y - cell * 7;
|
|
145
|
+
const saved = this.path; this.path = [];
|
|
146
|
+
[...text].forEach((char, i) => {
|
|
147
|
+
const glyph = GLYPHS[char] ?? GLYPHS[char.toUpperCase()];
|
|
148
|
+
if (glyph === undefined) return;
|
|
149
|
+
for (let row = 0; row < 7; row++) for (let col = 0; col < 5; col++) if (glyph[row * 5 + col] === '1') this.rect(left + i * advance + col * cell, top + row * cell, cell, cell);
|
|
150
|
+
});
|
|
151
|
+
this.fill(); this.path = saved;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private sample(style: Style, x: number, y: number): Colour {
|
|
155
|
+
if (typeof style === 'string') return parseColour(style);
|
|
156
|
+
const [u, v] = this.inverse([x, y]);
|
|
157
|
+
let t: number;
|
|
158
|
+
if (style.kind === 'linear') { const [x0 = 0, y0 = 0, x1 = 0, y1 = 0] = style.at, dx = x1 - x0, dy = y1 - y0; t = ((u - x0) * dx + (v - y0) * dy) / (dx * dx + dy * dy || 1); }
|
|
159
|
+
else { const x0 = style.at[0] ?? 0, y0 = style.at[1] ?? 0, r0 = style.at[2] ?? 0, r1 = style.at[5] ?? 1; t = (Math.hypot(u - x0, v - y0) - r0) / (r1 - r0 || 1); }
|
|
160
|
+
const stops = style.stops, first = stops[0], last = stops.at(-1);
|
|
161
|
+
if (first === undefined || last === undefined) return [0, 0, 0, 0];
|
|
162
|
+
if (t <= first[0]) return first[1]; if (t >= last[0]) return last[1];
|
|
163
|
+
for (let i = 1; i < stops.length; i++) {
|
|
164
|
+
const [o1, c1] = stops[i] ?? first, [o0, c0] = stops[i - 1] ?? first;
|
|
165
|
+
if (t <= o1) { const k = (t - o0) / (o1 - o0 || 1); return [c0[0] + (c1[0] - c0[0]) * k, c0[1] + (c1[1] - c0[1]) * k, c0[2] + (c1[2] - c0[2]) * k, c0[3] + (c1[3] - c0[3]) * k]; }
|
|
166
|
+
}
|
|
167
|
+
return last[1];
|
|
168
|
+
}
|
|
169
|
+
/** Nonzero-rule coverage of pixel centres, composited with the current style, alpha and operation. */
|
|
170
|
+
private cover(path: [number, number][][], style: Style): void {
|
|
171
|
+
const edges: [number, number, number, number, number][] = [];
|
|
172
|
+
let minY = Infinity, maxY = -Infinity;
|
|
173
|
+
for (const sub of path) for (let i = 0; i + 1 < sub.length; i++) {
|
|
174
|
+
const p = sub[i], q = sub[i + 1]; if (p === undefined || q === undefined || p[1] === q[1]) continue;
|
|
175
|
+
edges.push(p[1] < q[1] ? [p[0], p[1], q[0], q[1], 1] : [q[0], q[1], p[0], p[1], -1]);
|
|
176
|
+
minY = Math.min(minY, p[1], q[1]); maxY = Math.max(maxY, p[1], q[1]);
|
|
177
|
+
}
|
|
178
|
+
// an open subpath fills as if closed
|
|
179
|
+
for (const sub of path) { const p = sub.at(-1), q = sub[0]; if (p !== undefined && q !== undefined && sub.length > 2 && (p[0] !== q[0] || p[1] !== q[1]) && p[1] !== q[1]) { edges.push(p[1] < q[1] ? [p[0], p[1], q[0], q[1], 1] : [q[0], q[1], p[0], p[1], -1]); minY = Math.min(minY, p[1], q[1]); maxY = Math.max(maxY, p[1], q[1]); } }
|
|
180
|
+
const solid = typeof style === 'string' ? parseColour(style) : null, alpha = this.state.globalAlpha, out = this.state.globalCompositeOperation === 'destination-out';
|
|
181
|
+
for (let py = Math.max(0, Math.floor(minY)); py < Math.min(this.height, Math.ceil(maxY)); py++) {
|
|
182
|
+
const cy = py + 0.5, crossings: [number, number][] = [];
|
|
183
|
+
for (const [x0, y0, x1, y1, w] of edges) if (cy >= y0 && cy < y1) crossings.push([x0 + (cy - y0) / (y1 - y0) * (x1 - x0), w]);
|
|
184
|
+
crossings.sort((p, q) => p[0] - q[0]);
|
|
185
|
+
let winding = 0;
|
|
186
|
+
for (let i = 0; i + 1 < crossings.length; i++) {
|
|
187
|
+
winding += crossings[i]?.[1] ?? 0;
|
|
188
|
+
if (winding === 0) continue;
|
|
189
|
+
const start = crossings[i]?.[0] ?? 0, cx = crossings[i + 1]?.[0] ?? 0;
|
|
190
|
+
for (let px = Math.max(0, Math.ceil(start - 0.5)); px < Math.min(this.width, Math.ceil(cx - 0.5)); px++) {
|
|
191
|
+
const [r, g, b, a] = solid ?? this.sample(style, px + 0.5, cy), sa = a * alpha, at = (py * this.width + px) * 4, da = this.pixels[at + 3] ?? 0;
|
|
192
|
+
if (out) { this.pixels[at + 3] = da * (1 - sa); continue; }
|
|
193
|
+
const oa = sa + da * (1 - sa); if (oa <= 0) continue;
|
|
194
|
+
for (let c = 0; c < 3; c++) this.pixels[at + c] = ([r, g, b][c] ?? 0) * sa / oa + (this.pixels[at + c] ?? 0) * da * (1 - sa) / oa;
|
|
195
|
+
this.pixels[at + 3] = oa;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/** The painted bytes, rows top first. */
|
|
201
|
+
bytes(): Uint8Array {
|
|
202
|
+
const out = new Uint8Array(this.width * this.height * 4);
|
|
203
|
+
for (let i = 0; i < out.length; i += 4) { out[i] = byte(this.pixels[i] ?? 0); out[i + 1] = byte(this.pixels[i + 1] ?? 0); out[i + 2] = byte(this.pixels[i + 2] ?? 0); out[i + 3] = byte((this.pixels[i + 3] ?? 0) * 255); }
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** `paintCanvas(w, h, (ctx) => ...)`: a cleanroom canvas painter, run at compile time, as a sampled texture. */
|
|
209
|
+
export function paintCanvas(width: number, height: number, draw: (ctx: PaintContext) => void, options: { colourSpace?: 'srgb' | 'linear' } = {}): DataTexture {
|
|
210
|
+
checkSize(width, height);
|
|
211
|
+
const ctx = new PaintContext(width, height); draw(ctx);
|
|
212
|
+
return paintedTexture(width, height, ctx.bytes(), options);
|
|
213
|
+
}
|