Shader API (surface.hlsl)

Surface shader API v6 - PackShade, PackSurface (extra UVs, head bone, sphere / toon slots), PackResult (normal / emission / tag), PackEdge, scene / audio inputs and extended parameter accessors.

Shader entry-point contract

Every surface shader pack’s surface.hlsl implements exactly one entry function:

PackResult PackShade(PackSurface s);

It runs for every material pixel of a character model and is called in place of MMDX12’s default shading calculation.

Compilation environment and caveats

  • Compiler: DirectX Shader Compiler (DXC), shader model 6.0.
  • HLSL standard: -HV 2018.
  • Header includes: #include inside surface.hlsl resolves relative to the pack folder.
  • Reserved words: line is an HLSL reserved word, so do not use it as a variable or function name.
  • Shader cache: compiled on first draw and stored in <MMDX12>/shader_cache. Editing pack files invalidates the cache and recompiles.

Input struct: PackSurface

The surface information the engine computes and passes in the pixel shader:

FieldTypeDescription
worldPosfloat3World-space position (MMD units, +Y up)
Nfloat3World normal (flipped toward the view direction when rendering back faces)
Vfloat3Unit vector from the surface toward the camera
Lfloat3Unit vector toward the main light (sun)
uvfloat2Texture coordinates
uv1float4PMX extra UV1 (0 for models without it)
uv2float4PMX extra UV2 (0 for models without it)
pixelfloat2Screen pixel coordinates (SV_Position.xy)
viewZfloatView-space depth
texfloat4Base texture (gamma space, material morphs applied, white if absent)
alphafloatMaterial alpha × texture alpha (below 0.004 is already discarded by the engine)
shadowfloatSun shadow (0: shadow .. 1: light). 1 for materials that receive no shadow
materialClassuintPACK_BODY / SKIN / FACE / EYE / HAIR / WEAPON
hasHeadboolWhether a head bone (頭, or 首 if absent) exists
headPosfloat3World position of the head bone
headRightfloat3Right of the model’s head (+X, unit length)
headUpfloat3Up (+Y, unit length)
headForwardfloat3The direction the face looks (MMD models face -Z)
headScalefloatWorld units per model unit (display scale)

Extra UVs (uv1, uv2) and sphere / toon slot textures are API v6 features. Packs detect them with the PACK_API_ADDUV macro.

Head-bone coordinate frame

To keep the face from distorting because of nose and cheek normal curvature during face shading, the head bone’s rotation frame is provided. If hasHead is false, the axes are the world axes.

Output struct: PackResult

struct PackResult {
    float3 color;         // linear HDR radiance (the default shading multiplies gSunIntensity itself)
    float alpha;          // final alpha
    float reflectivity;   // 0..1, SSR / RT reflection strength
    bool noAo;            // true: SSAO / RTAO does not darken this pixel (face); also disables reflections
#if defined(PACK_CAP_SURFACE_OUTPUT) && PACK_CAP_SURFACE_OUTPUT
    float3 normal;        // world space. Used instead of s.N for the normal target / SSAO / SSR / RT reflections
    float3 emission;      // linear HDR. Added to the lit colour like AutoLumEmission
    uint tag;             // 0..15, author bits. ID image bits 0-3
#endif
};

To use normal / emission / tag, declare "requires": ["surface.output"] in pack.json. Without that capability the struct is exactly the original four fields. The engine normalises normal, adds emission to the final colour, and writes tag to the lower 4 bits of the ID image (inputs.id).

Outlines: PackEdge

Outlines are drawn by the engine’s edge pass separately from PackShade. Define PACK_HAS_EDGE at the top of surface.hlsl and implement PackEdge to control outline colour and width per material.

#define PACK_HAS_EDGE 1

PackEdgeResult PackEdge(uint materialClass, float4 mmdEdgeColor, float mmdEdgeSize) {
    PackEdgeResult e;
    e.color = materialClass == PACK_HAIR ? float4(0.25, 0.12, 0.10, 1.0) : mmdEdgeColor;   // gamma-space RGBA
    e.widthScale = materialClass == PACK_FACE ? 0.5 : 1.0;   // multiplied by the MMD width, 0 = no outline
    return e;
}
  • PackEdgeResult: float4 color (gamma space, the same space as the MMD edge colour) and float widthScale (multiplied by the MMD width).
  • mmdEdgeColor / mmdEdgeSize are the PMX material’s edge values.
  • Without PACK_HAS_EDGE, outlines keep the engine defaults.
  • API v6: the edge vertex stage puts the vertex’s PMX extra UV2 into PackEdgeUv2 before calling PackEdge. You can use it for per-vertex width: e.widthScale *= PackEdgeUv2.x;
  • Pack outlines are drawn not only in raster and RT but also in offline GI.

Built-in helpers (pack_api.hlsli)

