Skip to content

t1k:cocos:base:effect-authoring

FieldValue
Modulebase
Version4.51.9
Effortmedium
Tools—

Keywords: cceffect, ccprogram, chunk, effect, glsl, include, macro, material, mtl, shader, uniform

/t1k:cocos:base:effect-authoring

Hand-authoring .effect files for Cocos Creator 3.8.7. Covers the whole chain from GLSL to a material visible on a node: pick the archetype, get the chunk includes right, pack properties, author the .mtl, wire it up, verify it compiled.

The expensive part of Cocos shader work is not writing GLSL — it is the include graph and the fact that a failed import reports EFX2406: compilation failed: EXPAND THIS MESSAGE FOR MORE INFO and nothing else. This skill exists to make the first attempt compile, and to make the second attempt diagnosable.

Version scope: claims below are verified against 3.8.7 only. § 3 includes the procedure to re-verify on another version — run it rather than assuming.

  • Writing a new .effect from scratch, or porting one from another engine (pair with t1k-cocos-base-unity-shader-port).
  • An .effect fails to import and the editor error is unreadable.
  • A material exists but does not show up on the node, or MCP refuses to assign it.
  • Reviewing an existing .effect for the anti-patterns in § 7.
QuestionYes →No →
Rendered under a Canvas (Sprite / Label / UI)?B. UI sprite → references/archetype-ui-sprite.mdnext
Time-scrolled, additive, no depth (background flow, glow, energy)?C. Scroll-additive VFX → references/archetype-scroll-vfx.mdnext
Needs world position or world normal (fresnel, rim, world-space FX)?A. 3D unlit mesh → references/archetype-3d-unlit-mesh.mdA, minus the world-matrix includes

Archetype D — imported from DCC (a 400+ line multi-technique surface shader, e.g. imported-specular-glossiness-fade.effect): do not hand-author or hand-edit these. Change the material’s property values; if the shading model itself is wrong, re-export from the DCC tool.

CCEffect %{ ...YAML... }% ← techniques / passes / render state / properties
CCProgram <name> %{ ...GLSL... }% ← one block per shader stage, referenced as `<name>:<fn>`

A pass wires them: vert: my-vs:vert means “program my-vs, entry function vert”.

The single most important behavioral fact: the editor compiles every macro variant, not just the one your material uses. A #if branch that never runs at runtime still has to compile. This is why a missing include breaks the import even for a mesh that is never instanced — see § 3.

Each row is verified against engine chunk source at <CocosInstall>/resources/resources/3d/engine/editor/assets/chunks.

You needIncludeEvidenceTrap
World matrix (pos/normal)legacy/decode-base and legacy/local-batchdecode-base.chunk:13-16 declares the attributes; :32-38 declares a_matWorld0/1/2see “world-matrix trap” below
Skinned meshlegacy/input-standard (instead of decode-base alone)input-standard.chunk:12-21 — CCVertInput calls CCSkin(position, normal, tangent)An unskinned normal freezes a fresnel rim in bind pose while the mesh animates under it
Sprite texture (2D/UI)#pragma builtin(local) + layout(set = 2, binding = 12) uniform sampler2D cc_spriteTexture;all three builtin 2D effects use binding = 12do not also include decode-base — it declares a_position, and your own declaration then collides
Alpha testbuiltin/internal/alpha-test, then call ALPHA_TEST(color)alpha-test.chunk:9-19, two overloads (vec4, float)the uniform block only exists under USE_ALPHA_TEST; calling it unguarded is fine, the macro handles it
Timebuiltin/uniforms/cc-global → cc_time.x—
Local world matrix without instancingbuiltin/uniforms/cc-local → cc_matWorld—guard behind #if USE_LOCAL for 2D
Colour output (tone mapping)legacy/output-standard for linear-space frag() returns; legacy/output only for colours already in display spaceoutput.chunk:5-7 returns the colour unchanged; output-standard.chunk:6-17 tone-maps and applies LinearToSRGBsee “output-include trap” below

The world-matrix trap — why two includes, not one

Section titled “The world-matrix trap — why two includes, not one”

legacy/local-batch declares no attributes, and world-transform’s USE_INSTANCING branch reads a_matWorld0/1/2, which only decode-base declares. The editor builds every variant, so world-transform without decode-base fails every time (EFX2406 … 'a_matWorld0' : undeclared identifier). Dead ends and the verbatim block: references/include-and-verify-detail.md § “World-matrix trap”.

The output-include trap — legacy/output is a pass-through, legacy/output-standard tone-maps

Section titled “The output-include trap — legacy/output is a pass-through, legacy/output-standard tone-maps”

Both chunks define CCFragOutput(vec4), and both compile. They do not do the same thing:

