diff --git a/docs/EFFEKSEER-IN-SCENE.md b/docs/EFFEKSEER-IN-SCENE.md index ec60f8c4..766b453a 100644 --- a/docs/EFFEKSEER-IN-SCENE.md +++ b/docs/EFFEKSEER-IN-SCENE.md @@ -1,140 +1,65 @@ # Effekseer effects in the scene -From runtime revision **20261027.3**, a screen animation (an Effekseer animation -shown on a battler, a character or the screen) is drawn inside PIXI's scene on -PIXI 8's WebGL2 renderer, at its place in the scene graph. Until then every one -was drawn on a separate transparent canvas layered over the game canvas (the -Effekseer overlay). That overlay remains, as the fallback and for the effects a -3D map anchors in its world. - -## What a game sees - -- **Windows sit above effects.** An effect is drawn where its animation sits in - the spriteset: under the message, status, command and time windows, as in - RPG Maker MZ. On the overlay it was drawn over every window. -- **Screen tint, flashes and the spriteset's filters apply to effects.** In - battle the effects container sits inside three colour filters (its own - container, the spriteset and the scene); a tint now colours the effect with - the battle. On the overlay an effect kept its own colours under any tint. -- **Distortion reads the scene beneath the effect.** A layer that samples the - background (refraction, heat haze, darkening; most stock MZ effects have one, - Fire All 1 among them) captures exactly what PIXI has drawn under the effect so - far. The overlay copied the whole composited scene into its own canvas every - frame an effect played to give it the same thing. -- **Everything else is the same.** In a battle test without a tint, frames drawn - in the scene match the overlay's outside the windows. The one difference is - antialiasing on the edges of mesh layers (ribbons, rings): the overlay's - canvas is multisampled and PIXI's is not, so those edges are not smoothed. - Measured: at most 0.1 % of the screen's pixels differ by more than 8 levels. +RPG Reactor draws screen animations (Effekseer animations shown on a battler, a character or the screen) inside PIXI's scene, at their place among the game's sprites, as RPG Maker MZ layers them. This page covers what that changes for a game, when it applies, how to turn it off, and what plugins need to know. + +Effects that cannot be drawn in the scene play on the **Effekseer overlay**: a separate transparent canvas laid over the game canvas. + +## What changes in a game + +- **Windows are drawn over effects.** An effect sits under the message, status, command and time windows, as in RPG Maker MZ. On the overlay, effects are drawn over every window. +- **Screen tint, flashes and the spriteset's filters colour effects.** In battle, a tint colours the effect along with the battle. On the overlay, an effect keeps its own colours under any tint. +- **Distortion reads the scene under the effect.** Layers that sample the background (refraction, heat haze, darkening, as in Fire All 1 and most stock MZ effects) see exactly what has been drawn beneath the effect. Where a layer bends samples past the edge of the screen, they repeat the screen's edge pixels. +- **Mesh edges are not antialiased.** The edges of mesh layers such as ribbons and rings look slightly harder than on the overlay, whose canvas is multisampled. Everything else looks the same. ## When it applies -All of the following: +An animation is drawn in the scene when all of these are true: -- PIXI renders with WebGL2 (its default; not WebGPU, not WebGL1); +- PIXI renders with WebGL2 (its default; not WebGPU or WebGL1); - `Graphics.effekseerInScene` is not `false`; -- the context is not lost; -- the animation is a screen animation, not one a 3D map anchors in its world - (those draw in the 3D scene through `Reactor3D.EffekseerScene` and - `Reactor3D.GpuEffects`, as before). +- the WebGL context is not lost; +- the animation is a screen animation. An effect a 3D map anchors in its world is drawn by the 3D scene (`Reactor3D.EffekseerScene` and `Reactor3D.GpuEffects`). + +Any other animation plays on the overlay. -Anything else plays on the overlay exactly as it did. To keep the overlay for a -whole game, set it before the first animation, for example in a plugin: +## Keeping the overlay + +To draw every animation on the overlay, set this before the first animation plays, for example in a plugin: ```js Graphics.effekseerInScene = false; ``` -## How it works - -`Sprite_Animation.SceneLayer` (`runtime/reactor_sprites.js`) owns it. - -- **A context of its own.** The layer runs an Effekseer context on PIXI's WebGL2 - context, as `Reactor3D.GpuEffects` already does, with its own effect cache. - `Sprite_Animation.setup` hands it a screen animation; the animation plays in - that context through `_effectContext`. `EffectManager` keeps loading into the - overlay's context for everything else, and sends a map's preloads to the layer - while the layer is in use (`EffectManager.sceneLayer()`), so the scene still - waits for them behind the loading fade. -- **Drawn during PIXI's render.** Each animation has a `PIXI.RenderContainer` - child. PIXI executes it in scene order while it renders, with the sprite batch - broken before it, so the effect draws into whatever PIXI is drawing to at that - point: the canvas, or a filter's texture. Effekseer drew nothing on PIXI's - context only when it was called from `onRender`, which PIXI 8 runs before its - own draws; the old comment in `reactor_core.js` said otherwise and is corrected. -- **Placed in any target.** PIXI's current projection and offset - (`renderer.globalUniforms`) and viewport give where a global point lands in - the target's pixels. A filter's texture is stored upside down; the effect's - projection is flipped to match, with its winding. -- **Depth.** Effekseer's depth-tested layers get a depth buffer cleared once per - target per frame, as the overlay's was. The canvas has one; a filter's texture - is lent one for the draw and given it back. -- **PIXI's state.** The layer never reads GL state back (a query waits for the - GPU; it cost 1.4 ms a draw on a busy map). It reads what PIXI has bound from - PIXI's own records, puts the framebuffer, viewport, scissor and stencil back, - and resets only the caches a draw changes (state, textures, program, vertex - arrays, buffers, colour mask). PIXI's full `resetState()` would also forget - the render target it is drawing to. -- **Slow motion.** The layer's context steps with the overlay context's update, - so a battle's slowed time (`reactor_fight_camera.js`) reaches it too. - ## HDR effects -An HDR animation in the scene draws its light through its own -`ReactorHdrRenderer` on PIXI's context (RGBA16F targets, the light buffer -multisampled 4x where the format allows), at the game's own size as the overlay -does. Its bloom and grade are applied, and the result is screened into the -target where the animation sits. HDR animations of one grade in one container -share one light pass at the first one's place. When the context cannot draw HDR -(no float targets, a grade that does not compile, a pass that fails), the -sidecar's twin plays in the scene instead. See [HDR-EFFECT-OVERLAY.md](HDR-EFFECT-OVERLAY.md). - -## Context loss - -When PIXI's context is lost, the layer's animations end (a battle does not wait -on a stranded handle) and its context and effects are released. New animations -play on the overlay until the context is restored, and in the scene again after. -This is verified in a battle test by losing and restoring the context with -`WEBGL_lose_context`. - -## For plugins - -- An in-scene animation never reaches `Sprite_Animation.renderActive`, - `_doEffekseerDraw` or the overlay canvas. A plugin that reads the overlay - canvas's pixels, or draws on `Graphics._effekseerGL` expecting to be over - every effect, sees only overlay animations. -- `Sprite_Animation.prototype.setProjectionMatrix`, `setCameraMatrix` and - `setViewport` set up the overlay's draw; the layer does not call them. - Wrapping them changes overlay animations only. +An HDR animation in the scene draws its light through its own `ReactorHdrRenderer` on PIXI's context, at the game's resolution, with the sidecar's bloom and grade. The result is screened into the scene where the animation sits. HDR animations that share a grade in the same container share one light pass, at the place of the first one. + +A sidecar's [companion](HDR-EFFECT-OVERLAY.md#adding-a-companion-effect) plays in the layer's context with the HDR effect, from the same random seed. The companions of a light pass draw into the scene before it, and, unless `companionOccludes` is `false`, write their depth into the light buffer so their opaque parts hide the HDR light behind them. + +When the context cannot draw HDR (no floating-point render targets, a grade that does not compile, or a pass that fails), or the companion fails to load, the sidecar's normally graded twin plays in the scene instead, without the companion. See [HDR effects](HDR-EFFECT-OVERLAY.md). + +## Lost WebGL context + +When PIXI's context is lost, the animations drawn in the scene end, so a battle does not wait on them, and their resources are released. New animations play on the overlay until the context is restored, and in the scene again after that. + +## For plugin developers + +- An animation drawn in the scene never reaches `Sprite_Animation.renderActive`, `_doEffekseerDraw` or the overlay canvas. A plugin that reads the overlay canvas's pixels, or draws on `Graphics._effekseerGL` expecting to be over every effect, sees only overlay animations. +- `Sprite_Animation.prototype.setProjectionMatrix`, `setCameraMatrix` and `setViewport` set up the overlay's draw. The scene path does not call them, so wrapping them changes overlay animations only. - An animation's `_effekseerInScene` says which path draws it. -## Performance - -Measured on this machine at 1920x1080 (one effect looping, seeded so both paths -draw the same frames): - -| Battle test, per rendered frame with `gl.finish()` | Overlay | In the scene | -|---|---|---| -| Nothing playing | 1.31 ms | | -| Fire All 1 | 1.65 ms | 1.46 ms | -| Wind All 2 | 1.97 ms | 1.89 ms | -| Neutral All 2 | 1.64 ms | 1.51 ms | -| One True Magic (HDR) | 1.91 ms | 1.67 ms | - -On a 2D map (the Demo's Deck Drill), `ReactorProfiler`'s CPU average per tick -was 1.11 to 1.17 ms on the overlay and 1.09 to 1.15 ms in the scene, 1.04 ms -with nothing playing. Not measured: what the browser spends blending the -overlay canvas over the game, which the scene path does not use. - -## Verification - -`editor/tests/effekseer-in-scene.test.cjs` holds the mapping, which animations -the layer takes, the GL calls of a draw and what is put back, HDR groups, -context loss, loading and preloads, slow motion, and the setup routing. -`hdr-overlay.test.cjs` holds the HDR choices for an in-scene animation and the -composite's framebuffer. On screen, in the real runtime: frames compared with -the overlay's (battle, untinted and tinted), the windows' layering in battle -and on a map, a message window over both, and context loss and restore. Not -verified: WebGPU (it keeps the overlay), PIXI multisampled render textures -(a distortion capture cannot read one; PIXI's filters do not use them), and -GPUs other than this machine's. +### How the scene path works + +`Sprite_Animation.SceneLayer` in `runtime/reactor_sprites.js` owns it. + +- **Its own Effekseer context.** The layer runs an Effekseer context on PIXI's WebGL2 context, with its own effect cache. `Sprite_Animation.setup` hands it each screen animation, which plays through `_effectContext`. `EffectManager` keeps loading into the overlay's context for everything else. While the layer is in use, a map's preloads go to the layer (`EffectManager.sceneLayer()`), so the scene still waits for them behind the loading fade. +- **Drawn during PIXI's render.** Each animation has a `PIXI.RenderContainer` child. PIXI runs it in scene order, with the sprite batch broken before it, so the effect draws into whatever PIXI is drawing to at that point: the canvas or a filter's texture. +- **Placement in any target.** The effect is placed using PIXI's current projection, offset (`renderer.globalUniforms`) and viewport. A filter's texture is stored upside down, so the effect's projection and winding are flipped to match. +- **Depth.** Effekseer's depth-tested layers get a depth buffer, cleared once per target per frame. A filter's texture is lent one for the draw. +- **PIXI's state.** The layer never reads GL state back from the GPU. It reads what PIXI has bound from PIXI's own records, restores the framebuffer, viewport, scissor and stencil, and resets only the caches a draw changes (state, textures, program, vertex arrays, buffers and colour mask). It does not call PIXI's `resetState()`, which would also forget the render target. +- **Slow motion.** The layer's context steps with the overlay context's update, so a battle's slowed time (`reactor_fight_camera.js`) reaches it too. + +## Limits + +- WebGPU keeps the overlay. +- A distortion layer cannot read a PIXI multisampled render texture. PIXI's own filters do not use them. diff --git a/docs/HDR-EFFECT-OVERLAY.md b/docs/HDR-EFFECT-OVERLAY.md index 7d8df870..a6981702 100644 --- a/docs/HDR-EFFECT-OVERLAY.md +++ b/docs/HDR-EFFECT-OVERLAY.md @@ -1,70 +1,44 @@ -# HDR effect overlay - -RPG Reactor 0.99.2 (runtime revision **20261025.1**) includes HDR effect rendering. -There is no plugin to install or enable. An effect opts in through a sidecar next -to its `.efkefc`; ordinary effects retain their existing draw path. - -HDR materials emit exposed linear light. The overlay adds the animations sharing -a display grade into one floating-point target, adds reduced-resolution bloom, -and applies that grade once to the sum. Output is display SDR; this does not -enable HDR monitors, change the game's lighting, or grade the entire scene. - -On PIXI 8's WebGL2 renderer, HDR animations draw inside PIXI's scene with the -other screen animations (runtime 20261027.3, [EFFEKSEER-IN-SCENE.md](EFFEKSEER-IN-SCENE.md)): -the same light buffer, bloom and grade, screened into the scene where the -animation sits. The overlay this guide describes is the fallback, and what a -`Graphics.effekseerInScene = false` game uses. - -## Updating Reactor and existing projects - -The canonical module is `runtime/reactor_hdr_overlay.js`. `reactor_main.js` loads -it automatically. New projects inherit it through the normal runtime copy. -The editor's existing runtime refresh installs it in older Reactor projects when -their runtime revision changes. Game and editor distribution preflights require -the module, and the bundled Demo carries the same runtime. - -The file defines two globals. `ReactorHdrRenderer` is the light pipeline itself -(float targets, bloom, one grade, the composite), one instance per WebGL -context (the overlay's WebGL1, or PIXI's WebGL2 for the in-scene path) and free -of game state. `ReactorHdrOverlay` is the game's adapter: -sidecar requests, animation selection, the fallback twin and the overlay -canvas. The editor loads the same file for its previews and keeps only the -renderer (see Editor previews). - -Use the complete runtime from the same Reactor build. Mixing a new module with -old core/manager/sprite files does not install the native hooks. To update a -project by hand, back up its `js/` and copy the `reactor_*.js` files from -`runtime/` into it, except `reactor_plugins.js`, which belongs to the project. - -A project that still enables the overlay's earlier standalone plugin, under the -name `ReactorHdrOverlay`, keeps working: plugin setup passes that entry's -parameters to the built-in overlay and skips its script, so the two never both -render. The entry and its file can be removed after upgrading. A renamed copy of -that plugin is not recognized and must be disabled by hand. Other plugins load -as usual. - -## Installing an HDR effect - -Install all three files together, along with their referenced resources: +# HDR effects -```text -effects/MyEffect/MyEffect-hdr.efkefc -effects/MyEffect/MyEffect-hdr.hdr.json -effects/MyEffect/MyEffect-ldr.efkefc -effects/MyEffect/Materials/... -effects/MyEffect/Texture/... -effects/MyEffect/Model/... -``` +RPG Reactor can draw Effekseer effects in high dynamic range: an HDR effect's materials give off light brighter than white, the light of every effect sharing a grade is added together with bloom, and the grade turns the sum into display colour once. There is no plugin to install. An effect opts in with a sidecar file next to its `.efkefc`; every other effect draws as before. + +The output is ordinary display colour. HDR effects do not drive HDR monitors, change the game's lighting or grade the rest of the scene. + +On PIXI's WebGL2 renderer, HDR animations are drawn inside the scene with the other screen animations ([Effekseer effects in the scene](EFFEKSEER-IN-SCENE.md)). They use the same light buffer, bloom and grade, and are screened into the scene where the animation sits. The overlay this page describes is the fallback, and what a game with `Graphics.effekseerInScene = false` uses. + +## Adding an HDR effect + +1. Put the HDR effect, its sidecar and its normally graded twin in one folder under `effects/`, with the resources they use. An effect with a [companion](#adding-a-companion-effect) has a fourth file, here `MyEffect-body.efkefc`: + + ```text + effects/MyEffect/MyEffect-hdr.efkefc + effects/MyEffect/MyEffect-hdr.hdr.json + effects/MyEffect/MyEffect-ldr.efkefc + effects/MyEffect/MyEffect-body.efkefc + effects/MyEffect/Materials/... + effects/MyEffect/Texture/... + effects/MyEffect/Model/... + ``` + + Install them in this order: the twin first, then the companion if there is one, and the HDR effect with its sidecar last. The files a sidecar names are then in place before the sidecar is. + +2. Write the sidecar (see [The sidecar file](#the-sidecar-file)), with `fallback` naming the twin. +3. Set the animation's effect name to `MyEffect/MyEffect-hdr`, without the extension. -Set the animation's effect name to `MyEffect/MyEffect-hdr`, without an extension. -Keep the normally graded twin installed. Unsupported float rendering or a grade -compile failure selects that twin. Playback waits for the metadata request before -starting; requests are cached once per effect, including missing sidecars, and -abort after 15 seconds. Invalid/unreadable metadata fails closed because a safe -twin cannot be established. A conventional `-hdr` filename without metadata also -fails closed. Reload the game after changing a cached sidecar. +The twin plays wherever HDR cannot: a computer without floating-point render targets, or a grade that does not compile. Keep it installed. -## Sidecar contract +Playback waits for the sidecar to load before it starts. Each effect's sidecar is requested once and cached, including a missing one, and a request gives up after 15 seconds. Reload the game after changing a sidecar. + +An effect that cannot be played safely does not play: + +- a sidecar that is missing, unreadable or invalid, since no safe twin can be found; +- an effect named with `-hdr` but without a sidecar. + +## Making HDR assets + +An HDR asset's materials output exposed linear light, not display-graded colour. It must not contain baked bloom stand-ins or refraction and distortion nodes (see [Limits](#limits)); put those, and opaque bodies, in a [companion](#adding-a-companion-effect). RPG Reactor does not make HDR assets; they come from the tool that exported the effect. Build the normally graded twin separately. + +## The sidecar file ```json { @@ -81,145 +55,157 @@ fails closed. Reload the game after changing a cached sidecar. } ``` -The grade is trusted effect code in GLSL ES 1.00. It reads a local `vec3 hdr` -containing exposed light plus bloom, and declares a local `vec3 tmOut` containing -display RGB. Do not apply exposure again. One program is compiled per distinct -grade string. The example is a simple test grade. - -Fallback names without `/` resolve beside the HDR effect; names containing `/` -resolve from the `effects/` root. Do not include `.efkefc`. The fallback must be -an independently usable, normally graded effect, not another HDR asset. - -Sizes and tints contain six finite values: sizes must be positive, tints and -intensity nonnegative, radiusScale positive. `tints` are scalar bloom weights. -The six sizes follow UE 4.27's width-relative bloom radii; Gaussian sigma is -`viewWidth * size * 0.04 * 0.5 / sqrt(33.4) * radiusScale`. - -`bloom.threshold` (optional, runtime 20261027.1) is UE 4's bloom setup threshold. -When it is a number, the light is multiplied by -`clamp((dot(rgb, (0.3, 0.59, 0.11)) - threshold) * 0.5, 0, 1)` before any blur, as -`PostProcessBloomSetup` does. UE runs that setup at half its screen resolution; an -effect drawn `radiusScale` times larger than in the source game covers that pixel -with `radiusScale` overlay pixels, so the setup runs at pyramid level -`round(log2(radiusScale))` (level 0 is an extra full-resolution pass), and every -Gaussian reads that level or a coarser one: light whose exposed luminance is at or below the -threshold does not bloom, and bloom reaches full strength 2 units above it. A -negative threshold blooms dark light partly (-0.8 passes 40 % at zero). Without it -every pixel blooms, as before. Like the other bloom settings, it is taken from the -first sidecar of a grade group. - -## Authoring and tuning - -An HDR asset's materials output exposed linear light, not display-graded colour, -and it carries no baked bloom stand-ins or refraction/distortion nodes (see -Rendering limits). Reactor does not author HDR assets; they come from whatever -tool exported the effect. Build and install the normally graded variant -separately as the declared twin. - -The defaults above are the sidecar defaults. A game's startup script can override -tuning for all HDR effects: +The values above are the defaults. The grade in the example is a simple test grade. + +| Field | What it holds | +| --- | --- | +| `version` | `1` | +| `gradeInput` | `"hdr"` | +| `grade` | GLSL ES 1.00 code. It reads a local `vec3 hdr` (exposed light plus bloom) and declares a local `vec3 tmOut` (display RGB). Do not apply exposure again. The grade is trusted effect code; one shader is compiled per distinct grade string. | +| `bloom.intensity` | Bloom strength, zero or more. Zero turns bloom off. Required even when `bloom.intensityKeys` is given. | +| `bloom.intensityKeys` | Optional. Bloom strength keyed over the effect. See [Animating bloom and grade](#animating-bloom-and-grade). | +| `bloom.sizes` | Six positive bloom radii, as fractions of the view's width (Unreal Engine 4.27's bloom sizes). | +| `bloom.tints` | Six weights, zero or more, one per size. | +| `bloom.radiusScale` | A positive multiplier on every radius. | +| `bloom.threshold` | Optional. See [Bloom threshold](#bloom-threshold). | +| `bloom.prefilter` | Optional. Unity's bloom prefilter, in place of the threshold. See [Bloom prefilter](#bloom-prefilter). | +| `gradeB` | Optional, with `gradeKeys`. A second grade, written like `grade`. See [Animating bloom and grade](#animating-bloom-and-grade). | +| `gradeKeys` | Optional, with `gradeB`. How much of `gradeB` plays over the effect. | +| `fallback` | The normally graded twin, without `.efkefc`. A name without `/` is found beside the HDR effect; a name with `/` is found from the `effects/` root. It must be a complete, normally graded effect, not another HDR asset. | +| `companion` | Optional. A normally graded effect played with the HDR effect, named like `fallback`. See [Adding a companion effect](#adding-a-companion-effect). | +| `companionOccludes` | Optional, `true` or `false`; `true` when left out. Whether the companion's opaque parts hide the HDR light behind them. | + +A sidecar with a field outside these rules is invalid, and its effect does not play. + +The Gaussian sigma of each bloom radius is `viewWidth * size * 0.04 * 0.5 / sqrt(33.4) * radiusScale`. + +Bloom settings are taken from the first sidecar in each grade group. Give effects that share a grade the same bloom settings. Animations of one grade whose bloom intensity or grade weight differ at a frame are drawn in separate passes. + +### Bloom threshold + +`bloom.threshold` works like Unreal Engine 4's bloom setup threshold. When it is a number, the light is multiplied by + +```text +clamp((dot(rgb, (0.3, 0.59, 0.11)) - threshold) * 0.5, 0, 1) +``` + +before any blur. Light whose exposed luminance is at or below the threshold does not bloom, and bloom reaches full strength 2 units above it. A negative threshold lets dark light bloom partly: -0.8 passes 40% at zero. Without a threshold, every pixel blooms. + +Unreal runs this step at half its screen resolution. An effect drawn `radiusScale` times larger than in the source game covers that pixel with `radiusScale` pixels, so the step runs at bloom pyramid level `round(log2(radiusScale))` (level 0 is an extra full-resolution pass), and every blur reads that level or a coarser one. + +### Bloom prefilter + +`bloom.prefilter` is Unity post-processing's bloom prefilter, for effects tuned in Unity: + +```json +"prefilter": { "threshold": 1.1, "knee": 0.5, "clamp": 65472 } +``` + +`threshold` is a number and `knee` is zero or more. `clamp` is optional and positive; Unity's default, 65472, is used without it. The light is clamped to `clamp` in each channel, then multiplied by `max(b - threshold, s) / max(b, 0.0001)`, where `b` is its brightest channel and `s = clamp(b - threshold + knee, 0, 2 * knee)^2 / (4 * knee + 0.0001)`. Every pixel at or above the clamp blooms alike. + +The prefilter runs at the same pyramid level as `bloom.threshold`, and replaces it when a sidecar has both. In a GPU capture of a Unity game, the values are in the prefilter pass's constants: `threshold - knee`, `2 * knee` and `1 / (4 * knee)` in one row, the threshold and the clamp in others. + +### Animating bloom and grade + +`bloom.intensityKeys` changes the bloom strength over the effect: + +```json +"intensityKeys": [[0, 0.5], [60, 2.0], [120, 0.2]] +``` + +Each key is `[frame, intensity]`. There is at least one key, frames increase, and intensities are zero or more. Frames count the effect's own clock: 60 a second at speed 100, `speed / 100` per update at other speeds, and slower in a battle's slow motion. The strength runs in a straight line between keys, and holds the first key's value before it and the last key's after it. `REACTOR_HDR.bloom` overrides the keys, as it overrides `bloom.intensity`. + +`gradeB` and `gradeKeys` blend a second grade in over the effect. `gradeB` is a grade string like `grade`. `gradeKeys` is `[[frame, weight], ...]` with weights from 0 to 1: 0 plays `grade`, 1 plays `gradeB`, and values between mix the two outputs. The keys follow the same clock, straight lines and held ends as `bloom.intensityKeys`. Give both fields or neither. Each grade runs in its own function, so both may declare the same local names. + +## Adding a companion effect + +A companion is one normally graded effect that plays with the HDR effect. It holds what an HDR asset cannot: opaque bodies, and refraction and distortion layers. + +```json +"fallback": "MyEffect-ldr", +"companion": "MyEffect-body", +"companionOccludes": true +``` + +1. Export the companion from the same source as the HDR effect. Keep the node order, spawn and life settings, and every renderer parameter that draws random numbers the same in both. The two share one random seed per cast, so the same particles appear in both only when these match. +2. Leave out of the companion what the HDR effect draws. Nodes kept only so the spawning matches must not draw, and must not write depth. +3. Name the companion in the sidecar's `companion`, without `.efkefc`. It is found the way `fallback` is. + +The companion's name must not be empty, end in `.efkefc`, or name the HDR effect or its twin; such a sidecar is invalid. A companion that has a sidecar of its own is not played, and the twin plays instead. + +The two effects start together, with the same transforms and speed. Playback waits for both to load and ends when both have ended. When the companion is missing or fails to load within 15 seconds, the twin plays instead, with a warning in the console. When the twin plays, no companion is loaded. + +### Companion draw order + +The companion draws before the HDR light, on the overlay and in the scene alike. With `companionOccludes` on (the default), it also writes its depth into the HDR light buffer, with colour writes off, so its opaque parts hide the HDR light behind them. Opaque companion nodes must write depth for this; transparent ones must not. Effekseer's depth test is `LEQUAL`, so emissive HDR surfaces that lie exactly on a companion's surface still draw. Set `companionOccludes` to `false` to let all of the HDR light through. + +## Tuning for a whole game + +A game's startup script can override the tuning of every HDR effect: ```js ReactorHdrOverlay.configure({ bufferType: "auto", debug: false }); window.REACTOR_HDR = { bloom: 0.675, bloomScale: 2.4 }; ``` -`bufferType` is `auto`, `half`, or `float`: auto tries half first, then float. -It requires renderable, linearly filtered targets in the overlay's WebGL1 context, -or in the scene in PIXI's WebGL2 context (RGBA16F with `EXT_color_buffer_float`, -the light buffer multisampled 4x where the format allows). -Legacy plugin parameters `bloomIntensity`, `bloomRadiusScale`, `bufferType`, and -`debug` are accepted by `configure`; global `REACTOR_HDR` overrides their tuning. -Without overrides, each grade group's first sidecar supplies bloom settings. -Use consistent bloom settings for effects sharing a grade. - -For diagnostics, `REACTOR_HDR.debugScale` shows buffer light divided by a positive -value. `probeScale` records a quantized lower bound in -`ReactorHdrOverlay.stats.probe`; `probeFrame` limits sampling to that effect frame. -`measureGpu: true` uses synchronous `gl.finish()` around postprocessing and records -`postSamples`; it changes timing and is for measurement only. Statistics include -draw/group counts, target allocations, size, type and accumulated post time. -Testing markers `[HDR]` and `REACTOR_HDR_IDS` still require a valid sidecar or a -complete `ReactorHdrOverlay.overrides[effectName]` entry, including fallback. - -## Rendering limits - -- In the scene, each animation draws at its own place in the scene graph; HDR - animations of one grade in one container share a light pass at the first - one's place. When PIXI's context is lost, in-scene animations end and new - ones play on the overlay until it is restored. -- On the overlay, all ordinary animations draw in their original order, then HDR groups composite - in first-appearance order. Animations sharing a grade add before grading even - when ordinary animations occur between them. Interleaved scene/HDR occlusion - and light accumulation between different grades are not supported. -- The default is screen compositing over the scene and ordinary effects. As - measured on Effekseer's WebGL runtime, additive alpha uses `(SRC_ALPHA, ONE, ONE, ONE)`; - ordinary blend uses `(SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE)`. Both add alpha, - so alpha is not reliable coverage. Translucent HDR layers cannot darken the - scene. Experimental `REACTOR_HDR.coverage = true` uses the accumulated alpha; - it is unsuitable for mixed additive/translucent effects without corrected - coverage data. -- The target covers the overlay, with seven downsample and twelve blur passes - plus one composite per grade group. Bloom intensity zero skips all 19 bloom - passes. Allocations are lazy and reused; resize recreates them. Context loss - invalidates them, restoration creates them on the next HDR animation. The - native module ends active HDR effects at context loss; it does not preserve - their clock. New animations wait until the context is restored. -- This supports the WebGL1 effect overlay and the in-scene path on PIXI 8's - WebGL2 context. Effects the 3D scene draws on its own context (`Reactor3D.GpuEffects`) do - not use it. Refraction/distortion nodes must - be excluded from HDR assets. A future authoring approach can start a separate - ordinary refraction twin alongside the HDR effect; Effekseer cannot filter - individual nodes during a draw. That synchronized twin is not implemented here. - -## Editor previews - -The editor's animation previews draw an HDR effect through the same renderer -the game uses: Database › Animations and its effect file picker, the -Skills/Items animation picker, Show Animation's picker, and the effect layers -of Action Sequences, the 3D database and the map's 3D view. Each preview's -WebGL context gets a renderer of its own; the sidecar's bloom and grade apply -as they do in battle. Database › Animations says under the preview which of -the following happened. - -- **In HDR.** The two pickers and Database › Animations clear their canvas to - the backdrop (or copy it in) before drawing, so the graded light is screened - over it as the game screens it over the scene. The effect layers draw on a - transparent, premultiplied canvas the page lays over the 3D view; there the - composite writes alpha from the graded colour, so the page's own blend comes - close to the game's screen. A cropped view keeps a light buffer the size of - the full view, so bloom is not cut at the box's edge. An overlay layer's - buffer is its own square: light a grade spreads past it (a wide wash that - covers the whole screen in battle) stops at the square's edge. Bloom radii are - fractions of the game screen's width as each preview draws it (System's - screen size against the preview's scale), so a glow is the same size against - an effect as in battle. The same scale places `bloom.threshold`'s setup - level: a preview drawing a game pixel as `k` of its own runs the setup at - `round(log2(radiusScale * k))`, the game's own level when `k` is 1. -- **As its twin.** When the context has no float targets, the grade does not - compile, or the runtime file cannot be loaded, the preview plays the - sidecar's normally graded twin, as the game does. So does an effect drawn - by the 3D scene itself (a GPU effect on a model), which no HDR path covers - in the game either. The reason goes to the console. -- **Not at all.** What the game refuses to play - a `-hdr` effect with no - sidecar, or a sidecar that cannot be read or is invalid - the preview refuses. - -Database › Animations has an **HDR** checkbox beside Repeat for an effect it can -draw in HDR. Clearing it plays the twin instead, as a computer without float -targets would see the effect; a playing preview reloads and carries on. The -choice is remembered for the next HDR effect. - -The preview shows the sidecar's own settings; `REACTOR_HDR` overrides and the -legacy plugin parameters are the game's, and do not apply in the editor. The -sidecar is read again each time an effect loads. - -## Verification - -Run `node --test editor/tests/hdr-overlay.test.cjs` for metadata, safe fallback, -in-scene selection and the composite's framebuffer, -shared grading, resize/restoration, ordinary draw order, and plugin migration; -`hdr-preview-render.test.cjs` and `hdr-preview-twin.test.cjs` for the editor -previews' choices, loading, draw order and cleanup; -`effekseer-in-scene.test.cjs` for the in-scene light pass and its grouping. Manifest and template tests -cover loading and distribution. Unit tests do not establish GPU rendering or -appearance; check those on screen. +- `bufferType` is `"auto"`, `"half"` or `"float"`. Auto tries half-float first, then float. The targets must be renderable and linearly filtered: in the overlay's WebGL1 context, or in PIXI's WebGL2 context for the scene path (RGBA16F with `EXT_color_buffer_float`, the light buffer multisampled 4× where the format allows). +- `REACTOR_HDR.bloom` and `REACTOR_HDR.bloomScale` override every sidecar's bloom intensity and `radiusScale`. +- `configure` also accepts the older plugin parameters `bloomIntensity`, `bloomRadiusScale`, `bufferType` and `debug`. `REACTOR_HDR` overrides their tuning. + +Without overrides, each grade group's first sidecar supplies the bloom settings. + +### Diagnostics + +| Setting | What it does | +| --- | --- | +| `REACTOR_HDR.debugScale` | Shows the buffer's light divided by this positive value | +| `REACTOR_HDR.probeScale` | Records a quantized lower bound of the light in `ReactorHdrOverlay.stats.probe` | +| `REACTOR_HDR.probeFrame` | Limits the probe to that frame of the effect | +| `REACTOR_HDR.measureGpu` | `true` waits for the GPU (`gl.finish()`) around post-processing and records `postSamples`. It changes timing; use it for measurement only. | + +`ReactorHdrOverlay.stats` also counts draws and groups, target allocations, target size and type, and total post-processing time. + +For testing, an animation whose name contains `[HDR]`, or whose ID is in `window.REACTOR_HDR_IDS`, is treated as HDR. It still needs a valid sidecar or a complete `ReactorHdrOverlay.overrides[effectName]` entry, including a fallback. + +## Previews in the editor + +The editor's animation previews draw HDR effects through the same renderer as the game: + +- **Database › Animations** and its effect file picker; +- the animation picker in Skills and Items, and in **Show Animation**; +- the effect layers of Action Sequences, the 3D database and the map's 3D view. + +Database › Animations says under the preview which of these happened: + +- **In HDR.** The sidecar's bloom and grade apply as they do in battle. Bloom radii are scaled to the game screen's width as the preview draws it, so a glow is the same size against an effect as in battle. Effect layers laid over a 3D view draw on a transparent canvas that the page blends close to the game's screen blend. An overlay layer's light buffer is its own square, so a wash that would cover the whole screen in battle stops at the square's edge. +- **As its twin.** When the context has no floating-point targets, the grade does not compile or the runtime file cannot be loaded, the preview plays the twin, as the game would. So does an effect drawn by the 3D scene itself (a GPU effect on a model), which has no HDR path in the game either, and an effect whose companion is missing or has a sidecar of its own. The reason is written to the console. +- **Not at all.** What the game refuses to play, the preview refuses: a `-hdr` effect with no sidecar, or a sidecar that cannot be read or is invalid. + +An HDR effect with a companion plays both in the preview, with the same seed, transforms, clock and draw order as in the game. When the preview plays the twin, it loads only the twin. + +Database › Animations has an **HDR** checkbox beside **Repeat** for an effect it can draw in HDR. Clear it to play the twin instead, as a computer without float targets would; a playing preview reloads and carries on. The choice is remembered for the next HDR effect. + +Previews use the sidecar's own settings, read again each time an effect loads. `REACTOR_HDR` overrides and the older plugin parameters apply only in the game. + +## Updating projects + +The HDR module is `runtime/reactor_hdr_overlay.js`, and `reactor_main.js` loads it. New projects get it with the rest of the runtime, and the editor installs it in older projects when it refreshes their runtime. Game and editor distribution checks require it. + +The file defines two globals: + +- `ReactorHdrRenderer` is the light pipeline: float targets, bloom, one grade and the composite. There is one per WebGL context (the overlay's WebGL1 context, or PIXI's WebGL2 context for the scene path), and it holds no game state. The editor's previews use it. +- `ReactorHdrOverlay` connects it to the game: sidecar requests, choosing animations, the fallback twin and the overlay canvas. + +Use the complete runtime from one RPG Reactor build: a new module with older core, manager or sprite files does not install its hooks. To update a project by hand, back up its `js/` folder and copy the `reactor_*.js` files from `runtime/` into it, except `reactor_plugins.js`, which belongs to the project. + +A project that still enables the earlier standalone `ReactorHdrOverlay` plugin keeps working: its parameters go to the built-in overlay and its script is skipped, so the two never both draw. You can remove the plugin entry and its file. A renamed copy of that plugin is not recognized; disable it by hand. + +## Limits + +- **Draw order in the scene.** Each animation draws at its own place in the scene. HDR animations of one grade in one container share one light pass, at the first one's place. +- **Draw order on the overlay.** All ordinary animations draw first, in their order, then each HDR grade group, in order of first appearance. Animations sharing a grade are added together before grading, even with ordinary animations between them. Ordinary and HDR animations cannot be interleaved so that one hides the other, and light from different grades is not added together. +- **HDR cannot darken the scene.** The result is screened over the scene and the ordinary effects. Effekseer's additive blend writes `(SRC_ALPHA, ONE, ONE, ONE)` and its normal blend `(SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE)`; both add alpha, so alpha is not reliable coverage, and translucent HDR layers cannot darken what is under them. The experimental `REACTOR_HDR.coverage = true` uses the accumulated alpha instead; it does not suit effects that mix additive and translucent layers. +- **Cost.** Each grade group takes seven downsample passes, twelve blur passes and one composite. Bloom intensity zero skips the 19 bloom passes. Targets are created when first needed, reused, and recreated on resize. +- **Context loss.** Losing the WebGL context ends active HDR effects without keeping their place. New animations wait until the context is restored, and the targets are created again on the next HDR animation. +- **Where HDR is drawn.** HDR covers the WebGL1 overlay and the scene path on PIXI's WebGL2 context. Effects the 3D scene draws on its own (`Reactor3D.GpuEffects`), such as an effect anchored on a 3D model, play their twin. A `-hdr` effect without a valid sidecar is refused there too. +- **No refraction in HDR assets.** Refraction and distortion nodes must be left out of HDR assets: Effekseer cannot filter single nodes during a draw. Put them in a [companion](#adding-a-companion-effect). The companion draws before the HDR light as a whole; the two effects are not interleaved node by node. diff --git a/docs/INVENTORY-CAPACITY.md b/docs/INVENTORY-CAPACITY.md new file mode 100644 index 00000000..ef0e528b --- /dev/null +++ b/docs/INVENTORY-CAPACITY.md @@ -0,0 +1,58 @@ +# Inventory capacity: chests and rewards that wait for room + +A party can hold only so many of an item. `Game_Party.gainItem` cuts a gain off at the cap +(`runtime/reactor_objects_battlers.js`, `container[item.id] = newNumber.clamp(0, this.maxItems(item))`), +so a reward that does not fit is lost. For an ordinary chest, that means the +items are gone and the chest still counts as opened. **Can Receive** is how an event asks +first. + +## The Can Receive condition + +Conditional Branch › **Reactor** › **Can Receive** [Item / Weapon / Armor] [entry] × [amount]. + +- It is true when the party holds few enough that **the whole amount** fits: + `numItems(entry) + amount <= maxItems(entry)`. A stack that would only partly fit fails. +- The cap is the one the game reports when the event runs (`$gameParty.maxItems`), so any plugin that + sets it applies with no setup: VisuStella Items & Equips Core's defaults and its `` + notetag, or Reactor's own 99 (9999 with higher limits on). A cap of 0 refuses everything, and a + plugin with no cap lets everything through. +- Equipped copies do not count against the cap, which matches how `gainItem` itself counts. +- A deleted or missing entry makes the condition false: the branch's Else runs, and nothing is given. +- It is saved as an ordinary Script condition, so the game, RPG Maker MZ and old saves all run it + unchanged. The editor recognises it and reopens it in the dialog; if you edit the script by hand, it + stays your own Script condition from then on. + +## Treasure chests + +Quick Event › **Treasure** has **Check Inventory Space** (on by default) and a **Failure Message**. +With it on, an item, weapon or armor chest is built as: + +``` +◆If:Can Receive Item: #1 Potion × 5 + ◆Set Movement Route:This Event (open the lid) + ◆Change Items:Potion + 5 + ◆Text:You found treasure! + ◆Control Self Switch:A = ON +:Else + ◆Text:You cannot carry all of this item. Make room and try again. +:End +``` + +When the party is full it gets the message and nothing else: the lid does not open, nothing is given, +Self Switch A stays off, and the chest can be opened again once there is room. Gold chests are +unchanged (gold has its own cap). Untick the box to build the chest exactly as before. + +## Existing chests, conversations and plot items + +Nothing already on a map changes. To protect an existing chest, or a reward given in a conversation, +put a Can Receive branch around the commands that open and give it, and put the self switch (or +whatever marks the reward as taken) **inside** the branch. If the switch is set before or outside the +branch, a blocked reward is lost for good. + +Plot items get no special treatment: there is no plot-item category, and Key Items are not exempt. +Decide for each event. Put a story reward inside a Can Receive branch when it must not be lost, and +give the player another chance to collect it. Put it outside the branch when the scene must go on +regardless; then the reward is cut off at the cap, as it always was. + +Shops, battle drops, quest rewards and plain Change Items commands keep their current behaviour, +including the cutoff at the cap. diff --git a/docs/README.md b/docs/README.md index 265f937f..b599d0f3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -29,6 +29,7 @@ Guides for authoring with the engine, the current verified state, and maintainer - [Human face handoff](HUMAN-FACE-HANDOFF.md): the unfinished default human faces, how they are built and what remains. - [Audio formats and loop points](AUDIO-LOOP-POINTS.md): which audio files the game finds, where each format keeps its loop, making a looping Opus track, and what changed for older games and tools. - [Model face points and speech](3D-FACE-AND-SPEECH.md): eye placement, mouth and lip authoring, spoken dialogue, per-prop animation speed. +- [Inventory capacity](INVENTORY-CAPACITY.md): the Can Receive condition, Treasure chests that wait for room, and protecting existing chests and conversation rewards. - [Media surfaces](MEDIA-SURFACES.md): image and video placement on maps, models and the screen; transforms and proportions. - [Custom user interfaces](DESIGN-USER-INTERFACES.md): the User Interfaces database section, its node set, actor bindings, opt-in stock-scene replacement and explicit boundaries. - [2D structures](DESIGN-2D-STRUCTURES.md): a building made once on a phantom 2D map (any mix of tilesets, pictures, media surfaces, passability marked X, O or ★) and placed on 2D maps as an object that follows it. diff --git a/editor/index.html b/editor/index.html index fffdb0d3..f0d9bfd6 100644 --- a/editor/index.html +++ b/editor/index.html @@ -950,6 +950,7 @@