Parameters

  • float PackParam(uint i): the i-th slider value in manifest order (or its default).
  • Declaring params.ext reads from the 128 float4 slots and adds these accessors:
    • int PackParamInt(uint i)
    • bool PackParamBool(uint i)
    • float3 PackParamColor(uint i) / float4 PackParamColor4(uint i) (linear)
    • float3 PackParamVec3(uint i)
    • uint PackParamCount()

Material properties (gamma space, material morphs applied)

  • float4 PackDiffuse(): diffuse colour + alpha
  • float3 PackAmbient(): ambient factor
  • float3 PackSpecular(): specular colour
  • float PackSpecularPower(): highlight exponent
  • float PackEdgeReflectivity(): edge reflectivity

MMD lighting

  • float3 PackMmdLit(PackSurface s): saturate(ambient + diffuse * lightColor) * tex.rgb.

Sphere maps

  • uint PackSphereMode(): 0 none, 1 multiply, 2 add.
  • float3 PackSampleSphere(float3 N): sphere map by normal (view-space lookup).

Toon

  • bool PackHasToon(): whether the material has an MMD toon texture.
  • float3 PackSampleToon(float v): v=0 is the lit side, v=1 the shadow side. White if absent.

Sphere / toon slot textures (API v6)

The Project Sekai MME layout puts a UV-space parameter mask (_H) in the PMX sphere slot and a shadow colour (_S) in the toon slot. Both are sampled with mesh UVs (no sphere-map projection).

  • bool PackHasSphereTex(): whether a real sphere slot texture is bound (not the white fallback).
  • float4 PackSampleSphereUv(float2 uv): samples the original sphere texture with mesh UVs (wrap, material morphs applied).
  • bool PackHasToonMap(): whether the toon slot is a UV-mapped shadow colour (MAT_TOON_MAP).
  • float4 PackSampleToonUv(float2 uv): samples the original toon slot with mesh UVs (wrap, toon morphs applied).

Pack textures

Textures declared in pack.json are sampled by index in array order.

  • float4 PackSampleTex(uint i, float2 uv): samples with the declared address mode (wrap / clamp).
  • float4 PackSampleTexLevel(uint i, float2 uv, float lod): explicit mip level.
  • uint2 PackTexSize(uint i): level 0 size. 0, 0 if out of range.
  • uint PackTexCount(): the number of declared textures.

"srgb": true textures return linear values, so do not apply SrgbToLinear again. s.tex and PackMmdLit remain gamma space as before. "srgb": false returns stored values unchanged. Missing textures and out-of-range indices are white.

float3 ramp = PackSampleTexLevel(0, float2(saturate(dot(s.N, s.L) * 0.5 + 0.5), 0.5), 0).rgb;  // clamp ramp, linear
float4 lm   = PackSampleTex(1, s.uv);   // "srgb": false lightmap: raw channel values

Scene / audio inputs

Request them in "inputs" in pack.json and declare inputs.scene / inputs.audio in requires; the following functions then compile.

Scene

bool    PackInputValid(uint role);
float3  PackInputPos(uint role);
float3x3 PackInputFrame(uint role);   // row 0 = right, 1 = up, 2 = forward

Role constants: PACK_IN_PERFORMER_HEAD, PACK_IN_PERFORMER_CENTER, PACK_IN_PERFORMER_HAND_L, PACK_IN_PERFORMER_HAND_R, PACK_IN_PERFORMER_FOOT_L, PACK_IN_PERFORMER_FOOT_R, PACK_IN_LIGHT_KEY, PACK_IN_CAMERA_FOCUS, PACK_IN_AUDIO.

Audio

float PackAudioBeat();      // phase within the current beat, 0..1
float PackAudioDownbeat();  // phase within the bar, 0..1
float PackAudioOnset();     // attack envelope (about 0.25 s decay)
float PackAudioEnergy();    // normalised RMS of the current beat, 0..1
float PackAudioSection();   // energy section of the song (0 low / 0.5 mid / 1 high)
float PackAudioBpm();       // BPM

If there is no audio or analysis is not ready, all are 0.

PackResult PackShade(PackSurface s) {
    PackResult r;
    float3 base = PackMmdLit(s);
    float pulse = 1.0 + 0.15 * PackAudioOnset();
    r.color = base * pulse;
    r.alpha = s.alpha;
    r.reflectivity = 0.0;
    r.noAo = false;
    return r;
}

Engine environment variables

pack_api.hlsli / common.hlsli provide:

  • gLightColor (float3): sunlight colour
  • gSunIntensity (float): light intensity (multiply the final colour by it for day / night control)
  • gRimColor (float3), gRimStrength (float): global rim light
  • float3 Hemisphere(float3 n): hemispheric ambient between sky (gSkyZenith) and ground (gGroundColor)
  • float3 SrgbToLinear(float3 c): sRGB -> linear HDR
  • gTime, gView, gProj, gViewProj, gEyePos, gLightDir and other shared values in common.hlsli

Of the full list, the stable contract is the names written in this document and in pack_api.hlsli / pack_inputs.hlsli.