Recurring cleanup round over the code since round 6 (056a622), 105
commits. Behaviour is unchanged. Duplicated code in src went from 29
clones with 229 lines (0.32 %) to 14 clones with 109 lines (0.15 %),
measured with jscpd and the same settings as round 6.
- BehaviorSystem.ts shrinks from 941 to 589 lines. Collecting the
pulses (keys, timers, collisions, animations) moved to
behaviorPulses.ts. The NodeContext the nodes receive moved to
behaviorContext.ts. Imports from outside stay the same, TimeScaled
is still exported from BehaviorSystem.ts.
- PointKindButton and drawPointGrip replace the "Point:" button with
its menu and the point and handle drawing that the curve and the
vector art tab each had on their own.
- lerpVec, cubicAt and splitCubic in src/core/util/vec.ts replace four
copies of the cubic curve and two de Casteljau splits.
- mapNested in Properties.ts is the one walk over lists and structs
that liveObjects and objectRefs did separately. withFieldRenamed
and withoutField replace three copies of renaming a struct field
and two of removing one.
- jsonBody and staleRevision build the JSON body and turn a 409 into
StaleRevisionError for all stores. The auth store turns a 401 into
its error in one place.
- Smaller helpers: structAssetFrom for the two "Make struct type"
commands, shownObject in the inspector, selectedItem for the size
gizmo and the polygon corners, solidTiles in the tilemap collision,
requireVariablesAsset and requireBehaviorVariable.
- Left as is on purpose: the plain forwarding from the collision and
physics systems to Solids, the pointer wiring of the canvases and
the identical last lines of the two make commands.
- Removed unused code: tilemapTileIds and tilemapsUsing were never
called since #128 and #131. EditorState.runtimeProject became unused
with GameRun in #266. The assetId getter of the make commands was
read only by a test.
- 60 values used only in their own file lost their export. The shader
and particle node catalogues stay exported as in round 6.
- Five comments that told history now describe the current state. The
doc comment of BehaviorSystem sits on the class again.
- README lists the struct, clip area and curve assets and mentions the
game link from #266.
Findings:
- Deleting a tile that is painted on a tilemap leaves its cells in
place, and they draw nothing. The delete dialog does not mention the
tilemaps. That was probably the job of the unused tilemapsUsing.
Left as is, because fixing it changes behaviour.
- The solid filter for tile surfaces was untested. A bent filter
stayed green. A new test in tests/core/surface.test.ts now fails
against it.
Tests:
- ./check.sh: 195 files, 2815 tests, exit 0 (one test removed with
tilemapsUsing, one added for tile surfaces).
- Full e2e run: ALL PASSED, 1580 checks.
- Smokes jumprun, tetris, actor: 24, 19 and 21 checks, all passed.
The example project files were restored byte for byte afterwards.
- Counter-checks, 12, all fail as expected: 10 in unit tests (among
them mapNested, splitCubic, cubicAt, staleRevision, the stay pulse,
the late timer and the time scale), 2 in the browser (Point button
always enabled fails 47, selectedItem without a hit fails 29).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
113 lines
4.2 KiB
TypeScript
113 lines
4.2 KiB
TypeScript
import { CreateTextureCommand } from '../core/commands/assetCommands';
|
||
import type { TextureStore, UploadedTexture } from '../core/store/TextureStore';
|
||
import { formatBytes } from '../ui';
|
||
import { type ImportKind, type ImportOutcome, importFiles, importStored, pickAndImport } from './assetImport';
|
||
import type { EditorState } from './state';
|
||
|
||
/** What the picker offers and a drop accepts; the server rejects everything else anyway. */
|
||
const IMAGE_ACCEPT = 'image/png,image/jpeg,image/webp,image/gif';
|
||
|
||
/** Longest side a stored texture may have: a 4000×3000 photo costs 48 MB of video memory. */
|
||
export const MAX_TEXTURE_SIDE = 2048;
|
||
|
||
/** Byte budget for one upload: nginx cuts every request off at 1 MB, below the API's own 4 MB. */
|
||
export const MAX_UPLOAD_BYTES = 950 * 1024;
|
||
|
||
/** Tried in order when an image has to be re-encoded; the first result that fits wins. */
|
||
const WEBP_QUALITIES = [0.9, 0.75, 0.6] as const;
|
||
|
||
export type ImagePlan = { kind: 'keep' } | { kind: 'reencode'; width: number; height: number };
|
||
|
||
/**
|
||
* Re-encoding would turn crisp pixel art into mush, so an image within both limits is kept byte
|
||
* for byte. `bytes` is the encoded file size, not the pixel count.
|
||
*/
|
||
export function planImageFit(width: number, height: number, bytes: number): ImagePlan {
|
||
const scale = Math.min(1, MAX_TEXTURE_SIDE / Math.max(width, height));
|
||
if (scale === 1 && bytes <= MAX_UPLOAD_BYTES) return { kind: 'keep' };
|
||
return {
|
||
kind: 'reencode',
|
||
width: Math.max(1, Math.round(width * scale)),
|
||
height: Math.max(1, Math.round(height * scale)),
|
||
};
|
||
}
|
||
|
||
/** Encodes at decreasing quality; when none fits the budget, the last attempt comes back anyway. */
|
||
export async function encodeWithinBudget(encode: (quality: number) => Promise<Blob>): Promise<Blob> {
|
||
let result = await encode(WEBP_QUALITIES[0]);
|
||
for (const quality of WEBP_QUALITIES.slice(1)) {
|
||
if (result.size <= MAX_UPLOAD_BYTES) return result;
|
||
result = await encode(quality);
|
||
}
|
||
return result;
|
||
}
|
||
|
||
export interface PreparedImage {
|
||
blob: Blob;
|
||
/** Content-Type for the upload; `image/webp` whenever the image had to be re-encoded. */
|
||
type: string;
|
||
width: number;
|
||
height: number;
|
||
}
|
||
|
||
/** The bytes to upload: the file itself when it already fits, otherwise a downscaled WebP. */
|
||
async function prepareImage(file: File): Promise<PreparedImage> {
|
||
let bitmap: ImageBitmap;
|
||
try {
|
||
bitmap = await createImageBitmap(file);
|
||
} catch {
|
||
throw new Error('The file is not a readable image.');
|
||
}
|
||
try {
|
||
const plan = planImageFit(bitmap.width, bitmap.height, file.size);
|
||
if (plan.kind === 'keep') {
|
||
return {
|
||
blob: file,
|
||
type: file.type || 'application/octet-stream',
|
||
width: bitmap.width,
|
||
height: bitmap.height,
|
||
};
|
||
}
|
||
// Only the first frame of an animated GIF survives this.
|
||
const canvas = new OffscreenCanvas(plan.width, plan.height);
|
||
const context = canvas.getContext('2d');
|
||
if (!context) throw new Error('This browser cannot resize images.');
|
||
context.drawImage(bitmap, 0, 0, plan.width, plan.height);
|
||
const blob = await encodeWithinBudget((quality) => canvas.convertToBlob({ type: 'image/webp', quality }));
|
||
if (blob.size > MAX_UPLOAD_BYTES) {
|
||
throw new Error(
|
||
`The image is too large to upload: still ${formatBytes(blob.size)} at ${plan.width}×${plan.height}. Shrink it before importing.`,
|
||
);
|
||
}
|
||
return { blob, type: 'image/webp', width: plan.width, height: plan.height };
|
||
} finally {
|
||
bitmap.close();
|
||
}
|
||
}
|
||
|
||
export interface TextureImportDeps {
|
||
state: EditorState;
|
||
textures: TextureStore;
|
||
}
|
||
|
||
const IMAGE_KIND: ImportKind<UploadedTexture, TextureImportDeps> = {
|
||
type: 'texture',
|
||
noun: 'image',
|
||
fallbackName: 'Texture',
|
||
store: (deps) => deps.textures,
|
||
prepare: prepareImage,
|
||
create: (name, image) => new CreateTextureCommand(name, image),
|
||
};
|
||
|
||
export function importImages(files: readonly File[], deps: TextureImportDeps): Promise<ImportOutcome[]> {
|
||
return importFiles(IMAGE_KIND, files, deps);
|
||
}
|
||
|
||
export function importStoredImage(image: UploadedTexture, deps: TextureImportDeps): ImportOutcome {
|
||
return importStored(IMAGE_KIND, image, deps);
|
||
}
|
||
|
||
export function pickAndImportImages(deps: TextureImportDeps): void {
|
||
pickAndImport(IMAGE_KIND, IMAGE_ACCEPT, deps);
|
||
}
|