♪ Audio Player

+ diff --git a/editor/src/EventManager.js b/editor/src/EventManager.js index 2ea86133..d95fd5f4 100644 --- a/editor/src/EventManager.js +++ b/editor/src/EventManager.js @@ -1555,15 +1555,23 @@ class EventManager { return { id, name, note: '', pages, x, y }; } - quickEventMoveRoute(characterId, commands) { + quickEventMoveRoute(characterId, commands, indent = 0) { const list = commands.concat({ code: 0 }); const route = { list, repeat: false, skippable: false, wait: true }; return [ - { code: 205, indent: 0, parameters: [characterId, route] }, - ...commands.map(command => ({ code: 505, indent: 0, parameters: [command] })) + { code: 205, indent, parameters: [characterId, route] }, + ...commands.map(command => ({ code: 505, indent, parameters: [command] })) ]; } + // The Can Receive condition text, built by the Conditional Branch editor + // that also reopens it, so a generated chest's branch edits like any other. + quickEventCapacityCondition(rewardKind, rewardId, amount) { + const Editor = typeof ConditionalBranchEditor !== 'undefined' + ? ConditionalBranchEditor : require('./event/commands/ConditionalBranchEditor.js'); + return Editor.createItemCapacityText({ type: rewardKind, id: rewardId, amount }); + } + // The page keeps Direction Fix on so the closed graphic cannot turn toward the player, // which means the route has to release it (Direction Fix OFF, code 36) before its turns // can show the opening frames. Chests made by MZ's own Treasure quick event start with it too. @@ -1614,8 +1622,8 @@ class EventManager { if (kind === 'treasure') { const rewardKind = config.rewardKind || 'item'; - const rewardId = Math.max(1, Number(config.rewardId) || 1); - const amount = Math.max(1, Number(config.amount) || 1); + const rewardId = Math.max(1, Math.floor(Number(config.rewardId)) || 1); + const amount = Math.max(1, Math.floor(Number(config.amount)) || 1); const rewardCodes = { item: 126, weapon: 127, armor: 128 }; const reward = rewardKind === 'gold' ? { code: 125, indent: 0, parameters: [0, 0, amount] } @@ -1624,14 +1632,31 @@ class EventManager { ? [rewardId, 0, 0, amount] : [rewardId, 0, 0, amount, false] }; const routeCommands = this.quickEventOpenRoute(config.se); + // Item, weapon and armor chests check for room first (gold has no cap here). + // A full party gets the failure text and nothing else: no opening, no + // reward, no self switch, so the chest stays closed for another try. + const checkSpace = rewardKind !== 'gold' && config.checkSpace !== false; + const at = checkSpace ? 1 : 0; + const claim = [ + ...this.quickEventMoveRoute(0, routeCommands, at), { ...reward, indent: at }, + { code: 101, indent: at, parameters: ['', 0, 0, 2, ''] }, + { code: 401, indent: at, parameters: [config.message || 'You found treasure!'] }, + { code: 123, indent: at, parameters: ['A', 0] } + ]; + const list = checkSpace ? [ + { code: 111, indent: 0, parameters: [12, + this.quickEventCapacityCondition( + { 127: 'weapon', 128: 'armor' }[reward.code] || 'item', rewardId, amount)] }, + ...claim, { code: 0, indent: 1, parameters: [] }, + { code: 411, indent: 0, parameters: [] }, + { code: 101, indent: 1, parameters: ['', 0, 0, 2, ''] }, + { code: 401, indent: 1, parameters: [config.failMessage || + 'You cannot carry all of this item. Make room and try again.'] }, + { code: 0, indent: 1, parameters: [] }, + { code: 412, indent: 0, parameters: [] }, end + ] : [...claim, end]; const page1 = this.makeDefaultEventPage({ - image: { ...image, pattern: 1, direction: 2 }, directionFix: true, - list: [ - ...this.quickEventMoveRoute(0, routeCommands), reward, - { code: 101, indent: 0, parameters: ['', 0, 0, 2, ''] }, - { code: 401, indent: 0, parameters: [config.message || 'You found treasure!'] }, - { code: 123, indent: 0, parameters: ['A', 0] }, end - ] + image: { ...image, pattern: 1, direction: 2 }, directionFix: true, list }); const page2 = this.makeDefaultEventPage({ conditions: { selfSwitchCh: 'A', selfSwitchValid: true }, @@ -1841,10 +1866,20 @@ class EventManager { const rewardData = select([]); const amount = input('number', 1, 1); const message = input('text', tt('You found treasure!')); + const checkSpace = input('checkbox', ''); + checkSpace.checked = true; + checkSpace.style.justifySelf = 'start'; + const failMessage = input('text', tt('You cannot carry all of this item. Make room and try again.')); + // The fields open on translated text, so the event gets that text even untouched. + config.message = message.value; + config.checkSpace = true; + config.failMessage = failMessage.value; const populateRewards = () => { config.rewardKind = rewardType.value; rewardData.innerHTML = ''; rewardData.disabled = config.rewardKind === 'gold'; + checkSpace.disabled = config.rewardKind === 'gold'; + failMessage.disabled = config.rewardKind === 'gold' || !checkSpace.checked; const getter = { item: 'getItems', weapon: 'getWeapons', armor: 'getArmors' }[config.rewardKind]; for (const entry of getter ? (this.databaseManager[getter]?.() || []) : []) { if (!entry?.id) continue; @@ -1859,10 +1894,17 @@ class EventManager { rewardData.addEventListener('change', () => { config.rewardId = Number(rewardData.value) || 1; }); amount.addEventListener('input', () => { config.amount = Math.max(1, Number(amount.value) || 1); }); message.addEventListener('input', () => { config.message = message.value; }); + checkSpace.addEventListener('change', () => { + config.checkSpace = checkSpace.checked; + failMessage.disabled = !checkSpace.checked; + }); + failMessage.addEventListener('input', () => { config.failMessage = failMessage.value; }); row(tt('Reward Type:'), rewardType); row(tt('Reward:'), rewardData); row(tt('Amount:'), amount); row(tt('Message:'), message); + row(tt('Check Inventory Space:'), checkSpace); + row(tt('Failure Message:'), failMessage); populateRewards(); } diff --git a/editor/src/I18nManager.js b/editor/src/I18nManager.js index 0837bb98..a821d190 100644 --- a/editor/src/I18nManager.js +++ b/editor/src/I18nManager.js @@ -9133,6 +9133,68 @@ const RR_QUICK_EVENT_TEXT = { ko: '캐릭터 그래픽을 선택하세요.', ar: 'اختر صورة شخصية.', it: 'Scegli una grafica personaggio.', pl: 'Wybierz grafikę postaci.', id: 'Pilih grafis karakter.', vi: 'Chọn hình nhân vật.', th: 'เลือกกราฟิกตัวละคร', tr: 'Bir karakter grafiği seçin.' + }, + 'Check Inventory Space:': { + ja: '所持数の空きを確認:', es: 'Comprobar espacio en inventario:', 'zh-Hant': '檢查持有空間:', + 'zh-Hans': '检查持有空间:', ru: 'Проверять место в инвентаре:', pt: 'Verificar espaço no inventário:', + de: 'Inventarplatz prüfen:', fr: 'Vérifier la place dans l’inventaire :', el: 'Έλεγχος χώρου αποθέματος:', + ko: '소지 공간 확인:', ar: 'التحقق من مساحة المخزون:', it: 'Controlla spazio inventario:', + pl: 'Sprawdź miejsce w ekwipunku:', id: 'Periksa ruang inventaris:', vi: 'Kiểm tra chỗ trống túi đồ:', + th: 'ตรวจสอบพื้นที่เก็บของ:', tr: 'Envanter alanını denetle:' + }, + 'Failure Message:': { + ja: '失敗時のメッセージ:', es: 'Mensaje de fallo:', 'zh-Hant': '失敗訊息:', + 'zh-Hans': '失败消息:', ru: 'Сообщение при неудаче:', pt: 'Mensagem de falha:', + de: 'Fehlermeldung:', fr: 'Message d’échec :', el: 'Μήνυμα αποτυχίας:', + ko: '실패 메시지:', ar: 'رسالة الفشل:', it: 'Messaggio di fallimento:', + pl: 'Komunikat niepowodzenia:', id: 'Pesan gagal:', vi: 'Thông báo thất bại:', + th: 'ข้อความเมื่อล้มเหลว:', tr: 'Başarısızlık mesajı:' + }, + 'You cannot carry all of this item. Make room and try again.': { + ja: 'これ以上持ちきれない。空きを作ってからもう一度試そう。', + es: 'No puedes llevar todo esto. Haz sitio e inténtalo de nuevo.', + 'zh-Hant': '無法全部帶走。請騰出空間後再試一次。', 'zh-Hans': '无法全部带走。请腾出空间后再试一次。', + ru: 'Вы не можете унести всё. Освободите место и попробуйте снова.', + pt: 'Você não consegue carregar tudo isso. Libere espaço e tente novamente.', + de: 'Du kannst nicht alles davon tragen. Schaffe Platz und versuche es erneut.', + fr: 'Vous ne pouvez pas tout porter. Faites de la place et réessayez.', + el: 'Δεν μπορείτε να τα κουβαλήσετε όλα. Κάντε χώρο και δοκιμάστε ξανά.', + ko: '전부 가질 수 없다. 공간을 비운 뒤 다시 시도하자.', + ar: 'لا يمكنك حمل كل هذا. أفرغ مساحة وحاول مرة أخرى.', + it: 'Non puoi portare tutto questo. Fai spazio e riprova.', + pl: 'Nie możesz unieść tego wszystkiego. Zrób miejsce i spróbuj ponownie.', + id: 'Kamu tidak bisa membawa semuanya. Kosongkan ruang lalu coba lagi.', + vi: 'Bạn không thể mang hết những thứ này. Hãy dọn chỗ rồi thử lại.', + th: 'ถือไปทั้งหมดไม่ได้ เคลียร์พื้นที่แล้วลองอีกครั้ง', + tr: 'Bunların hepsini taşıyamazsın. Yer aç ve tekrar dene.' + }, + // Conditional Branch › Reactor: the Can Receive row and its event-list label. + 'Can Receive': { + ja: '受け取り可能', es: 'Puede recibir', 'zh-Hant': '可接收', 'zh-Hans': '可接收', + ru: 'Можно получить', pt: 'Pode receber', de: 'Kann erhalten', fr: 'Peut recevoir', + el: 'Μπορεί να λάβει', ko: '받을 수 있음', ar: 'يمكن الاستلام', it: 'Può ricevere', + pl: 'Można otrzymać', id: 'Dapat menerima', vi: 'Có thể nhận', th: 'รับได้', tr: 'Alınabilir' + }, + 'Can Receive Item': { + ja: 'アイテムを受け取り可能', es: 'Puede recibir objeto', 'zh-Hant': '可接收物品', 'zh-Hans': '可接收物品', + ru: 'Можно получить предмет', pt: 'Pode receber item', de: 'Kann Gegenstand erhalten', + fr: 'Peut recevoir l’objet', el: 'Μπορεί να λάβει αντικείμενο', ko: '아이템을 받을 수 있음', + ar: 'يمكن استلام العنصر', it: 'Può ricevere oggetto', pl: 'Można otrzymać przedmiot', + id: 'Dapat menerima item', vi: 'Có thể nhận vật phẩm', th: 'รับไอเทมได้', tr: 'Eşya alınabilir' + }, + 'Can Receive Weapon': { + ja: '武器を受け取り可能', es: 'Puede recibir arma', 'zh-Hant': '可接收武器', 'zh-Hans': '可接收武器', + ru: 'Можно получить оружие', pt: 'Pode receber arma', de: 'Kann Waffe erhalten', + fr: 'Peut recevoir l’arme', el: 'Μπορεί να λάβει όπλο', ko: '무기를 받을 수 있음', + ar: 'يمكن استلام السلاح', it: 'Può ricevere arma', pl: 'Można otrzymać broń', + id: 'Dapat menerima senjata', vi: 'Có thể nhận vũ khí', th: 'รับอาวุธได้', tr: 'Silah alınabilir' + }, + 'Can Receive Armor': { + ja: '防具を受け取り可能', es: 'Puede recibir armadura', 'zh-Hant': '可接收防具', 'zh-Hans': '可接收防具', + ru: 'Можно получить броню', pt: 'Pode receber armadura', de: 'Kann Rüstung erhalten', + fr: 'Peut recevoir l’armure', el: 'Μπορεί να λάβει πανοπλία', ko: '방어구를 받을 수 있음', + ar: 'يمكن استلام الدرع', it: 'Può ricevere armatura', pl: 'Można otrzymać pancerz', + id: 'Dapat menerima zirah', vi: 'Có thể nhận giáp', th: 'รับชุดเกราะได้', tr: 'Zırh alınabilir' } }; for (const [source, translations] of Object.entries(RR_QUICK_EVENT_TEXT)) { diff --git a/editor/src/database/AnimationPickerModal.js b/editor/src/database/AnimationPickerModal.js index e9a1f31a..244e9028 100644 --- a/editor/src/database/AnimationPickerModal.js +++ b/editor/src/database/AnimationPickerModal.js @@ -147,7 +147,7 @@ class AnimationPickerModal { if (!fx.gl) return false; fx.ctx = effekseer.createContext(); if (!fx.ctx) return false; - fx.ctx.init(fx.gl); + fx.ctx.init(fx.gl, (typeof RREffekseerContextSettings !== 'undefined' ? RREffekseerContextSettings : undefined)); if (typeof RREffekseerStateGuard !== 'undefined') RREffekseerStateGuard.attach(fx.ctx, fx.gl && fx.gl.canvas); else fx.ctx.setRestorationOfStatesFlag(true); fx.ready = true; @@ -315,7 +315,7 @@ class AnimationPickerModal { const settle = () => { if (typeof RREffekseerStateGuard !== 'undefined') RREffekseerStateGuard.settle(fx.ctx); }; if (hdr && fx.handle && fx.handle.exists) { RRHdrPreview.draw(gl, hdr, { width: fxCanvas.width, height: fxCanvas.height, - bloomWidth: RRHdrPreview.bloomWidth(fxCanvas.height) }, () => { + bloomWidth: RRHdrPreview.bloomWidth(fxCanvas.height), frame: aliveTicks * (anim.speed || 100) / 100 }, () => { fx.ctx.beginDraw(); fx.ctx.drawHandle(fx.handle); fx.ctx.endDraw(); diff --git a/editor/src/database/DatabaseAnimationEditor.js b/editor/src/database/DatabaseAnimationEditor.js index c3bf15a6..3ec106e5 100644 --- a/editor/src/database/DatabaseAnimationEditor.js +++ b/editor/src/database/DatabaseAnimationEditor.js @@ -13,13 +13,27 @@ function RR_isValidHdrSidecar(s) { return !!(s && s.version === 1 && s.gradeInput === 'hdr' && typeof s.grade === 'string' && /\bhdr\b/.test(s.grade) && /\btmOut\b/.test(s.grade) && typeof s.fallback === 'string' && s.fallback + && (s.companion === undefined || (typeof s.companion === 'string' && s.companion.trim() + && !/\.efkefc$/i.test(s.companion) && s.companion !== s.fallback)) + && (s.companionOccludes === undefined || typeof s.companionOccludes === 'boolean') + && (s.gradeB === undefined || (typeof s.gradeB === 'string' && /\bhdr\b/.test(s.gradeB) && /\btmOut\b/.test(s.gradeB) + && Array.isArray(s.gradeKeys) && s.gradeKeys.length > 0 + && s.gradeKeys.every((k, i, all) => Array.isArray(k) && k.length === 2 && finite(k[0]) && finite(k[1]) + && k[1] >= 0 && k[1] <= 1 && (i === 0 || k[0] > all[i - 1][0])))) + && (s.gradeKeys === undefined || s.gradeB !== undefined) && s.bloom && Array.isArray(s.bloom.sizes) && Array.isArray(s.bloom.tints) && s.bloom.sizes.length === 6 && s.bloom.tints.length === 6 && s.bloom.sizes.every(x => finite(x) && x > 0) && s.bloom.tints.every(x => finite(x) && x >= 0) && finite(s.bloom.intensity) && s.bloom.intensity >= 0 && finite(s.bloom.radiusScale) && s.bloom.radiusScale > 0 - && (s.bloom.threshold === undefined || finite(s.bloom.threshold))); + && (s.bloom.threshold === undefined || finite(s.bloom.threshold)) + && (s.bloom.intensityKeys === undefined || (Array.isArray(s.bloom.intensityKeys) && s.bloom.intensityKeys.length > 0 + && s.bloom.intensityKeys.every((k, i, all) => Array.isArray(k) && k.length === 2 && finite(k[0]) && finite(k[1]) + && k[1] >= 0 && (i === 0 || k[0] > all[i - 1][0])))) + && (s.bloom.prefilter === undefined || (!!s.bloom.prefilter && typeof s.bloom.prefilter === 'object' + && finite(s.bloom.prefilter.threshold) && finite(s.bloom.prefilter.knee) && s.bloom.prefilter.knee >= 0 + && (s.bloom.prefilter.clamp === undefined || (finite(s.bloom.prefilter.clamp) && s.bloom.prefilter.clamp > 0))))); } /** @@ -50,6 +64,11 @@ function RR_resolveHdrPreviewTwin(effectPath) { throw refuse(`Cannot read ${sidecarPath}: ${error.message}`); } if (!RR_isValidHdrSidecar(sidecar)) throw refuse(`Invalid HDR sidecar ${sidecarPath}`); + if (sidecar.companion) { + const resolve = other => other.includes('/') ? other : effectPath.replace(/\\/g, '/').split('/effects/').pop().replace(/[^/]+$/, '') + other; + const self = effectPath.replace(/\\/g, '/').split('/effects/').pop().replace(/\.efkefc$/i, ''); + if (resolve(sidecar.companion) === self || resolve(sidecar.companion) === resolve(sidecar.fallback)) throw refuse(`Invalid HDR companion ${sidecarPath}`); + } // As in the runtime: a name without '/' sits beside the HDR effect, one // with '/' is relative to the effects folder. let root = dir; @@ -4229,7 +4248,7 @@ class DatabaseAnimationEditor { } // Initialize Effekseer with WebGL context - effekseerContext.init(gl); + effekseerContext.init(gl, (typeof RREffekseerContextSettings !== 'undefined' ? RREffekseerContextSettings : undefined)); // This context also receives the Canvas2D scene blit before // each effect draw, so Effekseer must restore its GL state. effekseerContext.setRestorationOfStatesFlag(true); @@ -4436,8 +4455,9 @@ class DatabaseAnimationEditor { handle.location ? handle.location : 'not available'); } if (hdr) { + const frame = currentFrame * (animation.speed || 100) / 100; RRHdrPreview.draw(gl, hdr, { width: canvas.width, height: canvas.height, - bloomWidth: RRHdrPreview.bloomWidth(canvas.height) }, () => { + bloomWidth: RRHdrPreview.bloomWidth(canvas.height), frame }, () => { effekseerContext.beginDraw(); effekseerContext.drawHandle(handle); effekseerContext.endDraw(); @@ -5267,7 +5287,7 @@ class DatabaseAnimationEditor { return false; } - previewEffekseerContext.init(previewGL); + previewEffekseerContext.init(previewGL, (typeof RREffekseerContextSettings !== 'undefined' ? RREffekseerContextSettings : undefined)); if (typeof RREffekseerStateGuard !== 'undefined') RREffekseerStateGuard.attach(previewEffekseerContext, previewGL.canvas); else previewEffekseerContext.setRestorationOfStatesFlag(true); return true; @@ -5343,6 +5363,7 @@ class DatabaseAnimationEditor { // Render loop let lastTime = Date.now(); let accumulator = 0; + let previewTicks = 0; const fixedTimeStep = 1000 / 60; const render = () => { @@ -5357,6 +5378,7 @@ class DatabaseAnimationEditor { while (accumulator >= fixedTimeStep) { previewEffekseerContext.update(); accumulator -= fixedTimeStep; + previewTicks++; } if (accumulator > fixedTimeStep * 5) { @@ -5388,7 +5410,7 @@ class DatabaseAnimationEditor { const hdr = previewEffect && previewEffect.rrHdr; if (previewHandle && previewHandle.exists && hdr) { RRHdrPreview.draw(previewGL, hdr, { width: previewCanvas.width, height: previewCanvas.height, - bloomWidth: RRHdrPreview.bloomWidth(previewCanvas.height) }, () => { + bloomWidth: RRHdrPreview.bloomWidth(previewCanvas.height), frame: previewTicks * (animation.speed || 100) / 100 }, () => { previewEffekseerContext.beginDraw(); previewEffekseerContext.drawHandle(previewHandle); previewEffekseerContext.endDraw(); diff --git a/editor/src/event/AnimationPicker.js b/editor/src/event/AnimationPicker.js index eade6098..b323cb18 100644 --- a/editor/src/event/AnimationPicker.js +++ b/editor/src/event/AnimationPicker.js @@ -621,7 +621,7 @@ class AnimationPicker { console.error('Failed to create Effekseer context'); return; } - effekseerContext.init(gl); + effekseerContext.init(gl, (typeof RREffekseerContextSettings !== 'undefined' ? RREffekseerContextSettings : undefined)); if (typeof RREffekseerStateGuard !== 'undefined') RREffekseerStateGuard.attach(effekseerContext, gl.canvas); else effekseerContext.setRestorationOfStatesFlag(true); this._effekseerContext = effekseerContext; @@ -721,8 +721,9 @@ class AnimationPicker { const hdr = effect && effect.rrHdr; if (hdr && handle && handle.exists) { + const frame = currentFrame * (animation.speed || 100) / 100; RRHdrPreview.draw(gl, hdr, { width: canvas.width, height: canvas.height, - bloomWidth: RRHdrPreview.bloomWidth(canvas.height) }, () => { + bloomWidth: RRHdrPreview.bloomWidth(canvas.height), frame }, () => { effekseerContext.beginDraw(); effekseerContext.drawHandle(handle); effekseerContext.endDraw(); diff --git a/editor/src/event/EventCommandList.js b/editor/src/event/EventCommandList.js index ced76f6e..63364944 100644 --- a/editor/src/event/EventCommandList.js +++ b/editor/src/event/EventCommandList.js @@ -1711,6 +1711,7 @@ class EventCommandList { description = `${tt('Button')} ${tt(buttonNames[params[1]] || params[1] || 'OK')} ${tt('is')} ${tt(buttonModes[mode] || 'Pressed')}`; } else if (condType === 12) { // Script const generated = EventCommandList.generatedCommand(command, 'inputCondition'); + let capacity = null; // The row that ends a made loop (a number of times, while a variable, a range) reads as what the loop does. const LoopClass = EventCommandList.loopEditorClass(); const i18n = typeof window !== 'undefined' ? window.I18n : null; @@ -1734,6 +1735,14 @@ class EventCommandList { ? this._fmtVarBracket(data.value) : String(data.value); description = `${tt('Pointer Position')} ${data.axis.toUpperCase()} ${data.comparison} ${rhs}`; } + } else if ((capacity = EventCommandList.generatedCommand(command, 'itemCapacityCondition'))) { + const data = capacity.data; + const getter = { item: 'getItem', weapon: 'getWeapon', armor: 'getArmor' }[data.type]; + const label = data.type === 'weapon' ? tt('Can Receive Weapon') + : data.type === 'armor' ? tt('Can Receive Armor') : tt('Can Receive Item'); + const typeName = data.type === 'weapon' ? tt('Weapon') + : data.type === 'armor' ? tt('Armor') : tt('Item'); + description = `${label}: ${this._fmtDatabaseEntry(getter, data.id, typeName)} × ${data.amount}`; } else { const s = String(params[1] ?? ''); description = `${tt('Script:')} ${s.substring(0, 150)}${s.length > 150 ? '...' : ''}`; @@ -3712,6 +3721,11 @@ class EventCommandList { ? ConditionalBranchEditor : require('./commands/ConditionalBranchEditor.js'); return parsed.body === new Editor(null, null)._advancedInputExpression(parsed.data); } + if (kind === 'itemCapacityCondition') { + const Editor = typeof ConditionalBranchEditor !== 'undefined' + ? ConditionalBranchEditor : require('./commands/ConditionalBranchEditor.js'); + return parsed.body === Editor.itemCapacityExpression(parsed.data); + } return true; } @@ -3751,6 +3765,11 @@ class EventCommandList { (data.valueType !== 'variable' || positiveInteger(data.value)); } + if (kind === 'itemCapacityCondition') { + return hasKeys(['type', 'id', 'amount']) && ['item', 'weapon', 'armor'].includes(data.type) && + positiveInteger(data.id) && positiveInteger(data.amount); + } + if (kind === 'control-variables-expression') { const unary = ['absolute', 'squareRoot', 'sineDegrees', 'cosineDegrees']; const binary = ['add', 'subtract', 'multiply', 'divide', 'modulo', 'power', 'minimum', diff --git a/editor/src/event/commands/ConditionalBranchEditor.js b/editor/src/event/commands/ConditionalBranchEditor.js index e1a3adad..87788da1 100644 --- a/editor/src/event/commands/ConditionalBranchEditor.js +++ b/editor/src/event/commands/ConditionalBranchEditor.js @@ -69,6 +69,11 @@ class ConditionalBranchEditor { this.pointerValueType = 'constant'; this.pointerValue = 0; + // Editor-only Can Receive condition (serialized as Script). + this.capacityType = 'item'; + this.capacityItemId = 1; + this.capacityAmount = 1; + // Vehicle condition: 0=boat, 1=ship, 2=airship this.vehicleType = 0; @@ -112,7 +117,8 @@ class ConditionalBranchEditor { this.resetToDefaults(); this.conditionType = params[0] ?? 0; - if (this.conditionType === 12 && this._parseAdvancedInput(params[1])) { + if (this.conditionType === 12 && + (this._parseAdvancedInput(params[1]) || this._parseItemCapacity(params[1]))) { this.originalParameters = params.slice(); this.originalState = this.conditionState(); return; @@ -216,6 +222,9 @@ class ConditionalBranchEditor { this.pointerComparison = '=='; this.pointerValueType = 'constant'; this.pointerValue = 0; + this.capacityType = 'item'; + this.capacityItemId = 1; + this.capacityAmount = 1; this.vehicleType = 0; this.originalParameters = null; this.originalState = null; @@ -242,6 +251,7 @@ class ConditionalBranchEditor { case 16: return [16, this.wheelDirection]; case 17: return [17, this.pointerAxis, this.pointerComparison, this.pointerValueType, this.pointerValue]; + case 18: return [18, this.capacityType, this.capacityItemId, this.capacityAmount]; default: return [this.conditionType]; } } @@ -250,8 +260,8 @@ class ConditionalBranchEditor { * RPG Maker's Conditional Branch layout: four numbered tabs of * radio-selected conditions with every control on screen and only the * chosen condition's controls enabled. A fifth tab holds the Reactor-only - * input conditions (keyboard/mouse/wheel/pointer), which still serialize - * as a Script condition the runtime and RPG Maker both accept. + * conditions (keyboard/mouse/wheel/pointer input, and Can Receive), which + * still serialize as a Script condition the runtime and RPG Maker both accept. */ static get TABS() { return [ @@ -259,7 +269,7 @@ class ConditionalBranchEditor { { label: '2', types: [4] }, { label: '3', types: [5, 6, 13] }, { label: '4', types: [7, 8, 9, 10, 11, 12] }, - { label: 'Reactor', types: [14, 15, 16, 17] } + { label: 'Reactor', types: [14, 15, 16, 17, 18] } ]; } @@ -881,6 +891,84 @@ class ConditionalBranchEditor { () => { this.pointerValueType = 'variable'; if (!(this.pointerValue >= 1)) this.pointerValue = 1; }, [ this._reference('variable', Math.max(1, this.pointerValue), id => { this.pointerValue = id; }) ])); + + // Can Receive: whether the party has room for the whole amount, under + // whatever cap $gameParty.maxItems reports when the event runs. + const capacityGetter = ConditionalBranchEditor.CAPACITY_TYPES[this.capacityType].getter; + page.appendChild(this._conditionRow(18, this._tt('Can Receive'), [ + this._select([ + { value: 'item', label: this._tt('Item') }, + { value: 'weapon', label: this._tt('Weapon') }, + { value: 'armor', label: this._tt('Armor') } + ], this.capacityType, v => { + this.capacityType = v; + this.capacityItemId = 1; + this.renderContent(); + }, true), + this._databaseSelect(capacityGetter, this.capacityItemId, v => { this.capacityItemId = v; }), + this._word('×'), + this._number(this.capacityAmount, v => { this.capacityAmount = Math.max(1, v); }, + { min: 1, narrow: true }) + ])); + } + + /** Database table and editor getter for each Can Receive reward type. */ + static get CAPACITY_TYPES() { + return { + item: { table: '$dataItems', getter: 'getItems' }, + weapon: { table: '$dataWeapons', getter: 'getWeapons' }, + armor: { table: '$dataArmors', getter: 'getArmors' } + }; + } + + static isValidItemCapacityData(data) { + return !!data && typeof data === 'object' && !Array.isArray(data) && + Object.keys(data).length === 3 && + Object.prototype.hasOwnProperty.call(ConditionalBranchEditor.CAPACITY_TYPES, data.type) && + Number.isInteger(data.id) && data.id > 0 && + Number.isInteger(data.amount) && data.amount > 0; + } + + /** + * True when the party can take the whole amount without passing the cap. + * It asks the live Game_Party, so plugin limits (VisuStella's ) + * and Reactor's own apply; a missing database entry answers false. + */ + static itemCapacityExpression(data) { + const table = ConditionalBranchEditor.CAPACITY_TYPES[data.type].table; + return `(function(item){return !!item&&$gameParty.numItems(item)+${data.amount}<=` + + `$gameParty.maxItems(item);})(${table}[${data.id}])`; + } + + /** The Script condition text (codec header + expression) for Can Receive. */ + static createItemCapacityText(data, codec = ConditionalBranchEditor._codecClass()) { + if (!codec) throw new Error('ReactorEventCommandCodec is unavailable'); + if (!ConditionalBranchEditor.isValidItemCapacityData(data)) { + throw new TypeError('Can Receive needs an item, weapon or armor id and a positive amount'); + } + const canonical = { type: data.type, id: data.id, amount: data.amount }; + return codec.createText('itemCapacityCondition', canonical, + ConditionalBranchEditor.itemCapacityExpression(canonical)); + } + + _parseItemCapacity(text) { + const codec = this._codec(); + if (!codec || typeof text !== 'string') return false; + let parsed; + try { + parsed = codec.parseText(text, 'itemCapacityCondition'); + } catch (e) { + return false; + } + const data = parsed && parsed.data; + if (!ConditionalBranchEditor.isValidItemCapacityData(data)) return false; + // A hand-edited body is the author's script now: reopen it as one. + if (parsed.body !== ConditionalBranchEditor.itemCapacityExpression(data)) return false; + this.conditionType = 18; + this.capacityType = data.type; + this.capacityItemId = data.id; + this.capacityAmount = data.amount; + return true; } _tt(text) { @@ -985,6 +1073,11 @@ class ConditionalBranchEditor { case 17: // Pointer Position parameters = [12, this._buildAdvancedInputText()]; break; + case 18: // Can Receive + parameters = [12, ConditionalBranchEditor.createItemCapacityText({ + type: this.capacityType, id: this.capacityItemId, amount: this.capacityAmount + }, this._codec())]; + break; default: parameters = [this.conditionType]; break; @@ -1121,6 +1214,10 @@ class ConditionalBranchEditor { } _codec() { + return ConditionalBranchEditor._codecClass(); + } + + static _codecClass() { if (typeof globalThis !== 'undefined' && globalThis.ReactorEventCommandCodec) { return globalThis.ReactorEventCommandCodec; } diff --git a/editor/src/forge/EffekseerGenerator/EffekseerGenerator.js b/editor/src/forge/EffekseerGenerator/EffekseerGenerator.js index 8c1eca9e..ad093854 100644 --- a/editor/src/forge/EffekseerGenerator/EffekseerGenerator.js +++ b/editor/src/forge/EffekseerGenerator/EffekseerGenerator.js @@ -2341,7 +2341,7 @@ class EffekseerGenerator { if (!gl) { this._overlay(this._tx('WebGL unavailable'), true); return; } this._gl = gl; this._efkContext = effekseer.createContext(); - this._efkContext.init(gl); + this._efkContext.init(gl, (typeof RREffekseerContextSettings !== 'undefined' ? RREffekseerContextSettings : undefined)); if (typeof RREffekseerStateGuard !== 'undefined') RREffekseerStateGuard.attach(this._efkContext, gl.canvas); else this._efkContext.setRestorationOfStatesFlag(true); } catch (e) { diff --git a/editor/src/utils/AnimationPreviewLayer.js b/editor/src/utils/AnimationPreviewLayer.js index e79ff28f..785b75ec 100644 --- a/editor/src/utils/AnimationPreviewLayer.js +++ b/editor/src/utils/AnimationPreviewLayer.js @@ -399,7 +399,7 @@ else { fx.ctx = effekseer.createContext(); if (!fx.ctx) return false; - fx.ctx.init(fx.gl); + fx.ctx.init(fx.gl, (typeof RREffekseerContextSettings !== 'undefined' ? RREffekseerContextSettings : undefined)); } // This context is Effekseer's alone: restore state once, and // again only after a focus/visibility change (see the guard). @@ -570,7 +570,7 @@ }; // An HDR effect draws into a light buffer the size of the // full view, so its bloom is not cut at the box's edge. - if (hdr && drawn) RRHdrPreview.draw(gl, hdr, this._hdrView(), drawHandle); + if (hdr && drawn) RRHdrPreview.draw(gl, hdr, { ...this._hdrView(), frame: ticks * (animation.speed || 100) / 100 }, drawHandle); else drawHandle(); // Where the picture ends is learned from the first two // plays; the readback that finds it stalls the GPU, so diff --git a/editor/src/utils/EffekseerContextSettings.js b/editor/src/utils/EffekseerContextSettings.js new file mode 100644 index 00000000..655d2e40 --- /dev/null +++ b/editor/src/utils/EffekseerContextSettings.js @@ -0,0 +1,19 @@ +/** + * EffekseerContextSettings - what every Effekseer context the editor creates + * for an animation preview is initialized with, matching the runtime's + * `Graphics.effekseerContextSettings` (runtime/reactor_core.js). + * + * Effekseer keeps a fixed pool of particle instances per context (its own + * default is 4000) and silently skips a new particle when the pool is full, + * so the layers that spawn first keep everything and later ones lose + * particles. A preview with a smaller pool than the game would show a + * different effect. Each instance reserves about 5 KB of Effekseer's heap. + */ +(function(root) { + 'use strict'; + + const EffekseerContextSettings = { instanceMaxCount: 16000, squareMaxCount: 40000 }; + + root.RREffekseerContextSettings = EffekseerContextSettings; + if (typeof module !== 'undefined' && module.exports) module.exports = EffekseerContextSettings; +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/editor/src/utils/HdrPreview.js b/editor/src/utils/HdrPreview.js index f9b66308..66b3c3f8 100644 --- a/editor/src/utils/HdrPreview.js +++ b/editor/src/utils/HdrPreview.js @@ -19,6 +19,54 @@ // null: not tried; 'loading': the web host is fetching it; then true or false. let runtimeState = null; const renderers = new WeakMap(); + const contexts = new WeakMap(); + // Central pairing keeps every preview site on the same seed, clock and transforms. + function pairContext(context) { + if (contexts.has(context)) return; + const state = { pass: 'light' }; + contexts.set(context, state); + const play = context.play, drawHandle = context.drawHandle, releaseEffect = context.releaseEffect; + context.play = function(effect, ...args) { + const main = play.call(this, effect, ...args); + if (!effect.rrHdr?.companionEffect || !main) return main; + const companion = play.call(this, effect.rrHdr.companionEffect, ...args); + if (!companion) { main.stop(); throw Error('HDR companion play failed'); } + const seed = Math.floor(Math.random() * 0x7fffffff); + main.setRandomSeed(seed); companion.setRandomSeed(seed); + return new Proxy(main, { get(target, key) { + if (key === 'rrCompanion') return companion; + if (key === 'exists') return target.exists || companion.exists; + const value = target[key]; + if (typeof value !== 'function') return value; + return (...values) => { + const result = value.apply(target, values); + if ((String(key).startsWith('set') || key === 'stop') && typeof companion[key] === 'function') companion[key](...values); + return result; + }; + } }); + }; + context.drawHandle = function(handle) { + const chosen = state.pass === 'companion' ? handle?.rrCompanion : handle; + if (chosen?.exists) return drawHandle.call(this, chosen); + }; + if (releaseEffect) context.releaseEffect = function(effect) { + effect?.rrHdr?.cancelLoad?.(); + if (effect?.rrHdr?.companionEffect) releaseEffect.call(this, effect.rrHdr.companionEffect); + return releaseEffect.call(this, effect); + }; + } + function companionPath(effectPath, name) { + const path = require('path'); + let base = path.dirname(effectPath); + if (name.includes('/')) { + while (path.basename(base).toLowerCase() !== 'effects') { + const up = path.dirname(base); + if (up === base) throw Error('no effects directory for companion'); + base = up; + } + } + return path.join(base, ...name.split('/')) + '.efkefc'; + } function runtimeCandidates() { const path = require('path'); @@ -108,11 +156,16 @@ if (!renderer) return fallback(runtimeState === 'loading' ? 'the HDR renderer is still loading' : 'the HDR renderer is not available'); if (!renderer.ensure(Math.max(1, width | 0), Math.max(1, height | 0))) return fallback('this WebGL context has no float render targets'); try { - renderer.gradeProgram(twin.sidecar.grade); + renderer.gradeProgram(twin.sidecar.grade, twin.sidecar.gradeB); } catch (error) { return fallback('its grade does not compile: ' + (error && error.message)); } - return { mode: 'hdr', sidecar: twin.sidecar, renderer }; + if (twin.sidecar.companion) { + const fs = require('fs'); + const file = companionPath(effectPath, twin.sidecar.companion); + if (!fs.existsSync(file) || fs.existsSync(file.replace(/\.efkefc$/i, '.hdr.json'))) return fallback('companion missing or has HDR metadata'); + } + return { mode: 'hdr', sidecar: twin.sidecar, renderer, context: null }; } /** @@ -132,9 +185,41 @@ } const choice = choose(gl, effectPath, view.width, view.height, options); if (choice.mode === 'hdr') { - const effect = RR_loadEffekseerEffectFromFile(context, effectPath, scale, onLoad, onError, effectPath); - if (effect) effect.rrHdr = choice; - return effect; + if (!choice.sidecar.companion) { + const effect = RR_loadEffekseerEffectFromFile(context, effectPath, scale, onLoad, onError, effectPath); + if (effect) effect.rrHdr = choice; + return effect; + } + pairContext(context); + choice.context = context; + let current, primary, companion, finished = false, failed = false; + const complete = () => queueMicrotask(() => { + if (!finished && current?.isLoaded && (failed || companion?.isLoaded)) { finished = true; clearTimeout(timeout); onLoad?.(); } + }); + let timeout; + const fallback = () => queueMicrotask(() => { + if (failed || finished) return; + failed = true; + clearTimeout(timeout); + const ownsCompanion = !!primary?.rrHdr?.companionEffect; + if (primary) context.releaseEffect(primary); + if (companion && !ownsCompanion) context.releaseEffect(companion); + const twin = RR_resolveHdrPreviewTwin(effectPath); + current = RR_loadEffekseerEffectFromFile(context, twin.twinPath, scale, complete, onError, effectPath); + if (current) current.rrHdrTwin = Object.assign({}, twin, { reason: 'companion failed to load' }); + complete(); + }); + choice.cancelLoad = () => { clearTimeout(timeout); if (!failed) finished = true; }; + timeout = setTimeout(fallback, 15000); + companion = RR_loadEffekseerEffectFromFile(context, companionPath(effectPath, choice.sidecar.companion), scale, complete, fallback, effectPath); + primary = RR_loadEffekseerEffectFromFile(context, effectPath, scale, complete, onError, effectPath); + if (!failed) { current = primary; choice.companionEffect = companion; if (current) current.rrHdr = choice; } + complete(); + return new Proxy({}, { get(_target, key) { + if (key === 'isLoaded') return !!current?.isLoaded && (failed || !!companion?.isLoaded); + const value = current?.[key]; + return typeof value === 'function' ? value.bind(current) : value; + } }); } if (choice.mode === 'twin') { const effect = RR_loadEffekseerEffectFromFile(context, choice.twin.twinPath, scale, onLoad, onError, effectPath); @@ -173,8 +258,10 @@ * composite's viewport when it is not the buffer's own (a cropped view); * `premultiplied` for a premultiplied canvas with nothing behind it in GL; * `bloomWidth` (see bloomWidth), the buffer's width when absent. The - * sidecar's bloom threshold acts on the game's setup pixels, which the - * same width converts into the preview's. + * sidecar's bloom threshold (or prefilter) acts on the game's setup pixels, which the + * same width converts into the preview's. `frame`, the effect's own frame + * (updates since its play times its speed), picks the bloom intensity + * and the second grade's weight when the sidecar keys them (bloom.intensityKeys, gradeKeys); frame 0 when absent. * False when this context can no longer render HDR; nothing was drawn. */ function draw(gl, choice, view, drawEffect) { @@ -183,14 +270,27 @@ const sidecar = choice.sidecar; const game = screen(); try { + const state = choice.context && contexts.get(choice.context); + if (state && choice.companionEffect) { + state.pass = 'companion'; + try { drawEffect(); } finally { state.pass = 'light'; } + } renderer.begin(); + if (state && choice.companionEffect && sidecar.companionOccludes !== false) { + state.pass = 'companion'; + try { gl.colorMask(false, false, false, false); gl.depthMask(true); drawEffect(); } + finally { gl.colorMask(true, true, true, true); state.pass = 'light'; } + } drawEffect(); renderer.post({ - bloom: sidecar.bloom.intensity, + bloom: root.ReactorHdrRenderer.bloomIntensity ? root.ReactorHdrRenderer.bloomIntensity(sidecar.bloom, view.frame) + : sidecar.bloom.intensity, + gradeMix: root.ReactorHdrRenderer.gradeMix ? root.ReactorHdrRenderer.gradeMix(sidecar, view.frame) : 0, bloomScale: sidecar.bloom.radiusScale, alphaFromColor: !!view.premultiplied, bloomWidth: view.bloomWidth, threshold: sidecar.bloom.threshold, + prefilter: sidecar.bloom.prefilter, pixelScale: view.bloomWidth > 0 && game.width ? view.bloomWidth / game.width : undefined }, sidecar, view.out); return true; diff --git a/editor/tests/battle-presentation.test.cjs b/editor/tests/battle-presentation.test.cjs index 86bee01b..c1033b7b 100644 --- a/editor/tests/battle-presentation.test.cjs +++ b/editor/tests/battle-presentation.test.cjs @@ -733,3 +733,35 @@ test('a melee approach stops at the edge of a wide body (a tank), not inside it; assert.ok(Math.abs(P.reachAlong(box,{x:0,y:8},{x:8,y:8})-3)<1e-6,'along its length, half its length'); assert.ok(Math.abs(P.reachAlong(box,{x:8,y:0},{x:8,y:8})-1.4)<1e-6,'across it, half its width'); }); + +test('flat 2D float, fall, jump and leap keep vertical lift across Sprite_Battler.updatePosition, chain seamlessly and restore cleanly',()=>{ + const vm=require('node:vm'); + const updatePosSrc=runtimeSource('reactor_sprites.js').match(/Sprite_Battler\.prototype\.updatePosition\s*=\s*function\(\)\s*\{[\s\S]*?\n\};/)?.[0]; + assert.ok(updatePosSrc,'found Sprite_Battler.prototype.updatePosition'); + function Sprite(){this.x=808;this.y=487;this.opacity=255;this.rotation=0;this.visible=true;this.scale={x:1,y:1,set(x,y=x){this.x=x;this.y=y;}};this._homeX=808;this._homeY=487;this._offsetX=0;this._offsetY=0;this._animationSprites=[];this._damages=[];} + Sprite.prototype.setColorTone=()=>{};Sprite.prototype.getColorTone=()=>[0,0,0,0];Sprite.prototype.setBlendColor=()=>{};Sprite.prototype.getBlendColor=()=>[0,0,0,0]; + Sprite.prototype.isMoving=()=>false;Sprite.prototype.isEffecting=()=>false;Sprite.prototype.refreshMotion=()=>{};Sprite.prototype.startMotion=()=>{};Sprite.prototype.isAnimationPlaying=()=>false; + const user={isActor:()=>true,actorId:()=>1,isEnemy:()=>false,isDead:()=>false},target={isActor:()=>false,enemyId:()=>11,isEnemy:()=>true,isDead:()=>false}; + const userSprite=new Sprite(),targetSprite=new Sprite();targetSprite._homeX=480;targetSprite.x=480;targetSprite.y=487; + const ss={_animationSprites:[],_effectsContainer:{},_battleField:{},findTargetSprite:b=>b===user?userSprite:b===target?targetSprite:null}; + const scope={ReactorBattleData:B,Sprite,Sprite_Base:Sprite,Sprite_Battler:Sprite,Spriteset_Base:function(){},Spriteset_Battle:function(){},Window_BattleLog:function(){},Scene_Battle:function(){},PluginManager:{_scripts:[],registerCommand(){}},DataManager:{isDatabaseLoaded:()=>true,isSkill:()=>true},BattleManager:{_spriteset:ss,_subject:user,_targets:[target],_logWindow:{_methods:[],displayActionResults(){}},invokeAction(){}},SceneManager:{_scene:{_spriteset:ss}},$dataAnimations:[null],$gameTemp:{_animationQueue:[],requestAnimation(){}},Date}; + vm.runInNewContext(updatePosSrc,scope);vm.runInNewContext(runtimeSource('reactor_battle_presentation.js'),scope); + // Chained float -> fall -> concurrent jump + move -> impact -> cleanup + const seq={version:1,steps:[B.step('float',{role:'user',height:8,duration:25,easing:'linear'}),B.step('fall',{role:'user',height:0,duration:20,easing:'linear'}),B.step('jump',{role:'user',height:2.67,duration:10,easing:'linear',concurrent:true}),B.step('move',{role:'user',anchor:'home',x:0,y:0,duration:5}),B.step('wait',{role:'user',duration:0,waitFor:'jump'}),B.step('impact')]}; + const p=new B.Player(seq,scope.ReactorBattlePresentation.adapter(scope.BattleManager,user,[target])); + const seen={}; + for(let f=0;f<70&&!p.done;f++){ + p.update(1);userSprite.updatePosition(); + if([24,34,44,49,54].includes(f))seen[f]={y:userSprite.y,offsetY:userSprite._offsetY,lift:userSprite._rrLift}; + } + assert.equal(seen[24].lift,8);assert.equal(seen[24].offsetY,-384);assert.equal(seen[24].y,103); + assert.ok(Math.abs(seen[34].lift-4)<1e-6);assert.equal(seen[34].y,487-seen[34].lift*48); + assert.equal(seen[44].lift,0);assert.equal(seen[44].y,487); + assert.ok(Math.abs(seen[49].lift-2.67)<1e-6);assert.ok(Math.abs(seen[49].y-(487-2.67*48))<1e-6); + assert.equal(userSprite._rrLift,0);assert.equal(userSprite._offsetY,0);assert.equal(userSprite.y,487); + // Leap preserves external _offsetY and restores cleanly after completion + userSprite._offsetY=12;userSprite.updatePosition(); + const pLeap=new B.Player({version:1,steps:[B.step('leap',{role:'user',x:100,y:0,height:4,duration:10}),B.step('impact')]},scope.ReactorBattlePresentation.adapter(scope.BattleManager,user,[target])); + pLeap.update(5);userSprite.updatePosition();assert.ok(userSprite._rrLift>0);const lift=userSprite._rrLift;assert.equal(userSprite._offsetY,12-lift*48);assert.equal(userSprite.y,487+12-lift*48); + pLeap.update(20);pLeap.update(5);userSprite.updatePosition();assert.equal(pLeap.done,true);assert.equal(userSprite._rrLift,0);assert.equal(userSprite._offsetY,12);assert.equal(userSprite.y,499); +}); diff --git a/editor/tests/context-restore.test.cjs b/editor/tests/context-restore.test.cjs index bdbc648d..05353deb 100644 --- a/editor/tests/context-restore.test.cjs +++ b/editor/tests/context-restore.test.cjs @@ -137,9 +137,11 @@ test('the Effekseer overlay accepts its loss and starts a new context when it is const created = []; const gl = { lost: false, isContextLost() { return this.lost; } }; const context = { - Graphics: { _effekseerGL: gl, _effekseer: 'old', rearmEffekseerState() { this.rearmed = true; } }, + Graphics: { _effekseerGL: gl, _effekseer: 'old', rearmEffekseerState() { this.rearmed = true; }, + // The overlay's pool is chosen as at boot (Graphics._overlayEffekseerSettings). + _overlayEffekseerSettings() { return this.pool; }, pool: { instanceMaxCount: 16000 } }, window: { effekseer: true }, - effekseer: { createContext: () => { const c = { init(g) { this.gl = g; } }; created.push(c); return c; } }, + effekseer: { createContext: () => { const c = { init(g, settings) { this.gl = g; this.settings = settings; } }; created.push(c); return c; } }, EffectManager: { _cache: { 'effects/Old.efkefc': 1 } }, console }; @@ -148,6 +150,7 @@ test('the Effekseer overlay accepts its loss and starts a new context when it is assert.equal(created.length, 1); assert.equal(context.Graphics._effekseer, created[0]); assert.equal(created[0].gl, gl); + assert.equal(created[0].settings, context.Graphics.pool, 'a restored overlay takes the pool the boot rule gives it'); assert.deepEqual(Object.keys(context.EffectManager._cache), [], 'effects load again into the new context'); assert.equal(context.Graphics.rearmed, true); // Nothing starts on a context that is still lost. diff --git a/editor/tests/effekseer-context-settings.test.cjs b/editor/tests/effekseer-context-settings.test.cjs new file mode 100644 index 00000000..f7fd8d61 --- /dev/null +++ b/editor/tests/effekseer-context-settings.test.cjs @@ -0,0 +1,100 @@ +// The Effekseer contexts that play effects (the in-scene context, the 3D map's effects context, the overlay when it +// draws screen animations, and every editor preview) get the same instance pool, so the game and its previews drop +// particles at the same count (Effekseer skips a new particle silently when the pool is full). The overlay made at +// boot keeps Effekseer's default pool while screen animations play in the scene: there it only loads effects. +const test = require('node:test'), assert = require('node:assert/strict'), fs = require('node:fs'), path = require('node:path'), vm = require('node:vm'); +const root = path.resolve(__dirname, '../..'); + +function jsFiles(dir) { + const out = []; + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) { if (e.name !== 'libs' && e.name !== 'node_modules') out.push(...jsFiles(p)); } + else if (e.name.endsWith('.js')) out.push(p); + } + return out; +} + +function runtimeSettings() { + const src = fs.readFileSync(path.join(root, 'runtime/reactor_core.js'), 'utf8'); + const m = src.match(/Graphics\.effekseerContextSettings = (\{[^}]*\});/); + assert.ok(m, 'runtime/reactor_core.js defines Graphics.effekseerContextSettings'); + return vm.runInNewContext('(' + m[1] + ')'); +} + +/** The init line after each `effekseer.createContext()` in a file. */ +function initsAfterCreate(file) { + const lines = fs.readFileSync(path.join(root, file), 'utf8').split(/\r?\n/); + const out = []; + lines.forEach((line, i) => { + if (!/effekseer\.createContext\(\)/.test(line)) return; + const init = lines.slice(i, i + 10).find((l) => /\.init\(/.test(l)); + assert.ok(init, `${file}:${i + 1} has no init after createContext`); + out.push(init.trim()); + }); + return out; +} + +test('the runtime and the editor previews use one pool size, above Effekseer\'s default 4000', () => { + const runtime = runtimeSettings(); + const editor = require(path.join(root, 'editor/src/utils/EffekseerContextSettings.js')); + assert.deepEqual({ ...editor }, { ...runtime }); + assert.ok(Number.isInteger(runtime.instanceMaxCount) && runtime.instanceMaxCount > 4000); + assert.ok(runtime.squareMaxCount >= 10000); +}); + +test('the contexts that play effects take the large pool; the boot-time overlay is sized by Graphics._overlayEffekseerSettings', () => { + // The in-scene context and the 3D map's effects context are made at their first use, and play effects. + const sprites = initsAfterCreate('runtime/reactor_sprites.js'); + assert.equal(sprites.length, 1, 'one in-scene context'); + assert.match(sprites[0], /Graphics\.effekseerContextSettings/); + const gpu = initsAfterCreate('runtime/reactor_3d_effects.js'); + assert.equal(gpu.length, 1, 'one 3D effects context'); + assert.match(gpu[0], /Graphics\.effekseerContextSettings/); + const sceneLayer = fs.readFileSync(path.join(root, 'runtime/reactor_sprites.js'), 'utf8'); + assert.match(sceneLayer, /ensureContext\(\) \{\s*if \(this\.context\) return this\.context;/, 'the in-scene context is made once, at first use'); + // The overlay (made at boot, and again after a lost context) asks the helper both times. + const core = initsAfterCreate('runtime/reactor_core.js'); + assert.equal(core.length, 2, 'boot and restore'); + for (const init of core) assert.match(init, /this\._overlayEffekseerSettings\(\)/, init); + // Every editor preview keeps the shared settings. + let sites = 0; + for (const file of jsFiles(path.join(root, 'editor/src'))) { + for (const init of initsAfterCreate(path.relative(root, file))) { + sites++; + assert.match(init, /RREffekseerContextSettings|effekseerContextSettings/, `${path.relative(root, file)} inits without the shared settings: ${init}`); + } + } + assert.ok(sites >= 6, 'found ' + sites + ' editor createContext sites'); +}); + +test('the overlay keeps Effekseer\'s default pool only while screen animations play in the scene', () => { + const src = fs.readFileSync(path.join(root, 'runtime/reactor_core.js'), 'utf8'); + const m = src.match(/Graphics\._overlayEffekseerSettings = function\(\) \{[\s\S]*?\r?\n\};/); + assert.ok(m, 'runtime/reactor_core.js defines Graphics._overlayEffekseerSettings'); + const settings = runtimeSettings(); + const helper = (spriteAnimation) => { + const sandbox = { Graphics: { effekseerContextSettings: settings } }; + if (spriteAnimation !== undefined) sandbox.Sprite_Animation = spriteAnimation; + vm.runInNewContext(m[0], sandbox); + return sandbox.Graphics._overlayEffekseerSettings(); + }; + assert.equal(helper({ SceneLayer: { active: () => true } }), undefined, 'in-scene active: the overlay only loads effects'); + assert.equal(helper({ SceneLayer: { active: () => false } }), settings, 'in-scene inactive: the overlay draws screen animations'); + assert.equal(helper(undefined), settings, 'no Sprite_Animation'); + assert.equal(helper({}), settings, 'no SceneLayer'); + assert.equal(helper({ SceneLayer: { active() { throw new Error('boom'); } } }), settings, 'a throw'); +}); + +test('the editor loads the settings before any preview script', () => { + const html = fs.readFileSync(path.join(root, 'editor/index.html'), 'utf8'); + const at = (s) => html.indexOf(s); + assert.ok(at('src/utils/EffekseerContextSettings.js') > at('libs/effekseer.min.js')); + for (const s of ['AnimationPreviewLayer.js', 'DatabaseAnimationEditor.js', 'AnimationPicker.js', 'AnimationPickerModal.js']) + assert.ok(at('src/utils/EffekseerContextSettings.js') < at(s), s); +}); + +test('the Demo template carries the same runtime files', () => { + for (const f of ['reactor_core.js', 'reactor_sprites.js', 'reactor_3d_effects.js']) + assert.equal(fs.readFileSync(path.join(root, 'template/Demo/js', f), 'utf8'), fs.readFileSync(path.join(root, 'runtime', f), 'utf8'), f); +}); diff --git a/editor/tests/effekseer-in-scene.test.cjs b/editor/tests/effekseer-in-scene.test.cjs index 72ef4474..9319dd0e 100644 --- a/editor/tests/effekseer-in-scene.test.cjs +++ b/editor/tests/effekseer-in-scene.test.cjs @@ -137,6 +137,39 @@ test('screen animations are taken where PIXI is WebGL2 and in-scene is on; ancho assert.equal(environment({ webGLVersion: 1 }).layer.adopt({}), false, 'a WebGL1 renderer keeps the overlay'); }); +test('on the alpha-less canvas the scene is blitted into an RGBA square with clamped edges before the distortion copy', () => { + // PIXI creates the canvas with alpha: false; WebGL refuses copyTexSubImage2D from it into Effekseer's RGBA backdrop, + // so distortion layers drew black (BD2 Meltdown, 2026-11-04). A filter's texture is RGBA and copies directly. + const e = environment({ framebuffer: null, flipped: false }); + e.gl.getContextAttributes = () => ({ alpha: false }); + e.gl.drawingBufferWidth = 800; e.gl.drawingBufferHeight = 600; + const s = e.sprite(); + e.layer.adopt(s); + e.calls.length = 0; + s.children[0].render(e.renderer); + const name = c => c[0]; + assert.deepEqual(e.drawn, ['Fire']); + assert.deepEqual(e.captures, [[0, 0, 1200, 1200]], 'copied from the scratch square, whose origin is the viewport origin'); + assert.deepEqual(e.calls.find(c => name(c) === 'renderbufferStorage' && c[3] === 1200).slice(3), [1200, 1200], 'an RGBA square of the viewport size'); + const blits = e.calls.filter(c => name(c) === 'blitFramebuffer'); + assert.deepEqual(blits[0].slice(1, 9), [0, 0, 800, 600, 200, 300, 1000, 900], 'the screen at its place in the square'); + assert.equal(blits.length, 9, 'the screen, four edge strips and four corners: off-screen texels repeat the edge, as UE clamps'); + assert.deepEqual(blits[1].slice(1, 9), [0, 0, 1, 600, 0, 300, 200, 900], 'the left margin repeats the left column'); + const reads = e.calls.filter(c => name(c) === 'bindFramebuffer' && c[1] === e.gl.READ_FRAMEBUFFER).map(c => c[2]); + assert.ok(reads.length >= 2 && reads[0] === null && reads[reads.length - 1] && reads[reads.length - 1].made, 'blitted from the canvas, copied from the square'); + assert.deepEqual(e.reads, [], 'still no GL state read back'); + // a second draw reuses the square + e.calls.length = 0; + s.children[0].render(e.renderer); + assert.equal(e.calls.filter(c => name(c) === 'createFramebuffer').length, 0); + // with an alpha channel, or into a filter's texture, the copy is direct + const f = environment(); + f.gl.getContextAttributes = () => ({ alpha: false }); + const t = f.sprite(); f.layer.adopt(t); t.children[0].render(f.renderer); + assert.deepEqual(f.captures, [[-200, -300, 1200, 1200]]); + assert.equal(f.calls.filter(c => name(c) === 'blitFramebuffer').length, 0); +}); + test('an animation draws into the target PIXI is rendering to, then leaves PIXI as it found it', () => { const e = environment(); const s = e.sprite(); @@ -189,8 +222,6 @@ test('on the canvas no depth buffer is lent and the effect is drawn the right wa assert.equal(e.calls.filter(c => c[0] === 'clear').length, 1, 'the canvas\'s own depth buffer, cleared once a frame'); assert.deepEqual(e.projections[0].filter((_, i) => [1, 5, 9, 13].includes(i)), [2, 6, 10, 14]); assert.deepEqual(e.calls.filter(c => c[0] === 'frontFace').map(c => c[1]), [e.gl.CCW, e.gl.CCW]); - // The canvas has no alpha: its RGB pixels cannot be copied into Effekseer's RGBA background (GL refuses). - assert.deepEqual(e.captures, [], 'nothing captured from the canvas'); assert.deepEqual(e.drawn, ['Fire'], 'the effect is still drawn'); }); @@ -198,7 +229,7 @@ test('HDR animations of one grade in one container share a light pass, composite const e = environment(); const passes = [], fallbacks = []; const R = { ensure: (w, h) => { passes.push(['ensure', w, h]); return true; }, begin: () => passes.push(['begin']), post: (s, sc, out) => passes.push(['post', s, out]) }; - e.c.ReactorHdrOverlay = { scene: { sidecar: s => ({ grade: s.grade }), renderer: () => R, settings: () => ({ bloom: 1 }), fallBack: s => fallbacks.push(s) } }; + e.c.ReactorHdrOverlay = { scene: { sidecar: s => ({ grade: s.grade }), renderer: () => R, settings: () => ({ bloom: 1 }), intensity: () => 1, fallBack: s => fallbacks.push(s) } }; const a = e.sprite('A'), b = e.sprite('B'), other = e.sprite('C'); for (const s of [a, b, other]) { e.layer.adopt(s); s._hdrActive = true; s.grade = 'g'; } other.grade = 'h'; @@ -349,3 +380,16 @@ test('EffectManager preloads into the scene layer while screen animations play t assert.equal(c.EffectManager.preload('Wind'), true); assert.deepEqual(overlayLoads, ['Wind'], 'off: the overlay\'s context loads it'); }); + +test('HDR companions draw into the saved target before light and participate in the depth prepass',()=>{ + const e=environment(),order=[]; + const R={ensure(){e.gl.bindFramebuffer(e.gl.FRAMEBUFFER,null);return true;},begin(){order.push('begin');},post(){order.push('post');}}; + e.c.ReactorHdrOverlay={scene:{sidecar:()=>({grade:'g',companionOccludes:true}),renderer:()=>R,settings:()=>({}),intensity:()=>1,lost(){}}}; + const s=e.sprite('light');e.layer.adopt(s);s._hdrActive=true;s._companionHandle={exists:true,name:'body'};e.layer.frame.push(s); + const draw=e.context.drawHandle;e.context.drawHandle=h=>{order.push(h.name);draw(h);}; + e.layer.drawHdr(e.renderer,s);assert.deepEqual(order,['body','begin','body','light','post']); + const nullAt=e.calls.findIndex(c=>c[0]==='bindFramebuffer'&&c[2]===null); + assert.ok(e.calls.slice(nullAt+1).some(c=>c[0]==='bindFramebuffer'&&c[2]?.fb==='filter')); + assert.ok(e.calls.some(c=>c[0]==='colorMask'&&c.slice(1).every(v=>v===false))); + e.layer.lost();assert.equal(s._companionHandle,null);assert.equal(s._companionEffect,null); +}); diff --git a/editor/tests/effekseer-state-guard.test.cjs b/editor/tests/effekseer-state-guard.test.cjs index 52117bff..d2995d26 100644 --- a/editor/tests/effekseer-state-guard.test.cjs +++ b/editor/tests/effekseer-state-guard.test.cjs @@ -99,7 +99,7 @@ test('every Effekseer context the editor owns outright is guarded, and the share test('the game overlay context follows the same policy through Graphics', () => { const core = runtimeSource('reactor_core.js'); - assert.match(core, /this\._effekseer\.init\(efxGL\);\s*\n(?:\s*\/\/.*\n)*\s*this\.rearmEffekseerState\(\);\s*\n\s*this\._listenEffekseerStateResets\(\);/); + assert.match(core, /this\._effekseer\.init\(efxGL, this\._overlayEffekseerSettings\(\)\);\s*\n(?:\s*\/\/.*\n)*\s*this\.rearmEffekseerState\(\);\s*\n\s*this\._listenEffekseerStateResets\(\);/); assert.match(core, /Graphics\.settleEffekseerState = function\(\) \{\s*\n\s*if \(!this\._effekseerRestorePending \|\| !this\._effekseer\) return;/); assert.match(core, /window\.addEventListener\("focus", \(\) => this\.rearmEffekseerState\(\)\);/); assert.doesNotMatch(core, /this\._effekseer\.setRestorationOfStatesFlag\(true\);\s*\n\s*\}\s*\n\s*\} catch/, 'the flag is no longer pinned on at creation'); diff --git a/editor/tests/hdr-overlay.test.cjs b/editor/tests/hdr-overlay.test.cjs index a712b3b4..501c86fe 100644 --- a/editor/tests/hdr-overlay.test.cjs +++ b/editor/tests/hdr-overlay.test.cjs @@ -67,9 +67,10 @@ test('invalid metadata fails closed',async()=>{ const e=environment({...side,bloom:{...side.bloom,radiusScale:-1}}),s=e.sprite();await e.ready(s); assert.equal(e.api.canStart(s),false);assert.equal(s._playing,false); }); -test('3D scene effects do not enter the overlay',()=>{ - const e=environment(),s={_effectContext:{}};e.api.setup(s,{effectName:'Scene'}); - assert.equal(s._hdrEntry,undefined);assert.equal(e.fetches.length,0); +test('3D scene effects do not enter the overlay',async()=>{ + const e=environment(null),s={_effectContext:{},_animation:{effectName:'Scene'},_playing:true}; + e.api.setup(s,s._animation);await e.ready(s); + assert.equal(e.api.canStart(s),true);assert.equal(s._hdrActive,false);assert.equal(e.calls.length,0,'no HDR targets for it'); }); test('two same-grade HDR animations share one accumulation and grade pass',async()=>{ const e=environment(),a=e.sprite(),b=e.sprite();await e.ready(a); @@ -105,6 +106,31 @@ test('without a threshold every downsample is a plain average',async()=>{ assert.equal(e.calls.filter(c=>c[0]==='uniform1f'&&c[2]===0.15).length,0); assert.equal(e.calls.filter(c=>c[0]==='drawArrays').length,20); }); +test('a Unity bloom prefilter takes the setup pass with its clamp, threshold and knee',async()=>{ + const e=environment({...side,bloom:{...side.bloom,radiusScale:1,prefilter:{threshold:0.674,knee:0.464,clamp:0.8}}}),s=e.sprite();await e.ready(s); + e.api.canStart(s);e.api.render({},[s]); + for(const v of [0.674,0.464,0.8])assert.equal(e.calls.filter(c=>c[0]==='uniform1f'&&c[2]===v).length,1,'one '+v); + assert.equal(e.calls.filter(c=>c[0]==='uniform1f'&&c[2]===1).length,1,'the Unity switch set once'); + assert.equal(e.calls.filter(c=>c[0]==='drawArrays').length,21,'1 full-resolution setup, 7 downsamples, 12 blurs, 1 grade'); +}); +test('a caller that passes no prefilter (an older editor preview) still gets the sidecar\'s',async()=>{ + const e=environment(),pre={threshold:0.674,knee:0.464,clamp:0.8}; + const R=e.c.ReactorHdrRenderer.create(e.gl);assert.ok(R.ensure(128,72));R.begin(); + R.post({bloom:0.65,bloomScale:1},{...side,bloom:{...side.bloom,radiusScale:1,prefilter:pre}}); + for(const v of [0.674,0.464,0.8])assert.equal(e.calls.filter(c=>c[0]==='uniform1f'&&c[2]===v).length,1,'one '+v); +}); +test('a prefilter without a clamp uses Unity\'s default 65472',async()=>{ + const e=environment({...side,bloom:{...side.bloom,prefilter:{threshold:0.9,knee:0.45}}}),s=e.sprite();await e.ready(s); + e.api.canStart(s);e.api.render({},[s]); + assert.equal(e.calls.filter(c=>c[0]==='uniform1f'&&c[2]===65472).length,1); + assert.equal(e.calls.filter(c=>c[0]==='drawArrays').length,20,'7 downsamples (1 setup), 12 blurs, 1 grade'); +}); +test('an invalid bloom prefilter fails closed',async()=>{ + for(const prefilter of [{threshold:'0.9',knee:0.45},{threshold:0.9,knee:-1},{threshold:0.9,knee:0.45,clamp:0},null]){ + const e=environment({...side,bloom:{...side.bloom,prefilter}}),s=e.sprite();await e.ready(s); + assert.equal(e.api.canStart(s),false,JSON.stringify(prefilter));assert.equal(s._playing,false); + } +}); test('a non-numeric bloom threshold fails closed',async()=>{ const e=environment({...side,bloom:{...side.bloom,threshold:'0.15'}}),s=e.sprite();await e.ready(s); assert.equal(e.api.canStart(s),false);assert.equal(s._playing,false); @@ -193,3 +219,155 @@ test('the composite lands in the framebuffer the caller names',()=>{ e.calls.length=0;R.post({bloom:0,bloomScale:1},side); assert.equal(e.calls.filter(c=>c[0]==='bindFramebuffer').at(-1)[2],null,'unnamed: the default framebuffer, as before'); }); + +test('companion validation refuses invalid fields and resolved aliases',()=>{ + const e=environment(); + for(const companion of ['', ' ',null,3,'Body.efkefc','Twin'])assert.throws(()=>e.c.ReactorHdrRenderer.valid({...side,companion})); + for(const companionOccludes of [1,'true',null])assert.throws(()=>e.c.ReactorHdrRenderer.valid({...side,companionOccludes})); + for(const companion of ['Effect-hdr','Nested/Effect-hdr','Nested/Twin'])assert.throws(()=>e.c.ReactorHdrRenderer.valid({...side,companion},'Nested/Effect-hdr')); +}); +test('companion waits for metadata and loading and is stopped on fallback',async()=>{ + const e=environment({...side,companion:'Body'}),s=e.sprite();await e.ready(s); + const entry={ready:false,sidecar:null};e.api.cache.set('Nested/Body',entry); + const effect={isLoaded:false};e.c.EffectManager.load=n=>{e.loads.push(n);return effect;}; + assert.equal(e.api.canStart(s),false);entry.ready=true;assert.equal(e.api.canStart(s),false); + effect.isLoaded=true;assert.equal(e.api.canStart(s),true); + const h={stop(){this.stopped=true;}};s._companionHandle=h;e.api.scene.fallBack(s); + assert.equal(h.stopped,true);assert.equal(s._companionEffect,null);assert.equal(s._hdrActive,false); +}); +test('missing and HDR companions fall back; the twin loads no companion',async()=>{ + for(const failure of ['missing','hdr']){ + const e=environment({...side,companion:'Body'}),s=e.sprite();await e.ready(s); + e.c.Utils={localAssetExists:url=>failure==='missing'&&url.endsWith('Body.efkefc')?false:null}; + e.api.cache.set('Nested/Body',{ready:true,sidecar:failure==='hdr'?side:null}); + e.api.canStart(s);assert.equal(s._hdrActive,false);assert.equal(s._effect,'Nested/Twin');assert.equal(e.warnings.length,1); + } + const e=environment({...side,companion:'Body'},false),s=e.sprite();await e.ready(s);e.api.canStart(s); + assert.deepEqual(e.loads,['Nested/Twin']); +}); +test('companion prepass precedes HDR light and restores colour writes',async()=>{ + const e=environment({...side,companion:'Body'}),s=e.sprite();await e.ready(s); + e.api.cache.set('Nested/Body',{ready:true,sidecar:null});e.api.canStart(s); + const h=s._companionHandle={name:'body',exists:true,stop(){this.stopped=true;}}; + e.api.render({},[s]);assert.deepEqual(e.drawn,['body',s._handle.name]); + assert.ok(e.calls.some(c=>c[0]==='depthMask'&&c[1]===true)); + const masks=e.calls.filter(c=>c[0]==='colorMask'); const off=masks.findIndex(c=>c[1]===false); assert.ok(off>=0); assert.deepEqual(masks[off+1],['colorMask',true,true,true,true]); + e.api.release(s);assert.equal(h.stopped,true);assert.equal(s._companionHandle,null); +}); + +test('one fresh cast seed reaches both handles before transforms; either handle holds the animation open',()=>{ + const text=fs.readFileSync(path.join(runtime,'reactor_sprites.js'),'utf8'); + const extract=name=>{const a=text.indexOf('Sprite_Animation.prototype.'+name+' =');return text.slice(a,text.indexOf('\n};',a)+4);}; + const calls=[];let i=0; + const handles=[0,1].map(n=>({exists:true,setRandomSeed(seed){calls.push(['seed',n,seed]);},setLocation(...v){calls.push(['location',n,...v]);},setRotation(...v){calls.push(['rotation',n,...v]);},setScale(...v){calls.push(['scale',n,...v]);},setSpeed(...v){calls.push(['speed',n,...v]);}})); + const c={Sprite_Animation:function(){},Sprite:{prototype:{update(){}}},Graphics:{effekseer:{play(){calls.push(['play',i]);return handles[i++];}}},Math}; + for(const name of ['update','updateEffectGeometry','forEachEffectHandle','setRotation','checkEnd'])vm.runInNewContext(extract(name),c); + const s=new c.Sprite_Animation();Object.assign(s,{_playing:true,_effect:{isLoaded:true},_companionEffect:{isLoaded:true},_hdrActive:true,_animation:{scale:125,speed:80,rotation:{x:10,y:20,z:30}},canStart:()=>true,reactor3DScale:()=>1,updateMain(){},updateFlash(){}}); + s.update();assert.deepEqual(calls.slice(0,4).map(x=>x[0]),['play','play','seed','seed']);assert.equal(calls[2][2],calls[3][2]); + for(const method of ['location','rotation','scale','speed']){const pair=calls.filter(x=>x[0]===method);assert.equal(pair.length,2);assert.deepEqual(pair[0].slice(2),pair[1].slice(2));} + s._frameIndex=20;s._maxTimingFrames=0;s._flashDuration=0;handles[0].exists=false;s.checkEnd();assert.equal(s._playing,true);handles[1].exists=false;s.checkEnd();assert.equal(s._playing,false); +}); + +test('all adapter termination paths stop and drop the companion',async()=>{ + for(const action of ['release','lost','sceneLost','fallback','failedRender']){ + const e=environment({...side,companion:'Body'}),s=e.sprite();await e.ready(s);e.api.cache.set('Nested/Body',{ready:true,sidecar:null});e.api.canStart(s); + const h=s._companionHandle={exists:true,name:'body',stop(){this.stopped=true;}}; + if(action==='release')e.api.release(s); + if(action==='lost')e.api.contextLost(); + if(action==='sceneLost'){s._effekseerInScene=true;e.api.scene.lost();} + if(action==='fallback')e.api.scene.fallBack(s); + if(action==='failedRender'){e.c.Graphics.effekseer.drawHandle=()=>{throw Error('draw failure');};e.api.render({},[s]);} + assert.equal(h.stopped,true,action);assert.equal(s._companionHandle,null,action);assert.equal(s._companionEffect,null,action); + } +}); + +test('a companion load callback selects the twin without raising a global load error',async()=>{ + const e=environment({...side,companion:'Body'}),s=e.sprite();await e.ready(s);e.api.cache.set('Nested/Body',{ready:true,sidecar:null}); + let failure; e.c.EffectManager.load=(name,onError)=>{if(onError){failure=onError;return {isLoaded:false};}return name;}; + assert.equal(e.api.canStart(s),false);failure('resource failed','effects/Nested/Body.efkefc'); + assert.equal(e.api.canStart(s),true);assert.equal(s._hdrActive,false);assert.equal(s._effect,'Nested/Twin'); +}); +test('EffectManager soft failures are local; ordinary failures retain their queue',()=>{ + const text=fs.readFileSync(path.join(runtime,'reactor_managers.js'),'utf8'); + const take=name=>{const a=text.indexOf('EffectManager.'+name+' =');return text.slice(a,text.indexOf('\n};',a)+4);}; + let callback,reported=0; + const c={EffectManager:{_cache:{},_softLoadErrors:new Map(),onLoad(){},onError(){reported++;},makeUrl:n=>'effects/'+n+'.efkefc'},Graphics:{effekseer:{loadEffect(url,scale,loaded,failed){callback=failed;return {isLoaded:false};}}}}; + for(const name of ['load','startLoading'])vm.runInNewContext(take(name),c); + let soft=0;c.EffectManager.load('Body',()=>soft++);callback('bad','body');assert.equal(soft,1);assert.equal(reported,0);assert.equal(Object.keys(c.EffectManager._cache).length,0); + c.EffectManager.load('Ordinary');callback('bad','ordinary');assert.equal(reported,1); +}); + +test('bloom.intensityKeys play as straight lines between keys, held before the first and after the last',()=>{ + const e=environment(),f=e.c.ReactorHdrRenderer.bloomIntensity,b={intensity:1,intensityKeys:[[0,1.374],[66.4,2],[147.3,0.122]]}; + assert.equal(f(b,-5),1.374);assert.equal(f(b,0),1.374);assert.equal(f(b,66.4),2);assert.equal(f(b,400),0.122); + assert.ok(Math.abs(f(b,33.2)-1.687)<1e-9);assert.ok(Math.abs(f(b,106.85)-1.061)<1e-9); + assert.equal(f({intensity:0.675},50),0.675,'no keys: intensity');assert.equal(f(b,undefined),1.374,'no frame: frame 0'); +}); +test('a keyed intensity draws with the value at the sprite\'s effect frame',async()=>{ + const e=environment({...side,bloom:{...side.bloom,intensityKeys:[[0,2],[60,0.5]]}}),s=e.sprite();await e.ready(s); + e.api.canStart(s);s._effectFrame=30;e.api.render({},[s]); + const w=e.calls.filter(c=>c[0]==='uniform1fv').at(-1)[2]; + assert.deepEqual(Array.from(w).map(x=>+x.toFixed(9)),side.bloom.tints.map(t=>+(t*1.25).toFixed(9))); +}); +test('same-grade animations at different keyed intensities bloom in separate passes; equal ones share one',async()=>{ + const keys=[[0,2],[60,0.5]],e=environment({...side,bloom:{...side.bloom,intensityKeys:keys}}),a=e.sprite(),b=e.sprite();await e.ready(a); + e.api.canStart(a);e.api.canStart(b);a._effectFrame=10;b._effectFrame=10;e.api.render({},[a,b]);assert.equal(e.api.stats.groups,1); + b._effectFrame=40;e.api.render({},[a,b]);assert.equal(e.api.stats.groups,3); + assert.equal(e.api.scene.intensity(a),e.c.ReactorHdrRenderer.bloomIntensity({intensityKeys:keys},10)); +}); +const twoGrades={...side,gradeB:'vec3 tmOut = hdr * 0.5;',gradeKeys:[[10,0],[30,1]]}; +test('gradeKeys weigh the second grade on the effect clock, clamped and held at the ends',()=>{ + const f=environment().c.ReactorHdrRenderer.gradeMix; + assert.equal(f(twoGrades,0),0);assert.equal(f(twoGrades,20),0.5);assert.equal(f(twoGrades,90),1);assert.equal(f(side,20),0); +}); +test('gradeB compiles both grades in their own functions and leaves a one-grade program as it was',()=>{ + const e=environment(),R=e.c.ReactorHdrRenderer.create(e.c.Graphics._effekseerGL); + R.gradeProgram(twoGrades.grade,twoGrades.gradeB);R.gradeProgram(side.grade); + const fs=e.calls.filter(c=>c[0]==='shaderSource'&&/uHdr/.test(c[2])).map(c=>c[2]); + assert.match(fs[0],/vec3 rr_gradeA\(vec3 hdr\)\{\nvec3 tmOut = hdr \/ \(hdr \+ vec3\(1\.0\)\);\nreturn tmOut;/); + assert.match(fs[0],/vec3 rr_gradeB\(vec3 hdr\)\{\nvec3 tmOut = hdr \* 0\.5;\nreturn tmOut;/); + assert.match(fs[0],/mix\(rr_gradeA\(hdr\), rr_gradeB\(hdr\), uGradeMix\)/); + assert.doesNotMatch(fs[1],/uGradeMix|rr_grade/); +}); +test('invalid gradeB or gradeKeys fail closed',async()=>{ + for(const bad of [{gradeB:'vec3 x;',gradeKeys:[[0,1]]},{gradeB:twoGrades.gradeB},{gradeB:twoGrades.gradeB,gradeKeys:[]},{gradeB:twoGrades.gradeB,gradeKeys:[[0,2]]},{gradeKeys:[[0,1]]}]){ + const e=environment({...side,...bad}),s=e.sprite();await e.ready(s); + assert.equal(e.api.canStart(s),false,JSON.stringify(bad)); + } +}); +test('invalid bloom.intensityKeys fail closed',async()=>{ + for(const intensityKeys of [[],[[0,1],[0,2]],[[5,1],[2,2]],[[0,-1]],[[0,'1']],[[0,1,2]],{0:1},null]){ + const e=environment({...side,bloom:{...side.bloom,intensityKeys}}),s=e.sprite();await e.ready(s); + assert.equal(e.api.canStart(s),false,JSON.stringify(intensityKeys));assert.equal(s._playing,false); + } +}); +test('the effect clock steps with each Effekseer update, at the animation\'s speed, and slow motion scales it',()=>{ + const sprites=fs.readFileSync(path.join(runtime,'reactor_sprites.js'),'utf8'); + assert.ok(sprites.includes('if (this._started) this._effectFrame += (globalThis.SceneManager?._effekseerStep ?? 1) * this._animation.speed / 100;')); + assert.ok(fs.readFileSync(path.join(runtime,'reactor_fight_camera.js'),'utf8').includes('this._effekseerStep = (this._effekseerStep || 0) * scale;')); + const managers=fs.readFileSync(path.join(runtime,'reactor_managers.js'),'utf8'); + const a=managers.indexOf('SceneManager.updateEffekseer = function'),body=managers.slice(a,managers.indexOf('\n};',a)+4); + const c={Graphics:{effekseer:{update(){}}},SceneManager:{isGameActive:()=>true}}; + vm.runInNewContext(body,c);c.SceneManager.updateEffekseer();assert.equal(c.SceneManager._effekseerStep,1); + c.SceneManager.isGameActive=()=>false;c.SceneManager.updateEffekseer();assert.equal(c.SceneManager._effekseerStep,0,'a paused game does not step effects'); +}); +test('an effect the 3D scene draws reads its sidecar and plays its twin, from the context it plays in',async()=>{ + const entry={context:{}},gpu=[]; + const anchored=e=>{const s=e.sprite();delete s._hdrEntry;s._effectContext=entry;e.api.setup(s,s._animation);return s;}; + const stub=e=>{e.c.Reactor3D={GpuEffects:{load:(x,n)=>{gpu.push([x===entry,n]);return 'gpu:'+n;}}};}; + // A GPU effect on a model. + const e=environment();stub(e);const s=anchored(e);await e.ready(s); + assert.equal(e.api.canStart(s),true);assert.equal(s._hdrActive,false);assert.equal(s._effect,'gpu:Nested/Twin'); + assert.deepEqual(gpu,[[true,'Nested/Twin']]);assert.deepEqual(e.loads,[],'not the overlay\'s context');assert.equal(e.calls.length,0,'no HDR targets for it'); + // Drawn by the 3D scene through the overlay's context: float targets would otherwise select HDR for a handle nothing grades. + const o=environment(),t=o.sprite();t._reactorInScene=true;await o.ready(t); + assert.equal(o.api.canStart(t),true);assert.equal(t._hdrActive,false);assert.equal(t._effect,'Nested/Twin');assert.deepEqual(o.loads,['Nested/Twin']); +}); +test('a -hdr effect on a model without a sidecar is refused and says so; an ordinary one is untouched',async()=>{ + const entry={context:{}},e=environment(null); + e.c.Reactor3D={GpuEffects:{load:()=>{throw Error('no load');}}}; + const s=e.sprite();delete s._hdrEntry;s._effectContext=entry;e.api.setup(s,s._animation);await e.ready(s); + assert.equal(e.api.canStart(s),false);assert.equal(s._playing,false);assert.equal(s._hdrRefused,true); + const p=e.sprite('Plain');delete p._hdrEntry;p._effectContext=entry;p._effect='gpu:Plain';e.api.setup(p,p._animation);await e.ready(p); + assert.equal(e.api.canStart(p),true);assert.equal(p._effect,'gpu:Plain');assert.equal(p._hdrRefused,undefined); +}); diff --git a/editor/tests/hdr-preview-render.test.cjs b/editor/tests/hdr-preview-render.test.cjs index 144283b9..6fd29e1b 100644 --- a/editor/tests/hdr-preview-render.test.cjs +++ b/editor/tests/hdr-preview-render.test.cjs @@ -70,7 +70,7 @@ function editor() { const context = { console: { info() {}, warn() {}, error() {} }, require: name => ({ fs, path })[name], - process, Buffer, ArrayBuffer, Uint8Array, Float32Array, performance, setTimeout: () => 0, clearTimeout() {}, + queueMicrotask, process, Buffer, ArrayBuffer, Uint8Array, Float32Array, performance, setTimeout: () => 0, clearTimeout() {}, location: { pathname: path.join(editorRoot, 'index.html') } }; context.window = context; @@ -186,6 +186,25 @@ test('a frame draws into the light buffer, then composites over the canvas where } finally { p.done(); } }); +test('a keyed bloom intensity follows the frame the preview says', () => { + const p = project(); + try { + const w = editor(); + const { gl, calls } = fakeGl(); + const choice = w.RRHdrPreview.choose(gl, p.file('Fire-hdr'), 1600, 900); + choice.sidecar = { ...choice.sidecar, bloom: { ...choice.sidecar.bloom, intensityKeys: [[0, 2], [60, 0.5]] } }; + const weights = frame => { + calls.length = 0; + w.RRHdrPreview.draw(gl, choice, { width: 1600, height: 900, frame }, () => {}); + return Array.from(calls.findLast(c => c[0] === 'uniform1fv')[2]); + }; + const tints = choice.sidecar.bloom.tints, close = (a, b) => a.every((x, i) => Math.abs(x - b[i]) < 1e-9); + assert.ok(close(weights(30), tints.map(t => t * 1.25)), 'halfway between the keys'); + assert.ok(close(weights(undefined), tints.map(t => t * 2)), 'no frame: frame 0'); + assert.ok(close(weights(120), tints.map(t => t * 0.5)), 'held after the last key'); + } finally { p.done(); } +}); + test('bloom radii follow the game screen\'s width as the preview draws it, not the canvas\'s', () => { const p = project(); try { @@ -301,3 +320,17 @@ test('every animation preview loads through RRHdrPreview, which index.html loads assert.match(source, /RRHdrPreview\.release\(/, `${file} frees its HDR targets with its context`); } }); + +test('shared preview pairing loads both, seeds and transforms both, and draws body before light',async()=>{ + const p=project();try{ + fs.writeFileSync(p.file('Body'),'BODY');fs.writeFileSync(p.file('Fire-hdr').replace('.efkefc','.hdr.json'),JSON.stringify({...sidecar,companion:'Body'})); + const w=editor(),{gl}=fakeGl(),calls=[];let n=0; + w.RR_loadEffekseerEffectFromFile=(ctx,file,scale,done)=>{const effect={isLoaded:true,file};queueMicrotask(()=>done?.());return effect;}; + const ctx={play(effect){const id=n++;return {exists:true,id,setRandomSeed(seed){calls.push(['seed',id,seed]);},setScale(...v){calls.push(['scale',id,...v]);},stop(){this.exists=false;calls.push(['stop',id]);}};},drawHandle(h){calls.push(['draw',h.id]);},releaseEffect(){}}; + let loaded=0;const effect=w.RRHdrPreview.load(ctx,gl,p.file('Fire-hdr'),1,()=>loaded++,null,view);await new Promise(r=>setImmediate(r));assert.equal(loaded,1); + const handle=ctx.play(effect);assert.equal(calls[0][2],calls[1][2]);handle.setScale(2,2,2);assert.equal(calls.filter(x=>x[0]==='scale').length,2); + w.RRHdrPreview.draw(gl,effect.rrHdr,view,()=>ctx.drawHandle(handle));assert.deepEqual(calls.filter(x=>x[0]==='draw').map(x=>x[1]),[1,1,0]); + handle.stop();assert.equal(calls.filter(x=>x[0]==='stop').length,2); + const off=w.RRHdrPreview.load(ctx,gl,p.file('Fire-hdr'),1,null,null,view,{off:true});assert.equal(off.rrHdr,undefined);assert.equal(off.rrHdrTwin.twinName,'Fire-ldr'); + }finally{p.done();} +}); diff --git a/editor/tests/hdr-preview-twin.test.cjs b/editor/tests/hdr-preview-twin.test.cjs index 9c0b0af9..333e2951 100644 --- a/editor/tests/hdr-preview-twin.test.cjs +++ b/editor/tests/hdr-preview-twin.test.cjs @@ -130,6 +130,15 @@ test('the editor accepts exactly the sidecars the runtime accepts', async () => { ...sidecar, bloom: { ...sidecar.bloom, threshold: 0.15 } }, { ...sidecar, bloom: { ...sidecar.bloom, threshold: -0.8 } }, { ...sidecar, bloom: { ...sidecar.bloom, threshold: '0.15' } }, + { ...sidecar, bloom: { ...sidecar.bloom, intensityKeys: [[0, 1.374], [66.4, 2], [147.3, 0.122]] } }, + { ...sidecar, bloom: { ...sidecar.bloom, intensityKeys: [[10, 0]] } }, + { ...sidecar, bloom: { ...sidecar.bloom, intensityKeys: [] } }, + { ...sidecar, bloom: { ...sidecar.bloom, intensityKeys: [[0, 1], [0, 2]] } }, + { ...sidecar, bloom: { ...sidecar.bloom, intensityKeys: [[5, 1], [2, 2]] } }, + { ...sidecar, bloom: { ...sidecar.bloom, intensityKeys: [[0, -1]] } }, + { ...sidecar, bloom: { ...sidecar.bloom, intensityKeys: [[0, '1']] } }, + { ...sidecar, bloom: { ...sidecar.bloom, intensityKeys: [[0, 1, 2]] } }, + { ...sidecar, bloom: { ...sidecar.bloom, intensityKeys: { 0: 1 } } }, { ...sidecar, bloom: undefined }, {} ]; diff --git a/editor/tests/item-capacity-chests.test.cjs b/editor/tests/item-capacity-chests.test.cjs new file mode 100644 index 00000000..9761ca03 --- /dev/null +++ b/editor/tests/item-capacity-chests.test.cjs @@ -0,0 +1,272 @@ +'use strict'; +// Can Receive (Conditional Branch › Reactor) and the Treasure quick event's +// inventory-space check. The condition is a Script branch the codec tags, so it +// reopens as itself and reads as a sentence in the list; a chest built with the +// check runs through the game's own Game_Interpreter and Game_Party here, and a +// full party gets the failure text and nothing else, so the chest stays closed. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +const editorRoot = path.resolve(__dirname, '..'); +const repoRoot = path.resolve(editorRoot, '..'); +const ReactorEventCommandCodec = require('../src/event/commands/ReactorEventCommandCodec.js'); +const ConditionalBranchEditor = require('../src/event/commands/ConditionalBranchEditor.js'); +const EventCommandList = require('../src/event/EventCommandList.js'); +const plain = value => JSON.parse(JSON.stringify(value)); + +const managerSource = fs.readFileSync(path.join(editorRoot, 'src', 'EventManager.js'), 'utf8'); +const EventManager = vm.runInNewContext(`${managerSource}\nEventManager;`, { + console: { log() {}, warn() {}, error() {} }, + ConditionalBranchEditor +}); + +function manager() { + const instance = Object.create(EventManager.prototype); + instance.currentMap = { width: 20, height: 15, events: [null] }; + instance.getNextEventId = EventManager.prototype.getNextEventId; + return instance; +} + +function chest(config) { + return manager().buildQuickEvent('treasure', 1, 1, { characterName: '!Chest', ...config }); +} + +const FAILURE = 'You cannot carry all of this item. Make room and try again.'; + +// ---- The game: the shipped interpreter and party, with a stub map and message -------- + +function world() { + const context = { console, Math, JSON }; + vm.createContext(context); + vm.runInContext('Number.prototype.clamp = function(a, b) { return Math.min(Math.max(this, a), b); };', context); + for (const file of ['reactor_objects_interpreter.js', 'reactor_objects_battlers.js']) { + vm.runInContext(fs.readFileSync(path.join(repoRoot, 'runtime', file), 'utf8'), context, { filename: file }); + } + const log = { messages: [], routes: [], selfSwitches: {} }; + vm.runInContext(` + var $dataSystem = {}; + var $dataItems = [null, { id: 1, name: 'Potion', note: '' }, { id: 2, name: 'Ether', note: '' }]; + var $dataWeapons = [null, { id: 1, name: 'Sword', note: '' }]; + var $dataArmors = [null, { id: 1, name: 'Shield', note: '' }]; + var DataManager = { + isItem: item => !!item && $dataItems.includes(item), + isWeapon: item => !!item && $dataWeapons.includes(item), + isArmor: item => !!item && $dataArmors.includes(item) + }; + var ImageManager = { loadFace() {}, loadPicture() {} }; + var Game_Followers = { placeOfCharacterId: () => 0 }; + var $gameSystem = {}; + var $gameParty = Object.create(Game_Party.prototype); + $gameParty.initAllItems(); + $gameParty.inBattle = () => false; + `, context); + context.$gameMap = { + mapId: () => 1, refreshIfNeeded() {}, requestRefresh() {}, + event: () => ({ forceMoveRoute: route => log.routes.push(route), isMoveRouteForcing: () => false }) + }; + context.$gameMessage = { + isBusy: () => false, setFaceImage() {}, setFacePlay() {}, setBackground() {}, setPositionType() {}, setSpeakerName() {}, + add: text => log.messages.push(text) + }; + context.$gameSelfSwitches = { setValue: (key, value) => { log.selfSwitches[key.join(',')] = value; } }; + const run = list => { + log.messages.length = 0; + log.routes.length = 0; + const interpreter = new context.Game_Interpreter(); + interpreter.setup(list, 7); + for (let steps = 0; interpreter._list; steps++) { + assert.ok(steps < 500, 'the event list ends'); + interpreter.executeCommand(); + } + }; + const party = context.$gameParty; + const table = { item: '$dataItems', weapon: '$dataWeapons', armor: '$dataArmors' }; + const entry = (type, id) => vm.runInContext(`${table[type]}[${id}]`, context); + const count = (type, id) => party.numItems(entry(type, id)); + const give = (type, id, amount) => party.gainItem(entry(type, id), amount); + const claimed = () => log.selfSwitches['1,7,A'] === true; + return { context, log, run, party, entry, count, give, claimed }; +} + +// ---- The Conditional Branch editor ----------------------------------------------------- + +test('Can Receive sits on the Reactor tab and saves as a tagged Script condition that reopens as itself', () => { + const reactorTab = ConditionalBranchEditor.TABS.find(tab => tab.label === 'Reactor'); + assert.ok(reactorTab.types.includes(18)); + for (const [type, table] of [['item', '$dataItems'], ['weapon', '$dataWeapons'], ['armor', '$dataArmors']]) { + const editor = new ConditionalBranchEditor(null, null); + Object.assign(editor, { conditionType: 18, capacityType: type, capacityItemId: 4, capacityAmount: 6 }); + const command = editor.buildCommands()[0]; + assert.equal(command.code, 111); + assert.equal(command.parameters.length, 2); + assert.equal(command.parameters[0], 12, 'a Script condition RPG Maker and the runtime both run'); + const parsed = ReactorEventCommandCodec.parseCommand(command, 'itemCapacityCondition'); + assert.deepEqual(plain(parsed.data), { type, id: 4, amount: 6 }); + assert.ok(parsed.body.includes(`${table}[4]`), type); + + const reopened = new ConditionalBranchEditor(null, null); + reopened.parseCommand(command); + assert.equal(reopened.conditionType, 18); + assert.deepEqual([reopened.capacityType, reopened.capacityItemId, reopened.capacityAmount], [type, 4, 6]); + assert.deepEqual(reopened.buildCommands()[0], command); + } +}); + +test('an edited or malformed Can Receive script reopens as the author\'s own Script', () => { + const editor = new ConditionalBranchEditor(null, null); + Object.assign(editor, { conditionType: 18, capacityType: 'item', capacityItemId: 1, capacityAmount: 2 }); + const edited = editor.buildCommands()[0]; + edited.parameters[1] = edited.parameters[1].replace('+2<=', '+2<'); + const reopened = new ConditionalBranchEditor(null, null); + reopened.parseCommand(edited); + assert.equal(reopened.conditionType, 12); + assert.equal(reopened.scriptText, edited.parameters[1]); + assert.deepEqual(reopened.buildCommands()[0].parameters, edited.parameters, 'saved untouched, byte for byte'); + + for (const data of [{ type: 'gold', id: 1, amount: 1 }, { type: 'item', id: 1, amount: 0 }, + { type: 'item', id: 1.5, amount: 1 }, { type: 'item', id: 1, amount: 1, extra: true }]) { + const text = ReactorEventCommandCodec.createText('itemCapacityCondition', data, 'true'); + const other = new ConditionalBranchEditor(null, null); + other.parseCommand({ code: 111, indent: 0, parameters: [12, text] }); + assert.equal(other.conditionType, 12, JSON.stringify(data)); + } + assert.throws(() => ConditionalBranchEditor.createItemCapacityText({ type: 'item', id: 1, amount: 0 })); +}); + +test('the event list reads Can Receive as a sentence, and an edited one as a Script', () => { + const list = Object.create(EventCommandList.prototype); + list.eventEditor = { databaseManager: { + getItem: id => [null, { id: 1, name: 'Potion' }][id], + getWeapon: () => null, + getArmor: id => [null, { id: 1, name: 'Shield' }][id] + } }; + const describe = data => list.getCommandInfo({ code: 111, indent: 0, parameters: [12, + ConditionalBranchEditor.createItemCapacityText(data)] }, { list: [] }, 0).description; + assert.equal(describe({ type: 'item', id: 1, amount: 5 }), 'Can Receive Item: #1 Potion × 5'); + assert.equal(describe({ type: 'armor', id: 1, amount: 1 }), 'Can Receive Armor: #1 Shield × 1'); + assert.equal(describe({ type: 'weapon', id: 9, amount: 2 }), 'Can Receive Weapon: Weapon #9 (Missing) × 2'); + + const text = ConditionalBranchEditor.createItemCapacityText({ type: 'item', id: 1, amount: 5 }) + ' || true'; + const edited = list.getCommandInfo({ code: 111, indent: 0, parameters: [12, text] }, { list: [] }, 0).description; + assert.match(edited, /^Script: /); +}); + +// ---- The Treasure quick event ---------------------------------------------------------- + +test('item, weapon and armor chests wrap the whole claim in Can Receive, with the failure text in Else', () => { + for (const [rewardKind, code] of [['item', 126], ['weapon', 127], ['armor', 128]]) { + const event = chest({ rewardKind, rewardId: 3, amount: 4, message: 'Found it.' }); + const list = event.pages[0].list; + assert.deepEqual(plain(list.map(command => [command.code, command.indent])), [ + [111, 0], [205, 1], [505, 1], [505, 1], [505, 1], [505, 1], [505, 1], [505, 1], [505, 1], + [code, 1], [101, 1], [401, 1], [123, 1], [0, 1], + [411, 0], [101, 1], [401, 1], [0, 1], [412, 0], [0, 0] + ], rewardKind); + const parsed = ReactorEventCommandCodec.parseCommand(list[0], 'itemCapacityCondition'); + assert.deepEqual(plain(parsed.data), { type: rewardKind, id: 3, amount: 4 }); + const texts = list.filter(command => command.code === 401).map(command => command.parameters[0]); + assert.deepEqual(plain(texts), ['Found it.', FAILURE], 'the success text, then the default failure text'); + assert.deepEqual(plain(list.find(command => command.code === 123).parameters), ['A', 0]); + + const reopened = new ConditionalBranchEditor(null, null); + reopened.parseCommand(list[0]); + assert.equal(reopened.conditionType, 18, 'the chest\'s branch edits in the Conditional Branch dialog'); + } + const custom = chest({ rewardKind: 'item', rewardId: 1, amount: 1, failMessage: 'Too heavy.' }); + assert.equal(custom.pages[0].list.filter(command => command.code === 401)[1].parameters[0], 'Too heavy.'); +}); + +test('gold chests, and chests with the check turned off, are built exactly as before', () => { + const legacy = list => plain(list.map(command => [command.code, command.indent])); + const route = [[205, 0], [505, 0], [505, 0], [505, 0], [505, 0], [505, 0], [505, 0], [505, 0]]; + const gold = chest({ rewardKind: 'gold', amount: 50, checkSpace: true }); + assert.deepEqual(legacy(gold.pages[0].list), [...route, [125, 0], [101, 0], [401, 0], [123, 0], [0, 0]]); + const unchecked = chest({ rewardKind: 'weapon', rewardId: 2, amount: 1, checkSpace: false }); + assert.deepEqual(legacy(unchecked.pages[0].list), [...route, [127, 0], [101, 0], [401, 0], [123, 0], [0, 0]]); + assert.equal(gold.pages[1].conditions.selfSwitchCh, 'A'); +}); + +test('a fractional amount or id becomes a whole number before it reaches the condition', () => { + const event = chest({ rewardKind: 'item', rewardId: 2.7, amount: 3.9 }); + const parsed = ReactorEventCommandCodec.parseCommand(event.pages[0].list[0], 'itemCapacityCondition'); + assert.deepEqual(plain(parsed.data), { type: 'item', id: 2, amount: 3 }); + assert.deepEqual(plain(event.pages[0].list.find(command => command.code === 126).parameters), [2, 0, 0, 3]); +}); + +// ---- Running a generated chest in the game --------------------------------------------- + +test('the whole stack must fit: empty, exact fit, short by one, full and over the cap', () => { + for (const type of ['item', 'weapon', 'armor']) { + const list = chest({ rewardKind: type, rewardId: 1, amount: 5 }).pages[0].list; + for (const [held, opens] of [[0, true], [94, true], [95, false], [99, false], [120, false]]) { + const game = world(); + if (held) game.party[{ item: '_items', weapon: '_weapons', armor: '_armors' }[type]][1] = held; + game.run(list); + const label = `${type}, holding ${held}`; + assert.equal(game.count(type, 1), opens ? held + 5 : held, label); + assert.equal(game.claimed(), opens, label); + assert.equal(game.log.routes.length, opens ? 1 : 0, `${label}: the lid opens only on success`); + assert.deepEqual(game.log.messages, [opens ? 'You found treasure!' : FAILURE], label); + } + } +}); + +test('a blocked chest opens once room is made, and grants the reward exactly once', () => { + const list = chest({ rewardKind: 'item', rewardId: 1, amount: 5 }).pages[0].list; + const game = world(); + game.give('item', 1, 97); + game.run(list); + assert.equal(game.count('item', 1), 97); + assert.equal(game.claimed(), false); + game.give('item', 1, -3); + game.run(list); + assert.equal(game.count('item', 1), 99); + assert.equal(game.claimed(), true); +}); + +test('the cap is asked of the live party each time: a plugin\'s , zero and no limit at all', () => { + const game = world(); + const reactorMax = game.party.maxItems; + // VisuStella Items & Equips Core's rule: on the entry, else its default. + game.party.maxItems = item => (//i.exec(item.note) ? Number(RegExp.$1) : 99); + const ether = amount => chest({ rewardKind: 'item', rewardId: 2, amount }).pages[0].list; + game.run(ether(4)); + assert.equal(game.count('item', 2), 0, ' holds back a stack of 4'); + game.run(ether(3)); + assert.equal(game.count('item', 2), 3, 'and lets a stack of 3 through'); + + game.party.maxItems = () => 0; + game.run(chest({ rewardKind: 'weapon', rewardId: 1, amount: 1 }).pages[0].list); + assert.equal(game.count('weapon', 1), 0, 'a cap of zero takes nothing'); + + game.party.maxItems = () => Infinity; + game.party._armors[1] = 1e6; + game.run(chest({ rewardKind: 'armor', rewardId: 1, amount: 9 }).pages[0].list); + assert.equal(game.count('armor', 1), 1e6 + 9, 'no limit, no block'); + + game.party.maxItems = reactorMax; + game.context.$dataSystem.rrHigherLimits = true; + game.party._items[1] = 500; + game.run(chest({ rewardKind: 'item', rewardId: 1, amount: 5 }).pages[0].list); + assert.equal(game.count('item', 1), 505, 'Reactor\'s higher limits (9999) apply when the project turns them on'); +}); + +test('a deleted database entry fails the check quietly and gives nothing', () => { + const game = world(); + game.run(chest({ rewardKind: 'item', rewardId: 42, amount: 1 }).pages[0].list); + assert.equal(game.claimed(), false); + assert.deepEqual(game.log.messages, [FAILURE]); + assert.deepEqual(plain(game.party._items), {}); +}); + +test('a gold chest pays out as it always has', () => { + const game = world(); + game.context.$gameParty._gold = 0; + game.context.$gameParty.maxGold = () => 99999999; + game.run(chest({ rewardKind: 'gold', amount: 50 }).pages[0].list); + assert.equal(game.context.$gameParty._gold, 50); + assert.equal(game.claimed(), true); +}); diff --git a/editor/tests/model-effects.test.cjs b/editor/tests/model-effects.test.cjs index 51c66c8f..ce18da13 100644 --- a/editor/tests/model-effects.test.cjs +++ b/editor/tests/model-effects.test.cjs @@ -652,3 +652,20 @@ test('a placed prop plays several animations in order, loops the list, and fires assert.ok(Math.abs(grown.radius - 15) < 1e-9, 'five times the size, five times the reach (' + grown.radius + ')'); assert.ok(Math.abs(grown.width - 0.5) < 1e-9, 'and the width'); }); + +test('an anchored effect the game refuses stops after one try instead of respawning every frame', () => { + const spawned = []; + const fake = Object.create(Reactor3D); + fake.spawnAnchoredAnimation = effect => spawned.push(effect.name); + const entry = (name, sprite) => ({ effect: { name, loop: true }, sprite: Object.assign({ parent: null }, sprite), standIn: { parent: null }, loop: true }); + const holder = { object: {}, anchored: [entry('bad', { _hdrRefused: true }), entry('good', {})] }; + fake.updateAnchoredAnimations(holder); + assert.deepEqual(spawned, ['good'], 'an ordinary loop still restarts'); + assert.equal(holder.refusedEffects.has('bad'), true); + // The next spawn stops at the refusal, before any sprite is made (Sprite does not exist here). + global.SceneManager = { _scene: { _spriteset: { _effectsContainer: {}, createAnimationSprite() { throw Error('spawned'); } } } }; + global.$dataAnimations = [null, { effectName: 'Bad-hdr' }]; + try { + assert.equal(Reactor3D.spawnAnchoredAnimation({ name: 'bad', animation: 1 }, {}, { object: {}, refusedEffects: new Set(['bad']) }), undefined); + } finally { delete global.SceneManager; delete global.$dataAnimations; } +}); diff --git a/editor/tests/quick-event-creation-20260812.test.cjs b/editor/tests/quick-event-creation-20260812.test.cjs index 431e8045..afd81e23 100644 --- a/editor/tests/quick-event-creation-20260812.test.cjs +++ b/editor/tests/quick-event-creation-20260812.test.cjs @@ -6,8 +6,10 @@ const vm = require('node:vm'); const editorRoot = path.resolve(__dirname, '..'); const source = fs.readFileSync(path.join(editorRoot, 'src', 'EventManager.js'), 'utf8'); +// Item, weapon and armor chests build their Can Receive branch through ConditionalBranchEditor. const EventManager = vm.runInNewContext(`${source}\nEventManager;`, { - console: { log() {}, warn() {}, error() {} } + console: { log() {}, warn() {}, error() {} }, + ConditionalBranchEditor: require('../src/event/commands/ConditionalBranchEditor.js') }); function managerWithMap() { @@ -67,7 +69,9 @@ test('Treasure quick event supports every reward command and an opened page', () }); const reward = event.pages[0].list.find(command => command.code === code); assert.deepEqual(plain(reward.parameters), parameters, rewardKind); - assert.deepEqual(plain(event.pages[0].list.at(-2)), { code: 123, indent: 0, parameters: ['A', 0] }); + // Gold claims at the top level; the others claim inside their Can Receive branch. + const claim = event.pages[0].list.find(command => command.code === 123); + assert.deepEqual(plain(claim), { code: 123, indent: rewardKind === 'gold' ? 0 : 1, parameters: ['A', 0] }); assert.equal(event.pages[1].conditions.selfSwitchValid, true); assert.equal(event.pages[1].conditions.selfSwitchCh, 'A'); assert.equal(event.pages[1].image.direction, 8); @@ -83,7 +87,7 @@ test('Door and Treasure routes release Direction Fix before turning, or nothing for (const config of [{ se }, {}]) { const page = manager.buildQuickEvent(kind, 1, 1, config).pages[0]; assert.equal(page.directionFix, true, kind); - const route = page.list[0].parameters[1]; + const route = page.list.find(command => command.code === 205).parameters[1]; const expected = [ { code: 36 }, ...(config.se ? [{ code: 44, parameters: [se] }] : []), diff --git a/editor/tests/sequence-media.test.cjs b/editor/tests/sequence-media.test.cjs index 90e8bfdd..88053a32 100644 --- a/editor/tests/sequence-media.test.cjs +++ b/editor/tests/sequence-media.test.cjs @@ -37,3 +37,120 @@ test('MOG cursor uses projected room bounds and its own parent coordinates; ordi const c=new Cursor();Object.assign(c,{_battlerSprite:{_reactorRoomBounds:{x:100,y:120,width:80,height:200}},_align:2,parent:{toLocal:p=>({x:p.x-10,y:p.y-20})},_position:{xOffset:3,yOffset:4},_effect:{waveX:0,waveY:0},_battler:{_battleCursor:{X_Offset:1,Y_Offset:2}}}); assert.equal(c.posX(),174);assert.equal(c.posY(),166);c._align=4;assert.equal(c.posX(),214);assert.equal(c.posY(),266);ss._reactorRoom=null;assert.equal(c.posX(),999);assert.equal(c.posY(),888); }); +function makeWaitHarness(anims=[]){ + const queue=[],animSprites=[],impacts=[],cleanups=[]; + function Sprite(){this.initialize();} + Sprite.prototype.initialize=function(){this.x=0;this.y=0;this.opacity=255;this.rotation=0;this.visible=true;this.scale={x:1,y:1,set(x,y=x){this.x=x;this.y=y;}};this.children=[];}; + Sprite.prototype.setColorTone=function(){};Sprite.prototype.getColorTone=()=>[0,0,0,0];Sprite.prototype.setBlendColor=function(){};Sprite.prototype.getBlendColor=()=>[0,0,0,0]; + Sprite.prototype.destroy=function(){this.destroyed=true;}; + function Sprite_Battler(){this.initialize();} + Sprite_Battler.prototype=Object.create(Sprite.prototype);Sprite_Battler.prototype.constructor=Sprite_Battler; + Sprite_Battler.prototype.initialize=function(){Sprite.prototype.initialize.call(this);this._homeX=0;this._homeY=0;this._offsetX=0;this._offsetY=0;this._animationSprites=[];this._damages=[];}; + Sprite_Battler.prototype.isAnimationPlaying=function(){return this._animationSprites.length>0;}; + Sprite_Battler.prototype.isMoving=()=>false;Sprite_Battler.prototype.isEffecting=()=>false;Sprite_Battler.prototype.refreshMotion=()=>{};Sprite_Battler.prototype.startMotion=()=>{}; + const loadCallbacks=new Map(); + function Spriteset_Base(){} + Spriteset_Base.prototype.createAnimation=function(request){ + const anim=scope.$dataAnimations[request.animationId];if(!anim)return; + const eff=anim.effectName?{}:null; + if(eff)scope.Sprite_Animation.SceneLayer.cache.set(anim.effectName,eff); + const s={targetObjects:request.targets.slice(),_targets:request.targets.map(b=>this.findTargetSprite(b)).filter(Boolean),_animation:anim,_effect:eff,_bitmap1:anim._bitmap1||null,_bitmap2:anim._bitmap2||null,_remaining:anim._frames||10,destroyed:false,isPlaying(){return !this.destroyed&&this._remaining>0;},update(){if(this._remaining>0)this._remaining--;}}; + this._animationSprites.push(s);return s; + }; + Spriteset_Base.prototype.isAnimationPlaying=function(){return this._animationSprites.some(s=>s.isPlaying());}; + Spriteset_Base.prototype.removeAnimation=function(s){s._remaining=0;s.destroyed=true;const i=this._animationSprites.indexOf(s);if(i>=0)this._animationSprites.splice(i,1);}; + const user={isActor:()=>true,actorId:()=>1,isEnemy:()=>false,isDead:()=>false,weapons:()=>[],attackAnimationId1:()=>1}; + const target={isActor:()=>false,enemyId:()=>11,isEnemy:()=>true,isDead:()=>target._hp<=0,_hp:100}; + const userSprite=new Sprite_Battler();userSprite._battler=user;userSprite._homeX=800;userSprite._homeY=480;userSprite.x=800;userSprite.y=480; + const targetSprite=new Sprite_Battler();targetSprite._battler=target;targetSprite._homeX=480;targetSprite._homeY=480;targetSprite.x=480;targetSprite.y=480; + const ss=new Spriteset_Base();ss._animationSprites=animSprites;ss._effectsContainer=new Sprite();ss._battleField=new Sprite(); + ss.findTargetSprite=b=>b===user?userSprite:b===target?targetSprite:null; + const manager={_spriteset:ss,_subject:user,_targets:[target],_action:{item:()=>({id:1,animationId:1})},_logWindow:{_methods:[],displayActionResults(){}},invokeAction(){impacts.push(1);}}; + const scope={ + ReactorBattleData:B,Sprite,Sprite_Base:Sprite,Sprite_Battler,Spriteset_Base,Spriteset_Battle:Spriteset_Base,BattleManager:manager, + DataManager:{isDatabaseLoaded:()=>true,isSkill:()=>true},PluginManager:{_scripts:[],registerCommand(){}}, + Window_BattleLog:function(){},Scene_Battle:function(){},SceneManager:{_scene:{_spriteset:ss}}, + Sprite_Animation:{SceneLayer:{cache:new Map(),load(name,fail){loadCallbacks.set(name,fail);}}}, + $dataAnimations:[null,...anims], + $gameTemp:{_animationQueue:queue,requestAnimation(targets,animationId,mirror=false){queue.push({targets:targets.slice(),animationId,mirror});}}, + Date, + }; + vm.runInNewContext(read('reactor_battle_presentation.js'),scope);scope.ReactorBattlePresentation.installSequenceAnimations(); + return {scope,ss,manager,user,target,targetSprite,queue,animSprites,impacts,loadCallbacks,pump(){while(queue.length)ss.createAnimation(queue.shift());},tickSprites(){for(const s of animSprites)s.update();}}; +} +test('waitFor animation holds past mid-animation impact until sequence-owned animation completes',()=>{ + const h=makeWaitHarness([{id:1,effectName:'Pierce',_frames:40,soundTimings:[],flashTimings:[]}]); + const seq={version:1,steps:[B.step('animation',{role:'allTargets',animationId:1,waitForCompletion:false,duration:0}),B.step('wait',{duration:10}),B.step('impact'),B.step('wait',{role:'allTargets',duration:0,waitFor:'animation'})]}; + const p=new h.scope.ReactorBattleData.Player(seq,h.scope.ReactorBattlePresentation.adapter(h.manager,h.user,[h.target])); + let impactFrame=null,doneFrame=null; + for(let f=0;f<80;f++){ + p.update(1);h.pump(); + if(h.impacts.length&&impactFrame===null)impactFrame=f; + if(p.done){doneFrame=f;break;} + h.tickSprites(); + } + assert.equal(h.impacts.length,1);assert.equal(impactFrame,9);assert.equal(doneFrame,40);assert.equal(h.animSprites[0].isPlaying(),false); +}); +test('waitFor animation terminates cleanly on cancel, missing data, Effekseer/MV load errors, and target death',()=>{ + // Cancel clears sequence wait and removes active sprite + const c=makeWaitHarness([{id:1,effectName:'Slow',_frames:120,soundTimings:[],flashTimings:[]}]); + const seq={version:1,steps:[B.step('animation',{role:'allTargets',animationId:1,waitForCompletion:false,duration:0}),B.step('wait',{role:'allTargets',duration:0,waitFor:'animation'}),B.step('impact')]}; + const pc=new c.scope.ReactorBattleData.Player(seq,c.scope.ReactorBattlePresentation.adapter(c.manager,c.user,[c.target])); + pc.update(1);c.pump();assert.equal(c.animSprites.length,1);assert.equal(pc.done,false); + pc.cancel();assert.equal(pc.done,true);assert.equal(c.animSprites.length,0); + // Missing $dataAnimations record terminates wait without stalling + const m=makeWaitHarness([]); + const pm=new m.scope.ReactorBattleData.Player(seq,m.scope.ReactorBattlePresentation.adapter(m.manager,m.user,[m.target])); + pm.update(1);m.pump();pm.update(1);assert.equal(pm.done,true); + // Effekseer SceneLayer fail callback terminates wait immediately + const e=makeWaitHarness([{id:1,effectName:'BrokenEff',_frames:120,soundTimings:[],flashTimings:[]}]); + const pe=new e.scope.ReactorBattleData.Player(seq,e.scope.ReactorBattlePresentation.adapter(e.manager,e.user,[e.target])); + pe.update(1);e.pump();assert.equal(pe.done,false);e.loadCallbacks.get('BrokenEff')();pe.update(1);assert.equal(pe.done,true); + // MV bitmap load error terminates wait immediately + const mv=makeWaitHarness([{id:1,frames:[[]],_bitmap1:{isError:()=>true},_frames:120,soundTimings:[],flashTimings:[]}]); + const pmv=new mv.scope.ReactorBattleData.Player(seq,mv.scope.ReactorBattlePresentation.adapter(mv.manager,mv.user,[mv.target])); + pmv.update(1);mv.pump();pmv.update(1);assert.equal(pmv.done,true); + // Lethal impact: filter:'alive' stops waiting when target dies, while unfiltered waits for active impact animation then finishes + const l1=makeWaitHarness([{id:1,effectName:'LethalEff',_frames:30,soundTimings:[],flashTimings:[]}]); + const seqLethalFiltered={version:1,steps:[B.step('animation',{role:'allTargets',animationId:1,waitForCompletion:false,duration:0}),B.step('wait',{duration:5}),B.step('impact'),B.step('wait',{role:'allTargets',filter:'alive',duration:0,waitFor:'animation'})]}; + const ad1=l1.scope.ReactorBattlePresentation.adapter(l1.manager,l1.user,[l1.target]); + const origInvoke=l1.manager.invokeAction;l1.manager.invokeAction=()=>{origInvoke();l1.target._hp=0;}; + const pl1=new l1.scope.ReactorBattleData.Player(seqLethalFiltered,ad1); + let done1=null;for(let f=0;f<50;f++){pl1.update(1);l1.pump();if(pl1.done){done1=pl1.frame;break;}l1.tickSprites();} + assert.equal(done1,5); + const l2=makeWaitHarness([{id:1,effectName:'LethalEff',_frames:30,soundTimings:[],flashTimings:[]}]); + const seqLethalUnfiltered={version:1,steps:[B.step('animation',{role:'allTargets',animationId:1,waitForCompletion:false,duration:0}),B.step('wait',{duration:5}),B.step('impact'),B.step('wait',{role:'allTargets',duration:0,waitFor:'animation'})]}; + l2.manager.invokeAction=()=>{l2.impacts.push(1);l2.target._hp=0;}; + const pl2=new l2.scope.ReactorBattleData.Player(seqLethalUnfiltered,l2.scope.ReactorBattlePresentation.adapter(l2.manager,l2.user,[l2.target])); + let done2=null;for(let f=0;f<50;f++){pl2.update(1);l2.pump();if(pl2.done){done2=f;break;}l2.tickSprites();} + assert.equal(done2,30); +}); +test('a flat battler lifted by a sequence and moved by MZ meanwhile ends at the move\'s target, not the target plus the lift',()=>{ + const sprites=read('reactor_sprites.js').replace(/\r\n/g,'\n'),fn=name=>{const at=sprites.indexOf('\nSprite_Battler.prototype.'+name+' = function');return at<0?null:sprites.slice(at+1,sprites.indexOf('\n};',at)+3);}; + const mz=['updateMove','updatePosition','startMove','onMoveEnd','isMoving'].map(name=>{const src=fn(name);assert.ok(src,'found Sprite_Battler.prototype.'+name);return src;}).join('\n'); + function Sprite(){this.x=800;this.y=480;this.opacity=255;this.rotation=0;this.visible=true;this.scale={x:1,y:1,set(x,y=x){this.x=x;this.y=y;}};this._homeX=800;this._homeY=480;this._offsetX=0;this._offsetY=0;this._targetOffsetX=NaN;this._targetOffsetY=NaN;this._movementDuration=0;this._damages=[];} + Sprite.prototype.setColorTone=()=>{};Sprite.prototype.getColorTone=()=>[0,0,0,0];Sprite.prototype.setBlendColor=()=>{};Sprite.prototype.getBlendColor=()=>[0,0,0,0]; + Sprite.prototype.isEffecting=()=>false;Sprite.prototype.refreshMotion=()=>{};Sprite.prototype.startMotion=()=>{};Sprite.prototype.isAnimationPlaying=()=>false; + const user={isActor:()=>true,actorId:()=>1,isEnemy:()=>false,isDead:()=>false},target={isActor:()=>false,enemyId:()=>11,isEnemy:()=>true,isDead:()=>false}; + const userSprite=new Sprite(),targetSprite=new Sprite();targetSprite._homeX=480;targetSprite.x=480; + const ss={_animationSprites:[],_effectsContainer:{},_battleField:{},findTargetSprite:b=>b===user?userSprite:b===target?targetSprite:null}; + const scope={ReactorBattleData:B,Sprite,Sprite_Base:Sprite,Sprite_Battler:Sprite,Spriteset_Base:function(){},Spriteset_Battle:function(){},Window_BattleLog:function(){},Scene_Battle:function(){},PluginManager:{_scripts:[],registerCommand(){}},DataManager:{isDatabaseLoaded:()=>true,isSkill:()=>true},BattleManager:{_spriteset:ss,_subject:user,_targets:[target],_logWindow:{_methods:[],displayActionResults(){}},invokeAction(){}},SceneManager:{_scene:{_spriteset:ss}},$dataAnimations:[null],$gameTemp:{_animationQueue:[],requestAnimation(){}},Date}; + vm.runInNewContext(mz,scope);vm.runInNewContext(read('reactor_battle_presentation.js'),scope); + const seq={version:1,steps:[B.step('float',{role:'user',height:2,duration:10,easing:'linear'}),B.step('wait',{duration:30}),B.step('impact')]}; + const p=new B.Player(seq,scope.ReactorBattlePresentation.adapter(scope.BattleManager,user,[target])); + // Each frame as MZ runs it: the sequence poses, then the battler sprite updates (updateMove, then updatePosition). + const frame=()=>{if(!p.done)p.update(1);userSprite.updateMove();userSprite.updatePosition();}; + for(let f=0;f<30;f++)frame(); + assert.equal(userSprite._rrLift,2);assert.equal(userSprite.y,480-96,'lifted two tiles'); + // MZ steps the battler toward a target while it is lifted (Sprite_Actor.stepForward-style). Each pose sets + // _offsetY outright and the cleanup puts back the saved one, so what lands is the part of the move after the sequence. + userSprite.startMove(-48,24,24); + let lowest=-Infinity; + for(let f=0;f<80&&(!p.done||userSprite.isMoving());f++){frame();lowest=Math.max(lowest,userSprite._offsetY);} + assert.equal(p.done,true);assert.equal(userSprite.isMoving(),false); + for(let f=0;f<3;f++)frame(); + assert.equal(userSprite._rrLift,0);assert.equal(userSprite._rrAppliedLift,0);assert.equal(userSprite._rrLiftedOffsetY,undefined); + assert.equal(userSprite._offsetX,-48);assert.equal(userSprite._offsetY,24,'the move\'s target, not the target plus the lift'); + assert.equal(userSprite.y,480+24);assert.equal(userSprite.x,800-48); + assert.ok(lowest<=24+1e-9,'never below the move\'s target: '+lowest); +}); diff --git a/runtime/reactor_3d_effects.js b/runtime/reactor_3d_effects.js index e11df66d..640bd317 100644 --- a/runtime/reactor_3d_effects.js +++ b/runtime/reactor_3d_effects.js @@ -785,11 +785,16 @@ Reactor3D.stopVideoEffect = function(effect, character, holder) { * to the anchor's screen position every frame. Without a scene to project * through (a flat map) the animation plays on the character as before. */ +Reactor3D.anchoredEffectKey = function(effect) { + return effect.name || "#" + effect.animation; +}; + Reactor3D.spawnAnchoredAnimation = function(effect, character, holder) { const spriteset = typeof SceneManager !== "undefined" && SceneManager._scene ? SceneManager._scene._spriteset : null; const animation = typeof $dataAnimations !== "undefined" ? $dataAnimations[effect.animation] : null; if (!spriteset || !animation || !character) return; + if (holder && holder.refusedEffects && holder.refusedEffects.has(this.anchoredEffectKey(effect))) return; const object = holder && holder.object; if (!object || !spriteset._effectsContainer || !spriteset.createAnimationSprite) { if (typeof $gameTemp !== "undefined" && $gameTemp.requestAnimation) $gameTemp.requestAnimation([character], effect.animation); @@ -929,7 +934,7 @@ Reactor3D.GpuEffects = { try { renderer.resetState(); context = effekseer.createContext(); - context.init(gl); + context.init(gl, typeof Graphics !== 'undefined' ? Graphics.effekseerContextSettings : undefined); // This pass owns GL until it invalidates Three/PIXI's caches below. context.setRestorationOfStatesFlag(false); return { renderer, gl, context, samples, cache: new Map(), targets: new Set(), disposed: false, loading: 0 }; @@ -2084,7 +2089,10 @@ Reactor3D.updateAnchoredAnimations = function(holder) { if (!entry.sprite.parent) { if (entry.standIn.parent) entry.standIn.parent.removeChild(entry.standIn); if (entry.fx3d) this.EffekseerScene.stop(entry.fx3d); - if (entry.loop && !entry.restarted && holder.object) restart.push(entry); + // An effect the game refuses (a -hdr file without a valid sidecar) is not tried again: + // a loop or a live trigger would respawn it, and warn, every frame. + if (entry.sprite._hdrRefused) (holder.refusedEffects || (holder.refusedEffects = new Set())).add(this.anchoredEffectKey(entry.effect)); + else if (entry.loop && !entry.restarted && holder.object) restart.push(entry); continue; } this.placeStandIn(holder, entry.effect, entry.standIn); diff --git a/runtime/reactor_battle_presentation.js b/runtime/reactor_battle_presentation.js index 155d17a0..dace2d01 100644 --- a/runtime/reactor_battle_presentation.js +++ b/runtime/reactor_battle_presentation.js @@ -126,7 +126,7 @@ // Where each battler's posed parts stand, so a pose step starts from // the last one and the motion after a pose brings the parts home. const media=[],poseState=new Map(); - const adapter={context:{homes,target:homes.target,direction:homes.target&&homes.user&&homes.target.x0){ - const tickets=[],flat=[]; - for(const battler of chosen.filter(Boolean)){const ticket=room?.playAnimation(ss.findTargetSprite(battler)?._reactorRoomKey,step.animationId,step.animationTransform);if(ticket)tickets.push(ticket);else flat.push(battler);} - if(flat.length){ + if(root.$dataAnimations&&!root.$dataAnimations[step.animationId]){const ticket={kind:'animation',targets:[],isPlaying:()=>false,cancel(){}};media.push(ticket);return ticket;} + const targetsList=chosen.filter(Boolean),tickets=[],flat=[]; + for(const battler of targetsList){const ticket=room?.playAnimation(ss?.findTargetSprite(battler)?._reactorRoomKey,step.animationId,step.animationTransform);if(ticket){ticket.kind='animation';ticket.targets=[battler];tickets.push(ticket);}else flat.push(battler);} + if(flat.length&&root.$gameTemp?.requestAnimation){ const before=new Set($gameTemp._animationQueue||[]);$gameTemp.requestAnimation(flat,step.animationId); for(const request of ($gameTemp._animationQueue||[]).filter(r=>!before.has(r))){ - const created=Date.now(),ticket={pending:true,sprites:[],transform:{...step.animationTransform},room, - isPlaying(){return this.pending?Date.now()-created<15000:this.sprites.some(s=>s.isPlaying());}, - cancel(){this.pending=false;const i=$gameTemp._animationQueue.indexOf(request);if(i>=0){$gameTemp._animationQueue.splice(i,1);for(const b of request.targets)b.endAnimation?.();}for(const sprite of this.sprites)if(ss._animationSprites?.includes(sprite))ss.removeAnimation(sprite);}}; + const created=Date.now(),reqTargets=Array.isArray(request.targets)?request.targets:flat,ticket={kind:'animation',targets:reqTargets,pending:true,sprites:[],transform:{...step.animationTransform},room, + isPlaying(){ + if(this.pending){ + if(root.$gameTemp?._animationQueue&&!root.$gameTemp._animationQueue.includes(request)){this.pending=false;return false;} + if(this.targets.length&&this.targets.every(b=>b?.isDead?.()))return false; + return Date.now()-created<15000; + } + return this.sprites.some(s=>P.isSequenceSpritePlaying(s,ss)); + }, + cancel(){this.pending=false;const queue=root.$gameTemp?._animationQueue,i=queue?queue.indexOf(request):-1;if(i>=0){queue.splice(i,1);for(const b of request.targets)b.endAnimation?.();}for(const sprite of this.sprites){if(ss?._animationSprites?.includes(sprite)&&ss.removeAnimation)ss.removeAnimation(sprite);sprite._playing=false;sprite._duration=0;}}}; request._reactorSequenceMedia=ticket;tickets.push(ticket); } } - const ticket={isPlaying:()=>tickets.some(t=>t.isPlaying()),cancel:()=>tickets.forEach(t=>t.cancel?.())};media.push(ticket);return ticket; + const ticket={kind:'animation',targets:targetsList,isPlaying:()=>tickets.some(t=>t.isPlaying()),cancel:()=>tickets.forEach(t=>t.cancel?.())};media.push(ticket);return ticket; } else if(step.type==='motion')for(const battler of chosen.filter(Boolean)){ // A part pose is played by rules made for this step from @@ -381,6 +389,7 @@ }; const appearance=new Map(),spriteKeys=new Map();for(const [key,sprite] of Object.entries(roles))if(sprite&&!spriteKeys.has(sprite))spriteKeys.set(sprite,key); const tween=(sprite,key,to,duration,start,apply,from)=>{effects.push({sprite,key,from,to,start,end:start+duration,apply});}; + const liftHeight=(effect,at)=>{const t=Math.min(1,Math.max(0,(at-effect.start)/Math.max(1,effect.end-effect.start)));return effect.kind==='jump'?effect.from+(t>=1?0:Math.sin(Math.PI*t)*effect.height):effect.kind==='leap'?effect.from+effect.height*(1-(1-t)*(1-t)):effect.kind==='float'?effect.from+effect.height*t:effect.from+(effect.height-effect.from)*t;}; const layerPrefix='extra:sequence-layer:'+(P._layerSerial=(P._layerSerial||0)+1)+':'; const destroyLayer=(key,owners=[])=>{const entry=layers.get(key)||owners.map(o=>o?._rrLayers?.get(key)).find(Boolean);if(entry){if(entry.roomKey)room?.remove(entry.roomKey);entry.graphic.removeFromParent();entry.graphic.destroy();layers.delete(key);entry.owner?._rrLayers?.delete(key);}}; const pending=()=>({blocking:true,isPlaying:()=>adapter.pendingImpact}); @@ -481,12 +490,37 @@ if(step.type==='opacity')tween(sprite,'opacity',Math.max(0,Math.min(255,step.opacity)),step.duration,start,v=>sprite.opacity=v,sprite.opacity); else if(step.type==='tint')tween(sprite,'tone',[step.red,step.green,step.blue,step.gray],step.duration,start,v=>main.setColorTone?.(v),main.getColorTone?.()||[0,0,0,0]); else if(step.type==='whiten'){main.setBlendColor?.([255,255,255,160]);tween(sprite,'whiten',0,Math.max(1,step.duration),start,v=>main.setBlendColor?.([255,255,255,v]),160);} - else{effects.push({lift:sprite,kind:step.type,height:step.height,start,end:start+Math.max(1,step.duration),from:sprite._rrLift||0});} + else{for(const e of effects)if(e.lift===sprite)sprite._rrLift=liftHeight(e,start);effects.push({lift:sprite,kind:step.type,height:step.height,start,end:start+Math.max(1,step.duration),from:sprite._rrLift||0});} }return; } if(step.type==='motion'&&(step.motionIndex||step.motionFrames||step.motionSpeed||step.motionLoop&&step.motionLoop!=='default'))for(const sprite of sprites){sprite._rrMotionOverride={...(step.motionIndex?{index:step.motionIndex-1}:{}),...(step.motionFrames?{frames:step.motionFrames}:{}),...(step.motionSpeed?{speed:step.motionSpeed}:{}),...(step.motionLoop&&step.motionLoop!=='default'?{loop:step.motionLoop==='loop'?true:step.motionLoop==='hold'?'once':false}:{}),name:step.motion};} else if(step.type==='motion')for(const sprite of sprites)delete sprite._rrMotionOverride; - if(step.type==='wait'&&step.waitFor&&step.waitFor!=='frames')return {blocking:true,isPlaying:()=>sprites.some(s=>step.waitFor==='move'?s.isMoving?.():step.waitFor==='animation'?s.isAnimationPlaying?.():step.waitFor==='popup'?s._damages?.length:step.waitFor==='effecting'?s.isEffecting?.():step.waitFor==='motion'?s._motion&&!s._motion.loop&&s._pattern<2:false)}; + if(step.type==='wait'&&step.waitFor&&step.waitFor!=='frames'){ + let cancelled=false; + return { + blocking:true, + cancel(){cancelled=true;}, + isPlaying(){ + if(cancelled)return false; + const activeTargets=step.filter&&step.filter!=='all'?choose(step):chosen; + const activeSprites=activeTargets.map(b=>ss?.findTargetSprite(b)).filter(Boolean); + if(step.waitFor==='animation'){ + if(step.filter==='alive'&&!activeTargets.length)return false; + const animMedia=(adapter.media||[]).filter(m=>m.kind==='animation'); + const hasRoleMatch=animMedia.some(m=>m.targets?.some(t=>activeTargets.includes(t))); + if(animMedia.some(m=>m.isPlaying()&&(!m.targets?.length||m.targets.some(t=>activeTargets.includes(t))||(step.role==='user'&&!hasRoleMatch&&!(step.filter==='alive'&&m.targets.every(t=>t?.isDead?.()))))))return true; + if((ss?._animationSprites||[]).some(a=>P.isSequenceSpritePlaying(a,ss)&&((a.targetObjects||[]).some(t=>activeTargets.includes(t))||(a._targets||[]).some(t=>activeSprites.includes(t)))))return true; + if((root.$gameTemp?._animationQueue||[]).some(r=>(!root.$dataAnimations||root.$dataAnimations[r.animationId])&&(r.targets||[]).some(t=>activeTargets.includes(t)&&!t?.isDead?.())))return true; + return activeSprites.some(s=>!(s._battler||s._actor||s._enemy)?.isDead?.()&&s.isAnimationPlaying?.()); + } + if(step.waitFor==='move')return activeSprites.some(s=>!(s._battler||s._actor||s._enemy)?.isDead?.()&&s.isMoving?.()); + if(step.waitFor==='motion')return activeSprites.some(s=>!(s._battler||s._actor||s._enemy)?.isDead?.()&&s._motion&&!s._motion.loop&&s._pattern<2); + if(step.waitFor==='popup')return activeSprites.some(s=>s._damages?.length); + if(step.waitFor==='effecting')return activeSprites.some(s=>s.isEffecting?.()); + return false; + } + }; + } if(step.type==='animation'&&step.animationSource&&step.animationSource!=='id'){const id=action?.item()?.animationId??0;raw={...raw,animationId:step.animationSource==='weapon'||id===-1?subject.attackAnimationId1?.()||0:Math.max(0,id)};} return original.cue(raw,start); }; @@ -499,25 +533,32 @@ }}; if(room)(room.sequenceVisualUpdates||=new Set()).add(updateRoomLayers); adapter.pose=(positions,time)=>{ - frame=time;original.pose(positions,time); + frame=time; + if(!room)for(const sprite of appearance.keys())if(sprite._rrAppliedLift){sprite.y+=sprite._rrAppliedLift;if(Number.isFinite(sprite._offsetY))sprite._offsetY+=sprite._rrAppliedLift;sprite._rrAppliedLift=0;} + original.pose(positions,time); for(const effect of effects){ if(effect.balloon){effect.balloon.update();continue;} if(effect.direction){const sprite=effect.direction,old=saved.get(sprite);sprite.scale.x=Math.abs(old.scaleX)*(effect.facing<0?1:-1);if(room&&!room.models.has(sprite._reactorRoomKey))sprite._reactorRoomPosition.facing=effect.facing*90;continue;}// A room's model keeps the yaw the pose gave it; a picture can only face left or right. + if(effect.lift){effect.lift._rrLift=liftHeight(effect,time);continue;} const t=Math.min(1,Math.max(0,(time-effect.start)/Math.max(1,effect.end-effect.start))); - if(effect.lift){const h=effect.kind==='jump'?effect.from+Math.sin(Math.PI*t)*effect.height:effect.kind==='leap'?effect.from+effect.height*(1-(1-t)*(1-t)):effect.kind==='float'?effect.from+effect.height*t:effect.from+(effect.height-effect.from)*t;effect.lift._rrLift=h;continue;} const v=Array.isArray(effect.to)?effect.to.map((n,i)=>effect.from[i]+(n-effect.from[i])*t):effect.from+(effect.to-effect.from)*t;effect.apply(v); } - for(const sprite of appearance.keys())if(sprite._rrLift){if(room)sprite._reactorRoomPosition.z=(positions[spriteKeys.get(sprite)]?.z||0)+sprite._rrLift;else sprite.y-=sprite._rrLift*48;} + for(const sprite of appearance.keys()){ + if(room){if(sprite._rrLift)sprite._reactorRoomPosition.z=(positions?.[spriteKeys.get(sprite)]?.z||0)+sprite._rrLift;continue;} + const lift=(sprite._rrLift||0)*48; + if(lift){sprite.y-=lift;if(Number.isFinite(sprite._offsetY))sprite._offsetY-=lift;} + sprite._rrAppliedLift=lift; + } visuals.pose(time); for(const entry of layers.values()){const {graphic,owner,step}=entry;graphic.opacity=entry.opacity;graphic.rotation=(step.angle+(time-entry.start)*step.spin)*Math.PI/180;graphic.scale?.set(step.scale);if(entry.type==='plane'){graphic.origin.x=(time-entry.start)*step.scrollX;graphic.origin.y=(time-entry.start)*step.scrollY;}else if(entry.hosted){graphic.x=entry.x;graphic.y=entry.y;}else{graphic.x=(owner?.x||0)+entry.x;graphic.y=(owner?.y||0)+entry.y;}} }; - adapter.cleanup=cancelled=>{try{original.cleanup(cancelled);}finally{ + adapter.cleanup=cancelled=>{try{if(!room)for(const sprite of appearance.keys())if(sprite._rrAppliedLift){sprite.y+=sprite._rrAppliedLift;if(Number.isFinite(sprite._offsetY))sprite._offsetY+=sprite._rrAppliedLift;sprite._rrAppliedLift=0;}original.cleanup(cancelled);}finally{ visuals.cleanup();room?.sequenceVisualUpdates?.delete(updateRoomLayers); for(const fn of restore.reverse())fn();for(const key of [...layers.keys()])if(!(stateOnly&&layers.get(key).hosted))destroyLayer(key); for(const [sprite,old] of appearance){const main=sprite._mainSprite||sprite; // A dead enemy keeps what its collapse left (a few points of opacity, a blend colour): a reaction played over the collapse must not stand it back up. const gone=sprite._battler&&typeof sprite._battler.isDead==='function'&&sprite._battler.isDead()&&typeof sprite._battler.isEnemy==='function'&&sprite._battler.isEnemy(); - if(!gone){sprite.opacity=old.opacity;if(old.tone)main.setColorTone?.(old.tone);if(old.blend)main.setBlendColor?.(old.blend);}sprite._rrHeldPose=old.pose;sprite._rrGraphicMotion=old.motion;sprite._rrLift=0;delete sprite._rrFacing;delete sprite._rrMotionOverride;sprite._homeX=old.homeX;sprite._homeY=old.homeY;} + if(!gone){sprite.opacity=old.opacity;if(old.tone)main.setColorTone?.(old.tone);if(old.blend)main.setBlendColor?.(old.blend);}sprite._rrHeldPose=old.pose;sprite._rrGraphicMotion=old.motion;sprite._rrLift=0;sprite._rrAppliedLift=0;delete sprite._rrFacing;delete sprite._rrMotionOverride;sprite._homeX=old.homeX;sprite._homeY=old.homeY;} }}; return adapter; }; @@ -785,11 +826,19 @@ } if(sprite._stateIconSprite)sprite._stateIconSprite.y=bounds.y-room.project(sprite._reactorRoomPosition).y-20; }; + P.isSequenceSpritePlaying=function(sprite,ss){ + if(!sprite||sprite.destroyed||sprite._rrAssetError)return false; + if(sprite._bitmap1?.isError?.()||sprite._bitmap2?.isError?.()){sprite._rrAssetError=true;sprite._playing=false;sprite._duration=0;return false;} + if(ss?._animationSprites&&!ss._animationSprites.includes(sprite))return false; + if(sprite._targets?.length&&sprite._targets.every(t=>t?.destroyed))return false; + return !!sprite.isPlaying?.(); + }; P.installSequenceAnimations=function(){ if(!root.Spriteset_Base)return; const proto=Spriteset_Base.prototype,create=proto.createAnimation,busy=proto.isAnimationPlaying; proto.createAnimation=function(request){ const ticket=request._reactorSequenceMedia;if(!ticket)return create.call(this,request); + if(root.$dataAnimations&&!root.$dataAnimations[request.animationId]){ticket.pending=false;ticket.sprites=[];return;} const before=new Set(this._animationSprites); try{return create.call(this,request);}finally{ ticket.pending=false;ticket.sprites=this._animationSprites.filter(s=>!before.has(s)); @@ -797,6 +846,14 @@ sprite._reactorSequenceMedia=ticket; const t=ticket.transform,scale=t.scale??1; sprite._animation={...sprite._animation,scale:(sprite._animation.scale??100)*scale}; + const effName=sprite._animation?.effectName; + if(effName&&!sprite._animation?.frames){ + const fail=()=>{sprite._rrAssetError=true;sprite._playing=false;}; + const layer=root.Sprite_Animation?.SceneLayer; + if(sprite._effect&&layer?.load&&layer.cache?.get?.(effName)===sprite._effect)layer.load(effName,fail); + else if(sprite._effect&&root.EffectManager?.load&&root.EffectManager.makeUrl&&root.EffectManager._cache?.[root.EffectManager.makeUrl(effName)]===sprite._effect)root.EffectManager.load(effName,fail); + } + if(sprite._bitmap1?.isError?.()||sprite._bitmap2?.isError?.()){sprite._rrAssetError=true;sprite._playing=false;sprite._duration=0;} const offset=()=>{ const points=(sprite.targetObjects||[]).map(b=>this.findTargetSprite(b)?._reactorRoomPosition).filter(Boolean); if(ticket.room&&points.length){let x=0,y=0;for(const p of points){const a=ticket.room.project(p),b=ticket.room.project({x:p.x+(t.x||0),y:p.y+(t.y||0),z:(p.z||0)+(t.z||0)});x+=b.x-a.x;y+=b.y-a.y;}return {x:x/points.length,y:y/points.length};} diff --git a/runtime/reactor_core.js b/runtime/reactor_core.js index 2bd05cff..93332566 100644 --- a/runtime/reactor_core.js +++ b/runtime/reactor_core.js @@ -3619,6 +3619,43 @@ Graphics.blitSceneBehindEffects = function() { return drew; }; +/** + * What the Effekseer contexts that play effects are initialized with. + * + * Effekseer keeps a fixed pool of particle instances per context (its own + * default is 4000). When the pool is full a new particle is simply not made: + * no thinning, no error. The layers that spawn first keep everything and the + * later ones lose particles, and every effect playing in that context shares + * the pool (an HDR effect and its companion, several targets, other + * animations). A pool reserves about 5 KB of Effekseer's heap per instance + * at init (4000: ~20 MB, 8000: ~40 MB, 16000: ~80 MB per context). + * `squareMaxCount` is the sprite vertex buffer; it scales with the pool. + * + * The in-scene context (Sprite_Animation.SceneLayer) and the 3D map's + * effects context (Reactor3D.GpuEffects) take these, and both are made at + * their first use. The overlay context is made at boot, because plugins use + * `Graphics.effekseer` directly; it takes these only when it is the one + * drawing screen animations (see `_overlayEffekseerSettings`). While the + * in-scene layer is active the overlay only loads effects, so it keeps + * Effekseer's default pool and does not reserve the memory. + * A plugin can change these before the first context is created. + */ +Graphics.effekseerContextSettings = { instanceMaxCount: 16000, squareMaxCount: 40000 }; + +/** + * The overlay context's init settings: Effekseer's default pool (undefined) + * while screen animations play in the scene, the large pool when the overlay + * draws them itself (in-scene off, a WebGL1 or WebGPU renderer, no + * RenderContainer). Anything it cannot tell means the large pool. + */ +Graphics._overlayEffekseerSettings = function() { + try { + const layer = typeof Sprite_Animation !== "undefined" ? Sprite_Animation.SceneLayer : null; + if (layer && typeof layer.active === "function" && layer.active()) return undefined; + } catch (e) {} + return this.effekseerContextSettings; +}; + Graphics._createEffekseerContext = function() { if (!window.effekseer) return; try { @@ -3650,7 +3687,7 @@ Graphics._createEffekseerContext = function() { this._effekseerGL = efxGL; this._effekseer = effekseer.createContext(); if (this._effekseer) { - this._effekseer.init(efxGL); + this._effekseer.init(efxGL, this._overlayEffekseerSettings()); // ...but only until the first draw has re-asserted it. Reading // the state back is a synchronous round trip to the GPU process // per draw (15 ms a frame measured beside a 3D map), and this @@ -3709,7 +3746,7 @@ Graphics._restoreEffekseerContext = function() { try { const context = effekseer.createContext(); if (!context) return; - context.init(gl); + context.init(gl, this._overlayEffekseerSettings()); this._effekseer = context; if (typeof EffectManager !== "undefined") EffectManager._cache = {}; this.rearmEffekseerState(); diff --git a/runtime/reactor_fight_camera.js b/runtime/reactor_fight_camera.js index b5e970d4..d6793880 100644 --- a/runtime/reactor_fight_camera.js +++ b/runtime/reactor_fight_camera.js @@ -1613,7 +1613,10 @@ if (scale >= 1 || !player || typeof player.update !== "function") return updateEffekseer.call(this); const own = Object.prototype.hasOwnProperty.call(player, "update"), update = player.update; player.update = function(frames) { return update.call(this, (frames || 1) * scale); }; - try { return updateEffekseer.call(this); } finally { if (own) player.update = update; else delete player.update; } + try { return updateEffekseer.call(this); } finally { + this._effekseerStep = (this._effekseerStep || 0) * scale; + if (own) player.update = update; else delete player.update; + } }; } diff --git a/runtime/reactor_hdr_overlay.js b/runtime/reactor_hdr_overlay.js index e5d5ca5d..b065c34f 100644 --- a/runtime/reactor_hdr_overlay.js +++ b/runtime/reactor_hdr_overlay.js @@ -17,19 +17,55 @@ "void main(){ gl_FragColor = 0.25 * (texture2D(uTex, vUv + uTexel * vec2(-0.5,-0.5)) + texture2D(uTex, vUv + uTexel * vec2(0.5,-0.5))" + " + texture2D(uTex, vUv + uTexel * vec2(-0.5,0.5)) + texture2D(uTex, vUv + uTexel * vec2(0.5,0.5))); }"; // the first downsample with UE 4's bloom setup threshold (PostProcessBloomSetup): light below the threshold in - // luminance does not bloom, ramping to full over 2 units above it + // luminance does not bloom, ramping to full over 2 units above it. With uUnity, Unity post-processing's bloom + // prefilter instead: each channel clamped to uClampMax, then a soft-knee threshold on the brightest channel const FS_SETUP = "precision highp float; varying vec2 vUv; uniform sampler2D uTex; uniform vec2 uTexel; uniform float uThreshold;" + + "uniform float uUnity; uniform float uKnee; uniform float uClampMax;" + "void main(){ vec4 c = 0.25 * (texture2D(uTex, vUv + uTexel * vec2(-0.5,-0.5)) + texture2D(uTex, vUv + uTexel * vec2(0.5,-0.5))" + " + texture2D(uTex, vUv + uTexel * vec2(-0.5,0.5)) + texture2D(uTex, vUv + uTexel * vec2(0.5,0.5)));" + - " float lum = dot(c.rgb, vec3(0.3, 0.59, 0.11)); c.rgb *= clamp((lum - uThreshold) * 0.5, 0.0, 1.0);" + + " if (uUnity > 0.5) { c.rgb = min(c.rgb, vec3(uClampMax)); float br = max(c.r, max(c.g, c.b));" + + " float sf = clamp(br - uThreshold + uKnee, 0.0, 2.0 * uKnee); sf = sf * sf / (4.0 * uKnee + 0.0001);" + + " c.rgb *= max(br - uThreshold, sf) / max(br, 0.0001); }" + + " else { float lum = dot(c.rgb, vec3(0.3, 0.59, 0.11)); c.rgb *= clamp((lum - uThreshold) * 0.5, 0.0, 1.0); }" + " gl_FragColor = c; }"; + // Unity post-processing's bloom prefilter, when a sidecar gives one + function prefilterOf(p) { + return p ? {threshold: p.threshold, knee: p.knee, clamp: p.clamp === undefined ? 65472 : p.clamp} : null; + } // separable Gaussian, sigma in texels (<= ~5), +-3 sigma const FS_BLUR = "precision highp float; varying vec2 vUv; uniform sampler2D uTex; uniform vec2 uStep; uniform float uSigma;" + "void main(){ vec4 s = vec4(0.0); float w = 0.0; for (int i = -16; i <= 16; i++) { float x = float(i);" + " if (abs(x) > 3.0 * uSigma + 0.5) continue; float k = exp(-0.5 * x * x / (uSigma * uSigma));" + " s += k * texture2D(uTex, vUv + uStep * x); w += k; } gl_FragColor = s / w; }"; - function valid(s) { + // bloom.intensityKeys: [[frame, intensity], ...] on the effect's own clock (60 frames a second at speed 100), + // frames increasing, played as straight lines between keys and held before the first and after the last + function keysValid(k) { + return Array.isArray(k) && k.length > 0 && k.every((key, i) => Array.isArray(key) && key.length === 2 && + Number.isFinite(key[0]) && Number.isFinite(key[1]) && key[1] >= 0 && (i === 0 || key[0] > k[i - 1][0])); + } + // The bloom intensity at an effect frame: the keys when the sidecar has them, bloom.intensity otherwise. + function bloomIntensity(bloom, frame) { + const k = bloom.intensityKeys; + return k ? keyedValue(k, frame) : bloom.intensity; + } + // gradeB + gradeKeys: a second grade over part of the effect, the sidecar's `grade` at weight 0 and `gradeB` at + // weight 1, [[frame, weight 0..1], ...] on the same clock as bloom.intensityKeys. Without gradeKeys `grade` plays. + function gradeMix(sc, frame) { + return sc && sc.gradeKeys ? Math.min(1, Math.max(0, keyedValue(sc.gradeKeys, frame))) : 0; + } + function keyedValue(k, frame) { + const f = Number.isFinite(frame) ? frame : 0; + if (f <= k[0][0]) return k[0][1]; + for (let i = 1; i < k.length; i++) { + if (f > k[i][0]) continue; + const [f0, v0] = k[i - 1], [f1, v1] = k[i]; + return v0 + (v1 - v0) * (f - f0) / (f1 - f0); + } + return k[k.length - 1][1]; + } + + function valid(s, effectName) { if (!s || s.version !== 1 || s.gradeInput !== "hdr" || typeof s.grade !== "string" || !/\bhdr\b/.test(s.grade) || !/\btmOut\b/.test(s.grade) || typeof s.fallback !== "string" || !s.fallback || !s.bloom || !Array.isArray(s.bloom.sizes) || !Array.isArray(s.bloom.tints) || @@ -38,7 +74,18 @@ !s.bloom.tints.every(x => Number.isFinite(x) && x >= 0) || !Number.isFinite(s.bloom.intensity) || s.bloom.intensity < 0 || !Number.isFinite(s.bloom.radiusScale) || s.bloom.radiusScale <= 0 || - (s.bloom.threshold !== undefined && !Number.isFinite(s.bloom.threshold))) throw Error("invalid HDR sidecar"); + (s.bloom.threshold !== undefined && !Number.isFinite(s.bloom.threshold)) || + (s.bloom.intensityKeys !== undefined && !keysValid(s.bloom.intensityKeys)) || + (s.gradeB !== undefined && (typeof s.gradeB !== "string" || !/\bhdr\b/.test(s.gradeB) || !/\btmOut\b/.test(s.gradeB) || + !keysValid(s.gradeKeys) || !s.gradeKeys.every(k => k[1] <= 1))) || + (s.gradeKeys !== undefined && s.gradeB === undefined) || + (s.bloom.prefilter !== undefined && (!s.bloom.prefilter || typeof s.bloom.prefilter !== "object" || + !Number.isFinite(s.bloom.prefilter.threshold) || !Number.isFinite(s.bloom.prefilter.knee) || s.bloom.prefilter.knee < 0 || + (s.bloom.prefilter.clamp !== undefined && !(Number.isFinite(s.bloom.prefilter.clamp) && s.bloom.prefilter.clamp > 0))))) + throw Error("invalid HDR sidecar"); + if (s.companion !== undefined && (typeof s.companion !== "string" || !s.companion.trim() || /\.efkefc$/i.test(s.companion) || s.companion === s.fallback)) throw Error("invalid HDR companion"); + if (s.companionOccludes !== undefined && typeof s.companionOccludes !== "boolean") throw Error("invalid companionOccludes"); + if (effectName && s.companion && (resolveName(effectName, s.companion) === effectName || resolveName(effectName, s.companion) === resolveName(effectName, s.fallback))) throw Error("HDR companion must differ from effect and fallback"); return s; } @@ -86,15 +133,20 @@ } catch (e) { gl.deleteProgram(p); throw e; } finally { for (const shader of shaders) gl.deleteShader(shader); } } - function gradeProgram(grade) { - if (H.programs.has(grade)) return H.programs.get(grade); + function gradeProgram(grade, gradeB) { + const id = gradeB ? grade + "\n/*gradeB*/\n" + gradeB : grade; + if (H.programs.has(id)) return H.programs.get(id); + // Two grades: each in its own function (both declare tmOut and their temporaries), mixed by uGradeMix + const twoGrades = gradeB ? "vec3 rr_gradeA(vec3 hdr){\n" + grade + "\nreturn tmOut; }\n" + + "vec3 rr_gradeB(vec3 hdr){\n" + gradeB + "\nreturn tmOut; }\nuniform float uGradeMix;\n" : ""; + const body = gradeB ? "vec3 tmOut = mix(rr_gradeA(hdr), rr_gradeB(hdr), uGradeMix);" : grade; const fs = "precision highp float; varying vec2 vUv; uniform sampler2D uHdr; uniform sampler2D uG0; uniform sampler2D uG1;" + "uniform sampler2D uG2; uniform sampler2D uG3; uniform sampler2D uG4; uniform sampler2D uG5; uniform float uW[6];" + - "uniform float uDebug; uniform float uAlphaFromColor;" + + "uniform float uDebug; uniform float uAlphaFromColor;" + twoGrades + "void main(){ vec3 hdr = texture2D(uHdr, vUv).rgb;" + " hdr += uW[0] * texture2D(uG0, vUv).rgb + uW[1] * texture2D(uG1, vUv).rgb + uW[2] * texture2D(uG2, vUv).rgb" + " + uW[3] * texture2D(uG3, vUv).rgb + uW[4] * texture2D(uG4, vUv).rgb + uW[5] * texture2D(uG5, vUv).rgb;" + - " hdr = max(hdr, vec3(0.0));" + "\n" + grade + "\n" + + " hdr = max(hdr, vec3(0.0));" + "\n" + body + "\n" + // Alpha from colour: for a premultiplied canvas the page blends // over what lies behind it, with no backdrop in this buffer. The // screen the game does ignores coverage, so dark quads stay clear. @@ -103,7 +155,7 @@ " gl_FragColor = uDebug > 0.0 ? vec4(clamp(texture2D(uHdr, vUv).rgb / uDebug, 0.0, 1.0), 1.0) : vec4(rr_o, rr_a); }"; const program = compile(VS, fs); - H.programs.set(grade, program); + H.programs.set(id, program); return program; } function tex(w, h, type) { @@ -246,7 +298,7 @@ gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } // Bloom the light buffer, grade it once, and screen it over the default - // framebuffer, or s.framebuffer. `s` is { bloom, bloomScale, threshold, coverage, + // framebuffer, or s.framebuffer. `s` is { bloom, bloomScale, threshold, prefilter, coverage, // debugScale, measureGpu, alphaFromColor, bloomWidth, pixelScale, framebuffer }; // the overlay sets none of the last four. function post(s, sc, out) { @@ -254,7 +306,7 @@ if (s.measureGpu) gl.finish(); const start = performance.now(); const SIZES = sc.bloom.sizes, TINTS = sc.bloom.tints; - H.comp = gradeProgram(sc.grade); + H.comp = gradeProgram(sc.grade, sc.gradeB); gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.disable(gl.SCISSOR_TEST); gl.disable(gl.STENCIL_TEST); gl.colorMask(true, true, true, true); gl.disable(gl.BLEND); @@ -270,9 +322,18 @@ // The threshold acts at the game's bloom setup resolution, half its screen. An effect drawn radiusScale // times larger than in the game covers that pixel with radiusScale of ours: level log2(radiusScale). // Every Gaussian reads that level or a coarser one, so all of the bloom is thresholded. A preview - // draws a game pixel as pixelScale of its own, which moves the level with it. - const setupLevel = Number.isFinite(s.threshold) ? + // draws a game pixel as pixelScale of its own, which moves the level with it. A Unity prefilter + // (s.prefilter, or the sidecar's own when a caller does not pass one) takes the threshold's place. + const pf = prefilterOf(s.prefilter !== undefined ? s.prefilter : sc.bloom && sc.bloom.prefilter); + const setupLevel = Number.isFinite(s.threshold) || pf ? Math.min(H.levels.length - 1, Math.max(0, Math.round(Math.log2(s.bloomScale * (s.pixelScale > 0 ? s.pixelScale : 1))))) : -1; + const setupUniforms = () => { + gl.uniform1f(H.setup.u.uUnity, pf ? 1 : 0); + if (!pf) { gl.uniform1f(H.setup.u.uThreshold, s.threshold); return; } + gl.uniform1f(H.setup.u.uThreshold, pf.threshold); + gl.uniform1f(H.setup.u.uKnee, pf.knee); + gl.uniform1f(H.setup.u.uClampMax, pf.clamp); + }; let base = H.main; if (setupLevel === 0) { if (!H.pre) H.pre = target(H.w, H.h, H.type, false); @@ -280,7 +341,7 @@ gl.useProgram(H.setup.p); bind(0, H.main.t, H.setup.u.uTex); gl.uniform2f(H.setup.u.uTexel, 0, 0); - gl.uniform1f(H.setup.u.uThreshold, s.threshold); + setupUniforms(); quad(H.setup, H.pre); base = H.pre; } @@ -291,7 +352,7 @@ gl.useProgram(prog.p); bind(0, src.t, prog.u.uTex); gl.uniform2f(prog.u.uTexel, 1 / src.w, 1 / src.h); - if (prog === H.setup) gl.uniform1f(prog.u.uThreshold, s.threshold); + if (prog === H.setup) setupUniforms(); quad(prog, H.levels[l]); } // six Gaussians, each blurred at the level where its sigma is 2-4 texels (never finer than the setup) @@ -336,6 +397,7 @@ gl.uniform1fv(H.comp.u.uW, weights.length ? weights : [0,0,0,0,0,0]); gl.uniform1f(H.comp.u.uDebug, s.debugScale || 0); gl.uniform1f(H.comp.u.uAlphaFromColor, s.alphaFromColor ? 1 : 0); + if (sc.gradeB) gl.uniform1f(H.comp.u.uGradeMix, s.gradeMix || 0); gl.enable(gl.BLEND); gl.blendEquation(gl.FUNC_ADD); gl.blendFunc(gl.ONE, s.coverage ? gl.ONE_MINUS_SRC_ALPHA : gl.ONE_MINUS_SRC_COLOR); @@ -376,7 +438,7 @@ get size() { return [H.w, H.h]; } }; } - window.ReactorHdrRenderer = { create: createRenderer, valid }; + window.ReactorHdrRenderer = { create: createRenderer, valid, bloomIntensity, gradeMix }; // ---- The game's adapter ------------------------------------------------ const params = {}; @@ -386,9 +448,12 @@ const api = window.ReactorHdrOverlay = { native: true, cache, stats: { groups: 0, draws: 0, postMs: 0 }, // Testing overrides still require a grade and a safe twin. overrides: Object.create(null) }; - function settings(sidecar) { - return Object.assign({ bloom: Number(params.bloomIntensity ?? sidecar.bloom.intensity), + // A sprite's settings at its effect frame (Sprite_Animation's _effectFrame). + function settings(sidecar, frame) { + return Object.assign({ bloom: Number(params.bloomIntensity ?? bloomIntensity(sidecar.bloom, frame)), + gradeMix: gradeMix(sidecar, frame), bloomScale: Number(params.bloomRadiusScale ?? sidecar.bloom.radiusScale), threshold: sidecar.bloom.threshold, + prefilter: sidecar.bloom.prefilter, debug: (params.debug === true || params.debug === "true") }, window.REACTOR_HDR || {}); } @@ -418,7 +483,7 @@ const timer = setTimeout(() => controller.abort(), 15000); entry.promise = fetch(url, {signal: controller.signal}) .then(r => { if (r.status === 404) return null; if (!r.ok) throw Error("sidecar HTTP " + r.status); return r.json(); }) - .then(s => { entry.sidecar = s && valid(s); }) + .then(s => { entry.sidecar = s && valid(s, name); }) .catch(e => { entry.error = String(e); console.warn("[ReactorHdrOverlay] " + name + ": " + e); }) .finally(() => { clearTimeout(timer); entry.ready = true; }); return entry; @@ -432,16 +497,52 @@ const a = sprite._animation || {}, e = sprite._hdrEntry; return e && e.sidecar || (forced(sprite) && api.overrides[a.effectName]) || null; } - // The context an effect is loaded into: the scene's for an in-scene sprite, the overlay's otherwise. - function load(sprite, name) { - return sprite._effekseerInScene ? Sprite_Animation.SceneLayer.load(name) : EffectManager.load(name); + // The context an effect is loaded into: the one the sprite plays in. + function load(sprite, name, onError) { + if (sprite._effekseerInScene) return Sprite_Animation.SceneLayer.load(name, onError); + return sprite._effectContext ? Reactor3D.GpuEffects.load(sprite._effectContext, name) : EffectManager.load(name, onError); } - function fallbackName(sprite, sc) { - const name = sprite._animation.effectName; - return sc.fallback.includes('/') ? sc.fallback : name.slice(0, name.lastIndexOf('/') + 1) + sc.fallback; + function resolveName(name, other) { + return other.includes('/') ? other : name.slice(0, name.lastIndexOf('/') + 1) + other; + } + function fallbackName(sprite, sc) { return resolveName(sprite._animation.effectName, sc.fallback); } + api.stopCompanion = function(sprite) { + try { sprite._companionHandle?.stop(); } catch (error) { /* lost WASM context */ } finally { sprite._companionHandle = null; sprite._companionEffect = null; } + }; + function companionFailure(sprite, reason) { + // A timed-out soft load must not strand a later scene in isReady(). + const effect = sprite._companionEffect, sc = sidecarFor(sprite); + if (effect && !effect.isLoaded && sc?.companion) { + const name = resolveName(sprite._animation.effectName, sc.companion); + if (sprite._effekseerInScene) { + const cache = Sprite_Animation.SceneLayer.cache; + if (cache?.get(name) === effect) cache.delete(name); + } else { + const url = EffectManager.makeUrl(name); + if (EffectManager._cache?.[url] === effect) delete EffectManager._cache[url]; + } + } + if (!sprite._companionWarned) { + sprite._companionWarned = true; + console.warn("[ReactorHdrOverlay] " + sprite._animation.effectName + ": companion unavailable (" + reason + "); selecting twin"); + } + scene.fallBack(sprite); + sprite._hdrSelected = true; + } + function companionReady(sprite) { + if (!sprite._hdrActive || !sprite._companionEffect) return true; + if (sprite._companionLoadError) { companionFailure(sprite, sprite._companionLoadError); return true; } + const entry = sprite._companionEntry; + if (!entry.ready) return false; + if (entry.sidecar || entry.error) { companionFailure(sprite, "companion has HDR metadata"); return true; } + if (sprite._companionEffect.isLoaded) return true; + if (performance.now() >= sprite._companionDeadline) { + companionFailure(sprite, "load failed or timed out"); return true; + } + return false; } api.setup = function(sprite, animation) { - if ((!sprite._effectContext || sprite._effekseerInScene) && animation.effectName) { + if (animation.effectName) { sprite._hdrEntry = request(animation.effectName); sprite._hdrSelected = false; } @@ -453,32 +554,48 @@ if (this._hdrEntry && !this._hdrSelected) { if (!this._hdrEntry.ready) return false; const inScene = !!this._effekseerInScene; - if ((inScene ? scene.gl() : Graphics._effekseerGL)?.isContextLost()) return false; + // Drawn by the 3D scene (an effect anchored on a model), which has no HDR path: its twin plays. + const sceneOwned = !!this._reactorInScene || (!!this._effectContext && !inScene); + if ((inScene || this._effectContext ? scene.gl() : Graphics._effekseerGL)?.isContextLost()) return false; let sc = sidecarFor(this); try { - if (sc) sc = valid(sc); + if (sc) sc = valid(sc, this._animation.effectName); if ((forced(this) || /-hdr$/i.test(this._animation.effectName)) && !sc) throw Error("HDR effect requires a sidecar or ReactorHdrOverlay.overrides entry"); } catch (e) { - console.warn("[ReactorHdrOverlay] " + e.message); this._playing = false; return false; + console.warn("[ReactorHdrOverlay] " + e.message); this._playing = false; this._hdrRefused = true; return false; } if (this._hdrEntry.error && !sc) { // Malformed metadata cannot safely identify an HDR asset or its fallback. Fail closed. - this._playing = false; return false; + this._playing = false; this._hdrRefused = true; return false; } - if (inScene) { + if (sceneOwned) { + this._hdrActive = false; + } else if (inScene) { this._hdrActive = !!(sc && scene.ready(sc)); } else { const gl = Graphics._effekseerGL, canvas = Graphics._effekseerCanvas; this._hdrActive = !!(sc && gl && canvas && !gl.isContextLost() && ensure(gl, canvas.width, canvas.height)); if (this._hdrActive) { - try { R.gradeProgram(sc.grade); } catch (e) { this._hdrActive = false; console.warn("[ReactorHdrOverlay] " + e); } + try { R.gradeProgram(sc.grade, sc.gradeB); } catch (e) { this._hdrActive = false; console.warn("[ReactorHdrOverlay] " + e); } } } if (sc && !this._hdrActive) this._effect = load(this, fallbackName(this, sc)); + if (this._hdrActive && sc.companion) { + const name = resolveName(this._animation.effectName, sc.companion); + if (typeof Utils !== "undefined" && Utils.localAssetExists && Utils.localAssetExists(EffectManager.makeUrl(name)) === false) { + companionFailure(this, "missing " + name); + } else { + this._companionEntry = request(name); + this._companionDeadline = performance.now() + 15000; + try { this._companionEffect = load(this, name, (message, url) => { this._companionLoadError = String(message) + " " + url; }); } + catch (error) { companionFailure(this, String(error)); } + if (!this._companionEffect && this._hdrActive) companionFailure(this, "load returned no effect"); + } + } if (this._hdrActive) active.add(this); this._hdrSelected = true; } - return true; + return companionReady(this); } api.contextLost = function() { // Old WASM handles cannot be resumed in the replacement Effekseer context. @@ -487,13 +604,14 @@ for (const sprite of active) { if (sprite._effekseerInScene) continue; sprite._handle?.stop(); + api.stopCompanion(sprite); sprite._hdrActive = false; sprite._playing = false; sprite._started = false; active.delete(sprite); } R?.lost(); }; api.contextRestored = function() { R?.restored(); }; - api.release = function(sprite) { active.delete(sprite); }; + api.release = function(sprite) { active.delete(sprite); api.stopCompanion(sprite); }; api.configure = function(options) { Object.assign(params, options); }; @@ -503,20 +621,31 @@ if (gl?.isContextLost()) { api.contextLost(); return; } if (!gl || !ensure(gl, canvas.width, canvas.height)) { // Never draw HDR light into the display buffer. Existing effects are stopped on loss by the engine. - for (const sprite of draws) { sprite._handle.stop(); sprite._started = false; + for (const sprite of draws) { api.stopCompanion(sprite); sprite._handle.stop(); sprite._started = false; active.delete(sprite); sprite._hdrActive = false; sprite._effect = EffectManager.load(fallbackName(sprite, sidecarFor(sprite))); } return; } + // One pass per grade, bloom intensity and grade weight: keyed intensities differ between animations at different frames. const groups = new Map(); for (const sprite of draws) { - const sc = sidecarFor(sprite); - if (!groups.has(sc.grade)) groups.set(sc.grade, { sc, sprites: [] }); - groups.get(sc.grade).sprites.push(sprite); + const sc = sidecarFor(sprite), frame = sprite._effectFrame, key = sc.grade + "\u0000" + (sc.gradeB || "") + "\u0000" + bloomIntensity(sc.bloom, frame) + "\u0000" + gradeMix(sc, frame); + if (!groups.has(key)) groups.set(key, { sc, frame, sprites: [] }); + groups.get(key).sprites.push(sprite); } try { for (const group of groups.values()) { R.begin(); + try { + gl.colorMask(false, false, false, false); + gl.depthMask(true); + for (const sprite of group.sprites) if (sprite._companionHandle?.exists && sidecarFor(sprite).companionOccludes !== false) { + sprite.setProjectionMatrix(renderer); sprite.setCameraMatrix(renderer); sprite.setViewport(renderer); + const efx = Graphics.effekseer; + efx.beginDraw(); efx.drawHandle(sprite._companionHandle); efx.endDraw(); + Graphics.settleEffekseerState(); + } + } finally { gl.colorMask(true, true, true, true); } for (const sprite of group.sprites) { sprite.setProjectionMatrix(renderer); sprite.setCameraMatrix(renderer); sprite.setViewport(renderer); const efx = Graphics.effekseer; @@ -524,7 +653,7 @@ Graphics.settleEffekseerState(); api.stats.draws++; } - const config = settings(group.sc); + const config = settings(group.sc, group.frame); if (config.probeScale && (!config.probeFrame || group.sprites.some(x => x._frameIndex === config.probeFrame))) R.probe(config.probeScale); R.post(config, group.sc); } @@ -533,6 +662,7 @@ R.fail(); for (const sprite of draws) { active.delete(sprite); + api.stopCompanion(sprite); sprite._handle.stop(); sprite._started = false; sprite._hdrActive = false; sprite._effect = EffectManager.load(fallbackName(sprite, sidecarFor(sprite))); } @@ -568,7 +698,7 @@ return !!layer.guard(gl => { const R = scene.renderer(gl); if (!R.ensure(Math.max(1, Graphics.width | 0), Math.max(1, Graphics.height | 0))) return false; - R.gradeProgram(sc.grade); + R.gradeProgram(sc.grade, sc.gradeB); return true; }); } catch (e) { @@ -578,15 +708,20 @@ }, sidecar: sidecarFor, settings, + // The bloom intensity an in-scene sprite draws with now: sprites of one grade share a pass only when it agrees. + intensity(sprite) { return bloomIntensity(sidecarFor(sprite).bloom, sprite._effectFrame); }, + // Likewise the weight of the sidecar's second grade (gradeB, gradeKeys). + gradeMix(sprite) { return gradeMix(sidecarFor(sprite), sprite._effectFrame); }, // A pass that failed: this sprite plays its twin from here on. fallBack(sprite) { active.delete(sprite); + api.stopCompanion(sprite); try { sprite._handle?.stop(); } catch (e) { /* a lost context */ } sprite._started = false; sprite._hdrActive = false; sprite._effect = load(sprite, fallbackName(sprite, sidecarFor(sprite))); }, lost() { - for (const sprite of active) if (sprite._effekseerInScene) active.delete(sprite); + for (const sprite of active) if (sprite._effekseerInScene) { api.stopCompanion(sprite); active.delete(sprite); } RS?.lost(); }, restored() { RS?.restored(); } diff --git a/runtime/reactor_main.js b/runtime/reactor_main.js index 22a9a146..f5a26e27 100644 --- a/runtime/reactor_main.js +++ b/runtime/reactor_main.js @@ -1,10 +1,10 @@ //============================================================================= // reactor_main.js — RPG Reactor runtime entry point // RPG Reactor runtime version: 0.99.7 -// RPG Reactor runtime revision: 20261122.4 +// RPG Reactor runtime revision: 20261124.1 // The same stamp, reachable from the F12 console: which engine is this // window actually running? Type RPG_REACTOR_RUNTIME_REVISION to see. -globalThis.RPG_REACTOR_RUNTIME_REVISION = "20261122.4"; +globalThis.RPG_REACTOR_RUNTIME_REVISION = "20261124.1"; //============================================================================= const scriptUrls = [ diff --git a/runtime/reactor_managers.js b/runtime/reactor_managers.js index 12932072..0e0bbbcd 100644 --- a/runtime/reactor_managers.js +++ b/runtime/reactor_managers.js @@ -1430,12 +1430,17 @@ function EffectManager() { EffectManager._cache = {}; EffectManager._errorUrls = []; +EffectManager._softLoadErrors = new Map(); -EffectManager.load = function(filename) { +EffectManager.load = function(filename, onError) { if (filename) { globalThis.ReactorHdrOverlay?.request(filename); const url = this.makeUrl(filename); const cache = this._cache; + if (typeof onError === "function" && !cache[url]?.isLoaded) { + if (!this._softLoadErrors.has(url)) this._softLoadErrors.set(url, new Set()); + this._softLoadErrors.get(url).add(onError); + } if (!cache[url] && Graphics.effekseer) { this.startLoading(url); } @@ -1446,8 +1451,15 @@ EffectManager.load = function(filename) { }; EffectManager.startLoading = function(url) { - const onLoad = () => this.onLoad(url); - const onError = (message, url) => this.onError(url); + const onLoad = () => { this._softLoadErrors.delete(url); this.onLoad(url); }; + const onError = (message, resourceUrl) => { + const handlers = this._softLoadErrors.get(url); + if (handlers) { + this._softLoadErrors.delete(url); + delete this._cache[url]; + for (const failed of handlers) failed(message, resourceUrl || url); + } else this.onError(resourceUrl || url); + }; const effect = Graphics.effekseer.loadEffect(url, 1, onLoad, onError); this._cache[url] = effect; return effect; @@ -1459,6 +1471,7 @@ EffectManager.clear = function() { Graphics.effekseer.releaseEffect(effect); } this._cache = {}; + this._softLoadErrors.clear(); // The in-scene layer's effects go once the next map has named its own // (preloadMap): what both maps play stays loaded. this._sceneEffectsStale = true; @@ -3581,7 +3594,10 @@ SceneManager.updateInputData = function() { }; SceneManager.updateEffekseer = function() { + // Frames this update steps the effects by (Sprite_Animation's effect clock); battle slow motion scales it. + this._effekseerStep = 0; if (Graphics.effekseer && this.isGameActive()) { + this._effekseerStep = 1; Graphics.effekseer._makeContextCurrent?.(); Graphics.effekseer.update(); // The in-scene context steps with the same update, battle slow motion included. diff --git a/runtime/reactor_sprites.js b/runtime/reactor_sprites.js index 0ebf9b85..764588d2 100644 --- a/runtime/reactor_sprites.js +++ b/runtime/reactor_sprites.js @@ -2687,9 +2687,12 @@ Sprite_Animation.prototype.initMembers = function() { this._previous = null; this._effect = null; this._handle = null; + this._companionHandle = null; + this._companionEffect = null; this._playing = false; this._started = false; this._frameIndex = 0; + this._effectFrame = 0; this._maxTimingFrames = 0; this._flashColor = [0, 0, 0, 0]; this._flashDuration = 0; @@ -2706,6 +2709,8 @@ Sprite_Animation.prototype.destroy = function(options) { } this._effect = null; this._handle = null; + this._companionHandle = null; + this._companionEffect = null; this._playing = false; this._started = false; }; @@ -2739,17 +2744,27 @@ Sprite_Animation.prototype.setup = function( Sprite_Animation.prototype.update = function() { Sprite.prototype.update.call(this); + // The effect's own clock in frames: what this update's Effekseer step moved its handle by (battle slow + // motion included), at the animation's speed. HDR sidecars key their bloom intensity to it. + if (this._started) this._effectFrame += (globalThis.SceneManager?._effekseerStep ?? 1) * this._animation.speed / 100; if (this._delay > 0) { this._delay--; } else if (this._playing) { if (!this._started && this.canStart()) { if (this._effect) { - if (this._effect.isLoaded) { + if (this._effect.isLoaded && (!this._companionEffect || this._companionEffect.isLoaded)) { const context = this._effectContext?.context || Graphics.effekseer; context._makeContextCurrent?.(); this._handle = context.play(this._effect); + if (this._hdrActive && this._companionEffect) { + this._companionHandle = context.play(this._companionEffect); + const seed = Math.floor(Math.random() * 0x7fffffff); + this._handle.setRandomSeed(seed); + this._companionHandle.setRandomSeed(seed); + } Graphics.effekseer._makeContextCurrent?.(); this._started = true; + this._effectFrame = 0; } else { EffectManager.checkErrors(); } @@ -2825,10 +2840,12 @@ Sprite_Animation.prototype.updateEffectGeometry = function() { // rendered 50% wider than tall (measured 471×314). On-axis in its own // viewport, it stays round at every screen position — this is MZ's own // approach (4096² viewport at the target), adapted to the overlay recipe. - this._handle.setLocation(0, 0, 0); - this._handle.setRotation(rx, ry, rz); - this._handle.setScale(scale, scale, scale); - this._handle.setSpeed(this._animation.speed / 100); + this.forEachEffectHandle(handle => { + handle.setLocation(0, 0, 0); + handle.setRotation(rx, ry, rz); + handle.setScale(scale, scale, scale); + handle.setSpeed(this._animation.speed / 100); + }); }; // Target position in overlay-canvas pixels (shared by setViewport). @@ -2880,7 +2897,8 @@ Sprite_Animation.prototype.checkEnd = function() { this._frameIndex > this._maxTimingFrames && this._flashDuration === 0 && !(this._reactorHideDuration > 0) && - !(this._handle && this._handle.exists) + !(this._handle && this._handle.exists) && + !(this._companionHandle && this._companionHandle.exists) ) { this._playing = false; } @@ -2912,9 +2930,11 @@ Sprite_Animation.prototype.isPlaying = function() { }; Sprite_Animation.prototype.setRotation = function(x, y, z) { - if (this._handle) { - this._handle.setRotation(x, y, z); - } + this.forEachEffectHandle(handle => handle.setRotation(x, y, z)); +}; + +Sprite_Animation.prototype.forEachEffectHandle = function(fn) { + for (const handle of [this._handle, this._companionHandle]) if (handle) fn(handle); }; // v8: queue of Sprite_Animation instances that need an Effekseer draw on the @@ -2963,9 +2983,9 @@ Sprite_Animation.renderActive = function(renderer) { const composited = !!(Graphics.blitSceneBehindEffects && Graphics.blitSceneBehindEffects()); const hdr = []; for (const inst of list) { - if (inst._hdrActive) { hdr.push(inst); continue; } + if (inst._hdrActive) hdr.push(inst); try { - inst._doEffekseerDraw(renderer, composited); + inst._doEffekseerDraw(renderer, composited, inst._hdrActive ? inst._companionHandle : inst._handle); } catch (e) { // The draw runs every frame, so a throw here is reported once. // Swallowing it outright hid every effect in a game while the @@ -3008,6 +3028,7 @@ Sprite_Animation.SceneLayer = { entry: null, cache: new Map(), deadlines: new Map(), + loadErrors: new Map(), live: new Set(), frame: [], drawn: new Set(), @@ -3050,7 +3071,7 @@ Sprite_Animation.SceneLayer = { this.install(); this.guard(gl => { const context = effekseer.createContext(); - context.init(gl); + context.init(gl, Graphics.effekseerContextSettings); // Each draw sets what it needs; PIXI's caches are reset after it. context.setRestorationOfStatesFlag(false); this.context = context; @@ -3094,17 +3115,24 @@ Sprite_Animation.SceneLayer = { this.drawn.delete(sprite); }, /** An effect in the scene's context, loaded once. */ - load(name) { + load(name, onError) { + if (typeof onError === "function" && !this.cache.get(name)?.isLoaded) { + if (!this.loadErrors.has(name)) this.loadErrors.set(name, new Set()); + this.loadErrors.get(name).add(onError); + } if (this.cache.has(name)) return this.cache.get(name); const context = this.ensureContext(); const url = EffectManager.makeUrl(name); context._makeContextCurrent?.(); try { // Its textures upload when their images arrive, outside any draw: PIXI is reset before the next render. - const effect = context.loadEffect(url, 1, () => { this.dirty = true; Graphics.effekseer?._makeContextCurrent?.(); }, () => { + const effect = context.loadEffect(url, 1, () => { this.loadErrors.delete(name); this.dirty = true; Graphics.effekseer?._makeContextCurrent?.(); }, () => { this.cache.delete(name); this.dirty = true; - EffectManager.onError(url); + const handlers = this.loadErrors.get(name); + this.loadErrors.delete(name); + if (handlers) { for (const failed of handlers) failed("effect load failed", url); } + else EffectManager.onError(url); }); if (effect && typeof effect._update === "function") { const update = effect._update, layer = this; @@ -3194,6 +3222,8 @@ Sprite_Animation.SceneLayer = { */ lost() { for (const sprite of this.live) { + try { sprite._companionHandle?.stop(); } catch (e) { /* lost context */ } + sprite._companionHandle = null; sprite._companionEffect = null; try { sprite._handle?.stop(); } catch (e) { /* nothing left to stop */ } sprite._handle = null; sprite._playing = false; @@ -3209,7 +3239,9 @@ Sprite_Animation.SceneLayer = { this.entry = null; this.cache.clear(); this.deadlines.clear(); + this.loadErrors.clear(); this.depth = null; + this.backdropCopy = null; globalThis.ReactorHdrOverlay?.scene?.lost(); }, restored() { @@ -3325,18 +3357,75 @@ Sprite_Animation.SceneLayer = { gl.clear(gl.DEPTH_BUFFER_BIT); } }, + /** + * Effekseer copies the bound framebuffer into its RGBA backdrop texture (copyTexSubImage2D). From the canvas WebGL + * refuses that copy (INVALID_OPERATION) when the context has no alpha channel, as PIXI creates it (alpha: false), + * so the backdrop stayed black and every distortion layer drew black at its opacity instead of bending the scene + * (BD2 Meltdown's sphere in battle, 2026-11-04: the right scene point, darkened by the layer's alpha). The canvas + * is blitted into an RGBA scratch target the size of the effect's square viewport (WebGL2's blit converts the + * format) and copied from there. The square reaches past the screen (it is twice the screen's height), so the + * scratch's off-screen margins repeat the screen's edge rows and columns, as UE clamps its distortion to the screen; + * read as zeros they showed as black bands where the layer pushed samples outwards. Filter targets are RGBA + * textures and copy as they are. + */ + captureBackground(gl, context, rect, framebuffer) { + if (!context.captureBackground) return; + const attrs = gl.getContextAttributes && gl.getContextAttributes(); + if (framebuffer || typeof gl.blitFramebuffer !== "function" || !attrs || attrs.alpha) { + context.captureBackground(rect.x, rect.y, rect.side, rect.side); + return; + } + const W = gl.drawingBufferWidth, H = gl.drawingBufferHeight, S = rect.side; + const x0 = Math.max(rect.x, 0), y0 = Math.max(rect.y, 0), x1 = Math.min(rect.x + S, W), y1 = Math.min(rect.y + S, H); + if (x1 <= x0 || y1 <= y0) { + context.captureBackground(rect.x, rect.y, S, S); + return; + } + let copy = this.backdropCopy; + if (!copy || copy.side !== S) { + if (copy) { gl.deleteFramebuffer(copy.fb); gl.deleteRenderbuffer(copy.rb); } + copy = this.backdropCopy = { fb: gl.createFramebuffer(), rb: gl.createRenderbuffer(), side: S }; + gl.bindRenderbuffer(gl.RENDERBUFFER, copy.rb); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA8, S, S); + gl.bindRenderbuffer(gl.RENDERBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, copy.fb); + gl.framebufferRenderbuffer(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, copy.rb); + } + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, copy.fb); + const ox = rect.x, oy = rect.y; + // [source x0, y0, x1, y1] on the screen -> [destination] in the square, stretched with NEAREST + const blit = (sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1) => { + if (dx1 > dx0 && dy1 > dy0) gl.blitFramebuffer(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, gl.COLOR_BUFFER_BIT, gl.NEAREST); + }; + const ix0 = x0 - ox, iy0 = y0 - oy, ix1 = x1 - ox, iy1 = y1 - oy; + blit(x0, y0, x1, y1, ix0, iy0, ix1, iy1); // the screen itself + blit(x0, y0, x0 + 1, y1, 0, iy0, ix0, iy1); // left margin: the left column + blit(x1 - 1, y0, x1, y1, ix1, iy0, S, iy1); // right margin + blit(x0, y0, x1, y0 + 1, ix0, 0, ix1, iy0); // bottom margin: the bottom row + blit(x0, y1 - 1, x1, y1, ix0, iy1, ix1, S); // top margin + blit(x0, y0, x0 + 1, y0 + 1, 0, 0, ix0, iy0); // corners + blit(x1 - 1, y0, x1, y0 + 1, ix1, 0, S, iy0); + blit(x0, y1 - 1, x0 + 1, y1, 0, iy1, ix0, S); + blit(x1 - 1, y1 - 1, x1, y1, ix1, iy1, S, S); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, copy.fb); + context.captureBackground(0, 0, S, S); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + }, /** * Draw `sprites`' handles through `view`, into a buffer `scale` times * the target's pixels whose origin is the target viewport's (the HDR - * light), or into the target itself (scale 1, `inTarget`); `capture`: - * the target is a texture, whose pixels distortion can copy. + * light), or into the target itself (scale 1, `inTarget`). */ - drawHandles(gl, renderer, view, sprites, scale, inTarget, capture) { + drawHandles(gl, renderer, view, sprites, scale, inTarget, handleOf = sprite => sprite._handle) { const context = this.context; const height = Graphics.height * view.ppu * scale; const side = Sprite_Animation.effekseerViewportSide(Graphics.height) * view.ppu * scale; gl.frontFace(view.flipped ? gl.CW : gl.CCW); for (const sprite of sprites) { + const handle = handleOf(sprite); + if (!handle?.exists) continue; const pos = sprite.effekseerScreenPosition(renderer); const at = view.project(pos.x, pos.y); const cx = inTarget ? at.x : (at.x - view.vp.x) * scale, cy = inTarget ? at.y : (at.y - view.vp.y) * scale; @@ -3344,30 +3433,29 @@ Sprite_Animation.SceneLayer = { const projection = Sprite_Animation.effekseerProjection(height, rect.side, sprite._mirror).slice(); // A target stored upside down: the effect is drawn upside down into it (its winding with it). if (view.flipped) for (const i of [1, 5, 9, 13]) projection[i] = -projection[i]; - // The scene beneath the effect, for its distortion layers: what this target holds now. Only from a - // texture: the canvas has no alpha (Graphics: backgroundAlpha 1), and GL refuses to copy its RGB pixels - // into Effekseer's RGBA background. - if (capture && context.captureBackground) context.captureBackground(rect.x, rect.y, rect.side, rect.side); + // The scene beneath the effect, for its distortion layers: what this target holds now. + if (inTarget) this.captureBackground(gl, context, rect, this.targetFramebuffer); context.setProjectionMatrix(projection); context.setCameraMatrix(this.camera); gl.viewport(rect.x, rect.y, rect.side, rect.side); context.beginDraw(); - context.drawHandle(sprite._handle); + context.drawHandle(handle); context.endDraw(); this.stats.draws++; } }, /** One animation's draw, from its RenderContainer during PIXI's render. */ draw(renderer, sprite) { - if (!this.context || sprite._reactorInScene || !sprite._handle || !sprite._handle.exists || !sprite._targets.length) return; + if (!this.context || sprite._reactorInScene || !(sprite._handle?.exists || sprite._companionHandle?.exists) || !sprite._targets.length) return; if (sprite._hdrActive) return this.drawHdr(renderer, sprite); const gl = renderer.gl, saved = this.save(gl, renderer), start = performance.now(); try { const view = this.view(renderer); + this.targetFramebuffer = saved.framebuffer; gl.bindVertexArray(null); this.withDepth(gl, renderer, saved); this.context._makeContextCurrent?.(); - this.drawHandles(gl, renderer, view, [sprite], 1, true, !!saved.framebuffer); + this.drawHandles(gl, renderer, view, [sprite], 1, true); } catch (e) { this.warnOnce(e); } finally { @@ -3385,7 +3473,9 @@ Sprite_Animation.SceneLayer = { const hdr = globalThis.ReactorHdrOverlay.scene; const sc = hdr.sidecar(sprite); const group = this.frame.filter(other => other !== sprite && other._hdrActive && other.parent === sprite.parent - && other._handle && other._handle.exists && hdr.sidecar(other) && hdr.sidecar(other).grade === sc.grade); + && other._handle && other._handle.exists && hdr.sidecar(other) && hdr.sidecar(other).grade === sc.grade + && hdr.sidecar(other).gradeB === sc.gradeB && hdr.intensity(other) === hdr.intensity(sprite) + && hdr.gradeMix?.(other) === hdr.gradeMix?.(sprite)); group.unshift(sprite); for (const member of group) this.drawn.add(member); const gl = renderer.gl, saved = this.save(gl, renderer), start = performance.now(); @@ -3395,10 +3485,21 @@ Sprite_Animation.SceneLayer = { const R = hdr.renderer(gl); gl.bindVertexArray(null); if (!R.ensure(Math.max(1, Math.round(view.vp.w * scale)), Math.max(1, Math.round(view.vp.h * scale)))) throw Error("no HDR targets on PIXI's context"); + gl.bindFramebuffer(gl.FRAMEBUFFER, saved.framebuffer); + this.targetFramebuffer = saved.framebuffer; + this.withDepth(gl, renderer, saved); + this.context._makeContextCurrent?.(); + this.drawHandles(gl, renderer, view, group, 1, true, member => member._companionHandle); R.begin(); + try { + gl.colorMask(false, false, false, false); + gl.depthMask(true); + this.drawHandles(gl, renderer, view, group, scale, false, + member => hdr.sidecar(member).companionOccludes !== false ? member._companionHandle : null); + } finally { gl.colorMask(true, true, true, true); } this.context._makeContextCurrent?.(); this.drawHandles(gl, renderer, view, group, scale, false); - R.post(Object.assign(hdr.settings(sc), { + R.post(Object.assign(hdr.settings(sc, sprite._effectFrame), { framebuffer: saved.framebuffer, // The bloom's radii are fractions of the game screen's width, in the light's pixels. bloomWidth: Graphics.width * view.ppu * scale, @@ -3427,10 +3528,10 @@ Sprite_Animation.prototype._render = function(renderer) { // Drawn by its own RenderContainer during PIXI's render; noted for this // frame so HDR animations of one grade can share a light pass. if (this._effekseerInScene) { - if (this._targets.length > 0 && this._handle && this._handle.exists) Sprite_Animation.SceneLayer.frame.push(this); + if (this._targets.length > 0 && (this._handle?.exists || this._companionHandle?.exists)) Sprite_Animation.SceneLayer.frame.push(this); return; } - if (this._targets.length > 0 && this._handle && this._handle.exists) { + if (this._targets.length > 0 && (this._handle?.exists || this._companionHandle?.exists)) { if (PIXI.TextureSource) { // v8: defer to post-render flush; just queue self. Actual Effekseer // draw runs in Graphics._onTick after _app.render() returns so it @@ -3460,7 +3561,7 @@ Sprite_Animation.prototype._render = function(renderer) { // page-load. Confirms the overlay canvas exists in the DOM, that we have its // WebGL1 context, and that Effekseer actually writes pixels to it. Reset via -Sprite_Animation.prototype._doEffekseerDraw = function(renderer, composited) { +Sprite_Animation.prototype._doEffekseerDraw = function(renderer, composited, handle = this._handle) { if (this._reactorInScene) return; // Draws to the Effekseer overlay canvas's WebGL1 context (Graphics._effekseerGL). // The overlay canvas sits absolutely positioned over the game canvas with @@ -3468,7 +3569,7 @@ Sprite_Animation.prototype._doEffekseerDraw = function(renderer, composited) { // of the v8-rendered scene. This bypasses v8/WebGL2 entirely for Effekseer. // Called from Sprite_Animation.renderActive after the overlay has been // cleared once for this frame. - if (!(this._targets.length > 0 && this._handle && this._handle.exists)) { + if (!(this._targets.length > 0 && handle && handle.exists)) { return; } const efxGL = Graphics._effekseerGL; @@ -3487,7 +3588,7 @@ Sprite_Animation.prototype._doEffekseerDraw = function(renderer, composited) { this.setCameraMatrix(renderer); this.setViewport(renderer); Graphics.effekseer.beginDraw(); - Graphics.effekseer.drawHandle(this._handle); + Graphics.effekseer.drawHandle(handle); Graphics.effekseer.endDraw(); Graphics.settleEffekseerState(); this.resetViewport(renderer); diff --git a/template/Demo/js/reactor_3d_effects.js b/template/Demo/js/reactor_3d_effects.js index e11df66d..640bd317 100644 --- a/template/Demo/js/reactor_3d_effects.js +++ b/template/Demo/js/reactor_3d_effects.js @@ -785,11 +785,16 @@ Reactor3D.stopVideoEffect = function(effect, character, holder) { * to the anchor's screen position every frame. Without a scene to project * through (a flat map) the animation plays on the character as before. */ +Reactor3D.anchoredEffectKey = function(effect) { + return effect.name || "#" + effect.animation; +}; + Reactor3D.spawnAnchoredAnimation = function(effect, character, holder) { const spriteset = typeof SceneManager !== "undefined" && SceneManager._scene ? SceneManager._scene._spriteset : null; const animation = typeof $dataAnimations !== "undefined" ? $dataAnimations[effect.animation] : null; if (!spriteset || !animation || !character) return; + if (holder && holder.refusedEffects && holder.refusedEffects.has(this.anchoredEffectKey(effect))) return; const object = holder && holder.object; if (!object || !spriteset._effectsContainer || !spriteset.createAnimationSprite) { if (typeof $gameTemp !== "undefined" && $gameTemp.requestAnimation) $gameTemp.requestAnimation([character], effect.animation); @@ -929,7 +934,7 @@ Reactor3D.GpuEffects = { try { renderer.resetState(); context = effekseer.createContext(); - context.init(gl); + context.init(gl, typeof Graphics !== 'undefined' ? Graphics.effekseerContextSettings : undefined); // This pass owns GL until it invalidates Three/PIXI's caches below. context.setRestorationOfStatesFlag(false); return { renderer, gl, context, samples, cache: new Map(), targets: new Set(), disposed: false, loading: 0 }; @@ -2084,7 +2089,10 @@ Reactor3D.updateAnchoredAnimations = function(holder) { if (!entry.sprite.parent) { if (entry.standIn.parent) entry.standIn.parent.removeChild(entry.standIn); if (entry.fx3d) this.EffekseerScene.stop(entry.fx3d); - if (entry.loop && !entry.restarted && holder.object) restart.push(entry); + // An effect the game refuses (a -hdr file without a valid sidecar) is not tried again: + // a loop or a live trigger would respawn it, and warn, every frame. + if (entry.sprite._hdrRefused) (holder.refusedEffects || (holder.refusedEffects = new Set())).add(this.anchoredEffectKey(entry.effect)); + else if (entry.loop && !entry.restarted && holder.object) restart.push(entry); continue; } this.placeStandIn(holder, entry.effect, entry.standIn); diff --git a/template/Demo/js/reactor_battle_presentation.js b/template/Demo/js/reactor_battle_presentation.js index 155d17a0..dace2d01 100644 --- a/template/Demo/js/reactor_battle_presentation.js +++ b/template/Demo/js/reactor_battle_presentation.js @@ -126,7 +126,7 @@ // Where each battler's posed parts stand, so a pose step starts from // the last one and the motion after a pose brings the parts home. const media=[],poseState=new Map(); - const adapter={context:{homes,target:homes.target,direction:homes.target&&homes.user&&homes.target.x0){ - const tickets=[],flat=[]; - for(const battler of chosen.filter(Boolean)){const ticket=room?.playAnimation(ss.findTargetSprite(battler)?._reactorRoomKey,step.animationId,step.animationTransform);if(ticket)tickets.push(ticket);else flat.push(battler);} - if(flat.length){ + if(root.$dataAnimations&&!root.$dataAnimations[step.animationId]){const ticket={kind:'animation',targets:[],isPlaying:()=>false,cancel(){}};media.push(ticket);return ticket;} + const targetsList=chosen.filter(Boolean),tickets=[],flat=[]; + for(const battler of targetsList){const ticket=room?.playAnimation(ss?.findTargetSprite(battler)?._reactorRoomKey,step.animationId,step.animationTransform);if(ticket){ticket.kind='animation';ticket.targets=[battler];tickets.push(ticket);}else flat.push(battler);} + if(flat.length&&root.$gameTemp?.requestAnimation){ const before=new Set($gameTemp._animationQueue||[]);$gameTemp.requestAnimation(flat,step.animationId); for(const request of ($gameTemp._animationQueue||[]).filter(r=>!before.has(r))){ - const created=Date.now(),ticket={pending:true,sprites:[],transform:{...step.animationTransform},room, - isPlaying(){return this.pending?Date.now()-created<15000:this.sprites.some(s=>s.isPlaying());}, - cancel(){this.pending=false;const i=$gameTemp._animationQueue.indexOf(request);if(i>=0){$gameTemp._animationQueue.splice(i,1);for(const b of request.targets)b.endAnimation?.();}for(const sprite of this.sprites)if(ss._animationSprites?.includes(sprite))ss.removeAnimation(sprite);}}; + const created=Date.now(),reqTargets=Array.isArray(request.targets)?request.targets:flat,ticket={kind:'animation',targets:reqTargets,pending:true,sprites:[],transform:{...step.animationTransform},room, + isPlaying(){ + if(this.pending){ + if(root.$gameTemp?._animationQueue&&!root.$gameTemp._animationQueue.includes(request)){this.pending=false;return false;} + if(this.targets.length&&this.targets.every(b=>b?.isDead?.()))return false; + return Date.now()-created<15000; + } + return this.sprites.some(s=>P.isSequenceSpritePlaying(s,ss)); + }, + cancel(){this.pending=false;const queue=root.$gameTemp?._animationQueue,i=queue?queue.indexOf(request):-1;if(i>=0){queue.splice(i,1);for(const b of request.targets)b.endAnimation?.();}for(const sprite of this.sprites){if(ss?._animationSprites?.includes(sprite)&&ss.removeAnimation)ss.removeAnimation(sprite);sprite._playing=false;sprite._duration=0;}}}; request._reactorSequenceMedia=ticket;tickets.push(ticket); } } - const ticket={isPlaying:()=>tickets.some(t=>t.isPlaying()),cancel:()=>tickets.forEach(t=>t.cancel?.())};media.push(ticket);return ticket; + const ticket={kind:'animation',targets:targetsList,isPlaying:()=>tickets.some(t=>t.isPlaying()),cancel:()=>tickets.forEach(t=>t.cancel?.())};media.push(ticket);return ticket; } else if(step.type==='motion')for(const battler of chosen.filter(Boolean)){ // A part pose is played by rules made for this step from @@ -381,6 +389,7 @@ }; const appearance=new Map(),spriteKeys=new Map();for(const [key,sprite] of Object.entries(roles))if(sprite&&!spriteKeys.has(sprite))spriteKeys.set(sprite,key); const tween=(sprite,key,to,duration,start,apply,from)=>{effects.push({sprite,key,from,to,start,end:start+duration,apply});}; + const liftHeight=(effect,at)=>{const t=Math.min(1,Math.max(0,(at-effect.start)/Math.max(1,effect.end-effect.start)));return effect.kind==='jump'?effect.from+(t>=1?0:Math.sin(Math.PI*t)*effect.height):effect.kind==='leap'?effect.from+effect.height*(1-(1-t)*(1-t)):effect.kind==='float'?effect.from+effect.height*t:effect.from+(effect.height-effect.from)*t;}; const layerPrefix='extra:sequence-layer:'+(P._layerSerial=(P._layerSerial||0)+1)+':'; const destroyLayer=(key,owners=[])=>{const entry=layers.get(key)||owners.map(o=>o?._rrLayers?.get(key)).find(Boolean);if(entry){if(entry.roomKey)room?.remove(entry.roomKey);entry.graphic.removeFromParent();entry.graphic.destroy();layers.delete(key);entry.owner?._rrLayers?.delete(key);}}; const pending=()=>({blocking:true,isPlaying:()=>adapter.pendingImpact}); @@ -481,12 +490,37 @@ if(step.type==='opacity')tween(sprite,'opacity',Math.max(0,Math.min(255,step.opacity)),step.duration,start,v=>sprite.opacity=v,sprite.opacity); else if(step.type==='tint')tween(sprite,'tone',[step.red,step.green,step.blue,step.gray],step.duration,start,v=>main.setColorTone?.(v),main.getColorTone?.()||[0,0,0,0]); else if(step.type==='whiten'){main.setBlendColor?.([255,255,255,160]);tween(sprite,'whiten',0,Math.max(1,step.duration),start,v=>main.setBlendColor?.([255,255,255,v]),160);} - else{effects.push({lift:sprite,kind:step.type,height:step.height,start,end:start+Math.max(1,step.duration),from:sprite._rrLift||0});} + else{for(const e of effects)if(e.lift===sprite)sprite._rrLift=liftHeight(e,start);effects.push({lift:sprite,kind:step.type,height:step.height,start,end:start+Math.max(1,step.duration),from:sprite._rrLift||0});} }return; } if(step.type==='motion'&&(step.motionIndex||step.motionFrames||step.motionSpeed||step.motionLoop&&step.motionLoop!=='default'))for(const sprite of sprites){sprite._rrMotionOverride={...(step.motionIndex?{index:step.motionIndex-1}:{}),...(step.motionFrames?{frames:step.motionFrames}:{}),...(step.motionSpeed?{speed:step.motionSpeed}:{}),...(step.motionLoop&&step.motionLoop!=='default'?{loop:step.motionLoop==='loop'?true:step.motionLoop==='hold'?'once':false}:{}),name:step.motion};} else if(step.type==='motion')for(const sprite of sprites)delete sprite._rrMotionOverride; - if(step.type==='wait'&&step.waitFor&&step.waitFor!=='frames')return {blocking:true,isPlaying:()=>sprites.some(s=>step.waitFor==='move'?s.isMoving?.():step.waitFor==='animation'?s.isAnimationPlaying?.():step.waitFor==='popup'?s._damages?.length:step.waitFor==='effecting'?s.isEffecting?.():step.waitFor==='motion'?s._motion&&!s._motion.loop&&s._pattern<2:false)}; + if(step.type==='wait'&&step.waitFor&&step.waitFor!=='frames'){ + let cancelled=false; + return { + blocking:true, + cancel(){cancelled=true;}, + isPlaying(){ + if(cancelled)return false; + const activeTargets=step.filter&&step.filter!=='all'?choose(step):chosen; + const activeSprites=activeTargets.map(b=>ss?.findTargetSprite(b)).filter(Boolean); + if(step.waitFor==='animation'){ + if(step.filter==='alive'&&!activeTargets.length)return false; + const animMedia=(adapter.media||[]).filter(m=>m.kind==='animation'); + const hasRoleMatch=animMedia.some(m=>m.targets?.some(t=>activeTargets.includes(t))); + if(animMedia.some(m=>m.isPlaying()&&(!m.targets?.length||m.targets.some(t=>activeTargets.includes(t))||(step.role==='user'&&!hasRoleMatch&&!(step.filter==='alive'&&m.targets.every(t=>t?.isDead?.()))))))return true; + if((ss?._animationSprites||[]).some(a=>P.isSequenceSpritePlaying(a,ss)&&((a.targetObjects||[]).some(t=>activeTargets.includes(t))||(a._targets||[]).some(t=>activeSprites.includes(t)))))return true; + if((root.$gameTemp?._animationQueue||[]).some(r=>(!root.$dataAnimations||root.$dataAnimations[r.animationId])&&(r.targets||[]).some(t=>activeTargets.includes(t)&&!t?.isDead?.())))return true; + return activeSprites.some(s=>!(s._battler||s._actor||s._enemy)?.isDead?.()&&s.isAnimationPlaying?.()); + } + if(step.waitFor==='move')return activeSprites.some(s=>!(s._battler||s._actor||s._enemy)?.isDead?.()&&s.isMoving?.()); + if(step.waitFor==='motion')return activeSprites.some(s=>!(s._battler||s._actor||s._enemy)?.isDead?.()&&s._motion&&!s._motion.loop&&s._pattern<2); + if(step.waitFor==='popup')return activeSprites.some(s=>s._damages?.length); + if(step.waitFor==='effecting')return activeSprites.some(s=>s.isEffecting?.()); + return false; + } + }; + } if(step.type==='animation'&&step.animationSource&&step.animationSource!=='id'){const id=action?.item()?.animationId??0;raw={...raw,animationId:step.animationSource==='weapon'||id===-1?subject.attackAnimationId1?.()||0:Math.max(0,id)};} return original.cue(raw,start); }; @@ -499,25 +533,32 @@ }}; if(room)(room.sequenceVisualUpdates||=new Set()).add(updateRoomLayers); adapter.pose=(positions,time)=>{ - frame=time;original.pose(positions,time); + frame=time; + if(!room)for(const sprite of appearance.keys())if(sprite._rrAppliedLift){sprite.y+=sprite._rrAppliedLift;if(Number.isFinite(sprite._offsetY))sprite._offsetY+=sprite._rrAppliedLift;sprite._rrAppliedLift=0;} + original.pose(positions,time); for(const effect of effects){ if(effect.balloon){effect.balloon.update();continue;} if(effect.direction){const sprite=effect.direction,old=saved.get(sprite);sprite.scale.x=Math.abs(old.scaleX)*(effect.facing<0?1:-1);if(room&&!room.models.has(sprite._reactorRoomKey))sprite._reactorRoomPosition.facing=effect.facing*90;continue;}// A room's model keeps the yaw the pose gave it; a picture can only face left or right. + if(effect.lift){effect.lift._rrLift=liftHeight(effect,time);continue;} const t=Math.min(1,Math.max(0,(time-effect.start)/Math.max(1,effect.end-effect.start))); - if(effect.lift){const h=effect.kind==='jump'?effect.from+Math.sin(Math.PI*t)*effect.height:effect.kind==='leap'?effect.from+effect.height*(1-(1-t)*(1-t)):effect.kind==='float'?effect.from+effect.height*t:effect.from+(effect.height-effect.from)*t;effect.lift._rrLift=h;continue;} const v=Array.isArray(effect.to)?effect.to.map((n,i)=>effect.from[i]+(n-effect.from[i])*t):effect.from+(effect.to-effect.from)*t;effect.apply(v); } - for(const sprite of appearance.keys())if(sprite._rrLift){if(room)sprite._reactorRoomPosition.z=(positions[spriteKeys.get(sprite)]?.z||0)+sprite._rrLift;else sprite.y-=sprite._rrLift*48;} + for(const sprite of appearance.keys()){ + if(room){if(sprite._rrLift)sprite._reactorRoomPosition.z=(positions?.[spriteKeys.get(sprite)]?.z||0)+sprite._rrLift;continue;} + const lift=(sprite._rrLift||0)*48; + if(lift){sprite.y-=lift;if(Number.isFinite(sprite._offsetY))sprite._offsetY-=lift;} + sprite._rrAppliedLift=lift; + } visuals.pose(time); for(const entry of layers.values()){const {graphic,owner,step}=entry;graphic.opacity=entry.opacity;graphic.rotation=(step.angle+(time-entry.start)*step.spin)*Math.PI/180;graphic.scale?.set(step.scale);if(entry.type==='plane'){graphic.origin.x=(time-entry.start)*step.scrollX;graphic.origin.y=(time-entry.start)*step.scrollY;}else if(entry.hosted){graphic.x=entry.x;graphic.y=entry.y;}else{graphic.x=(owner?.x||0)+entry.x;graphic.y=(owner?.y||0)+entry.y;}} }; - adapter.cleanup=cancelled=>{try{original.cleanup(cancelled);}finally{ + adapter.cleanup=cancelled=>{try{if(!room)for(const sprite of appearance.keys())if(sprite._rrAppliedLift){sprite.y+=sprite._rrAppliedLift;if(Number.isFinite(sprite._offsetY))sprite._offsetY+=sprite._rrAppliedLift;sprite._rrAppliedLift=0;}original.cleanup(cancelled);}finally{ visuals.cleanup();room?.sequenceVisualUpdates?.delete(updateRoomLayers); for(const fn of restore.reverse())fn();for(const key of [...layers.keys()])if(!(stateOnly&&layers.get(key).hosted))destroyLayer(key); for(const [sprite,old] of appearance){const main=sprite._mainSprite||sprite; // A dead enemy keeps what its collapse left (a few points of opacity, a blend colour): a reaction played over the collapse must not stand it back up. const gone=sprite._battler&&typeof sprite._battler.isDead==='function'&&sprite._battler.isDead()&&typeof sprite._battler.isEnemy==='function'&&sprite._battler.isEnemy(); - if(!gone){sprite.opacity=old.opacity;if(old.tone)main.setColorTone?.(old.tone);if(old.blend)main.setBlendColor?.(old.blend);}sprite._rrHeldPose=old.pose;sprite._rrGraphicMotion=old.motion;sprite._rrLift=0;delete sprite._rrFacing;delete sprite._rrMotionOverride;sprite._homeX=old.homeX;sprite._homeY=old.homeY;} + if(!gone){sprite.opacity=old.opacity;if(old.tone)main.setColorTone?.(old.tone);if(old.blend)main.setBlendColor?.(old.blend);}sprite._rrHeldPose=old.pose;sprite._rrGraphicMotion=old.motion;sprite._rrLift=0;sprite._rrAppliedLift=0;delete sprite._rrFacing;delete sprite._rrMotionOverride;sprite._homeX=old.homeX;sprite._homeY=old.homeY;} }}; return adapter; }; @@ -785,11 +826,19 @@ } if(sprite._stateIconSprite)sprite._stateIconSprite.y=bounds.y-room.project(sprite._reactorRoomPosition).y-20; }; + P.isSequenceSpritePlaying=function(sprite,ss){ + if(!sprite||sprite.destroyed||sprite._rrAssetError)return false; + if(sprite._bitmap1?.isError?.()||sprite._bitmap2?.isError?.()){sprite._rrAssetError=true;sprite._playing=false;sprite._duration=0;return false;} + if(ss?._animationSprites&&!ss._animationSprites.includes(sprite))return false; + if(sprite._targets?.length&&sprite._targets.every(t=>t?.destroyed))return false; + return !!sprite.isPlaying?.(); + }; P.installSequenceAnimations=function(){ if(!root.Spriteset_Base)return; const proto=Spriteset_Base.prototype,create=proto.createAnimation,busy=proto.isAnimationPlaying; proto.createAnimation=function(request){ const ticket=request._reactorSequenceMedia;if(!ticket)return create.call(this,request); + if(root.$dataAnimations&&!root.$dataAnimations[request.animationId]){ticket.pending=false;ticket.sprites=[];return;} const before=new Set(this._animationSprites); try{return create.call(this,request);}finally{ ticket.pending=false;ticket.sprites=this._animationSprites.filter(s=>!before.has(s)); @@ -797,6 +846,14 @@ sprite._reactorSequenceMedia=ticket; const t=ticket.transform,scale=t.scale??1; sprite._animation={...sprite._animation,scale:(sprite._animation.scale??100)*scale}; + const effName=sprite._animation?.effectName; + if(effName&&!sprite._animation?.frames){ + const fail=()=>{sprite._rrAssetError=true;sprite._playing=false;}; + const layer=root.Sprite_Animation?.SceneLayer; + if(sprite._effect&&layer?.load&&layer.cache?.get?.(effName)===sprite._effect)layer.load(effName,fail); + else if(sprite._effect&&root.EffectManager?.load&&root.EffectManager.makeUrl&&root.EffectManager._cache?.[root.EffectManager.makeUrl(effName)]===sprite._effect)root.EffectManager.load(effName,fail); + } + if(sprite._bitmap1?.isError?.()||sprite._bitmap2?.isError?.()){sprite._rrAssetError=true;sprite._playing=false;sprite._duration=0;} const offset=()=>{ const points=(sprite.targetObjects||[]).map(b=>this.findTargetSprite(b)?._reactorRoomPosition).filter(Boolean); if(ticket.room&&points.length){let x=0,y=0;for(const p of points){const a=ticket.room.project(p),b=ticket.room.project({x:p.x+(t.x||0),y:p.y+(t.y||0),z:(p.z||0)+(t.z||0)});x+=b.x-a.x;y+=b.y-a.y;}return {x:x/points.length,y:y/points.length};} diff --git a/template/Demo/js/reactor_core.js b/template/Demo/js/reactor_core.js index 2bd05cff..93332566 100644 --- a/template/Demo/js/reactor_core.js +++ b/template/Demo/js/reactor_core.js @@ -3619,6 +3619,43 @@ Graphics.blitSceneBehindEffects = function() { return drew; }; +/** + * What the Effekseer contexts that play effects are initialized with. + * + * Effekseer keeps a fixed pool of particle instances per context (its own + * default is 4000). When the pool is full a new particle is simply not made: + * no thinning, no error. The layers that spawn first keep everything and the + * later ones lose particles, and every effect playing in that context shares + * the pool (an HDR effect and its companion, several targets, other + * animations). A pool reserves about 5 KB of Effekseer's heap per instance + * at init (4000: ~20 MB, 8000: ~40 MB, 16000: ~80 MB per context). + * `squareMaxCount` is the sprite vertex buffer; it scales with the pool. + * + * The in-scene context (Sprite_Animation.SceneLayer) and the 3D map's + * effects context (Reactor3D.GpuEffects) take these, and both are made at + * their first use. The overlay context is made at boot, because plugins use + * `Graphics.effekseer` directly; it takes these only when it is the one + * drawing screen animations (see `_overlayEffekseerSettings`). While the + * in-scene layer is active the overlay only loads effects, so it keeps + * Effekseer's default pool and does not reserve the memory. + * A plugin can change these before the first context is created. + */ +Graphics.effekseerContextSettings = { instanceMaxCount: 16000, squareMaxCount: 40000 }; + +/** + * The overlay context's init settings: Effekseer's default pool (undefined) + * while screen animations play in the scene, the large pool when the overlay + * draws them itself (in-scene off, a WebGL1 or WebGPU renderer, no + * RenderContainer). Anything it cannot tell means the large pool. + */ +Graphics._overlayEffekseerSettings = function() { + try { + const layer = typeof Sprite_Animation !== "undefined" ? Sprite_Animation.SceneLayer : null; + if (layer && typeof layer.active === "function" && layer.active()) return undefined; + } catch (e) {} + return this.effekseerContextSettings; +}; + Graphics._createEffekseerContext = function() { if (!window.effekseer) return; try { @@ -3650,7 +3687,7 @@ Graphics._createEffekseerContext = function() { this._effekseerGL = efxGL; this._effekseer = effekseer.createContext(); if (this._effekseer) { - this._effekseer.init(efxGL); + this._effekseer.init(efxGL, this._overlayEffekseerSettings()); // ...but only until the first draw has re-asserted it. Reading // the state back is a synchronous round trip to the GPU process // per draw (15 ms a frame measured beside a 3D map), and this @@ -3709,7 +3746,7 @@ Graphics._restoreEffekseerContext = function() { try { const context = effekseer.createContext(); if (!context) return; - context.init(gl); + context.init(gl, this._overlayEffekseerSettings()); this._effekseer = context; if (typeof EffectManager !== "undefined") EffectManager._cache = {}; this.rearmEffekseerState(); diff --git a/template/Demo/js/reactor_fight_camera.js b/template/Demo/js/reactor_fight_camera.js index b5e970d4..d6793880 100644 --- a/template/Demo/js/reactor_fight_camera.js +++ b/template/Demo/js/reactor_fight_camera.js @@ -1613,7 +1613,10 @@ if (scale >= 1 || !player || typeof player.update !== "function") return updateEffekseer.call(this); const own = Object.prototype.hasOwnProperty.call(player, "update"), update = player.update; player.update = function(frames) { return update.call(this, (frames || 1) * scale); }; - try { return updateEffekseer.call(this); } finally { if (own) player.update = update; else delete player.update; } + try { return updateEffekseer.call(this); } finally { + this._effekseerStep = (this._effekseerStep || 0) * scale; + if (own) player.update = update; else delete player.update; + } }; } diff --git a/template/Demo/js/reactor_hdr_overlay.js b/template/Demo/js/reactor_hdr_overlay.js index e5d5ca5d..b065c34f 100644 --- a/template/Demo/js/reactor_hdr_overlay.js +++ b/template/Demo/js/reactor_hdr_overlay.js @@ -17,19 +17,55 @@ "void main(){ gl_FragColor = 0.25 * (texture2D(uTex, vUv + uTexel * vec2(-0.5,-0.5)) + texture2D(uTex, vUv + uTexel * vec2(0.5,-0.5))" + " + texture2D(uTex, vUv + uTexel * vec2(-0.5,0.5)) + texture2D(uTex, vUv + uTexel * vec2(0.5,0.5))); }"; // the first downsample with UE 4's bloom setup threshold (PostProcessBloomSetup): light below the threshold in - // luminance does not bloom, ramping to full over 2 units above it + // luminance does not bloom, ramping to full over 2 units above it. With uUnity, Unity post-processing's bloom + // prefilter instead: each channel clamped to uClampMax, then a soft-knee threshold on the brightest channel const FS_SETUP = "precision highp float; varying vec2 vUv; uniform sampler2D uTex; uniform vec2 uTexel; uniform float uThreshold;" + + "uniform float uUnity; uniform float uKnee; uniform float uClampMax;" + "void main(){ vec4 c = 0.25 * (texture2D(uTex, vUv + uTexel * vec2(-0.5,-0.5)) + texture2D(uTex, vUv + uTexel * vec2(0.5,-0.5))" + " + texture2D(uTex, vUv + uTexel * vec2(-0.5,0.5)) + texture2D(uTex, vUv + uTexel * vec2(0.5,0.5)));" + - " float lum = dot(c.rgb, vec3(0.3, 0.59, 0.11)); c.rgb *= clamp((lum - uThreshold) * 0.5, 0.0, 1.0);" + + " if (uUnity > 0.5) { c.rgb = min(c.rgb, vec3(uClampMax)); float br = max(c.r, max(c.g, c.b));" + + " float sf = clamp(br - uThreshold + uKnee, 0.0, 2.0 * uKnee); sf = sf * sf / (4.0 * uKnee + 0.0001);" + + " c.rgb *= max(br - uThreshold, sf) / max(br, 0.0001); }" + + " else { float lum = dot(c.rgb, vec3(0.3, 0.59, 0.11)); c.rgb *= clamp((lum - uThreshold) * 0.5, 0.0, 1.0); }" + " gl_FragColor = c; }"; + // Unity post-processing's bloom prefilter, when a sidecar gives one + function prefilterOf(p) { + return p ? {threshold: p.threshold, knee: p.knee, clamp: p.clamp === undefined ? 65472 : p.clamp} : null; + } // separable Gaussian, sigma in texels (<= ~5), +-3 sigma const FS_BLUR = "precision highp float; varying vec2 vUv; uniform sampler2D uTex; uniform vec2 uStep; uniform float uSigma;" + "void main(){ vec4 s = vec4(0.0); float w = 0.0; for (int i = -16; i <= 16; i++) { float x = float(i);" + " if (abs(x) > 3.0 * uSigma + 0.5) continue; float k = exp(-0.5 * x * x / (uSigma * uSigma));" + " s += k * texture2D(uTex, vUv + uStep * x); w += k; } gl_FragColor = s / w; }"; - function valid(s) { + // bloom.intensityKeys: [[frame, intensity], ...] on the effect's own clock (60 frames a second at speed 100), + // frames increasing, played as straight lines between keys and held before the first and after the last + function keysValid(k) { + return Array.isArray(k) && k.length > 0 && k.every((key, i) => Array.isArray(key) && key.length === 2 && + Number.isFinite(key[0]) && Number.isFinite(key[1]) && key[1] >= 0 && (i === 0 || key[0] > k[i - 1][0])); + } + // The bloom intensity at an effect frame: the keys when the sidecar has them, bloom.intensity otherwise. + function bloomIntensity(bloom, frame) { + const k = bloom.intensityKeys; + return k ? keyedValue(k, frame) : bloom.intensity; + } + // gradeB + gradeKeys: a second grade over part of the effect, the sidecar's `grade` at weight 0 and `gradeB` at + // weight 1, [[frame, weight 0..1], ...] on the same clock as bloom.intensityKeys. Without gradeKeys `grade` plays. + function gradeMix(sc, frame) { + return sc && sc.gradeKeys ? Math.min(1, Math.max(0, keyedValue(sc.gradeKeys, frame))) : 0; + } + function keyedValue(k, frame) { + const f = Number.isFinite(frame) ? frame : 0; + if (f <= k[0][0]) return k[0][1]; + for (let i = 1; i < k.length; i++) { + if (f > k[i][0]) continue; + const [f0, v0] = k[i - 1], [f1, v1] = k[i]; + return v0 + (v1 - v0) * (f - f0) / (f1 - f0); + } + return k[k.length - 1][1]; + } + + function valid(s, effectName) { if (!s || s.version !== 1 || s.gradeInput !== "hdr" || typeof s.grade !== "string" || !/\bhdr\b/.test(s.grade) || !/\btmOut\b/.test(s.grade) || typeof s.fallback !== "string" || !s.fallback || !s.bloom || !Array.isArray(s.bloom.sizes) || !Array.isArray(s.bloom.tints) || @@ -38,7 +74,18 @@ !s.bloom.tints.every(x => Number.isFinite(x) && x >= 0) || !Number.isFinite(s.bloom.intensity) || s.bloom.intensity < 0 || !Number.isFinite(s.bloom.radiusScale) || s.bloom.radiusScale <= 0 || - (s.bloom.threshold !== undefined && !Number.isFinite(s.bloom.threshold))) throw Error("invalid HDR sidecar"); + (s.bloom.threshold !== undefined && !Number.isFinite(s.bloom.threshold)) || + (s.bloom.intensityKeys !== undefined && !keysValid(s.bloom.intensityKeys)) || + (s.gradeB !== undefined && (typeof s.gradeB !== "string" || !/\bhdr\b/.test(s.gradeB) || !/\btmOut\b/.test(s.gradeB) || + !keysValid(s.gradeKeys) || !s.gradeKeys.every(k => k[1] <= 1))) || + (s.gradeKeys !== undefined && s.gradeB === undefined) || + (s.bloom.prefilter !== undefined && (!s.bloom.prefilter || typeof s.bloom.prefilter !== "object" || + !Number.isFinite(s.bloom.prefilter.threshold) || !Number.isFinite(s.bloom.prefilter.knee) || s.bloom.prefilter.knee < 0 || + (s.bloom.prefilter.clamp !== undefined && !(Number.isFinite(s.bloom.prefilter.clamp) && s.bloom.prefilter.clamp > 0))))) + throw Error("invalid HDR sidecar"); + if (s.companion !== undefined && (typeof s.companion !== "string" || !s.companion.trim() || /\.efkefc$/i.test(s.companion) || s.companion === s.fallback)) throw Error("invalid HDR companion"); + if (s.companionOccludes !== undefined && typeof s.companionOccludes !== "boolean") throw Error("invalid companionOccludes"); + if (effectName && s.companion && (resolveName(effectName, s.companion) === effectName || resolveName(effectName, s.companion) === resolveName(effectName, s.fallback))) throw Error("HDR companion must differ from effect and fallback"); return s; } @@ -86,15 +133,20 @@ } catch (e) { gl.deleteProgram(p); throw e; } finally { for (const shader of shaders) gl.deleteShader(shader); } } - function gradeProgram(grade) { - if (H.programs.has(grade)) return H.programs.get(grade); + function gradeProgram(grade, gradeB) { + const id = gradeB ? grade + "\n/*gradeB*/\n" + gradeB : grade; + if (H.programs.has(id)) return H.programs.get(id); + // Two grades: each in its own function (both declare tmOut and their temporaries), mixed by uGradeMix + const twoGrades = gradeB ? "vec3 rr_gradeA(vec3 hdr){\n" + grade + "\nreturn tmOut; }\n" + + "vec3 rr_gradeB(vec3 hdr){\n" + gradeB + "\nreturn tmOut; }\nuniform float uGradeMix;\n" : ""; + const body = gradeB ? "vec3 tmOut = mix(rr_gradeA(hdr), rr_gradeB(hdr), uGradeMix);" : grade; const fs = "precision highp float; varying vec2 vUv; uniform sampler2D uHdr; uniform sampler2D uG0; uniform sampler2D uG1;" + "uniform sampler2D uG2; uniform sampler2D uG3; uniform sampler2D uG4; uniform sampler2D uG5; uniform float uW[6];" + - "uniform float uDebug; uniform float uAlphaFromColor;" + + "uniform float uDebug; uniform float uAlphaFromColor;" + twoGrades + "void main(){ vec3 hdr = texture2D(uHdr, vUv).rgb;" + " hdr += uW[0] * texture2D(uG0, vUv).rgb + uW[1] * texture2D(uG1, vUv).rgb + uW[2] * texture2D(uG2, vUv).rgb" + " + uW[3] * texture2D(uG3, vUv).rgb + uW[4] * texture2D(uG4, vUv).rgb + uW[5] * texture2D(uG5, vUv).rgb;" + - " hdr = max(hdr, vec3(0.0));" + "\n" + grade + "\n" + + " hdr = max(hdr, vec3(0.0));" + "\n" + body + "\n" + // Alpha from colour: for a premultiplied canvas the page blends // over what lies behind it, with no backdrop in this buffer. The // screen the game does ignores coverage, so dark quads stay clear. @@ -103,7 +155,7 @@ " gl_FragColor = uDebug > 0.0 ? vec4(clamp(texture2D(uHdr, vUv).rgb / uDebug, 0.0, 1.0), 1.0) : vec4(rr_o, rr_a); }"; const program = compile(VS, fs); - H.programs.set(grade, program); + H.programs.set(id, program); return program; } function tex(w, h, type) { @@ -246,7 +298,7 @@ gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } // Bloom the light buffer, grade it once, and screen it over the default - // framebuffer, or s.framebuffer. `s` is { bloom, bloomScale, threshold, coverage, + // framebuffer, or s.framebuffer. `s` is { bloom, bloomScale, threshold, prefilter, coverage, // debugScale, measureGpu, alphaFromColor, bloomWidth, pixelScale, framebuffer }; // the overlay sets none of the last four. function post(s, sc, out) { @@ -254,7 +306,7 @@ if (s.measureGpu) gl.finish(); const start = performance.now(); const SIZES = sc.bloom.sizes, TINTS = sc.bloom.tints; - H.comp = gradeProgram(sc.grade); + H.comp = gradeProgram(sc.grade, sc.gradeB); gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.disable(gl.SCISSOR_TEST); gl.disable(gl.STENCIL_TEST); gl.colorMask(true, true, true, true); gl.disable(gl.BLEND); @@ -270,9 +322,18 @@ // The threshold acts at the game's bloom setup resolution, half its screen. An effect drawn radiusScale // times larger than in the game covers that pixel with radiusScale of ours: level log2(radiusScale). // Every Gaussian reads that level or a coarser one, so all of the bloom is thresholded. A preview - // draws a game pixel as pixelScale of its own, which moves the level with it. - const setupLevel = Number.isFinite(s.threshold) ? + // draws a game pixel as pixelScale of its own, which moves the level with it. A Unity prefilter + // (s.prefilter, or the sidecar's own when a caller does not pass one) takes the threshold's place. + const pf = prefilterOf(s.prefilter !== undefined ? s.prefilter : sc.bloom && sc.bloom.prefilter); + const setupLevel = Number.isFinite(s.threshold) || pf ? Math.min(H.levels.length - 1, Math.max(0, Math.round(Math.log2(s.bloomScale * (s.pixelScale > 0 ? s.pixelScale : 1))))) : -1; + const setupUniforms = () => { + gl.uniform1f(H.setup.u.uUnity, pf ? 1 : 0); + if (!pf) { gl.uniform1f(H.setup.u.uThreshold, s.threshold); return; } + gl.uniform1f(H.setup.u.uThreshold, pf.threshold); + gl.uniform1f(H.setup.u.uKnee, pf.knee); + gl.uniform1f(H.setup.u.uClampMax, pf.clamp); + }; let base = H.main; if (setupLevel === 0) { if (!H.pre) H.pre = target(H.w, H.h, H.type, false); @@ -280,7 +341,7 @@ gl.useProgram(H.setup.p); bind(0, H.main.t, H.setup.u.uTex); gl.uniform2f(H.setup.u.uTexel, 0, 0); - gl.uniform1f(H.setup.u.uThreshold, s.threshold); + setupUniforms(); quad(H.setup, H.pre); base = H.pre; } @@ -291,7 +352,7 @@ gl.useProgram(prog.p); bind(0, src.t, prog.u.uTex); gl.uniform2f(prog.u.uTexel, 1 / src.w, 1 / src.h); - if (prog === H.setup) gl.uniform1f(prog.u.uThreshold, s.threshold); + if (prog === H.setup) setupUniforms(); quad(prog, H.levels[l]); } // six Gaussians, each blurred at the level where its sigma is 2-4 texels (never finer than the setup) @@ -336,6 +397,7 @@ gl.uniform1fv(H.comp.u.uW, weights.length ? weights : [0,0,0,0,0,0]); gl.uniform1f(H.comp.u.uDebug, s.debugScale || 0); gl.uniform1f(H.comp.u.uAlphaFromColor, s.alphaFromColor ? 1 : 0); + if (sc.gradeB) gl.uniform1f(H.comp.u.uGradeMix, s.gradeMix || 0); gl.enable(gl.BLEND); gl.blendEquation(gl.FUNC_ADD); gl.blendFunc(gl.ONE, s.coverage ? gl.ONE_MINUS_SRC_ALPHA : gl.ONE_MINUS_SRC_COLOR); @@ -376,7 +438,7 @@ get size() { return [H.w, H.h]; } }; } - window.ReactorHdrRenderer = { create: createRenderer, valid }; + window.ReactorHdrRenderer = { create: createRenderer, valid, bloomIntensity, gradeMix }; // ---- The game's adapter ------------------------------------------------ const params = {}; @@ -386,9 +448,12 @@ const api = window.ReactorHdrOverlay = { native: true, cache, stats: { groups: 0, draws: 0, postMs: 0 }, // Testing overrides still require a grade and a safe twin. overrides: Object.create(null) }; - function settings(sidecar) { - return Object.assign({ bloom: Number(params.bloomIntensity ?? sidecar.bloom.intensity), + // A sprite's settings at its effect frame (Sprite_Animation's _effectFrame). + function settings(sidecar, frame) { + return Object.assign({ bloom: Number(params.bloomIntensity ?? bloomIntensity(sidecar.bloom, frame)), + gradeMix: gradeMix(sidecar, frame), bloomScale: Number(params.bloomRadiusScale ?? sidecar.bloom.radiusScale), threshold: sidecar.bloom.threshold, + prefilter: sidecar.bloom.prefilter, debug: (params.debug === true || params.debug === "true") }, window.REACTOR_HDR || {}); } @@ -418,7 +483,7 @@ const timer = setTimeout(() => controller.abort(), 15000); entry.promise = fetch(url, {signal: controller.signal}) .then(r => { if (r.status === 404) return null; if (!r.ok) throw Error("sidecar HTTP " + r.status); return r.json(); }) - .then(s => { entry.sidecar = s && valid(s); }) + .then(s => { entry.sidecar = s && valid(s, name); }) .catch(e => { entry.error = String(e); console.warn("[ReactorHdrOverlay] " + name + ": " + e); }) .finally(() => { clearTimeout(timer); entry.ready = true; }); return entry; @@ -432,16 +497,52 @@ const a = sprite._animation || {}, e = sprite._hdrEntry; return e && e.sidecar || (forced(sprite) && api.overrides[a.effectName]) || null; } - // The context an effect is loaded into: the scene's for an in-scene sprite, the overlay's otherwise. - function load(sprite, name) { - return sprite._effekseerInScene ? Sprite_Animation.SceneLayer.load(name) : EffectManager.load(name); + // The context an effect is loaded into: the one the sprite plays in. + function load(sprite, name, onError) { + if (sprite._effekseerInScene) return Sprite_Animation.SceneLayer.load(name, onError); + return sprite._effectContext ? Reactor3D.GpuEffects.load(sprite._effectContext, name) : EffectManager.load(name, onError); } - function fallbackName(sprite, sc) { - const name = sprite._animation.effectName; - return sc.fallback.includes('/') ? sc.fallback : name.slice(0, name.lastIndexOf('/') + 1) + sc.fallback; + function resolveName(name, other) { + return other.includes('/') ? other : name.slice(0, name.lastIndexOf('/') + 1) + other; + } + function fallbackName(sprite, sc) { return resolveName(sprite._animation.effectName, sc.fallback); } + api.stopCompanion = function(sprite) { + try { sprite._companionHandle?.stop(); } catch (error) { /* lost WASM context */ } finally { sprite._companionHandle = null; sprite._companionEffect = null; } + }; + function companionFailure(sprite, reason) { + // A timed-out soft load must not strand a later scene in isReady(). + const effect = sprite._companionEffect, sc = sidecarFor(sprite); + if (effect && !effect.isLoaded && sc?.companion) { + const name = resolveName(sprite._animation.effectName, sc.companion); + if (sprite._effekseerInScene) { + const cache = Sprite_Animation.SceneLayer.cache; + if (cache?.get(name) === effect) cache.delete(name); + } else { + const url = EffectManager.makeUrl(name); + if (EffectManager._cache?.[url] === effect) delete EffectManager._cache[url]; + } + } + if (!sprite._companionWarned) { + sprite._companionWarned = true; + console.warn("[ReactorHdrOverlay] " + sprite._animation.effectName + ": companion unavailable (" + reason + "); selecting twin"); + } + scene.fallBack(sprite); + sprite._hdrSelected = true; + } + function companionReady(sprite) { + if (!sprite._hdrActive || !sprite._companionEffect) return true; + if (sprite._companionLoadError) { companionFailure(sprite, sprite._companionLoadError); return true; } + const entry = sprite._companionEntry; + if (!entry.ready) return false; + if (entry.sidecar || entry.error) { companionFailure(sprite, "companion has HDR metadata"); return true; } + if (sprite._companionEffect.isLoaded) return true; + if (performance.now() >= sprite._companionDeadline) { + companionFailure(sprite, "load failed or timed out"); return true; + } + return false; } api.setup = function(sprite, animation) { - if ((!sprite._effectContext || sprite._effekseerInScene) && animation.effectName) { + if (animation.effectName) { sprite._hdrEntry = request(animation.effectName); sprite._hdrSelected = false; } @@ -453,32 +554,48 @@ if (this._hdrEntry && !this._hdrSelected) { if (!this._hdrEntry.ready) return false; const inScene = !!this._effekseerInScene; - if ((inScene ? scene.gl() : Graphics._effekseerGL)?.isContextLost()) return false; + // Drawn by the 3D scene (an effect anchored on a model), which has no HDR path: its twin plays. + const sceneOwned = !!this._reactorInScene || (!!this._effectContext && !inScene); + if ((inScene || this._effectContext ? scene.gl() : Graphics._effekseerGL)?.isContextLost()) return false; let sc = sidecarFor(this); try { - if (sc) sc = valid(sc); + if (sc) sc = valid(sc, this._animation.effectName); if ((forced(this) || /-hdr$/i.test(this._animation.effectName)) && !sc) throw Error("HDR effect requires a sidecar or ReactorHdrOverlay.overrides entry"); } catch (e) { - console.warn("[ReactorHdrOverlay] " + e.message); this._playing = false; return false; + console.warn("[ReactorHdrOverlay] " + e.message); this._playing = false; this._hdrRefused = true; return false; } if (this._hdrEntry.error && !sc) { // Malformed metadata cannot safely identify an HDR asset or its fallback. Fail closed. - this._playing = false; return false; + this._playing = false; this._hdrRefused = true; return false; } - if (inScene) { + if (sceneOwned) { + this._hdrActive = false; + } else if (inScene) { this._hdrActive = !!(sc && scene.ready(sc)); } else { const gl = Graphics._effekseerGL, canvas = Graphics._effekseerCanvas; this._hdrActive = !!(sc && gl && canvas && !gl.isContextLost() && ensure(gl, canvas.width, canvas.height)); if (this._hdrActive) { - try { R.gradeProgram(sc.grade); } catch (e) { this._hdrActive = false; console.warn("[ReactorHdrOverlay] " + e); } + try { R.gradeProgram(sc.grade, sc.gradeB); } catch (e) { this._hdrActive = false; console.warn("[ReactorHdrOverlay] " + e); } } } if (sc && !this._hdrActive) this._effect = load(this, fallbackName(this, sc)); + if (this._hdrActive && sc.companion) { + const name = resolveName(this._animation.effectName, sc.companion); + if (typeof Utils !== "undefined" && Utils.localAssetExists && Utils.localAssetExists(EffectManager.makeUrl(name)) === false) { + companionFailure(this, "missing " + name); + } else { + this._companionEntry = request(name); + this._companionDeadline = performance.now() + 15000; + try { this._companionEffect = load(this, name, (message, url) => { this._companionLoadError = String(message) + " " + url; }); } + catch (error) { companionFailure(this, String(error)); } + if (!this._companionEffect && this._hdrActive) companionFailure(this, "load returned no effect"); + } + } if (this._hdrActive) active.add(this); this._hdrSelected = true; } - return true; + return companionReady(this); } api.contextLost = function() { // Old WASM handles cannot be resumed in the replacement Effekseer context. @@ -487,13 +604,14 @@ for (const sprite of active) { if (sprite._effekseerInScene) continue; sprite._handle?.stop(); + api.stopCompanion(sprite); sprite._hdrActive = false; sprite._playing = false; sprite._started = false; active.delete(sprite); } R?.lost(); }; api.contextRestored = function() { R?.restored(); }; - api.release = function(sprite) { active.delete(sprite); }; + api.release = function(sprite) { active.delete(sprite); api.stopCompanion(sprite); }; api.configure = function(options) { Object.assign(params, options); }; @@ -503,20 +621,31 @@ if (gl?.isContextLost()) { api.contextLost(); return; } if (!gl || !ensure(gl, canvas.width, canvas.height)) { // Never draw HDR light into the display buffer. Existing effects are stopped on loss by the engine. - for (const sprite of draws) { sprite._handle.stop(); sprite._started = false; + for (const sprite of draws) { api.stopCompanion(sprite); sprite._handle.stop(); sprite._started = false; active.delete(sprite); sprite._hdrActive = false; sprite._effect = EffectManager.load(fallbackName(sprite, sidecarFor(sprite))); } return; } + // One pass per grade, bloom intensity and grade weight: keyed intensities differ between animations at different frames. const groups = new Map(); for (const sprite of draws) { - const sc = sidecarFor(sprite); - if (!groups.has(sc.grade)) groups.set(sc.grade, { sc, sprites: [] }); - groups.get(sc.grade).sprites.push(sprite); + const sc = sidecarFor(sprite), frame = sprite._effectFrame, key = sc.grade + "\u0000" + (sc.gradeB || "") + "\u0000" + bloomIntensity(sc.bloom, frame) + "\u0000" + gradeMix(sc, frame); + if (!groups.has(key)) groups.set(key, { sc, frame, sprites: [] }); + groups.get(key).sprites.push(sprite); } try { for (const group of groups.values()) { R.begin(); + try { + gl.colorMask(false, false, false, false); + gl.depthMask(true); + for (const sprite of group.sprites) if (sprite._companionHandle?.exists && sidecarFor(sprite).companionOccludes !== false) { + sprite.setProjectionMatrix(renderer); sprite.setCameraMatrix(renderer); sprite.setViewport(renderer); + const efx = Graphics.effekseer; + efx.beginDraw(); efx.drawHandle(sprite._companionHandle); efx.endDraw(); + Graphics.settleEffekseerState(); + } + } finally { gl.colorMask(true, true, true, true); } for (const sprite of group.sprites) { sprite.setProjectionMatrix(renderer); sprite.setCameraMatrix(renderer); sprite.setViewport(renderer); const efx = Graphics.effekseer; @@ -524,7 +653,7 @@ Graphics.settleEffekseerState(); api.stats.draws++; } - const config = settings(group.sc); + const config = settings(group.sc, group.frame); if (config.probeScale && (!config.probeFrame || group.sprites.some(x => x._frameIndex === config.probeFrame))) R.probe(config.probeScale); R.post(config, group.sc); } @@ -533,6 +662,7 @@ R.fail(); for (const sprite of draws) { active.delete(sprite); + api.stopCompanion(sprite); sprite._handle.stop(); sprite._started = false; sprite._hdrActive = false; sprite._effect = EffectManager.load(fallbackName(sprite, sidecarFor(sprite))); } @@ -568,7 +698,7 @@ return !!layer.guard(gl => { const R = scene.renderer(gl); if (!R.ensure(Math.max(1, Graphics.width | 0), Math.max(1, Graphics.height | 0))) return false; - R.gradeProgram(sc.grade); + R.gradeProgram(sc.grade, sc.gradeB); return true; }); } catch (e) { @@ -578,15 +708,20 @@ }, sidecar: sidecarFor, settings, + // The bloom intensity an in-scene sprite draws with now: sprites of one grade share a pass only when it agrees. + intensity(sprite) { return bloomIntensity(sidecarFor(sprite).bloom, sprite._effectFrame); }, + // Likewise the weight of the sidecar's second grade (gradeB, gradeKeys). + gradeMix(sprite) { return gradeMix(sidecarFor(sprite), sprite._effectFrame); }, // A pass that failed: this sprite plays its twin from here on. fallBack(sprite) { active.delete(sprite); + api.stopCompanion(sprite); try { sprite._handle?.stop(); } catch (e) { /* a lost context */ } sprite._started = false; sprite._hdrActive = false; sprite._effect = load(sprite, fallbackName(sprite, sidecarFor(sprite))); }, lost() { - for (const sprite of active) if (sprite._effekseerInScene) active.delete(sprite); + for (const sprite of active) if (sprite._effekseerInScene) { api.stopCompanion(sprite); active.delete(sprite); } RS?.lost(); }, restored() { RS?.restored(); } diff --git a/template/Demo/js/reactor_main.js b/template/Demo/js/reactor_main.js index 22a9a146..f5a26e27 100644 --- a/template/Demo/js/reactor_main.js +++ b/template/Demo/js/reactor_main.js @@ -1,10 +1,10 @@ //============================================================================= // reactor_main.js — RPG Reactor runtime entry point // RPG Reactor runtime version: 0.99.7 -// RPG Reactor runtime revision: 20261122.4 +// RPG Reactor runtime revision: 20261124.1 // The same stamp, reachable from the F12 console: which engine is this // window actually running? Type RPG_REACTOR_RUNTIME_REVISION to see. -globalThis.RPG_REACTOR_RUNTIME_REVISION = "20261122.4"; +globalThis.RPG_REACTOR_RUNTIME_REVISION = "20261124.1"; //============================================================================= const scriptUrls = [ diff --git a/template/Demo/js/reactor_managers.js b/template/Demo/js/reactor_managers.js index 12932072..0e0bbbcd 100644 --- a/template/Demo/js/reactor_managers.js +++ b/template/Demo/js/reactor_managers.js @@ -1430,12 +1430,17 @@ function EffectManager() { EffectManager._cache = {}; EffectManager._errorUrls = []; +EffectManager._softLoadErrors = new Map(); -EffectManager.load = function(filename) { +EffectManager.load = function(filename, onError) { if (filename) { globalThis.ReactorHdrOverlay?.request(filename); const url = this.makeUrl(filename); const cache = this._cache; + if (typeof onError === "function" && !cache[url]?.isLoaded) { + if (!this._softLoadErrors.has(url)) this._softLoadErrors.set(url, new Set()); + this._softLoadErrors.get(url).add(onError); + } if (!cache[url] && Graphics.effekseer) { this.startLoading(url); } @@ -1446,8 +1451,15 @@ EffectManager.load = function(filename) { }; EffectManager.startLoading = function(url) { - const onLoad = () => this.onLoad(url); - const onError = (message, url) => this.onError(url); + const onLoad = () => { this._softLoadErrors.delete(url); this.onLoad(url); }; + const onError = (message, resourceUrl) => { + const handlers = this._softLoadErrors.get(url); + if (handlers) { + this._softLoadErrors.delete(url); + delete this._cache[url]; + for (const failed of handlers) failed(message, resourceUrl || url); + } else this.onError(resourceUrl || url); + }; const effect = Graphics.effekseer.loadEffect(url, 1, onLoad, onError); this._cache[url] = effect; return effect; @@ -1459,6 +1471,7 @@ EffectManager.clear = function() { Graphics.effekseer.releaseEffect(effect); } this._cache = {}; + this._softLoadErrors.clear(); // The in-scene layer's effects go once the next map has named its own // (preloadMap): what both maps play stays loaded. this._sceneEffectsStale = true; @@ -3581,7 +3594,10 @@ SceneManager.updateInputData = function() { }; SceneManager.updateEffekseer = function() { + // Frames this update steps the effects by (Sprite_Animation's effect clock); battle slow motion scales it. + this._effekseerStep = 0; if (Graphics.effekseer && this.isGameActive()) { + this._effekseerStep = 1; Graphics.effekseer._makeContextCurrent?.(); Graphics.effekseer.update(); // The in-scene context steps with the same update, battle slow motion included. diff --git a/template/Demo/js/reactor_sprites.js b/template/Demo/js/reactor_sprites.js index 0ebf9b85..764588d2 100644 --- a/template/Demo/js/reactor_sprites.js +++ b/template/Demo/js/reactor_sprites.js @@ -2687,9 +2687,12 @@ Sprite_Animation.prototype.initMembers = function() { this._previous = null; this._effect = null; this._handle = null; + this._companionHandle = null; + this._companionEffect = null; this._playing = false; this._started = false; this._frameIndex = 0; + this._effectFrame = 0; this._maxTimingFrames = 0; this._flashColor = [0, 0, 0, 0]; this._flashDuration = 0; @@ -2706,6 +2709,8 @@ Sprite_Animation.prototype.destroy = function(options) { } this._effect = null; this._handle = null; + this._companionHandle = null; + this._companionEffect = null; this._playing = false; this._started = false; }; @@ -2739,17 +2744,27 @@ Sprite_Animation.prototype.setup = function( Sprite_Animation.prototype.update = function() { Sprite.prototype.update.call(this); + // The effect's own clock in frames: what this update's Effekseer step moved its handle by (battle slow + // motion included), at the animation's speed. HDR sidecars key their bloom intensity to it. + if (this._started) this._effectFrame += (globalThis.SceneManager?._effekseerStep ?? 1) * this._animation.speed / 100; if (this._delay > 0) { this._delay--; } else if (this._playing) { if (!this._started && this.canStart()) { if (this._effect) { - if (this._effect.isLoaded) { + if (this._effect.isLoaded && (!this._companionEffect || this._companionEffect.isLoaded)) { const context = this._effectContext?.context || Graphics.effekseer; context._makeContextCurrent?.(); this._handle = context.play(this._effect); + if (this._hdrActive && this._companionEffect) { + this._companionHandle = context.play(this._companionEffect); + const seed = Math.floor(Math.random() * 0x7fffffff); + this._handle.setRandomSeed(seed); + this._companionHandle.setRandomSeed(seed); + } Graphics.effekseer._makeContextCurrent?.(); this._started = true; + this._effectFrame = 0; } else { EffectManager.checkErrors(); } @@ -2825,10 +2840,12 @@ Sprite_Animation.prototype.updateEffectGeometry = function() { // rendered 50% wider than tall (measured 471×314). On-axis in its own // viewport, it stays round at every screen position — this is MZ's own // approach (4096² viewport at the target), adapted to the overlay recipe. - this._handle.setLocation(0, 0, 0); - this._handle.setRotation(rx, ry, rz); - this._handle.setScale(scale, scale, scale); - this._handle.setSpeed(this._animation.speed / 100); + this.forEachEffectHandle(handle => { + handle.setLocation(0, 0, 0); + handle.setRotation(rx, ry, rz); + handle.setScale(scale, scale, scale); + handle.setSpeed(this._animation.speed / 100); + }); }; // Target position in overlay-canvas pixels (shared by setViewport). @@ -2880,7 +2897,8 @@ Sprite_Animation.prototype.checkEnd = function() { this._frameIndex > this._maxTimingFrames && this._flashDuration === 0 && !(this._reactorHideDuration > 0) && - !(this._handle && this._handle.exists) + !(this._handle && this._handle.exists) && + !(this._companionHandle && this._companionHandle.exists) ) { this._playing = false; } @@ -2912,9 +2930,11 @@ Sprite_Animation.prototype.isPlaying = function() { }; Sprite_Animation.prototype.setRotation = function(x, y, z) { - if (this._handle) { - this._handle.setRotation(x, y, z); - } + this.forEachEffectHandle(handle => handle.setRotation(x, y, z)); +}; + +Sprite_Animation.prototype.forEachEffectHandle = function(fn) { + for (const handle of [this._handle, this._companionHandle]) if (handle) fn(handle); }; // v8: queue of Sprite_Animation instances that need an Effekseer draw on the @@ -2963,9 +2983,9 @@ Sprite_Animation.renderActive = function(renderer) { const composited = !!(Graphics.blitSceneBehindEffects && Graphics.blitSceneBehindEffects()); const hdr = []; for (const inst of list) { - if (inst._hdrActive) { hdr.push(inst); continue; } + if (inst._hdrActive) hdr.push(inst); try { - inst._doEffekseerDraw(renderer, composited); + inst._doEffekseerDraw(renderer, composited, inst._hdrActive ? inst._companionHandle : inst._handle); } catch (e) { // The draw runs every frame, so a throw here is reported once. // Swallowing it outright hid every effect in a game while the @@ -3008,6 +3028,7 @@ Sprite_Animation.SceneLayer = { entry: null, cache: new Map(), deadlines: new Map(), + loadErrors: new Map(), live: new Set(), frame: [], drawn: new Set(), @@ -3050,7 +3071,7 @@ Sprite_Animation.SceneLayer = { this.install(); this.guard(gl => { const context = effekseer.createContext(); - context.init(gl); + context.init(gl, Graphics.effekseerContextSettings); // Each draw sets what it needs; PIXI's caches are reset after it. context.setRestorationOfStatesFlag(false); this.context = context; @@ -3094,17 +3115,24 @@ Sprite_Animation.SceneLayer = { this.drawn.delete(sprite); }, /** An effect in the scene's context, loaded once. */ - load(name) { + load(name, onError) { + if (typeof onError === "function" && !this.cache.get(name)?.isLoaded) { + if (!this.loadErrors.has(name)) this.loadErrors.set(name, new Set()); + this.loadErrors.get(name).add(onError); + } if (this.cache.has(name)) return this.cache.get(name); const context = this.ensureContext(); const url = EffectManager.makeUrl(name); context._makeContextCurrent?.(); try { // Its textures upload when their images arrive, outside any draw: PIXI is reset before the next render. - const effect = context.loadEffect(url, 1, () => { this.dirty = true; Graphics.effekseer?._makeContextCurrent?.(); }, () => { + const effect = context.loadEffect(url, 1, () => { this.loadErrors.delete(name); this.dirty = true; Graphics.effekseer?._makeContextCurrent?.(); }, () => { this.cache.delete(name); this.dirty = true; - EffectManager.onError(url); + const handlers = this.loadErrors.get(name); + this.loadErrors.delete(name); + if (handlers) { for (const failed of handlers) failed("effect load failed", url); } + else EffectManager.onError(url); }); if (effect && typeof effect._update === "function") { const update = effect._update, layer = this; @@ -3194,6 +3222,8 @@ Sprite_Animation.SceneLayer = { */ lost() { for (const sprite of this.live) { + try { sprite._companionHandle?.stop(); } catch (e) { /* lost context */ } + sprite._companionHandle = null; sprite._companionEffect = null; try { sprite._handle?.stop(); } catch (e) { /* nothing left to stop */ } sprite._handle = null; sprite._playing = false; @@ -3209,7 +3239,9 @@ Sprite_Animation.SceneLayer = { this.entry = null; this.cache.clear(); this.deadlines.clear(); + this.loadErrors.clear(); this.depth = null; + this.backdropCopy = null; globalThis.ReactorHdrOverlay?.scene?.lost(); }, restored() { @@ -3325,18 +3357,75 @@ Sprite_Animation.SceneLayer = { gl.clear(gl.DEPTH_BUFFER_BIT); } }, + /** + * Effekseer copies the bound framebuffer into its RGBA backdrop texture (copyTexSubImage2D). From the canvas WebGL + * refuses that copy (INVALID_OPERATION) when the context has no alpha channel, as PIXI creates it (alpha: false), + * so the backdrop stayed black and every distortion layer drew black at its opacity instead of bending the scene + * (BD2 Meltdown's sphere in battle, 2026-11-04: the right scene point, darkened by the layer's alpha). The canvas + * is blitted into an RGBA scratch target the size of the effect's square viewport (WebGL2's blit converts the + * format) and copied from there. The square reaches past the screen (it is twice the screen's height), so the + * scratch's off-screen margins repeat the screen's edge rows and columns, as UE clamps its distortion to the screen; + * read as zeros they showed as black bands where the layer pushed samples outwards. Filter targets are RGBA + * textures and copy as they are. + */ + captureBackground(gl, context, rect, framebuffer) { + if (!context.captureBackground) return; + const attrs = gl.getContextAttributes && gl.getContextAttributes(); + if (framebuffer || typeof gl.blitFramebuffer !== "function" || !attrs || attrs.alpha) { + context.captureBackground(rect.x, rect.y, rect.side, rect.side); + return; + } + const W = gl.drawingBufferWidth, H = gl.drawingBufferHeight, S = rect.side; + const x0 = Math.max(rect.x, 0), y0 = Math.max(rect.y, 0), x1 = Math.min(rect.x + S, W), y1 = Math.min(rect.y + S, H); + if (x1 <= x0 || y1 <= y0) { + context.captureBackground(rect.x, rect.y, S, S); + return; + } + let copy = this.backdropCopy; + if (!copy || copy.side !== S) { + if (copy) { gl.deleteFramebuffer(copy.fb); gl.deleteRenderbuffer(copy.rb); } + copy = this.backdropCopy = { fb: gl.createFramebuffer(), rb: gl.createRenderbuffer(), side: S }; + gl.bindRenderbuffer(gl.RENDERBUFFER, copy.rb); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA8, S, S); + gl.bindRenderbuffer(gl.RENDERBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, copy.fb); + gl.framebufferRenderbuffer(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, copy.rb); + } + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, copy.fb); + const ox = rect.x, oy = rect.y; + // [source x0, y0, x1, y1] on the screen -> [destination] in the square, stretched with NEAREST + const blit = (sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1) => { + if (dx1 > dx0 && dy1 > dy0) gl.blitFramebuffer(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, gl.COLOR_BUFFER_BIT, gl.NEAREST); + }; + const ix0 = x0 - ox, iy0 = y0 - oy, ix1 = x1 - ox, iy1 = y1 - oy; + blit(x0, y0, x1, y1, ix0, iy0, ix1, iy1); // the screen itself + blit(x0, y0, x0 + 1, y1, 0, iy0, ix0, iy1); // left margin: the left column + blit(x1 - 1, y0, x1, y1, ix1, iy0, S, iy1); // right margin + blit(x0, y0, x1, y0 + 1, ix0, 0, ix1, iy0); // bottom margin: the bottom row + blit(x0, y1 - 1, x1, y1, ix0, iy1, ix1, S); // top margin + blit(x0, y0, x0 + 1, y0 + 1, 0, 0, ix0, iy0); // corners + blit(x1 - 1, y0, x1, y0 + 1, ix1, 0, S, iy0); + blit(x0, y1 - 1, x0 + 1, y1, 0, iy1, ix0, S); + blit(x1 - 1, y1 - 1, x1, y1, ix1, iy1, S, S); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, copy.fb); + context.captureBackground(0, 0, S, S); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + }, /** * Draw `sprites`' handles through `view`, into a buffer `scale` times * the target's pixels whose origin is the target viewport's (the HDR - * light), or into the target itself (scale 1, `inTarget`); `capture`: - * the target is a texture, whose pixels distortion can copy. + * light), or into the target itself (scale 1, `inTarget`). */ - drawHandles(gl, renderer, view, sprites, scale, inTarget, capture) { + drawHandles(gl, renderer, view, sprites, scale, inTarget, handleOf = sprite => sprite._handle) { const context = this.context; const height = Graphics.height * view.ppu * scale; const side = Sprite_Animation.effekseerViewportSide(Graphics.height) * view.ppu * scale; gl.frontFace(view.flipped ? gl.CW : gl.CCW); for (const sprite of sprites) { + const handle = handleOf(sprite); + if (!handle?.exists) continue; const pos = sprite.effekseerScreenPosition(renderer); const at = view.project(pos.x, pos.y); const cx = inTarget ? at.x : (at.x - view.vp.x) * scale, cy = inTarget ? at.y : (at.y - view.vp.y) * scale; @@ -3344,30 +3433,29 @@ Sprite_Animation.SceneLayer = { const projection = Sprite_Animation.effekseerProjection(height, rect.side, sprite._mirror).slice(); // A target stored upside down: the effect is drawn upside down into it (its winding with it). if (view.flipped) for (const i of [1, 5, 9, 13]) projection[i] = -projection[i]; - // The scene beneath the effect, for its distortion layers: what this target holds now. Only from a - // texture: the canvas has no alpha (Graphics: backgroundAlpha 1), and GL refuses to copy its RGB pixels - // into Effekseer's RGBA background. - if (capture && context.captureBackground) context.captureBackground(rect.x, rect.y, rect.side, rect.side); + // The scene beneath the effect, for its distortion layers: what this target holds now. + if (inTarget) this.captureBackground(gl, context, rect, this.targetFramebuffer); context.setProjectionMatrix(projection); context.setCameraMatrix(this.camera); gl.viewport(rect.x, rect.y, rect.side, rect.side); context.beginDraw(); - context.drawHandle(sprite._handle); + context.drawHandle(handle); context.endDraw(); this.stats.draws++; } }, /** One animation's draw, from its RenderContainer during PIXI's render. */ draw(renderer, sprite) { - if (!this.context || sprite._reactorInScene || !sprite._handle || !sprite._handle.exists || !sprite._targets.length) return; + if (!this.context || sprite._reactorInScene || !(sprite._handle?.exists || sprite._companionHandle?.exists) || !sprite._targets.length) return; if (sprite._hdrActive) return this.drawHdr(renderer, sprite); const gl = renderer.gl, saved = this.save(gl, renderer), start = performance.now(); try { const view = this.view(renderer); + this.targetFramebuffer = saved.framebuffer; gl.bindVertexArray(null); this.withDepth(gl, renderer, saved); this.context._makeContextCurrent?.(); - this.drawHandles(gl, renderer, view, [sprite], 1, true, !!saved.framebuffer); + this.drawHandles(gl, renderer, view, [sprite], 1, true); } catch (e) { this.warnOnce(e); } finally { @@ -3385,7 +3473,9 @@ Sprite_Animation.SceneLayer = { const hdr = globalThis.ReactorHdrOverlay.scene; const sc = hdr.sidecar(sprite); const group = this.frame.filter(other => other !== sprite && other._hdrActive && other.parent === sprite.parent - && other._handle && other._handle.exists && hdr.sidecar(other) && hdr.sidecar(other).grade === sc.grade); + && other._handle && other._handle.exists && hdr.sidecar(other) && hdr.sidecar(other).grade === sc.grade + && hdr.sidecar(other).gradeB === sc.gradeB && hdr.intensity(other) === hdr.intensity(sprite) + && hdr.gradeMix?.(other) === hdr.gradeMix?.(sprite)); group.unshift(sprite); for (const member of group) this.drawn.add(member); const gl = renderer.gl, saved = this.save(gl, renderer), start = performance.now(); @@ -3395,10 +3485,21 @@ Sprite_Animation.SceneLayer = { const R = hdr.renderer(gl); gl.bindVertexArray(null); if (!R.ensure(Math.max(1, Math.round(view.vp.w * scale)), Math.max(1, Math.round(view.vp.h * scale)))) throw Error("no HDR targets on PIXI's context"); + gl.bindFramebuffer(gl.FRAMEBUFFER, saved.framebuffer); + this.targetFramebuffer = saved.framebuffer; + this.withDepth(gl, renderer, saved); + this.context._makeContextCurrent?.(); + this.drawHandles(gl, renderer, view, group, 1, true, member => member._companionHandle); R.begin(); + try { + gl.colorMask(false, false, false, false); + gl.depthMask(true); + this.drawHandles(gl, renderer, view, group, scale, false, + member => hdr.sidecar(member).companionOccludes !== false ? member._companionHandle : null); + } finally { gl.colorMask(true, true, true, true); } this.context._makeContextCurrent?.(); this.drawHandles(gl, renderer, view, group, scale, false); - R.post(Object.assign(hdr.settings(sc), { + R.post(Object.assign(hdr.settings(sc, sprite._effectFrame), { framebuffer: saved.framebuffer, // The bloom's radii are fractions of the game screen's width, in the light's pixels. bloomWidth: Graphics.width * view.ppu * scale, @@ -3427,10 +3528,10 @@ Sprite_Animation.prototype._render = function(renderer) { // Drawn by its own RenderContainer during PIXI's render; noted for this // frame so HDR animations of one grade can share a light pass. if (this._effekseerInScene) { - if (this._targets.length > 0 && this._handle && this._handle.exists) Sprite_Animation.SceneLayer.frame.push(this); + if (this._targets.length > 0 && (this._handle?.exists || this._companionHandle?.exists)) Sprite_Animation.SceneLayer.frame.push(this); return; } - if (this._targets.length > 0 && this._handle && this._handle.exists) { + if (this._targets.length > 0 && (this._handle?.exists || this._companionHandle?.exists)) { if (PIXI.TextureSource) { // v8: defer to post-render flush; just queue self. Actual Effekseer // draw runs in Graphics._onTick after _app.render() returns so it @@ -3460,7 +3561,7 @@ Sprite_Animation.prototype._render = function(renderer) { // page-load. Confirms the overlay canvas exists in the DOM, that we have its // WebGL1 context, and that Effekseer actually writes pixels to it. Reset via -Sprite_Animation.prototype._doEffekseerDraw = function(renderer, composited) { +Sprite_Animation.prototype._doEffekseerDraw = function(renderer, composited, handle = this._handle) { if (this._reactorInScene) return; // Draws to the Effekseer overlay canvas's WebGL1 context (Graphics._effekseerGL). // The overlay canvas sits absolutely positioned over the game canvas with @@ -3468,7 +3569,7 @@ Sprite_Animation.prototype._doEffekseerDraw = function(renderer, composited) { // of the v8-rendered scene. This bypasses v8/WebGL2 entirely for Effekseer. // Called from Sprite_Animation.renderActive after the overlay has been // cleared once for this frame. - if (!(this._targets.length > 0 && this._handle && this._handle.exists)) { + if (!(this._targets.length > 0 && handle && handle.exists)) { return; } const efxGL = Graphics._effekseerGL; @@ -3487,7 +3588,7 @@ Sprite_Animation.prototype._doEffekseerDraw = function(renderer, composited) { this.setCameraMatrix(renderer); this.setViewport(renderer); Graphics.effekseer.beginDraw(); - Graphics.effekseer.drawHandle(this._handle); + Graphics.effekseer.drawHandle(handle); Graphics.effekseer.endDraw(); Graphics.settleEffekseerState(); this.resetViewport(renderer);