Communitygithub.com

melonjs/melonjs-effects-and-shaders

使用此技能处理 melonJS 中的后期处理效果、自定义着色器、混合模式和色彩分级。涵盖内置 ShaderEffect 预设、在可渲染对象和摄像机上的 addPostEffect、编写自定义双语 GLSL/WGSL 效果、screen_texture 内置变量,以及效果在 Canvas 回退中静默失效的原因。

melonjs-effects-and-shaders 是什么?

该技能为 melonJS 游戏引擎提供全面的后期处理与着色器支持,帮助开发者轻松实现视觉效果增强。它涵盖了 melonJS 内置的 ShaderEffect 预设(如 VignetteEffect、GlowEffect、BlurEffect 等),指导如何在可渲染对象或摄像机实例上使用 addPostEffect 动态添加效果。技能深入介绍了编写自定义双语言(GLSL 与 WGSL)着色器的方法,包括 uniform 传递、纹理绑定和时间变量控制。同时,它解释了 screen_texture 内置变量的用途以及 toFrameTexture 的帧缓冲提取。技能还强调了 Canvas2D 回退模式下效果静默失效的原因,帮助开发者避免常见陷阱。适用于 melonJS 游戏开发中的视觉特效、滤镜与混合模式场景。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/melonjs/melonJS/tree/master/packages/melonjs/skills/melonjs-effects-and-shaders

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

melonjs-effects-and-shaders 是做什么的?

使用此技能处理 melonJS 中的后期处理效果、自定义着色器、混合模式和色彩分级。涵盖内置 ShaderEffect 预设、在可渲染对象和摄像机上的 addPostEffect、编写自定义双语 GLSL/WGSL 效果、screen_texture 内置变量,以及效果在 Canvas 回退中静默失效的原因。触发关键词:ShaderEffect, addPostEffect, removePostEffect, getPostEffect, VignetteEffect, GlowEffect, BlurEffect, PixelateEffect, ScanlineEffect, shader, GLSL, WGSL, uniform, setUniform, setTexture, setTime, blendMode, colorMatrix, screen_texture, toFrameTexture, post effect, filter。

快速使用

import { ShaderEffect, VignetteEffect } from "@melonjs/melonjs";

// 在摄像机中应用暗角效果
me.game.viewport.addPostEffect(new VignetteEffect());

内置 ShaderEffect 预设

melonJS 提供了一系列可直接使用的内置效果预设:

  • VignetteEffect:在屏幕边缘添加暗角效果。
  • GlowEffect:添加发光/辉光效果。
  • BlurEffect:高斯模糊效果。
  • PixelateEffect:像素化效果。
  • ScanlineEffect:扫描线/CRT 效果。

所有预设均继承自 ShaderEffect 基类,使用方式一致。

添加与移除效果

在摄像机层级添加

// 添加效果
const blur = new BlurEffect();
me.game.viewport.addPostEffect(blur);

// 稍后移除
me.game.viewport.removePostEffect(blur);

在可渲染对象上添加

const sprite = new me.Sprite(0, 0, { image: "hero" });
sprite.addPostEffect(new GlowEffect());

获取已添加的效果

const effects = me.game.viewport.getPostEffect();
// effects 为 ShaderEffect 实例数组

自定义着色器效果

melonis 支持编写自定义的 GLSL 与 WGSL 双语言着色器效果,确保同时兼容 WebGL 和 WebGPU。

基本结构

class MyCustomEffect extends ShaderEffect {
    constructor() {
        super({
            name: "MyCustomEffect",
            vertex: "#version 300 es\n...",  // GLSL 顶点着色器
            fragment: "#version 300 es\n..."  // GLSL 片段着色器
        });
        
        // 对于 WebGPU,提供 WGSL 版本
        this.wgslVertex = `...`;
        this.wgslFragment = `...`;
    }
}

传递 Uniform 值

class MyEffect extends ShaderEffect {
    constructor() {
        super({ ... });
        this._intensity = 1.0;
    }
    
    setUniforms(shader) {
        shader.setUniform("uIntensity", this._intensity);
        shader.setUniform("uTime", me.game.getTime());
    }
}

使用纹理

// 设置纹理 uniform
shader.setTexture("uTexture", someTexture);

// 使用 screen_texture 访问前一帧的屏幕图像
// 在片段着色器中定义:uniform sampler2D screen_texture;

时间控制

// 在更新循环中更新时间 uniform
shader.setTime(me.game.getTime());

混合模式与色彩矩阵

设置混合模式

