Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
// This example shows how to add a custom post-effect to a CameraFrame with CameraFrameEffect. A
// pixelation effect is written as a shader chunk whose entry function the single compose pass calls,
// so no additional full-screen pass is needed. The effect is an instance registered with one
// CameraFrame, and its parameters are updated per frame like those of the built-in effects.
// CameraFrame, and its parameters are applied by cameraFrame.update(), like those of the built-in
// effects.
//
// @credit
// title: Mirror's Edge Apartment - Interior Scene
Expand Down Expand Up @@ -170,7 +171,7 @@ app.root.addChild(cameraEntity);
// A CameraFrameEffect contributes a shader chunk to the compose pass. The chunk declares its uniforms
// and an entry function named apply<Id>, which the compose shader calls for the effect's slot as
// `result = applyPixelation(result, uv)`. COMPOSESLOT_LDR runs after tone mapping, so the dots are
// drawn in display space. The uniforms are set once per frame from the effect's fields in update().
// drawn in display space. update() hands the uniform values to the effect when cameraFrame.update() is called.
class PixelationEffect extends CameraFrameEffect {
// Size of one pixelation tile in screen pixels
tilePixels = 8;
Expand All @@ -186,7 +187,7 @@ class PixelationEffect extends CameraFrameEffect {
uniform float pixelationIntensity;

vec3 applyPixelation(vec3 color, vec2 uv) {
vec2 tileUV = vec2(pixelationTilePixels) * sceneTextureInvRes;
vec2 tileUV = vec2(pixelationTilePixels) * sceneTextureSize.zw;
vec2 centerUv = (floor(uv / tileUV) + 0.5) * tileUV;

vec2 local = (uv - centerUv) / tileUV;
Expand All @@ -203,7 +204,7 @@ class PixelationEffect extends CameraFrameEffect {
uniform pixelationIntensity: f32;

fn applyPixelation(color: vec3f, uv: vec2f) -> vec3f {
let tileUV = vec2f(uniform.pixelationTilePixels) * uniform.sceneTextureInvRes;
let tileUV = vec2f(uniform.pixelationTilePixels) * uniform.sceneTextureSize.zw;
let centerUv = (floor(uv / tileUV) + vec2f(0.5, 0.5)) * tileUV;

let local = (uv - centerUv) / tileUV;
Expand All @@ -216,20 +217,17 @@ class PixelationEffect extends CameraFrameEffect {
}
`
});

// uniforms are resolved once, and written every frame in update()
this.tilePixelsId = device.scope.resolve('pixelationTilePixels');
this.intensityId = device.scope.resolve('pixelationIntensity');
}

// At zero intensity the effect would leave the image untouched, so it is left out of the shader
get active() {
return this.enabled && this.intensity > 0;
}

// called by cameraFrame.update(), the values apply to the frames rendered after it
update() {
this.tilePixelsId.setValue(this.tilePixels);
this.intensityId.setValue(this.intensity);
this.setUniform('pixelationTilePixels', this.tilePixels);
this.setUniform('pixelationIntensity', this.intensity);
}
}

Expand All @@ -251,7 +249,7 @@ cameraFrame.addEffect(pixelation);

cameraFrame.update();

// Apply UI changes (tone mapping only)
// Apply UI changes, applied by cameraFrame.update()
data.on('*:set', (/** @type {string} */ path, value) => {
if (path === 'data.sceneTonemapping') {
// postprocessing tone mapping
Expand All @@ -261,10 +259,12 @@ data.on('*:set', (/** @type {string} */ path, value) => {

if (path === 'data.pixelSize') {
pixelation.tilePixels = value;
cameraFrame.update();
}

if (path === 'data.pixelationIntensity') {
pixelation.intensity = value;
cameraFrame.update();
}
});

Expand Down
127 changes: 98 additions & 29 deletions src/extras/render-passes/camera-frame-effect.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,27 @@ import { SHADERLANGUAGE_WGSL } from '../../platform/graphics/constants.js';
* @import { FramePass } from '../../platform/graphics/frame-pass.js'
* @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js'
* @import { ScopeId } from '../../platform/graphics/scope-id.js'
* @import { Texture } from '../../platform/graphics/texture.js'
* @import { ShaderChunks } from '../../scene/shader-lib/shader-chunks.js'
*/

/**
* The context handed to {@link CameraFrameEffect#frameUpdate} by the camera frame the effect is
* registered with: the values of the frame being prepared. Valid only for the duration of that
* call - the object is reused, and its contents change from frame to frame.
*
* The texture is this frame's, but its size is final only once the frame's passes are updated,
* after that call - when the canvas or the render target scale changes, it still has the size of
* the previous frame. Use the sizes in the context instead of the texture's own.
*
* @typedef {object} CameraFrameEffectContext
* @property {Texture} sceneTexture - The scene color the composition reads this frame: the output
* of the temporal anti-aliasing when it is enabled, which alternates between two textures from
* frame to frame, and the scene render target's color otherwise.
* @property {number} sceneWidth - The width of the scene texture this frame, in pixels.
* @property {number} sceneHeight - The height of the scene texture this frame, in pixels.
*/

// capitalizes the first character of a name, to derive the identifiers an effect's chunk uses
const capitalize = name => name.charAt(0).toUpperCase() + name.slice(1);

Expand All @@ -20,8 +38,8 @@ const capitalize = name => name.charAt(0).toUpperCase() + name.slice(1);
*
* An effect contributes to the composition: you supply its shader chunk (GLSL and WGSL) and write
* its entry function under a conventional name, `apply<Id>`. The camera frame generates the call to
* that function at the effect's slot, and rebuilds the compose shader whenever an effect becomes
* active or inactive, or changes one of its defines. The chunk is only included while the effect is
* that function at the effect's slot, and rebuilds the compose shader when an effect becomes active
* or inactive, or changes one of its defines. The chunk is only included while the effect is
* active, so it needs no `#ifdef` guard of its own - defines are for an effect's own variants, set
* with {@link CameraFrameEffect#setDefine}. The chunk can be overridden by name like the built-in
* chunks: a chunk set in {@link ShaderChunks} under `compose<Id>PS` replaces the effect's own
Expand All @@ -32,19 +50,27 @@ const capitalize = name => name.charAt(0).toUpperCase() + name.slice(1);
* All effects registered to a compose slot are called in registration order from within the single
* compose pass, so an effect never costs an additional full-screen pass.
*
* Every chunk can read what the composition provides: the scene color, `sceneTexture`, and
* `sceneTextureSize` - the width, height, 1 / width and 1 / height of the scene texture. Use the
* size for anything which depends on the resolution, such as texel offsets, pixel sizes or the
* aspect ratio, as it is always current for the camera being drawn.
*
* Like the rest of the camera frame, an effect is configured when {@link CameraFrame#update} is
* called: changes to its parameters take effect at the next update, and every frame rendered after
* it uses exactly what the update applied.
*
* Lifetime:
*
* - **Construct** - pass the device, the id and the declarations to the constructor; declare the
* parameters as fields. Resources the effect keeps for its whole life - a lookup texture, a noise
* texture - are created here, the {@link ScopeId}s of its uniforms are resolved here, and fixed
* defines can be set with {@link CameraFrameEffect#setDefine}.
* - **Each frame while {@link CameraFrameEffect#active}, preparing** -
* {@link CameraFrameEffect#frameUpdate} is called while the frame is prepared, before anything
* renders, for changes that decide what is rendered, such as defines. Most effects do not need
* it.
* - **Each frame while {@link CameraFrameEffect#active}, rendering** -
* {@link CameraFrameEffect#update} is called right before the compose pass renders the camera,
* to write the uniforms the chunk reads.
* texture - are created here, and fixed defines can be set with
* {@link CameraFrameEffect#setDefine}.
* - **On {@link CameraFrame#update}, while {@link CameraFrameEffect#active}** -
* {@link CameraFrameEffect#update} applies the parameters: the values of the uniforms with
* {@link CameraFrameEffect#setUniform}, and the defines that depend on them.
* - **Each frame while it takes part** - {@link CameraFrameEffect#frameUpdate} is called with the
* values of the frame being prepared, for the few effects which depend on them. Most effects do
* not need it.
* - **Destroy** - {@link CameraFrameEffect#destroy} releases what the constructor created. Whoever
* constructs an effect destroys it: the camera frame destroys its built-in effects, and an effect
* you add is yours to destroy.
Expand All @@ -55,6 +81,8 @@ const capitalize = name => name.charAt(0).toUpperCase() + name.slice(1);
* class TintEffect extends CameraFrameEffect {
* color = new Color(1, 0.9, 0.8);
*
* tintColor = new Float32Array(3);
*
* constructor(device) {
* super(device, 'tint', {
* slot: COMPOSESLOT_LDR,
Expand All @@ -71,20 +99,21 @@ const capitalize = name => name.charAt(0).toUpperCase() + name.slice(1);
* }
* `
* });
* this.tintColorId = device.scope.resolve('tintColor');
* }
*
* update() {
* this.tintColorId.setValue([this.color.r, this.color.g, this.color.b]);
* this.tintColor[0] = this.color.r;
* this.tintColor[1] = this.color.g;
* this.tintColor[2] = this.color.b;
* this.setUniform('tintColor', this.tintColor);
* }
* }
*
* cameraFrame.addEffect(new TintEffect(app.graphicsDevice));
*
* // The same effect without a class, for effects driven by data
* const tint = new CameraFrameEffect(app.graphicsDevice, 'tint', { slot: COMPOSESLOT_LDR, glsl, wgsl });
* const tintColorId = app.graphicsDevice.scope.resolve('tintColor');
* tint.update = () => tintColorId.setValue([1, 0.9, 0.8]);
* tint.setUniform('tintColor', new Float32Array([1, 0.9, 0.8]));
* cameraFrame.addEffect(tint);
* @category Graphics
*/
Expand Down Expand Up @@ -164,6 +193,15 @@ class CameraFrameEffect {
*/
_definesVersion = 0;

/**
* The uniform values set with {@link CameraFrameEffect#setUniform}, bound right before the
* compose pass renders.
*
* @type {Map<string, { scopeId: ScopeId, value: * }>}
* @private
*/
_uniforms = new Map();

/**
* Creates a new effect.
*
Expand Down Expand Up @@ -327,9 +365,9 @@ class CameraFrameEffect {

/**
* Sets a define on the compose shader. The define persists until changed, so fixed defines
* can be set once in the constructor and state-dependent ones from
* {@link CameraFrameEffect#frameUpdate}. A value of false, null or undefined removes it.
* Changing a define rebuilds the compose shader.
* can be set once in the constructor and those depending on the parameters from
* {@link CameraFrameEffect#update}. A value of false, null or undefined removes it. Changing a
* define rebuilds the compose shader.
*
* @param {string} name - The define name.
* @param {*} value - The value.
Expand Down Expand Up @@ -379,26 +417,57 @@ class CameraFrameEffect {
}

/**
* Called every frame while the effect is active, while the frame is being prepared and before
* any pass renders. Use it for changes that decide what is rendered, such as defines set with
* {@link CameraFrameEffect#setDefine}; changes made here apply to this frame.
* Sets the value of a uniform the effect's shader chunk reads. Like a material parameter, the
* value is stored by reference, so an array or a texture can be updated in place. Set the
* values in {@link CameraFrameEffect#update}, or in {@link CameraFrameEffect#frameUpdate} for
* a value which changes every frame.
*
* Do not write uniforms here: every camera is prepared before any camera renders, so a uniform
* written here is overwritten by the next camera. Write them in
* {@link CameraFrameEffect#update} instead. Most effects do not need this method.
* @param {string} name - The name of the uniform, as declared in the chunk.
* @param {number|number[]|ArrayBufferView|Texture} value - The value.
*/
frameUpdate() {
setUniform(name, value) {
let uniform = this._uniforms.get(name);
if (!uniform) {
uniform = { scopeId: this.device.scope.resolve(name), value: null };
this._uniforms.set(name, uniform);
}
uniform.value = value;
}

/**
* Called every frame while the effect is active, right before the compose pass renders the
* camera. Write the uniforms the effect's shader chunk reads here, using the {@link ScopeId}s
* resolved in the constructor. It runs once per camera, so each camera renders with its own
* values.
* Binds the uniform values, right before the compose pass renders.
*
* @ignore
*/
_bindUniforms() {
for (const uniform of this._uniforms.values()) {
uniform.scopeId.setValue(uniform.value);
}
}

/**
* Applies the effect's parameters. Called by {@link CameraFrame#update} while the effect is
* active, and when it is added to a camera frame: set the uniform values with
* {@link CameraFrameEffect#setUniform} here, and the defines which depend on the parameters.
* Everything it sets is what the frames rendered until the next update use.
*/
update() {
}

/**
* Called every frame while the effect takes part in the frame, while the frame is being
* prepared and before any pass renders, with the values of that frame. Most effects do not
* need it: their configuration belongs in {@link CameraFrameEffect#update}, which runs only
* when the camera frame is updated. Values derived from the resolution, which can change
* without an update, are computed here from the sizes in the frame, or in the shader from
* `sceneTextureSize`.
*
* @param {CameraFrameEffectContext} frame - The values of this frame. Read them during this
* call only.
*/
frameUpdate(frame) {
}

/**
* Destroys the effect, removing it from its camera frame if it is still registered and
* releasing everything it owns. Subclasses which create resources in their constructor release
Expand Down
45 changes: 38 additions & 7 deletions src/extras/render-passes/camera-frame.js
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,16 @@ class CameraFrame {
*/
_builtInEffects = [];

/**
* The effects taking part in the frames, in registration order: the active ones, as of the
* last time the effects were applied - by {@link CameraFrame#update}, or by a change to the
* registered effects.
*
* @type {CameraFrameEffect[]}
* @ignore
*/
_activeEffects = [];

/**
* The sharpening effect, whose sharpness is exposed as `rendering.sharpness`.
*
Expand Down Expand Up @@ -427,8 +437,8 @@ class CameraFrame {
this._builtInEffects = [this._cas, this.fringing, this.colorEnhance, this.grading, this.colorLUT, this.vignette];
this._builtInEffects.forEach(effect => this.addEffect(effect));

// rendering.sharpness is the sharpening effect's parameter, forwarded so that it applies
// without CameraFrame#update, like the parameters of the other effects
// rendering.sharpness is the sharpening effect's parameter, forwarded to it so that the
// effect is its single home
const cas = this._cas;
Object.defineProperty(this.rendering, 'sharpness', {
get: () => cas.sharpness,
Expand Down Expand Up @@ -546,7 +556,7 @@ class CameraFrame {

this.effects.splice(index, 0, effect);
effect._attach(this);
this._syncEffects();
this._applyEffects();
}

/**
Expand All @@ -559,7 +569,7 @@ class CameraFrame {
if (index >= 0) {
this.effects.splice(index, 1);
effect._detach();
this._syncEffects();
this._applyEffects();
}
}

Expand All @@ -575,20 +585,38 @@ class CameraFrame {
}

/**
* Republishes the effects to the composition, which assembles its shader from them.
* Applies the effects: decides which take part in the frames rendered until they are next
* applied, has each of them apply its parameters, and hands them to the composition, which
* rebuilds its shader only when they or their defines changed. Called by
* {@link CameraFrame#update}, when the camera frame is enabled, and when an effect is added or
* removed.
*
* @private
*/
_syncEffects() {
_applyEffects() {

// the effects taking part until the effects are next applied, each applying its parameters
const active = this._activeEffects;
active.length = 0;
const { effects } = this;
for (let i = 0; i < effects.length; i++) {
const effect = effects[i];
if (effect.active) {
active.push(effect);
effect.update();
}
}

const composePass = this.renderPassCamera?.composePass;
if (composePass) {
composePass.effects = this.effects;
composePass.effects = active;
}
}

enable() {
this.renderPassCamera = this.createRenderPass();
this.cameraComponent.framePasses = [this.renderPassCamera];
this._applyEffects();
}

disable() {
Expand Down Expand Up @@ -779,6 +807,9 @@ class CameraFrame {
// enable camera jitter if taa is enabled
cameraComponent.jitter = taa.enabled ? taa.jitter : 0;

// the effects apply their parameters, and the frames rendered from now use them
this._applyEffects();

// debug rendering
composePass.debug = this.debug;
if (composePass.debug === 'ssao' && options.ssaoType === SSAOTYPE_NONE) composePass.debug = null;
Expand Down
Loading
Loading