legacy/output returns the colour unchanged; legacy/output-standard tone-maps and encodes to sRGB (verbatim bodies: references/include-and-verify-detail.md § “Output chunks”).

Pick by the space your frag() returns, not by name similarity:

  • legacy/output-standard — the default for anything that renders a shaded surface. Your frag() works in linear space (mainColor: { linear: true }, SRGBToLinear(texture(...)) samples, any ported shader that expects tone mapping) and relies on the chunk to finish the conversion. Every coloured builtin does this: builtin-unlit.effect’s unlit-fs includes legacy/output-standard and returns CCFragOutput(o) from a linear mainColor.
  • legacy/output — only when your frag() already returns display-space colour. In stock 3.8.7 the users are the editor’s own non-surface passes — planar-shadow-fs (builtin-unlit.effect), outline-fs, builtin-camera-texture, builtin-debug-renderer, builtin-geometry-renderer, builtin-wireframe, the gizmos — each returning a flat unlit constant, plus the shipped effect template below. None of them is a shaded material archetype.

The one that catches people: the shipped effect template is a legacy/output template. <CocosInstall>/resources/resources/3d/engine/editor/assets/default_file_content/effect/default.effect includes legacy/output and multiplies mainColor * texture(mainTexture, v_uv) straight into CCFragOutput(col). Its properties are declared without linear: true (mainColor: { value: [1,1,1,1], editor: { type: color } }), so the template is internally consistent: display-space colour in, display-space colour out, no conversion either way.

The trap opens the moment you take that template and make it a linear-space shader — add linear: true to a colour property (the engine then converts the authored value to linear on upload, effect-asset.ts:46), or sample a texture through SRGBToLinear(...) as the builtins do — while leaving the legacy/output include untouched. If you go linear, switch the include in the same edit.

