/ proof-of-concept / plate-mechanics-sim
Sign in
proof-of-concept / plate-mechanics-sim
plate-mechanics-sim / packages / core / src / fields / raster.ts
37 lines · 1.1 KBBlameHistoryRaw
1import type { Field2D, Range } from "./field";
2import { colormapTable, type Colormap } from "./colormap";
4/**
5 * Paint a field into RGBA pixels with y increasing upward (row 0 of the image is
6 * the top of the plate, y = Ly). Non-finite values are drawn transparent.
7 */
8export function rasterizeField(
9 field: Field2D,
10 range: Range,
11 cm: Colormap,
12 out?: Uint8ClampedArray,
13): Uint8ClampedArray {
14 const { nx, ny, data } = field;
15 const table = colormapTable(cm);
16 const rgba = out && out.length === nx * ny * 4 ? out : new Uint8ClampedArray(nx * ny * 4);
17 const span = range.max - range.min || 1;
18 for (let i = 0; i < ny; i++) {
19 const row = ny - 1 - i;
20 for (let j = 0; j < nx; j++) {
21 const v = data[i + j * ny];
22 const px = (row * nx + j) * 4;
23 if (!Number.isFinite(v)) {
24 rgba[px + 3] = 0;
25 continue;
26 }
27 let t = (v - range.min) / span;
28 t = t < 0 ? 0 : t > 1 ? 1 : t;
29 const k = Math.round(t * 255) * 3;
30 rgba[px] = table[k];
31 rgba[px + 1] = table[k + 1];
32 rgba[px + 2] = table[k + 2];
33 rgba[px + 3] = 255;
34 }
35 }
36 return rgba;
↑↓ move↵openescclose