Skip to content

Commit 72efa7f

Browse files
committed
fix(export): keep downloads available for incomplete characters
1 parent 2076124 commit 72efa7f

19 files changed

Lines changed: 890 additions & 210 deletions

‎app/src/lib/dress/project.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,13 +108,14 @@ export async function openFixture(
108108

109109
export async function openSource(
110110
id: string,
111-
signal?: AbortSignal
112-
): Promise<{ project: Project; current?: Outfit }> {
111+
signal?: AbortSignal,
112+
options?: Parameters<typeof loadProject>[2]
113+
): Promise<{ project: Project; current?: Outfit; missingImages?: number }> {
113114
signal?.throwIfAborted();
114115
if (id.startsWith('fixture:')) return openFixture(id, signal);
115-
const { rec, project } = await loadProject(id, signal); // B4's loader (store/project.ts)
116+
const { rec, project, missingImages } = await loadProject(id, signal, options);
116117
signal?.throwIfAborted();
117-
return { project, current: (rec as ProjectRecord).dress?.current };
118+
return { project, current: (rec as ProjectRecord).dress?.current, missingImages };
118119
}
119120

120121
export const dressOf = (m: Manifest, current?: Outfit): DressState => ({

‎app/src/lib/export/build.ts‎

Lines changed: 139 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,19 @@
33
import { exportZip } from './export.ts';
44
import { storeVariants, variantOf } from '../dress/dress.ts';
55
import { itemHashes } from '../equipment/copy.ts';
6+
import { SLOTS } from '../items/slots.ts';
67
import { retainMoves } from '../rig/moves.ts';
7-
import { DEFAULT_MOVE } from '../rig/rig.ts';
8+
import { cellHash, DEFAULT_MOVE } from '../rig/rig.ts';
9+
import { validEquipment } from '../runtime/paperdoll.js';
10+
import { leaveEmptyFrames, recoverArtwork } from './recovery.ts';
811
import { applyExportSettings, type ExportSettings } from '../store/export-settings.ts';
9-
import type { ImportedCharacter } from '../store/import.ts';
12+
import {
13+
fitsEditableImage,
14+
hashPattern,
15+
hasVisibleBase,
16+
manifestShape,
17+
type ImportedCharacter
18+
} from '../store/import.ts';
1019
import type { Engine, Item, Manifest, Preset, Project } from '../store/manifest.ts';
1120

1221
export type Look = Pick<Preset, 'items' | 'variants'> & Partial<Pick<Preset, 'id' | 'name'>>;
@@ -40,8 +49,7 @@ export function outfitProject(
4049
return { ...selected, look: { ...saved, ...selected.look } };
4150
}
4251

43-
/** The export in one format: the look given (the current outfit) first, then the saved outfits. */
44-
export function buildExport(
52+
async function requestedExport(
4553
p: Project,
4654
o: {
4755
engine: Engine;
@@ -62,14 +70,139 @@ export function buildExport(
6270
...p.manifest.presets.filter((x) => x.id !== 'current' && x.id !== current.id)
6371
];
6472
const manifest = structuredClone({ ...p.manifest, presets }) as Manifest;
73+
const warnings = new Set<string>();
74+
for (const preset of manifest.presets) {
75+
const omitted: string[] = [];
76+
for (const [slot, item] of Object.entries(preset.items)) {
77+
if (slot === 'body' || validEquipment(manifest, slot, item)) continue;
78+
delete preset.items[slot];
79+
if (item != null)
80+
omitted.push(
81+
manifest.slots.find((entry) => entry.id === slot)?.label ??
82+
SLOTS.find((entry) => entry.id === slot)?.label ??
83+
slot.replace(/[_-]/g, ' ')
84+
);
85+
}
86+
if (omitted.length)
87+
warnings.add(`${preset.name}: Missing equipment was left out (${omitted.join(', ')}).`);
88+
}
6589
applyExportSettings(manifest, o.settings);
6690
storeVariants(manifest, ...presets.map((x) => x.variants));
91+
for (const warning of leaveEmptyFrames({ manifest, images: p.images })) warnings.add(warning);
92+
const blocked = (problem: string, errors: string[] = []) => ({
93+
zip: null,
94+
entries: [],
95+
warnings: [...warnings],
96+
errors,
97+
problem
98+
});
99+
try {
100+
manifestShape(manifest);
101+
} catch (error) {
102+
return blocked('This character does not fit the export limits.', [String(error)]);
103+
}
104+
if (!hasVisibleBase({ manifest, images: p.images }))
105+
return blocked('The body has no visible frames.');
106+
const images: Project['images'] = new Map();
107+
const missing = new Set<string>();
108+
async function include(hash: string) {
109+
if (images.has(hash)) return true;
110+
if (missing.has(hash)) return false;
111+
const image = p.images.get(hash);
112+
if (
113+
!image ||
114+
!hashPattern.test(hash) ||
115+
!fitsEditableImage(image) ||
116+
(await cellHash(image)) !== hash
117+
) {
118+
missing.add(hash);
119+
return false;
120+
}
121+
images.set(hash, image);
122+
return true;
123+
}
124+
for (const view of Object.keys(manifest.rig.rest ?? {}) as (keyof NonNullable<
125+
Manifest['rig']['rest']
126+
>)[]) {
127+
const rest = manifest.rig.rest?.[view];
128+
if (rest && !(await include(rest.image))) {
129+
delete manifest.rig.rest![view];
130+
warnings.add('Missing body reference images were left out of the editable copy.');
131+
}
132+
}
133+
for (const item of manifest.items) {
134+
for (const facing of Object.keys(item.dressed ?? {}) as (keyof NonNullable<
135+
Item['dressed']
136+
>)[]) {
137+
const hash = item.dressed?.[facing];
138+
if (hash && !(await include(hash))) {
139+
delete item.dressed![facing];
140+
warnings.add(`${item.name}: Missing reference images were left out of the editable copy.`);
141+
}
142+
}
143+
for (const hash of itemHashes(item))
144+
if (!(await include(hash))) return blocked('Some saved images are damaged.');
145+
}
67146
return exportZip(
68-
{ manifest, images: p.images },
69-
{ engines: [o.engine], baked: o.baked, projectData: o.projectData }
147+
{ manifest, images },
148+
{
149+
engines: [o.engine],
150+
baked: o.baked,
151+
projectData: o.projectData
152+
},
153+
[...warnings]
70154
);
71155
}
72156

157+
export async function buildExport(
158+
project: Project,
159+
options: Parameters<typeof requestedExport>[1]
160+
) {
161+
let problem = 'Could not build this export.';
162+
let errors: string[] = [];
163+
let retryable = false;
164+
try {
165+
const result = await requestedExport(project, options);
166+
if (result.zip) return { ...result, kind: 'requested' as const };
167+
problem = result.problem ?? problem;
168+
errors = result.errors;
169+
} catch (error) {
170+
console.error('Could not build export', error);
171+
retryable = true;
172+
}
173+
try {
174+
const recovery = await recoverArtwork(project, problem);
175+
if (recovery)
176+
return {
177+
kind: 'recovery' as const,
178+
...recovery,
179+
problem,
180+
errors,
181+
warnings: recovery.skipped ? ['Some source images could not be included.'] : []
182+
};
183+
return {
184+
kind: 'failed' as const,
185+
zip: null,
186+
entries: [],
187+
problem,
188+
errors,
189+
warnings: [],
190+
retryable
191+
};
192+
} catch (error) {
193+
console.error('Could not build recovery ZIP', error);
194+
return {
195+
kind: 'failed' as const,
196+
zip: null,
197+
entries: [],
198+
problem: 'The artwork ZIP could not be prepared.',
199+
errors,
200+
warnings: [],
201+
retryable: true
202+
};
203+
}
204+
}
205+
73206
const covers = (it: Item) =>
74207
Array.isArray(it.underAll) ? it.underAll : it.under ? [it.under] : [];
75208

‎app/src/lib/export/export.ts‎

Lines changed: 64 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import type { Img } from '../image/png.ts';
33
import { encodePngBytes } from '../image/pngraw.ts';
44
import type { Engine, Project } from '../store/manifest.ts';
5-
import { zip, type ZipEntry } from '../store/zip.ts';
5+
import { fitsEditableZip, MAX_ZIP_BYTES, zip, type ZipEntry } from '../store/zip.ts';
66
import {
77
bodyCutVariantCount,
88
bodyCutVariantLimit,
@@ -17,7 +17,7 @@ import { phaserFiles } from './phaser.ts';
1717
import { unityFiles } from './unity.ts';
1818
import { gdevelopFiles } from './gdevelop.ts';
1919
import { rpgMakerFiles } from './rpgmaker.ts';
20-
import { projectEntries, type ImportedCharacter } from '../store/import.ts';
20+
import { checkArchivePixels, projectEntries, type ImportedCharacter } from '../store/import.ts';
2121
import { reservedPathSegment } from './paths.ts';
2222

2323
export interface ExportOptions {
@@ -31,6 +31,7 @@ export interface ExportResult {
3131
entries: ZipEntry[];
3232
warnings: string[];
3333
errors: string[];
34+
problem?: string;
3435
}
3536

3637
export async function exportFiles(src: Project, o: ExportOptions): Promise<ExportResult> {
@@ -70,7 +71,8 @@ export async function exportFiles(src: Project, o: ExportOptions): Promise<Expor
7071
return {
7172
entries: [],
7273
warnings: [],
73-
errors: ['The base body is stale; freeze a matching base before exporting.']
74+
errors: ['The base body is stale; freeze a matching base before exporting.'],
75+
problem: 'The body frames no longer match this character.'
7476
};
7577
const p = await withTuckVariants(src); // B14: hair under a helmet ships as a baked "<hair>~<helmet>" item; engines swap to it
7678
const errors = validate(p);
@@ -89,7 +91,8 @@ export async function exportFiles(src: Project, o: ExportOptions): Promise<Expor
8991
return {
9092
entries: [],
9193
warnings: [],
92-
errors: ['The base body has no visible animation frames to export.']
94+
errors: ['The base body has no visible animation frames to export.'],
95+
problem: 'The body has no visible frames.'
9396
};
9497
}
9598
const { manifest: m, warnings } = exportManifest(p, o);
@@ -120,7 +123,12 @@ export async function exportFiles(src: Project, o: ExportOptions): Promise<Expor
120123
files.push(...godotFiles(m));
121124
} catch (error) {
122125
if (!(error instanceof Error) || !error.message.startsWith('Godot: ')) throw error;
123-
return { entries: [], warnings, errors: [error.message] };
126+
return {
127+
entries: [],
128+
warnings,
129+
errors: [error.message],
130+
problem: 'Godot could not use these sprite sheets.'
131+
};
124132
}
125133
}
126134
if (o.engines.includes('phaser')) files.push(...phaserFiles(m));
@@ -130,7 +138,12 @@ export async function exportFiles(src: Project, o: ExportOptions): Promise<Expor
130138
files.push(...gdevelopFiles(m, sheets));
131139
} catch (error) {
132140
if (!(error instanceof Error) || !error.message.startsWith('GDevelop: ')) throw error;
133-
return { entries: [], warnings, errors: [error.message] };
141+
return {
142+
entries: [],
143+
warnings,
144+
errors: [error.message],
145+
problem: 'GDevelop could not use these sprite sheets.'
146+
};
134147
}
135148
}
136149
if (rpg) {
@@ -140,15 +153,25 @@ export async function exportFiles(src: Project, o: ExportOptions): Promise<Expor
140153
warnings.push(...r.warnings);
141154
} catch (error) {
142155
if (!(error instanceof Error) || !error.message.startsWith('RPG Maker: ')) throw error;
143-
return { entries: [], warnings, errors: [error.message] };
156+
return {
157+
entries: [],
158+
warnings,
159+
errors: [error.message],
160+
problem: 'RPG Maker needs front, side and back views.'
161+
};
144162
}
145163
}
146164
if (o.engines.includes('aseprite')) {
147165
try {
148166
files.push(...(await asepriteFiles(m, sheets)));
149167
} catch (error) {
150168
if (!(error instanceof Error) || !error.message.startsWith('Aseprite ')) throw error;
151-
return { entries: [], warnings, errors: [error.message] };
169+
return {
170+
entries: [],
171+
warnings,
172+
errors: [error.message],
173+
problem: 'The animation does not fit the Aseprite format.'
174+
};
152175
}
153176
}
154177
const projectFiles = await projectEntries(src, o.projectData);
@@ -165,7 +188,8 @@ export async function exportFiles(src: Project, o: ExportOptions): Promise<Expor
165188
if (names.has(name)) errors.push(`Duplicate export path: ${name}`);
166189
names.add(name);
167190
}
168-
if (errors.length) return { entries: [], warnings, errors };
191+
if (errors.length)
192+
return { entries: [], warnings, errors, problem: 'Some file names cannot be packaged safely.' };
169193
const enc = new TextEncoder();
170194
const entries = await Promise.all(
171195
files.map(async (f: OutFile) => ({
@@ -182,7 +206,36 @@ export async function exportFiles(src: Project, o: ExportOptions): Promise<Expor
182206
return { entries, warnings, errors };
183207
}
184208

185-
export async function exportZip(p: Project, o: ExportOptions) {
209+
export async function exportZip(p: Project, o: ExportOptions, notes?: string[]) {
186210
const r = await exportFiles(p, o);
187-
return { ...r, zip: r.errors.length ? null : await zip(r.entries, { deflate: true }) };
211+
if (r.errors.length) return { ...r, zip: null };
212+
const warnings = [...new Set([...(notes ?? []), ...r.warnings])];
213+
if (notes && warnings.length)
214+
r.entries.push({
215+
name: 'Export notes.txt',
216+
data: new TextEncoder().encode(warnings.join('\n'))
217+
});
218+
const oversized = () => ({
219+
entries: [],
220+
warnings,
221+
zip: null,
222+
problem: 'This export is too large.',
223+
errors: ['The archive exceeds PixelDoll’s size limits.']
224+
});
225+
if (!fitsEditableZip(r.entries)) return oversized();
226+
try {
227+
checkArchivePixels(
228+
r.entries.filter(({ name }) => name.startsWith('cells/')).map(({ data }) => data)
229+
);
230+
} catch {
231+
return oversized();
232+
}
233+
let bytes: Uint8Array;
234+
try {
235+
bytes = await zip(r.entries, { deflate: true });
236+
} catch (error) {
237+
console.warn('Could not compress export; saving without ZIP compression', error);
238+
bytes = await zip(r.entries);
239+
}
240+
return bytes.length <= MAX_ZIP_BYTES ? { ...r, warnings, zip: bytes } : oversized();
188241
}

‎app/src/lib/export/generic.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ export function exportManifest(
366366
warnings: string[] = [];
367367
const items = src.items.filter((it) => {
368368
const ok = it.baseHash === src.rig.baseHash;
369-
if (!ok) warnings.push(`${it.id}: stale (baseHash differs from the rig), excluded`);
369+
if (!ok) warnings.push(`${it.name}: Left out because it no longer matches the body.`);
370370
else if (it.unfitted)
371371
warnings.push(`${it.name}: worn as drawn for another body, not fitted to this character.`);
372372
return ok;
@@ -436,8 +436,7 @@ export function exportManifest(
436436
for (const a of m.rig.animations) {
437437
const directions = moveDirs(src, a.id);
438438
Object.assign(a, { directions });
439-
if (!directions.length)
440-
warnings.push(`${a.id}: no base frames; playback is unavailable for this move`);
439+
if (!directions.length) warnings.push(`${a.id.replace(/[_-]/g, ' ')}: No body frames to play.`);
441440
}
442441
m.export = {
443442
exportedAt: o.exportedAt ?? new Date().toISOString(),
@@ -673,7 +672,9 @@ export function selfTest() {
673672
exportedAt: 'T'
674673
});
675674
console.assert(
676-
warnings.some((warning) => warning.includes('old: stale')) &&
675+
warnings.some((warning) =>
676+
warning.includes('Left out because it no longer matches the body.')
677+
) &&
677678
m.items.length === 1 &&
678679
m.presets[0].items.head === null,
679680
'stale item excluded and unequipped'

0 commit comments

Comments
 (0)