embedded-react 0.18.0 → 0.20.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.
Files changed (117) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +8 -4
  3. package/aot/compile.mjs +178 -58
  4. package/aot/compiler/animations.mjs +290 -281
  5. package/aot/compiler/boot.mjs +70 -33
  6. package/aot/compiler/branch-merge.mjs +4 -3
  7. package/aot/compiler/check.mjs +9 -9
  8. package/aot/compiler/collect.mjs +324 -205
  9. package/aot/compiler/control-flow.mjs +209 -197
  10. package/aot/compiler/diagnostics.mjs +22 -25
  11. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  12. package/aot/compiler/elements/dial.mjs +91 -77
  13. package/aot/compiler/elements/flat-list.mjs +24 -22
  14. package/aot/compiler/elements/image.mjs +51 -50
  15. package/aot/compiler/elements/modal.mjs +31 -30
  16. package/aot/compiler/elements/props.mjs +23 -23
  17. package/aot/compiler/elements/switch.mjs +42 -34
  18. package/aot/compiler/elements/text-input.mjs +34 -32
  19. package/aot/compiler/expressions.mjs +372 -333
  20. package/aot/compiler/handlers.mjs +473 -387
  21. package/aot/compiler/ir/functions.mjs +11 -1
  22. package/aot/compiler/ir/nodes.mjs +4 -4
  23. package/aot/compiler/ir/reads.mjs +19 -19
  24. package/aot/compiler/ir/types.mjs +14 -14
  25. package/aot/compiler/ir/vectors.mjs +5 -1
  26. package/aot/compiler/keyboard.mjs +17 -7
  27. package/aot/compiler/lower.mjs +77 -80
  28. package/aot/compiler/nodes.mjs +169 -152
  29. package/aot/compiler/options.mjs +35 -30
  30. package/aot/compiler/out.mjs +18 -22
  31. package/aot/compiler/package/animations.mjs +669 -0
  32. package/aot/compiler/package/arena.mjs +252 -0
  33. package/aot/compiler/package/assemble.mjs +177 -0
  34. package/aot/compiler/package/bytecode.mjs +286 -0
  35. package/aot/compiler/package/checks.mjs +1022 -0
  36. package/aot/compiler/package/codegen.mjs +1329 -0
  37. package/aot/compiler/package/enums.mjs +138 -0
  38. package/aot/compiler/package/format.mjs +760 -0
  39. package/aot/compiler/package/layouts.mjs +136 -0
  40. package/aot/compiler/package/lower.mjs +1606 -0
  41. package/aot/compiler/package/props.mjs +118 -0
  42. package/aot/compiler/package/tables.mjs +103 -0
  43. package/aot/compiler/package/vectors.mjs +502 -0
  44. package/aot/compiler/package/writer.mjs +664 -0
  45. package/aot/compiler/pan-responder.mjs +69 -61
  46. package/aot/compiler/parse.mjs +21 -21
  47. package/aot/compiler/static-eval.mjs +25 -23
  48. package/aot/compiler/style-text.mjs +161 -172
  49. package/aot/compiler/svg.mjs +477 -251
  50. package/aot/screenshot-smoke.mjs +55 -41
  51. package/aot/style-map.mjs +102 -90
  52. package/assets/bake-font.mjs +123 -77
  53. package/assets/bake-image.mjs +39 -22
  54. package/assets/bake-svg.mjs +361 -262
  55. package/assets/build-builtin-font.mjs +14 -10
  56. package/assets/emit-c.mjs +83 -62
  57. package/assets/emit-container.mjs +124 -38
  58. package/assets/emit-pack.mjs +77 -67
  59. package/assets/font-config.mjs +9 -6
  60. package/assets/font-sizes.mjs +163 -123
  61. package/assets/glyph-coverage.mjs +74 -54
  62. package/assets/index.mjs +31 -9
  63. package/assets/rasterize.mjs +126 -99
  64. package/assets/svg-loader.mjs +8 -8
  65. package/build.mjs +16 -14
  66. package/cli.mjs +359 -172
  67. package/compile-bin.mjs +5 -5
  68. package/flash.mjs +537 -0
  69. package/hotreload/dev-device.mjs +90 -33
  70. package/hotreload/pack-app.mjs +55 -43
  71. package/hotreload/pack-split.mjs +46 -37
  72. package/hotreload/package-transfer.mjs +175 -0
  73. package/hotreload/protocol.mjs +51 -38
  74. package/hotreload/uploader.mjs +38 -27
  75. package/hotreload/watch-tree.mjs +19 -19
  76. package/pack-container.mjs +31 -23
  77. package/package.json +11 -12
  78. package/persist-transform.mjs +34 -28
  79. package/qjsc-wasm.mjs +25 -14
  80. package/sim/embedded-react.cjs +1 -1
  81. package/sim/embedded-react.js +1 -1
  82. package/sim/embedded-react.wasm +0 -0
  83. package/sim/index.html +94 -85
  84. package/sim-server.mjs +101 -82
  85. package/src/embedded-react/Animated.js +24 -24
  86. package/src/embedded-react/Easing.js +1 -1
  87. package/src/embedded-react/FlatList.js +4 -4
  88. package/src/embedded-react/LayoutAnimation.js +8 -5
  89. package/src/embedded-react/PanResponder.js +75 -71
  90. package/src/embedded-react/Pressable.js +2 -8
  91. package/src/embedded-react/SectionList.js +6 -6
  92. package/src/embedded-react/StyleSheet.js +4 -3
  93. package/src/embedded-react/TouchableOpacity.js +13 -8
  94. package/src/embedded-react/index.d.ts +5 -5
  95. package/src/embedded-react/layout-anim-config.js +10 -4
  96. package/src/embedded-react/list-child.js +5 -5
  97. package/src/embedded-react/named-colors.js +1 -1
  98. package/src/embedded-react/split-style.js +11 -11
  99. package/src/embedded-react/svg-ops.js +760 -593
  100. package/src/embedded-react/useHostValue.js +3 -3
  101. package/src/embedded-react/usePersistentState.js +6 -6
  102. package/src/embedded-react/warn-props.js +1 -1
  103. package/src/host-config.js +60 -53
  104. package/src/props.js +49 -41
  105. package/src/renderer.js +7 -4
  106. package/aot/compiler/assemble.mjs +0 -944
  107. package/aot/compiler/c/animations.mjs +0 -436
  108. package/aot/compiler/c/boot.mjs +0 -127
  109. package/aot/compiler/c/expressions.mjs +0 -270
  110. package/aot/compiler/c/functions.mjs +0 -268
  111. package/aot/compiler/c/keyboard.mjs +0 -96
  112. package/aot/compiler/c/nodes.mjs +0 -303
  113. package/aot/compiler/c/pan-responder.mjs +0 -136
  114. package/aot/compiler/c/statements.mjs +0 -319
  115. package/aot/compiler/c/text.mjs +0 -83
  116. package/aot/compiler/c/vectors.mjs +0 -381
  117. package/aot/compiler/c-syntax.mjs +0 -127
