Add textures for sprites
Images are uploaded to a content-addressed blob endpoint and stored as data/textures/<sha256>.<ext>; the project only keeps the file name. The sprite points at a texture asset through an ordinary property of the new kind `asset`, so instance overrides, "Apply to container", "Reset to asset", undo and `Set property` work without any extra code. The new kind also replaces the ad-hoc asset picker the graph nodes faked as an enum. Import goes through + -> Texture, drag & drop onto the canvas or Ctrl+V. Images wider than 2048px are downscaled client-side and re-encoded to WebP if needed, because nginx caps uploads at 1MB; an image that already fits is uploaded byte for byte so pixel art is never resampled. The sprite colour default changes from red to white, since colour tints the texture multiplicatively and a tint of white shows an image as it is. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6168df41f8
commit
5a6af74e44
47 files changed
+1995
-110
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import type { Project } from '../model/Project';
|
||||
import { statusMessage } from './http';
|
||||
import {
|
||||
type LoadedProject,
|
||||
type ProjectStore,
|
||||
@@ -62,14 +63,20 @@ export class HttpProjectStore implements ProjectStore {
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
throw new Error(`API ${method} ${route}: invalid JSON (${response.status})`);
|
||||
// Not every failure comes from our API: nginx rejects an oversized body itself and
|
||||
// answers with an HTML page. Such a response is explained by its status, and saying
|
||||
// "invalid JSON" instead of "too large" would send the user looking in the wrong place.
|
||||
// A *successful* response that is not JSON stays a defect and keeps its old message.
|
||||
if (response.ok) throw new Error(`API ${method} ${route}: invalid JSON (${response.status})`);
|
||||
data = null;
|
||||
}
|
||||
if (response.status === 409) {
|
||||
const rev = (data as { revision?: number } | null)?.revision ?? -1;
|
||||
throw new StaleRevisionError(rev);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const message = (data as { error?: string } | null)?.error ?? response.statusText;
|
||||
const message =
|
||||
(data as { error?: string } | null)?.error ?? statusMessage(response.status, response.statusText);
|
||||
throw new Error(`API ${method} ${route}: ${message} (${response.status})`);
|
||||
}
|
||||
return data as T;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { statusMessage } from './http';
|
||||
import type { StoredTexture, TextureStore, UploadedTexture } from './TextureStore';
|
||||
|
||||
/**
|
||||
* Talks to the texture routes of `api/index.php`. Routing goes through the `r` query parameter
|
||||
* (`?r=textures/{file}`) for the same reason as `HttpProjectStore`: nginx does not pass
|
||||
* PATH_INFO to PHP.
|
||||
*/
|
||||
export class HttpTextureStore implements TextureStore {
|
||||
constructor(private readonly endpoint: string) {}
|
||||
|
||||
async upload(bytes: Blob | ArrayBuffer, type: string): Promise<UploadedTexture> {
|
||||
return this.request<UploadedTexture>('POST', 'textures', { bytes, type });
|
||||
}
|
||||
|
||||
async list(): Promise<StoredTexture[]> {
|
||||
return this.request<StoredTexture[]>('GET', 'textures');
|
||||
}
|
||||
|
||||
async delete(file: string): Promise<void> {
|
||||
await this.request<void>('DELETE', `textures/${encodeURIComponent(file)}`);
|
||||
}
|
||||
|
||||
/** One round trip; every failure becomes an `Error` carrying the server's message. */
|
||||
private async request<T>(
|
||||
method: string,
|
||||
route: string,
|
||||
payload?: { bytes: Blob | ArrayBuffer; type: string },
|
||||
): Promise<T> {
|
||||
const url = `${this.endpoint}?r=${encodeURIComponent(route)}`;
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers: payload ? { 'Content-Type': payload.type } : {},
|
||||
body: payload?.bytes,
|
||||
});
|
||||
if (response.status === 204) return undefined as T;
|
||||
const text = await response.text();
|
||||
let data: unknown;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
// An upload is exactly the request nginx refuses before PHP sees it, and its answer is
|
||||
// an HTML page. Explain such a failure from the status; a successful non-JSON body is a defect.
|
||||
if (response.ok) throw new Error(`API ${method} ${route}: invalid JSON (${response.status})`);
|
||||
data = null;
|
||||
}
|
||||
if (!response.ok) {
|
||||
const message =
|
||||
(data as { error?: string } | null)?.error ?? statusMessage(response.status, response.statusText);
|
||||
throw new Error(`API ${method} ${route}: ${message} (${response.status})`);
|
||||
}
|
||||
return data as T;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/** What the server made of an uploaded image; the payload a texture asset is built from. */
|
||||
export interface UploadedTexture {
|
||||
/** Content-addressed name in `data/textures/`: `{sha256}.{png|jpg|webp|gif}` (see `isTextureFile`). */
|
||||
file: string;
|
||||
width: number;
|
||||
height: number;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
/** One stored image as the server lists it. */
|
||||
export interface StoredTexture {
|
||||
file: string;
|
||||
bytes: number;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload boundary for images, the counterpart of `ProjectStore`. The editor only talks to this
|
||||
* interface. An upload is raw bytes rather than a multipart form: name, size and format are
|
||||
* derived from the image itself on the server, so there is nothing else to send.
|
||||
*/
|
||||
export interface TextureStore {
|
||||
/**
|
||||
* Stores an image and returns its file name and pixel size. `type` only fills the
|
||||
* Content-Type header – the server trusts the bytes, not the label – and uploading the same
|
||||
* picture twice yields the same file, because the name is the hash of its content.
|
||||
*/
|
||||
upload(bytes: Blob | ArrayBuffer, type: string): Promise<UploadedTexture>;
|
||||
list(): Promise<StoredTexture[]>;
|
||||
delete(file: string): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* The bit of HTTP handling both stores share. It exists because a failed response does not
|
||||
* always come from our API: nginx caps request bodies at 1 MB and answers a larger one with
|
||||
* its own HTML page, so there is no `{error}` object to read the reason from.
|
||||
*/
|
||||
|
||||
/** Reasons for the statuses that can arrive without an API body of their own. */
|
||||
const STATUS_MESSAGES: Record<number, string> = {
|
||||
400: 'Bad request',
|
||||
403: 'Forbidden',
|
||||
404: 'Not found',
|
||||
413: 'Request too large',
|
||||
500: 'Server error',
|
||||
502: 'Server unavailable',
|
||||
503: 'Server unavailable',
|
||||
504: 'Server timed out',
|
||||
};
|
||||
|
||||
/** What to tell the user about a failed response whose body is not our JSON – the status is all there is. */
|
||||
export function statusMessage(status: number, statusText: string): string {
|
||||
return STATUS_MESSAGES[status] ?? (statusText || `HTTP ${status}`);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { isAssetType } from '../model/AssetTypes';
|
||||
import type { PropertyBag, PropertyValue } from '../model/Properties';
|
||||
import { PROJECT_FORMAT_VERSION, type Project } from '../model/Project';
|
||||
import type { SceneObject } from '../model/SceneObject';
|
||||
import { isTextureFile } from '../model/texture';
|
||||
import { hasParentCycle } from '../model/walk';
|
||||
import {
|
||||
coerceValue,
|
||||
@@ -62,6 +63,8 @@ export function deserializeProject(raw: unknown, fallbackId = ''): Project {
|
||||
variables: variables.get(id) ?? [],
|
||||
graph: normalizeGraph(a.graph),
|
||||
});
|
||||
} else if (type === 'texture') {
|
||||
assets.push({ id, type, name, props, ...normalizeTexture(a) });
|
||||
} else {
|
||||
assets.push({ id, type, name, props });
|
||||
}
|
||||
@@ -181,6 +184,18 @@ function normalizeGraph(raw: unknown): Graph {
|
||||
return graph;
|
||||
}
|
||||
|
||||
/**
|
||||
* The picture of a texture asset. A file name that is not the server's content-addressed form
|
||||
* is dropped rather than kept: it can only have been hand-written, and a request built from it
|
||||
* would 404. Such a texture loads as "no picture", which draws as the sprite's plain colour.
|
||||
*/
|
||||
function normalizeTexture(raw: Record<string, unknown>): { file: string; width: number; height: number } {
|
||||
const file = typeof raw.file === 'string' && isTextureFile(raw.file) ? raw.file : '';
|
||||
const size = (value: unknown): number =>
|
||||
typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
|
||||
return { file, width: size(raw.width), height: size(raw.height) };
|
||||
}
|
||||
|
||||
function normalizeBag(raw: unknown, schema: PropertySchema, sparse: boolean): PropertyBag {
|
||||
const r = asRecord(raw);
|
||||
const bag: PropertyBag = {};
|
||||
|
||||
Reference in new issue
Block a user