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(editor): move asset compression to per-asset import settings; modernize Package dialog
yhh06c554139ce2
diff --git a/desktop/electron/atlasPacker.ts b/desktop/electron/atlasPacker.tsindex fd25793b8..928698497 100644--- a/desktop/electron/atlasPacker.ts+++ b/desktop/electron/atlasPacker.ts@@ -161,9 +161,53 @@ export function decodePngImage(key: string, png: Uint8Array): AtlasInputImage {return { key, width: decoded.width, height: decoded.height, rgba: new Uint8Array(decoded.data) };}+/** Encode raw RGBA8 (row 0 = top) to PNG bytes. */+export function encodeRgbaPng(width: number, height: number, rgba: Uint8Array): Uint8Array {+ const png = new PNG({ width, height });+ Buffer.from(rgba).copy(png.data);+ return new Uint8Array(PNG.sync.write(png));+}+/** Encode a composed page back to PNG bytes. */export function encodePagePng(page: AtlasPage): Uint8Array {- const png = new PNG({ width: page.width, height: page.height });- Buffer.from(page.rgba).copy(png.data);- return new Uint8Array(PNG.sync.write(png));+ return encodeRgbaPng(page.width, page.height, page.rgba);+}++/**+ * Box-filter downscale so max(width, height) ≤ `maxDim`. Returns the input+ * unchanged when already within the cap. Averages in premultiplied-alpha space+ * (color weighted by coverage) so transparent pixels don't bleed dark fringes+ * into the shrunk result. Pure + deterministic — composes with content-addressed+ * staging exactly like the packer.+ */+export function downscaleRgba(img: AtlasInputImage, maxDim: number): AtlasInputImage {+ const longest = Math.max(img.width, img.height);+ if (!(maxDim > 0) || longest <= maxDim) return img;+ const scale = maxDim / longest;+ const nw = Math.max(1, Math.round(img.width * scale));+ const nh = Math.max(1, Math.round(img.height * scale));+ const out = new Uint8Array(nw * nh * 4);+ for (let y = 0; y < nh; y++) {+ const sy0 = Math.floor((y * img.height) / nh);+ const sy1 = Math.max(sy0 + 1, Math.floor(((y + 1) * img.height) / nh));+ for (let x = 0; x < nw; x++) {+ const sx0 = Math.floor((x * img.width) / nw);+ const sx1 = Math.max(sx0 + 1, Math.floor(((x + 1) * img.width) / nw));+ let r = 0, g = 0, b = 0, a = 0, n = 0;+ for (let sy = sy0; sy < sy1; sy++) {+ for (let sx = sx0; sx < sx1; sx++) {+ const i = (sy * img.width + sx) * 4;+ const al = img.rgba[i + 3];+ r += img.rgba[i] * al; g += img.rgba[i + 1] * al; b += img.rgba[i + 2] * al;+ a += al; n++;+ }+ }+ const o = (y * nw + x) * 4;+ out[o] = a > 0 ? Math.round(r / a) : 0;+ out[o + 1] = a > 0 ? Math.round(g / a) : 0;+ out[o + 2] = a > 0 ? Math.round(b / a) : 0;+ out[o + 3] = Math.round(a / n);+ }+ }+ return { key: img.key, width: nw, height: nh, rgba: out };}diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.tsindex 8ec267a90..f88a4353e 100644--- a/desktop/electron/cookAssets.ts+++ b/desktop/electron/cookAssets.ts@@ -20,7 +20,11 @@import { writeFile, mkdir, readFile } from 'node:fs/promises';import path from 'node:path';import { scanAssetDatabase, type AssetEntry } from './assetDb';-import { packAtlas, decodePngImage, encodePagePng, type AtlasInputImage } from './atlasPacker';+import { packAtlas, decodePngImage, encodePagePng, encodeRgbaPng, downscaleRgba, type AtlasInputImage } from './atlasPacker';+// Per-asset texture cook settings (compress opt-out / format / size cap), read+// from the `.meta` `importer` block — the same registry the inspector edits, so a+// texture's ship-time compression is authored per asset, not one global switch.+import { readTextureCookSettings } from '../src/project/assetImporter';// Single-source content hash (sdk/src/asset/contentHash.ts). Imported as source —// no hand-mirrored copy — so the cook and the runtime agree by construction.import { contentHashHex } from '../../sdk/src/asset/contentHash';@@ -126,9 +130,28 @@ function caBaseFor(name: string, delivery: GroupDelivery): string {return 'assets';}-/** Targets the UASTC KTX2 the cook emits can transcode to at runtime. */+/** Targets the KTX2 the cook emits can transcode to at runtime (UASTC + ETC1S). */const COMPRESSED_TARGETS = ['astc-4x4', 'etc2-rgba8', 's3tc-dxt5'];+/** PNG width/height from the IHDR (big-endian u32 at byte offsets 16 / 20) —+ * a header peek, so the `maxSize` cap can skip decoding textures already in range. */+function pngDimensions(png: Uint8Array): { width: number; height: number } {+ const dv = new DataView(png.buffer, png.byteOffset, png.byteLength);+ return { width: dv.getUint32(16), height: dv.getUint32(20) };+}++/** The slice of the vendored Basis encoder (build-tools/basis/encoder.mjs, a JS+ * module) the cook uses. Typed locally so the per-texture format/srgb path stays+ * type-checked without a hand-written `.d.ts`. */+interface BasisEncoderModule {+ encodePngToKtx2(png: Uint8Array, opts?: { mode?: string; srgb?: boolean }): Promise<Uint8Array>;+ encodeToKtx2(+ source: { type: string; data: Uint8Array; width?: number; height?: number },+ opts?: { mode?: string; srgb?: boolean },+ ): Promise<Uint8Array>;+ ImageType: { PNG: string; JPG: string; RGBA: string };+}+/** Replace a path's extension (e.g. .png → .ktx2); appends if it had none. */function swapExt(p: string, ext: string): string {const cur = path.extname(p);@@ -292,10 +315,14 @@ export async function cookAssets(// Load the KTX2 encoder lazily (only when compressing — it pulls a ~MB wasm) and// by dynamic import, so the Electron-main bundle keeps it external rather than// inlining a module that resolves its wasm via import.meta.url.+ // Atlas pages compress as UASTC (they aggregate many textures — no single+ // per-asset setting applies); standalone textures use `textureEnc` directly so+ // each honors its own format / srgb / opt-out from the importer block.let encodePng: ((png: Uint8Array) => Promise<Uint8Array>) | null = null;+ let textureEnc: BasisEncoderModule | null = null;if (compressTextures) {- const enc = await import('../../build-tools/basis/encoder.mjs');- encodePng = (png) => enc.encodePngToKtx2(png, { mode: 'uastc' });+ textureEnc = await import('../../build-tools/basis/encoder.mjs') as unknown as BasisEncoderModule;+ encodePng = (png) => textureEnc!.encodePngToKtx2(png, { mode: 'uastc' });}// WAV → MP3 (LAME wasm) rides the same lazy pattern; per-asset importer// settings can opt a clip out (seamless loops) or pick a bitrate.@@ -423,10 +450,32 @@ export async function cookAssets(// Encode raster textures (PNG) to GPU-compressed KTX2 — they stay compressed// in VRAM, the runtime transcodes per device. Hash + name reflect the ENCODED// bytes, so this composes with content-addressing below.- if (encodePng && entry.type !== 'scene' && ext.toLowerCase() === '.png') {- data = await encodePng(data);- ext = '.ktx2';- compressedFormats = COMPRESSED_TARGETS;+ if (textureEnc && entry.type !== 'scene' && ext.toLowerCase() === '.png') {+ const tex = readTextureCookSettings(entry.importer);+ // maxSize downscale first — it applies even when a texture opts OUT of+ // compression (a huge UI sprite can ship as a smaller raw PNG).+ let rgba: Uint8Array | null = null;+ let tw = 0, th = 0;+ try {+ const dims = pngDimensions(data);+ if (tex.maxSize < Math.max(dims.width, dims.height)) {+ const scaled = downscaleRgba(decodePngImage(entry.path, data), tex.maxSize);+ rgba = scaled.rgba; tw = scaled.width; th = scaled.height;+ if (!tex.compress) data = encodeRgbaPng(tw, th, rgba); // ship the shrunk PNG+ }+ } catch (err) {+ warnings.push(`${entry.path}: texture resize skipped — ${err instanceof Error ? err.message : String(err)}`);+ }+ // Per-asset compression: KTX2 (Basis) in the texture's chosen format, or+ // ship the raw/shrunk PNG when the asset opted out. Hash + name below+ // reflect the ENCODED bytes, so this composes with content-addressing.+ if (tex.compress) {+ data = rgba+ ? await textureEnc.encodeToKtx2({ type: textureEnc.ImageType.RGBA, data: rgba, width: tw, height: th }, { mode: tex.format, srgb: tex.srgb })+ : await textureEnc.encodeToKtx2({ type: textureEnc.ImageType.PNG, data }, { mode: tex.format, srgb: tex.srgb });+ ext = '.ktx2';+ compressedFormats = COMPRESSED_TARGETS;+ }}// WAV sources re-encode to MP3 (universal decode); other audio formats are// already compressed and pass through. Hash + name reflect the ENCODED bytes.diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsxindex 234e56922..fe6aa25f5 100644--- a/desktop/src/components/BuildDialog.tsx+++ b/desktop/src/components/BuildDialog.tsx@@ -1,17 +1,24 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file BuildDialog.tsx — the UE5-style "Package Project" modal.+ * @file BuildDialog.tsx — the "Package Project" modal.* Pick a target platform + configuration + output, hit Build, watch the* cook → bundle → copy run, then reveal the output. The dialog is driven by* a per-platform descriptor table ({@link PLATFORMS}): each platform supplies- * its blurb, default output, which options apply, any build prerequisite, and- * the post-build next-steps — so the UI is contextual per target (UE-style)- * rather than one fixed option set. All four targets (Web / Desktop / WeChat- * / Playable) are live.+ * its icon, blurb, default output, which options apply, any build prerequisite,+ * and the post-build next-steps — so the UI is contextual per target.+ *+ * Altitude: this dialog is the *publish* layer, so it does NOT carry+ * per-asset optimization. Texture compression / Max Size / audio bitrate are+ * authored per asset in the Inspector's Import Settings; the build only+ * chooses whether to HONOR those settings (`assetCompression: 'auto'`) or+ * skip them for fast iteration (`'skip'`). All four targets are live.*/-import { useState, useSyncExternalStore } from 'react';-import { Loader2, FolderOpen, CheckCircle2, AlertCircle, Boxes, Info, Copy, ExternalLink, Play } from 'lucide-react';+import { useState, useSyncExternalStore, type ReactNode } from 'react';+import {+ Loader2, FolderOpen, CheckCircle2, AlertCircle, Boxes, Info, Copy, ExternalLink, Play,+ Globe, Monitor, MessageSquare, ChevronRight,+} from 'lucide-react';import { Modal } from '@/components/Modal';import { Segmented } from '@/components/Segmented';import { Button } from '@/components/Button';@@ -22,6 +29,7 @@ import { t } from '@/i18n';type Phase = 'idle' | 'running' | 'done' | 'error';type Config = 'development' | 'shipping';type Platform = 'web' | 'desktop' | 'wechat' | 'playable';+type AssetCompression = 'auto' | 'skip';interface Result {ok: boolean;@@ -38,6 +46,8 @@ interface PlatformDef {id: Platform;label: string;ready: boolean;+ /** Target glyph shown on the platform tile. */+ icon: ReactNode;/** One-line description of the target (shown under the platform row). */blurb: string;defaultOut: string;@@ -54,26 +64,26 @@ interface PlatformDef {const PLATFORMS: PlatformDef[] = [{- id: 'web', label: t('build.plat.web'), ready: true,+ id: 'web', label: t('build.plat.web'), ready: true, icon: <Globe size={17} />,blurb: t('build.blurb.web'),defaultOut: 'dist-web', sourceMaps: true, httpPreview: true,next: (o) => t('build.next.web', { out: o }),},{- id: 'desktop', label: t('build.plat.desktop'), ready: true,+ id: 'desktop', label: t('build.plat.desktop'), ready: true, icon: <Monitor size={17} />,blurb: t('build.blurb.desktop'),defaultOut: 'dist-desktop', sourceMaps: true,next: (o) => t('build.next.desktop', { out: o }),},{- id: 'wechat', label: t('build.plat.wechat'), ready: true,+ id: 'wechat', label: t('build.plat.wechat'), ready: true, icon: <MessageSquare size={17} />,blurb: t('build.blurb.wechat'),defaultOut: 'dist-wechat', sourceMaps: false,prereq: t('build.prereq.wechat'),next: (o) => t('build.next.wechat', { out: o }),},{- id: 'playable', label: t('build.plat.playable'), ready: true,+ id: 'playable', label: t('build.plat.playable'), ready: true, icon: <Play size={16} />,blurb: t('build.blurb.playable'),defaultOut: 'dist-playable', sourceMaps: false, httpPreview: true,prereq: t('build.prereq.playable'),@@ -83,6 +93,19 @@ const PLATFORMS: PlatformDef[] = [const mb = (bytes: number): string => `${(bytes / 1024 / 1024).toFixed(1)} MB`;+/** A titled section box — gives the dialog visual grouping instead of a flat column. */+function Group({ title, count, children }: { title: string; count?: string; children: ReactNode }) {+ return (+ <div className="build__group">+ <div className="build__group-head">+ <span className="build__group-title">{title}</span>+ {count && <span className="build__group-count">{count}</span>}+ </div>+ <div className="build__group-body">{children}</div>+ </div>+ );+}+export function BuildDialog() {const close = () => useEditorStore.getState().setBuildOpen(false);const project = useSyncExternalStore(ProjectStore.subscribe, ProjectStore.getSnapshot);@@ -97,9 +120,11 @@ export function BuildDialog() {const [outDir, setOutDir] = useState(saved.outDir?.[initialPlatform] ?? initialDef.defaultOut);const [openFolder, setOpenFolder] = useState(saved.openFolder ?? true);const [sourceMaps, setSourceMaps] = useState(saved.sourceMaps ?? false);- const [compressTextures, setCompressTextures] = useState(saved.compressTextures ?? false);- const [atlasTextures, setAtlasTextures] = useState(saved.atlasTextures ?? false);- const [compressAudio, setCompressAudio] = useState(saved.compressAudio ?? false);+ // Publish-layer optimization switch: honor each asset's Import Settings, or skip+ // compression entirely for fast iteration. The per-asset decisions live in the+ // Inspector; this only picks whether to apply them.+ const [assetCompression, setAssetCompression] = useState<AssetCompression>(saved.assetCompression ?? 'auto');+ const [advOpen, setAdvOpen] = useState(false);const [phase, setPhase] = useState<Phase>('idle');const [result, setResult] = useState<Result | null>(null);const [log, setLog] = useState<string[]>([]);@@ -119,6 +144,7 @@ export function BuildDialog() {.filter((a) => a.type === 'scene' && (a.path.startsWith(`${scenesDir}/`) || a.path === project?.defaultScene)).sort((a, b) =>a.path === project?.defaultScene ? -1 : b.path === project?.defaultScene ? 1 : a.path.localeCompare(b.path));+ const shippedScenes = sceneList.filter((s) => s.path === project?.defaultScene || !excludedScenes.has(s.path)).length;const pickPlatform = (p: PlatformDef) => {if (!p.ready) return;@@ -139,7 +165,10 @@ export function BuildDialog() {setResult(null);setLog([]);// Persist the chosen settings to project.esproject (restored next time).- void ProjectStore.setPackaging({ platform, config, sourceMaps, openFolder, compressTextures, atlasTextures, compressAudio, outDir: { [platform]: outDir } });+ void ProjectStore.setPackaging({ platform, config, sourceMaps, openFolder, assetCompression, outDir: { [platform]: outDir } });+ // 'auto' → honor each asset's Import Settings (the cook then reads per-asset+ // texture/audio compression + Max Size); 'skip' → ship everything raw.+ const compress = assetCompression === 'auto';// Live build log (UE-style): each export phase streams over IPC.const unsub = window.estella.project?.onExportProgress?.((p) =>setLog((l) => [...l, p.detail ? `${p.phase} — ${p.detail}` : p.phase]),@@ -150,9 +179,9 @@ export function BuildDialog() {outDir,minify: config === 'shipping',sourcemap: def.sourceMaps && sourceMaps,- compressTextures,- atlasTextures,- compressAudio,+ compressTextures: compress,+ atlasTextures: compress,+ compressAudio: compress,})) as Result | null;if (!res) {setResult({ ok: false, outDir, included: 0, warnings: [], errors: [t('build.noProjectOpen')] });@@ -190,6 +219,7 @@ export function BuildDialog() {const footer = (<>+ {phase === 'idle' && <span className="build__footsum">{t('build.footSummary', { count: shippedScenes, platform: def.label })}</span>}<Button onClick={close} disabled={running}>{phase === 'done' ? t('ui.close') : t('ui.cancel')}</Button>@@ -208,7 +238,7 @@ export function BuildDialog() {);return (- <Modal title={t('build.title')} onClose={running ? () => {} : close} footer={footer} width={500}>+ <Modal title={t('build.title')} onClose={running ? () => {} : close} footer={footer} width={520}><div className="build"><div className="build__label">{t('build.platform')}</div><div className="build__platforms">@@ -222,119 +252,136 @@ export function BuildDialog() {title={p.ready ? p.label : t('build.comingSoon')}onClick={() => pickPlatform(p)}>- {p.label}- {!p.ready && <span className="soon">{t('build.soon')}</span>}+ {p.icon}+ <span className="build__plat-name">{p.label}</span></button>))}</div><div className="build__blurb">{def.blurb}</div>- <div className="build__row">- <span className="build__label">{t('build.configuration')}</span>- <Segmented- ariaLabel={t('build.configuration')}- value={config}- options={[- { value: 'development', label: t('build.development') },- { value: 'shipping', label: t('build.shipping') },- ]}- onChange={setConfig}- />- </div>-- <div className="build__row">- <span className="build__label">{t('build.output')}</span>- <div className="build__out">- <input- value={outDir}- spellCheck={false}- onChange={(e) => setOutDir(e.target.value)}- />- <Button onClick={() => void browse()}>- <FolderOpen size={13} /> {t('build.browse')}- </Button>- </div>- </div>-- <label className="build__opt">- <input type="checkbox" checked={openFolder} onChange={(e) => setOpenFolder(e.target.checked)} />- {t('build.openFolderWhenDone')}- </label>- {def.sourceMaps && (- <label className="build__opt">- <input type="checkbox" checked={sourceMaps} onChange={(e) => setSourceMaps(e.target.checked)} />- {t('build.includeSourceMaps')}- </label>- )}- <label className="build__opt">- <input type="checkbox" checked={compressTextures} onChange={(e) => setCompressTextures(e.target.checked)} />- {t('build.compressTextures')}- </label>- <label className="build__opt">- <input type="checkbox" checked={atlasTextures} onChange={(e) => setAtlasTextures(e.target.checked)} />- {t('build.atlasTextures')}- </label>- <label className="bd-check" title={t('build.compressAudioTip')}>- <input type="checkbox" checked={compressAudio} onChange={(e) => setCompressAudio(e.target.checked)} />- {t('build.compressAudio')}- </label>-- <div className="build__row">- <span className="build__label" title={t('build.cdnRootTip')}>{t('build.cdnRoot')}</span>- <input- value={cdnRoot}- spellCheck={false}- placeholder="https://cdn…"- title={t('build.cdnRootTip')}- onChange={(e) => setCdnRoot(e.target.value)}- onBlur={() => void ProjectStore.setActiveProfileRemoteRoot(cdnRoot.trim())}- />- </div>-{def.prereq && (<div className="build__prereq"><Info size={13} /> <span className="selectable">{def.prereq}</span></div>)}+ <Group title={t('build.secBuild')}>+ <div className="build__row">+ <span className="build__label">{t('build.configuration')}</span>+ <Segmented+ ariaLabel={t('build.configuration')}+ value={config}+ options={[+ { value: 'development', label: t('build.development') },+ { value: 'shipping', label: t('build.shipping') },+ ]}+ onChange={setConfig}+ />+ </div>+ <div className="build__row">+ <span className="build__label" title={t('build.assetCompressionTip')}>{t('build.assetCompression')}</span>+ <Segmented+ ariaLabel={t('build.assetCompression')}+ value={assetCompression}+ options={[+ { value: 'auto', label: t('build.assetAuto') },+ { value: 'skip', label: t('build.assetSkip') },+ ]}+ onChange={setAssetCompression}+ />+ </div>+ <div className="build__hint">+ <Info size={11} /> {t('build.compressionHint')}+ </div>+ <div className="build__row">+ <span className="build__label">{t('build.output')}</span>+ <div className="build__out">+ <input+ value={outDir}+ spellCheck={false}+ onChange={(e) => setOutDir(e.target.value)}+ />+ <Button onClick={() => void browse()}>+ <FolderOpen size={13} /> {t('build.browse')}+ </Button>+ </div>+ </div>+ </Group>+{/* Scenes in build — the same single source the exporters read(defaultScene + packaging.excludeScenes), edited in place. Thestartup scene is pinned: it boots the game, so it always ships. */}- <div className="build__scenes">- <div className="build__scenes-head">{t('build.scenesHead')}</div>- {sceneList.map((s) => {- const isEntry = s.path === project?.defaultScene;- const ships = isEntry || !excludedScenes.has(s.path);- return (- <div key={s.path} className={`build__scene${ships ? '' : ' is-excluded'}`}>- <button- type="button"- className={`build__scene-start${isEntry ? ' is-on' : ''}`}- title={isEntry ? t('build.startupScene') : t('build.setStartupScene')}- aria-label={isEntry ? t('build.startupScene') : t('build.setStartupSceneNamed', { name: s.name })}- disabled={running || isEntry}- onClick={() => void ProjectStore.setDefaultScene(s.path)}- >- <Play size={11} strokeWidth={2.5} />- </button>- <label className="build__scene-row">- <input- type="checkbox"- checked={ships}+ <Group title={t('build.scenesHead')} count={String(sceneList.length)}>+ <div className="build__scenes-list">+ {sceneList.map((s) => {+ const isEntry = s.path === project?.defaultScene;+ const ships = isEntry || !excludedScenes.has(s.path);+ return (+ <div key={s.path} className={`build__scene${ships ? '' : ' is-excluded'}`}>+ <button+ type="button"+ className={`build__scene-start${isEntry ? ' is-on' : ''}`}+ title={isEntry ? t('build.startupScene') : t('build.setStartupScene')}+ aria-label={isEntry ? t('build.startupScene') : t('build.setStartupSceneNamed', { name: s.name })}disabled={running || isEntry}- onChange={(e) => void ProjectStore.setSceneExcluded(s.path, !e.target.checked)}- />- <span className="build__scene-name">{s.name.replace(/\.esscene$/i, '')}</span>- <span className="build__scene-path mono">{s.path}</span>- </label>- </div>- );- })}- {sceneList.length === 0 && <div className="build__scenes-empty">{t('build.noScenes')}</div>}- {platform === 'playable' && sceneList.length > 1 && (- <div className="build__scenes-note">{t('build.playableSingleScene')}</div>- )}- </div>+ onClick={() => void ProjectStore.setDefaultScene(s.path)}+ >+ <Play size={11} strokeWidth={2.5} />+ </button>+ <label className="build__scene-row">+ <input+ type="checkbox"+ checked={ships}+ disabled={running || isEntry}+ onChange={(e) => void ProjectStore.setSceneExcluded(s.path, !e.target.checked)}+ />+ <span className="build__scene-name">{s.name.replace(/\.esscene$/i, '')}</span>+ <span className="build__scene-path mono">{s.path}</span>+ </label>+ </div>+ );+ })}+ {sceneList.length === 0 && <div className="build__scenes-empty">{t('build.noScenes')}</div>}+ {platform === 'playable' && sceneList.length > 1 && (+ <div className="build__scenes-note">{t('build.playableSingleScene')}</div>+ )}+ </div>+ </Group>++ <button+ type="button"+ className={`build__adv${advOpen ? ' open' : ''}`}+ aria-expanded={advOpen}+ onClick={() => setAdvOpen((o) => !o)}+ >+ <span className="chev"><ChevronRight size={13} /></span>+ {t('build.advanced')}+ </button>+ {advOpen && (+ <div className="build__adv-body">+ <div className="build__row">+ <span className="build__label" title={t('build.cdnRootTip')}>{t('build.cdnRoot')}</span>+ <input+ value={cdnRoot}+ spellCheck={false}+ placeholder="https://cdn…"+ title={t('build.cdnRootTip')}+ onChange={(e) => setCdnRoot(e.target.value)}+ onBlur={() => void ProjectStore.setActiveProfileRemoteRoot(cdnRoot.trim())}+ />+ </div>+ {def.sourceMaps && (+ <label className="build__opt">+ <input type="checkbox" checked={sourceMaps} onChange={(e) => setSourceMaps(e.target.checked)} />+ {t('build.includeSourceMaps')}+ </label>+ )}+ <label className="build__opt">+ <input type="checkbox" checked={openFolder} onChange={(e) => setOpenFolder(e.target.checked)} />+ {t('build.openFolderWhenDone')}+ </label>+ </div>+ )}{phase !== 'idle' && (<div className={`build__status ${phase}`}>diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex 867cf8688..72b7e9fff 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -61,13 +61,22 @@ export const projectMessages = defineMessages({'build.browse': { en: 'Browse', zh: '浏览' },'build.openFolderWhenDone': { en: 'Open output folder when done', zh: '完成后打开输出文件夹' },'build.includeSourceMaps': { en: 'Include source maps', zh: '包含源码映射' },- 'build.compressTextures': { en: 'Compress textures (PNG → KTX2)', zh: '压缩纹理(PNG → KTX2)' },- 'build.compressAudio': { en: 'Compress audio (WAV → MP3)', zh: '压缩音频(WAV → MP3)' },- 'build.compressAudioTip': {- en: 'Re-encode WAV sources to MP3 at cook. Per-asset Import Settings can opt a clip out (seamless loops) or pick a bitrate.',- zh: '打包时将 WAV 源重编码为 MP3。可在资产的导入设置中单独关闭(无缝循环素材)或选择码率。',++ // — Section headers + asset-optimization mode (per-asset compression lives in+ // the Inspector's Import Settings; the build only picks honor-vs-skip) —+ 'build.secBuild': { en: 'Build', zh: '构建' },+ 'build.advanced': { en: 'Advanced', zh: '高级' },+ 'build.assetCompression': { en: 'Asset compression', zh: '资源压缩' },+ 'build.assetAuto': { en: 'By import settings', zh: '按导入设置' },+ 'build.assetSkip': { en: 'Skip all', zh: '全部跳过' },+ 'build.assetCompressionTip': {+ en: 'By import settings — each texture and audio clip compresses per its Inspector Import Settings (KTX2 · Max Size · WAV→MP3) and .atlas folders pack. Skip all — ship everything raw for fast iteration.',+ zh: '按导入设置——纹理与音频各自按检视面板的导入设置压缩(KTX2 · Max Size · WAV→MP3),.atlas 文件夹打包。全部跳过——一律原样输出,便于快速迭代。',+ },+ 'build.compressionHint': {+ en: 'Per-asset compression lives in each asset’s Import Settings.',+ zh: '每个资源的压缩设置在其「导入设置」里。',},- 'build.atlasTextures': { en: 'Pack .atlas folders into atlases', zh: '将 .atlas 文件夹打包为图集' },// — Scenes in build —'build.scenesHead': { en: 'Scenes in build', zh: '构建包含的场景' },@@ -91,6 +100,7 @@ export const projectMessages = defineMessages({},// — Run / progress / result —+ 'build.footSummary': { en: '{count} scene(s) · {platform}', zh: '{count} 个场景 · {platform}' },'build.package': { en: 'Package', zh: '打包' },'build.packaging': { en: 'Packaging…', zh: '打包中…' },'build.packagingPlatform': { en: 'Packaging the {platform} build…', zh: '正在打包 {platform} 构建…' },diff --git a/desktop/src/project/assetImporter.ts b/desktop/src/project/assetImporter.tsindex c5cb4c6d9..4c3dea2dc 100644--- a/desktop/src/project/assetImporter.ts+++ b/desktop/src/project/assetImporter.ts@@ -21,7 +21,20 @@ const TEXTURE: ImporterFieldSpec[] = [{key: 'maxSize', label: 'Max Size', type: 'enum', default: 2048, category: 'Texture',options: powerOfTwo.map((n) => ({ label: String(n), value: n })),- tooltip: 'Downscale cap applied when the asset is imported/cooked (power of two).',+ tooltip: 'Downscale cap applied at cook (power of two). A source larger than this on '+ + 'its longest side is box-filtered down; smaller sources are untouched.',+ },+ {+ key: 'compress', label: 'Compress', type: 'bool', default: true, category: 'Texture',+ tooltip: 'GPU-compress this texture to KTX2 (Basis Universal) at cook — it stays '+ + 'compressed in VRAM and transcodes per device. Turn OFF to ship the raw image '+ + '(crisp UI, smooth gradients). Only applies when the build compresses assets.',+ },+ {+ key: 'compressFormat', label: 'Compress Format', type: 'select', default: 'uastc',+ category: 'Texture', advanced: true, selectOptions: ['uastc', 'etc1s'],+ tooltip: 'UASTC — high quality, larger. ETC1S — much smaller, lower quality '+ + '(good for photographic / low-frequency art). Only used when Compress is on.',},{key: 'filterMode', label: 'Filter', type: 'select', default: 'linear', category: 'Texture',@@ -163,6 +176,25 @@ export function buildImporterComponent(type: string, importer: Record<string, unreturn { name: 'Import Settings', label: 'Import Settings', fields };}+/** Cook-facing texture settings (compression + downscale), tolerant of hand-edited+ * `.meta` blocks. Mirrors {@link readAudioImportSettings} — the cook reads this+ * per asset so each texture decides its own KTX2 format / opt-out / size cap,+ * the way audio clips already do. Defaults match a fresh `.meta`. */+export function readTextureCookSettings(importer: Record<string, unknown> | undefined): {+ compress: boolean; format: 'uastc' | 'etc1s'; maxSize: number; srgb: boolean;+} {+ const compress = importer?.compress;+ const format = importer?.compressFormat;+ const maxSize = importer?.maxSize;+ const srgb = importer?.sRGB;+ return {+ compress: typeof compress === 'boolean' ? compress : true,+ format: format === 'etc1s' ? 'etc1s' : 'uastc',+ maxSize: typeof maxSize === 'number' && maxSize > 0 ? maxSize : 2048,+ srgb: typeof srgb === 'boolean' ? srgb : true,+ };+}+/** A texture's sampler settings, in the string shape the engine's TextureLoader* and the runtime importer-resolver consume (filterMode/wrapMode → filter/wrap).* Undefined when the `.meta` carries neither ⇒ loader defaults. */diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.tsindex b94ee0af8..17972ea6b 100644--- a/desktop/src/project/format.ts+++ b/desktop/src/project/format.ts@@ -136,11 +136,21 @@ export interface ProjectPackaging {* derived from the design resolution's aspect (see {@link resolveOrientation}) —* so a landscape design ships landscape with zero config. */orientation?: ScreenOrientation;- /** Cook PNGs to GPU-ready KTX2 (Basis Universal). */+ /**+ * How the build treats asset optimization. `'auto'` (default) honors each+ * asset's per-asset Import Settings — textures compress to KTX2 / downscale to+ * their Max Size, WAV → MP3, `<name>.atlas/` folders pack — so what ships is+ * authored on the asset, not toggled here. `'skip'` ships everything raw for+ * fast iteration (Unity's "Asset Import Overrides"). The build derives the cook+ * flags below from this; the per-ASSET decisions live in the Inspector.+ */+ assetCompression?: 'auto' | 'skip';+ /** @deprecated Superseded by {@link assetCompression}. Kept so older projects+ * still parse; the dialog no longer writes these. */compressTextures?: boolean;- /** Cook WAV sources to MP3 (per-asset Import Settings can override). */+ /** @deprecated see {@link assetCompression}. */compressAudio?: boolean;- /** Pack `<name>.atlas/` folders into atlas pages at cook time. */+ /** @deprecated see {@link assetCompression}. */atlasTextures?: boolean;/** Project-relative scene paths NOT shipped as switchable scenes (dev/test* scenes). Everything else under the scenes dir exports; the startup scenediff --git a/desktop/src/theme/menus.css b/desktop/src/theme/menus.cssindex e1d20a128..b73effc70 100644--- a/desktop/src/theme/menus.css+++ b/desktop/src/theme/menus.css@@ -210,7 +210,9 @@.build { display: flex; flex-direction: column; gap: 12px; }.build__label { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; color: var(--text-mute); }.build__platforms { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }-.build__plat { position: relative; height: 54px; display: grid; place-items: center; font-size: var(--fs-sm); color: var(--text-dim); background: var(--srf-3); border: 1px solid var(--border-line); border-radius: var(--r-md); transition: color var(--t-fast), background var(--t-fast), border-color var(--t-fast); }+.build__plat { position: relative; height: 58px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; font-size: var(--fs-xs); color: var(--text-dim); background: var(--srf-3); border: 1px solid var(--border-line); border-radius: var(--r-md); transition: color var(--t-fast), background var(--t-fast), border-color var(--t-fast); }+.build__plat svg { opacity: 0.92; }+.build__plat-name { line-height: 1; }.build__plat:not(:disabled):hover { color: var(--text); border-color: var(--text-mute); }.build__plat.on { color: var(--on-accent); background: var(--acc); border-color: var(--acc); }.build__plat:disabled { opacity: 0.5; }@@ -225,6 +227,7 @@.build__summary strong { color: var(--text-dim); font-family: var(--mono); }/* Scenes in build — the exporter's scene set (startup pinned, exclusions live). */.build__scenes { display: flex; flex-direction: column; gap: 2px; max-height: 148px; overflow-y: auto; padding: 6px 8px; background: var(--srf-3); border: 1px solid var(--border-line); border-radius: var(--r-sm); }+.build__scenes-list { display: flex; flex-direction: column; gap: 2px; max-height: 150px; overflow-y: auto; margin: -2px 0; }.build__scenes-head { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; color: var(--text-mute); padding-bottom: 3px; }.build__scene { display: flex; align-items: center; gap: 6px; height: 24px; }.build__scene-start { display: grid; place-items: center; width: 20px; height: 20px; border-radius: var(--r-xs); color: transparent; background: none; }@@ -254,3 +257,25 @@.build__loglabel { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; color: var(--text-mute); }.build__copy { display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 18px; color: var(--text-mute); background: none; border: none; border-radius: var(--r-xs); cursor: pointer; transition: color var(--t-fast), background var(--t-fast); }.build__copy:hover { color: var(--text); background: var(--srf-4); }++/* Grouped sections (target / build / scenes) — give the dialog visual hierarchy+ instead of one flat column. */+.build__group { background: var(--srf-3); border: 1px solid var(--border-line); border-radius: var(--r-md); overflow: hidden; }+.build__group-head { display: flex; align-items: center; gap: 8px; padding: 7px 11px; border-bottom: 1px solid var(--line-soft); }+.build__group-title { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; color: var(--text-dim); }+.build__group-count { margin-left: auto; font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-mute); }+.build__group-body { padding: 10px 11px; display: flex; flex-direction: column; gap: 10px; }+.build__group-body .build__row { gap: 10px; }+.build__group-body .build__label { width: 74px; }+.build__tip { font-size: var(--fs-2xs); color: var(--text-mute); line-height: 1.45; margin-top: -3px; }++/* Progressive disclosure: advanced (hot-update CDN / source maps / open folder). */+.build__adv { display: flex; align-items: center; gap: 6px; font-size: var(--fs-xs); color: var(--text-dim); background: none; border: none; cursor: pointer; padding: 2px 0; }+.build__adv:hover { color: var(--text); }+.build__adv .chev { display: inline-flex; transition: transform var(--t-fast); color: var(--text-mute); }+.build__adv.open .chev { transform: rotate(90deg); }+.build__adv-body { display: flex; flex-direction: column; gap: 10px; padding: 4px 0 2px 2px; }++/* "compression lives in Import Settings" pointer + footer scene/target summary. */+.build__hint { display: inline-flex; align-items: center; gap: 5px; font-size: var(--fs-2xs); color: var(--text-mute); }+.build__footsum { margin-right: auto; align-self: center; font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-mute); }diff --git a/desktop/tests/asset-importer.test.ts b/desktop/tests/asset-importer.test.tsindex 7143106a9..d90f7a4f1 100644--- a/desktop/tests/asset-importer.test.ts+++ b/desktop/tests/asset-importer.test.ts@@ -20,6 +20,8 @@ describe('importerDefaults (import-time .meta)', () => {it('reproduces the texture defaults (incl. nested 9-slice)', () => {expect(importerDefaults('texture')).toEqual({maxSize: 2048,+ compress: true,+ compressFormat: 'uastc',filterMode: 'linear',wrapMode: 'repeat',premultiplyAlpha: false,diff --git a/desktop/tests/atlas-packer.test.ts b/desktop/tests/atlas-packer.test.tsindex 6066b51f1..e8da7d8cf 100644--- a/desktop/tests/atlas-packer.test.ts+++ b/desktop/tests/atlas-packer.test.ts@@ -4,7 +4,7 @@* @file Atlas packer — deterministic shelf packing + page composition.*/import { describe, it, expect } from 'vitest';-import { packAtlas, decodePngImage, encodePagePng, type AtlasInputImage } from '../electron/atlasPacker';+import { packAtlas, decodePngImage, encodePagePng, encodeRgbaPng, downscaleRgba, type AtlasInputImage } from '../electron/atlasPacker';function solid(key: string, width: number, height: number, rgba: [number, number, number, number]): AtlasInputImage {const data = new Uint8Array(width * height * 4);@@ -96,3 +96,39 @@ describe('packAtlas', () => {expect([...back.rgba]).toEqual([...pages[0].rgba]);});});++describe('downscaleRgba (Max Size cook cap)', () => {+ it('returns the input untouched when within the cap', () => {+ const img = solid('a', 64, 64, [1, 2, 3, 255]);+ expect(downscaleRgba(img, 2048)).toBe(img); // same reference — no work+ expect(downscaleRgba(img, 64)).toBe(img); // exactly at cap+ });++ it('shrinks so the longest side ≤ cap, keeping aspect + solid color', () => {+ const out = downscaleRgba(solid('a', 128, 32, [200, 100, 50, 255]), 32);+ expect(out.width).toBe(32); // 128 → 32+ expect(out.height).toBe(8); // 32 → 8 (aspect preserved)+ expect(out.rgba).toHaveLength(32 * 8 * 4);+ // A solid image downscales to the same solid color everywhere.+ for (let i = 0; i < out.width * out.height; i++) {+ expect([...out.rgba.subarray(i * 4, i * 4 + 4)]).toEqual([200, 100, 50, 255]);+ }+ });++ it('averages color in premultiplied space (transparent pixels do not bleed)', () => {+ // 2×1: opaque red + fully-transparent — the shrunk pixel keeps red's hue,+ // with alpha averaged to half. (Naive averaging would darken toward black.)+ const img: AtlasInputImage = { key: 'k', width: 2, height: 1, rgba: new Uint8Array([255, 0, 0, 255, 0, 0, 0, 0]) };+ const out = downscaleRgba(img, 1);+ expect(out.width).toBe(1);+ expect(out.height).toBe(1);+ expect([...out.rgba]).toEqual([255, 0, 0, 128]);+ });++ it('encodeRgbaPng round-trips raw pixels', () => {+ const rgba = new Uint8Array([9, 8, 7, 255, 6, 5, 4, 255]);+ const back = decodePngImage('p', encodeRgbaPng(2, 1, rgba));+ expect(back.width).toBe(2);+ expect([...back.rgba]).toEqual([...rgba]);+ });+});diff --git a/desktop/tests/cook-assets.test.ts b/desktop/tests/cook-assets.test.tsindex 1d12ef16e..02cfd0336 100644--- a/desktop/tests/cook-assets.test.ts+++ b/desktop/tests/cook-assets.test.ts@@ -10,6 +10,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSyncimport { tmpdir } from 'node:os';import path from 'node:path';import { cookAssets } from '../electron/cookAssets';+import { decodePngImage } from '../electron/atlasPacker';import { contentHashHex } from '../../sdk/src/asset/contentHash';interface AssetManifest {@@ -221,6 +222,61 @@ describe('cookAssets (A4)', () => {}}, 30_000);+ it('honors per-texture compress=false: ships the raw PNG even when the build compresses', async () => {+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-texopt-'));+ try {+ const TEX = '77777777-7777-4777-8777-777777777771';+ const SC = '88888888-8888-4888-8888-888888888881';+ const png = readFileSync(path.resolve(__dirname, '../../examples/hello-world/assets/textures/logo.png'));+ const abs = path.join(r, 't/logo.png');+ mkdirSync(path.dirname(abs), { recursive: true });+ writeFileSync(abs, png);+ // Per-asset opt-out — the same switch audio clips already have.+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid: TEX, version: '2.0', type: 'texture', importer: { compress: false } }));+ const sc = path.join(r, 's/main.esscene');+ mkdirSync(path.dirname(sc), { recursive: true });+ writeFileSync(sc, JSON.stringify({ version: '1.0', name: 's', entities: [{ id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }));+ writeFileSync(`${sc}.meta`, JSON.stringify({ uuid: SC, version: '2.0', type: 'scene', importer: {} }));++ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out', compressTextures: true });+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;+ const tex = m.entries.find((e) => e.uuid === TEX)!;+ expect(tex.path).toMatch(/\.png$/); // NOT .ktx2 — the asset opted out+ expect(tex.compressedFormats).toBeUndefined();+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ }, 30_000);++ it('downscales a texture to its Max Size at cook (longest side capped)', async () => {+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-maxsize-'));+ try {+ const TEX = '77777777-7777-4777-8777-777777777772';+ const SC = '88888888-8888-4888-8888-888888888882';+ const png = readFileSync(path.resolve(__dirname, '../../examples/hello-world/assets/textures/logo.png'));+ const src = decodePngImage('src', png);+ expect(Math.max(src.width, src.height)).toBeGreaterThan(64); // fixture is larger than the cap+ const abs = path.join(r, 't/logo.png');+ mkdirSync(path.dirname(abs), { recursive: true });+ writeFileSync(abs, png);+ // maxSize + compress:false → ships a SHRUNK PNG we can measure directly.+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid: TEX, version: '2.0', type: 'texture', importer: { compress: false, maxSize: 64 } }));+ const sc = path.join(r, 's/main.esscene');+ mkdirSync(path.dirname(sc), { recursive: true });+ writeFileSync(sc, JSON.stringify({ version: '1.0', name: 's', entities: [{ id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }));+ writeFileSync(`${sc}.meta`, JSON.stringify({ uuid: SC, version: '2.0', type: 'scene', importer: {} }));++ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out', compressTextures: true });+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;+ const tex = m.entries.find((e) => e.uuid === TEX)!;+ const shrunk = decodePngImage('out', readFileSync(path.join(res.outDir, tex.path)));+ expect(Math.max(shrunk.width, shrunk.height)).toBeLessThanOrEqual(64);+ expect(Math.max(shrunk.width, shrunk.height)).toBeGreaterThan(32); // scaled to fit, not over-shrunk+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ }, 30_000);+it('follows PATH refs: scene → material (project path) → shader + texture (dir-relative)', async () => {const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-pathref-'));try {