dewdrop-sdk 0.10.0 → 0.11.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/README.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  The Vite plugin that builds a three.js game for Dewdrop, and the name a game
4
4
  imports model calls, multiplayer, saves, sessions and voice from. Dewdrop
5
- supplies those where the game runs; this package carries only the build.
5
+ supplies those where the game runs; this package carries the build, and
6
+ `dewdrop-sdk/vertex`, a material whose vertices a game's own WGSL moves.
6
7
 
7
8
  How to set up a project and everything a game can do is in the docs:
8
9
  https://alpha.dewdrop.world/docs
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dewdrop-sdk",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "The Vite plugin that builds a three.js game for Dewdrop.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -12,6 +12,13 @@
12
12
  "./vite": {
13
13
  "types": "./src/vite.d.ts",
14
14
  "default": "./src/vite.js"
15
+ },
16
+ "./three": {
17
+ "types": "./src/three.d.ts"
18
+ },
19
+ "./vertex": {
20
+ "types": "./src/vertex.d.ts",
21
+ "default": "./src/vertex.js"
15
22
  }
16
23
  },
17
24
  "files": [
package/src/three.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ // What Dewdrop reads from three.js beyond three.js's own API, for a project that types three.js with
2
+ // @types/three. Add `/// <reference types="dewdrop-sdk/three" />` to a file, or "dewdrop-sdk/three" to the
3
+ // "types" of its tsconfig.json or jsconfig.json.
4
+ import 'three';
5
+
6
+ /** One point of `ExposureSettings.compensationCurve`: a scene's brightness in EV100, and how many stops
7
+ * brighter (positive) or darker (negative) than middle grey an adapting exposure shows it. */
8
+ export type CompensationPoint = readonly [ev100: number, stops: number];
9
+
10
+ /** How Dewdrop exposes the lit scene. Settings left out keep their defaults. */
11
+ export interface ExposureSettings {
12
+ /** A fixed exposure in EV100, where each step up halves the brightness; `null` (the default) adapts to the
13
+ * scene. */
14
+ ev?: number | null;
15
+ /** How much brighter or darker than middle grey an adapting exposure keeps a scene, by how bright the scene
16
+ * is: 1 to 8 points, straight lines between them. Default `[[-2, -2.5], [7, 0]]`. */
17
+ compensationCurve?: readonly CompensationPoint[];
18
+ /** How fast the exposure brightens (default 4). */
19
+ up?: number;
20
+ /** How fast the exposure darkens (default 10). */
21
+ down?: number;
22
+ /** Contrast below middle grey, `1` the tone curve's own (default 0.85). */
23
+ shadowContrast?: number;
24
+ /** Contrast above middle grey, `1` the tone curve's own (default 0.85). */
25
+ highlightContrast?: number;
26
+ /** How far, in EV from 0 to 6, a dark area may be lifted (default 2). */
27
+ localShadowsEv?: number;
28
+ /** How far, in EV from 0 to 6, a bright area may be brought down (default 5). */
29
+ localHighlightsEv?: number;
30
+ /** Not a setting since dewdrop-sdk 0.10.1: use `localShadowsEv`. */
31
+ localShadows?: never;
32
+ /** Not a setting since dewdrop-sdk 0.10.1: use `localHighlightsEv`. */
33
+ localHighlights?: never;
34
+ /** Not a setting since dewdrop-sdk 0.10.1: an adapting exposure is shaped by `compensationCurve`. */
35
+ strength?: never;
36
+ /** Not a setting since dewdrop-sdk 0.10.1: an adapting exposure is shaped by `compensationCurve`. */
37
+ range?: never;
38
+ }
39
+
40
+ /** The exposure as reading `renderer.exposure` gives it: every setting filled in. */
41
+ export interface ResolvedExposureSettings {
42
+ ev: number | null;
43
+ compensationCurve: readonly CompensationPoint[];
44
+ up: number;
45
+ down: number;
46
+ shadowContrast: number;
47
+ highlightContrast: number;
48
+ localShadowsEv: number;
49
+ localHighlightsEv: number;
50
+ }
51
+
52
+ declare module 'three' {
53
+ interface WebGLRenderer {
54
+ /** The style of the whole game, `style: <style phrase>. <scene sentence>`; at most 4 KiB. */
55
+ prompt: string;
56
+ /** What the sky is, every pixel no mesh covers, in a few words; at most 1 KiB. Give `scene.background` a
57
+ * matching `Color`. */
58
+ backgroundDescription: string;
59
+ /** How the lit scene is exposed: `null` for Dewdrop's own, adapting exposure. Reading it back gives every
60
+ * setting filled in. */
61
+ get exposure(): ResolvedExposureSettings | null;
62
+ set exposure(settings: ExposureSettings | null);
63
+ /** The time in seconds a `VertexMaterial`'s program reads as `time()`; it stays as set, so set it from the
64
+ * game's clock every frame. */
65
+ programTime: number;
66
+ }
67
+ }
@@ -0,0 +1,97 @@
1
+ // The types of `dewdrop-sdk/vertex`: a material whose vertices the game's
2
+ // own WGSL moves every frame, which Dewdrop's `three` provides.
3
+ /// <reference path="./wgsl.d.ts" />
4
+ import type { Color, ColorRepresentation, Material, MaterialParameters, Texture } from 'three';
5
+
6
+ /**
7
+ * A vertex program: what importing a `.wgsl` file gives in a game built
8
+ * with `dewdrop-sdk/vite`. The file defines
9
+ * `fn vertex(v: Vertex) -> Moved`, which runs for every vertex every frame
10
+ * and may use:
11
+ *
12
+ * - `struct Vertex { position: vec3f, normal: vec3f, uv: vec2f, color: vec4f, index: u32 }`,
13
+ * the vertex in object space, after skinning and morphs;
14
+ * - `struct Moved { position: vec3f, normal: vec3f }`, where it goes and its
15
+ * normal there, in object space;
16
+ * - `time() -> f32`, `renderer.programTime` in seconds;
17
+ * - `param(i: u32) -> f32`, the material's number `i` (0 past the last);
18
+ * - `camera() -> vec3f`, the camera's position in the world;
19
+ * - `world(p: vec3f) -> vec3f`, object-space `p` in the world, each
20
+ * instance's own for an `InstancedMesh` (`world(vec3f(0.0))` is where
21
+ * the instance stands).
22
+ *
23
+ * Programs use 32-bit types, declare no bindings or entry points, and leave
24
+ * out a few built-in functions (`asinh`, `acosh`, `atanh`, `modf`, `frexp`,
25
+ * `ldexp`, the `pack` and `unpack` families, `firstLeadingBit`,
26
+ * `firstTrailingBit`, `countLeadingZeros`, `countTrailingZeros`,
27
+ * `extractBits`, `insertBits`, `reverseBits`, `quantizeToF16`,
28
+ * `determinant`, `dot4I8Packed`, `dot4U8Packed`). A file is at most 64 KiB;
29
+ * its brackets nest at most 32 deep, a statement holds at most 512
30
+ * operators, and an `if` chains at most 32 `else if`. A program's variables
31
+ * hold at most 1,024 values in all, and its size and complexity are held
32
+ * to limits far past a sway, a wave or a swell. A vertex runs for a
33
+ * limited time each frame: a loop with a constant count that would run
34
+ * past it is refused, and one whose count the game sets (`param(i)`) is
35
+ * the program's own to keep to a few thousand passes, since a vertex that
36
+ * runs past it is dropped with its triangles. `vite build` says where a
37
+ * file goes outside any of these. A material drawn with a program for the
38
+ * first time may draw its mesh unmoved for a frame or so.
39
+ */
40
+ export interface VertexProgram {
41
+ readonly isVertexProgram: true;
42
+ /** The file's path in the project, which an error building it names. */
43
+ readonly file: string;
44
+ /** The file's WGSL. */
45
+ readonly source: string;
46
+ }
47
+
48
+ export interface VertexMaterialParameters extends MaterialParameters {
49
+ /** The program, from `import sway from './sway.wgsl'`. */
50
+ program?: VertexProgram | null;
51
+ /** The program's numbers: `param(0)`, `param(1)` and on, at most 1,000. */
52
+ params?: ArrayLike<number> | null;
53
+ /** How far, in object units, the program may move any vertex; a vertex is held within it. 1 unless set. */
54
+ maxDisplacement?: number;
55
+ color?: ColorRepresentation;
56
+ /** Multiplies `color`: a PNG, JPEG or WebP texture, or a DataTexture of RGBA bytes; sRGB when its `colorSpace` is. */
57
+ map?: Texture | null;
58
+ roughness?: number;
59
+ metalness?: number;
60
+ emissive?: ColorRepresentation;
61
+ emissiveIntensity?: number;
62
+ /** Whether the geometry's `color` attribute multiplies `color`. */
63
+ vertexColors?: boolean;
64
+ /** Whether what it draws casts shadows; true unless set. */
65
+ castShadow?: boolean;
66
+ }
67
+
68
+ /**
69
+ * A material whose vertices a WGSL program moves every frame, shaded as a
70
+ * `MeshStandardMaterial` is: `color` × `map` (× vertex colors), `roughness`,
71
+ * `metalness`, and `emissive` × `emissiveIntensity`. A change to any of
72
+ * those shows on the next frame without `needsUpdate`; a game sets
73
+ * `renderer.programTime` from its clock each frame for `time()`.
74
+ */
75
+ export class VertexMaterial extends Material {
76
+ constructor(parameters?: VertexMaterialParameters);
77
+ readonly isVertexMaterial: true;
78
+ program: VertexProgram | null;
79
+ maxDisplacement: number;
80
+ color: Color;
81
+ map: Texture | null;
82
+ roughness: number;
83
+ metalness: number;
84
+ emissive: Color;
85
+ emissiveIntensity: number;
86
+ vertexColors: boolean;
87
+ castShadow: boolean;
88
+ /** The program's numbers: `param(0)`, `param(1)` and on, at most 1,000; a number edited in place shows the next frame. */
89
+ get params(): Float32Array;
90
+ set params(values: ArrayLike<number>);
91
+ /** The program's number `i`, 0 past the last. */
92
+ getParam(i: number): number;
93
+ /** Sets the program's number `i`, from 0 to 999, from the next frame on, as often as every frame. */
94
+ setParam(i: number, value: number): void;
95
+ copy(source: VertexMaterial): this;
96
+ clone(): this;
97
+ }
package/src/vertex.js ADDED
@@ -0,0 +1,5 @@
1
+ // `VertexMaterial`: a mesh material whose vertices a game's own WGSL
2
+ // function moves every frame, shaded as a standard material is. Dewdrop's
3
+ // `three` provides it, and builds the program a `.wgsl` import gives
4
+ // (`vite.js`).
5
+ export { VertexMaterial } from 'three';
package/src/vite.js CHANGED
@@ -10,9 +10,14 @@
10
10
  // says where. The plugin imports nothing from Vite itself, so it works
11
11
  // linked from a checkout as well as installed, on Vite 3 through 8.
12
12
  import { existsSync } from 'node:fs';
13
- import { resolve } from 'node:path';
13
+ import { basename, isAbsolute, relative, resolve, sep } from 'node:path';
14
14
  import { ASSETS_DIR, BACKEND_FILE, BUILD_RECORD_FILE, ENTRY_FILE, PAGE_FILE, buildRecord, detectViteMajor, openPage, outputOptions } from './build.js';
15
15
  import { ON_DEWDROP } from './message.js';
16
+ import { checkVertexProgram, programModule } from './wgsl.js';
17
+
18
+ // A WGSL file imported as it is, with no query asking Vite for its text or
19
+ // URL instead.
20
+ const WGSL = /\.wgsl$/;
16
21
 
17
22
  const BACKEND_SOURCES = ['backend.js', 'backend.ts', 'src/backend.js', 'src/backend.ts'];
18
23
 
@@ -51,8 +56,13 @@ export function backendEntry(root) {
51
56
  }
52
57
 
53
58
  export default function dew() {
59
+ // The project's root, which a `.wgsl` file's path is given from.
60
+ let projectRoot = process.cwd();
54
61
  return {
55
62
  name: 'dew',
63
+ configResolved(config) {
64
+ projectRoot = config.root;
65
+ },
56
66
  config(userConfig, env) {
57
67
  // Said in the terminal, where the developer typed `vite`, rather than
58
68
  // left to the page's console.
@@ -100,6 +110,22 @@ export default function dew() {
100
110
  };
101
111
  return config;
102
112
  },
113
+ // A `.wgsl` import is its vertex program; one Dewdrop would not build
114
+ // stops the build at the line and column of the file the error is at.
115
+ transform(code, id) {
116
+ if (!WGSL.test(id)) return null;
117
+ const result = checkVertexProgram(code);
118
+ if (!result.ok) {
119
+ const error = { message: result.message, id };
120
+ if (result.line > 0) error.loc = { file: id, line: result.line, column: result.column - 1 };
121
+ this.error(error);
122
+ }
123
+ // Its path in the project; one outside it, by its name alone.
124
+ const path = relative(projectRoot, id);
125
+ const outside = isAbsolute(path) || path === '..' || path.startsWith(`..${sep}`);
126
+ const file = outside ? basename(id) : path.split(sep).join('/');
127
+ return { code: programModule(code, file), map: { mappings: '' } };
128
+ },
103
129
  // The built page, its URLs rewritten and its stylesheets linked as Vite
104
130
  // made it for a browser, is opened at the top of the entry, and the
105
131
  // build's record is written beside it. Last of the hooks, since Vite
package/src/wgsl.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ // The type of a `.wgsl` import in a game built with `dewdrop-sdk/vite`.
2
+
3
+ declare module '*.wgsl' {
4
+ /** The vertex program the file holds, for `VertexMaterial`'s `program`. */
5
+ const program: import('./vertex.js').VertexProgram;
6
+ export default program;
7
+ }
package/src/wgsl.js ADDED
@@ -0,0 +1,55 @@
1
+ // Checks a vertex program's WGSL file as Dewdrop builds it, with
2
+ // `wgsl.wasm`: what Dewdrop refuses, the check refuses, at a 1-based line
3
+ // and column of the file (0 and 0 for none) with its message. A file that
4
+ // passes is taken into the game as its source, which Dewdrop builds.
5
+ import { readFileSync } from 'node:fs';
6
+
7
+ let compiled = null;
8
+ let instance = null;
9
+
10
+ // The checker, made once and made again after a failure inside it.
11
+ function checker() {
12
+ compiled ??= new WebAssembly.Module(readFileSync(new URL('./wgsl.wasm', import.meta.url)));
13
+ instance ??= new WebAssembly.Instance(compiled, {}).exports;
14
+ return instance;
15
+ }
16
+
17
+ export function checkVertexProgram(source) {
18
+ const bytes = new TextEncoder().encode(source);
19
+ const c = checker();
20
+ let status;
21
+ let output;
22
+ try {
23
+ // Null for a file past the most it reads, which the check refuses
24
+ // unread; memory read after the call, which may grow it.
25
+ const at = c.dewdrop_input(bytes.length);
26
+ if (at !== 0) new Uint8Array(c.memory.buffer, at, bytes.length).set(bytes);
27
+ status = c.dewdrop_check();
28
+ output = new Uint8Array(c.memory.buffer, c.dewdrop_output(), c.dewdrop_output_len()).slice();
29
+ } catch (error) {
30
+ instance = null;
31
+ return { ok: false, line: 0, column: 0, message: `the check failed on this file (${error.message})` };
32
+ }
33
+ if (status === 0) return { ok: true };
34
+ const view = new DataView(output.buffer);
35
+ return {
36
+ ok: false,
37
+ line: view.getUint32(0, true),
38
+ column: view.getUint32(4, true),
39
+ message: new TextDecoder().decode(output.subarray(8)),
40
+ };
41
+ }
42
+
43
+ // The module a `.wgsl` import becomes: its program, frozen — the file's
44
+ // source and its path in the project, which an error building it names.
45
+ // Both are written as hex, so no replacement a build makes in the text of
46
+ // its modules (Vite's `define`) reaches them.
47
+ export function programModule(source, file) {
48
+ return `const text = (hex) => new TextDecoder('utf-8', { ignoreBOM: true }).decode(Uint8Array.from(hex.match(/../g) ?? [], (h) => parseInt(h, 16)));
49
+ export default Object.freeze({ isVertexProgram: true, file: text("${hex(file)}"), source: text("${hex(source)}") });
50
+ `;
51
+ }
52
+
53
+ function hex(text) {
54
+ return Buffer.from(text, 'utf8').toString('hex');
55
+ }
package/src/wgsl.wasm ADDED
Binary file