A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(build): a Windows game carries its own icon, written in Node
esengine58d6b3b833a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6b3fad721..b3c30aea7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -216,6 +216,16 @@ published separately; it ships inside the editor.movement, clipboard and Enter/Escape are the model's. Keys still reach the gameas well as the field, which is what a browser does and what keeps play == ship.+- **A Windows game shipped with the default executable icon.** The assembler+ wrote the macOS `.icns` and had nothing for the PE, so every Windows build+ carried whatever icon the runtime template's executable happened to have. The+ icon is now written into the executable in pure Node — `rcedit` is a+ Windows-only binary and the assembler has to run on any OS, the same reason the+ APK's binary XML and the `.icns` are written here. The resource tree is rebuilt+ and appended as a new section rather than grown in place (`.rsrc` is not the+ last section an MSVC link emits), and everything the executable already held —+ the manifest that makes it DPI-aware among it — is carried across.+- **Every packaged desktop game opened 1280x720.** The window ignored theproject's design resolution — a portrait game got a landscape window — becausethe host cannot read one: the window exists before any JS does and the hostdiff --git a/build-tools/utils/desktopApp.js b/build-tools/utils/desktopApp.jsindex 4b6903c5e..122358c0a 100644--- a/build-tools/utils/desktopApp.js+++ b/build-tools/utils/desktopApp.js@@ -18,6 +18,7 @@ import path from 'path';import { existsSync } from 'fs';import { chmod, cp, mkdir, readdir, readFile, rm, writeFile } from 'fs/promises';import { pngToIcns } from './icns.js';+import { setExeIcon } from './peResource.js';import { desktopTemplateSources, steamRedistIn } from './nativeTemplate.js';import { fillTemplate } from './nativeApp.js';@@ -124,8 +125,16 @@ export async function assembleDesktopApp(options) {}const iconPng = options.iconPng && existsSync(options.iconPng) ? options.iconPng : sources.icon;- if (platform === 'macos' && existsSync(iconPng)) {- await writeFile(path.join(root, layout.beside, 'AppIcon.icns'), pngToIcns(await readFile(iconPng)));+ if (existsSync(iconPng)) {+ const png = await readFile(iconPng);+ // Where each OS keeps it: macOS beside the app's other resources, Windows+ // INSIDE the executable — which is why one is a file to write and the+ // other is a rewrite of the thing that was just copied.+ if (platform === 'macos') {+ await writeFile(path.join(root, layout.beside, 'AppIcon.icns'), pngToIcns(png));+ } else {+ await writeFile(executable, setExeIcon(await readFile(executable), png));+ }}if (platform === 'macos') {diff --git a/build-tools/utils/peResource.d.ts b/build-tools/utils/peResource.d.tsnew file mode 100644index 000000000..176c75b36--- /dev/null+++ b/build-tools/utils/peResource.d.ts@@ -0,0 +1,11 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// Types for peResource.js, which is plain ESM so the CLI runs it unbuilt.++/**+ * Replace a Windows executable's icon with @p png (square; scaled down to the+ * largest icon size it covers). Everything else the executable's resource tree+ * held is carried over.+ */+export function setExeIcon(exe: Buffer, png: Buffer): Buffer;diff --git a/build-tools/utils/peResource.js b/build-tools/utils/peResource.jsnew file mode 100644index 000000000..001529823--- /dev/null+++ b/build-tools/utils/peResource.js@@ -0,0 +1,367 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The icon inside a Windows executable — written here, in Node, because+ * the alternative is a toolchain on the packaging machine.+ *+ * `rcedit.exe` is a Windows-only binary and `wine` is worse; the assembler has to+ * run on any OS, as it does for the APK's binary XML and the macOS icns. What an+ * exe's icon actually is: an `RT_ICON` resource holding one image, and an+ * `RT_GROUP_ICON` naming it — the same pair a `.ico` file carries, in the PE's+ * resource tree.+ *+ * The tree is rebuilt and APPENDED as a new section rather than grown in place:+ * `.rsrc` is not the last section in an MSVC link, so growing it would shift+ * `.reloc` and every file offset after it. Appending moves nothing — the old+ * section's bytes stay where they are, unreferenced, and everything they held is+ * carried into the new tree.+ */++import { decodePng } from './png.js';++/** Resource types, as the PE numbers them. */+const RT_ICON = 3;+const RT_GROUP_ICON = 14;++/** The sizes Windows draws an icon at. An image is scaled to the largest one it+ * covers — the same rule the macOS icns writer follows, with a smaller ceiling+ * because 256 is the largest icon the format has. */+const ICON_SIZES = [16, 32, 48, 64, 128, 256];++/** US English. An icon under a language nothing asks for is an icon Explorer+ * does not draw; this is the one every packer writes. */+const LANG_EN_US = 0x0409;++const align = (n, to) => Math.ceil(n / to) * to;++/**+ * Area-average downscale of RGBA pixels.+ *+ * Not nearest-neighbour: an icon is looked at, and dropping three quarters of a+ * 1024px mark's pixels is visible as ragged edges at every size Windows draws.+ */+function resampleRgba(src, srcW, srcH, dstW, dstH) {+ const out = Buffer.alloc(dstW * dstH * 4);+ for (let y = 0; y < dstH; y++) {+ const y0 = Math.floor((y * srcH) / dstH);+ const y1 = Math.max(y0 + 1, Math.floor(((y + 1) * srcH) / dstH));+ for (let x = 0; x < dstW; x++) {+ const x0 = Math.floor((x * srcW) / dstW);+ const x1 = Math.max(x0 + 1, Math.floor(((x + 1) * srcW) / dstW));+ let r = 0, g = 0, b = 0, a = 0, n = 0;+ for (let sy = y0; sy < y1; sy++) {+ for (let sx = x0; sx < x1; sx++) {+ const at = (sy * srcW + sx) * 4;+ // Premultiplied while averaging: a transparent pixel's colour+ // is undefined, and letting it vote turns soft edges grey.+ const alpha = src[at + 3] / 255;+ r += src[at] * alpha; g += src[at + 1] * alpha; b += src[at + 2] * alpha;+ a += src[at + 3];+ n++;+ }+ }+ const at = (y * dstW + x) * 4;+ const avgA = a / n;+ const un = avgA > 0 ? 255 / avgA : 0;+ out[at] = Math.min(255, Math.round((r / n) * un));+ out[at + 1] = Math.min(255, Math.round((g / n) * un));+ out[at + 2] = Math.min(255, Math.round((b / n) * un));+ out[at + 3] = Math.round(avgA);+ }+ }+ return out;+}++/**+ * One icon image as `RT_ICON` carries it: a BITMAPINFOHEADER, a bottom-up BGRA+ * bitmap, and an AND mask.+ *+ * The header's height is DOUBLED — colour bitmap and mask are one image to the+ * format, and an icon that says its real height draws as its own top half.+ */+function iconImage(rgba, size) {+ const maskStride = align(Math.ceil(size / 8), 4);+ const out = Buffer.alloc(40 + size * size * 4 + maskStride * size);+ out.writeUInt32LE(40, 0); // biSize+ out.writeInt32LE(size, 4); // biWidth+ out.writeInt32LE(size * 2, 8); // biHeight — colour + mask+ out.writeUInt16LE(1, 12); // biPlanes+ out.writeUInt16LE(32, 14); // biBitCount+ out.writeUInt32LE(0, 16); // biCompression = BI_RGB+ out.writeUInt32LE(size * size * 4, 20);+ for (let y = 0; y < size; y++) {+ // Bottom-up, and BGRA rather than RGBA.+ const src = (size - 1 - y) * size * 4;+ let at = 40 + y * size * 4;+ for (let x = 0; x < size; x++) {+ out[at++] = rgba[src + x * 4 + 2];+ out[at++] = rgba[src + x * 4 + 1];+ out[at++] = rgba[src + x * 4];+ out[at++] = rgba[src + x * 4 + 3];+ }+ }+ // The AND mask stays zero: with 32 bits per pixel the alpha channel is the+ // transparency, and a mask that disagreed with it would punch holes.+ return out;+}++/** The GRPICONDIR that names the image above — what an `.ico` file's header is. */+function iconGroup(size, byteLength, iconId) {+ const out = Buffer.alloc(6 + 14);+ out.writeUInt16LE(0, 0); // reserved+ out.writeUInt16LE(1, 2); // type = icon+ out.writeUInt16LE(1, 4); // one image+ // 256 is written as 0: the field is a byte, and 256 does not fit in one.+ out[6] = size === 256 ? 0 : size;+ out[7] = size === 256 ? 0 : size;+ out[8] = 0; // colours in palette (0 = not paletted)+ out[9] = 0;+ out.writeUInt16LE(1, 10); // planes+ out.writeUInt16LE(32, 12); // bits per pixel+ out.writeUInt32LE(byteLength, 14);+ out.writeUInt16LE(iconId, 18);+ return out;+}++/** Where a PE keeps the things this rewrites. */+function peLayout(exe) {+ const pe = exe.readUInt32LE(0x3c);+ if (exe.toString('ascii', pe, pe + 4) !== 'PE\0\0') throw new Error('not a PE executable');+ const optSize = exe.readUInt16LE(pe + 20);+ const magic = exe.readUInt16LE(pe + 24);+ if (magic !== 0x20b && magic !== 0x10b) throw new Error(`unknown PE optional header ${magic}`);+ return {+ pe,+ sections: exe.readUInt16LE(pe + 6),+ sectionTable: pe + 24 + optSize,+ sectionAlignment: exe.readUInt32LE(pe + 24 + 32),+ fileAlignment: exe.readUInt32LE(pe + 24 + 36),+ sizeOfImage: pe + 24 + 56,+ sizeOfHeaders: exe.readUInt32LE(pe + 24 + 60),+ // The data directories follow the optional header's fixed part, whose+ // length is the one thing PE32 and PE32+ disagree about.+ dataDirs: pe + 24 + (magic === 0x20b ? 112 : 96),+ };+}++function sectionsOf(exe, layout) {+ const out = [];+ for (let i = 0; i < layout.sections; i++) {+ const at = layout.sectionTable + i * 40;+ out.push({+ at,+ name: exe.toString('ascii', at, at + 8).replace(/\0+$/, ''),+ virtualSize: exe.readUInt32LE(at + 8),+ virtualAddress: exe.readUInt32LE(at + 12),+ rawSize: exe.readUInt32LE(at + 16),+ rawPointer: exe.readUInt32LE(at + 20),+ });+ }+ return out;+}++/** Read the existing tree into `[{type, id, lang, data}]`, flattened. */+function readResources(exe, layout) {+ const rva = exe.readUInt32LE(layout.dataDirs + 2 * 8);+ if (!rva) return [];+ const sections = sectionsOf(exe, layout);+ const owner = sections.find((s) => rva >= s.virtualAddress+ && rva < s.virtualAddress + Math.max(s.virtualSize, s.rawSize));+ if (!owner) throw new Error('the resource directory points outside every section');+ const base = owner.rawPointer + (rva - owner.virtualAddress);+ const fileOf = (r) => {+ const s = sections.find((x) => r >= x.virtualAddress+ && r < x.virtualAddress + Math.max(x.virtualSize, x.rawSize));+ return s ? s.rawPointer + (r - s.virtualAddress) : -1;+ };++ const out = [];+ const walk = (offset, path) => {+ const dir = base + offset;+ const named = exe.readUInt16LE(dir + 12);+ const ids = exe.readUInt16LE(dir + 14);+ for (let i = 0; i < named + ids; i++) {+ const e = dir + 16 + i * 8;+ const nameOrId = exe.readUInt32LE(e);+ const child = exe.readUInt32LE(e + 4);+ // A NAMED entry at any level is dropped: nothing this writes uses one,+ // and carrying a name would mean carrying its string table too.+ if (nameOrId & 0x80000000) continue;+ if (child & 0x80000000) {+ walk(child & 0x7fffffff, [...path, nameOrId]);+ } else {+ const dataRva = exe.readUInt32LE(base + child);+ const size = exe.readUInt32LE(base + child + 4);+ const file = fileOf(dataRva);+ if (file < 0) continue;+ const [type, id] = [...path, nameOrId];+ out.push({ type, id, lang: nameOrId, data: exe.subarray(file, file + size) });+ }+ }+ };+ walk(0, []);+ return out;+}++/** Serialize `[{type, id, lang, data}]` into a resource section placed at @p rva. */+function writeResources(entries, rva) {+ const byType = new Map();+ for (const e of entries) {+ if (!byType.has(e.type)) byType.set(e.type, new Map());+ const byId = byType.get(e.type);+ if (!byId.has(e.id)) byId.set(e.id, []);+ byId.get(e.id).push(e);+ }+ // ID entries must be ASCENDING: the loader binary-searches them, so an+ // out-of-order tree parses and then cannot be looked up.+ const types = [...byType.keys()].sort((a, b) => a - b);++ let dirBytes = 16 + types.length * 8;+ for (const t of types) {+ const byId = byType.get(t);+ dirBytes += 16 + byId.size * 8;+ for (const list of byId.values()) dirBytes += 16 + list.length * 8;+ }+ const dataEntryCount = entries.length;+ const dataEntriesAt = dirBytes;+ let blobsAt = align(dataEntriesAt + dataEntryCount * 16, 8);++ let total = blobsAt;+ for (const e of entries) total = align(total + e.data.length, 8);+ const out = Buffer.alloc(total);++ const writeDir = (at, count) => {+ out.writeUInt32LE(0, at); // characteristics+ out.writeUInt32LE(0, at + 4); // timestamp+ out.writeUInt32LE(0, at + 8); // version+ out.writeUInt16LE(0, at + 12); // named entries — none, see readResources+ out.writeUInt16LE(count, at + 14);+ };++ let cursor = 16 + types.length * 8;+ let dataEntry = dataEntriesAt;+ let blob = blobsAt;+ writeDir(0, types.length);+ types.forEach((type, i) => {+ const typeEntryAt = 16 + i * 8;+ out.writeUInt32LE(type, typeEntryAt);+ out.writeUInt32LE((cursor | 0x80000000) >>> 0, typeEntryAt + 4);++ const byId = byType.get(type);+ const ids = [...byId.keys()].sort((a, b) => a - b);+ const idDirAt = cursor;+ writeDir(idDirAt, ids.length);+ cursor += 16 + ids.length * 8;++ ids.forEach((id, j) => {+ const idEntryAt = idDirAt + 16 + j * 8;+ out.writeUInt32LE(id, idEntryAt);+ out.writeUInt32LE((cursor | 0x80000000) >>> 0, idEntryAt + 4);++ const langs = byId.get(id);+ const langDirAt = cursor;+ writeDir(langDirAt, langs.length);+ cursor += 16 + langs.length * 8;++ langs.forEach((entry, k) => {+ const langEntryAt = langDirAt + 16 + k * 8;+ out.writeUInt32LE(entry.lang, langEntryAt);+ out.writeUInt32LE(dataEntry, langEntryAt + 4);+ // An RVA, not an offset into this section — the one field in the+ // tree that is not section-relative.+ out.writeUInt32LE(rva + blob, dataEntry);+ out.writeUInt32LE(entry.data.length, dataEntry + 4);+ out.writeUInt32LE(0, dataEntry + 8); // code page+ out.writeUInt32LE(0, dataEntry + 12);+ entry.data.copy(out, blob);+ blob = align(blob + entry.data.length, 8);+ dataEntry += 16;+ });+ });+ });+ return out;+}++/**+ * Give @p exe the icon in @p png.+ *+ * @param {Buffer} exe A Windows executable.+ * @param {Buffer} png A square PNG; scaled down to the largest icon size it+ * covers, because 256 is the largest the format has.+ * @returns {Buffer} the executable, with its icon replaced.+ */+export function setExeIcon(exe, png) {+ const image = decodePng(png);+ if (image.width !== image.height) throw new Error('an icon must be square');+ const size = [...ICON_SIZES].reverse().find((s) => s <= image.width);+ if (!size) throw new Error(`a ${image.width}px icon is under the smallest Windows slot (16)`);++ const rgba = image.channels === 4+ ? image.data+ : Buffer.from(Uint8Array.from({ length: image.width * image.height * 4 }, (_, i) => (+ i % 4 === 3 ? 255 : image.data[Math.floor(i / 4) * image.channels + (i % 4)]+ )));+ const scaled = size === image.width ? rgba : resampleRgba(rgba, image.width, image.height, size, size);+ const icon = iconImage(scaled, size);++ const layout = peLayout(exe);+ const kept = readResources(exe, layout)+ .filter((e) => e.type !== RT_ICON && e.type !== RT_GROUP_ICON);+ const entries = [+ ...kept,+ { type: RT_ICON, id: 1, lang: LANG_EN_US, data: icon },+ { type: RT_GROUP_ICON, id: 1, lang: LANG_EN_US, data: iconGroup(size, icon.length, 1) },+ ];++ const sections = sectionsOf(exe, layout);+ if (layout.sectionTable + (layout.sections + 1) * 40 > layout.sizeOfHeaders) {+ throw new Error('no room in the PE header for another section');+ }+ const end = sections.reduce((n, s) => Math.max(n, s.virtualAddress + s.virtualSize), 0);+ const rva = align(end, layout.sectionAlignment);+ const tree = writeResources(entries, rva);+ const rawPointer = align(exe.length, layout.fileAlignment);+ const rawSize = align(tree.length, layout.fileAlignment);++ const out = Buffer.alloc(rawPointer + rawSize);+ exe.copy(out);+ tree.copy(out, rawPointer);++ const header = layout.sectionTable + layout.sections * 40;+ out.fill(0, header, header + 40);+ out.write('.rsrc', header, 'ascii');+ out.writeUInt32LE(tree.length, header + 8);+ out.writeUInt32LE(rva, header + 12);+ out.writeUInt32LE(rawSize, header + 16);+ out.writeUInt32LE(rawPointer, header + 20);+ // Initialized data, read-only: what a resource section is, and what the+ // loader maps it as.+ out.writeUInt32LE(0x40000040, header + 36);++ out.writeUInt16LE(layout.sections + 1, layout.pe + 6);+ out.writeUInt32LE(align(rva + tree.length, layout.sectionAlignment), layout.sizeOfImage);+ out.writeUInt32LE(rva, layout.dataDirs + 2 * 8);+ out.writeUInt32LE(tree.length, layout.dataDirs + 2 * 8 + 4);+ // The checksum covers the whole file; a stale one is what makes an executable+ // "corrupt" to the tools that check it. Zero means "not computed", which is+ // what a linker leaves unless asked, so a zero stays zero.+ const checksumAt = layout.pe + 24 + 64;+ if (out.readUInt32LE(checksumAt) !== 0) out.writeUInt32LE(peChecksum(out, checksumAt), checksumAt);+ return out;+}++/** The PE checksum: a 16-bit ones'-complement sum of the file, plus its length,+ * with the checksum field itself read as zero. */+function peChecksum(buf, checksumAt) {+ let sum = 0;+ for (let at = 0; at + 1 < buf.length; at += 2) {+ if (at === checksumAt) { at += 2; continue; }+ sum += buf.readUInt16LE(at);+ sum = (sum & 0xffff) + (sum >>> 16);+ }+ if (buf.length % 2) {+ sum += buf[buf.length - 1];+ sum = (sum & 0xffff) + (sum >>> 16);+ }+ return (sum + buf.length) >>> 0;+}diff --git a/desktop/tests/pe-icon.test.ts b/desktop/tests/pe-icon.test.tsnew file mode 100644index 000000000..f40db7bc1--- /dev/null+++ b/desktop/tests/pe-icon.test.ts@@ -0,0 +1,250 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The icon written into a Windows executable.+ *+ * Read back by a reader written from the PE spec rather than by the writer's own+ * code — the rule the APK and the icns are already held to. What it checks is not+ * "does it parse" but the three things that are wrong in a way nothing reports:+ * a tree the loader cannot binary-search, an existing resource dropped on the+ * floor, and a header that no longer describes the file.+ */+import { describe, it, expect } from 'vitest';+import { setExeIcon } from '../../build-tools/utils/peResource.js';++/** A minimal but STRUCTURALLY REAL PE32+: headers, three sections, and a+ * resource tree holding a manifest. Enough that a spec reader can walk it. */+function fakePe(withResources = true): Buffer {+ const FILE_ALIGN = 0x200;+ const SECT_ALIGN = 0x1000;+ const peAt = 0x80;+ // Two file-alignment units, as a real link leaves: one is exactly the+ // header's own length here, and a PE with no room for another section+ // header is a different case (asserted below).+ const headerSize = FILE_ALIGN * 2;+ const manifest = Buffer.from('<assembly/>', 'ascii');++ // One resource section: root → type 24 → id 1 → lang 0x409 → the manifest.+ const dirBytes = (16 + 8) * 3;+ const dataEntryAt = dirBytes;+ const blobAt = dataEntryAt + 16;+ const rsrcRva = 0x3000;+ const rsrc = Buffer.alloc(blobAt + manifest.length);+ const dir = (at: number) => { rsrc.writeUInt16LE(1, at + 14); };+ dir(0);+ rsrc.writeUInt32LE(24, 16);+ rsrc.writeUInt32LE((24 | 0x80000000) >>> 0, 20);+ dir(24);+ rsrc.writeUInt32LE(1, 40);+ rsrc.writeUInt32LE((48 | 0x80000000) >>> 0, 44);+ dir(48);+ rsrc.writeUInt32LE(0x409, 64);+ rsrc.writeUInt32LE(dataEntryAt, 68);+ rsrc.writeUInt32LE(rsrcRva + blobAt, dataEntryAt);+ rsrc.writeUInt32LE(manifest.length, dataEntryAt + 4);+ manifest.copy(rsrc, blobAt);++ const sections = [+ { name: '.text', rva: 0x1000, size: 0x100 },+ { name: '.data', rva: 0x2000, size: 0x100 },+ ...(withResources ? [{ name: '.rsrc', rva: rsrcRva, size: rsrc.length }] : []),+ ];+ const raw = headerSize + sections.length * FILE_ALIGN;+ const buf = Buffer.alloc(raw);+ buf.write('MZ', 0, 'ascii');+ buf.writeUInt32LE(peAt, 0x3c);+ buf.write('PE\0\0', peAt, 'ascii');+ buf.writeUInt16LE(0x8664, peAt + 4); // machine+ buf.writeUInt16LE(sections.length, peAt + 6);+ buf.writeUInt16LE(240, peAt + 20); // optional header size+ buf.writeUInt16LE(0x20b, peAt + 24); // PE32++ buf.writeUInt32LE(SECT_ALIGN, peAt + 24 + 32);+ buf.writeUInt32LE(FILE_ALIGN, peAt + 24 + 36);+ buf.writeUInt32LE(0x4000, peAt + 24 + 56); // size of image+ buf.writeUInt32LE(headerSize, peAt + 24 + 60);+ const dataDirs = peAt + 24 + 112;+ if (withResources) {+ buf.writeUInt32LE(rsrcRva, dataDirs + 2 * 8);+ buf.writeUInt32LE(rsrc.length, dataDirs + 2 * 8 + 4);+ }+ const table = peAt + 24 + 240;+ sections.forEach((s, i) => {+ const at = table + i * 40;+ buf.write(s.name, at, 'ascii');+ buf.writeUInt32LE(s.size, at + 8);+ buf.writeUInt32LE(s.rva, at + 12);+ buf.writeUInt32LE(FILE_ALIGN, at + 16);+ buf.writeUInt32LE(headerSize + i * FILE_ALIGN, at + 20);+ });+ if (withResources) rsrc.copy(buf, headerSize + 2 * FILE_ALIGN);+ return buf;+}++/** A real PNG of one flat colour — decodePng reads it, so a stub will not do. */+function png(size: number, rgba: [number, number, number, number]): Buffer {+ const zlib = require('node:zlib') as typeof import('node:zlib');+ const raw = Buffer.alloc((size * 4 + 1) * size);+ for (let y = 0; y < size; y++) {+ const row = y * (size * 4 + 1);+ for (let x = 0; x < size; x++) {+ raw[row + 1 + x * 4] = rgba[0];+ raw[row + 2 + x * 4] = rgba[1];+ raw[row + 3 + x * 4] = rgba[2];+ raw[row + 4 + x * 4] = rgba[3];+ }+ }+ const chunk = (type: string, body: Buffer) => {+ const head = Buffer.alloc(8);+ head.writeUInt32BE(body.length, 0);+ head.write(type, 4, 'ascii');+ const crc = Buffer.alloc(4);+ crc.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, 'ascii'), body])) >>> 0, 0);+ return Buffer.concat([head, body, crc]);+ };+ const ihdr = Buffer.alloc(13);+ ihdr.writeUInt32BE(size, 0);+ ihdr.writeUInt32BE(size, 4);+ ihdr[8] = 8;+ ihdr[9] = 6; // RGBA+ return Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ chunk('IHDR', ihdr),+ chunk('IDAT', zlib.deflateSync(raw)),+ chunk('IEND', Buffer.alloc(0)),+ ]);+}++function crc32(buf: Buffer): number {+ let c = ~0;+ for (const byte of buf) {+ c ^= byte;+ for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xedb88320 & -(c & 1));+ }+ return ~c;+}++/** A reader written from the PE format, not from the writer. */+function readResources(exe: Buffer): { type: number; id: number; lang: number; data: Buffer }[] {+ const pe = exe.readUInt32LE(0x3c);+ const optSize = exe.readUInt16LE(pe + 20);+ const count = exe.readUInt16LE(pe + 6);+ const table = pe + 24 + optSize;+ const sections = Array.from({ length: count }, (_, i) => {+ const at = table + i * 40;+ return {+ rva: exe.readUInt32LE(at + 12),+ size: Math.max(exe.readUInt32LE(at + 8), exe.readUInt32LE(at + 16)),+ file: exe.readUInt32LE(at + 20),+ };+ });+ const fileOf = (rva: number) => {+ const s = sections.find((x) => rva >= x.rva && rva < x.rva + x.size);+ return s ? s.file + (rva - s.rva) : -1;+ };+ const dirRva = exe.readUInt32LE(pe + 24 + 112 + 2 * 8);+ const base = fileOf(dirRva);+ const out: { type: number; id: number; lang: number; data: Buffer }[] = [];+ const walk = (offset: number, path: number[]) => {+ const at = base + offset;+ const named = exe.readUInt16LE(at + 12);+ const ids = exe.readUInt16LE(at + 14);+ expect(named, 'named entries are not written').toBe(0);+ let previous = -1;+ for (let i = 0; i < ids; i++) {+ const e = at + 16 + i * 8;+ const id = exe.readUInt32LE(e);+ const child = exe.readUInt32LE(e + 4);+ // The loader BINARY-SEARCHES each directory, so a tree whose ids are+ // out of order parses and then cannot be looked up.+ expect(id, 'directory ids ascend').toBeGreaterThan(previous);+ previous = id;+ if (child & 0x80000000) walk(child & 0x7fffffff, [...path, id]);+ else {+ const rva = exe.readUInt32LE(base + child);+ const size = exe.readUInt32LE(base + child + 4);+ const file = fileOf(rva);+ expect(file, 'a data entry points into a section').toBeGreaterThanOrEqual(0);+ out.push({ type: path[0], id: path[1], lang: id, data: exe.subarray(file, file + size) });+ }+ }+ };+ walk(0, []);+ return out;+}++describe('the icon inside a Windows executable', () => {+ it('writes an icon and the group that names it', () => {+ const out = setExeIcon(fakePe(), png(64, [10, 20, 30, 255]));+ const res = readResources(out);+ const icon = res.find((r) => r.type === 3);+ const group = res.find((r) => r.type === 14);+ expect(icon).toBeDefined();+ expect(group).toBeDefined();++ // The image's header height is DOUBLED — the format counts the colour+ // bitmap and the mask as one image, and an icon that says its real height+ // draws as the top half of itself.+ expect(icon!.data.readInt32LE(4)).toBe(64);+ expect(icon!.data.readInt32LE(8)).toBe(128);+ expect(icon!.data.readUInt16LE(14)).toBe(32);++ // And the group has to agree with it, byte count included: Windows reads+ // the size from here, not from the resource entry.+ expect(group!.data.readUInt16LE(4)).toBe(1);+ expect(group!.data[6]).toBe(64);+ expect(group!.data.readUInt32LE(14)).toBe(icon!.data.length);+ expect(group!.data.readUInt16LE(18)).toBe(icon!.id);+ });++ it('carries over what the executable already had', () => {+ // The manifest is what tells Windows the app is DPI-aware and which+ // common-controls version it wants; losing it is a visibly blurry app.+ const res = readResources(setExeIcon(fakePe(), png(32, [1, 2, 3, 255])));+ const manifest = res.find((r) => r.type === 24);+ expect(manifest?.data.toString('ascii')).toBe('<assembly/>');+ });++ it('leaves the headers describing the file it produced', () => {+ const before = fakePe();+ const after = setExeIcon(before, png(64, [0, 0, 0, 255]));+ const pe = after.readUInt32LE(0x3c);+ expect(after.readUInt16LE(pe + 6)).toBe(before.readUInt16LE(pe + 6) + 1);++ // Every section must fit inside SizeOfImage, or the loader refuses the+ // image outright — the failure that is a dialog, not a wrong icon.+ const table = pe + 24 + after.readUInt16LE(pe + 20);+ const sections = after.readUInt16LE(pe + 6);+ const sizeOfImage = after.readUInt32LE(pe + 24 + 56);+ for (let i = 0; i < sections; i++) {+ const at = table + i * 40;+ expect(after.readUInt32LE(at + 12) + after.readUInt32LE(at + 8)).toBeLessThanOrEqual(sizeOfImage);+ // And inside the file it was written to.+ expect(after.readUInt32LE(at + 20) + after.readUInt32LE(at + 16)).toBeLessThanOrEqual(after.length);+ }+ });++ it('scales down to the largest slot the format has', () => {+ // 256 is the ceiling: a 1024px mark is what the template ships, and an+ // icon larger than the format allows is one Windows does not draw.+ const res = readResources(setExeIcon(fakePe(), png(1024, [200, 100, 50, 255])));+ const icon = res.find((r) => r.type === 3)!;+ expect(icon.data.readInt32LE(4)).toBe(256);+ // 256 is written as ZERO in the group entry — the field is one byte.+ expect(res.find((r) => r.type === 14)!.data[6]).toBe(0);+ });++ it('takes a size the format has, not the picture\'s own', () => {+ const res = readResources(setExeIcon(fakePe(), png(100, [0, 255, 0, 255])));+ expect(res.find((r) => r.type === 3)!.data.readInt32LE(4)).toBe(64);+ });++ it('refuses what it cannot honestly write', () => {+ expect(() => setExeIcon(fakePe(), png(8, [0, 0, 0, 255]))).toThrow(/smallest Windows slot/);+ expect(() => setExeIcon(Buffer.alloc(64), png(32, [0, 0, 0, 255]))).toThrow(/not a PE/);+ });++ it('gives an executable with no resources at all one', () => {+ const res = readResources(setExeIcon(fakePe(false), png(32, [4, 5, 6, 255])));+ expect(res.map((r) => r.type).sort((a, b) => a - b)).toEqual([3, 14]);+ });+});