@swf2es/render 0.1.45 → 0.1.47

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.
@@ -1,9 +1,22 @@
1
1
  import type { GlState } from "@swf2es/context3d/device";
2
+ import { RAMP_BYTES, rampOf } from "../ramps.js";
2
3
  import { ROW_FLOATS, ROWS_A_LINE, type Rows } from "../rows.js";
3
4
  import { MIRROR, REPEAT, SMOOTH } from "../scene.js";
4
5
  import { LINE_TEXELS, type Textures } from "../textures.js";
5
6
  import { OUTLINE_ROW, OUTLINE_UNIT, ROW_TEXELS, TEXTURE_UNIT } from "./programs.js";
6
7
 
8
+ /**
9
+ * Fewer ramps than this set in a frame (Textures.addRamp) are built on the
10
+ * CPU (rampOf) into the lines' bytes, uploaded with the other lines, so
11
+ * that a frame making a ramp or two, as most do, draws nothing more for
12
+ * them; as many or more, as instances under changing tints make, are
13
+ * built by the backend's pass on the GPU. Both make the same bytes.
14
+ */
15
+ const RAMPS_ON_GPU = 16;
16
+
17
+ /** Whether the machine keeps a word's low byte first, as a texel's red is in rampOf's swapped words. */
18
+ const LITTLE_ENDIAN = new Uint8Array(Uint32Array.of(1).buffer)[0] === 1;
19
+
7
20
  /**
8
21
  * The textures the programs read: the registry's, uploaded as they are
9
22
  * added or change, and the samplers they are read through; the rows, a
@@ -29,9 +42,20 @@ export class GpuTextures {
29
42
  * names in `textures`, the bytes of its lines as uploaded, and how many
30
43
  * lines it has room for.
31
44
  */
32
- private lines: WebGLTexture | null = null;
45
+ lines: WebGLTexture | null = null;
33
46
  private lineBytes = new Uint8Array(0);
34
- private lineRoom = 0;
47
+ /** lineBytes as words, which a ramp spanned on the CPU is written into (rampOf). */
48
+ private lineWords = new Uint32Array(0);
49
+ lineRoom = 0;
50
+ /**
51
+ * The records of the lines built from them (Textures.addRamp), a line's at
52
+ * its line's place; which lines are built so; and those to build in the
53
+ * backend's next pass (WebGLBackend's ramps), each once.
54
+ */
55
+ rampRecords = new Uint8Array(0);
56
+ private built = new Uint8Array(0);
57
+ readonly builds: number[] = [];
58
+ private building = new Uint8Array(0);
35
59
 
