Loading…
Loading…
6 карточек
How do you write a custom Filter in v8 that works on both WebGL and WebGPU?
нажми, чтобы перевернуть
resources block (uniforms + input textures). Pixi v8 compiles the right pipeline for the active renderer. Uniform types must match across both backends.Filter.from({ gl: { vertex, fragment }, gpu: { vertex, fragment }, resources }) is the portable entry. The vertex shader of a Filter has a fixed contract: an input quad and uFilterUniforms (outputFrame, inputSize, inputClamp). WGSL uses @group(0) for Pixi's built-ins and @group(1) for user uniforms — the layouts must line up with the GLSL block layout. The GLSL fragment samples uTexture; WGSL samples a texture_2d bound from the same resources entry. Filters don't need to touch the vertex shader 95% of the time — reuse the shipped defaultFilter vertex sources.
import { Filter, GlProgram, GpuProgram } from 'pixi.js'
const glsl = `
in vec2 vTextureCoord;
uniform sampler2D uTexture;
uniform float uStrength;
out vec4 finalColor;
void main() {
vec4 c = texture(uTexture, vTextureCoord);
float g = dot(c.rgb, vec3(0.299, 0.587, 0.114));
finalColor = vec4(mix(c.rgb, vec3(g), uStrength), c.a);
}`
const wgsl = `
@group(0) @binding(1) var uSampler: sampler;
@group(0) @binding(2) var uTexture: texture_2d<f32>;
@group(1) @binding(0) var<uniform> uniforms: Uniforms;
struct Uniforms { uStrength: f32 };
@fragment fn mainF(@location(0) vUv: vec2<f32>) -> @location(0) vec4<f32> {
let c = textureSample(uTexture, uSampler, vUv);
let g = dot(c.rgb, vec3<f32>(0.299, 0.587, 0.114));
return vec4<f32>(mix(c.rgb, vec3<f32>(g), uniforms.uStrength), c.a);
}`
const desaturate = new Filter({
glProgram: GlProgram.from({ vertex: defaultVertGLSL, fragment: glsl }),
gpuProgram: GpuProgram.from({ vertex: { source: defaultVertWGSL, entryPoint: 'mainV' },
fragment: { source: wgsl, entryPoint: 'mainF' } }),
resources: { uniforms: { uStrength: { value: 0.7, type: 'f32' } } },
})
world.filters = [desaturate]Когда да
Когда нет
Совет на собеседовании
If your filter renders solid black on WebGPU only, the uniform struct is misaligned — WGSL requires 16-byte alignment for vec3 / float tails. Pad with an unused f32.
Свайп вправо — знаю, влево — не знаю