@@ -32,6 +32,19 @@ import {rasterize} from './rasterize.mjs';
32
32
  export const ASCII_FIRST = 0x20;
33
33
  export const ASCII_LAST = 0x7e;
34
34
 
35
+ const SPACE_CODEPOINT = 0x20;
36
+ const MAX_CODEPOINT = 0x10ffff;
37
+ const SUPPORTED_BPP = [1, 2, 4, 8];
38
+ const DEFAULT_BPP = 4;
39
+ const BITS_PER_BYTE = 8;
40
+ const UINT8_MAX = 255;
41
+ const COVERAGE_MAX = 255;
42
+ const COVERAGE_THRESHOLD_1BPP = 128;
43
+ const SUPERSAMPLE = 4;
44
+ const SUPERSAMPLE_8BPP = 8;
45
+ const MIN_CURVE_STEPS = 6;
46
+ const PIXELS_PER_CURVE_STEP = 3;
47
+
35
48
  // Named extra-symbol sets selectable from assets.config.js (glyphs: 'common' | 'minimal' | ...).
36
49
  const SYMBOLS_MINIMAL = [
37
50
  0x00b0, 0x00b1, 0x00b5, 0x00d7, 0x00f7, 0x2013, 0x2014, 0x2022, 0x2026,
@@ -46,15 +59,17 @@ const SYMBOLS_COMMON = [
46
59
  0x2713, 0x2717,
47
60
  ];
48
61
  const SYMBOLS_GREEK = [];
49
- for (let c = 0x0391; c <= 0x03a9; c++) if (c !== 0x03a2) SYMBOLS_GREEK.push(c); // uppercase (skip gap)
50
- for (let c = 0x03b1; c <= 0x03c9; c++) SYMBOLS_GREEK.push(c); // lowercase
62
+ for (let codepoint = 0x0391; codepoint <= 0x03a9; codepoint++)
63
+ if (codepoint !== 0x03a2) SYMBOLS_GREEK.push(codepoint); // uppercase (skip gap)
64
+ for (let codepoint = 0x03b1; codepoint <= 0x03c9; codepoint++)
65
+ SYMBOLS_GREEK.push(codepoint); // lowercase
51
66
  const SYMBOL_SETS = {
52
67
  none: [],
53
68
  minimal: SYMBOLS_MINIMAL,
54
69
  common: SYMBOLS_COMMON,
55
70
  greek: SYMBOLS_GREEK,
56
71
  'common-greek': [...new Set([...SYMBOLS_COMMON, ...SYMBOLS_GREEK])].sort(
57
- (a, b) => a - b,
72
+ (left, right) => left - right,
58
73
  ),
59
74
  };
60
75
 
@@ -89,24 +104,24 @@ export const BUILTIN_SIZES = Object.freeze([10, 12, 16, 20, 24, 32, 48]);
89
104
  */
90
105
  function toCodepoints(spec, field) {
91
106
  if (spec === undefined || spec === null) return [];
92
- const out = [];
107
+ const codepoints = [];
93
108
  for (const item of Array.isArray(spec) ? spec : [spec]) {
94
109
  if (typeof item === 'string') {
95
- for (const ch of item) out.push(ch.codePointAt(0));
110
+ for (const character of item) codepoints.push(character.codePointAt(0));
96
111
  } else if (
97
112
  typeof item === 'number' &&
98
113
  Number.isInteger(item) &&
99
114
  item >= 0 &&
100
- item <= 0x10ffff
115
+ item <= MAX_CODEPOINT
101
116
  ) {
102
- out.push(item);
117
+ codepoints.push(item);
103
118
  } else {
104
119
  throw new Error(
105
120
  `${field}: expected a codepoint number or a string of characters, got ${JSON.stringify(item)}`,
106
121
  );
107
122
  }
108
123
  }
109
- return out;
124
+ return codepoints;
110
125
  }
111
126
 
112
127
  /**
@@ -120,15 +135,15 @@ function toCodepoints(spec, field) {
120
135
  * @returns {number[]} Sorted extra codepoints outside the dense ASCII range.
121
136
  */
122
137
  export function resolveExtras(glyphs, extraGlyphs) {
123
- let cps;
124
- if (!glyphs || glyphs === 'ascii') cps = [];
138
+ let codepoints;
139
+ if (!glyphs || glyphs === 'ascii') codepoints = [];
125
140
  else if (typeof glyphs === 'string') {
126
141
  if (!SYMBOL_SETS[glyphs])
127
142
  throw new Error(
128
143
  `unknown glyph set "${glyphs}" (use 'ascii', one of [${Object.keys(SYMBOL_SETS).join(', ')}], or a list of codepoints/characters)`,
129
144
  );
130
- cps = SYMBOL_SETS[glyphs].slice();
131
- } else cps = toCodepoints(glyphs, 'glyphs');
145
+ codepoints = SYMBOL_SETS[glyphs].slice();
146
+ } else codepoints = toCodepoints(glyphs, 'glyphs');
132
147
 
133
148
  // A bare set name here is almost certainly meant for `glyphs` — as characters it would be a
134
149
  // silent no-op (all ASCII), so say so instead of baking nothing.
@@ -136,11 +151,11 @@ export function resolveExtras(glyphs, extraGlyphs) {
136
151
  throw new Error(
137
152
  `extraGlyphs: "${extraGlyphs}" is a named glyph set — put it in \`glyphs\` (extraGlyphs takes the characters themselves)`,
138
153
  );
139
- cps.push(...toCodepoints(extraGlyphs, 'extraGlyphs'));
154
+ codepoints.push(...toCodepoints(extraGlyphs, 'extraGlyphs'));
140
155
 
141
- return [...new Set(cps)]
142
- .filter(c => c < ASCII_FIRST || c > ASCII_LAST)
143
- .sort((a, b) => a - b);
156
+ return [...new Set(codepoints)]
157
+ .filter(codepoint => codepoint < ASCII_FIRST || codepoint > ASCII_LAST)
158
+ .sort((left, right) => left - right);
144
159
  }
145
160
 
146
161
  /**
@@ -149,13 +164,14 @@ export function resolveExtras(glyphs, extraGlyphs) {
149
164
  * simply cannot draw the character ("pick a different font").
150
165
  *
151
166
  * @param {string} path Path to the .ttf/.otf file.
152
- * @returns {(cp:number)=>boolean} Always true if the file can't be read, so a probe failure never
167
+ * @returns {(codepoint:number)=>boolean} Always true if the file can't be read, so a probe failure never
153
168
  * turns into a misleading claim about the font.
154
169
  */
155
170
  export function loadGlyphProbe(path) {
156
171
  try {
157
172
  const font = opentype.parse(fs.readFileSync(path).buffer);
158
- return cp => font.charToGlyphIndex(String.fromCodePoint(cp)) !== 0;
173
+ return codepoint =>
174
+ font.charToGlyphIndex(String.fromCodePoint(codepoint)) !== 0;
159
175
  } catch {
160
176
  return () => true;
161
177
  }
@@ -164,36 +180,41 @@ export function loadGlyphProbe(path) {
164
180
  /**
165
181
  * Packs an 8-bit coverage bitmap (one byte per pixel) into the engine's per-row bpp layout.
166
182
  *
167
- * @param {Uint8Array} cov Row-major coverage, width*height bytes.
168
- * @param {number} w Glyph width in pixels.
169
- * @param {number} h Glyph height in pixels.
170
- * @param {number} bpp Bits per pixel (1, 2, 4, or 8).
183
+ * @param {Uint8Array} coverage Row-major coverage, width*height bytes.
184
+ * @param {number} width Glyph width in pixels.
185
+ * @param {number} height Glyph height in pixels.
186
+ * @param {number} bpp Bits per pixel (1, 2, 4, or 8).
171
187
  * @returns {number[]} Packed bytes (row-major, each row padded to a whole byte).
172
188
  */
173
- function packCoverage(cov, w, h, bpp) {
174
- const out = [];
175
- if (bpp === 8) {
176
- for (let i = 0; i < w * h; i++) out.push(cov[i]);
177
- return out;
189
+ function packCoverage(coverage, width, height, bpp) {
190
+ const packed = [];
191
+ if (bpp === BITS_PER_BYTE) {
192
+ for (let pixel = 0; pixel < width * height; pixel++)
193
+ packed.push(coverage[pixel]);
194
+ return packed;
178
195
  }
179
- const maxVal = (1 << bpp) - 1;
180
- const perByte = 8 / bpp;
181
- const rowBytes = Math.ceil(w / perByte);
182
- for (let row = 0; row < h; row++) {
183
- for (let b = 0; b < rowBytes; b++) {
196
+ const maxLevel = (1 << bpp) - 1;
197
+ const pixelsPerByte = BITS_PER_BYTE / bpp;
198
+ const rowBytes = Math.ceil(width / pixelsPerByte);
199
+ for (let row = 0; row < height; row++) {
200
+ for (let byteIndex = 0; byteIndex < rowBytes; byteIndex++) {
184
201
  let byte = 0;
185
- for (let s = 0; s < perByte; s++) {
186
- const col = b * perByte + s;
187
- if (col >= w) continue;
188
- const c = cov[row * w + col];
189
- const v =
190
- bpp === 1 ? (c >= 128 ? 1 : 0) : Math.round((c * maxVal) / 255);
191
- byte |= v << (8 - bpp - s * bpp); // first pixel in the high bits
202
+ for (let slot = 0; slot < pixelsPerByte; slot++) {
203
+ const column = byteIndex * pixelsPerByte + slot;
204
+ if (column >= width) continue;
205
+ const sample = coverage[row * width + column];
206
+ const level =
207
+ bpp === 1
208
+ ? sample >= COVERAGE_THRESHOLD_1BPP
209
+ ? 1
210
+ : 0
211
+ : Math.round((sample * maxLevel) / COVERAGE_MAX);
212
+ byte |= level << (BITS_PER_BYTE - bpp - slot * bpp); // first pixel in the high bits
192
213
  }
193
- out.push(byte);
214
+ packed.push(byte);
194
215
  }
195
216
  }
196
- return out;
217
+ return packed;
197
218
  }
198
219
 
199
220
  /**
@@ -201,33 +222,42 @@ function packCoverage(cov, w, h, bpp) {
201
222
  *
202
223
  * @returns {{glyph:object, bytes:number[]}|null} null when the font has no glyph for the codepoint.
203
224
  */
204
- function bakeGlyph(font, cp, pixelSize, baseline, scale, bpp) {
205
- if (font.charToGlyphIndex(String.fromCodePoint(cp)) === 0 && cp !== 0x20)
225
+ function bakeGlyph(font, codepoint, pixelSize, baseline, scale, bpp) {
226
+ if (
227
+ font.charToGlyphIndex(String.fromCodePoint(codepoint)) === 0 &&
228
+ codepoint !== SPACE_CODEPOINT
229
+ )
206
230
  return null;
207
- const glyph = font.charToGlyph(String.fromCodePoint(cp));
231
+ const glyph = font.charToGlyph(String.fromCodePoint(codepoint));
208
232
  const advance = Math.round(glyph.advanceWidth * scale);
209
- const ss = bpp === 8 ? 8 : 4;
210
- const steps = Math.max(6, Math.ceil(pixelSize / 3));
211
- const r = rasterize(glyph.getPath(0, baseline, pixelSize), {ss, steps});
233
+ const supersample = bpp === BITS_PER_BYTE ? SUPERSAMPLE_8BPP : SUPERSAMPLE;
234
+ const steps = Math.max(
235
+ MIN_CURVE_STEPS,
236
+ Math.ceil(pixelSize / PIXELS_PER_CURVE_STEP),
237
+ );
238
+ const raster = rasterize(glyph.getPath(0, baseline, pixelSize), {
239
+ ss: supersample,
240
+ steps,
241
+ });
212
242
 
213
- if (r.width > 255 || r.height > 255) {
243
+ if (raster.width > UINT8_MAX || raster.height > UINT8_MAX) {
214
244
  throw new Error(
215
- `glyph U+${cp.toString(16)} is ${r.width}x${r.height}px — exceeds the uint8 glyph limit`,
245
+ `glyph U+${codepoint.toString(16)} is ${raster.width}x${raster.height}px — exceeds the uint8 glyph limit`,
216
246
  );
217
247
  }
218
- const glyphRec = {
248
+ const glyphRecord = {
219
249
  bitmapOffset: 0, // filled in by the caller once the running offset is known
220
- width: r.width,
221
- height: r.height,
222
- xOffset: r.xOffset,
223
- yOffset: r.yOffset,
224
- advance: Math.min(advance, 255),
250
+ width: raster.width,
251
+ height: raster.height,
252
+ xOffset: raster.xOffset,
253
+ yOffset: raster.yOffset,
254
+ advance: Math.min(advance, UINT8_MAX),
225
255
  };
226
256
  const bytes =
227
- r.width > 0 && r.height > 0
228
- ? packCoverage(r.coverage, r.width, r.height, bpp)
257
+ raster.width > 0 && raster.height > 0
258
+ ? packCoverage(raster.coverage, raster.width, raster.height, bpp)
229
259
  : [];
230
- return {glyph: glyphRec, bytes};
260
+ return {glyph: glyphRecord, bytes};
231
261
  }
232
262
 
233
263
  /**
@@ -247,16 +277,16 @@ export function bakeFont({
247
277
  path,
248
278
  family,
249
279
  sizes,
250
- bpp = 4,
280
+ bpp = DEFAULT_BPP,
251
281
  glyphs = 'ascii',
252
282
  extraGlyphs,
253
283
  }) {
254
- if (![1, 2, 4, 8].includes(bpp))
284
+ if (!SUPPORTED_BPP.includes(bpp))
255
285
  throw new Error(`bpp must be 1, 2, 4, or 8 (got ${bpp})`);
256
286
  const font = opentype.parse(fs.readFileSync(path).buffer);
257
- const extraCps = resolveExtras(glyphs, extraGlyphs);
287
+ const extraCodepoints = resolveExtras(glyphs, extraGlyphs);
258
288
 
259
- const baked = [];
289
+ const bakedSizes = [];
260
290
  for (const pixelSize of sizes) {
261
291
  const scale = pixelSize / font.unitsPerEm;
262
292
  const baseline = Math.round(font.ascender * scale);
@@ -264,8 +294,15 @@ export function bakeFont({
264
294
 
265
295
  const bitmap = [];
266
296
  const dense = [];
267
- for (let cp = ASCII_FIRST; cp <= ASCII_LAST; cp++) {
268
- const baked1 = bakeGlyph(font, cp, pixelSize, baseline, scale, bpp) || {
297
+ for (let codepoint = ASCII_FIRST; codepoint <= ASCII_LAST; codepoint++) {
298
+ const bakedGlyph = bakeGlyph(
299
+ font,
300
+ codepoint,
301
+ pixelSize,
302
+ baseline,
303
+ scale,
304
+ bpp,
305
+ ) || {
269
306
  glyph: {
270
307
  bitmapOffset: 0,
271
308
  width: 0,
@@ -276,24 +313,33 @@ export function bakeFont({
276
313
  },
277
314
  bytes: [],
278
315
  };
279
- baked1.glyph.bitmapOffset = baked1.bytes.length > 0 ? bitmap.length : 0;
280
- bitmap.push(...baked1.bytes);
281
- dense.push(baked1.glyph);
316
+ bakedGlyph.glyph.bitmapOffset =
317
+ bakedGlyph.bytes.length > 0 ? bitmap.length : 0;
318
+ bitmap.push(...bakedGlyph.bytes);
319
+ dense.push(bakedGlyph.glyph);
282
320
  }
283
321
 
284
322
  const extras = [];
285
- for (const cp of extraCps) {
286
- const b = bakeGlyph(font, cp, pixelSize, baseline, scale, bpp);
287
- if (!b) continue; // font has no such glyph
288
- b.glyph.bitmapOffset = b.bytes.length > 0 ? bitmap.length : 0;
289
- bitmap.push(...b.bytes);
290
- extras.push({codepoint: cp, info: b.glyph});
323
+ for (const codepoint of extraCodepoints) {
324
+ const bakedGlyph = bakeGlyph(
325
+ font,
326
+ codepoint,
327
+ pixelSize,
328
+ baseline,
329
+ scale,
330
+ bpp,
331
+ );
332
+ if (!bakedGlyph) continue; // font has no such glyph
333
+ bakedGlyph.glyph.bitmapOffset =
334
+ bakedGlyph.bytes.length > 0 ? bitmap.length : 0;
335
+ bitmap.push(...bakedGlyph.bytes);
336
+ extras.push({codepoint, info: bakedGlyph.glyph});
291
337
  }
292
338
 
293
- baked.push({
339
+ bakedSizes.push({
294
340
  pixelSize,
295
- lineHeight: Math.min(lineHeight, 255),
296
- baseline: Math.min(baseline, 255),
341
+ lineHeight: Math.min(lineHeight, UINT8_MAX),
342
+ baseline: Math.min(baseline, UINT8_MAX),
297
343
  first: ASCII_FIRST,
298
344
  last: ASCII_LAST,
299
345
  bpp,
@@ -302,5 +348,5 @@ export function bakeFont({
302
348
  bitmap,
303
349
  });
304
350
  }
305
- return {family, path, sizes: baked};
351
+ return {family, path, sizes: bakedSizes};
306
352
  }
@@ -21,6 +21,12 @@
21
21
  import fs from 'node:fs';
22
22
  import {PNG} from 'pngjs';
23
23
 
24
+ const RGBA_BYTES = 4;
25
+ const CHANNEL_MAX = 255;
26
+ const CHANNEL_ROUND = 127;
27
+ const RGB565_RED_BLUE_MAX = 31;
28
+ const RGB565_GREEN_MAX = 63;
29
+
24
30
  /**
25
31
  * Decodes an image and returns its baked pixels.
26
32
  *
@@ -52,39 +58,50 @@ export function bakeImage({path, name, format = 'argb8888'}) {
52
58
 
53
59
  if (format === 'rgb565') {
54
60
  const pixels = new Uint16Array(width * height);
55
- for (let i = 0; i < width * height; i++) {
56
- const r = data[i * 4];
57
- const g = data[i * 4 + 1];
58
- const b = data[i * 4 + 2];
59
- const a = data[i * 4 + 3];
60
- if (a !== 255) {
61
- const x = i % width;
62
- const y = (i - x) / width;
61
+ for (let pixel = 0; pixel < width * height; pixel++) {
62
+ const red = data[pixel * RGBA_BYTES];
63
+ const green = data[pixel * RGBA_BYTES + 1];
64
+ const blue = data[pixel * RGBA_BYTES + 2];
65
+ const alpha = data[pixel * RGBA_BYTES + 3];
66
+ if (alpha !== CHANNEL_MAX) {
67
+ const x = pixel % width;
68
+ const y = (pixel - x) / width;
63
69
  throw new Error(
64
- `image "${name}": rgb565 requires a fully opaque source, but pixel (${x},${y}) has alpha ${a} — ` +
70
+ `image "${name}": rgb565 requires a fully opaque source, but pixel (${x},${y}) has alpha ${alpha} — ` +
65
71
  `flatten the art onto its background, or keep the default argb8888 format`,
66
72
  );
67
73
  }
68
74
  // Round-to-nearest 8→5/6/5 bit reduction (the engine bit-replicates back on expand).
69
- const r5 = Math.round((r * 31) / 255);
70
- const g6 = Math.round((g * 63) / 255);
71
- const b5 = Math.round((b * 31) / 255);
72
- pixels[i] = ((r5 << 11) | (g6 << 5) | b5) & 0xffff;
75
+ const red5 = Math.round((red * RGB565_RED_BLUE_MAX) / CHANNEL_MAX);
76
+ const green6 = Math.round((green * RGB565_GREEN_MAX) / CHANNEL_MAX);
77
+ const blue5 = Math.round((blue * RGB565_RED_BLUE_MAX) / CHANNEL_MAX);
78
+ pixels[pixel] = ((red5 << 11) | (green6 << 5) | blue5) & 0xffff;
73
79
  }
74
80
  return {name, width, height, format, pixels};
75
81
  }
76
82
 
77
83
  const pixels = new Uint32Array(width * height);
78
- for (let i = 0; i < width * height; i++) {
79
- const r = data[i * 4];
80
- const g = data[i * 4 + 1];
81
- const b = data[i * 4 + 2];
82
- const a = data[i * 4 + 3];
84
+ for (let pixel = 0; pixel < width * height; pixel++) {
85
+ const red = data[pixel * RGBA_BYTES];
86
+ const green = data[pixel * RGBA_BYTES + 1];
87
+ const blue = data[pixel * RGBA_BYTES + 2];
88
+ const alpha = data[pixel * RGBA_BYTES + 3];
83
89
  // Premultiply the color channels by alpha (round-to-nearest) — the engine's image format.
84
- const rp = Math.floor((r * a + 127) / 255);
85
- const gp = Math.floor((g * a + 127) / 255);
86
- const bp = Math.floor((b * a + 127) / 255);
87
- pixels[i] = ((a << 24) | (rp << 16) | (gp << 8) | bp) >>> 0;
90
+ const premultipliedRed = Math.floor(
91
+ (red * alpha + CHANNEL_ROUND) / CHANNEL_MAX,
92
+ );
93
+ const premultipliedGreen = Math.floor(
94
+ (green * alpha + CHANNEL_ROUND) / CHANNEL_MAX,
95
+ );
96
+ const premultipliedBlue = Math.floor(
97
+ (blue * alpha + CHANNEL_ROUND) / CHANNEL_MAX,
98
+ );
99
+ pixels[pixel] =
100
+ ((alpha << 24) |
101
+ (premultipliedRed << 16) |
102
+ (premultipliedGreen << 8) |
103
+ premultipliedBlue) >>>
104
+ 0;
88
105
  }
89
106
  return {name, width, height, format, pixels};
90
107
  }