// 混合模式影响绘制时的颜色混合行为
renderable.blendMode = me.BlendMode.NORMAL;
// 可选值:NORMAL, ADDITIVE, MULTIPLY, SCREEN 等

色彩矩阵

// 通过 colorMatrix 调整颜色
const matrix = [
    0.5, 0.5, 0.5, 0, 0,
    0.5, 0.5, 0.5, 0, 0,
    0.5, 0.5, 0.5, 0, 0,
    0,   0,   0,   1, 0
];

// 应用色彩矩阵作为后期效果
class ColorMatrixEffect extends ShaderEffect {
    constructor() {
        super({
            name: "ColorMatrix",
            fragment: `
                precision highp float;
                uniform sampler2D screen_texture;
                uniform mat4 uColorMatrix;
                varying vec2 vUv;
                
                void main() {
                    vec4 color = texture2D(screen_texture, vUv);
                    gl_FragColor = uColorMatrix * color;
                }
            `
        });
    }
    
    setUniforms(shader) {
        shader.setUniform("uColorMatrix", matrix);
    }
}

帧纹理操作

// 将当前帧渲染为纹理
const frameTex = me.video.renderer.toFrameTexture();
// 可将 frameTex 用于后续效果或纹理

常见陷阱:Canvas 回退中的效果

melonJS 在无法使用 WebGL/WebGPU 时会回退到 Canvas2D 渲染模式。在此模式下,自定义着色器不会执行。效果会静默失败而不会报错。

检查当前渲染器类型:

console.log(me.video.renderer.type);
// "WebGL"、"WebGPU" 或 "Canvas"

建议: 在生产环境中始终检测 WebGL 支持,并在 Canvas 模式下降级使用内置效果。

完整示例

import { ShaderEffect, VignetteEffect } from "@melonjs/melonjs";

class SepiaEffect extends ShaderEffect {
    constructor() {
        super({
            name: "Sepia",
            fragment: `
                precision highp float;
                uniform sampler2D screen_texture;
                varying vec2 vUv;
                
                void main() {
                    vec4 color = texture2D(screen_texture, vUv);
                    float r = dot(color.rgb, vec3(0.393, 0.769, 0.189));
                    float g = dot(color.rgb, vec3(0.349, 0.686, 0.168));
                    float b = dot(color.rgb, vec3(0.272, 0.534, 0.131));
                    gl_FragColor = vec4(r, g, b, color.a);
                }
            `
        });
    }
}

// 应用
const sepia = new SepiaEffect();
me.game.viewport.addPostEffect(sepia);

// 3 秒后移除
setTimeout(() => {
    me.game.viewport.removePostEffect(sepia);
}, 3000);

相关链接

注意事项

  • 自定义着色器需同时提供 GLSL 和 WGSL 版本以支持 WebGPU。
  • screen_texture 是一个特殊的内置 uniform,良用于访问前一帧渲染结果。
  • Canvas 回退模式下效果不会抛出错误,应主动检测渲染器类型。
  • 建议在文档中记录颜色分量的取值范围(通常为 0.0 到 1.0)。

Individual skills in this repo

This repo contains 10 individual skills — each has its own dedicated page.

melonjs/melonjs-3d

Use this skill for anything 3D or 2.5D in melonJS — Camera3d, Mesh, InstancedMesh, Sprite3d billboards, Light3d, ground shadows, glTF/GLB scenes, and depth sorting. Covers the Y-down/+Z-forward convention that is the inverse of OpenGL, the cameraClass opt-in, clip planes, and what does not work on the Canvas fallback. Triggers on: Camera3d, Mesh, InstancedMesh, Sprite3d, Light3d, billboard, glTF, glb, 3D, 2.5D, depth, cameraClass, fov, setClipPlanes, setFog, fog, distance fog, height fog, heightFalloff, transparent, transparency, alpha, blendMode, fade, castGroundShadow, lit.

melonjs/melonjs-3d-assets

Use this skill when loading 3D models into melonJS — glTF and GLB scenes, OBJ/MTL models, materials, imported lights, node animation, ground shadows and GPU instancing. Covers level.load options including the async flag, the rightHanded conversion, and exactly what the loader does and does not support. Triggers on: glTF, gltf, glb, OBJ, MTL, 3D model, getGLTF, getOBJ, getMTL, GLTFModel, GLTFScene, level.load glb, rightHanded, lightIntensityScale, castGroundShadow, shadowGroundY, EXT_mesh_gpu_instancing, KHR_lights_punctual, skinning, Blender export, 3D asset.

