@flare-engine/assets 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.d.mts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@ const { image, sheet: atlas } = await createProceduralAtlas(skia, [
|
|
|
25
25
|
]);
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
See [API spec](../../docs/design/api-specs.md#flare-engineassets--6kb-gzip)
|
|
28
|
+
See [API spec](../../docs/design/api-specs.md#flare-engineassets--6kb-gzip).
|
|
29
29
|
|
|
30
30
|
## License
|
|
31
31
|
|
package/dist/index.d.mts
CHANGED
|
@@ -219,10 +219,11 @@ interface SkiaAtlasModuleLike {
|
|
|
219
219
|
* - engine tests / benchmarks that need a valid `SkImage` without
|
|
220
220
|
* shipping any binary asset.
|
|
221
221
|
*
|
|
222
|
-
* **Canonical placeholder-atlas example (Phase 11.14):**
|
|
223
|
-
* ships a full "shape atlas" that draws
|
|
224
|
-
*
|
|
225
|
-
* the result in a `SpriteSheet` — see
|
|
222
|
+
* **Canonical placeholder-atlas example (Phase 11.14):** Pan Tvardowski
|
|
223
|
+
* (github.com/grzott/Pan-Tvardowski) ships a full "shape atlas" that draws
|
|
224
|
+
* every enemy / miniboss / boss / ship / pickup as composed primitives onto
|
|
225
|
+
* an offscreen Skia surface, then wraps the result in a `SpriteSheet` — see
|
|
226
|
+
* `src/shape-atlas.ts` in that repo.
|
|
226
227
|
* That pattern (declarative `ShapeSpec` → `Skia` draw calls → `SpriteSheet`
|
|
227
228
|
* with one named frame per shape) is the recommended way to build a
|
|
228
229
|
* manifest-swappable placeholder atlas: when final art lands, drop the
|
package/dist/index.d.ts
CHANGED
|
@@ -219,10 +219,11 @@ interface SkiaAtlasModuleLike {
|
|
|
219
219
|
* - engine tests / benchmarks that need a valid `SkImage` without
|
|
220
220
|
* shipping any binary asset.
|
|
221
221
|
*
|
|
222
|
-
* **Canonical placeholder-atlas example (Phase 11.14):**
|
|
223
|
-
* ships a full "shape atlas" that draws
|
|
224
|
-
*
|
|
225
|
-
* the result in a `SpriteSheet` — see
|
|
222
|
+
* **Canonical placeholder-atlas example (Phase 11.14):** Pan Tvardowski
|
|
223
|
+
* (github.com/grzott/Pan-Tvardowski) ships a full "shape atlas" that draws
|
|
224
|
+
* every enemy / miniboss / boss / ship / pickup as composed primitives onto
|
|
225
|
+
* an offscreen Skia surface, then wraps the result in a `SpriteSheet` — see
|
|
226
|
+
* `src/shape-atlas.ts` in that repo.
|
|
226
227
|
* That pattern (declarative `ShapeSpec` → `Skia` draw calls → `SpriteSheet`
|
|
227
228
|
* with one named frame per shape) is the recommended way to build a
|
|
228
229
|
* manifest-swappable placeholder atlas: when final art lands, drop the
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/texture.ts","../src/sprite-sheet.ts","../src/asset-manager.ts","../src/decode-image.ts","../src/procedural-atlas.ts"],"sourcesContent":["export { type SkImageLike, type Texture, createTexture } from './texture.js';\n\nexport {\n type SpriteFrame,\n type AnimationSequence,\n type SpriteSheet,\n createSpriteSheet,\n parseTexturePackerHash,\n parseTexturePackerArray,\n parseAseprite,\n addAnimation,\n getFrame,\n} from './sprite-sheet.js';\n\nexport {\n type AssetType,\n type ManifestEntry,\n type AssetLoader,\n AssetManager,\n} from './asset-manager.js';\n\nexport {\n type SkDataLike,\n type SkiaImageDecodeModuleLike,\n decodeImage,\n} from './decode-image.js';\n\nexport {\n type ProceduralFrameSpec,\n type ProceduralAtlasOptions,\n type ProceduralAtlas,\n type SkPaintLike,\n type SkRectLike,\n type SkCanvasLike,\n type SkSurfaceLike,\n type SkiaAtlasModuleLike,\n createProceduralAtlas,\n} from './procedural-atlas.js';\n","/** Minimal interface for the Skia SkImage we wrap. */\nexport interface SkImageLike {\n width(): number;\n height(): number;\n readPixels(): Float32Array | Uint8Array | null;\n /**\n * Optional — present on GPU-backed SkImages returned by RN-Skia's\n * MakeOffscreen surfaces. Copies the texture into a CPU-raster image so it\n * can be safely sampled from a different GrDirectContext (e.g. the on-screen\n * Canvas). Must be called before the image crosses a context boundary.\n */\n makeNonTextureImage?(): SkImageLike;\n}\n\n/** A loaded texture wrapping a Skia SkImage. */\nexport interface Texture {\n /** Unique key for this texture in the asset manager. */\n readonly key: string;\n /** The underlying Skia SkImage. */\n readonly image: SkImageLike;\n /** Width in pixels. */\n readonly width: number;\n /** Height in pixels. */\n readonly height: number;\n}\n\n/** Create a Texture from a Skia SkImage. */\nexport function createTexture(key: string, image: SkImageLike): Texture {\n return {\n key,\n image,\n width: image.width(),\n height: image.height(),\n };\n}\n","/** A single frame rectangle in a sprite sheet. */\nexport interface SpriteFrame {\n /** Name/key of the frame. */\n name: string;\n /** X offset in the source texture (pixels). */\n x: number;\n /** Y offset in the source texture (pixels). */\n y: number;\n /** Width of the frame (pixels). */\n w: number;\n /** Height of the frame (pixels). */\n h: number;\n}\n\n/** A named animation sequence within a sprite sheet. */\nexport interface AnimationSequence {\n /** Sequence name (e.g. \"walk\", \"idle\"). */\n name: string;\n /** Indices into the SpriteSheet.frames array. */\n frameIndices: number[];\n /** Duration per frame in seconds. */\n frameDuration: number;\n /** Whether to loop the sequence. */\n loop: boolean;\n}\n\n/** Parsed sprite sheet data — pure data, no Skia dependency. */\nexport interface SpriteSheet {\n /** Ordered array of all frames. */\n frames: SpriteFrame[];\n /** Map from frame name to index in frames[]. */\n frameMap: Map<string, number>;\n /** Named animation sequences. */\n animations: Map<string, AnimationSequence>;\n}\n\n/** Create an empty sprite sheet. */\nexport function createSpriteSheet(): SpriteSheet {\n return {\n frames: [],\n frameMap: new Map(),\n animations: new Map(),\n };\n}\n\n// ----- TexturePacker JSON (hash format) -----\n\ninterface TPHashFrame {\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPHashJSON {\n frames: Record<string, TPHashFrame>;\n}\n\n/** Parse TexturePacker JSON hash format. */\nexport function parseTexturePackerHash(json: unknown): SpriteSheet {\n const data = json as TPHashJSON;\n const sheet = createSpriteSheet();\n const entries = Object.entries(data.frames);\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (!entry) continue;\n const [name, value] = entry;\n const f = value.frame;\n sheet.frames.push({ name, x: f.x, y: f.y, w: f.w, h: f.h });\n sheet.frameMap.set(name, i);\n }\n return sheet;\n}\n\n// ----- TexturePacker JSON (array format) -----\n\ninterface TPArrayFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPArrayJSON {\n frames: TPArrayFrame[];\n}\n\n/** Parse TexturePacker JSON array format. */\nexport function parseTexturePackerArray(json: unknown): SpriteSheet {\n const data = json as TPArrayJSON;\n const sheet = createSpriteSheet();\n for (let i = 0; i < data.frames.length; i++) {\n const entry = data.frames[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n return sheet;\n}\n\n// ----- Aseprite JSON -----\n\ninterface AsepriteFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n duration: number; // ms\n}\n\ninterface AsepriteTag {\n name: string;\n from: number;\n to: number;\n direction: string;\n}\n\ninterface AsepriteJSON {\n frames: AsepriteFrame[] | Record<string, AsepriteFrame>;\n meta?: {\n frameTags?: AsepriteTag[];\n };\n}\n\n/** Parse Aseprite JSON export. */\nexport function parseAseprite(json: unknown): SpriteSheet {\n const data = json as AsepriteJSON;\n const sheet = createSpriteSheet();\n\n // Aseprite can export frames as array or object\n const frameEntries: AsepriteFrame[] = Array.isArray(data.frames)\n ? data.frames\n : Object.values(data.frames);\n\n for (let i = 0; i < frameEntries.length; i++) {\n const entry = frameEntries[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n\n // Parse frame tags as animation sequences\n const tags = data.meta?.frameTags;\n if (tags) {\n for (const tag of tags) {\n const indices: number[] = [];\n if (tag.direction === 'reverse') {\n for (let i = tag.to; i >= tag.from; i--) {\n indices.push(i);\n }\n } else if (tag.direction === 'pingpong') {\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n for (let i = tag.to - 1; i > tag.from; i--) {\n indices.push(i);\n }\n } else {\n // \"forward\" or default\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n }\n\n // Use the first frame's duration as the uniform frame duration\n const firstFrame = frameEntries[tag.from];\n const durationMs = firstFrame?.duration ?? 100;\n\n sheet.animations.set(tag.name, {\n name: tag.name,\n frameIndices: indices,\n frameDuration: durationMs / 1000,\n loop: true,\n });\n }\n }\n\n return sheet;\n}\n\n/**\n * Add a custom animation sequence to a sprite sheet.\n */\nexport function addAnimation(\n sheet: SpriteSheet,\n name: string,\n frameIndices: number[],\n frameDuration: number,\n loop = true,\n): void {\n sheet.animations.set(name, { name, frameIndices, frameDuration, loop });\n}\n\n/** Get a frame by name. Returns undefined if not found. */\nexport function getFrame(sheet: SpriteSheet, name: string): SpriteFrame | undefined {\n const idx = sheet.frameMap.get(name);\n if (idx === undefined) return undefined;\n return sheet.frames[idx];\n}\n","import { Signal } from '@flare-engine/events';\nimport type { SpriteSheet } from './sprite-sheet.js';\nimport type { Texture } from './texture.js';\n\n/** Types of assets the manager can store. */\nexport type AssetType = 'texture' | 'spritesheet' | 'json' | 'binary';\n\n/** A single entry in an asset manifest. */\nexport interface ManifestEntry {\n /** Unique key to retrieve this asset. */\n key: string;\n /** Asset type. */\n type: AssetType;\n /** Path or URI to the asset. */\n path: string;\n}\n\n/** A load function provided by the platform to actually fetch+decode assets. */\nexport type AssetLoader = (entry: ManifestEntry) => Promise<Texture | SpriteSheet | unknown>;\n\n/**\n * AssetManager — loads, caches, and provides access to game assets.\n *\n * Platform-agnostic: the actual loading is delegated to an `AssetLoader`\n * function injected at construction. This allows Skia-dependent texture\n * loading to live in the React layer while keeping this module testable.\n */\nexport class AssetManager {\n /** Fires on each asset loaded with current progress (0-1). */\n readonly onProgress = new Signal<number>();\n\n /** Current loading progress 0-1. */\n progress = 0;\n\n private _assets = new Map<string, unknown>();\n private _loader: AssetLoader;\n\n constructor(loader: AssetLoader) {\n this._loader = loader;\n }\n\n /**\n * Load all assets in the manifest.\n * Resolves when all assets are loaded and cached.\n */\n async load(manifest: ManifestEntry[]): Promise<void> {\n if (manifest.length === 0) {\n this.progress = 1;\n this.onProgress.emit(1);\n return;\n }\n\n let loaded = 0;\n const total = manifest.length;\n\n const promises = manifest.map(async (entry) => {\n const asset = await this._loader(entry);\n this._assets.set(entry.key, asset);\n loaded++;\n this.progress = loaded / total;\n this.onProgress.emit(this.progress);\n });\n\n await Promise.all(promises);\n }\n\n /** Get a loaded asset by key. Returns undefined if not found. */\n get<T = unknown>(key: string): T | undefined {\n return this._assets.get(key) as T | undefined;\n }\n\n /** Check if an asset is loaded. */\n has(key: string): boolean {\n return this._assets.has(key);\n }\n\n /** Remove an asset from the cache. */\n unload(key: string): boolean {\n return this._assets.delete(key);\n }\n\n /** Clear all cached assets. */\n clear(): void {\n this._assets.clear();\n this.progress = 0;\n }\n}\n","import type { SkImageLike } from './texture.js';\n\n/** Opaque handle for a Skia SkData object. */\nexport interface SkDataLike {\n readonly __skData: unique symbol;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Injected by the caller so @flare-engine/assets stays runtime-agnostic.\n */\nexport interface SkiaImageDecodeModuleLike {\n Data: {\n fromBytes(bytes: Uint8Array): SkDataLike;\n };\n Image: {\n MakeImageFromEncoded(data: SkDataLike): SkImageLike | null;\n };\n}\n\n/**\n * Decode raw image bytes into a Skia SkImage.\n *\n * Returns null on failure — never throws. Callers are responsible for\n * handling null (e.g. falling back to a placeholder texture).\n */\nexport function decodeImage(\n Skia: SkiaImageDecodeModuleLike,\n bytes: Uint8Array,\n): SkImageLike | null {\n const data = Skia.Data.fromBytes(bytes);\n return Skia.Image.MakeImageFromEncoded(data);\n}\n","import { type SpriteFrame, type SpriteSheet, createSpriteSheet } from './sprite-sheet.js';\nimport type { SkImageLike } from './texture.js';\n\n/** One entry in a procedural atlas — a named colored rectangle. */\nexport interface ProceduralFrameSpec {\n /** Frame name (used as the SpriteFrame name for lookup). */\n name: string;\n /** Width in pixels. */\n w: number;\n /** Height in pixels. */\n h: number;\n /** Color as ARGB int (0xAARRGGBB). */\n color: number;\n}\n\n/** Options controlling atlas layout. */\nexport interface ProceduralAtlasOptions {\n /** Max atlas width before wrapping to a new row. Default 1024. */\n maxWidth?: number;\n /** Gap between frames in pixels. Default 0. */\n padding?: number;\n}\n\n/** Result of a procedural atlas build. */\nexport interface ProceduralAtlas {\n /** Backing Skia image with all rects drawn. */\n image: SkImageLike;\n /** SpriteSheet whose frames describe the rect positions. */\n sheet: SpriteSheet;\n /** Total atlas width in pixels. */\n width: number;\n /** Total atlas height in pixels. */\n height: number;\n}\n\n/** Opaque Skia color value — a Float32Array of length 4 (r, g, b, a in [0,1]). */\ntype SkColorLike = Float32Array;\n\n/** Narrow paint interface — only the setter we use. */\nexport interface SkPaintLike {\n setColor(color: SkColorLike): void;\n}\n\n/** Narrow rect interface — a rect value object passed to drawRect. */\nexport interface SkRectLike {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** Narrow canvas interface — only the method we use. */\nexport interface SkCanvasLike {\n drawRect(rect: SkRectLike, paint: SkPaintLike): void;\n}\n\n/** Narrow surface interface — getCanvas + snapshot. */\nexport interface SkSurfaceLike {\n getCanvas(): SkCanvasLike;\n makeImageSnapshot(): SkImageLike;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Declared locally so unit tests can supply a plain mock without pulling\n * in the full `@shopify/react-native-skia` surface.\n */\nexport interface SkiaAtlasModuleLike {\n Surface: { Make(width: number, height: number): SkSurfaceLike | null };\n Paint(): SkPaintLike;\n XYWHRect(x: number, y: number, w: number, h: number): SkRectLike;\n}\n\n/**\n * Build a flat atlas `SkImage` from a list of colored rectangles.\n *\n * Row-packs frames left-to-right until `maxWidth` is exceeded, then wraps\n * to a new row. Returns both the backing image and a `SpriteSheet` whose\n * frames match the packed positions, so consumers can look up frames by\n * name exactly as with a real `parseTexturePacker*` sheet.\n *\n * Useful for:\n * - bootstrapping gameplay before final art lands (replace with one\n * `parseTexturePackerHash` call once the real atlas arrives),\n * - engine tests / benchmarks that need a valid `SkImage` without\n * shipping any binary asset.\n *\n * **Canonical placeholder-atlas example (Phase 11.14):** `apps/pan-tvardowski`\n * ships a full \"shape atlas\" that draws every enemy / miniboss / boss / ship /\n * pickup as composed primitives onto an offscreen Skia surface, then wraps\n * the result in a `SpriteSheet` — see `apps/pan-tvardowski/src/shape-atlas.ts`.\n * That pattern (declarative `ShapeSpec` → `Skia` draw calls → `SpriteSheet`\n * with one named frame per shape) is the recommended way to build a\n * manifest-swappable placeholder atlas: when final art lands, drop the\n * shape draw-calls for `parseTexturePackerHash(jsonText)` with no other\n * code changes.\n */\nexport function createProceduralAtlas(\n Skia: SkiaAtlasModuleLike,\n frames: readonly ProceduralFrameSpec[],\n options: ProceduralAtlasOptions = {},\n): ProceduralAtlas {\n const maxWidth = options.maxWidth ?? 1024;\n const padding = options.padding ?? 0;\n\n const positions = layoutRows(frames, maxWidth, padding);\n const surface = Skia.Surface.Make(positions.width, positions.height);\n if (surface === null) {\n throw new Error(`Skia.Surface.Make returned null for ${positions.width}x${positions.height}`);\n }\n\n const canvas = surface.getCanvas();\n const paint = Skia.Paint();\n const color: SkColorLike = new Float32Array(4);\n\n const sheet = createSpriteSheet();\n\n for (let i = 0; i < frames.length; i++) {\n const spec = frames[i];\n const pos = positions.rects[i];\n if (spec === undefined || pos === undefined) continue;\n\n writeArgb(color, spec.color);\n paint.setColor(color);\n canvas.drawRect(Skia.XYWHRect(pos.x, pos.y, spec.w, spec.h), paint);\n\n const frame: SpriteFrame = {\n name: spec.name,\n x: pos.x,\n y: pos.y,\n w: spec.w,\n h: spec.h,\n };\n sheet.frames.push(frame);\n sheet.frameMap.set(spec.name, i);\n }\n\n return {\n image: surface.makeImageSnapshot(),\n sheet,\n width: positions.width,\n height: positions.height,\n };\n}\n\ninterface PackedPosition {\n x: number;\n y: number;\n}\n\ninterface PackedLayout {\n rects: PackedPosition[];\n width: number;\n height: number;\n}\n\nfunction layoutRows(\n frames: readonly ProceduralFrameSpec[],\n maxWidth: number,\n padding: number,\n): PackedLayout {\n const rects: PackedPosition[] = [];\n let x = 0;\n let y = 0;\n let rowHeight = 0;\n let atlasWidth = 0;\n\n for (const spec of frames) {\n if (x > 0 && x + spec.w > maxWidth) {\n y += rowHeight + padding;\n x = 0;\n rowHeight = 0;\n }\n rects.push({ x, y });\n x += spec.w + padding;\n if (spec.h > rowHeight) rowHeight = spec.h;\n if (x - padding > atlasWidth) atlasWidth = x - padding;\n }\n\n const atlasHeight = y + rowHeight;\n return {\n rects,\n width: atlasWidth > 0 ? atlasWidth : 1,\n height: atlasHeight > 0 ? atlasHeight : 1,\n };\n}\n\nfunction writeArgb(out: SkColorLike, argb: number): void {\n out[0] = ((argb >>> 16) & 0xff) / 255;\n out[1] = ((argb >>> 8) & 0xff) / 255;\n out[2] = (argb & 0xff) / 255;\n out[3] = ((argb >>> 24) & 0xff) / 255;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC2BO,SAAS,cAAc,KAAa,OAA6B;AACtE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO,MAAM,MAAM;AAAA,IACnB,QAAQ,MAAM,OAAO;AAAA,EACvB;AACF;;;ACGO,SAAS,oBAAiC;AAC/C,SAAO;AAAA,I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B,aAAW,QAAQ,QAAQ;AACzB,QAAI,IAAI,KAAK,IAAI,KAAK,IAAI,UAAU;AAClC,WAAK,YAAY;AACjB,UAAI;AACJ,kBAAY;AAAA,IACd;AACA,UAAM,KAAK,EAAE,GAAG,EAAE,CAAC;AACnB,SAAK,KAAK,IAAI;AACd,QAAI,KAAK,IAAI,UAAW,aAAY,KAAK;AACzC,QAAI,IAAI,UAAU,WAAY,cAAa,IAAI;AAAA,EACjD;AAEA,QAAM,cAAc,IAAI;AACxB,SAAO;AAAA,IACL;AAAA,IACA,OAAO,aAAa,IAAI,aAAa;AAAA,IACrC,QAAQ,cAAc,IAAI,cAAc;AAAA,EAC1C;AACF;AAEA,SAAS,UAAU,KAAkB,MAAoB;AACvD,MAAI,CAAC,KAAM,SAAS,KAAM,OAAQ;AAClC,MAAI,CAAC,KAAM,SAAS,IAAK,OAAQ;AACjC,MAAI,CAAC,KAAK,OAAO,OAAQ;AACzB,MAAI,CAAC,KAAM,SAAS,KAAM,OAAQ;AACpC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/texture.ts","../src/sprite-sheet.ts","../src/asset-manager.ts","../src/decode-image.ts","../src/procedural-atlas.ts"],"sourcesContent":["export { type SkImageLike, type Texture, createTexture } from './texture.js';\n\nexport {\n type SpriteFrame,\n type AnimationSequence,\n type SpriteSheet,\n createSpriteSheet,\n parseTexturePackerHash,\n parseTexturePackerArray,\n parseAseprite,\n addAnimation,\n getFrame,\n} from './sprite-sheet.js';\n\nexport {\n type AssetType,\n type ManifestEntry,\n type AssetLoader,\n AssetManager,\n} from './asset-manager.js';\n\nexport {\n type SkDataLike,\n type SkiaImageDecodeModuleLike,\n decodeImage,\n} from './decode-image.js';\n\nexport {\n type ProceduralFrameSpec,\n type ProceduralAtlasOptions,\n type ProceduralAtlas,\n type SkPaintLike,\n type SkRectLike,\n type SkCanvasLike,\n type SkSurfaceLike,\n type SkiaAtlasModuleLike,\n createProceduralAtlas,\n} from './procedural-atlas.js';\n","/** Minimal interface for the Skia SkImage we wrap. */\nexport interface SkImageLike {\n width(): number;\n height(): number;\n readPixels(): Float32Array | Uint8Array | null;\n /**\n * Optional — present on GPU-backed SkImages returned by RN-Skia's\n * MakeOffscreen surfaces. Copies the texture into a CPU-raster image so it\n * can be safely sampled from a different GrDirectContext (e.g. the on-screen\n * Canvas). Must be called before the image crosses a context boundary.\n */\n makeNonTextureImage?(): SkImageLike;\n}\n\n/** A loaded texture wrapping a Skia SkImage. */\nexport interface Texture {\n /** Unique key for this texture in the asset manager. */\n readonly key: string;\n /** The underlying Skia SkImage. */\n readonly image: SkImageLike;\n /** Width in pixels. */\n readonly width: number;\n /** Height in pixels. */\n readonly height: number;\n}\n\n/** Create a Texture from a Skia SkImage. */\nexport function createTexture(key: string, image: SkImageLike): Texture {\n return {\n key,\n image,\n width: image.width(),\n height: image.height(),\n };\n}\n","/** A single frame rectangle in a sprite sheet. */\nexport interface SpriteFrame {\n /** Name/key of the frame. */\n name: string;\n /** X offset in the source texture (pixels). */\n x: number;\n /** Y offset in the source texture (pixels). */\n y: number;\n /** Width of the frame (pixels). */\n w: number;\n /** Height of the frame (pixels). */\n h: number;\n}\n\n/** A named animation sequence within a sprite sheet. */\nexport interface AnimationSequence {\n /** Sequence name (e.g. \"walk\", \"idle\"). */\n name: string;\n /** Indices into the SpriteSheet.frames array. */\n frameIndices: number[];\n /** Duration per frame in seconds. */\n frameDuration: number;\n /** Whether to loop the sequence. */\n loop: boolean;\n}\n\n/** Parsed sprite sheet data — pure data, no Skia dependency. */\nexport interface SpriteSheet {\n /** Ordered array of all frames. */\n frames: SpriteFrame[];\n /** Map from frame name to index in frames[]. */\n frameMap: Map<string, number>;\n /** Named animation sequences. */\n animations: Map<string, AnimationSequence>;\n}\n\n/** Create an empty sprite sheet. */\nexport function createSpriteSheet(): SpriteSheet {\n return {\n frames: [],\n frameMap: new Map(),\n animations: new Map(),\n };\n}\n\n// ----- TexturePacker JSON (hash format) -----\n\ninterface TPHashFrame {\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPHashJSON {\n frames: Record<string, TPHashFrame>;\n}\n\n/** Parse TexturePacker JSON hash format. */\nexport function parseTexturePackerHash(json: unknown): SpriteSheet {\n const data = json as TPHashJSON;\n const sheet = createSpriteSheet();\n const entries = Object.entries(data.frames);\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (!entry) continue;\n const [name, value] = entry;\n const f = value.frame;\n sheet.frames.push({ name, x: f.x, y: f.y, w: f.w, h: f.h });\n sheet.frameMap.set(name, i);\n }\n return sheet;\n}\n\n// ----- TexturePacker JSON (array format) -----\n\ninterface TPArrayFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPArrayJSON {\n frames: TPArrayFrame[];\n}\n\n/** Parse TexturePacker JSON array format. */\nexport function parseTexturePackerArray(json: unknown): SpriteSheet {\n const data = json as TPArrayJSON;\n const sheet = createSpriteSheet();\n for (let i = 0; i < data.frames.length; i++) {\n const entry = data.frames[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n return sheet;\n}\n\n// ----- Aseprite JSON -----\n\ninterface AsepriteFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n duration: number; // ms\n}\n\ninterface AsepriteTag {\n name: string;\n from: number;\n to: number;\n direction: string;\n}\n\ninterface AsepriteJSON {\n frames: AsepriteFrame[] | Record<string, AsepriteFrame>;\n meta?: {\n frameTags?: AsepriteTag[];\n };\n}\n\n/** Parse Aseprite JSON export. */\nexport function parseAseprite(json: unknown): SpriteSheet {\n const data = json as AsepriteJSON;\n const sheet = createSpriteSheet();\n\n // Aseprite can export frames as array or object\n const frameEntries: AsepriteFrame[] = Array.isArray(data.frames)\n ? data.frames\n : Object.values(data.frames);\n\n for (let i = 0; i < frameEntries.length; i++) {\n const entry = frameEntries[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n\n // Parse frame tags as animation sequences\n const tags = data.meta?.frameTags;\n if (tags) {\n for (const tag of tags) {\n const indices: number[] = [];\n if (tag.direction === 'reverse') {\n for (let i = tag.to; i >= tag.from; i--) {\n indices.push(i);\n }\n } else if (tag.direction === 'pingpong') {\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n for (let i = tag.to - 1; i > tag.from; i--) {\n indices.push(i);\n }\n } else {\n // \"forward\" or default\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n }\n\n // Use the first frame's duration as the uniform frame duration\n const firstFrame = frameEntries[tag.from];\n const durationMs = firstFrame?.duration ?? 100;\n\n sheet.animations.set(tag.name, {\n name: tag.name,\n frameIndices: indices,\n frameDuration: durationMs / 1000,\n loop: true,\n });\n }\n }\n\n return sheet;\n}\n\n/**\n * Add a custom animation sequence to a sprite sheet.\n */\nexport function addAnimation(\n sheet: SpriteSheet,\n name: string,\n frameIndices: number[],\n frameDuration: number,\n loop = true,\n): void {\n sheet.animations.set(name, { name, frameIndices, frameDuration, loop });\n}\n\n/** Get a frame by name. Returns undefined if not found. */\nexport function getFrame(sheet: SpriteSheet, name: string): SpriteFrame | undefined {\n const idx = sheet.frameMap.get(name);\n if (idx === undefined) return undefined;\n return sheet.frames[idx];\n}\n","import { Signal } from '@flare-engine/events';\nimport type { SpriteSheet } from './sprite-sheet.js';\nimport type { Texture } from './texture.js';\n\n/** Types of assets the manager can store. */\nexport type AssetType = 'texture' | 'spritesheet' | 'json' | 'binary';\n\n/** A single entry in an asset manifest. */\nexport interface ManifestEntry {\n /** Unique key to retrieve this asset. */\n key: string;\n /** Asset type. */\n type: AssetType;\n /** Path or URI to the asset. */\n path: string;\n}\n\n/** A load function provided by the platform to actually fetch+decode assets. */\nexport type AssetLoader = (entry: ManifestEntry) => Promise<Texture | SpriteSheet | unknown>;\n\n/**\n * AssetManager — loads, caches, and provides access to game assets.\n *\n * Platform-agnostic: the actual loading is delegated to an `AssetLoader`\n * function injected at construction. This allows Skia-dependent texture\n * loading to live in the React layer while keeping this module testable.\n */\nexport class AssetManager {\n /** Fires on each asset loaded with current progress (0-1). */\n readonly onProgress = new Signal<number>();\n\n /** Current loading progress 0-1. */\n progress = 0;\n\n private _assets = new Map<string, unknown>();\n private _loader: AssetLoader;\n\n constructor(loader: AssetLoader) {\n this._loader = loader;\n }\n\n /**\n * Load all assets in the manifest.\n * Resolves when all assets are loaded and cached.\n */\n async load(manifest: ManifestEntry[]): Promise<void> {\n if (manifest.length === 0) {\n this.progress = 1;\n this.onProgress.emit(1);\n return;\n }\n\n let loaded = 0;\n const total = manifest.length;\n\n const promises = manifest.map(async (entry) => {\n const asset = await this._loader(entry);\n this._assets.set(entry.key, asset);\n loaded++;\n this.progress = loaded / total;\n this.onProgress.emit(this.progress);\n });\n\n await Promise.all(promises);\n }\n\n /** Get a loaded asset by key. Returns undefined if not found. */\n get<T = unknown>(key: string): T | undefined {\n return this._assets.get(key) as T | undefined;\n }\n\n /** Check if an asset is loaded. */\n has(key: string): boolean {\n return this._assets.has(key);\n }\n\n /** Remove an asset from the cache. */\n unload(key: string): boolean {\n return this._assets.delete(key);\n }\n\n /** Clear all cached assets. */\n clear(): void {\n this._assets.clear();\n this.progress = 0;\n }\n}\n","import type { SkImageLike } from './texture.js';\n\n/** Opaque handle for a Skia SkData object. */\nexport interface SkDataLike {\n readonly __skData: unique symbol;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Injected by the caller so @flare-engine/assets stays runtime-agnostic.\n */\nexport interface SkiaImageDecodeModuleLike {\n Data: {\n fromBytes(bytes: Uint8Array): SkDataLike;\n };\n Image: {\n MakeImageFromEncoded(data: SkDataLike): SkImageLike | null;\n };\n}\n\n/**\n * Decode raw image bytes into a Skia SkImage.\n *\n * Returns null on failure — never throws. Callers are responsible for\n * handling null (e.g. falling back to a placeholder texture).\n */\nexport function decodeImage(\n Skia: SkiaImageDecodeModuleLike,\n bytes: Uint8Array,\n): SkImageLike | null {\n const data = Skia.Data.fromBytes(bytes);\n return Skia.Image.MakeImageFromEncoded(data);\n}\n","import { type SpriteFrame, type SpriteSheet, createSpriteSheet } from './sprite-sheet.js';\nimport type { SkImageLike } from './texture.js';\n\n/** One entry in a procedural atlas — a named colored rectangle. */\nexport interface ProceduralFrameSpec {\n /** Frame name (used as the SpriteFrame name for lookup). */\n name: string;\n /** Width in pixels. */\n w: number;\n /** Height in pixels. */\n h: number;\n /** Color as ARGB int (0xAARRGGBB). */\n color: number;\n}\n\n/** Options controlling atlas layout. */\nexport interface ProceduralAtlasOptions {\n /** Max atlas width before wrapping to a new row. Default 1024. */\n maxWidth?: number;\n /** Gap between frames in pixels. Default 0. */\n padding?: number;\n}\n\n/** Result of a procedural atlas build. */\nexport interface ProceduralAtlas {\n /** Backing Skia image with all rects drawn. */\n image: SkImageLike;\n /** SpriteSheet whose frames describe the rect positions. */\n sheet: SpriteSheet;\n /** Total atlas width in pixels. */\n width: number;\n /** Total atlas height in pixels. */\n height: number;\n}\n\n/** Opaque Skia color value — a Float32Array of length 4 (r, g, b, a in [0,1]). */\ntype SkColorLike = Float32Array;\n\n/** Narrow paint interface — only the setter we use. */\nexport interface SkPaintLike {\n setColor(color: SkColorLike): void;\n}\n\n/** Narrow rect interface — a rect value object passed to drawRect. */\nexport interface SkRectLike {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** Narrow canvas interface — only the method we use. */\nexport interface SkCanvasLike {\n drawRect(rect: SkRectLike, paint: SkPaintLike): void;\n}\n\n/** Narrow surface interface — getCanvas + snapshot. */\nexport interface SkSurfaceLike {\n getCanvas(): SkCanvasLike;\n makeImageSnapshot(): SkImageLike;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Declared locally so unit tests can supply a plain mock without pulling\n * in the full `@shopify/react-native-skia` surface.\n */\nexport interface SkiaAtlasModuleLike {\n Surface: { Make(width: number, height: number): SkSurfaceLike | null };\n Paint(): SkPaintLike;\n XYWHRect(x: number, y: number, w: number, h: number): SkRectLike;\n}\n\n/**\n * Build a flat atlas `SkImage` from a list of colored rectangles.\n *\n * Row-packs frames left-to-right until `maxWidth` is exceeded, then wraps\n * to a new row. Returns both the backing image and a `SpriteSheet` whose\n * frames match the packed positions, so consumers can look up frames by\n * name exactly as with a real `parseTexturePacker*` sheet.\n *\n * Useful for:\n * - bootstrapping gameplay before final art lands (replace with one\n * `parseTexturePackerHash` call once the real atlas arrives),\n * - engine tests / benchmarks that need a valid `SkImage` without\n * shipping any binary asset.\n *\n * **Canonical placeholder-atlas example (Phase 11.14):** Pan Tvardowski\n * (github.com/grzott/Pan-Tvardowski) ships a full \"shape atlas\" that draws\n * every enemy / miniboss / boss / ship / pickup as composed primitives onto\n * an offscreen Skia surface, then wraps the result in a `SpriteSheet` — see\n * `src/shape-atlas.ts` in that repo.\n * That pattern (declarative `ShapeSpec` → `Skia` draw calls → `SpriteSheet`\n * with one named frame per shape) is the recommended way to build a\n * manifest-swappable placeholder atlas: when final art lands, drop the\n * shape draw-calls for `parseTexturePackerHash(jsonText)` with no other\n * code changes.\n */\nexport function createProceduralAtlas(\n Skia: SkiaAtlasModuleLike,\n frames: readonly ProceduralFrameSpec[],\n options: ProceduralAtlasOptions = {},\n): ProceduralAtlas {\n const maxWidth = options.maxWidth ?? 1024;\n const padding = options.padding ?? 0;\n\n const positions = layoutRows(frames, maxWidth, padding);\n const surface = Skia.Surface.Make(positions.width, positions.height);\n if (surface === null) {\n throw new Error(`Skia.Surface.Make returned null for ${positions.width}x${positions.height}`);\n }\n\n const canvas = surface.getCanvas();\n const paint = Skia.Paint();\n const color: SkColorLike = new Float32Array(4);\n\n const sheet = createSpriteSheet();\n\n for (let i = 0; i < frames.length; i++) {\n const spec = frames[i];\n const pos = positions.rects[i];\n if (spec === undefined || pos === undefined) continue;\n\n writeArgb(color, spec.color);\n paint.setColor(color);\n canvas.drawRect(Skia.XYWHRect(pos.x, pos.y, spec.w, spec.h), paint);\n\n const frame: SpriteFrame = {\n name: spec.name,\n x: pos.x,\n y: pos.y,\n w: spec.w,\n h: spec.h,\n };\n sheet.frames.push(frame);\n sheet.frameMap.set(spec.name, i);\n }\n\n return {\n image: surface.makeImageSnapshot(),\n sheet,\n width: positions.width,\n height: positions.height,\n };\n}\n\ninterface PackedPosition {\n x: number;\n y: number;\n}\n\ninterface PackedLayout {\n rects: PackedPosition[];\n width: number;\n height: number;\n}\n\nfunction layoutRows(\n frames: readonly ProceduralFrameSpec[],\n maxWidth: number,\n padding: number,\n): PackedLayout {\n const rects: PackedPosition[] = [];\n let x = 0;\n let y = 0;\n let rowHeight = 0;\n let atlasWidth = 0;\n\n for (const spec of frames) {\n if (x > 0 && x + spec.w > maxWidth) {\n y += rowHeight + padding;\n x = 0;\n rowHeight = 0;\n }\n rects.push({ x, y });\n x += spec.w + padding;\n if (spec.h > rowHeight) rowHeight = spec.h;\n if (x - padding > atlasWidth) atlasWidth = x - padding;\n }\n\n const atlasHeight = y + rowHeight;\n return {\n rects,\n width: atlasWidth > 0 ? atlasWidth : 1,\n height: atlasHeight > 0 ? atlasHeight : 1,\n };\n}\n\nfunction writeArgb(out: SkColorLike, argb: number): void {\n out[0] = ((argb >>> 16) & 0xff) / 255;\n out[1] = ((argb >>> 8) & 0xff) / 255;\n out[2] = (argb & 0xff) / 255;\n out[3] = ((argb >>> 24) & 0xff) / 255;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC2BO,SAAS,cAAc,KAAa,OAA6B;AACtE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO,MAAM,MAAM;AAAA,IACnB,QAAQ,MAAM,OAAO;AAAA,EACvB;AACF;;;ACG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R,MAAI,YAAY;AAChB,MAAI,aAAa;AAEjB,aAAW,QAAQ,QAAQ;AACzB,QAAI,IAAI,KAAK,IAAI,KAAK,IAAI,UAAU;AAClC,WAAK,YAAY;AACjB,UAAI;AACJ,kBAAY;AAAA,IACd;AACA,UAAM,KAAK,EAAE,GAAG,EAAE,CAAC;AACnB,SAAK,KAAK,IAAI;AACd,QAAI,KAAK,IAAI,UAAW,aAAY,KAAK;AACzC,QAAI,IAAI,UAAU,WAAY,cAAa,IAAI;AAAA,EACjD;AAEA,QAAM,cAAc,IAAI;AACxB,SAAO;AAAA,IACL;AAAA,IACA,OAAO,aAAa,IAAI,aAAa;AAAA,IACrC,QAAQ,cAAc,IAAI,cAAc;AAAA,EAC1C;AACF;AAEA,SAAS,UAAU,KAAkB,MAAoB;AACvD,MAAI,CAAC,KAAM,SAAS,KAAM,OAAQ;AAClC,MAAI,CAAC,KAAM,SAAS,IAAK,OAAQ;AACjC,MAAI,CAAC,KAAK,OAAO,OAAQ;AACzB,MAAI,CAAC,KAAM,SAAS,KAAM,OAAQ;AACpC;","names":[]}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/texture.ts","../src/sprite-sheet.ts","../src/asset-manager.ts","../src/decode-image.ts","../src/procedural-atlas.ts"],"sourcesContent":["/** Minimal interface for the Skia SkImage we wrap. */\nexport interface SkImageLike {\n width(): number;\n height(): number;\n readPixels(): Float32Array | Uint8Array | null;\n /**\n * Optional — present on GPU-backed SkImages returned by RN-Skia's\n * MakeOffscreen surfaces. Copies the texture into a CPU-raster image so it\n * can be safely sampled from a different GrDirectContext (e.g. the on-screen\n * Canvas). Must be called before the image crosses a context boundary.\n */\n makeNonTextureImage?(): SkImageLike;\n}\n\n/** A loaded texture wrapping a Skia SkImage. */\nexport interface Texture {\n /** Unique key for this texture in the asset manager. */\n readonly key: string;\n /** The underlying Skia SkImage. */\n readonly image: SkImageLike;\n /** Width in pixels. */\n readonly width: number;\n /** Height in pixels. */\n readonly height: number;\n}\n\n/** Create a Texture from a Skia SkImage. */\nexport function createTexture(key: string, image: SkImageLike): Texture {\n return {\n key,\n image,\n width: image.width(),\n height: image.height(),\n };\n}\n","/** A single frame rectangle in a sprite sheet. */\nexport interface SpriteFrame {\n /** Name/key of the frame. */\n name: string;\n /** X offset in the source texture (pixels). */\n x: number;\n /** Y offset in the source texture (pixels). */\n y: number;\n /** Width of the frame (pixels). */\n w: number;\n /** Height of the frame (pixels). */\n h: number;\n}\n\n/** A named animation sequence within a sprite sheet. */\nexport interface AnimationSequence {\n /** Sequence name (e.g. \"walk\", \"idle\"). */\n name: string;\n /** Indices into the SpriteSheet.frames array. */\n frameIndices: number[];\n /** Duration per frame in seconds. */\n frameDuration: number;\n /** Whether to loop the sequence. */\n loop: boolean;\n}\n\n/** Parsed sprite sheet data — pure data, no Skia dependency. */\nexport interface SpriteSheet {\n /** Ordered array of all frames. */\n frames: SpriteFrame[];\n /** Map from frame name to index in frames[]. */\n frameMap: Map<string, number>;\n /** Named animation sequences. */\n animations: Map<string, AnimationSequence>;\n}\n\n/** Create an empty sprite sheet. */\nexport function createSpriteSheet(): SpriteSheet {\n return {\n frames: [],\n frameMap: new Map(),\n animations: new Map(),\n };\n}\n\n// ----- TexturePacker JSON (hash format) -----\n\ninterface TPHashFrame {\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPHashJSON {\n frames: Record<string, TPHashFrame>;\n}\n\n/** Parse TexturePacker JSON hash format. */\nexport function parseTexturePackerHash(json: unknown): SpriteSheet {\n const data = json as TPHashJSON;\n const sheet = createSpriteSheet();\n const entries = Object.entries(data.frames);\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (!entry) continue;\n const [name, value] = entry;\n const f = value.frame;\n sheet.frames.push({ name, x: f.x, y: f.y, w: f.w, h: f.h });\n sheet.frameMap.set(name, i);\n }\n return sheet;\n}\n\n// ----- TexturePacker JSON (array format) -----\n\ninterface TPArrayFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPArrayJSON {\n frames: TPArrayFrame[];\n}\n\n/** Parse TexturePacker JSON array format. */\nexport function parseTexturePackerArray(json: unknown): SpriteSheet {\n const data = json as TPArrayJSON;\n const sheet = createSpriteSheet();\n for (let i = 0; i < data.frames.length; i++) {\n const entry = data.frames[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n return sheet;\n}\n\n// ----- Aseprite JSON -----\n\ninterface AsepriteFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n duration: number; // ms\n}\n\ninterface AsepriteTag {\n name: string;\n from: number;\n to: number;\n direction: string;\n}\n\ninterface AsepriteJSON {\n frames: AsepriteFrame[] | Record<string, AsepriteFrame>;\n meta?: {\n frameTags?: AsepriteTag[];\n };\n}\n\n/** Parse Aseprite JSON export. */\nexport function parseAseprite(json: unknown): SpriteSheet {\n const data = json as AsepriteJSON;\n const sheet = createSpriteSheet();\n\n // Aseprite can export frames as array or object\n const frameEntries: AsepriteFrame[] = Array.isArray(data.frames)\n ? data.frames\n : Object.values(data.frames);\n\n for (let i = 0; i < frameEntries.length; i++) {\n const entry = frameEntries[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n\n // Parse frame tags as animation sequences\n const tags = data.meta?.frameTags;\n if (tags) {\n for (const tag of tags) {\n const indices: number[] = [];\n if (tag.direction === 'reverse') {\n for (let i = tag.to; i >= tag.from; i--) {\n indices.push(i);\n }\n } else if (tag.direction === 'pingpong') {\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n for (let i = tag.to - 1; i > tag.from; i--) {\n indices.push(i);\n }\n } else {\n // \"forward\" or default\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n }\n\n // Use the first frame's duration as the uniform frame duration\n const firstFrame = frameEntries[tag.from];\n const durationMs = firstFrame?.duration ?? 100;\n\n sheet.animations.set(tag.name, {\n name: tag.name,\n frameIndices: indices,\n frameDuration: durationMs / 1000,\n loop: true,\n });\n }\n }\n\n return sheet;\n}\n\n/**\n * Add a custom animation sequence to a sprite sheet.\n */\nexport function addAnimation(\n sheet: SpriteSheet,\n name: string,\n frameIndices: number[],\n frameDuration: number,\n loop = true,\n): void {\n sheet.animations.set(name, { name, frameIndices, frameDuration, loop });\n}\n\n/** Get a frame by name. Returns undefined if not found. */\nexport function getFrame(sheet: SpriteSheet, name: string): SpriteFrame | undefined {\n const idx = sheet.frameMap.get(name);\n if (idx === undefined) return undefined;\n return sheet.frames[idx];\n}\n","import { Signal } from '@flare-engine/events';\nimport type { SpriteSheet } from './sprite-sheet.js';\nimport type { Texture } from './texture.js';\n\n/** Types of assets the manager can store. */\nexport type AssetType = 'texture' | 'spritesheet' | 'json' | 'binary';\n\n/** A single entry in an asset manifest. */\nexport interface ManifestEntry {\n /** Unique key to retrieve this asset. */\n key: string;\n /** Asset type. */\n type: AssetType;\n /** Path or URI to the asset. */\n path: string;\n}\n\n/** A load function provided by the platform to actually fetch+decode assets. */\nexport type AssetLoader = (entry: ManifestEntry) => Promise<Texture | SpriteSheet | unknown>;\n\n/**\n * AssetManager — loads, caches, and provides access to game assets.\n *\n * Platform-agnostic: the actual loading is delegated to an `AssetLoader`\n * function injected at construction. This allows Skia-dependent texture\n * loading to live in the React layer while keeping this module testable.\n */\nexport class AssetManager {\n /** Fires on each asset loaded with current progress (0-1). */\n readonly onProgress = new Signal<number>();\n\n /** Current loading progress 0-1. */\n progress = 0;\n\n private _assets = new Map<string, unknown>();\n private _loader: AssetLoader;\n\n constructor(loader: AssetLoader) {\n this._loader = loader;\n }\n\n /**\n * Load all assets in the manifest.\n * Resolves when all assets are loaded and cached.\n */\n async load(manifest: ManifestEntry[]): Promise<void> {\n if (manifest.length === 0) {\n this.progress = 1;\n this.onProgress.emit(1);\n return;\n }\n\n let loaded = 0;\n const total = manifest.length;\n\n const promises = manifest.map(async (entry) => {\n const asset = await this._loader(entry);\n this._assets.set(entry.key, asset);\n loaded++;\n this.progress = loaded / total;\n this.onProgress.emit(this.progress);\n });\n\n await Promise.all(promises);\n }\n\n /** Get a loaded asset by key. Returns undefined if not found. */\n get<T = unknown>(key: string): T | undefined {\n return this._assets.get(key) as T | undefined;\n }\n\n /** Check if an asset is loaded. */\n has(key: string): boolean {\n return this._assets.has(key);\n }\n\n /** Remove an asset from the cache. */\n unload(key: string): boolean {\n return this._assets.delete(key);\n }\n\n /** Clear all cached assets. */\n clear(): void {\n this._assets.clear();\n this.progress = 0;\n }\n}\n","import type { SkImageLike } from './texture.js';\n\n/** Opaque handle for a Skia SkData object. */\nexport interface SkDataLike {\n readonly __skData: unique symbol;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Injected by the caller so @flare-engine/assets stays runtime-agnostic.\n */\nexport interface SkiaImageDecodeModuleLike {\n Data: {\n fromBytes(bytes: Uint8Array): SkDataLike;\n };\n Image: {\n MakeImageFromEncoded(data: SkDataLike): SkImageLike | null;\n };\n}\n\n/**\n * Decode raw image bytes into a Skia SkImage.\n *\n * Returns null on failure — never throws. Callers are responsible for\n * handling null (e.g. falling back to a placeholder texture).\n */\nexport function decodeImage(\n Skia: SkiaImageDecodeModuleLike,\n bytes: Uint8Array,\n): SkImageLike | null {\n const data = Skia.Data.fromBytes(bytes);\n return Skia.Image.MakeImageFromEncoded(data);\n}\n","import { type SpriteFrame, type SpriteSheet, createSpriteSheet } from './sprite-sheet.js';\nimport type { SkImageLike } from './texture.js';\n\n/** One entry in a procedural atlas — a named colored rectangle. */\nexport interface ProceduralFrameSpec {\n /** Frame name (used as the SpriteFrame name for lookup). */\n name: string;\n /** Width in pixels. */\n w: number;\n /** Height in pixels. */\n h: number;\n /** Color as ARGB int (0xAARRGGBB). */\n color: number;\n}\n\n/** Options controlling atlas layout. */\nexport interface ProceduralAtlasOptions {\n /** Max atlas width before wrapping to a new row. Default 1024. */\n maxWidth?: number;\n /** Gap between frames in pixels. Default 0. */\n padding?: number;\n}\n\n/** Result of a procedural atlas build. */\nexport interface ProceduralAtlas {\n /** Backing Skia image with all rects drawn. */\n image: SkImageLike;\n /** SpriteSheet whose frames describe the rect positions. */\n sheet: SpriteSheet;\n /** Total atlas width in pixels. */\n width: number;\n /** Total atlas height in pixels. */\n height: number;\n}\n\n/** Opaque Skia color value — a Float32Array of length 4 (r, g, b, a in [0,1]). */\ntype SkColorLike = Float32Array;\n\n/** Narrow paint interface — only the setter we use. */\nexport interface SkPaintLike {\n setColor(color: SkColorLike): void;\n}\n\n/** Narrow rect interface — a rect value object passed to drawRect. */\nexport interface SkRectLike {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** Narrow canvas interface — only the method we use. */\nexport interface SkCanvasLike {\n drawRect(rect: SkRectLike, paint: SkPaintLike): void;\n}\n\n/** Narrow surface interface — getCanvas + snapshot. */\nexport interface SkSurfaceLike {\n getCanvas(): SkCanvasLike;\n makeImageSnapshot(): SkImageLike;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Declared locally so unit tests can supply a plain mock without pulling\n * in the full `@shopify/react-native-skia` surface.\n */\nexport interface SkiaAtlasModuleLike {\n Surface: { Make(width: number, height: number): SkSurfaceLike | null };\n Paint(): SkPaintLike;\n XYWHRect(x: number, y: number, w: number, h: number): SkRectLike;\n}\n\n/**\n * Build a flat atlas `SkImage` from a list of colored rectangles.\n *\n * Row-packs frames left-to-right until `maxWidth` is exceeded, then wraps\n * to a new row. Returns both the backing image and a `SpriteSheet` whose\n * frames match the packed positions, so consumers can look up frames by\n * name exactly as with a real `parseTexturePacker*` sheet.\n *\n * Useful for:\n * - bootstrapping gameplay before final art lands (replace with one\n * `parseTexturePackerHash` call once the real atlas arrives),\n * - engine tests / benchmarks that need a valid `SkImage` without\n * shipping any binary asset.\n *\n * **Canonical placeholder-atlas example (Phase 11.14):** `apps/pan-tvardowski`\n * ships a full \"shape atlas\" that draws every enemy / miniboss / boss / ship /\n * pickup as composed primitives onto an offscreen Skia surface, then wraps\n * the result in a `SpriteSheet` — see `apps/pan-tvardowski/src/shape-atlas.ts`.\n * That pattern (declarative `ShapeSpec` → `Skia` draw calls → `SpriteSheet`\n * with one named frame per shape) is the recommended way to build a\n * manifest-swappable placeholder atlas: when final art lands, drop the\n * shape draw-calls for `parseTexturePackerHash(jsonText)` with no other\n * code changes.\n */\nexport function createProceduralAtlas(\n Skia: SkiaAtlasModuleLike,\n frames: readonly ProceduralFrameSpec[],\n options: ProceduralAtlasOptions = {},\n): ProceduralAtlas {\n const maxWidth = options.maxWidth ?? 1024;\n const padding = options.padding ?? 0;\n\n const positions = layoutRows(frames, maxWidth, padding);\n const surface = Skia.Surface.Make(positions.width, positions.height);\n if (surface === null) {\n throw new Error(`Skia.Surface.Make returned null for ${positions.width}x${positions.height}`);\n }\n\n const canvas = surface.getCanvas();\n const paint = Skia.Paint();\n const color: SkColorLike = new Float32Array(4);\n\n const sheet = createSpriteSheet();\n\n for (let i = 0; i < frames.length; i++) {\n const spec = frames[i];\n const pos = positions.rects[i];\n if (spec === undefined || pos === undefined) continue;\n\n writeArgb(color, spec.color);\n paint.setColor(color);\n canvas.drawRect(Skia.XYWHRect(pos.x, pos.y, spec.w, spec.h), paint);\n\n const frame: SpriteFrame = {\n name: spec.name,\n x: pos.x,\n y: pos.y,\n w: spec.w,\n h: spec.h,\n };\n sheet.frames.push(frame);\n sheet.frameMap.set(spec.name, i);\n }\n\n return {\n image: surface.makeImageSnapshot(),\n sheet,\n width: positions.width,\n height: positions.height,\n };\n}\n\ninterface PackedPosition {\n x: number;\n y: number;\n}\n\ninterface PackedLayout {\n rects: PackedPosition[];\n width: number;\n height: number;\n}\n\nfunction layoutRows(\n frames: readonly ProceduralFrameSpec[],\n maxWidth: number,\n padding: number,\n): PackedLayout {\n const rects: PackedPosition[] = [];\n let x = 0;\n let y = 0;\n let rowHeight = 0;\n let atlasWidth = 0;\n\n for (const spec of frames) {\n if (x > 0 && x + spec.w > maxWidth) {\n y += rowHeight + padding;\n x = 0;\n rowHeight = 0;\n }\n rects.push({ x, y });\n x += spec.w + padding;\n if (spec.h > rowHeight) rowHeight = spec.h;\n if (x - padding > atlasWidth) atlasWidth = x - padding;\n }\n\n const atlasHeight = y + rowHeight;\n return {\n rects,\n width: atlasWidth > 0 ? atlasWidth : 1,\n height: atlasHeight > 0 ? atlasHeight : 1,\n };\n}\n\nfunction writeArgb(out: SkColorLike, argb: number): void {\n out[0] = ((argb >>> 16) & 0xff) / 255;\n out[1] = ((argb >>> 8) & 0xff) / 255;\n out[2] = (argb & 0xff) / 255;\n out[3] = ((argb >>> 24) & 0xff) / 255;\n}\n"],"mappings":";AA2BO,SAAS,cAAc,KAAa,OAA6B;AACtE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO,MAAM,MAAM;AAAA,IACnB,QAAQ,MAAM,OAAO;AAAA,EACvB;AACF;;;ACGO,SAAS,oBAAiC;AAC/C,SAAO;AAAA,IACL,QAAQ,CAAC;AAAA,IACT,UAAU,oBAAI,IAAI;AAAA,IAClB,YAAY,oBAAI,IAAI;AAAA,EACtB;AACF;AAaO,SAAS,uBAAuB,MAA4B;AACjE,QAAM,OAAO;AACb,QAAM,QAAQ,kBAAkB;AAChC,QAAM,UAAU,OAAO,QAAQ,KAAK,MAAM;AAC1C,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,QAAQ,QAAQ,CAAC;AACvB,QAAI,CAAC,MAAO;AACZ,UAAM,CAAC,MAAM,KAAK,IAAI;AACtB,UAAM,IAAI,MAAM;AAChB,UAAM,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,GAAG,EAAE,EAAE,CAAC;A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AAQ;AAClC,MAAI,CAAC,KAAM,SAAS,IAAK,OAAQ;AACjC,MAAI,CAAC,KAAK,OAAO,OAAQ;AACzB,MAAI,CAAC,KAAM,SAAS,KAAM,OAAQ;AACpC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/texture.ts","../src/sprite-sheet.ts","../src/asset-manager.ts","../src/decode-image.ts","../src/procedural-atlas.ts"],"sourcesContent":["/** Minimal interface for the Skia SkImage we wrap. */\nexport interface SkImageLike {\n width(): number;\n height(): number;\n readPixels(): Float32Array | Uint8Array | null;\n /**\n * Optional — present on GPU-backed SkImages returned by RN-Skia's\n * MakeOffscreen surfaces. Copies the texture into a CPU-raster image so it\n * can be safely sampled from a different GrDirectContext (e.g. the on-screen\n * Canvas). Must be called before the image crosses a context boundary.\n */\n makeNonTextureImage?(): SkImageLike;\n}\n\n/** A loaded texture wrapping a Skia SkImage. */\nexport interface Texture {\n /** Unique key for this texture in the asset manager. */\n readonly key: string;\n /** The underlying Skia SkImage. */\n readonly image: SkImageLike;\n /** Width in pixels. */\n readonly width: number;\n /** Height in pixels. */\n readonly height: number;\n}\n\n/** Create a Texture from a Skia SkImage. */\nexport function createTexture(key: string, image: SkImageLike): Texture {\n return {\n key,\n image,\n width: image.width(),\n height: image.height(),\n };\n}\n","/** A single frame rectangle in a sprite sheet. */\nexport interface SpriteFrame {\n /** Name/key of the frame. */\n name: string;\n /** X offset in the source texture (pixels). */\n x: number;\n /** Y offset in the source texture (pixels). */\n y: number;\n /** Width of the frame (pixels). */\n w: number;\n /** Height of the frame (pixels). */\n h: number;\n}\n\n/** A named animation sequence within a sprite sheet. */\nexport interface AnimationSequence {\n /** Sequence name (e.g. \"walk\", \"idle\"). */\n name: string;\n /** Indices into the SpriteSheet.frames array. */\n frameIndices: number[];\n /** Duration per frame in seconds. */\n frameDuration: number;\n /** Whether to loop the sequence. */\n loop: boolean;\n}\n\n/** Parsed sprite sheet data — pure data, no Skia dependency. */\nexport interface SpriteSheet {\n /** Ordered array of all frames. */\n frames: SpriteFrame[];\n /** Map from frame name to index in frames[]. */\n frameMap: Map<string, number>;\n /** Named animation sequences. */\n animations: Map<string, AnimationSequence>;\n}\n\n/** Create an empty sprite sheet. */\nexport function createSpriteSheet(): SpriteSheet {\n return {\n frames: [],\n frameMap: new Map(),\n animations: new Map(),\n };\n}\n\n// ----- TexturePacker JSON (hash format) -----\n\ninterface TPHashFrame {\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPHashJSON {\n frames: Record<string, TPHashFrame>;\n}\n\n/** Parse TexturePacker JSON hash format. */\nexport function parseTexturePackerHash(json: unknown): SpriteSheet {\n const data = json as TPHashJSON;\n const sheet = createSpriteSheet();\n const entries = Object.entries(data.frames);\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (!entry) continue;\n const [name, value] = entry;\n const f = value.frame;\n sheet.frames.push({ name, x: f.x, y: f.y, w: f.w, h: f.h });\n sheet.frameMap.set(name, i);\n }\n return sheet;\n}\n\n// ----- TexturePacker JSON (array format) -----\n\ninterface TPArrayFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPArrayJSON {\n frames: TPArrayFrame[];\n}\n\n/** Parse TexturePacker JSON array format. */\nexport function parseTexturePackerArray(json: unknown): SpriteSheet {\n const data = json as TPArrayJSON;\n const sheet = createSpriteSheet();\n for (let i = 0; i < data.frames.length; i++) {\n const entry = data.frames[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n return sheet;\n}\n\n// ----- Aseprite JSON -----\n\ninterface AsepriteFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n duration: number; // ms\n}\n\ninterface AsepriteTag {\n name: string;\n from: number;\n to: number;\n direction: string;\n}\n\ninterface AsepriteJSON {\n frames: AsepriteFrame[] | Record<string, AsepriteFrame>;\n meta?: {\n frameTags?: AsepriteTag[];\n };\n}\n\n/** Parse Aseprite JSON export. */\nexport function parseAseprite(json: unknown): SpriteSheet {\n const data = json as AsepriteJSON;\n const sheet = createSpriteSheet();\n\n // Aseprite can export frames as array or object\n const frameEntries: AsepriteFrame[] = Array.isArray(data.frames)\n ? data.frames\n : Object.values(data.frames);\n\n for (let i = 0; i < frameEntries.length; i++) {\n const entry = frameEntries[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n\n // Parse frame tags as animation sequences\n const tags = data.meta?.frameTags;\n if (tags) {\n for (const tag of tags) {\n const indices: number[] = [];\n if (tag.direction === 'reverse') {\n for (let i = tag.to; i >= tag.from; i--) {\n indices.push(i);\n }\n } else if (tag.direction === 'pingpong') {\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n for (let i = tag.to - 1; i > tag.from; i--) {\n indices.push(i);\n }\n } else {\n // \"forward\" or default\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n }\n\n // Use the first frame's duration as the uniform frame duration\n const firstFrame = frameEntries[tag.from];\n const durationMs = firstFrame?.duration ?? 100;\n\n sheet.animations.set(tag.name, {\n name: tag.name,\n frameIndices: indices,\n frameDuration: durationMs / 1000,\n loop: true,\n });\n }\n }\n\n return sheet;\n}\n\n/**\n * Add a custom animation sequence to a sprite sheet.\n */\nexport function addAnimation(\n sheet: SpriteSheet,\n name: string,\n frameIndices: number[],\n frameDuration: number,\n loop = true,\n): void {\n sheet.animations.set(name, { name, frameIndices, frameDuration, loop });\n}\n\n/** Get a frame by name. Returns undefined if not found. */\nexport function getFrame(sheet: SpriteSheet, name: string): SpriteFrame | undefined {\n const idx = sheet.frameMap.get(name);\n if (idx === undefined) return undefined;\n return sheet.frames[idx];\n}\n","import { Signal } from '@flare-engine/events';\nimport type { SpriteSheet } from './sprite-sheet.js';\nimport type { Texture } from './texture.js';\n\n/** Types of assets the manager can store. */\nexport type AssetType = 'texture' | 'spritesheet' | 'json' | 'binary';\n\n/** A single entry in an asset manifest. */\nexport interface ManifestEntry {\n /** Unique key to retrieve this asset. */\n key: string;\n /** Asset type. */\n type: AssetType;\n /** Path or URI to the asset. */\n path: string;\n}\n\n/** A load function provided by the platform to actually fetch+decode assets. */\nexport type AssetLoader = (entry: ManifestEntry) => Promise<Texture | SpriteSheet | unknown>;\n\n/**\n * AssetManager — loads, caches, and provides access to game assets.\n *\n * Platform-agnostic: the actual loading is delegated to an `AssetLoader`\n * function injected at construction. This allows Skia-dependent texture\n * loading to live in the React layer while keeping this module testable.\n */\nexport class AssetManager {\n /** Fires on each asset loaded with current progress (0-1). */\n readonly onProgress = new Signal<number>();\n\n /** Current loading progress 0-1. */\n progress = 0;\n\n private _assets = new Map<string, unknown>();\n private _loader: AssetLoader;\n\n constructor(loader: AssetLoader) {\n this._loader = loader;\n }\n\n /**\n * Load all assets in the manifest.\n * Resolves when all assets are loaded and cached.\n */\n async load(manifest: ManifestEntry[]): Promise<void> {\n if (manifest.length === 0) {\n this.progress = 1;\n this.onProgress.emit(1);\n return;\n }\n\n let loaded = 0;\n const total = manifest.length;\n\n const promises = manifest.map(async (entry) => {\n const asset = await this._loader(entry);\n this._assets.set(entry.key, asset);\n loaded++;\n this.progress = loaded / total;\n this.onProgress.emit(this.progress);\n });\n\n await Promise.all(promises);\n }\n\n /** Get a loaded asset by key. Returns undefined if not found. */\n get<T = unknown>(key: string): T | undefined {\n return this._assets.get(key) as T | undefined;\n }\n\n /** Check if an asset is loaded. */\n has(key: string): boolean {\n return this._assets.has(key);\n }\n\n /** Remove an asset from the cache. */\n unload(key: string): boolean {\n return this._assets.delete(key);\n }\n\n /** Clear all cached assets. */\n clear(): void {\n this._assets.clear();\n this.progress = 0;\n }\n}\n","import type { SkImageLike } from './texture.js';\n\n/** Opaque handle for a Skia SkData object. */\nexport interface SkDataLike {\n readonly __skData: unique symbol;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Injected by the caller so @flare-engine/assets stays runtime-agnostic.\n */\nexport interface SkiaImageDecodeModuleLike {\n Data: {\n fromBytes(bytes: Uint8Array): SkDataLike;\n };\n Image: {\n MakeImageFromEncoded(data: SkDataLike): SkImageLike | null;\n };\n}\n\n/**\n * Decode raw image bytes into a Skia SkImage.\n *\n * Returns null on failure — never throws. Callers are responsible for\n * handling null (e.g. falling back to a placeholder texture).\n */\nexport function decodeImage(\n Skia: SkiaImageDecodeModuleLike,\n bytes: Uint8Array,\n): SkImageLike | null {\n const data = Skia.Data.fromBytes(bytes);\n return Skia.Image.MakeImageFromEncoded(data);\n}\n","import { type SpriteFrame, type SpriteSheet, createSpriteSheet } from './sprite-sheet.js';\nimport type { SkImageLike } from './texture.js';\n\n/** One entry in a procedural atlas — a named colored rectangle. */\nexport interface ProceduralFrameSpec {\n /** Frame name (used as the SpriteFrame name for lookup). */\n name: string;\n /** Width in pixels. */\n w: number;\n /** Height in pixels. */\n h: number;\n /** Color as ARGB int (0xAARRGGBB). */\n color: number;\n}\n\n/** Options controlling atlas layout. */\nexport interface ProceduralAtlasOptions {\n /** Max atlas width before wrapping to a new row. Default 1024. */\n maxWidth?: number;\n /** Gap between frames in pixels. Default 0. */\n padding?: number;\n}\n\n/** Result of a procedural atlas build. */\nexport interface ProceduralAtlas {\n /** Backing Skia image with all rects drawn. */\n image: SkImageLike;\n /** SpriteSheet whose frames describe the rect positions. */\n sheet: SpriteSheet;\n /** Total atlas width in pixels. */\n width: number;\n /** Total atlas height in pixels. */\n height: number;\n}\n\n/** Opaque Skia color value — a Float32Array of length 4 (r, g, b, a in [0,1]). */\ntype SkColorLike = Float32Array;\n\n/** Narrow paint interface — only the setter we use. */\nexport interface SkPaintLike {\n setColor(color: SkColorLike): void;\n}\n\n/** Narrow rect interface — a rect value object passed to drawRect. */\nexport interface SkRectLike {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** Narrow canvas interface — only the method we use. */\nexport interface SkCanvasLike {\n drawRect(rect: SkRectLike, paint: SkPaintLike): void;\n}\n\n/** Narrow surface interface — getCanvas + snapshot. */\nexport interface SkSurfaceLike {\n getCanvas(): SkCanvasLike;\n makeImageSnapshot(): SkImageLike;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Declared locally so unit tests can supply a plain mock without pulling\n * in the full `@shopify/react-native-skia` surface.\n */\nexport interface SkiaAtlasModuleLike {\n Surface: { Make(width: number, height: number): SkSurfaceLike | null };\n Paint(): SkPaintLike;\n XYWHRect(x: number, y: number, w: number, h: number): SkRectLike;\n}\n\n/**\n * Build a flat atlas `SkImage` from a list of colored rectangles.\n *\n * Row-packs frames left-to-right until `maxWidth` is exceeded, then wraps\n * to a new row. Returns both the backing image and a `SpriteSheet` whose\n * frames match the packed positions, so consumers can look up frames by\n * name exactly as with a real `parseTexturePacker*` sheet.\n *\n * Useful for:\n * - bootstrapping gameplay before final art lands (replace with one\n * `parseTexturePackerHash` call once the real atlas arrives),\n * - engine tests / benchmarks that need a valid `SkImage` without\n * shipping any binary asset.\n *\n * **Canonical placeholder-atlas example (Phase 11.14):** Pan Tvardowski\n * (github.com/grzott/Pan-Tvardowski) ships a full \"shape atlas\" that draws\n * every enemy / miniboss / boss / ship / pickup as composed primitives onto\n * an offscreen Skia surface, then wraps the result in a `SpriteSheet` — see\n * `src/shape-atlas.ts` in that repo.\n * That pattern (declarative `ShapeSpec` → `Skia` draw calls → `SpriteSheet`\n * with one named frame per shape) is the recommended way to build a\n * manifest-swappable placeholder atlas: when final art lands, drop the\n * shape draw-calls for `parseTexturePackerHash(jsonText)` with no other\n * code changes.\n */\nexport function createProceduralAtlas(\n Skia: SkiaAtlasModuleLike,\n frames: readonly ProceduralFrameSpec[],\n options: ProceduralAtlasOptions = {},\n): ProceduralAtlas {\n const maxWidth = options.maxWidth ?? 1024;\n const padding = options.padding ?? 0;\n\n const positions = layoutRows(frames, maxWidth, padding);\n const surface = Skia.Surface.Make(positions.width, positions.height);\n if (surface === null) {\n throw new Error(`Skia.Surface.Make returned null for ${positions.width}x${positions.height}`);\n }\n\n const canvas = surface.getCanvas();\n const paint = Skia.Paint();\n const color: SkColorLike = new Float32Array(4);\n\n const sheet = createSpriteSheet();\n\n for (let i = 0; i < frames.length; i++) {\n const spec = frames[i];\n const pos = positions.rects[i];\n if (spec === undefined || pos === undefined) continue;\n\n writeArgb(color, spec.color);\n paint.setColor(color);\n canvas.drawRect(Skia.XYWHRect(pos.x, pos.y, spec.w, spec.h), paint);\n\n const frame: SpriteFrame = {\n name: spec.name,\n x: pos.x,\n y: pos.y,\n w: spec.w,\n h: spec.h,\n };\n sheet.frames.push(frame);\n sheet.frameMap.set(spec.name, i);\n }\n\n return {\n image: surface.makeImageSnapshot(),\n sheet,\n width: positions.width,\n height: positions.height,\n };\n}\n\ninterface PackedPosition {\n x: number;\n y: number;\n}\n\ninterface PackedLayout {\n rects: PackedPosition[];\n width: number;\n height: number;\n}\n\nfunction layoutRows(\n frames: readonly ProceduralFrameSpec[],\n maxWidth: number,\n padding: number,\n): PackedLayout {\n const rects: PackedPosition[] = [];\n let x = 0;\n let y = 0;\n let rowHeight = 0;\n let atlasWidth = 0;\n\n for (const spec of frames) {\n if (x > 0 && x + spec.w > maxWidth) {\n y += rowHeight + padding;\n x = 0;\n rowHeight = 0;\n }\n rects.push({ x, y });\n x += spec.w + padding;\n if (spec.h > rowHeight) rowHeight = spec.h;\n if (x - padding > atlasWidth) atlasWidth = x - padding;\n }\n\n const atlasHeight = y + rowHeight;\n return {\n rects,\n width: atlasWidth > 0 ? atlasWidth : 1,\n height: atlasHeight > 0 ? atlasHeight : 1,\n };\n}\n\nfunction writeArgb(out: SkColorLike, argb: number): void {\n out[0] = ((argb >>> 16) & 0xff) / 255;\n out[1] = ((argb >>> 8) & 0xff) / 255;\n out[2] = (argb & 0xff) / 255;\n out[3] = ((argb >>> 24) & 0xff) / 255;\n}\n"],"mappings":";AA2BO,SA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,UAAU;AAAA,IACjB,QAAQ,UAAU;AAAA,EACpB;AACF;AAaA,SAAS,WACP,QACA,UACA,SACc;AACd,QAAM,QAA0B,CAAC;AACjC,MAAI,IAAI;AACR,MAAI,IAAI;AACR,MAAI,YAAY;AAChB,MAAI,aAAa;AAEjB,aAAW,QAAQ,QAAQ;AACzB,QAAI,IAAI,KAAK,IAAI,KAAK,IAAI,UAAU;AAClC,WAAK,YAAY;AACjB,UAAI;AACJ,kBAAY;AAAA,IACd;AACA,UAAM,KAAK,EAAE,GAAG,EAAE,CAAC;AACnB,SAAK,KAAK,IAAI;AACd,QAAI,KAAK,IAAI,UAAW,aAAY,KAAK;AACzC,QAAI,IAAI,UAAU,WAAY,cAAa,IAAI;AAAA,EACjD;AAEA,QAAM,cAAc,IAAI;AACxB,SAAO;AAAA,IACL;AAAA,IACA,OAAO,aAAa,IAAI,aAAa;AAAA,IACrC,QAAQ,cAAc,IAAI,cAAc;AAAA,EAC1C;AACF;AAEA,SAAS,UAAU,KAAkB,MAAoB;AACvD,MAAI,CAAC,KAAM,SAAS,KAAM,OAAQ;AAClC,MAAI,CAAC,KAAM,SAAS,IAAK,OAAQ;AACjC,MAAI,CAAC,KAAK,OAAO,OAAQ;AACzB,MAAI,CAAC,KAAM,SAAS,KAAM,OAAQ;AACpC;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flare-engine/assets",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Asset loading, sprite sheet parsing",
|
|
5
5
|
"keywords": ["flare-engine", "assets", "sprite-sheet", "loader"],
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,8 +32,8 @@
|
|
|
32
32
|
"typecheck": "tsc --noEmit"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@flare-engine/core": "^0.
|
|
36
|
-
"@flare-engine/events": "^0.
|
|
35
|
+
"@flare-engine/core": "^0.2.0",
|
|
36
|
+
"@flare-engine/events": "^0.2.0"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
39
|
"@shopify/react-native-skia": ">=1.0.0"
|