@flare-engine/react 0.4.8 → 0.4.11
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 +2 -2
- package/dist/index.d.mts +10 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +10 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +83 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +83 -7
- package/dist/index.mjs.map +1 -1
- package/package.json +22 -11
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["createContext","createContext","useContext","createFrameRenderer","Skia","useContext","SafeAreaInsetsContext","useCanvasRef","useState","PixelRatio","Platform","useSharedValue","useRef","useMemo","GameLoop","World","Camera2D","InputManager","AudioManager","AssetManager","SceneManager","Renderer","SpriteBatch","Position","Sprite","createRenderSystem","useCallback","styles","Image","RuntimeShader","ImageShader","Shader","Rect","View","returnTrue","Canvas","StyleSheet","FilterMode","MipmapMode","useContext","useState","useRef","useCallback","View","styles","StyleSheet","useState","useRef","easeOutCubic","Skia","useRef","createButtonState","useCallback","View","styles","StyleSheet","useRef","createJoystickState","useState","useCallback","View","StyleSheet"],"sources":["../src/game-context.ts","../src/safe-area.ts","../src/scene-texture.ts","../src/skia-bridge.ts","../src/game-view.tsx","../src/hooks.ts","../src/loading-screen.tsx","../src/overlay-hooks.ts","../src/skia-atlas.ts","../src/virtual-button.tsx","../src/virtual-joystick.tsx"],"sourcesContent":["import type { AssetManager } from '@flare-engine/assets';\nimport type { AudioManager } from '@flare-engine/audio';\nimport type { GameLoop } from '@flare-engine/core';\nimport type { World } from '@flare-engine/ecs';\nimport type { InputManager } from '@flare-engine/input';\nimport type { Camera2D, Renderer, SpriteBatch } from '@flare-engine/render';\nimport type { SceneManager } from '@flare-engine/scene';\nimport { createContext } from 'react';\n\n/** The value exposed via GameContext. */\nexport interface GameContextValue {\n /** ECS world. */\n world: World;\n /** Primary 2D camera. */\n camera: Camera2D;\n /** Input manager (pointer, touches). */\n input: InputManager;\n /** Audio manager. */\n audio: AudioManager;\n /** Asset manager. */\n assets: AssetManager;\n /** Scene manager. */\n scenes: SceneManager;\n /** Game loop. */\n loop: GameLoop;\n /** Frame renderer (owns the draw phase). */\n renderer: Renderer;\n /** Sprite batch — queue `draw()` calls from systems or custom logic. */\n batch: SpriteBatch;\n}\n\n/**\n * React context that provides access to core game objects.\n * Null if accessed outside a <GameView>.\n */\nexport const GameContext = createContext<GameContextValue | null>(null);\n","import { createContext, useContext } from 'react';\n\nexport interface SafeArea {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\nexport const SafeAreaContext = createContext<SafeArea | null>(null);\n\nexport function useSafeArea(): SafeArea {\n const value = useContext(SafeAreaContext);\n if (value === null) {\n throw new Error('useSafeArea must be used inside a <GameView>');\n }\n return value;\n}\n","import type { SkImageLike } from '@flare-engine/assets';\n\n/**\n * Structural offscreen surface — the subset `GameView`'s scene capture needs.\n * Declared locally so this module does not depend on RN-Skia's concrete types.\n */\nexport interface SceneSurfaceLike<TImage = SkImageLike> {\n getCanvas(): SceneSurfaceCanvasLike;\n makeImageSnapshot(): TImage;\n flush(): void;\n}\n\n/** The canvas subset used when capturing a frame's picture. */\nexport interface SceneSurfaceCanvasLike {\n drawPicture(picture: unknown): void;\n}\n\n/** Structural Skia module — only the offscreen-surface factory is needed. */\nexport interface SceneSurfaceModuleLike<TImage = SkImageLike> {\n Surface: {\n MakeOffscreen(width: number, height: number): SceneSurfaceLike<TImage> | null;\n };\n}\n\n/** A size-keyed offscreen surface holder. */\nexport interface SceneSurfaceCache<TImage = SkImageLike> {\n /**\n * The surface for this viewport size, allocating only when the size actually\n * changed. Returns null for a zero-sized viewport, or when Skia refuses the\n * allocation.\n */\n acquire(width: number, height: number): SceneSurfaceLike<TImage> | null;\n /** Release the live surface. Safe to call repeatedly. */\n dispose(): void;\n}\n\n/**\n * `Symbol.dispose` is not in this project's ES2022 lib, so the well-known\n * symbol is looked up at runtime instead of written as a computed key.\n */\nconst DISPOSE = (Symbol as unknown as { dispose?: symbol }).dispose;\n\nfunction releaseSkiaObject(target: unknown): void {\n if (DISPOSE === undefined || target === null || target === undefined) return;\n const disposer = (target as Record<symbol, unknown>)[DISPOSE];\n if (typeof disposer === 'function') {\n (disposer as () => void).call(target);\n }\n}\n\n/**\n * Reuse one offscreen surface across frames instead of allocating per frame.\n *\n * On **web** this is a correctness requirement, not an optimisation. RN-Skia's\n * web `MakeOffscreen` builds a fresh `OffscreenCanvas` and a fresh WebGL\n * context on every call and releases neither; Chrome caps a page at 16 live\n * WebGL contexts and evicts the oldest, which is the on-screen `<Canvas>`.\n * A per-frame allocation therefore kills the visible canvas within ~16 frames\n * while the game loop keeps running — the app looks alive and paints nothing.\n * Measured and written up in docs/plans/web-target-2026-08.md §12.\n */\nexport function createSceneSurfaceCache<TImage>(\n Skia: SceneSurfaceModuleLike<TImage>,\n): SceneSurfaceCache<TImage> {\n let surface: SceneSurfaceLike<TImage> | null = null;\n let currentWidth = 0;\n let currentHeight = 0;\n\n const dispose = (): void => {\n if (surface === null) return;\n releaseSkiaObject(surface);\n surface = null;\n currentWidth = 0;\n currentHeight = 0;\n };\n\n return {\n acquire(width: number, height: number): SceneSurfaceLike<TImage> | null {\n if (width <= 0 || height <= 0) return null;\n if (surface !== null && currentWidth === width && currentHeight === height) {\n return surface;\n }\n dispose();\n const next = Skia.Surface.MakeOffscreen(width, height);\n if (next === null) return null;\n surface = next;\n currentWidth = width;\n currentHeight = height;\n return surface;\n },\n dispose,\n };\n}\n\n/** A snapshot that can be detached from its GL context (RN-Skia web SkImage). */\ninterface DetachableImage<TImage> {\n makeNonTextureImage?(): TImage;\n}\n\n/** Per-frame scene capture over a reused surface. */\nexport interface SceneCapture<TImage> {\n /**\n * Draw `picture` into the reused surface and return an image detached from\n * that surface's GL context. Returns null for a zero-sized viewport.\n */\n capture(picture: unknown, width: number, height: number): TImage | null;\n /** Release the surface and the frame image still held. */\n dispose(): void;\n}\n\n/**\n * Options for `createSceneCapture`.\n *\n * `nonTextureImage` defaults to `true` (web semantics: call\n * `makeNonTextureImage()` to copy the snapshot off the surface's GL context so\n * the on-screen canvas can sample it).\n *\n * **This factory is web-only since XR-1c.** An earlier revision said the\n * snapshot \"is a true copy on native\", so `false` was safe there. That is\n * wrong: the native snapshot is GPU-backed and belongs to whichever context\n * created the surface. What actually makes it sampleable is building the\n * surface on the **UI thread**, which `game-view.tsx` does through\n * `scheduleOnUI`, not through a call into this module. Passing `false` here on native\n * yields a black frame; passing `true` fixes it only by forcing a per-frame\n * GPU→CPU readback. Verified on a Pixel 7 — external-review-2026-08.md §11.4b.\n *\n * `retentionDepth` defaults to 3 — the web-measured minimum, and the only\n * platform this runs on.\n */\nexport interface SceneCaptureOptions {\n nonTextureImage?: boolean;\n retentionDepth?: number;\n}\n\n/**\n * Capture the scene into a reused offscreen surface, releasing Skia objects as\n * it goes.\n *\n * Two leaks have to be avoided here, and both were measured in a browser\n * (docs/plans/web-target-2026-08.md §12):\n *\n * 1. **Per-frame surfaces.** RN-Skia's web `MakeOffscreen` builds an\n * `OffscreenCanvas` + WebGL context per call and releases neither; Chrome\n * caps a page at 16 live contexts and evicts the on-screen canvas. Hence the\n * surface cache.\n * 2. **Per-frame images.** `makeNonTextureImage()` reads the whole viewport back\n * into the wasm heap. Leaving old CPU images unreleased exhausts that heap.\n * A single-slot release strategy is not enough: RN-Skia's web `<Canvas>`\n * paints on its own rAF, which fires *after* the capture, so the image handed\n * to React on frame N is still in use when frame N+1 runs. Releasing it\n * immediately causes `BindingError: Cannot pass deleted object as a pointer of\n * type Image const*` from `JsiSkImage.width` every frame and a blank canvas.\n * Measured at 2560×1215 / Chrome (WEB-3):\n * hold=1 (one slot — what shipped at WEB-2) → blank, BindingError every frame\n * hold=2 → blank\n * hold=3 → 1378 frames, zero errors\n * A FIFO ring of depth 3 is the measured minimum.\n *\n * The snapshot is released as soon as it has been copied. Frame images are\n * released once the ring exceeds depth 3, ensuring the canvas's rAF always has\n * a live image to paint from.\n */\n\nexport function createSceneCapture<TImage>(\n Skia: SceneSurfaceModuleLike<TImage>,\n opts?: SceneCaptureOptions,\n): SceneCapture<TImage> {\n const useNonTexture = opts?.nonTextureImage ?? true;\n const retentionDepth = opts?.retentionDepth ?? 3;\n const surfaces = createSceneSurfaceCache(Skia);\n const ring: TImage[] = [];\n\n return {\n capture(picture: unknown, width: number, height: number): TImage | null {\n const surface = surfaces.acquire(width, height);\n if (surface === null) return null;\n\n surface.getCanvas().drawPicture(picture);\n surface.flush();\n\n const snapshot = surface.makeImageSnapshot();\n const detachable = snapshot as DetachableImage<TImage>;\n const detached =\n useNonTexture && detachable.makeNonTextureImage\n ? detachable.makeNonTextureImage()\n : snapshot;\n\n if (detached !== snapshot) releaseSkiaObject(snapshot);\n ring.push(detached);\n if (ring.length > retentionDepth) {\n releaseSkiaObject(ring.shift()!);\n }\n return detached;\n },\n dispose(): void {\n for (const img of ring) {\n releaseSkiaObject(img);\n }\n ring.length = 0;\n surfaces.dispose();\n },\n };\n}\n","import type { SkImageLike } from '@flare-engine/assets';\nimport {\n createFrameRenderer,\n type FrameRenderer,\n type FrameRendererCompiledPass,\n type FrameRendererModule,\n type FrameRendererPostFxChain,\n type FrameRendererPostFxDescriptor,\n type FrameRendererPostFxRuntime,\n type SpriteDrawCommand,\n} from '@flare-engine/render';\nimport type { SkColor, SkImage, SkImageFilter, SkRuntimeEffect } from '@shopify/react-native-skia';\n\n/** Structural canvas — minimal subset needed for offscreen rendering. */\nexport interface SkOffscreenCanvasLike {\n drawPicture(picture: unknown): void;\n drawImageRect(image: unknown, src: unknown, dst: unknown, paint: unknown): void;\n drawRect(rect: unknown, paint: unknown): void;\n clear(color: unknown): void;\n}\n\n/** Structural canvas surface — minimal subset needed for offscreen capture. */\nexport interface SkSurfaceLike {\n getCanvas(): SkOffscreenCanvasLike;\n makeImageSnapshot(): SkImageLike;\n /** Force queued draws to execute. Required for GPU-backed surfaces before\n * makeImageSnapshot is called, otherwise the snapshot may capture\n * uninitialized texture content. See Skia's SkSurface.flush docs. */\n flush(): void;\n}\n\n/**\n * A single post-processing pass descriptor built by `buildPostFxPasses`.\n * GameView maps each descriptor to a `<RuntimeShader>` image filter, or to a\n * nested `<Shader>` when a pass carries `children` (see that field).\n */\nexport interface PostFxPassDescriptor {\n /** Stable id, used as React key. */\n readonly id: string;\n /** The compiled SkRuntimeEffect passed as `<RuntimeShader source={…}/>`. */\n readonly source: SkRuntimeEffect;\n /**\n * Uniform map keyed by SkSL uniform name. Vector uniforms are `number[]`\n * whose length equals `columns * rows`; scalar uniforms are `number`.\n * Built by zipping `shader.getUniformName(i)` → sliced Float32Array values.\n */\n readonly uniforms: Record<string, number | readonly number[]>;\n /**\n * Extra sampler children beyond the implicit scene sampler, in SkSL\n * declaration order with `src` excluded. Empty for every built-in effect\n * except color-grading-lut (its LUT image). RN-Skia's `<RuntimeShader>`\n * image filter cannot bind them — it calls `MakeRuntimeShader(rtb, null,\n * null)`, source only — so GameView renders a pass with children, and every\n * pass before it, as a nested `<Shader>` chain whose children are bound\n * positionally: `src` first, then one `<ImageShader>` per entry here.\n */\n readonly children: readonly SkImage[];\n}\n\n/**\n * Take a snapshot of `surface` and detach it from the GPU context so it can\n * be safely sampled from a different GrDirectContext (e.g. the on-screen\n * Canvas). RN-Skia's MakeOffscreen allocates a private Gr context per\n * surface; without this step Skia silently renders black when the texture is\n * read from any other context.\n *\n * Calls `makeNonTextureImage()` when available (RN-Skia ≥ 0.1 on device).\n * Falls back to the raw snapshot when the method is absent (CPU surfaces,\n * test mocks) — no behavioural change in those paths.\n */\nfunction detachSnapshot(surface: SkSurfaceLike): SkImageLike {\n const snap = surface.makeImageSnapshot();\n if (typeof snap.makeNonTextureImage === 'function') {\n return snap.makeNonTextureImage();\n }\n return snap;\n}\n\n/** A single axis-aligned rectangle shape to draw into an offscreen surface. */\nexport interface ShapeRect {\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n /** ARGB packed integer: 0xAARRGGBB */\n readonly color: number;\n}\n\n/** Options for `renderShapesToImage`. */\nexport interface RenderShapesOpts {\n readonly width: number;\n readonly height: number;\n /** ARGB packed integer: 0xAARRGGBB */\n readonly clearColor: number;\n readonly shapes: readonly ShapeRect[];\n}\n\n/**\n * Narrow view of the Skia module — only the factories the bridge needs.\n * Declared as its own type so tests can pass a plain mock without pulling\n * in the full `@shopify/react-native-skia` surface.\n *\n * Extends `FrameRendererModule` from `@flare-engine/render` with the\n * native Surface and ImageFilter that are not needed in render-web.\n */\nexport type SkiaModuleLike = FrameRendererModule & {\n RuntimeEffect?: { Make(sksl: string): SkRuntimeEffect | null };\n Surface?: {\n Make(width: number, height: number): SkSurfaceLike | null;\n MakeOffscreen?(width: number, height: number): SkSurfaceLike | null;\n };\n /** Optional — present on device builds; absent in CPU/test mocks (drop-shadow falls back to the default paint). */\n ImageFilter?: {\n MakeDropShadow(\n dx: number,\n dy: number,\n sigmaX: number,\n sigmaY: number,\n color: SkColor,\n input: SkImageFilter | null,\n ): SkImageFilter;\n };\n};\n\n/**\n * A single compiled postfx pass descriptor produced by the runtime.\n * Re-exported from render's FrameRendererCompiledPass for consumer compatibility.\n */\nexport type CompiledPassLike = FrameRendererCompiledPass;\n\n/**\n * Minimal structural view of a PostFxRuntime that the bridge needs.\n * Re-exported from render's FrameRendererPostFxRuntime for consumer compatibility.\n */\nexport type PostFxRuntimeLike = FrameRendererPostFxRuntime;\n\n/** Minimal structural view of an EffectChain the bridge needs. */\nexport type PostFxChainLike = FrameRendererPostFxChain;\n\n/**\n * Frame renderer that bridges a `SpriteBatch` to a Skia `<Picture>`.\n * The implementation lives in `@flare-engine/render` (`createFrameRenderer`);\n * this interface narrows the return type for native-Skia consumers.\n */\nexport type SkiaFrameRenderer = FrameRenderer;\n\n/**\n * Create a `SkiaFrameRenderer`.\n *\n * `Skia` is passed in (rather than imported) so unit tests can supply a\n * mock. Production code constructs this once inside `<GameView>` using the\n * real `Skia` import from `@shopify/react-native-skia`.\n *\n * Delegates to `createFrameRenderer` from `@flare-engine/render` — the\n * frame-renderer body is backend-neutral and shared with render-web.\n */\nexport function createSkiaFrameRenderer(Skia: SkiaModuleLike): SkiaFrameRenderer {\n return createFrameRenderer(Skia);\n}\n\n// Scratch buffer for ARGB → RGBA-float unpacking in renderShapesToImage.\n// Allocated once per call (not module-level) so concurrent callers are safe.\n// Hot paths inside createSkiaFrameRenderer use their own pre-allocated buffers.\n\n/**\n * Render a list of solid rectangles into a fresh offscreen surface and return\n * the resulting image snapshot. Returns `null` if `Surface` factory is absent or\n * fails. The surface is not cached — callers that need reuse should cache the\n * returned image themselves.\n */\nexport function renderShapesToImage(\n skia: SkiaModuleLike,\n opts: RenderShapesOpts,\n): SkImageLike | null {\n if (skia.Surface === undefined) return null;\n const surface = skia.Surface.Make(opts.width, opts.height);\n if (surface === null) return null;\n\n const scratch = new Float32Array(4);\n const canvas = surface.getCanvas();\n\n unpackArgb(scratch, opts.clearColor);\n canvas.clear(scratch);\n\n const paint = skia.Paint();\n for (const shape of opts.shapes) {\n unpackArgb(scratch, shape.color);\n if (paint.setColor) paint.setColor(scratch);\n const rect = skia.XYWHRect(shape.x, shape.y, shape.w, shape.h);\n canvas.drawRect(rect, paint);\n }\n\n return detachSnapshot(surface);\n}\n\n/** Unpack a 0xAARRGGBB integer into a Float32Array [r, g, b, a] in 0..1 range. */\nfunction unpackArgb(out: Float32Array, 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\n// Re-export the PostFxPassDescriptor shape for GameView consumers.\n// The type is defined above in this file so it carries the concrete SkRuntimeEffect/SkImage\n// types that GameView needs — unlike the generic FrameRendererPostFxDescriptor from render.\n// Alias for clarity at call-sites.\nexport type { FrameRendererPostFxDescriptor, SpriteDrawCommand };\n","import type { AssetLoader } from '@flare-engine/assets';\nimport { AssetManager } from '@flare-engine/assets';\nimport { AudioManager } from '@flare-engine/audio';\nimport { GameLoop } from '@flare-engine/core';\nimport { Position, World } from '@flare-engine/ecs';\nimport { InputManager } from '@flare-engine/input';\nimport { Camera2D, createRenderSystem, Renderer, Sprite, SpriteBatch } from '@flare-engine/render';\nimport { SceneManager } from '@flare-engine/scene';\nimport type { CanvasRef, SkImage, SkPicture, SkSurface } from '@shopify/react-native-skia';\nimport {\n Canvas,\n FilterMode,\n Image,\n ImageShader,\n MipmapMode,\n Rect,\n RuntimeShader,\n Shader,\n Skia,\n useCanvasRef,\n} from '@shopify/react-native-skia';\nimport type React from 'react';\nimport { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport type { GestureResponderEvent, LayoutChangeEvent, ViewStyle } from 'react-native';\nimport { PixelRatio, Platform, StyleSheet, View } from 'react-native';\nimport { type SharedValue, useSharedValue } from 'react-native-reanimated';\nimport { SafeAreaInsetsContext } from 'react-native-safe-area-context';\nimport { scheduleOnUI } from 'react-native-worklets';\nimport { GameContext, type GameContextValue } from './game-context.js';\nimport { type SafeArea, SafeAreaContext } from './safe-area.js';\nimport { createSceneCapture, type SceneCapture } from './scene-texture.js';\nimport { createSkiaFrameRenderer, type PostFxPassDescriptor } from './skia-bridge.js';\n\n/**\n * Capture the frame's picture into an offscreen surface **on the UI thread**.\n *\n * The thread is the entire point, and getting it wrong is invisible to every\n * test in this repo. RN-Skia's own `usePictureAsTexture` does exactly this work\n * inside `runOnUI` (`external/reanimated/textures.ts`), and it must: a surface\n * built on the JS thread belongs to a different GL context than the on-screen\n * `<Canvas>`, so the `<Image>` samples nothing and the app renders a black\n * frame while the game loop runs happily. Building the surface here — same\n * thread, same context as the canvas that samples it — is what makes the\n * snapshot drawable without a `makeNonTextureImage()` GPU→CPU readback.\n *\n * Verified on device (Pixel 7 / Android 17): JS-thread capture → black canvas;\n * this path → renders. See external-review-2026-08.md §11.4b.\n *\n * The surface is cached across frames in a shared value rather than rebuilt per\n * frame (RN-Skia rebuilds it every call; that is NEW-2). `surfaceKey` packs the\n * pixel size so a viewport change reallocates exactly once.\n */\nconst captureSceneOnUI = (\n target: SharedValue<SkImage | null>,\n surfaceSV: SharedValue<SkSurface | null>,\n surfaceKey: SharedValue<number>,\n picture: SkPicture,\n w: number,\n h: number,\n): void => {\n 'worklet';\n const key = w * 65536 + h;\n if (surfaceSV.value === null || surfaceKey.value !== key) {\n surfaceSV.value = Skia.Surface.MakeOffscreen(w, h);\n surfaceKey.value = key;\n }\n const surface = surfaceSV.value;\n if (surface === null) return;\n surface.getCanvas().drawPicture(picture);\n surface.flush();\n target.value = surface.makeImageSnapshot();\n};\n\n/** Render hook invoked during the frame — receives the game context and\n * the active Skia canvas for direct draw calls. Hooks run between\n * `renderer.applyCamera()` and `renderer.end()`, so the camera transform\n * is already applied. */\nexport type RenderHook = (ctx: GameContextValue, canvas: unknown) => void;\n\n/** Render hook for post-processing passes. Receives the game context, the\n * active Skia canvas, and the `SkiaFrameRenderer` bridge so the hook can\n * call `bridge.setPostFxBinding(runtime, chain)` to register the runtime\n * and chain for the current frame.\n * `bridge` is `null` only on platforms where no Skia renderer was created\n * (future web fallback). */\nexport type PostFxRenderHook = (\n ctx: GameContextValue,\n canvas: unknown,\n bridge: import('./skia-bridge.js').SkiaFrameRenderer | null,\n) => void;\n\n/** Configuration passed to <GameView>. */\nexport interface GameConfig {\n /** Fixed timestep in seconds (default 1/60). */\n fixedDt?: number;\n /** Maximum dt cap in seconds (default 0.25). */\n maxDt?: number;\n /** Background clear color as 32-bit ARGB int (default 0xFF000000). */\n clearColor?: number;\n /** Asset loader function — injected into AssetManager at construction. */\n assetLoader?: AssetLoader;\n /** Called after camera transform and before the sprite render system.\n * Intended for tilemap / background layer rendering. */\n onRenderBackground?: RenderHook;\n /** Called after the sprite batch has been flushed, before `renderer.end()`.\n * Receives the bridge as 3rd arg so the hook can call\n * `bridge.setPostFxBinding(runtime, chain)` to register the postfx runtime\n * and chain for the current frame. */\n onRenderPostFx?: PostFxRenderHook;\n /**\n * Promote the underlying Skia surface from a TextureView (default) to a\n * SurfaceView on Android. With `opaque: true`, SurfaceView paints in a\n * separate compositing layer below the regular RN view tree, which lets\n * full-screen RN overlays (HUDs, menus) render on top without needing\n * elevation/zIndex tricks.\n *\n * Without this, RN-Skia's TextureView can clip overlapping full-screen\n * RN siblings on certain Android devices/Fabric configurations.\n *\n * Implies the canvas content is opaque — the clearColor's alpha must be\n * fully opaque (0xFF), which the default `0xff000000` already satisfies.\n * Defaults to `false` to preserve the current iOS-equivalent behavior.\n *\n * **Recommended on Android.** Measured on a Pixel 7 (Android 17, release\n * build, XR-1c): with the default TextureView path RN-Skia logs its\n * `updateTexImage: LegacySurfaceTexture is not attached!` /\n * `updateAndRelease() failed` pair **22 028 times per 60 s** — 90% of all\n * logcat output, saturating the 256 KiB ring buffer so unrelated diagnostics\n * are lost. With `opaque: true` the same build over three 60 s windows logs\n * the pair **zero** times and total log volume drops ~10x. RN-Skia labels the\n * pair ignorable and rendering is correct either way, so this is log noise\n * and TextureView overhead, not a correctness fix. Native memory is flat\n * across a 6-minute soak on both paths.\n */\n opaque?: boolean;\n}\n\n/** Props for the <GameView> component. */\nexport interface GameViewProps {\n /** Game configuration. */\n config?: GameConfig;\n /** Called once the game context is ready (loop not yet started). */\n onReady?: (ctx: GameContextValue) => void;\n /** Style applied to the outer View container. */\n style?: ViewStyle;\n /** Optional overlay children (e.g. VirtualJoystick, VirtualButton). */\n children?: React.ReactNode;\n /** Explicit safe-area insets. If omitted, resolved via `useContext(SafeAreaInsetsContext)`\n * from react-native-safe-area-context; falls back to `{ top: 0, right: 0, bottom: 0,\n * left: 0 }` when no `<SafeAreaProvider>` ancestor is mounted. */\n safeArea?: SafeArea;\n}\n\n/**\n * GameView — root component that sets up the Skia canvas, game loop,\n * and all core game systems. Provides GameContext to descendants.\n *\n * Overlay controls (VirtualJoystick, VirtualButton) should be placed\n * as children; they render on top of the Skia canvas.\n */\nexport function GameView({\n config,\n onReady,\n style,\n children,\n safeArea,\n}: GameViewProps): React.ReactElement {\n // useContext must run unconditionally (hook rules), even when `safeArea` makes its\n // value unused below — it never throws, unlike useSafeAreaInsets() without a provider.\n const contextInsets = useContext(SafeAreaInsetsContext);\n const resolvedSafeArea: SafeArea = safeArea ?? contextInsets ?? ZERO_INSETS;\n const canvasRef = useCanvasRef();\n const [passes, setPasses] = useState<readonly PostFxPassDescriptor[]>(EMPTY_PASSES);\n const [viewportSize, setViewportSize] = useState({ w: 0, h: 0 });\n const pd = PixelRatio.get();\n const isWeb = Platform.OS === 'web';\n // Both platforms write captured frames into a Reanimated shared value so\n // rn-skia's <Image> reads the latest frame on the UI thread without a React\n // re-render. createSceneCapture reuses one offscreen surface per viewport\n // size (fixing per-frame MakeOffscreen on native, NEW-2) and gates the\n // GPU→CPU makeNonTextureImage() copy to web only, where cross-context\n // sampling requires it (web: nonTextureImage true, native: false).\n const sceneImage = useSharedValue<SkImage | null>(null);\n const captureRef = useRef<SceneCapture<SkImage> | null>(null);\n // Native only: the offscreen surface lives on the UI thread, so it is held in\n // shared values rather than a ref — a ref would put it back on the JS thread\n // and reintroduce the black-frame regression captureSceneOnUI exists to fix.\n const uiSurface = useSharedValue<SkSurface | null>(null);\n const uiSurfaceKey = useSharedValue(0);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: intentional mount-only\n const ctx = useMemo<GameContextValue>(() => {\n const loop = new GameLoop({\n fixedDt: config?.fixedDt,\n maxDt: config?.maxDt,\n });\n const world = new World();\n const camera = new Camera2D();\n const input = new InputManager();\n const audio = new AudioManager();\n const noop: AssetLoader = () => Promise.resolve(null);\n const assets = new AssetManager(config?.assetLoader ?? noop);\n const scenes = new SceneManager();\n const renderer = new Renderer();\n const batch = new SpriteBatch();\n return { world, camera, input, audio, assets, scenes, loop, renderer, batch };\n }, []);\n\n // Warn once per <GameView> instance (not per page load) so each independently\n // mounted instance with a postfx binding gets its own one-time notice.\n const webPostFxWarnedRef = useRef(false);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: intentional mount-only\n useEffect(() => {\n const bridge = createSkiaFrameRenderer(Skia);\n ctx.renderer.setCanvas(bridge.canvas);\n\n const clearColor = config?.clearColor ?? 0xff000000;\n const onRenderBackground = config?.onRenderBackground;\n const onRenderPostFx = config?.onRenderPostFx;\n\n const spriteQuery = ctx.world.query(Position, Sprite);\n const renderSystem = createRenderSystem(ctx.world, spriteQuery, Position, Sprite, ctx.batch);\n\n // Last passes signature pushed to state; gates setPasses so an unchanged\n // (or empty) chain does not churn a fresh array + RuntimeShader tree every\n // frame. Seeded to the same EMPTY_PASSES the state holds, so an empty chain\n // never triggers a re-render from passes.\n let prevBuilt: readonly PostFxPassDescriptor[] = EMPTY_PASSES;\n\n const unsubscribeLate = ctx.loop.onLateUpdate.add((dt) => {\n ctx.camera.update(dt);\n ctx.input.update();\n });\n\n const unsubscribePre = ctx.loop.onPreRender.add(() => {\n const w = ctx.camera.viewportWidth;\n const h = ctx.camera.viewportHeight;\n bridge.beginFrame(w, h, ctx.loop.clock.elapsed, pd);\n ctx.renderer.begin(clearColor);\n ctx.renderer.applyCamera(\n ctx.camera.effectiveX,\n ctx.camera.effectiveY,\n ctx.camera.zoom,\n ctx.camera.rotation,\n w,\n h,\n );\n if (onRenderBackground) onRenderBackground(ctx, ctx.renderer.canvas);\n renderSystem();\n ctx.batch.flush(bridge.drawAtlas, ctx.renderer);\n if (onRenderPostFx) onRenderPostFx(ctx, ctx.renderer.canvas, bridge);\n ctx.renderer.end();\n const pic = bridge.endFrame();\n if (pic !== null) {\n if (isWeb) {\n // Web has one thread, so the JS-thread capture is same-context by\n // construction; this is the path WEB-1..WEB-7 verified in Chrome,\n // including the surface cache that keeps Chrome from evicting the\n // on-screen canvas (web-target-2026-08.md §12). Left untouched.\n if (captureRef.current === null) {\n captureRef.current = createSceneCapture(Skia, {\n nonTextureImage: true,\n retentionDepth: 3,\n });\n }\n const img = captureRef.current.capture(pic, w * pd, h * pd);\n if (img !== null) sceneImage.value = img;\n } else {\n // Native must build the surface on the UI thread — see captureSceneOnUI.\n // `scheduleOnUI` and not Reanimated's `runOnUI`: the latter is curried,\n // so `runOnUI(fn)` allocated a fresh wrapper on every frame in this\n // hook. Passing the args directly allocates nothing (ADR-0002).\n scheduleOnUI(\n captureSceneOnUI,\n sceneImage,\n uiSurface,\n uiSurfaceKey,\n pic as SkPicture,\n w * pd,\n h * pd,\n );\n }\n }\n if (!isWeb) {\n const built = bridge.buildPostFxPasses(null, null, w, h) as readonly PostFxPassDescriptor[];\n if (!samePasses(prevBuilt, built)) {\n prevBuilt = built.length === 0 ? EMPTY_PASSES : built;\n setPasses(prevBuilt);\n }\n } else if (bridge.hasPostFxBinding() && !webPostFxWarnedRef.current) {\n console.warn(\n 'postfx chain skipped: Skia.RuntimeShaderBuilder and' +\n ' ImageFilter.MakeRuntimeShaderWithChildren both throw' +\n ' \"Not implemented on React Native Web\".',\n );\n webPostFxWarnedRef.current = true;\n }\n canvasRef.current?.redraw();\n });\n\n onReady?.(ctx);\n ctx.loop.start();\n return () => {\n unsubscribeLate();\n unsubscribePre();\n captureRef.current?.dispose();\n captureRef.current = null;\n ctx.loop.stop();\n };\n }, []);\n\n const handleLayout = useCallback(\n (event: LayoutChangeEvent): void => {\n const { width, height } = event.nativeEvent.layout;\n ctx.camera.setViewport(width, height);\n setViewportSize({ w: width, h: height });\n },\n [ctx],\n );\n\n const onGrant = useCallback(\n (e: GestureResponderEvent): void => {\n const { changedTouches, identifier, locationX, locationY } = e.nativeEvent;\n if (changedTouches.length === 0) {\n ctx.input.onPointerDown(Number(identifier), locationX, locationY);\n return;\n }\n for (let i = 0; i < changedTouches.length; i++) {\n const t = changedTouches[i];\n if (t === undefined) continue;\n ctx.input.onPointerDown(Number(t.identifier), t.locationX, t.locationY);\n }\n },\n [ctx],\n );\n const onMove = useCallback(\n (e: GestureResponderEvent): void => {\n const { changedTouches, identifier, locationX, locationY } = e.nativeEvent;\n if (changedTouches.length === 0) {\n ctx.input.onPointerMove(Number(identifier), locationX, locationY);\n return;\n }\n for (let i = 0; i < changedTouches.length; i++) {\n const t = changedTouches[i];\n if (t === undefined) continue;\n ctx.input.onPointerMove(Number(t.identifier), t.locationX, t.locationY);\n }\n },\n [ctx],\n );\n const onRelease = useCallback(\n (e: GestureResponderEvent): void => {\n const { changedTouches, identifier, locationX, locationY } = e.nativeEvent;\n if (changedTouches.length === 0) {\n ctx.input.onPointerUp(Number(identifier), locationX, locationY);\n return;\n }\n for (let i = 0; i < changedTouches.length; i++) {\n const t = changedTouches[i];\n if (t === undefined) continue;\n ctx.input.onPointerUp(Number(t.identifier), t.locationX, t.locationY);\n }\n },\n [ctx],\n );\n\n const containerStyle = useMemo(() => [styles.container, style], [style]);\n // RN-Skia's <RuntimeShader> image filter binds the implicit source only\n // (MakeRuntimeShader(rtb, null, null)) and never consumes child shaders, so a\n // pass with extra sampler children (color-grading-lut) would be dropped by\n // it. Such a pass, and every pass before it, runs as one paint shader on a\n // <Rect> instead: nested <Shader>s bind their children positionally (src,\n // then each entry of pass.children), the convention render-web uses. Passes\n // after the last child-bearing one stay <RuntimeShader> image filters — a\n // nested <Shader> re-evaluates src per tap, which would multiply reads for\n // multi-tap effects. A chain with no children keeps the plain <Image> tree.\n const canvasContent = useMemo(() => {\n if (viewportSize.w === 0) return null;\n const w = viewportSize.w;\n const h = viewportSize.h;\n const last = lastPassWithChildren(passes);\n if (last < 0) {\n return (\n <Image image={sceneImage} x={0} y={0} width={w} height={h} fit=\"cover\">\n {passes.map((p) => (\n <RuntimeShader key={p.id} source={p.source} uniforms={p.uniforms} />\n ))}\n </Image>\n );\n }\n let shader: React.ReactElement = (\n <ImageShader\n image={sceneImage}\n fit=\"cover\"\n rect={{ x: 0, y: 0, width: w, height: h }}\n tx=\"clamp\"\n ty=\"clamp\"\n sampling={LINEAR_SAMPLING}\n />\n );\n for (let i = 0; i <= last; i++) {\n const p = passes[i];\n if (p === undefined) continue;\n const samplers: React.ReactElement[] = [];\n for (let c = 0; c < p.children.length; c++) {\n samplers.push(\n <ImageShader\n key={c}\n image={p.children[c] ?? null}\n tx=\"clamp\"\n ty=\"clamp\"\n sampling={LINEAR_SAMPLING}\n />,\n );\n }\n shader = (\n <Shader source={p.source} uniforms={p.uniforms}>\n {shader}\n {samplers}\n </Shader>\n );\n }\n const filters: React.ReactElement[] = [];\n for (let i = last + 1; i < passes.length; i++) {\n const p = passes[i];\n if (p === undefined) continue;\n filters.push(<RuntimeShader key={p.id} source={p.source} uniforms={p.uniforms} />);\n }\n return (\n <Rect x={0} y={0} width={w} height={h}>\n {shader}\n {filters}\n </Rect>\n );\n }, [passes, viewportSize, sceneImage]);\n\n return (\n <SafeAreaContext.Provider value={resolvedSafeArea}>\n <GameContext.Provider value={ctx}>\n <View\n style={containerStyle}\n onLayout={handleLayout}\n onStartShouldSetResponder={returnTrue}\n onResponderGrant={onGrant}\n onResponderMove={onMove}\n onResponderRelease={onRelease}\n onResponderTerminate={onRelease}\n >\n <Canvas\n ref={canvasRef as React.Ref<CanvasRef>}\n style={StyleSheet.absoluteFill}\n pointerEvents=\"none\"\n opaque={config?.opaque ?? false}\n >\n {canvasContent}\n </Canvas>\n {children}\n </View>\n </GameContext.Provider>\n </SafeAreaContext.Provider>\n );\n}\n\nfunction returnTrue(): boolean {\n return true;\n}\n\n/** Stable empty-chain reference — an empty `buildPostFxPasses` result collapses\n * to this so the `passes` state never changes for a postfx-free GameView. */\nconst EMPTY_PASSES: readonly PostFxPassDescriptor[] = [];\n\n/** Linear, mipmap-free sampling for every ImageShader in the pass chain — the\n * options render-web hands makeShaderOptions, so both backends sample alike. */\nconst LINEAR_SAMPLING = { filter: FilterMode.Linear, mipmap: MipmapMode.None };\n\n/** Index of the last pass carrying extra sampler children, or -1 when none does. */\nfunction lastPassWithChildren(passes: readonly PostFxPassDescriptor[]): number {\n for (let i = passes.length - 1; i >= 0; i--) {\n const p = passes[i];\n if (p !== undefined && p.children.length > 0) return i;\n }\n return -1;\n}\n\n/** Fallback insets when no `<SafeAreaProvider>` ancestor supplies a context value. */\nconst ZERO_INSETS: SafeArea = { top: 0, right: 0, bottom: 0, left: 0 };\n\n/**\n * Shallow structural equality of two pass lists. The signature is length +\n * per-pass `id` + shader ref + child-image refs + uniform values. Uniforms are\n * compared (not just `id`/`source`) because animating effects — the hit-flash\n * decay and timed triggers — keep a constant `id`/`source` while only their\n * uniform values change frame to frame; excluding them would freeze those\n * animations. Cost is trivial: postfx chains hold a handful of scalar/short-vec\n * uniforms.\n */\nfunction samePasses(\n a: readonly PostFxPassDescriptor[],\n b: readonly PostFxPassDescriptor[],\n): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const pa = a[i];\n const pb = b[i];\n if (pa === undefined || pb === undefined) return false;\n if (pa.id !== pb.id || pa.source !== pb.source) return false;\n if (!sameChildren(pa.children, pb.children)) return false;\n if (!sameUniforms(pa.uniforms, pb.uniforms)) return false;\n }\n return true;\n}\n\nfunction sameChildren(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nfunction sameUniforms(\n a: PostFxPassDescriptor['uniforms'],\n b: PostFxPassDescriptor['uniforms'],\n): boolean {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n const va = a[key];\n const vb = b[key];\n if (va === undefined || vb === undefined) return false;\n if (typeof va === 'number') {\n if (va !== vb) return false;\n } else {\n if (typeof vb === 'number' || va.length !== vb.length) return false;\n for (let i = 0; i < va.length; i++) {\n if (va[i] !== vb[i]) return false;\n }\n }\n }\n return true;\n}\n\nconst styles = StyleSheet.create({\n container: { flex: 1 },\n});\n","import type { Query } from '@flare-engine/ecs';\nimport { useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport { GameContext, type GameContextValue } from './game-context.js';\n\n/**\n * useGame — returns the GameContextValue from the nearest <GameView>.\n * Throws if called outside a <GameView>.\n */\nexport function useGame(): GameContextValue {\n const ctx = useContext(GameContext);\n if (!ctx) {\n throw new Error('useGame must be used inside a <GameView>');\n }\n return ctx;\n}\n\n/**\n * useEntity — subscribes to an ECS Query and returns the current entity list.\n * Re-renders when entities are added to or removed from the query.\n *\n * @param query An active Query obtained from world.query(...)\n */\nexport function useEntity(query: Query): readonly number[] {\n const [entities, setEntities] = useState<readonly number[]>(() => Array.from(query));\n\n useEffect(() => {\n const refresh = () => setEntities(Array.from(query));\n\n const unsubAdd = query.onEntityAdded.add(refresh);\n const unsubRemove = query.onEntityRemoved.add(refresh);\n\n // Sync initial state (query may have changed between render and effect)\n refresh();\n\n return () => {\n unsubAdd();\n unsubRemove();\n };\n }, [query]);\n\n return entities;\n}\n\n/**\n * useGameLoop — registers a per-frame callback on the game loop's onUpdate signal.\n * The callback is called each frame with delta time in seconds.\n * Automatically unregisters on unmount.\n *\n * @param callback Function called each frame with dt in seconds.\n */\nexport function useGameLoop(callback: (dt: number) => void): void {\n const { loop } = useGame();\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n const stable = useCallback((dt: number) => {\n callbackRef.current(dt);\n }, []);\n\n useEffect(() => {\n const unsub = loop.onUpdate.add(stable);\n return () => {\n unsub();\n };\n }, [loop, stable]);\n}\n","import type React from 'react';\nimport type { ViewStyle } from 'react-native';\nimport { StyleSheet, View } from 'react-native';\n\n/** Props for the <LoadingScreen> component. */\nexport interface LoadingScreenProps {\n /** Progress in [0, 1]. Values outside this range are clamped. */\n progress: number;\n /** Style applied to the outer container (covers parent by default). */\n style?: ViewStyle;\n /** Filled portion color. */\n barColor?: string;\n /** Track color. */\n trackColor?: string;\n /** Background color behind the track. */\n backgroundColor?: string;\n}\n\n/**\n * LoadingScreen — full-screen asset-load overlay.\n *\n * Renders before `<GameView>` mounts its Skia canvas (or alongside it\n * while `AssetManager.load()` resolves). Pure RN Views so it works\n * without a live Skia context. Consumers drive `progress` from the\n * AssetManager progress callback.\n */\nexport function LoadingScreen({\n progress,\n style,\n barColor = '#ffffff',\n trackColor = 'rgba(255,255,255,0.2)',\n backgroundColor = '#000000',\n}: LoadingScreenProps): React.ReactElement {\n const clamped = progress < 0 ? 0 : progress > 1 ? 1 : progress;\n const percent = `${Math.round(clamped * 100)}%` as `${number}%`;\n\n return (\n <View style={[styles.container, { backgroundColor }, style]}>\n <View style={[styles.track, { backgroundColor: trackColor }]}>\n <View style={[styles.bar, { width: percent, backgroundColor: barColor }]} />\n </View>\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n position: 'absolute',\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n alignItems: 'center',\n justifyContent: 'center',\n padding: 32,\n },\n track: {\n width: '80%',\n height: 6,\n borderRadius: 3,\n overflow: 'hidden',\n },\n bar: {\n height: '100%',\n },\n});\n","import type { Signal } from '@flare-engine/events';\nimport { easeOutCubic } from '@flare-engine/math';\nimport { useEffect, useRef, useState } from 'react';\n\nexport function useOverlayFade(visible: boolean, durationMs = 300): number {\n const target = visible ? 1 : 0;\n const [opacity, setOpacity] = useState<number>(target);\n const opacityRef = useRef<number>(opacity);\n const startRef = useRef<number | null>(null);\n const rafRef = useRef<number | null>(null);\n\n // Keep ref in sync with state (runs before effect)\n opacityRef.current = opacity;\n\n useEffect(() => {\n if (typeof requestAnimationFrame === 'undefined') {\n setOpacity(target);\n return;\n }\n const from = opacityRef.current;\n startRef.current = null;\n if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);\n\n const step = (now: number) => {\n if (startRef.current === null) startRef.current = now;\n const t = Math.min((now - startRef.current) / durationMs, 1);\n setOpacity(from + (target - from) * t);\n if (t < 1) {\n rafRef.current = requestAnimationFrame(step);\n }\n };\n rafRef.current = requestAnimationFrame(step);\n return () => {\n if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);\n };\n }, [target, durationMs]);\n\n return opacity;\n}\n\nexport function useCountUp(target: number, durationMs = 600): number {\n const [value, setValue] = useState<number>(target);\n const valueRef = useRef<number>(value);\n const startRef = useRef<number | null>(null);\n const rafRef = useRef<number | null>(null);\n\n // Keep ref in sync with state (runs before effect)\n valueRef.current = value;\n\n useEffect(() => {\n if (typeof requestAnimationFrame === 'undefined') {\n setValue(target);\n return;\n }\n const from = valueRef.current;\n startRef.current = null;\n if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);\n\n const step = (now: number) => {\n if (startRef.current === null) startRef.current = now;\n const t = Math.min((now - startRef.current) / durationMs, 1);\n setValue(from + (target - from) * easeOutCubic(t));\n if (t < 1) {\n rafRef.current = requestAnimationFrame(step);\n }\n };\n rafRef.current = requestAnimationFrame(step);\n return () => {\n if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);\n };\n }, [target, durationMs]);\n\n return value;\n}\n\nexport function useSignalState<T>(signal: Signal<T>, initial: T): T {\n const [state, setState] = useState<T>(initial);\n\n useEffect(() => {\n const disposer = signal.add(setState);\n return disposer;\n }, [signal]);\n\n return state;\n}\n","import type { SkiaAtlasModuleLike } from '@flare-engine/assets';\nimport { Skia } from '@shopify/react-native-skia';\n\n/**\n * The RN-Skia module adapted to the engine's structural atlas interface.\n * Centralises the one boundary assertion so template code stays cast-free.\n */\nexport const skiaAtlasModule: SkiaAtlasModuleLike = Skia as unknown as SkiaAtlasModuleLike;\n","import {\n createButtonState,\n pressButton,\n releaseButton,\n resetButtonFrame,\n type VirtualButtonState,\n} from '@flare-engine/input';\nimport type React from 'react';\nimport { useCallback, useRef } from 'react';\nimport type { ViewStyle } from 'react-native';\nimport { StyleSheet, View } from 'react-native';\n\n/** Props for the <VirtualButton> component. */\nexport interface VirtualButtonProps {\n /** Called on each state change. */\n onStateChange?: (state: VirtualButtonState) => void;\n /** Style applied to the button. */\n style?: ViewStyle;\n /** Button label / overlay content. */\n children?: React.ReactNode;\n}\n\n/**\n * VirtualButton — an on-screen button overlay component.\n *\n * Uses raw `onTouchStart`/`onTouchEnd` so press and release fire regardless\n * of which ancestor holds the RN responder — enabling simultaneous use with\n * `<VirtualJoystick>` without responder conflicts.\n */\nexport function VirtualButton({\n onStateChange,\n style,\n children,\n}: VirtualButtonProps): React.ReactElement {\n const stateRef = useRef<VirtualButtonState>(createButtonState());\n\n const handlePress = useCallback(() => {\n resetButtonFrame(stateRef.current);\n pressButton(stateRef.current);\n onStateChange?.(stateRef.current);\n }, [onStateChange]);\n\n const handleRelease = useCallback(() => {\n resetButtonFrame(stateRef.current);\n releaseButton(stateRef.current);\n onStateChange?.(stateRef.current);\n }, [onStateChange]);\n\n return (\n <View\n style={[styles.button, style]}\n onTouchStart={handlePress}\n onTouchEnd={handleRelease}\n onTouchCancel={handleRelease}\n >\n {children}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n button: {\n width: 60,\n height: 60,\n borderRadius: 30,\n backgroundColor: 'rgba(255,255,255,0.3)',\n alignItems: 'center',\n justifyContent: 'center',\n },\n});\n","import {\n createJoystickState,\n releaseJoystick,\n updateJoystick,\n type VirtualJoystickConfig,\n type VirtualJoystickState,\n} from '@flare-engine/input';\nimport type React from 'react';\nimport { useCallback, useRef, useState } from 'react';\nimport type { GestureResponderEvent, ViewStyle } from 'react-native';\nimport { StyleSheet, View } from 'react-native';\n\n/** Props for the <VirtualJoystick> component. */\nexport interface VirtualJoystickProps {\n /** Joystick configuration (dead zone, max radius). */\n config?: VirtualJoystickConfig;\n /** Called on each state change. */\n onStateChange?: (state: VirtualJoystickState) => void;\n /** Style applied to the outer container. */\n style?: ViewStyle;\n /** Custom node rendered in place of the default base circle View. */\n base?: React.ReactNode;\n /** Custom node rendered in place of the default knob View. */\n thumb?: React.ReactNode;\n}\n\ntype TouchPoint = GestureResponderEvent['nativeEvent'];\n\n/** The finger that holds the stick, and the page position of the stick's top-left corner. */\ninterface Finger {\n id: TouchPoint['identifier'] | null;\n originX: number;\n originY: number;\n}\n\n/**\n * VirtualJoystick — an on-screen joystick overlay component.\n *\n * Renders a base circle and a knob that follows the user's touch.\n * Claims the React Native touch responder so children of a parent that\n * also claims the responder (e.g. <GameView>) still receive move/end events.\n */\nexport function VirtualJoystick({\n config,\n onStateChange,\n style,\n base,\n thumb,\n}: VirtualJoystickProps): React.ReactElement {\n const stateRef = useRef<VirtualJoystickState>(createJoystickState());\n const sizeRef = useRef<{ w: number; h: number }>({ w: 0, h: 0 });\n const fingerRef = useRef<Finger>({ id: null, originX: 0, originY: 0 });\n const [knob, setKnob] = useState({ x: 0, y: 0 });\n\n const handleLayout = useCallback(\n (e: { nativeEvent: { layout: { width: number; height: number } } }) => {\n sizeRef.current = { w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height };\n },\n [],\n );\n\n const moveTo = useCallback(\n (touchX: number, touchY: number) => {\n const { w, h } = sizeRef.current;\n updateJoystick(stateRef.current, w / 2, h / 2, touchX, touchY, config);\n onStateChange?.(stateRef.current);\n const { x, y } = stateRef.current.offset;\n setKnob((prev) => (prev.x === x && prev.y === y ? prev : { x, y }));\n },\n [config, onStateChange],\n );\n\n // No child of the stick is a touch target, so at grant `locationX/Y` is measured\n // against the stick on every platform. Android measures later events against\n // whichever view is under the finger by then, so moves are read as page\n // coordinates from the origin taken here.\n const handleGrant = useCallback(\n (e: GestureResponderEvent) => {\n const touch = e.nativeEvent;\n const finger = fingerRef.current;\n finger.id = touch.identifier;\n finger.originX = touch.pageX - touch.locationX;\n finger.originY = touch.pageY - touch.locationY;\n moveTo(touch.locationX, touch.locationY);\n },\n [moveTo],\n );\n\n const handleMove = useCallback(\n (e: GestureResponderEvent) => {\n const finger = fingerRef.current;\n const touch = findTouch(e.nativeEvent, finger.id);\n if (touch === undefined) return;\n moveTo(touch.pageX - finger.originX, touch.pageY - finger.originY);\n },\n [moveTo],\n );\n\n const handleRelease = useCallback(() => {\n releaseJoystick(stateRef.current);\n onStateChange?.(stateRef.current);\n setKnob((prev) => (prev.x === 0 && prev.y === 0 ? prev : { x: 0, y: 0 }));\n }, [onStateChange]);\n\n const maxRadius = config?.maxRadius ?? 50;\n\n return (\n <View\n style={[\n styles.center,\n ...(base ? [] : [styles.baseBg]),\n {\n width: maxRadius * 2,\n height: maxRadius * 2,\n borderRadius: maxRadius,\n },\n style,\n ]}\n onLayout={handleLayout}\n onStartShouldSetResponder={returnTrue}\n onMoveShouldSetResponder={returnTrue}\n onResponderGrant={handleGrant}\n onResponderMove={handleMove}\n onResponderRelease={handleRelease}\n onResponderTerminate={handleRelease}\n onResponderTerminationRequest={returnFalse}\n >\n {base ? (\n <View style={StyleSheet.absoluteFill} pointerEvents=\"none\">\n {base}\n </View>\n ) : null}\n {thumb ? (\n <View\n style={{ transform: [{ translateX: knob.x }, { translateY: knob.y }] }}\n pointerEvents=\"none\"\n >\n {thumb}\n </View>\n ) : (\n <View\n style={[styles.knob, { transform: [{ translateX: knob.x }, { translateY: knob.y }] }]}\n />\n )}\n </View>\n );\n}\n\n/**\n * The stick's own finger in a touch event. The event's own fields describe the\n * first changed touch, which can be another finger on the screen.\n */\nfunction findTouch(event: TouchPoint, id: Finger['id']): TouchPoint | undefined {\n const touches = event.touches;\n if (touches !== undefined) {\n for (let i = 0; i < touches.length; i++) {\n const touch = touches[i];\n if (touch !== undefined && touch.identifier === id) return touch;\n }\n }\n return event.identifier === id ? event : undefined;\n}\n\nfunction returnTrue(): boolean {\n return true;\n}\n\nfunction returnFalse(): boolean {\n return false;\n}\n\nconst styles = StyleSheet.create({\n center: {\n alignItems: 'center',\n justifyContent: 'center',\n },\n baseBg: {\n backgroundColor: 'rgba(255,255,255,0.2)',\n },\n knob: {\n width: 40,\n height: 40,\n borderRadius: 20,\n backgroundColor: 'rgba(255,255,255,0.6)',\n pointerEvents: 'none',\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,eAAA,GAAcA,MAAAA,cAAAA,CAAuC,IAAI;;AC1BtE,MAAa,mBAAA,GAAkBC,MAAAA,cAAAA,CAA+B,IAAI;AAElE,SAAgB,cAAwB;CACtC,MAAM,SAAA,GAAQC,MAAAA,WAAAA,CAAW,eAAe;CACxC,IAAI,UAAU,MACZ,MA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AAD,EACE,OAAO,CAAC,OAAO,MAAM,EAAE,WAAW,CAAC,EAAE,YAAY,KAAK,EAAE,GAAG,EAAE,YAAY,KAAK,EAAE,CAAC,EAAE,CAAC,EACrF,CAAA,CAEC;;AAEV;;;;;AAMA,SAAS,UAAU,OAAmB,IAA0C;CAC9E,MAAM,UAAU,MAAM;CACtB,IAAI,YAAY,KAAA,GACd,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;EACvC,MAAM,QAAQ,QAAQ;EACtB,IAAI,UAAU,KAAA,KAAa,MAAM,eAAe,IAAI,OAAO;CAC7D;CAEF,OAAO,MAAM,eAAe,KAAK,QAAQ,KAAA;AAC3C;AAEA,SAAS,aAAsB;CAC7B,OAAO;AACT;AAEA,SAAS,cAAuB;CAC9B,OAAO;AACT;AAEA,MAAM,SAASC,aAAAA,WAAW,OAAO;CAC/B,QAAQ;EACN,YAAY;EACZ,gBAAgB;CAClB;CACA,QAAQ,EACN,iBAAiB,wBACnB;CACA,MAAM;EACJ,OAAO;EACP,QAAQ;EACR,cAAc;EACd,iBAAiB;EACjB,eAAe;CACjB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["createContext","createContext","useContext","createFrameRenderer","Skia","useContext","SafeAreaInsetsContext","useCanvasRef","useState","PixelRatio","Platform","useSharedValue","useRef","useMemo","GameLoop","World","Camera2D","InputManager","AudioManager","AssetManager","SceneManager","Renderer","SpriteBatch","Position","Sprite","createRenderSystem","useCallback","styles","Image","RuntimeShader","ImageShader","Shader","Rect","View","returnTrue","Canvas","StyleSheet","FilterMode","MipmapMode","useContext","useState","useRef","useCallback","View","styles","StyleSheet","useState","useRef","easeOutCubic","Skia","useRef","createButtonState","useCallback","View","styles","StyleSheet","useRef","createJoystickState","useState","useCallback","View","StyleSheet"],"sources":["../src/game-context.ts","../src/safe-area.ts","../src/scene-texture.ts","../src/skia-bridge.ts","../src/web-postfx.ts","../src/game-view.tsx","../src/hooks.ts","../src/loading-screen.tsx","../src/overlay-hooks.ts","../src/skia-atlas.ts","../src/virtual-button.tsx","../src/virtual-joystick.tsx"],"sourcesContent":["import type { AssetManager } from '@flare-engine/assets';\nimport type { AudioManager } from '@flare-engine/audio';\nimport type { GameLoop } from '@flare-engine/core';\nimport type { World } from '@flare-engine/ecs';\nimport type { InputManager } from '@flare-engine/input';\nimport type { Camera2D, Renderer, SpriteBatch } from '@flare-engine/render';\nimport type { SceneManager } from '@flare-engine/scene';\nimport { createContext } from 'react';\n\n/** The value exposed via GameContext. */\nexport interface GameContextValue {\n /** ECS world. */\n world: World;\n /** Primary 2D camera. */\n camera: Camera2D;\n /** Input manager (pointer, touches). */\n input: InputManager;\n /** Audio manager. */\n audio: AudioManager;\n /** Asset manager. */\n assets: AssetManager;\n /** Scene manager. */\n scenes: SceneManager;\n /** Game loop. */\n loop: GameLoop;\n /** Frame renderer (owns the draw phase). */\n renderer: Renderer;\n /** Sprite batch — queue `draw()` calls from systems or custom logic. */\n batch: SpriteBatch;\n}\n\n/**\n * React context that provides access to core game objects.\n * Null if accessed outside a <GameView>.\n */\nexport const GameContext = createContext<GameContextValue | null>(null);\n","import { createContext, useContext } from 'react';\n\nexport interface SafeArea {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\nexport const SafeAreaContext = createContext<SafeArea | null>(null);\n\nexport function useSafeArea(): SafeArea {\n const value = useContext(SafeAreaContext);\n if (value === null) {\n throw new Error('useSafeArea must be used inside a <GameView>');\n }\n return value;\n}\n","import type { SkImageLike } from '@flare-engine/assets';\nimport type { FrameRendererCompiledPass } from '@flare-engine/render';\nimport type { WebPostFxCompositor } from './web-postfx.js';\n\n/**\n * Structural offscreen surface — the subset `GameView`'s scene capture needs.\n * Declared locally so this module does not depend on RN-Skia's concrete types.\n */\nexport interface SceneSurfaceLike<TImage = SkImageLike> {\n getCanvas(): SceneSurfaceCanvasLike;\n makeImageSnapshot(): TImage;\n flush(): void;\n}\n\n/** The canvas subset used when capturing a frame's picture and compositing postfx over it. */\nexport interface SceneSurfaceCanvasLike {\n drawPicture(picture: unknown): void;\n drawRect(rect: { x: number; y: number; width: number; height: number }, paint: unknown): void;\n}\n\n/** Structural Skia module — only the offscreen-surface factory is needed. */\nexport interface SceneSurfaceModuleLike<TImage = SkImageLike> {\n Surface: {\n MakeOffscreen(width: number, height: number): SceneSurfaceLike<TImage> | null;\n };\n}\n\n/** A size-keyed offscreen surface holder. */\nexport interface SceneSurfaceCache<TImage = SkImageLike> {\n /**\n * The surface for this viewport size, allocating only when the size actually\n * changed. Returns null for a zero-sized viewport, or when Skia refuses the\n * allocation.\n */\n acquire(width: number, height: number): SceneSurfaceLike<TImage> | null;\n /** Release the live surface. Safe to call repeatedly. */\n dispose(): void;\n}\n\n/**\n * `Symbol.dispose` is not in this project's ES2022 lib, so the well-known\n * symbol is looked up at runtime instead of written as a computed key.\n */\nconst DISPOSE = (Symbol as unknown as { dispose?: symbol }).dispose;\n\n/** Release an RN-Skia wrapper through its `Symbol.dispose`; a no-op for null or non-disposable values. */\nexport function releaseSkiaObject(target: unknown): void {\n if (DISPOSE === undefined || target === null || target === undefined) return;\n const disposer = (target as Record<symbol, unknown>)[DISPOSE];\n if (typeof disposer === 'function') {\n (disposer as () => void).call(target);\n }\n}\n\n/**\n * Reuse one offscreen surface across frames instead of allocating per frame.\n *\n * On **web** this is a correctness requirement, not an optimisation. RN-Skia's\n * web `MakeOffscreen` builds a fresh `OffscreenCanvas` and a fresh WebGL\n * context on every call and releases neither; Chrome caps a page at 16 live\n * WebGL contexts and evicts the oldest, which is the on-screen `<Canvas>`.\n * A per-frame allocation therefore kills the visible canvas within ~16 frames\n * while the game loop keeps running — the app looks alive and paints nothing.\n * Measured and written up in docs/plans/web-target-2026-08.md §12.\n */\nexport function createSceneSurfaceCache<TImage>(\n Skia: SceneSurfaceModuleLike<TImage>,\n): SceneSurfaceCache<TImage> {\n let surface: SceneSurfaceLike<TImage> | null = null;\n let currentWidth = 0;\n let currentHeight = 0;\n\n const dispose = (): void => {\n if (surface === null) return;\n releaseSkiaObject(surface);\n surface = null;\n currentWidth = 0;\n currentHeight = 0;\n };\n\n return {\n acquire(width: number, height: number): SceneSurfaceLike<TImage> | null {\n if (width <= 0 || height <= 0) return null;\n if (surface !== null && currentWidth === width && currentHeight === height) {\n return surface;\n }\n dispose();\n const next = Skia.Surface.MakeOffscreen(width, height);\n if (next === null) return null;\n surface = next;\n currentWidth = width;\n currentHeight = height;\n return surface;\n },\n dispose,\n };\n}\n\n/** A snapshot that can be detached from its GL context (RN-Skia web SkImage). */\ninterface DetachableImage<TImage> {\n makeNonTextureImage?(): TImage;\n}\n\n/** Per-frame scene capture over a reused surface. */\nexport interface SceneCapture<TImage> {\n /**\n * Draw `picture` into the reused surface, run `passes` over it in place when\n * a compositor was supplied, and return an image detached from that surface's\n * GL context. Returns null for a zero-sized viewport.\n */\n capture(\n picture: unknown,\n width: number,\n height: number,\n passes?: readonly FrameRendererCompiledPass[],\n ): TImage | null;\n /** Release the surface, the frame images still held, and the compositor. */\n dispose(): void;\n}\n\n/**\n * Options for `createSceneCapture`.\n *\n * `nonTextureImage` defaults to `true` (web semantics: call\n * `makeNonTextureImage()` to copy the snapshot off the surface's GL context so\n * the on-screen canvas can sample it).\n *\n * **This factory is web-only since XR-1c.** An earlier revision said the\n * snapshot \"is a true copy on native\", so `false` was safe there. That is\n * wrong: the native snapshot is GPU-backed and belongs to whichever context\n * created the surface. What actually makes it sampleable is building the\n * surface on the **UI thread**, which `game-view.tsx` does through\n * `scheduleOnUI`, not through a call into this module. Passing `false` here on native\n * yields a black frame; passing `true` fixes it only by forcing a per-frame\n * GPU→CPU readback. Verified on a Pixel 7 — external-review-2026-08.md §11.4b.\n *\n * `retentionDepth` defaults to 3 — the web-measured minimum, and the only\n * platform this runs on.\n *\n * `postfx` runs the passes `capture` receives over the surface before the\n * snapshot; the capture owns it and `dispose()` disposes it.\n */\nexport interface SceneCaptureOptions<TImage = SkImageLike> {\n nonTextureImage?: boolean;\n retentionDepth?: number;\n postfx?: WebPostFxCompositor<TImage>;\n}\n\n/**\n * Capture the scene into a reused offscreen surface, releasing Skia objects as\n * it goes.\n *\n * Two leaks have to be avoided here, and both were measured in a browser\n * (docs/plans/web-target-2026-08.md §12):\n *\n * 1. **Per-frame surfaces.** RN-Skia's web `MakeOffscreen` builds an\n * `OffscreenCanvas` + WebGL context per call and releases neither; Chrome\n * caps a page at 16 live contexts and evicts the on-screen canvas. Hence the\n * surface cache.\n * 2. **Per-frame images.** `makeNonTextureImage()` reads the whole viewport back\n * into the wasm heap. Leaving old CPU images unreleased exhausts that heap.\n * A single-slot release strategy is not enough: RN-Skia's web `<Canvas>`\n * paints on its own rAF, which fires *after* the capture, so the image handed\n * to React on frame N is still in use when frame N+1 runs. Releasing it\n * immediately causes `BindingError: Cannot pass deleted object as a pointer of\n * type Image const*` from `JsiSkImage.width` every frame and a blank canvas.\n * Measured at 2560×1215 / Chrome (WEB-3):\n * hold=1 (one slot — what shipped at WEB-2) → blank, BindingError every frame\n * hold=2 → blank\n * hold=3 → 1378 frames, zero errors\n * A FIFO ring of depth 3 is the measured minimum.\n *\n * The snapshot is released as soon as it has been copied. Frame images are\n * released once the ring exceeds depth 3, ensuring the canvas's rAF always has\n * a live image to paint from.\n *\n * The postfx chain runs **here, in place**, for the same reasons: the `postfx`\n * compositor draws each pass back over this one surface between the picture\n * and the snapshot (Skia's copy-on-write keeps each pass's snapshot valid), so\n * the chain costs no second surface or WebGL context, and the image RN-Skia's\n * `<Image>` draws is already filtered — no shader node (the per-paint leak of\n * §14) is ever mounted on web.\n */\n\nexport function createSceneCapture<TImage>(\n Skia: SceneSurfaceModuleLike<TImage>,\n opts?: SceneCaptureOptions<TImage>,\n): SceneCapture<TImage> {\n const useNonTexture = opts?.nonTextureImage ?? true;\n const retentionDepth = opts?.retentionDepth ?? 3;\n const postfx = opts?.postfx ?? null;\n const surfaces = createSceneSurfaceCache(Skia);\n const ring: TImage[] = [];\n\n return {\n capture(\n picture: unknown,\n width: number,\n height: number,\n passes?: readonly FrameRendererCompiledPass[],\n ): TImage | null {\n const surface = surfaces.acquire(width, height);\n if (surface === null) return null;\n\n surface.getCanvas().drawPicture(picture);\n surface.flush();\n if (postfx !== null && passes !== undefined && passes.length > 0) {\n postfx.composite(surface, passes, width, height);\n }\n\n const snapshot = surface.makeImageSnapshot();\n const detachable = snapshot as DetachableImage<TImage>;\n const detached =\n useNonTexture && detachable.makeNonTextureImage\n ? detachable.makeNonTextureImage()\n : snapshot;\n\n if (detached !== snapshot) releaseSkiaObject(snapshot);\n ring.push(detached);\n if (ring.length > retentionDepth) {\n releaseSkiaObject(ring.shift()!);\n }\n return detached;\n },\n dispose(): void {\n for (const img of ring) {\n releaseSkiaObject(img);\n }\n ring.length = 0;\n surfaces.dispose();\n postfx?.dispose();\n },\n };\n}\n","import type { SkImageLike } from '@flare-engine/assets';\nimport {\n createFrameRenderer,\n type FrameRenderer,\n type FrameRendererCompiledPass,\n type FrameRendererModule,\n type FrameRendererPostFxChain,\n type FrameRendererPostFxDescriptor,\n type FrameRendererPostFxRuntime,\n type SpriteDrawCommand,\n} from '@flare-engine/render';\nimport type { SkColor, SkImage, SkImageFilter, SkRuntimeEffect } from '@shopify/react-native-skia';\n\n/** Structural canvas — minimal subset needed for offscreen rendering. */\nexport interface SkOffscreenCanvasLike {\n drawPicture(picture: unknown): void;\n drawImageRect(image: unknown, src: unknown, dst: unknown, paint: unknown): void;\n drawRect(rect: unknown, paint: unknown): void;\n clear(color: unknown): void;\n}\n\n/** Structural offscreen surface — what `SkiaModuleLike.Surface.Make` / `MakeOffscreen` return. */\nexport interface SkOffscreenSurfaceLike {\n getCanvas(): SkOffscreenCanvasLike;\n makeImageSnapshot(): SkImageLike;\n /** Force queued draws to execute. Required for GPU-backed surfaces before\n * makeImageSnapshot is called, otherwise the snapshot may capture\n * uninitialized texture content. See Skia's SkSurface.flush docs. */\n flush(): void;\n}\n\n/**\n * A single post-processing pass descriptor built by `buildPostFxPasses`.\n * GameView maps each descriptor to a `<RuntimeShader>` image filter, or to a\n * nested `<Shader>` when a pass carries `children` (see that field).\n */\nexport interface PostFxPassDescriptor {\n /** Stable id, used as React key. */\n readonly id: string;\n /** The compiled SkRuntimeEffect passed as `<RuntimeShader source={…}/>`. */\n readonly source: SkRuntimeEffect;\n /**\n * Uniform map keyed by SkSL uniform name. Vector uniforms are `number[]`\n * whose length equals `columns * rows`; scalar uniforms are `number`.\n * Built by zipping `shader.getUniformName(i)` → sliced Float32Array values.\n */\n readonly uniforms: Record<string, number | readonly number[]>;\n /**\n * Extra sampler children beyond the implicit scene sampler, in SkSL\n * declaration order with `src` excluded. Empty for every built-in effect\n * except color-grading-lut (its LUT image). RN-Skia's `<RuntimeShader>`\n * image filter cannot bind them — it calls `MakeRuntimeShader(rtb, null,\n * null)`, source only — so GameView renders a pass with children, and every\n * pass before it, as a nested `<Shader>` chain whose children are bound\n * positionally: `src` first, then one `<ImageShader>` per entry here.\n */\n readonly children: readonly SkImage[];\n}\n\n/**\n * Take a snapshot of `surface` and detach it from the GPU context so it can\n * be safely sampled from a different GrDirectContext (e.g. the on-screen\n * Canvas). RN-Skia's MakeOffscreen allocates a private Gr context per\n * surface; without this step Skia silently renders black when the texture is\n * read from any other context.\n *\n * Calls `makeNonTextureImage()` when available (RN-Skia ≥ 0.1 on device).\n * Falls back to the raw snapshot when the method is absent (CPU surfaces,\n * test mocks) — no behavioural change in those paths.\n */\nfunction detachSnapshot(surface: SkOffscreenSurfaceLike): SkImageLike {\n const snap = surface.makeImageSnapshot();\n if (typeof snap.makeNonTextureImage === 'function') {\n return snap.makeNonTextureImage();\n }\n return snap;\n}\n\n/** A single axis-aligned rectangle shape to draw into an offscreen surface. */\nexport interface ShapeRect {\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n /** ARGB packed integer: 0xAARRGGBB */\n readonly color: number;\n}\n\n/** Options for `renderShapesToImage`. */\nexport interface RenderShapesOpts {\n readonly width: number;\n readonly height: number;\n /** ARGB packed integer: 0xAARRGGBB */\n readonly clearColor: number;\n readonly shapes: readonly ShapeRect[];\n}\n\n/**\n * Narrow view of the Skia module — only the factories the bridge needs.\n * Declared as its own type so tests can pass a plain mock without pulling\n * in the full `@shopify/react-native-skia` surface.\n *\n * Extends `FrameRendererModule` from `@flare-engine/render` with the\n * native Surface and ImageFilter that are not needed in render-web.\n */\nexport type SkiaModuleLike = FrameRendererModule & {\n RuntimeEffect?: { Make(sksl: string): SkRuntimeEffect | null };\n Surface?: {\n Make(width: number, height: number): SkOffscreenSurfaceLike | null;\n MakeOffscreen?(width: number, height: number): SkOffscreenSurfaceLike | null;\n };\n /** Optional — present on device builds; absent in CPU/test mocks (drop-shadow falls back to the default paint). */\n ImageFilter?: {\n MakeDropShadow(\n dx: number,\n dy: number,\n sigmaX: number,\n sigmaY: number,\n color: SkColor,\n input: SkImageFilter | null,\n ): SkImageFilter;\n };\n};\n\n/**\n * A single compiled postfx pass descriptor produced by the runtime.\n * Re-exported from render's FrameRendererCompiledPass for consumer compatibility.\n */\nexport type CompiledPassLike = FrameRendererCompiledPass;\n\n/**\n * Minimal structural view of a PostFxRuntime that the bridge needs.\n * Re-exported from render's FrameRendererPostFxRuntime for consumer compatibility.\n */\nexport type PostFxRuntimeLike = FrameRendererPostFxRuntime;\n\n/** Minimal structural view of an EffectChain the bridge needs. */\nexport type PostFxChainLike = FrameRendererPostFxChain;\n\n/**\n * Frame renderer that bridges a `SpriteBatch` to a Skia `<Picture>`.\n * The implementation lives in `@flare-engine/render` (`createFrameRenderer`);\n * this interface narrows the return type for native-Skia consumers.\n */\nexport type SkiaFrameRenderer = FrameRenderer;\n\n/**\n * Create a `SkiaFrameRenderer`.\n *\n * `Skia` is passed in (rather than imported) so unit tests can supply a\n * mock. Production code constructs this once inside `<GameView>` using the\n * real `Skia` import from `@shopify/react-native-skia`.\n *\n * Delegates to `createFrameRenderer` from `@flare-engine/render` — the\n * frame-renderer body is backend-neutral and shared with render-web.\n */\nexport function createSkiaFrameRenderer(Skia: SkiaModuleLike): SkiaFrameRenderer {\n return createFrameRenderer(Skia);\n}\n\n// Scratch buffer for ARGB → RGBA-float unpacking in renderShapesToImage.\n// Allocated once per call (not module-level) so concurrent callers are safe.\n// Hot paths inside createSkiaFrameRenderer use their own pre-allocated buffers.\n\n/**\n * Render a list of solid rectangles into a fresh offscreen surface and return\n * the resulting image snapshot. Returns `null` if `Surface` factory is absent or\n * fails. The surface is not cached — callers that need reuse should cache the\n * returned image themselves.\n */\nexport function renderShapesToImage(\n skia: SkiaModuleLike,\n opts: RenderShapesOpts,\n): SkImageLike | null {\n if (skia.Surface === undefined) return null;\n const surface = skia.Surface.Make(opts.width, opts.height);\n if (surface === null) return null;\n\n const scratch = new Float32Array(4);\n const canvas = surface.getCanvas();\n\n unpackArgb(scratch, opts.clearColor);\n canvas.clear(scratch);\n\n const paint = skia.Paint();\n for (const shape of opts.shapes) {\n unpackArgb(scratch, shape.color);\n if (paint.setColor) paint.setColor(scratch);\n const rect = skia.XYWHRect(shape.x, shape.y, shape.w, shape.h);\n canvas.drawRect(rect, paint);\n }\n\n return detachSnapshot(surface);\n}\n\n/** Unpack a 0xAARRGGBB integer into a Float32Array [r, g, b, a] in 0..1 range. */\nfunction unpackArgb(out: Float32Array, 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\n// Re-export the PostFxPassDescriptor shape for GameView consumers.\n// The type is defined above in this file so it carries the concrete SkRuntimeEffect/SkImage\n// types that GameView needs — unlike the generic FrameRendererPostFxDescriptor from render.\n// Alias for clarity at call-sites.\nexport type { FrameRendererPostFxDescriptor, SpriteDrawCommand };\n","import type { FrameRendererCompiledPass } from '@flare-engine/render';\nimport { releaseSkiaObject } from './scene-texture.js';\n\n/**\n * Imperative postfx compositor for the web scene capture: the blit\n * `@flare-engine/render-web`'s `createPostFxSurface` runs, retargeted at\n * RN-Skia's web wrappers (whose `makeShaderWithChildren` does work there).\n * Why the chain runs in place over the capture surface instead of as RN-Skia\n * shader nodes: scene-texture.ts and docs/plans/web-target-2026-08.md §14.\n */\n\n// RN-Skia enum values: TileMode.Clamp, FilterMode.Linear, MipmapMode.None,\n// BlendMode.Src (a full-surface replace, never a blend over the previous pass).\nconst TILE_CLAMP = 0;\nconst FILTER_LINEAR = 1;\nconst MIPMAP_NONE = 0;\nconst BLEND_SRC = 1;\n\n/** The paint subset the compositor drives. */\nexport interface WebPostFxPaintLike {\n setShader(shader: unknown): void;\n setBlendMode(mode: number): void;\n}\n\n/** An image that can be wrapped as a sampler child (RN-Skia web `SkImage`). */\nexport interface WebPostFxImageLike {\n makeShaderOptions(tx: number, ty: number, fm: number, mm: number): unknown;\n}\n\n/** The canvas subset the compositor draws with. */\nexport interface WebPostFxCanvasLike {\n drawRect(rect: { x: number; y: number; width: number; height: number }, paint: unknown): void;\n}\n\n/** The surface subset the compositor runs over — satisfied by `SceneSurfaceLike`. */\nexport interface WebPostFxSurfaceLike<TImage = WebPostFxImageLike> {\n getCanvas(): WebPostFxCanvasLike;\n makeImageSnapshot(): TImage;\n flush(): void;\n}\n\n/** Structural Skia module — only the paint factory is needed. */\nexport interface WebPostFxModuleLike {\n Paint(): WebPostFxPaintLike;\n}\n\n/** Runs compiled postfx passes in place over an offscreen surface. */\nexport interface WebPostFxCompositor<TImage = WebPostFxImageLike> {\n /**\n * Run `passes` in place over `surface`'s current contents; each pass samples\n * a snapshot of the previous result. No-op when `passes` is empty.\n */\n composite(\n surface: WebPostFxSurfaceLike<TImage>,\n passes: readonly FrameRendererCompiledPass[],\n width: number,\n height: number,\n ): void;\n /** Release the paint. */\n dispose(): void;\n}\n\n/**\n * Create a compositor over `Skia.Paint()`. The paint, the full-surface rect and\n * the shader-children array are allocated once and reused, so a frame allocates\n * nothing here beyond the Skia objects each pass creates and releases.\n */\nexport function createWebPostFxCompositor<TImage extends WebPostFxImageLike>(\n Skia: WebPostFxModuleLike,\n): WebPostFxCompositor<TImage> {\n const paint = Skia.Paint();\n paint.setBlendMode(BLEND_SRC);\n const rect = { x: 0, y: 0, width: 0, height: 0 };\n const childrenBuf: unknown[] = [null];\n const wrap = (img: WebPostFxImageLike): unknown =>\n img.makeShaderOptions(TILE_CLAMP, TILE_CLAMP, FILTER_LINEAR, MIPMAP_NONE);\n\n return {\n composite(surface, passes, width, height): void {\n if (passes.length === 0) return;\n rect.width = width;\n rect.height = height;\n const canvas = surface.getCanvas();\n for (let i = 0; i < passes.length; i++) {\n const pass = passes[i];\n if (pass === undefined) continue;\n const snapshot = surface.makeImageSnapshot();\n // src is child 0; pass.children (which excludes src — e.g. the LUT\n // image) follow in SkSL declaration order. Slots are nulled after the\n // pass so a LUT child cannot leak into a later pass.\n const childCount = 1 + pass.children.length;\n childrenBuf.length = childCount;\n childrenBuf[0] = wrap(snapshot);\n for (let c = 0; c < pass.children.length; c++) {\n const child = pass.children[c] as WebPostFxImageLike | null | undefined;\n if (child !== null && child !== undefined) childrenBuf[c + 1] = wrap(child);\n }\n const shader = pass.shader.makeShaderWithChildren(pass.uniforms, childrenBuf);\n if (shader !== null && shader !== undefined) {\n paint.setShader(shader);\n canvas.drawRect(rect, paint);\n paint.setShader(null);\n }\n surface.flush();\n // The pass.children images themselves are caller-owned and stay alive.\n releaseSkiaObject(shader);\n for (let c = 0; c < childCount; c++) {\n releaseSkiaObject(childrenBuf[c]);\n childrenBuf[c] = null;\n }\n releaseSkiaObject(snapshot);\n }\n },\n dispose(): void {\n releaseSkiaObject(paint);\n },\n };\n}\n","import type { AssetLoader } from '@flare-engine/assets';\nimport { AssetManager } from '@flare-engine/assets';\nimport { AudioManager } from '@flare-engine/audio';\nimport { GameLoop } from '@flare-engine/core';\nimport { Position, World } from '@flare-engine/ecs';\nimport { InputManager } from '@flare-engine/input';\nimport {\n Camera2D,\n createRenderSystem,\n type FrameRendererCompiledPass,\n Renderer,\n Sprite,\n SpriteBatch,\n} from '@flare-engine/render';\nimport { SceneManager } from '@flare-engine/scene';\nimport type { CanvasRef, SkImage, SkPicture, SkSurface } from '@shopify/react-native-skia';\nimport {\n Canvas,\n FilterMode,\n Image,\n ImageShader,\n MipmapMode,\n Rect,\n RuntimeShader,\n Shader,\n Skia,\n useCanvasRef,\n} from '@shopify/react-native-skia';\nimport type React from 'react';\nimport { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport type { GestureResponderEvent, LayoutChangeEvent, ViewStyle } from 'react-native';\nimport { PixelRatio, Platform, StyleSheet, View } from 'react-native';\nimport { type SharedValue, useSharedValue } from 'react-native-reanimated';\nimport { SafeAreaInsetsContext } from 'react-native-safe-area-context';\nimport { scheduleOnUI } from 'react-native-worklets';\nimport { GameContext, type GameContextValue } from './game-context.js';\nimport { type SafeArea, SafeAreaContext } from './safe-area.js';\nimport { createSceneCapture, type SceneCapture } from './scene-texture.js';\nimport { createSkiaFrameRenderer, type PostFxPassDescriptor } from './skia-bridge.js';\nimport { createWebPostFxCompositor } from './web-postfx.js';\n\n/**\n * Capture the frame's picture into an offscreen surface **on the UI thread**.\n *\n * The thread is the entire point, and getting it wrong is invisible to every\n * test in this repo. RN-Skia's own `usePictureAsTexture` does exactly this work\n * inside `runOnUI` (`external/reanimated/textures.ts`), and it must: a surface\n * built on the JS thread belongs to a different GL context than the on-screen\n * `<Canvas>`, so the `<Image>` samples nothing and the app renders a black\n * frame while the game loop runs happily. Building the surface here — same\n * thread, same context as the canvas that samples it — is what makes the\n * snapshot drawable without a `makeNonTextureImage()` GPU→CPU readback.\n *\n * Verified on device (Pixel 7 / Android 17): JS-thread capture → black canvas;\n * this path → renders. See external-review-2026-08.md §11.4b.\n *\n * The surface is cached across frames in a shared value rather than rebuilt per\n * frame (RN-Skia rebuilds it every call; that is NEW-2). `surfaceKey` packs the\n * pixel size so a viewport change reallocates exactly once.\n */\nconst captureSceneOnUI = (\n target: SharedValue<SkImage | null>,\n surfaceSV: SharedValue<SkSurface | null>,\n surfaceKey: SharedValue<number>,\n picture: SkPicture,\n w: number,\n h: number,\n): void => {\n 'worklet';\n const key = w * 65536 + h;\n if (surfaceSV.value === null || surfaceKey.value !== key) {\n surfaceSV.value = Skia.Surface.MakeOffscreen(w, h);\n surfaceKey.value = key;\n }\n const surface = surfaceSV.value;\n if (surface === null) return;\n surface.getCanvas().drawPicture(picture);\n surface.flush();\n target.value = surface.makeImageSnapshot();\n};\n\n/** Render hook invoked during the frame — receives the game context and\n * the active Skia canvas for direct draw calls. Hooks run between\n * `renderer.applyCamera()` and `renderer.end()`, so the camera transform\n * is already applied. */\nexport type RenderHook = (ctx: GameContextValue, canvas: unknown) => void;\n\n/** Render hook for post-processing passes. Receives the game context, the\n * active Skia canvas, and the `SkiaFrameRenderer` bridge so the hook can\n * call `bridge.setPostFxBinding(runtime, chain)` to register the runtime\n * and chain for the current frame. The bound chain renders on native through\n * RN-Skia shader nodes and on web through the imperative composite inside the\n * scene capture (see `createWebPostFxCompositor`).\n * `bridge` is `null` only on platforms where no Skia renderer was created. */\nexport type PostFxRenderHook = (\n ctx: GameContextValue,\n canvas: unknown,\n bridge: import('./skia-bridge.js').SkiaFrameRenderer | null,\n) => void;\n\n/** Configuration passed to <GameView>. */\nexport interface GameConfig {\n /** Fixed timestep in seconds (default 1/60). */\n fixedDt?: number;\n /** Maximum dt cap in seconds (default 0.25). */\n maxDt?: number;\n /** Background clear color as 32-bit ARGB int (default 0xFF000000). */\n clearColor?: number;\n /** Asset loader function — injected into AssetManager at construction. */\n assetLoader?: AssetLoader;\n /** Called after camera transform and before the sprite render system.\n * Intended for tilemap / background layer rendering. */\n onRenderBackground?: RenderHook;\n /** Called after the sprite batch has been flushed, before `renderer.end()`.\n * Receives the bridge as 3rd arg so the hook can call\n * `bridge.setPostFxBinding(runtime, chain)` to register the postfx runtime\n * and chain for the current frame, on native and on web alike. */\n onRenderPostFx?: PostFxRenderHook;\n /**\n * Promote the underlying Skia surface from a TextureView (default) to a\n * SurfaceView on Android. With `opaque: true`, SurfaceView paints in a\n * separate compositing layer below the regular RN view tree, which lets\n * full-screen RN overlays (HUDs, menus) render on top without needing\n * elevation/zIndex tricks.\n *\n * Without this, RN-Skia's TextureView can clip overlapping full-screen\n * RN siblings on certain Android devices/Fabric configurations.\n *\n * Implies the canvas content is opaque — the clearColor's alpha must be\n * fully opaque (0xFF), which the default `0xff000000` already satisfies.\n * Defaults to `false` to preserve the current iOS-equivalent behavior.\n *\n * **Recommended on Android.** Measured on a Pixel 7 (Android 17, release\n * build, XR-1c): with the default TextureView path RN-Skia logs its\n * `updateTexImage: LegacySurfaceTexture is not attached!` /\n * `updateAndRelease() failed` pair **22 028 times per 60 s** — 90% of all\n * logcat output, saturating the 256 KiB ring buffer so unrelated diagnostics\n * are lost. With `opaque: true` the same build over three 60 s windows logs\n * the pair **zero** times and total log volume drops ~10x. RN-Skia labels the\n * pair ignorable and rendering is correct either way, so this is log noise\n * and TextureView overhead, not a correctness fix. Native memory is flat\n * across a 6-minute soak on both paths.\n */\n opaque?: boolean;\n}\n\n/** Props for the <GameView> component. */\nexport interface GameViewProps {\n /** Game configuration. */\n config?: GameConfig;\n /** Called once the game context is ready (loop not yet started). */\n onReady?: (ctx: GameContextValue) => void;\n /** Style applied to the outer View container. */\n style?: ViewStyle;\n /** Optional overlay children (e.g. VirtualJoystick, VirtualButton). */\n children?: React.ReactNode;\n /** Explicit safe-area insets. If omitted, resolved via `useContext(SafeAreaInsetsContext)`\n * from react-native-safe-area-context; falls back to `{ top: 0, right: 0, bottom: 0,\n * left: 0 }` when no `<SafeAreaProvider>` ancestor is mounted. */\n safeArea?: SafeArea;\n}\n\n/**\n * GameView — root component that sets up the Skia canvas, game loop,\n * and all core game systems. Provides GameContext to descendants.\n *\n * Overlay controls (VirtualJoystick, VirtualButton) should be placed\n * as children; they render on top of the Skia canvas.\n */\nexport function GameView({\n config,\n onReady,\n style,\n children,\n safeArea,\n}: GameViewProps): React.ReactElement {\n // useContext must run unconditionally (hook rules), even when `safeArea` makes its\n // value unused below — it never throws, unlike useSafeAreaInsets() without a provider.\n const contextInsets = useContext(SafeAreaInsetsContext);\n const resolvedSafeArea: SafeArea = safeArea ?? contextInsets ?? ZERO_INSETS;\n const canvasRef = useCanvasRef();\n const [passes, setPasses] = useState<readonly PostFxPassDescriptor[]>(EMPTY_PASSES);\n const [viewportSize, setViewportSize] = useState({ w: 0, h: 0 });\n const pd = PixelRatio.get();\n const isWeb = Platform.OS === 'web';\n // Both platforms write captured frames into a Reanimated shared value so\n // rn-skia's <Image> reads the latest frame on the UI thread without a React\n // re-render. createSceneCapture reuses one offscreen surface per viewport\n // size (fixing per-frame MakeOffscreen on native, NEW-2) and gates the\n // GPU→CPU makeNonTextureImage() copy to web only, where cross-context\n // sampling requires it (web: nonTextureImage true, native: false).\n const sceneImage = useSharedValue<SkImage | null>(null);\n const captureRef = useRef<SceneCapture<SkImage> | null>(null);\n // Native only: the offscreen surface lives on the UI thread, so it is held in\n // shared values rather than a ref — a ref would put it back on the JS thread\n // and reintroduce the black-frame regression captureSceneOnUI exists to fix.\n const uiSurface = useSharedValue<SkSurface | null>(null);\n const uiSurfaceKey = useSharedValue(0);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: intentional mount-only\n const ctx = useMemo<GameContextValue>(() => {\n const loop = new GameLoop({\n fixedDt: config?.fixedDt,\n maxDt: config?.maxDt,\n });\n const world = new World();\n const camera = new Camera2D();\n const input = new InputManager();\n const audio = new AudioManager();\n const noop: AssetLoader = () => Promise.resolve(null);\n const assets = new AssetManager(config?.assetLoader ?? noop);\n const scenes = new SceneManager();\n const renderer = new Renderer();\n const batch = new SpriteBatch();\n return { world, camera, input, audio, assets, scenes, loop, renderer, batch };\n }, []);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: intentional mount-only\n useEffect(() => {\n const bridge = createSkiaFrameRenderer(Skia);\n ctx.renderer.setCanvas(bridge.canvas);\n\n const clearColor = config?.clearColor ?? 0xff000000;\n const onRenderBackground = config?.onRenderBackground;\n const onRenderPostFx = config?.onRenderPostFx;\n\n const spriteQuery = ctx.world.query(Position, Sprite);\n const renderSystem = createRenderSystem(ctx.world, spriteQuery, Position, Sprite, ctx.batch);\n\n // Last passes signature pushed to state; gates setPasses so an unchanged\n // (or empty) chain does not churn a fresh array + RuntimeShader tree every\n // frame. Seeded to the same EMPTY_PASSES the state holds, so an empty chain\n // never triggers a re-render from passes.\n let prevBuilt: readonly PostFxPassDescriptor[] = EMPTY_PASSES;\n\n const unsubscribeLate = ctx.loop.onLateUpdate.add((dt) => {\n ctx.camera.update(dt);\n ctx.input.update();\n });\n\n const unsubscribePre = ctx.loop.onPreRender.add(() => {\n const w = ctx.camera.viewportWidth;\n const h = ctx.camera.viewportHeight;\n bridge.beginFrame(w, h, ctx.loop.clock.elapsed, pd);\n ctx.renderer.begin(clearColor);\n ctx.renderer.applyCamera(\n ctx.camera.effectiveX,\n ctx.camera.effectiveY,\n ctx.camera.zoom,\n ctx.camera.rotation,\n w,\n h,\n );\n if (onRenderBackground) onRenderBackground(ctx, ctx.renderer.canvas);\n renderSystem();\n ctx.batch.flush(bridge.drawAtlas, ctx.renderer);\n if (onRenderPostFx) onRenderPostFx(ctx, ctx.renderer.canvas, bridge);\n ctx.renderer.end();\n const pic = bridge.endFrame();\n if (pic !== null) {\n if (isWeb) {\n // Web has one thread, so the JS-thread capture is same-context by\n // construction; this is the path WEB-1..WEB-7 verified in Chrome,\n // including the surface cache that keeps Chrome from evicting the\n // on-screen canvas (web-target-2026-08.md §12). The postfx chain runs\n // inside the capture, in place on that same surface (#60), so the\n // image the plain <Image> below samples is already filtered.\n if (captureRef.current === null) {\n captureRef.current = createSceneCapture(Skia, {\n nonTextureImage: true,\n retentionDepth: 3,\n postfx: createWebPostFxCompositor<SkImage>(Skia),\n });\n }\n // Physical pixels: the surface is w*pd × h*pd and every SkSL\n // `resolution` uniform must match the space the pass is drawn in.\n const fx = bridge.hasPostFxBinding()\n ? bridge.compilePostFxPasses(null, null, w * pd, h * pd)\n : EMPTY_COMPILED;\n const img = captureRef.current.capture(pic, w * pd, h * pd, fx);\n if (img !== null) sceneImage.value = img;\n } else {\n // Native must build the surface on the UI thread — see captureSceneOnUI.\n // `scheduleOnUI` and not Reanimated's `runOnUI`: the latter is curried,\n // so `runOnUI(fn)` allocated a fresh wrapper on every frame in this\n // hook. Passing the args directly allocates nothing (ADR-0002).\n scheduleOnUI(\n captureSceneOnUI,\n sceneImage,\n uiSurface,\n uiSurfaceKey,\n pic as SkPicture,\n w * pd,\n h * pd,\n );\n }\n }\n // Web never pushes passes: its chain was composited into the scene image\n // above, so `passes` stays EMPTY_PASSES and the tree is the plain <Image>.\n if (!isWeb) {\n const built = bridge.buildPostFxPasses(null, null, w, h) as readonly PostFxPassDescriptor[];\n if (!samePasses(prevBuilt, built)) {\n prevBuilt = built.length === 0 ? EMPTY_PASSES : built;\n setPasses(prevBuilt);\n }\n }\n canvasRef.current?.redraw();\n });\n\n onReady?.(ctx);\n ctx.loop.start();\n return () => {\n unsubscribeLate();\n unsubscribePre();\n captureRef.current?.dispose();\n captureRef.current = null;\n ctx.loop.stop();\n };\n }, []);\n\n const handleLayout = useCallback(\n (event: LayoutChangeEvent): void => {\n const { width, height } = event.nativeEvent.layout;\n ctx.camera.setViewport(width, height);\n setViewportSize({ w: width, h: height });\n },\n [ctx],\n );\n\n const onGrant = useCallback(\n (e: GestureResponderEvent): void => {\n const { changedTouches, identifier, locationX, locationY } = e.nativeEvent;\n if (changedTouches.length === 0) {\n ctx.input.onPointerDown(Number(identifier), locationX, locationY);\n return;\n }\n for (let i = 0; i < changedTouches.length; i++) {\n const t = changedTouches[i];\n if (t === undefined) continue;\n ctx.input.onPointerDown(Number(t.identifier), t.locationX, t.locationY);\n }\n },\n [ctx],\n );\n const onMove = useCallback(\n (e: GestureResponderEvent): void => {\n const { changedTouches, identifier, locationX, locationY } = e.nativeEvent;\n if (changedTouches.length === 0) {\n ctx.input.onPointerMove(Number(identifier), locationX, locationY);\n return;\n }\n for (let i = 0; i < changedTouches.length; i++) {\n const t = changedTouches[i];\n if (t === undefined) continue;\n ctx.input.onPointerMove(Number(t.identifier), t.locationX, t.locationY);\n }\n },\n [ctx],\n );\n const onRelease = useCallback(\n (e: GestureResponderEvent): void => {\n const { changedTouches, identifier, locationX, locationY } = e.nativeEvent;\n if (changedTouches.length === 0) {\n ctx.input.onPointerUp(Number(identifier), locationX, locationY);\n return;\n }\n for (let i = 0; i < changedTouches.length; i++) {\n const t = changedTouches[i];\n if (t === undefined) continue;\n ctx.input.onPointerUp(Number(t.identifier), t.locationX, t.locationY);\n }\n },\n [ctx],\n );\n\n const containerStyle = useMemo(() => [styles.container, style], [style]);\n // RN-Skia's <RuntimeShader> image filter binds the implicit source only\n // (MakeRuntimeShader(rtb, null, null)) and never consumes child shaders, so a\n // pass with extra sampler children (color-grading-lut) would be dropped by\n // it. Such a pass, and every pass before it, runs as one paint shader on a\n // <Rect> instead: nested <Shader>s bind their children positionally (src,\n // then each entry of pass.children), the convention render-web uses. Passes\n // after the last child-bearing one stay <RuntimeShader> image filters — a\n // nested <Shader> re-evaluates src per tap, which would multiply reads for\n // multi-tap effects. A chain with no children keeps the plain <Image> tree.\n const canvasContent = useMemo(() => {\n if (viewportSize.w === 0) return null;\n const w = viewportSize.w;\n const h = viewportSize.h;\n const last = lastPassWithChildren(passes);\n if (last < 0) {\n return (\n <Image image={sceneImage} x={0} y={0} width={w} height={h} fit=\"cover\">\n {passes.map((p) => (\n <RuntimeShader key={p.id} source={p.source} uniforms={p.uniforms} />\n ))}\n </Image>\n );\n }\n let shader: React.ReactElement = (\n <ImageShader\n image={sceneImage}\n fit=\"cover\"\n rect={{ x: 0, y: 0, width: w, height: h }}\n tx=\"clamp\"\n ty=\"clamp\"\n sampling={LINEAR_SAMPLING}\n />\n );\n for (let i = 0; i <= last; i++) {\n const p = passes[i];\n if (p === undefined) continue;\n const samplers: React.ReactElement[] = [];\n for (let c = 0; c < p.children.length; c++) {\n samplers.push(\n <ImageShader\n key={c}\n image={p.children[c] ?? null}\n tx=\"clamp\"\n ty=\"clamp\"\n sampling={LINEAR_SAMPLING}\n />,\n );\n }\n shader = (\n <Shader source={p.source} uniforms={p.uniforms}>\n {shader}\n {samplers}\n </Shader>\n );\n }\n const filters: React.ReactElement[] = [];\n for (let i = last + 1; i < passes.length; i++) {\n const p = passes[i];\n if (p === undefined) continue;\n filters.push(<RuntimeShader key={p.id} source={p.source} uniforms={p.uniforms} />);\n }\n return (\n <Rect x={0} y={0} width={w} height={h}>\n {shader}\n {filters}\n </Rect>\n );\n }, [passes, viewportSize, sceneImage]);\n\n return (\n <SafeAreaContext.Provider value={resolvedSafeArea}>\n <GameContext.Provider value={ctx}>\n <View\n style={containerStyle}\n onLayout={handleLayout}\n onStartShouldSetResponder={returnTrue}\n onResponderGrant={onGrant}\n onResponderMove={onMove}\n onResponderRelease={onRelease}\n onResponderTerminate={onRelease}\n >\n <Canvas\n ref={canvasRef as React.Ref<CanvasRef>}\n style={StyleSheet.absoluteFill}\n pointerEvents=\"none\"\n opaque={config?.opaque ?? false}\n >\n {canvasContent}\n </Canvas>\n {children}\n </View>\n </GameContext.Provider>\n </SafeAreaContext.Provider>\n );\n}\n\nfunction returnTrue(): boolean {\n return true;\n}\n\n/** Stable empty-chain reference — an empty `buildPostFxPasses` result collapses\n * to this so the `passes` state never changes for a postfx-free GameView. */\nconst EMPTY_PASSES: readonly PostFxPassDescriptor[] = [];\n\n/** Stable empty compiled-pass list handed to the web capture when no chain is bound. */\nconst EMPTY_COMPILED: readonly FrameRendererCompiledPass[] = Object.freeze([]);\n\n/** Linear, mipmap-free sampling for every ImageShader in the pass chain — the\n * options render-web hands makeShaderOptions, so both backends sample alike. */\nconst LINEAR_SAMPLING = { filter: FilterMode.Linear, mipmap: MipmapMode.None };\n\n/** Index of the last pass carrying extra sampler children, or -1 when none does. */\nfunction lastPassWithChildren(passes: readonly PostFxPassDescriptor[]): number {\n for (let i = passes.length - 1; i >= 0; i--) {\n const p = passes[i];\n if (p !== undefined && p.children.length > 0) return i;\n }\n return -1;\n}\n\n/** Fallback insets when no `<SafeAreaProvider>` ancestor supplies a context value. */\nconst ZERO_INSETS: SafeArea = { top: 0, right: 0, bottom: 0, left: 0 };\n\n/**\n * Shallow structural equality of two pass lists. The signature is length +\n * per-pass `id` + shader ref + child-image refs + uniform values. Uniforms are\n * compared (not just `id`/`source`) because animating effects — the hit-flash\n * decay and timed triggers — keep a constant `id`/`source` while only their\n * uniform values change frame to frame; excluding them would freeze those\n * animations. Cost is trivial: postfx chains hold a handful of scalar/short-vec\n * uniforms.\n */\nfunction samePasses(\n a: readonly PostFxPassDescriptor[],\n b: readonly PostFxPassDescriptor[],\n): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const pa = a[i];\n const pb = b[i];\n if (pa === undefined || pb === undefined) return false;\n if (pa.id !== pb.id || pa.source !== pb.source) return false;\n if (!sameChildren(pa.children, pb.children)) return false;\n if (!sameUniforms(pa.uniforms, pb.uniforms)) return false;\n }\n return true;\n}\n\nfunction sameChildren(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nfunction sameUniforms(\n a: PostFxPassDescriptor['uniforms'],\n b: PostFxPassDescriptor['uniforms'],\n): boolean {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n const va = a[key];\n const vb = b[key];\n if (va === undefined || vb === undefined) return false;\n if (typeof va === 'number') {\n if (va !== vb) return false;\n } else {\n if (typeof vb === 'number' || va.length !== vb.length) return false;\n for (let i = 0; i < va.length; i++) {\n if (va[i] !== vb[i]) return false;\n }\n }\n }\n return true;\n}\n\nconst styles = StyleSheet.create({\n container: { flex: 1 },\n});\n","import type { Query } from '@flare-engine/ecs';\nimport { useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport { GameContext, type GameContextValue } from './game-context.js';\n\n/**\n * useGame — returns the GameContextValue from the nearest <GameView>.\n * Throws if called outside a <GameView>.\n */\nexport function useGame(): GameContextValue {\n const ctx = useContext(GameContext);\n if (!ctx) {\n throw new Error('useGame must be used inside a <GameView>');\n }\n return ctx;\n}\n\n/**\n * useEntity — subscribes to an ECS Query and returns the current entity list.\n * Re-renders when entities are added to or removed from the query.\n *\n * @param query An active Query obtained from world.query(...)\n */\nexport function useEntity(query: Query): readonly number[] {\n const [entities, setEntities] = useState<readonly number[]>(() => Array.from(query));\n\n useEffect(() => {\n const refresh = () => setEntities(Array.from(query));\n\n const unsubAdd = query.onEntityAdded.add(refresh);\n const unsubRemove = query.onEntityRemoved.add(refresh);\n\n // Sync initial state (query may have changed between render and effect)\n refresh();\n\n return () => {\n unsubAdd();\n unsubRemove();\n };\n }, [query]);\n\n return entities;\n}\n\n/**\n * useGameLoop — registers a per-frame callback on the game loop's onUpdate signal.\n * The callback is called each frame with delta time in seconds.\n * Automatically unregisters on unmount.\n *\n * @param callback Function called each frame with dt in seconds.\n */\nexport function useGameLoop(callback: (dt: number) => void): void {\n const { loop } = useGame();\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n const stable = useCallback((dt: number) => {\n callbackRef.current(dt);\n }, []);\n\n useEffect(() => {\n const unsub = loop.onUpdate.add(stable);\n return () => {\n unsub();\n };\n }, [loop, stable]);\n}\n","import type React from 'react';\nimport type { ViewStyle } from 'react-native';\nimport { StyleSheet, View } from 'react-native';\n\n/** Props for the <LoadingScreen> component. */\nexport interface LoadingScreenProps {\n /** Progress in [0, 1]. Values outside this range are clamped. */\n progress: number;\n /** Style applied to the outer container (covers parent by default). */\n style?: ViewStyle;\n /** Filled portion color. */\n barColor?: string;\n /** Track color. */\n trackColor?: string;\n /** Background color behind the track. */\n backgroundColor?: string;\n}\n\n/**\n * LoadingScreen — full-screen asset-load overlay.\n *\n * Renders before `<GameView>` mounts its Skia canvas (or alongside it\n * while `AssetManager.load()` resolves). Pure RN Views so it works\n * without a live Skia context. Consumers drive `progress` from the\n * AssetManager progress callback.\n */\nexport function LoadingScreen({\n progress,\n style,\n barColor = '#ffffff',\n trackColor = 'rgba(255,255,255,0.2)',\n backgroundColor = '#000000',\n}: LoadingScreenProps): React.ReactElement {\n const clamped = progress < 0 ? 0 : progress > 1 ? 1 : progress;\n const percent = `${Math.round(clamped * 100)}%` as `${number}%`;\n\n return (\n <View style={[styles.container, { backgroundColor }, style]}>\n <View style={[styles.track, { backgroundColor: trackColor }]}>\n <View style={[styles.bar, { width: percent, backgroundColor: barColor }]} />\n </View>\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n position: 'absolute',\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n alignItems: 'center',\n justifyContent: 'center',\n padding: 32,\n },\n track: {\n width: '80%',\n height: 6,\n borderRadius: 3,\n overflow: 'hidden',\n },\n bar: {\n height: '100%',\n },\n});\n","import type { Signal } from '@flare-engine/events';\nimport { easeOutCubic } from '@flare-engine/math';\nimport { useEffect, useRef, useState } from 'react';\n\nexport function useOverlayFade(visible: boolean, durationMs = 300): number {\n const target = visible ? 1 : 0;\n const [opacity, setOpacity] = useState<number>(target);\n const opacityRef = useRef<number>(opacity);\n const startRef = useRef<number | null>(null);\n const rafRef = useRef<number | null>(null);\n\n // Keep ref in sync with state (runs before effect)\n opacityRef.current = opacity;\n\n useEffect(() => {\n if (typeof requestAnimationFrame === 'undefined') {\n setOpacity(target);\n return;\n }\n const from = opacityRef.current;\n startRef.current = null;\n if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);\n\n const step = (now: number) => {\n if (startRef.current === null) startRef.current = now;\n const t = Math.min((now - startRef.current) / durationMs, 1);\n setOpacity(from + (target - from) * t);\n if (t < 1) {\n rafRef.current = requestAnimationFrame(step);\n }\n };\n rafRef.current = requestAnimationFrame(step);\n return () => {\n if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);\n };\n }, [target, durationMs]);\n\n return opacity;\n}\n\nexport function useCountUp(target: number, durationMs = 600): number {\n const [value, setValue] = useState<number>(target);\n const valueRef = useRef<number>(value);\n const startRef = useRef<number | null>(null);\n const rafRef = useRef<number | null>(null);\n\n // Keep ref in sync with state (runs before effect)\n valueRef.current = value;\n\n useEffect(() => {\n if (typeof requestAnimationFrame === 'undefined') {\n setValue(target);\n return;\n }\n const from = valueRef.current;\n startRef.current = null;\n if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);\n\n const step = (now: number) => {\n if (startRef.current === null) startRef.current = now;\n const t = Math.min((now - startRef.current) / durationMs, 1);\n setValue(from + (target - from) * easeOutCubic(t));\n if (t < 1) {\n rafRef.current = requestAnimationFrame(step);\n }\n };\n rafRef.current = requestAnimationFrame(step);\n return () => {\n if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);\n };\n }, [target, durationMs]);\n\n return value;\n}\n\nexport function useSignalState<T>(signal: Signal<T>, initial: T): T {\n const [state, setState] = useState<T>(initial);\n\n useEffect(() => {\n const disposer = signal.add(setState);\n return disposer;\n }, [signal]);\n\n return state;\n}\n","import type { SkiaAtlasModuleLike } from '@flare-engine/assets';\nimport { Skia } from '@shopify/react-native-skia';\n\n/**\n * The RN-Skia module adapted to the engine's structural atlas interface.\n * Centralises the one boundary assertion so template code stays cast-free.\n */\nexport const skiaAtlasModule: SkiaAtlasModuleLike = Skia as unknown as SkiaAtlasModuleLike;\n","import {\n createButtonState,\n pressButton,\n releaseButton,\n resetButtonFrame,\n type VirtualButtonState,\n} from '@flare-engine/input';\nimport type React from 'react';\nimport { useCallback, useRef } from 'react';\nimport type { ViewStyle } from 'react-native';\nimport { StyleSheet, View } from 'react-native';\n\n/** Props for the <VirtualButton> component. */\nexport interface VirtualButtonProps {\n /** Called on each state change. */\n onStateChange?: (state: VirtualButtonState) => void;\n /** Style applied to the button. */\n style?: ViewStyle;\n /** Button label / overlay content. */\n children?: React.ReactNode;\n}\n\n/**\n * VirtualButton — an on-screen button overlay component.\n *\n * Uses raw `onTouchStart`/`onTouchEnd` so press and release fire regardless\n * of which ancestor holds the RN responder — enabling simultaneous use with\n * `<VirtualJoystick>` without responder conflicts.\n */\nexport function VirtualButton({\n onStateChange,\n style,\n children,\n}: VirtualButtonProps): React.ReactElement {\n const stateRef = useRef<VirtualButtonState>(createButtonState());\n\n const handlePress = useCallback(() => {\n resetButtonFrame(stateRef.current);\n pressButton(stateRef.current);\n onStateChange?.(stateRef.current);\n }, [onStateChange]);\n\n const handleRelease = useCallback(() => {\n resetButtonFrame(stateRef.current);\n releaseButton(stateRef.current);\n onStateChange?.(stateRef.current);\n }, [onStateChange]);\n\n return (\n <View\n style={[styles.button, style]}\n onTouchStart={handlePress}\n onTouchEnd={handleRelease}\n onTouchCancel={handleRelease}\n >\n {children}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n button: {\n width: 60,\n height: 60,\n borderRadius: 30,\n backgroundColor: 'rgba(255,255,255,0.3)',\n alignItems: 'center',\n justifyContent: 'center',\n },\n});\n","import {\n createJoystickState,\n releaseJoystick,\n updateJoystick,\n type VirtualJoystickConfig,\n type VirtualJoystickState,\n} from '@flare-engine/input';\nimport type React from 'react';\nimport { useCallback, useRef, useState } from 'react';\nimport type { GestureResponderEvent, ViewStyle } from 'react-native';\nimport { StyleSheet, View } from 'react-native';\n\n/** Props for the <VirtualJoystick> component. */\nexport interface VirtualJoystickProps {\n /** Joystick configuration (dead zone, max radius). */\n config?: VirtualJoystickConfig;\n /** Called on each state change. */\n onStateChange?: (state: VirtualJoystickState) => void;\n /** Style applied to the outer container. */\n style?: ViewStyle;\n /** Custom node rendered in place of the default base circle View. */\n base?: React.ReactNode;\n /** Custom node rendered in place of the default knob View. */\n thumb?: React.ReactNode;\n}\n\ntype TouchPoint = GestureResponderEvent['nativeEvent'];\n\n/** The finger that holds the stick, and the page position of the stick's top-left corner. */\ninterface Finger {\n id: TouchPoint['identifier'] | null;\n originX: number;\n originY: number;\n}\n\n/**\n * VirtualJoystick — an on-screen joystick overlay component.\n *\n * Renders a base circle and a knob that follows the user's touch.\n * Claims the React Native touch responder so children of a parent that\n * also claims the responder (e.g. <GameView>) still receive move/end events.\n */\nexport function VirtualJoystick({\n config,\n onStateChange,\n style,\n base,\n thumb,\n}: VirtualJoystickProps): React.ReactElement {\n const stateRef = useRef<VirtualJoystickState>(createJoystickState());\n const sizeRef = useRef<{ w: number; h: number }>({ w: 0, h: 0 });\n const fingerRef = useRef<Finger>({ id: null, originX: 0, originY: 0 });\n const [knob, setKnob] = useState({ x: 0, y: 0 });\n\n const handleLayout = useCallback(\n (e: { nativeEvent: { layout: { width: number; height: number } } }) => {\n sizeRef.current = { w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height };\n },\n [],\n );\n\n const moveTo = useCallback(\n (touchX: number, touchY: number) => {\n const { w, h } = sizeRef.current;\n updateJoystick(stateRef.current, w / 2, h / 2, touchX, touchY, config);\n onStateChange?.(stateRef.current);\n const { x, y } = stateRef.current.offset;\n setKnob((prev) => (prev.x === x && prev.y === y ? prev : { x, y }));\n },\n [config, onStateChange],\n );\n\n // No child of the stick is a touch target, so at grant `locationX/Y` is measured\n // against the stick on every platform. Android measures later events against\n // whichever view is under the finger by then, so moves are read as page\n // coordinates from the origin taken here.\n const handleGrant = useCallback(\n (e: GestureResponderEvent) => {\n const touch = e.nativeEvent;\n const finger = fingerRef.current;\n finger.id = touch.identifier;\n finger.originX = touch.pageX - touch.locationX;\n finger.originY = touch.pageY - touch.locationY;\n moveTo(touch.locationX, touch.locationY);\n },\n [moveTo],\n );\n\n const handleMove = useCallback(\n (e: GestureResponderEvent) => {\n const finger = fingerRef.current;\n const touch = findTouch(e.nativeEvent, finger.id);\n if (touch === undefined) return;\n moveTo(touch.pageX - finger.originX, touch.pageY - finger.originY);\n },\n [moveTo],\n );\n\n const handleRelease = useCallback(() => {\n releaseJoystick(stateRef.current);\n onStateChange?.(stateRef.current);\n setKnob((prev) => (prev.x === 0 && prev.y === 0 ? prev : { x: 0, y: 0 }));\n }, [onStateChange]);\n\n const maxRadius = config?.maxRadius ?? 50;\n\n return (\n <View\n style={[\n styles.center,\n ...(base ? [] : [styles.baseBg]),\n {\n width: maxRadius * 2,\n height: maxRadius * 2,\n borderRadius: maxRadius,\n },\n style,\n ]}\n onLayout={handleLayout}\n onStartShouldSetResponder={returnTrue}\n onMoveShouldSetResponder={returnTrue}\n onResponderGrant={handleGrant}\n onResponderMove={handleMove}\n onResponderRelease={handleRelease}\n onResponderTerminate={handleRelease}\n onResponderTerminationRequest={returnFalse}\n >\n {base ? (\n <View style={StyleSheet.absoluteFill} pointerEvents=\"none\">\n {base}\n </View>\n ) : null}\n {thumb ? (\n <View\n style={{ transform: [{ translateX: knob.x }, { translateY: knob.y }] }}\n pointerEvents=\"none\"\n >\n {thumb}\n </View>\n ) : (\n <View\n style={[styles.knob, { transform: [{ translateX: knob.x }, { translateY: knob.y }] }]}\n />\n )}\n </View>\n );\n}\n\n/**\n * The stick's own finger in a touch event. The event's own fields describe the\n * first changed touch, which can be another finger on the screen.\n */\nfunction findTouch(event: TouchPoint, id: Finger['id']): TouchPoint | undefined {\n const touches = event.touches;\n if (touches !== undefined) {\n for (let i = 0; i < touches.length; i++) {\n const touch = touches[i];\n if (touch !== undefined && touch.identifier === id) return touch;\n }\n }\n return event.identifier === id ? event : undefined;\n}\n\nfunction returnTrue(): boolean {\n return true;\n}\n\nfunction returnFalse(): boolean {\n return false;\n}\n\nconst styles = StyleSheet.create({\n center: {\n alignItems: 'center',\n justifyContent: 'center',\n },\n baseBg: {\n backgroundColor: 'rgba(255,255,255,0.2)',\n },\n knob: {\n width: 40,\n height: 40,\n borderRadius: 20,\n backgroundColor: 'rgba(255,255,255,0.6)',\n pointerEvents: 'none',\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,eAAA,GAAcA,MAAAA,cAAAA,CAAuC,IAAI;;AC1BtE,MAAa,mBAAA,GAAkBC,MAAAA,cAAAA,CAA+B,IAAI;AAElE,SAAgB,cAAwB;CACtC,MAAM,SAAA,GAAQC,MAAAA,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AD;GAAM,OAAOC,aAAAA,WAAW;GAAc,eAAc;GACjD,UAAA;EACG,CAAA,IACJ,MACH,QACC,iBAAA,GAAA,kBAAA,IAAA,CAACD,aAAAA,MAAD;GACE,OAAO,EAAE,WAAW,CAAC,EAAE,YAAY,KAAK,EAAE,GAAG,EAAE,YAAY,KAAK,EAAE,CAAC,EAAE;GACrE,eAAc;GAEb,UAAA;EACG,CAAA,IAEN,iBAAA,GAAA,kBAAA,IAAA,CAACA,aAAAA,MAAD,EACE,OAAO,CAAC,OAAO,MAAM,EAAE,WAAW,CAAC,EAAE,YAAY,KAAK,EAAE,GAAG,EAAE,YAAY,KAAK,EAAE,CAAC,EAAE,CAAC,EACrF,CAAA,CAEC;;AAEV;;;;;AAMA,SAAS,UAAU,OAAmB,IAA0C;CAC9E,MAAM,UAAU,MAAM;CACtB,IAAI,YAAY,KAAA,GACd,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;EACvC,MAAM,QAAQ,QAAQ;EACtB,IAAI,UAAU,KAAA,KAAa,MAAM,eAAe,IAAI,OAAO;CAC7D;CAEF,OAAO,MAAM,eAAe,KAAK,QAAQ,KAAA;AAC3C;AAEA,SAAS,aAAsB;CAC7B,OAAO;AACT;AAEA,SAAS,cAAuB;CAC9B,OAAO;AACT;AAEA,MAAM,SAASC,aAAAA,WAAW,OAAO;CAC/B,QAAQ;EACN,YAAY;EACZ,gBAAgB;CAClB;CACA,QAAQ,EACN,iBAAiB,wBACnB;CACA,MAAM;EACJ,OAAO;EACP,QAAQ;EACR,cAAc;EACd,iBAAiB;EACjB,eAAe;CACjB;AACF,CAAC"}
|
package/dist/index.mjs
CHANGED
|
@@ -32,6 +32,7 @@ function useSafeArea() {
|
|
|
32
32
|
* symbol is looked up at runtime instead of written as a computed key.
|
|
33
33
|
*/
|
|
34
34
|
const DISPOSE = Symbol.dispose;
|
|
35
|
+
/** Release an RN-Skia wrapper through its `Symbol.dispose`; a no-op for null or non-disposable values. */
|
|
35
36
|
function releaseSkiaObject(target) {
|
|
36
37
|
if (DISPOSE === void 0 || target === null || target === void 0) return;
|
|
37
38
|
const disposer = target[DISPOSE];
|
|
@@ -101,18 +102,27 @@ function createSceneSurfaceCache(Skia) {
|
|
|
101
102
|
* The snapshot is released as soon as it has been copied. Frame images are
|
|
102
103
|
* released once the ring exceeds depth 3, ensuring the canvas's rAF always has
|
|
103
104
|
* a live image to paint from.
|
|
105
|
+
*
|
|
106
|
+
* The postfx chain runs **here, in place**, for the same reasons: the `postfx`
|
|
107
|
+
* compositor draws each pass back over this one surface between the picture
|
|
108
|
+
* and the snapshot (Skia's copy-on-write keeps each pass's snapshot valid), so
|
|
109
|
+
* the chain costs no second surface or WebGL context, and the image RN-Skia's
|
|
110
|
+
* `<Image>` draws is already filtered — no shader node (the per-paint leak of
|
|
111
|
+
* §14) is ever mounted on web.
|
|
104
112
|
*/
|
|
105
113
|
function createSceneCapture(Skia, opts) {
|
|
106
114
|
const useNonTexture = opts?.nonTextureImage ?? true;
|
|
107
115
|
const retentionDepth = opts?.retentionDepth ?? 3;
|
|
116
|
+
const postfx = opts?.postfx ?? null;
|
|
108
117
|
const surfaces = createSceneSurfaceCache(Skia);
|
|
109
118
|
const ring = [];
|
|
110
119
|
return {
|
|
111
|
-
capture(picture, width, height) {
|
|
120
|
+
capture(picture, width, height, passes) {
|
|
112
121
|
const surface = surfaces.acquire(width, height);
|
|
113
122
|
if (surface === null) return null;
|
|
114
123
|
surface.getCanvas().drawPicture(picture);
|
|
115
124
|
surface.flush();
|
|
125
|
+
if (postfx !== null && passes !== void 0 && passes.length > 0) postfx.composite(surface, passes, width, height);
|
|
116
126
|
const snapshot = surface.makeImageSnapshot();
|
|
117
127
|
const detachable = snapshot;
|
|
118
128
|
const detached = useNonTexture && detachable.makeNonTextureImage ? detachable.makeNonTextureImage() : snapshot;
|
|
@@ -125,6 +135,7 @@ function createSceneCapture(Skia, opts) {
|
|
|
125
135
|
for (const img of ring) releaseSkiaObject(img);
|
|
126
136
|
ring.length = 0;
|
|
127
137
|
surfaces.dispose();
|
|
138
|
+
postfx?.dispose();
|
|
128
139
|
}
|
|
129
140
|
};
|
|
130
141
|
}
|
|
@@ -188,6 +199,71 @@ function unpackArgb(out, argb) {
|
|
|
188
199
|
out[2] = (argb & 255) / 255;
|
|
189
200
|
out[3] = (argb >>> 24 & 255) / 255;
|
|
190
201
|
}
|
|
202
|
+
// src/web-postfx.ts
|
|
203
|
+
/**
|
|
204
|
+
* Imperative postfx compositor for the web scene capture: the blit
|
|
205
|
+
* `@flare-engine/render-web`'s `createPostFxSurface` runs, retargeted at
|
|
206
|
+
* RN-Skia's web wrappers (whose `makeShaderWithChildren` does work there).
|
|
207
|
+
* Why the chain runs in place over the capture surface instead of as RN-Skia
|
|
208
|
+
* shader nodes: scene-texture.ts and docs/plans/web-target-2026-08.md §14.
|
|
209
|
+
*/
|
|
210
|
+
const TILE_CLAMP = 0;
|
|
211
|
+
const FILTER_LINEAR = 1;
|
|
212
|
+
const MIPMAP_NONE = 0;
|
|
213
|
+
const BLEND_SRC = 1;
|
|
214
|
+
/**
|
|
215
|
+
* Create a compositor over `Skia.Paint()`. The paint, the full-surface rect and
|
|
216
|
+
* the shader-children array are allocated once and reused, so a frame allocates
|
|
217
|
+
* nothing here beyond the Skia objects each pass creates and releases.
|
|
218
|
+
*/
|
|
219
|
+
function createWebPostFxCompositor(Skia) {
|
|
220
|
+
const paint = Skia.Paint();
|
|
221
|
+
paint.setBlendMode(BLEND_SRC);
|
|
222
|
+
const rect = {
|
|
223
|
+
x: 0,
|
|
224
|
+
y: 0,
|
|
225
|
+
width: 0,
|
|
226
|
+
height: 0
|
|
227
|
+
};
|
|
228
|
+
const childrenBuf = [null];
|
|
229
|
+
const wrap = (img) => img.makeShaderOptions(TILE_CLAMP, TILE_CLAMP, FILTER_LINEAR, MIPMAP_NONE);
|
|
230
|
+
return {
|
|
231
|
+
composite(surface, passes, width, height) {
|
|
232
|
+
if (passes.length === 0) return;
|
|
233
|
+
rect.width = width;
|
|
234
|
+
rect.height = height;
|
|
235
|
+
const canvas = surface.getCanvas();
|
|
236
|
+
for (let i = 0; i < passes.length; i++) {
|
|
237
|
+
const pass = passes[i];
|
|
238
|
+
if (pass === void 0) continue;
|
|
239
|
+
const snapshot = surface.makeImageSnapshot();
|
|
240
|
+
const childCount = 1 + pass.children.length;
|
|
241
|
+
childrenBuf.length = childCount;
|
|
242
|
+
childrenBuf[0] = wrap(snapshot);
|
|
243
|
+
for (let c = 0; c < pass.children.length; c++) {
|
|
244
|
+
const child = pass.children[c];
|
|
245
|
+
if (child !== null && child !== void 0) childrenBuf[c + 1] = wrap(child);
|
|
246
|
+
}
|
|
247
|
+
const shader = pass.shader.makeShaderWithChildren(pass.uniforms, childrenBuf);
|
|
248
|
+
if (shader !== null && shader !== void 0) {
|
|
249
|
+
paint.setShader(shader);
|
|
250
|
+
canvas.drawRect(rect, paint);
|
|
251
|
+
paint.setShader(null);
|
|
252
|
+
}
|
|
253
|
+
surface.flush();
|
|
254
|
+
releaseSkiaObject(shader);
|
|
255
|
+
for (let c = 0; c < childCount; c++) {
|
|
256
|
+
releaseSkiaObject(childrenBuf[c]);
|
|
257
|
+
childrenBuf[c] = null;
|
|
258
|
+
}
|
|
259
|
+
releaseSkiaObject(snapshot);
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
dispose() {
|
|
263
|
+
releaseSkiaObject(paint);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
}
|
|
191
267
|
// src/game-view.tsx
|
|
192
268
|
/**
|
|
193
269
|
* Capture the frame's picture into an offscreen surface **on the UI thread**.
|
|
@@ -265,7 +341,6 @@ function GameView({ config, onReady, style, children, safeArea }) {
|
|
|
265
341
|
batch: new SpriteBatch()
|
|
266
342
|
};
|
|
267
343
|
}, []);
|
|
268
|
-
const webPostFxWarnedRef = useRef(false);
|
|
269
344
|
useEffect(() => {
|
|
270
345
|
const bridge = createSkiaFrameRenderer(Skia);
|
|
271
346
|
ctx.renderer.setCanvas(bridge.canvas);
|
|
@@ -295,9 +370,11 @@ function GameView({ config, onReady, style, children, safeArea }) {
|
|
|
295
370
|
if (isWeb) {
|
|
296
371
|
if (captureRef.current === null) captureRef.current = createSceneCapture(Skia, {
|
|
297
372
|
nonTextureImage: true,
|
|
298
|
-
retentionDepth: 3
|
|
373
|
+
retentionDepth: 3,
|
|
374
|
+
postfx: createWebPostFxCompositor(Skia)
|
|
299
375
|
});
|
|
300
|
-
const
|
|
376
|
+
const fx = bridge.hasPostFxBinding() ? bridge.compilePostFxPasses(null, null, w * pd, h * pd) : EMPTY_COMPILED;
|
|
377
|
+
const img = captureRef.current.capture(pic, w * pd, h * pd, fx);
|
|
301
378
|
if (img !== null) sceneImage.value = img;
|
|
302
379
|
} else scheduleOnUI(captureSceneOnUI, sceneImage, uiSurface, uiSurfaceKey, pic, w * pd, h * pd);
|
|
303
380
|
}
|
|
@@ -307,9 +384,6 @@ function GameView({ config, onReady, style, children, safeArea }) {
|
|
|
307
384
|
prevBuilt = built.length === 0 ? EMPTY_PASSES : built;
|
|
308
385
|
setPasses(prevBuilt);
|
|
309
386
|
}
|
|
310
|
-
} else if (bridge.hasPostFxBinding() && !webPostFxWarnedRef.current) {
|
|
311
|
-
console.warn("postfx chain skipped: Skia.RuntimeShaderBuilder and ImageFilter.MakeRuntimeShaderWithChildren both throw \"Not implemented on React Native Web\".");
|
|
312
|
-
webPostFxWarnedRef.current = true;
|
|
313
387
|
}
|
|
314
388
|
canvasRef.current?.redraw();
|
|
315
389
|
});
|
|
@@ -464,6 +538,8 @@ function returnTrue$1() {
|
|
|
464
538
|
/** Stable empty-chain reference — an empty `buildPostFxPasses` result collapses
|
|
465
539
|
* to this so the `passes` state never changes for a postfx-free GameView. */
|
|
466
540
|
const EMPTY_PASSES = [];
|
|
541
|
+
/** Stable empty compiled-pass list handed to the web capture when no chain is bound. */
|
|
542
|
+
const EMPTY_COMPILED = Object.freeze([]);
|
|
467
543
|
/** Linear, mipmap-free sampling for every ImageShader in the pass chain — the
|
|
468
544
|
* options render-web hands makeShaderOptions, so both backends sample alike. */
|
|
469
545
|
const LINEAR_SAMPLING = {
|