36
60
  constructor(gl: WebGL2RenderingContext, state: GlState) {
37
61
  this.gl = gl;
@@ -47,7 +71,12 @@ export class GpuTextures {
47
71
  this.outlineRows = 0;
48
72
  this.lines = null;
49
73
  this.lineBytes = new Uint8Array(0);
74
+ this.lineWords = new Uint32Array(0);
50
75
  this.lineRoom = 0;
76
+ this.rampRecords = new Uint8Array(0);
77
+ this.built = new Uint8Array(0);
78
+ this.builds.length = 0;
79
+ this.building = new Uint8Array(0);
51
80
  this.textures = [];
52
81
  this.samplers = [];
53
82
  this.rowsTexture = gl.createTexture() as WebGLTexture;
@@ -144,15 +173,43 @@ export class GpuTextures {
144
173
  this.growLines(textures.lines);
145
174
  }
146
175
 
147
- for (const id of textures.pending) {
176
+ const pending = textures.pending;
177
+ let ramps = 0;
178
+ for (let k = 0; k < pending.length; k++) {
179
+ ramps += textures.get(pending[k])?.ramp ? 1 : 0;
180
+ }
181
+
182
+ const onGpu = ramps >= RAMPS_ON_GPU || !LITTLE_ENDIAN;
183
+ for (let k = 0; k < pending.length; k++) {
184
+ const id = pending[k];
148
185
  const data = textures.get(id);
149
186
  const fill = data?.pixels ? null : (data?.fill ?? null);
150
187
  if (!data || (!data.pixels && !data.source && fill === null)) {
151
188
  continue;
152
189
  }
153
190
 
191
+ if (data.line !== undefined && data.pixels instanceof Uint8Array && data.ramp) {
192
+ const line = data.line;
193
+ const record =
194
+ data.pixels.length === RAMP_BYTES ? data.pixels : data.pixels.subarray(0, RAMP_BYTES);
195
+ this.rampRecords.set(record, line * RAMP_BYTES);
196
+ this.built[line] = onGpu ? 1 : 0;
197
+ this.textures[id] = this.lines;
198
+ data.pixels = null;
199
+ if (onGpu) {
200
+ this.build(line);
201
+ continue;
202
+ }
203
+
204
+ rampOf(record, this.lineWords, true, line * LINE_TEXELS);
205
+ linesFrom = Math.min(linesFrom, line);
206
+ linesTo = Math.max(linesTo, line + 1);
207
+ continue;
208
+ }
209
+
154
210
  if (data.line !== undefined && data.pixels instanceof Uint8Array) {
155
211
  this.lineBytes.set(data.pixels.subarray(0, LINE_TEXELS * 4), data.line * LINE_TEXELS * 4);
212
+ this.built[data.line] = 0;
156
213
  this.textures[id] = this.lines;
157
214
  linesFrom = Math.min(linesFrom, data.line);
158
215
  linesTo = Math.max(linesTo, data.line + 1);
@@ -290,8 +347,34 @@ export class GpuTextures {
290
347
  textures.pending.length = 0;
291
348
 
292
349
  if (grown || linesTo > 0) {
293
- this.uploadLines(grown ? 0 : linesFrom, grown ? this.lineRoom : linesTo);
350
+ const from = grown ? 0 : linesFrom;
351
+ const to = grown ? this.lineRoom : linesTo;
352
+ this.uploadLines(from, to);
353
+ // Lines built from records in between had their bytes overwritten with none: built again.
354
+ for (let line = from; line < to; line++) {
355
+ if (this.built[line]) {
356
+ this.build(line);
357
+ }
358
+ }
359
+ }
360
+ }
361
+
362
+ /** Line `line` built from its record in the backend's next pass, once however often asked. */
363
+ private build(line: number): void {
364
+ if (!this.building[line]) {
365
+ this.building[line] = 1;
366
+ this.builds.push(line);
367
+ }
368
+ }
369
+
370
+ /** The lines built (builds), done with. */
371
+ builtAll(): void {
372
+ const builds = this.builds;
373
+ for (let i = 0; i < builds.length; i++) {
374
+ this.building[builds[i]] = 0;
294
375
  }
376
+
377
+ this.builds.length = 0;
295
378
  }
296
379
 
297
380
  /**
@@ -303,6 +386,16 @@ export class GpuTextures {
303
386
  const bytes = new Uint8Array(room * LINE_TEXELS * 4);
304
387
  bytes.set(this.lineBytes);
305
388
  this.lineBytes = bytes;
389
+ this.lineWords = new Uint32Array(bytes.buffer);
390
+ const records = new Uint8Array(room * RAMP_BYTES);
391
+ records.set(this.rampRecords);
392
+ this.rampRecords = records;
393
+ const built = new Uint8Array(room);
394
+ built.set(this.built);
395
+ this.built = built;
396
+ const building = new Uint8Array(room);
397
+ building.set(this.building);
398
+ this.building = building;
306
399
  this.lineRoom = room;
307
400
  this.lines ??= this.gl.createTexture() as WebGLTexture;
308
401
  }
@@ -0,0 +1,345 @@
1
+ // Ramps built on the GPU (Textures.addRamp): the lines a frame set from
2
+ // records drawn into the lines' texture at once, each texel its entry as
3
+ // ramps.ts's rampOf finds it on the CPU, in the same integers, so that the
4
+ // bytes are the same. One instanced draw for all of them, each instance a
5
+ // run of lines one after another, each texel's record read from a texture of
6
+ // them by its row, uploaded from the first line set to the last; no uniform
7
+ // array, nothing indexed by gl_DrawID.
8
+ import { type GlState, linkProgram } from "@swf2es/context3d/device";
9
+ import {
10
+ RAMP_BYTES,
11
+ RAMP_COLORS,
12
+ RAMP_COUNT,
13
+ RAMP_LINEAR,
14
+ RAMP_RATIOS,
15
+ RAMP_STOPS,
16
+ TO_SRGB,
17
+ } from "../ramps.js";
18
+ import { LINE_TEXELS } from "../textures.js";
19
+ import type { GpuTextures } from "./gpu-textures.js";
20
+ import { BACK_UNIT, LAYER_UNIT, TEXTURE_UNIT } from "./programs.js";
21
+
22
+ /** Texels of a record, RGBA: the records' texture's width. */
23
+ const RECORD_TEXELS = RAMP_BYTES / 4;
24
+
25
+ /** The most lines built at once: the lines' texture's most, the runs' texture's width. */
26
+ const BUILDS_MOST = 2048;
27
+
28
+ /**
29
+ * Each instance a run of lines, from its first to past its last, two
30
+ * triangles across them in a viewport of the lines' texture. Drawn a quad
31
+ * each, 240 lines took SwiftShader 2.4 ms with a fragment shader that wrote
32
+ * a constant; one quad of as many texels took it 0.1 ms.
33
+ */
34
+ export const RAMP_VERTEX = `#version 300 es
35
+ precision highp float;
36
+ precision highp int;
37
+ uniform highp isampler2D uRuns;
38
+ uniform highp usampler2D uRecords;
39
+
40
+ void main(void) {
41
+ ivec2 run = texelFetch(uRuns, ivec2(gl_InstanceID, 0), 0).rg;
42
+ int c = gl_VertexID;
43
+ float x = c == 1 || c == 2 || c == 4 ? 1.0 : 0.0;
44
+ int row = c == 2 || c == 4 || c == 5 ? run.y : run.x;
45
+ // The records' texture has a row for each of the lines' texture's.
46
+ float room = float(textureSize(uRecords, 0).y);
47
+ gl_Position = vec4(x * 2.0 - 1.0, float(row) / room * 2.0 - 1.0, 0.0, 1.0);
48
+ }
49
+ `;
50
+
51
+ /**
52
+ * Each texel the entry of its line's ramp at its column, as rampOf finds it:
53
+ * the stop's colour, or the span's c0 + floor(d * j / w) in integers, the
54
+ * colour channels back through TO_SRGB in linear light, premultiplied. The
55
+ * ratios are read four a fetch, as the walk comes to them, and the quotient
56
+ * is found in floats and put right by its remainder: a fetch for each stop
57
+ * and four integer divisions an entry took SwiftShader a quarter more.
58
+ */
59
+ export const RAMP_FRAGMENT = `#version 300 es
60
+ precision highp float;
61
+ precision highp int;
62
+ uniform highp usampler2D uRecords;
63
+ uniform highp usampler2D uSrgb;
64
+ out vec4 finalColor;
65
+ int line;
66
+
67
+ ivec4 colorOf(int i) {
68
+ return ivec4(texelFetch(uRecords, ivec2(${RAMP_COLORS / 4} + i, line), 0));
69
+ }
70
+
71
+ int srgb(int l) {
72
+ return int(texelFetch(uSrgb, ivec2(l, 0), 0).r);
73
+ }
74
+
75
+ void main(void) {
76
+ line = int(gl_FragCoord.y);
77
+ int k = int(gl_FragCoord.x);
78
+ uvec4 head = texelFetch(uRecords, ivec2(0, line), 0);
79
+ int count = int(head[${RAMP_COUNT}]);
80
+ bool linear = head[${RAMP_LINEAR}] != 0u;
81
+ uvec4 ratios = texelFetch(uRecords, ivec2(${RAMP_RATIOS / 4}, line), 0);
82
+ int from = int(ratios.x);
83
+ ivec4 c;
84
+ if (k <= from) {
85
+ c = colorOf(0);
86
+ } else {
87
+ // The span k lies in, as rampOf walks them: each one entry wide at least.
88
+ int span = 0;
89
+ int w = 0;
90
+ int at = from + 1;
91
+ for (int i = 1; i < ${RAMP_STOPS}; i++) {
92
+ if (i >= count || at > 255) {
93
+ break;
94
+ }
95
+
96
+ if ((i & 3) == 0) {
97
+ ratios = texelFetch(uRecords, ivec2(${RAMP_RATIOS / 4} + (i >> 2), line), 0);
98
+ }
99
+
100
+ int to = int(ratios[i & 3]);
101
+ w = to - from;
102
+ int end = w <= 0 ? at : max(at, min(to, 255));
103
+ if (k <= end) {
104
+ span = i;
105
+ break;
106
+ }
107
+
108
+ at = end + 1;
109
+ from = to;
110
+ }
111
+
112
+ if (span == 0) {
113
+ c = colorOf(count - 1);
114
+ } else {
115
+ ivec4 x = colorOf(span - 1);
116
+ c = x;
117
+ if (w > 0) {
118
+ ivec4 d = colorOf(span) - x;
119
+ int j = k - from;
120
+ // floor(n / w) exactly: n is within 255 * 255 of 0, so (n + 0.5) / w is
121
+ // at least 0.5 / w from a whole number, which a division up to about 16 ULP
122
+ // out cannot cross; the remainder puts the quotient right on a GPU that
123
+ // divides worse.
124
+ ivec4 n = d * j;
125
+ ivec4 q = ivec4(floor((vec4(n) + 0.5) / float(w)));
126
+ ivec4 r = n - q * w;
127
+ q += ivec4(greaterThanEqual(r, ivec4(w))) - ivec4(lessThan(r, ivec4(0)));
128
+ c = (x + q) & 255;
129
+ }
130
+ }
131
+ }
132
+
133
+ ivec3 rgb = c.rgb;
134
+ if (linear) {
135
+ rgb = ivec3(srgb(c.r), srgb(c.g), srgb(c.b));
136
+ }
137
+
138
+ rgb = (rgb * (c.a + 1)) >> 8;
139
+ finalColor = vec4(vec3(rgb), float(c.a)) / 255.0;
140
+ }
141
+ `;
142
+
143
+ /**
144
+ * Builds the lines GpuTextures marked (builds) from their records: the
145
+ * records uploaded, then drawn into the lines' texture through a
146
+ * framebuffer of its own, blending off.
147
+ */
148
+ export class RampBuilder {
149
+ private readonly gl: WebGL2RenderingContext;
150
+ private readonly state: GlState;
151
+ private program: WebGLProgram | null = null;
152
+ private records: WebGLTexture | null = null;
153
+ private recordRoom = 0;
154
+ private srgb: WebGLTexture | null = null;
155
+ private runList: WebGLTexture | null = null;
156
+ private readonly sorted = new Int32Array(BUILDS_MOST);
157
+ private readonly runs = new Int32Array(BUILDS_MOST * 2);
158
+ private framebuffer: WebGLFramebuffer | null = null;
159
+ private target: WebGLTexture | null = null;
160
+
161
+ constructor(gl: WebGL2RenderingContext, state: GlState) {
162
+ this.gl = gl;
163
+ this.state = state;
164
+ }
165
+
166
+ /**
167
+ * As the context comes or comes back, and once what it made is deleted:
168
+ * nothing made yet, the program included, which link makes. Nothing here
169
+ * touches the context, so that destroy works on a lost one.
170
+ */
171
+ setUp(): void {
172
+ this.program = null;
173
+ this.records = null;
174
+ this.recordRoom = 0;
175
+ this.srgb = null;
176
+ this.runList = null;
177
+ this.framebuffer = null;
178
+ this.target = null;
179
+ }
180
+
181
+ /**
182
+ * The program linked, its samplers told their units: the last of the
183
+ * backend's setUp, so that a context lost meanwhile throws here with all
184
+ * else made, for destroy, and a frame or a BitmapData drawn while links
185
+ * would fail needs none.
186
+ */
187
+ link(): void {
188
+ const gl = this.gl;
189
+ const program = linkProgram(gl, RAMP_VERTEX, RAMP_FRAGMENT);
190
+ this.state.useProgram(program);
191
+ gl.uniform1i(gl.getUniformLocation(program, "uRecords"), TEXTURE_UNIT);
192
+ gl.uniform1i(gl.getUniformLocation(program, "uSrgb"), LAYER_UNIT);
193
+ gl.uniform1i(gl.getUniformLocation(program, "uRuns"), BACK_UNIT);
194
+ this.program = program;
195
+ }
196
+
197
+ /** What it made on the context, deleted. */
198
+ destroy(): void {
199
+ const gl = this.gl;
200
+ for (const texture of [this.records, this.srgb, this.runList]) {
201
+ if (texture) {
202
+ this.state.dropTexture(texture);
203
+ gl.deleteTexture(texture);
204
+ }
205
+ }
206
+
207
+ gl.deleteFramebuffer(this.framebuffer);
208
+ gl.deleteProgram(this.program);
209
+ this.setUp();
210
+ }
211
+
212
+ /** The lines `gpu` marked built into its lines' texture, and marked done. */
213
+ build(gpu: GpuTextures, nearest: WebGLSampler): void {
214
+ const gl = this.gl;
215
+ const state = this.state;
216
+ const program = this.program;
217
+ const lines = gpu.lines;
218
+ if (!program || !lines || gpu.builds.length === 0) {
219
+ gpu.builtAll();
220
+ return;
221
+ }
222
+
223
+ // The lines in order, into runs of lines one after another, each [first, past its last).
224
+ const count = Math.min(gpu.builds.length, BUILDS_MOST);
225
+ const sorted = this.sorted;
226
+ for (let i = 0; i < count; i++) {
227
+ sorted[i] = gpu.builds[i];
228
+ }
229
+
230
+ sorted.subarray(0, count).sort();
231
+ const runs = this.runs;
232
+ let made = 0;
233
+ for (let i = 0; i < count; ) {
234
+ const first = sorted[i];
235
+ let past = first + 1;
236
+ i++;
237
+ while (i < count && sorted[i] === past) {
238
+ past++;
239
+ i++;
240
+ }
241
+
242
+ runs[made * 2] = first;
243
+ runs[made * 2 + 1] = past;
244
+ made++;
245
+ }
246
+
247
+ // The records from the first line built to the last, uploaded in one call.
248
+ this.upload(gpu, sorted[0], sorted[count - 1] + 1);
249
+
250
+ state.bindTexture(BACK_UNIT, this.runList);
251
+ state.activeTexture(BACK_UNIT);
252
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, made, 1, gl.RG_INTEGER, gl.INT, runs);
253
+
254
+ if (this.target !== lines) {
255
+ if (this.framebuffer) {
256
+ gl.deleteFramebuffer(this.framebuffer);
257
+ }
258
+
259
+ this.framebuffer = gl.createFramebuffer() as WebGLFramebuffer;
260
+ state.bindFramebuffer(this.framebuffer);
261
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, lines, 0);
262
+ this.target = lines;
263
+ }
264
+
265
+ state.bindFramebuffer(this.framebuffer);
266
+ state.viewport(0, 0, LINE_TEXELS, gpu.lineRoom);
267
+ state.scissor(null);
268
+ state.colorMask(15);
269
+ state.stencil(null);
270
+ state.setBlend(null);
271
+ state.useProgram(program);
272
+ state.bindVertexArray(null);
273
+ state.bindTexture(TEXTURE_UNIT, this.records);
274
+ state.bindSampler(TEXTURE_UNIT, nearest);
275
+ state.bindTexture(LAYER_UNIT, this.srgb);
276
+ state.bindSampler(LAYER_UNIT, nearest);
277
+ state.bindSampler(BACK_UNIT, nearest);
278
+ gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, made);
279
+ // Integer textures left on units a float sampler of the next program names, whether it reads
280
+ // them or not, fail its draws (INVALID_OPERATION).
281
+ state.bindTexture(TEXTURE_UNIT, null);
282
+ state.bindTexture(LAYER_UNIT, null);
283
+ state.bindTexture(BACK_UNIT, null);
284
+ gpu.builtAll();
285
+ }
286
+
287
+ /** Records `from` up to `to` uploaded; the textures made first where there are none or too few rows. */
288
+ private upload(gpu: GpuTextures, from: number, to: number): void {
289
+ const gl = this.gl;
290
+ const state = this.state;
291
+ if (!this.srgb) {
292
+ this.srgb = gl.createTexture() as WebGLTexture;
293
+ state.bindTexture(LAYER_UNIT, this.srgb);
294
+ state.activeTexture(LAYER_UNIT);
295
+ gl.texImage2D(
296
+ gl.TEXTURE_2D,
297
+ 0,
298
+ gl.R8UI,
299
+ 256,
300
+ 1,
301
+ 0,
302
+ gl.RED_INTEGER,
303
+ gl.UNSIGNED_BYTE,
304
+ TO_SRGB,
305
+ );
306
+ this.runList = gl.createTexture() as WebGLTexture;
307
+ state.bindTexture(BACK_UNIT, this.runList);
308
+ state.activeTexture(BACK_UNIT);
309
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RG32I, BUILDS_MOST, 1, 0, gl.RG_INTEGER, gl.INT, null);
310
+ }
311
+
312
+ const made = !this.records || this.recordRoom !== gpu.lineRoom;
313
+ this.records ??= gl.createTexture() as WebGLTexture;
314
+ state.bindTexture(TEXTURE_UNIT, this.records);
315
+ state.activeTexture(TEXTURE_UNIT);
316
+ if (made) {
317
+ this.recordRoom = gpu.lineRoom;
318
+ gl.texImage2D(
319
+ gl.TEXTURE_2D,
320
+ 0,
321
+ gl.RGBA8UI,
322
+ RECORD_TEXELS,
323
+ this.recordRoom,
324
+ 0,
325
+ gl.RGBA_INTEGER,
326
+ gl.UNSIGNED_BYTE,
327
+ gpu.rampRecords,
328
+ );
329
+ return;
330
+ }
331
+
332
+ gl.texSubImage2D(
333
+ gl.TEXTURE_2D,
334
+ 0,
335
+ 0,
336
+ from,
337
+ RECORD_TEXELS,
338
+ to - from,
339
+ gl.RGBA_INTEGER,
340
+ gl.UNSIGNED_BYTE,
341
+ gpu.rampRecords,
342
+ from * RAMP_BYTES,
343
+ );
344
+ }
345
+ }