The failure is silent and visual, never a compile error: with legacy/output, a linear-space colour skips the sRGB encode and reads oversaturated and warm. A ported playable floor authored as pale sand (#ECCC9C) rendered visibly orange; switching the one include to legacy/output-standard fixed it. If a ported shader’s colours look too saturated, too warm, or too contrasty against the reference, check this include before you touch the colour values — the numbers are usually right and the encoding is wrong.

Both branches are macro-gated, so the tone map only actually fires under CC_USE_HDR with CC_TONE_MAPPING_TYPE == HDR_TONE_MAPPING_ACES; the LinearToSRGB encode is the part that always applies when CC_USE_FLOAT_OUTPUT is off. Do not “fix” a colour by hand-encoding LinearToSRGB in frag() while also including output-standard — that double-encodes and washes the colour out.

Re-verifying on a version other than 3.8.7

Section titled “Re-verifying on a version other than 3.8.7”

Re-run the chunk-name grep and copy the include block from that version’s own assets/effects/builtin-unlit.effect; grep before you guess (commands: references/include-and-verify-detail.md § “Re-verify chunk names”).

Full reference: references/properties-and-macros.md. The conventions that matter:

  • Pack scalars into a vec4, don’t give each float its own uniform:
    emissionPower: { value: 1.0, target: params.x, editor: { displayName: Emission Power } }
    fresnelPower: { value: 0.0, target: params.y, editor: { slide: true, range: [0.0, 10.0], step: 0.01 } }
    uniform Constants { vec4 mainColor; vec4 params; };
  • Name the uniform block Constants.
  • editor: { parent: USE_XXX } hides a property until its macro is on; visible: false hides the raw packed vector.
  • Declare an optional feature as a macro and gate both the sampler and its use:
    #if USE_EMISSIVE_MAP
    uniform sampler2D emissiveTexture;
    #endif
  • target: destroys the property name — GLSL only sees the target. A property declared mainColor: { target: albedo } has no mainColor identifier to compile against; referencing it in a surface function is EFX2406 … 'mainColor' : undeclared identifier, while material.setProperty('mainColor', …) still works (the alias is resolved one layer up). Separately, a declarator’s name is in scope in its own initializer, so vec4 baseColor = vec4(mix(baseColor.rgb, …)) reads the uninitialised local — no error, silently wrong output. Details: references/properties-and-macros.md.

A .effect that “looks fine” and a .effect that imported are different things. Always run this.

Step 1 — force the import. A running editor does not pick up newly written asset files on its own: call manage_asset action=refresh url=db://assets/<your-folder> over the project MCP (curl form: references/include-and-verify-detail.md § “Force the import”). The MCP port is per project — read it from <project>/settings/mcp-server.json; 3000 is only the extension’s shipped default, so a refused connection usually means “wrong port” or “server not started” (autoStart defaults to false), not “editor closed”.

No MCP? Use the editor’s Assets → Refresh. Never hand-write the .effect.meta — let the editor generate it.

Step 2 — check the artifact. A successful import writes library/<first 2 chars of uuid>/<uuid>.json:

Terminal window
UUID=$(grep -o '"uuid": "[^"]*"' path/to/my.effect.meta | head -1 | cut -d'"' -f4)
ls "library/${UUID:0:2}/$UUID.json" && echo COMPILED || echo FAILED

No artifact = this effect failed to compile. There is no other reliable per-effect signal. Exception: if EVERY program on the page failed with a null info log, the WebGL context was lost; that says nothing about your GLSL (references/unity-port-rendering-gotchas.md row 2). Step 2 — check the artifact. A successful import writes library/<first 2 chars of uuid>/<uuid>.json. Lookup command: references/include-and-verify-detail.md § “Check the artifact”. Decode what you find with references/troubleshooting.md.

Full detail: references/material-and-wiring.md.

.mtl is plain JSON referencing the effect by uuid. Colors are integers 0–255, not floats 0–1:

{
"__type__": "cc.Material",
"_effectAsset": { "__uuid__": "<effect uuid>", "__expectedType__": "cc.EffectAsset" },
"_techIdx": 0,
"_defines": [ { "USE_EMISSIVE_MAP": true } ],
"_props": [ { "mainColor": { "__type__": "cc.Color", "r": 255, "g": 242, "b": 242, "a": 255 } } ]
}

MCP cannot assign a MeshRenderer material array. set_property on sharedMaterials / _materials silently no-ops (changeVerified: false), passing an array value hangs the editor for ~2 minutes then times out, and the indexed path sharedMaterials.0 is rejected outright. Mesh assignment (property: "mesh") works normally.

Workaround: hand-author a small .prefab with _materials baked in, refresh, then manage_node create assetUuid:<prefab>. Recipe in references/material-and-wiring.md.

Runtime material hard rules — macros gate uniforms, blend lives on the target

Section titled “Runtime material hard rules — macros gate uniforms, blend lives on the target”

Three silent failures when driving a builtin-standard (or any macro-gated) material from code:

  • material.setProperty('mainTexture', tex) does NOTHING unless USE_ALBEDO_MAP is defined. In builtin-standard.effect the sampler is declared and read inside #if USE_ALBEDO_MAP — uniform sampler2D albedoMap; then texture(albedoMap, ALBEDO_UV) — so without the define the uniform does not exist in the compiled shader and setProperty binds to nothing, with no warning. The model renders with the flat albedo colour (white), indistinguishable on screen from “the textures failed to load”. Macros must be passed at material.initialize({ effectName, defines }), or via recompileShaders(defines) on an already-instanced material (a plain shared Material asset refuses that call — see the next bullet); setting the property afterwards cannot enable them.
  • BlendState has no enabled property. The flag that actually enables blending is targets[i].blend. Assigning blendState.enabled = true silently adds a stray field and the material stays opaque. For glTF alphaMode: BLEND, prefer technique: 1 (transparent) on builtin-standard, which already ships src_alpha / one_minus_src_alpha and depthWrite: false.
  • recompileShaders() on a plain (non-instanced) Material asset is a warn-only no-op — it logs “cannot be modified at runtime, please instantiate the material first” and leaves pass.batchingScheme unchanged. To add a define (e.g. USE_INSTANCING) to an already-authored material while keeping its other pass state (mainColor, etc.), construct a copy and pass the define at construction: new Material().copy(authored, { defines: { USE_INSTANCING: true } }).

Full mechanics + a minimal runtime example: references/runtime-material-macros.md.

Porting from Unity: the shader is usually right, the pipeline around it is not

Section titled “Porting from Unity: the shader is usually right, the pipeline around it is not”

Washed-out grey frame (scene HDR toggle vs legacy/output-standard ACES), gamma reference needing out*out, cc_fogColor arriving squared, builtin-toon having no ambient, nothing rendering because gfx-webgl2 is off, _defines needing one record per pass, queue-to-priority, mirrored renderers, HDR particle blend, hit flash (a tint cannot draw it): references/unity-port-rendering-gotchas.md. Lint .mtl _defines against the effect’s pass count: bun scripts/lint-mtl-defines.cjs <dir>.

Full-screen post-process pass — do NOT use the Custom pipeline name in 3.8.7

Section titled “Full-screen post-process pass — do NOT use the Custom pipeline name in 3.8.7”

custom-pipeline-post-process is hidden: true, default: false and stays out of the editor preview build even with engine.json, includeModules and CUSTOM_PIPELINE_NAME = "Custom" all set: cc.BlitScreen is undefined and the preview throws Cannot read properties of undefined (reading 'windowResize') every frame. Keep CUSTOM_PIPELINE_NAME at Builtin, put BuiltinPipelineSettings on the camera, and add a component extending BuiltinPipelinePassBuilder (addRenderPass + addFullscreenQuad); the effect’s pass: must equal the layout name. Order 350 = after tone mapping, before FXAA. Recipe: references/custom-pipeline-post-process-pass.md.

Don’tWhy
Guess a chunk namecc-local-batch vs cc-local-batched costs a full import cycle. Grep the chunks folder.
Give every float its own uniformWastes uniform slots and makes the material editor a wall of fields. Pack into vec4.
Hand-write .effect.metaThe editor owns the uuid. Write the .effect, refresh, let the meta appear.
Declare in vec3 a_position; after including decode-baseERROR: 0:154: 'a_position' : redefinition
Declare in vec2 a_texCoord; after including legacy/decode-basedecode-base already declares it (layout(location = 2) in vec2 a_texCoord;) — fails import with EFX2406: compilation failed ... 'a_texCoord' : redefinition. Use the attribute directly (v_uv = a_texCoord;); declare it yourself only in programs that don’t include decode-base / input-standard.
Edit one effect of a shared-math pairEffects that port the same source shader (e.g. a body and a prop variant) drift apart silently. Note the pairing in a header comment and change both.
Treat “it compiled” as “it works”The binding number on a builtin-tagged sampler is not compile-validated — see references/archetype-ui-sprite.md.
Include legacy/output in a linear-space shaderIt is a pass-through: no sRGB encode, no tone map, so colours read oversaturated and warm (a pale sand floor turns orange). Use legacy/output-standard and see “the output-include trap” in § 3.
FileContents
references/archetype-3d-unlit-mesh.mdVerified skeleton, fresnel/rim math, skinning, instancing
references/archetype-ui-sprite.mdVerified skeleton, cc_spriteTexture binding caveat, 2D macros
references/archetype-scroll-vfx.mdVerified skeleton, additive state, UV scroll + noise distortion
references/properties-and-macros.mdFull editor: field table, packing rules, #pragma define-meta, target: alias-vs-GLSL-name rule
references/material-and-wiring.md.mtl schema, MCP limits, bake-prefab workaround
references/troubleshooting.mdError code → cause → fix, with verbatim messages; EFX1001 YAML-vs-#-comment parser trap, EFX2207 duplicate UBO (declare once in shared-ubos), target: alias undeclared identifier, silent init-scope trap
references/runtime-material-macros.mdmaterial.setProperty needs the macro defined (USE_ALBEDO_MAP); BlendState.enabled does not exist — use targets[].blend or technique: 1; recompileShaders() is a no-op on a plain Material asset — use copy(src, { defines })
references/unity-port-rendering-gotchas.md13 rows (rule, symptom, fix, evidence) for Unity ports: gfx-webgl2 off, lost-context false compile errors, scene HDR vs ACES, gamma out*out, squared cc_fogColor, builtin-toon no ambient, hit flash, _defines per pass, queue to priority, isFrontFaceCCW for mirrored renderers, overridePipelineStates, HDR particle blend, generated materials. Script: scripts/lint-mtl-defines.cjs
references/custom-pipeline-post-process-pass.mdFullscreen post-process in 3.8.7: custom-pipeline-post-process is hidden/default-off so Custom pipeline throws windowResize; use Builtin + BuiltinPipelinePassBuilder, pass: = layout name, order 350, sqrt-encoded LDR input, @property(Boolean) warning

Running scripts/lint-mtl-defines.cjs (report-only) and tabulating its findings is mechanical: t1k-list-classifier. Authoring or editing .effect/.mtl files stays on t1k-cocos-base-developer (reasoning tier).

  • t1k-cocos-base-unity-shader-port — porting from a Unity .shader. It produces a port spec (archetype, property table, render state, translated fragment math) and hands off here for the actual file. Start there when the source is Unity; start here when authoring fresh.
  • t1k-cocos-base-apk-port/references/ui-rule.md — a renderer’s own colour alpha multiplies into every descendant in Cocos (Unity’s does not), and the invisible-UI-node triage: UI-side lessons, not repeated here.
  • t1k-cocos-playable-unity-particle — Unity ParticleSystem prefab conversion. Its materials still need an .effect; this skill covers that half.

Rule visual-change-discord-notice: authoring a shader or material is a visible change. Capture OLD before the first edit and NEW after the last (preview-verify shot steps, or the image file itself for a 2D asset), return the paths and a draft Discord post (what changed, undo = revert the PR) to the orchestrator, who posts; never post from here. Logic-only: no visible change. No capture possible: screenshots pending: <reason>, never a mock image. The PR needs the Discord link or visual-notice-waiver: <reason>; the owning agent’s Visual change notice section has the full steps.