melonjs/melonjs-camera-and-drawing

Use this skill for camera control and immediate-mode drawing in melonJS — following a target, viewport bounds, shake and fade, secondary cameras, and drawing shapes, lines and gradients inside a custom draw(). Covers world versus screen coordinate conversion, clipping and masking, and baking with CanvasRenderTarget. Triggers on: Camera2d, viewport, follow, setBounds, shake, fadeIn, fadeOut, worldToLocal, localToWorld, colorMatrix, renderer.fill, renderer.stroke, Rect, Ellipse, Polygon, Line, Gradient, clipRect, mask, CanvasRenderTarget, NoiseTexture2d.

melonjs/melonjs-loading-assets

Use this skill for loading and managing game assets in melonJS — the resource descriptor format, the full asset type list, preload versus load, retrieving loaded assets, base URLs and cross-origin settings, and the loading screen. Triggers on: loader, loader.preload, loader.load, resources, getImage, getJSON, getTMX, getGLTF, getVideo, getFont, setBaseURL, setOptions, crossOrigin, withCredentials, credentials, cookies, authenticated assets, CORS, asset, preload, LOADER_COMPLETE, loading screen, unload.

melonjs/melonjs-performance

Use this skill when a melonJS game drops frames, allocates heavily, or needs to scale to many objects. Covers object pooling, draw-call batching, atlases, baking with CanvasRenderTarget, instancing, culling and alwaysUpdate, the debug plugin, and where the real costs are. Triggers on: performance, slow, frame rate, fps, lag, pool, pool.register, pool.pull, batching, draw calls, InstancedMesh, culling, alwaysUpdate, inViewport, CanvasRenderTarget, optimise, profiling, debug plugin, memory.

melonjs/melonjs-physics

Use this skill for collision, physics bodies, movement, and spatial queries in melonJS — the built-in SAT world and the planck/matter adapters. Covers bodyDef vs Body, collision types and masks, the collision callback family and their firing rules, raycast/queryAABB/querySphere, and the behaviour differences between adapters. Triggers on: Body, bodyDef, collision, collisionType, collisionMask, onCollision, onCollisionStart, onCollisionActive, raycast, queryAABB, querySphere, PlanckAdapter, MatterAdapter, gravity, velocity, applyForce, isGrounded, SAT.

melonjs/melonjs-renderables

Use this skill when subclassing Renderable, writing a custom draw() method, handling pointer or click events on game objects, applying post effects and shaders, or controlling draw order. Covers the pos-relative draw contract, isKinematic and input, addPostEffect vs the deprecated shader property, and z-ordering. Triggers on: Renderable, extends Renderable, draw(, update(, isKinematic, pointerEvent, registerPointerEvent, onClick, addPostEffect, removePostEffect, ShaderEffect, addChild, z-order, anchorPoint, floating.

melonjs/melonjs-renderer-backends

Use this skill when a feature works on one machine and not another, when choosing or pinning a renderer, or when writing code that must degrade gracefully. Covers the WebGPU to WebGL 2 to Canvas fallback ladder, what each backend supports, capability detection, and the subsystems that warn once and then stop working on Canvas. Triggers on: video.AUTO, video.WEBGPU, video.WEBGL, video.CANVAS, renderer.type, supportsDepthBuffer, shaderLanguage, WebGPU, WebGL2, Canvas fallback, context loss, backen

melonjs/melonjs-scenes-and-state

Use this skill for scene structure and game flow in melonJS — Stage subclasses, the state manager, transitions, pausing, the update loop, timers and tweens. Covers onResetEvent versus the constructor, state.set before state.change, the camera and world lifecycle per stage, and pause-aware timing. Triggers on: Stage, state, state.set, state.change, state.transition, state.pause, onResetEvent, onDestroyEvent, onActivateEvent, onDeactivateEvent, PLAY, MENU, LOADING, update loop, GAME_UPDATE, timer, setTimeout, setInterval, Tween, freeze.

melonjs/melonjs-ui-and-text

Use this skill for HUDs, buttons, menus, dialogue panels and on-screen text in melonJS. Covers UIBaseElement/UISpriteElement/UITextButton, Draggable and DropTarget, the floating screen-space container pattern, Text and BitmapText, web font loading, and NineSliceSprite panels. Triggers on: UI, HUD, button, UIBaseElement, UISpriteElement, UITextButton, Draggable, DropTarget, menu, dialogue, Text, BitmapText, font, fontface, wordWrapWidth, NineSliceSprite, score display, floating.

相关技能