Skip to main content

shadersobj — Compiled shaders

Verified via reverse engineering

Container and index layouts decoded from the shipped shadersobj export and confirmed by round-tripping every one of the 1,698 Direct3D 9 objects byte-identically (ShaderObjectTests in JackAll). Path construction traced in Dunia.dll (0x10446180) via GhidraMCP. See intro for how RE-verified and community-reported claims are distinguished on this site.

shadersobj.dat (archive slot 0x24) holds every compiled shader in the game, under two parallel trees: engine\shaders\obj\ for the Direct3D 9 backend and engine\shaders\obj10\ for Direct3D 10. Only the D3D9 tree is described here; the D3D10 tree is plain DXBC in a different wrapper.

Nothing in the tree is named after a shader. A file is addressed by a 32-bit object hash and lives in one of 128 buckets:

engine\shaders\obj\h5d\shadernumber_3ffcc3dd.pso

The bucket is the hash's low seven bits — 0x3ffcc3dd & 0x7F = 0x5d — which is why the folders run h00..h7f rather than h00..hff. Three extensions appear: .pso (pixel shader), .vso (vertex shader) and .rs (render state).

Object container​

A .pso/.vso is a parameter binding table in front of stock Direct3D 9 bytecode.

OffsetSizeField
04Magic 8D 06 08 02
42Offset of the bytecode, always 12 + 8 × count
620x7F7F
81Kind, 4 in every shipped object
91Parameter count
1020x7F7F
128 × countParameter table
bytecode offsetto EOFvs_3_0 / ps_3_0 token stream

Each parameter row is:

OffsetSizeField
04CRC32 of the parameter's name
42Packed register: binding >> 6 is the register number
61Registers occupied; 0 when the shader does not use the parameter
71Registers per element, 4 for a matrix

The low six bits of the packed register sort parameters into kinds the corpus only partly explains: 12 is always a sampler and 8 always a constant, while 0, 9, 10, 16 and 20 also occur. JackAll preserves the field verbatim rather than reinterpreting it.

Names survive as CRC32​

The bytecode ships without its CTAB, so the binding table is the only record of which parameter feeds which register, and a name is only ever present as its hash. The hash is plain CRC-32 over the name in its exact case — TEXKILL, CelestialBodySampler — not the lowercasing that archive paths go through.

Names are recoverable by hashing a candidate dictionary and matching. Against the identifiers in the September 2008 prototype's HLSL sources, 44,507 of 44,610 bindings across the whole D3D9 tree resolve, or 99.8%.

The globals every shader inherits are bound at fixed registers, listed in the prototype's globalparameterproviders.inc.fx and registered at runtime by CViewportShaderParameterProvider (Dunia.dll:0x103788f0). ViewProjectionMatrix is always c4, FogColorVector c48, BloomAdaptationFactor c58, SunOcclusionFactor c63. A shader's own parameters start at c71. SkyColor, GroundColor and LightColor are among those own parameters rather than the globals, so their register changes from one object to the next.

Naming a draw in a running game​

Verified in a running game

Retail GOG v1.03, logged from an FCSE plugin hooking the device's draw calls.

The bytecode a bound shader returns through GetFunction is the bytecode stored in its object here, byte for byte. A draw seen at the device is therefore named by matching that bytecode's size and CRC-32 against the export. Not every draw matches: some vertex shaders bound in the sky pass match no object in the export.

Finding an object by what it binds​

A permutation whose index key is unknown can still be found by a parameter it binds, since every binding row carries the name's CRC-32. Searches over the D3D9 obj tree:

ParameterObjectsRegister
DepthVPSampler74, bytecode 196 to 5,332 bytess0 in every one
Saturation, ColorRemapData, ContrastData7c71 to c73 in the 244, 316 and 388 byte objects; c73 to c75 in the 440, 496, 512 and 568 byte ones
WindSimParamsX and MeshDecompression, without WorldMatrix39 .vso, the grass material—
LeavesMorphFact, LeavesEquations, DistanceFactors or LevelLOD, without TrunkStencil or TrunkUVDecompression97 .vso, tree leaves—

The grass material places its instances from vertex data, so its per-instance wind and rotation never appear as constants; the combination above is what is left to find it by. The tree trunk binds DistanceFactors and LevelLOD too, which is why the trunk's own constants rule it out.

Grass lit by the sun is in the unnamed objects​

Verified via reverse engineering

Measured on GOG in savannah and jungle, by the bytecode of every grass draw, over three launches that gave the same CRCs.

The 39 named grass .vso draw grass only into depth: the linear depth pass, and its alpha-tested near grass. Grass lit in the HDR scene pass comes through objects the hash list has no name for, at _unknown\<hash>.bin in an export. The D3D9 tree holds 2,844 vertex shaders, all vs_3_0, and 456 of them read c32 to c34. The CRC is of the bytecode the device hands back, not of the object:

Vertex shaderPixel shaderDraws
736F4429D26F57AE, B65F81B2 with alphalit by the sun, one shadow map slice
50B69F13FA083E8Flit by the sun, shadow cascades
0701D375D26F57AEthe same for bent clumps, placed through a rotation from the instance data
A08FE8BF, 7601537EABB7093Clit without a shadow
05D4DC7E, 94B542065D532300an omni light's additive pass, depth test equal
D6110861, DC1C293C5D532300, 8FE88A8C with alphaa spot light's additive pass, depth test equal, upright and bent
AFCC79D6320F2CEC, E2CA3564 with alphathe same for an upright clump, receiving the light's shadow

These CRCs are at 4x multisampling with very high vegetation. With multisampling off and low vegetation the spot pair upright is 270DCCA2 and 84DD1CBD, so nothing that reaches every player can match on them. What tells a spot light's additive pass from the rest in any setting, exactly 80 of the 2,844:

  • three dp3 reading c32 to c34, which only grass has;
  • one unsaturated dp3 with a constant as its second source, the light's direction for the cone. Omni has no such dot, the sun's is saturated, and the depth pass has the constant first;
  • no read of FogColorVector at c48. 80 more have both of the above and read it: a clump's first pass, ambient and spot light together, and only a first pass writes the fog's colour. None was drawn in any run measured.

The omni pair has the same two faults as the spot passes: mul o1.w writes the fog's amount where an additive light wants what the fog leaves, and the diffuse is a saturated dot with the ground's normal. The only omni light measured drew for a few seconds after each load, at the player, in a colour of (0, 0.4, 0.5), with c72.x, its falloff, under 0.0005.

A light that casts shadows draws grass through both of its passes in one place, and which one a draw gets changes as the camera turns. Over a full turn in long grass the shadowed pass took 374,226 instances and the unshadowed 3,682. What decides it is not traced.

Every grass vertex shader, shipped or built, turns each clump by GrassCylindricalBillboardMatrix at c32 to c34, reading only xyz: one camera heading shared by every clump, so each faces the eye. The savannah meshes are flat sheets whose blades all face within about 22° of one direction, which is why the turn is needed.

The lit pair splits the work so that the vertex shader holds all the light. The pixel shader draws texture × (TEXCOORD1.rgb + TEXCOORD2.rgb × shadow), fogged by the two .w values. Per vertex, 736F4429 computes:

  • ambient: (instance colour × 2.5 + the clump's sky occlusion) × SkyColor × ½;
  • sun: saturate(ground normal · sun) × LightColor, plus a glint pow(…, 7) on a pattern built from position and wind rather than a normal;
  • both × instance colour × vertex colour × 4, and × 1 + a wave from the wind's lean.

Its registers match the prototype's global table (ViewProjectionMatrix c4, CameraPosition c45, FogColorVector c48, FogValues c51, FogHeightValues c52, WindSimParamsX and WindSimParamsY c65 and c66) and then ShadowProjectionMatrix c71 to c73, MeshDecompression c74, LightColor c75, LightDirectionWS c76, the shadow's fades c77 to c79, SkyColor c80 and DiffuseTiling1 c81. The shadowless pair moves LightColor, LightDirectionWS and SkyColor to c72 to c74. A replacement that repeats 736F4429's placement instruction for instruction lands on the depth the depth pass wrote; Sky Overhaul's grass.fx does.

How a shadow read spreads its samples​

Every one of the 272 retail pixel shaders that binds ShadowMapSize reads the shadow map 8 times around the point and averages, with the samples ShadowMapSize.zw, one texel, apart times a factor. The 158 that pick their cascade per pixel carry the factor in one def (encoded 0x05000051): 0.5, 1/6, 1/3, 1, the near, middle and far slice's spread in its own texels, chosen by a dp4 against the one-hot slice. Of the 114 others, 87 bind CascadedShadowTexelScale and take the factor from its x, set per draw; the remaining 27 were not examined. No other register is read with ShadowMapSize.zw, so scaling it widens every shadow alike; scaling the def widens the farther slices alone.

A row's registers-occupied field is nonzero for many viewport globals in every shader searched, the water reflection constants in grass among them, so a global's row alone does not show that a shader reads it. The material's own parameters are the ones to search by.

The seven are the final pass of the prototype's posteffect_adaptivebloom.fx. The four larger ones also bind BloomParams at c71, LuminanceRange at c72 and LuminanceAdaptationRange at c76 with the adapted luminance at s2; the 244-byte one binds no bloom at all. No retail object binds the prototype's PowLUTSampler variant.

Render states​

A .rs is plain text, one Key=Value per line, and matches the technique block of the shader's source one for one:

AlphaBlendEnable=true
BlendOp=Add
ZWriteEnable=false
CullMode=None

Only states the source names are present. Anything absent is inherited from whatever the renderer set last, so a shader that never mentions ZEnable does not control its own depth test. Editing one of these needs no compiler.

Index tables​

Three tables sit at the root of each tree — index.pso, index.vso, index.rs — mapping a shader permutation to the object it loads.

OffsetSizeField
04File size
44"DAEH"
84Version, 10
124File size − 4
164File size − 24
204Zero
244Entry count
288 × countEntries, sorted ascending by key

Each entry is a 32-bit permutation key and a 32-bit object hash. A hash of zero is a real answer meaning the permutation binds no object of that kind — a shader that overrides no render state, say.

The D3D9 tables carry 147,140 permutations for .pso/.vso and 147,200 for .rs, against 1,698 objects actually present in the export: one object serves many permutations, and permutations that differ only in a define with no effect on the PC build (TEXKILL) share one file.

The permutation compiled with no options keys on the CRC32 of the shader's source name. That is confirmed for 30 shaders, and it is how a named shader is located at all. Shaders whose option domain has no empty case — cloudlayer, which requires LAYER1 or LAYER2 — correctly have no such entry.

An option-bearing permutation keys on the CRC32 of a string built from its options (BuildPermutationKey, 0x104267a0 in the GOG build, RE-verified):

<shader name>, then for each option the permutation sets, in ascending CRC32 of the option's name:
"_" + the option's index in the shader's define list
+ "-" + (value - 1) + "of" + max only for an option that has a maximum value

The index counts the shader's <define>s in declaration order, the define list that fastinitdata_d3d9.bin stores for each shader. A boolean option has no maximum and adds only _<index>. So celestialbody_3_4_2_5 is celestialbody with TEXKILL, ADDITIVE, TOD_COLOR and FAKEHDR set, and burnterrain_0-0of31 to burnterrain_0-31of31 are the 32 values of a ranged option.

Every permutation is named this way. Building the key of each of fastinitdata's 147,828 permutations reaches every key of all three D3D9 tables, 147,140 in index.pso and index.vso and 147,200 in index.rs, with none left over (seen in data). The 686 permutations no table holds are the editor's PICKING variants and console-only grass.

What fastinitdata_d3d9.bin holds​

Verified via reverse engineering

Layout read from the loader CSceneRenderer_Init calls (0x10436620, one shader at 0x10443010, Steam Dunia.dll) and walked over the retail file, which it consumes to the last byte.

common\engine\shaders\fastinitdata_d3d9.bin lists every permutation the game was compiled with and every shader's options. It is big-endian, and a string is a 2-byte length then ASCII. The D3D10 build reads fastinitdata_d3d10.bin instead.

FieldSizeContents
Version41
Permutation count4147,828
Permutations8 × countOption masks, ascending
Shader count486
Shaders—One record each, below
Trailer5AllOk

A mask's low byte is the shader's 1-based position in the shader list, and its other bits are the options the permutation sets. The options every material shader shares, from meta\commonoptions.xml, sit at bits 8 to 30 in that file's order (SHADOW 8, RECEIVE_SHADOWS 9 … ALPHA_TO_COVERAGE 30); a shader's own options start at 31. A ranged option takes as many bits as its largest value needs, and holds the value plus one.

One shader record:

FieldContents
NameString
7 masks8 bytes each: the options that matter to each stage, the SHADOW, DEPTH and PICKING bits, and the bits valid on this platform
Next free bit4 bytes
OptionsA 4-byte count, then per option its CRC-32 (exact case), its name, its bit and its maximum (FFFFFFFF for a boolean), sorted by CRC
PreloadsA 4-byte count, then per variation to load early a mask and a byte: 1 receives shadows, 2 shadow pass, 4 depth pass
DefinesA 4-byte count, then the names in declaration order, the index a permutation key uses
3 stringsEmpty in every retail shader
2 masks, a 4-byte wordZero in every retail shader
LOD level count4 bytes
8 LOD masks8 bytes each, ANDed into a permutation at that material LOD level
Flag1 byte
PairsA 4-byte count, then two 4-byte hashes each

celestialbody's options are TIME_OF_DAY_MAPPING 31, VISIBILITY_TEST 32, TIME_OF_DAY_COLOR 33, TEXKILL 34, ADDITIVE 35 and FAKEHDR 36. The LOD masks are the source's <lod level="N"> lines inverted: aaa drops REFLECTION at level 1, then SPECULARMAP as well, then NORMALMAP as well at level 3. Without this file the engine builds the same tables from the meta\*.meta.xml sources (0x10436d50).

Which quality draws an object​

A permutation's options come from the material, the pass and the lights, and then the quality settings change them. engine\settings\defaultrenderconfig.xml holds both halves of that. Its <RenderQuality> presets (low, medium, high, veryhigh, ultrahigh, and D3D10 versions) each pick a level for every setting (VegetationQuality="veryhigh", ShadowQuality="off" …). Under a setting's element, each level can list what it adds to or removes from a shader's options:

<Vegetation>
<quality id="low">
<Shaders>
<shader name="AAA" add="" remove="SPECULARMAP,NORMALMAP,REFLECTION,AMBIENT_SPECULAR"/>
<shader name="Mesh_Grass" add="GRASSQUALITYLOW" remove="" />

CRenderShaderConfig (0x103f43b0) registers those four attributes: name, add, remove and csmExcludeMask. Five settings change shader options this way:

SettingShaders it changes
EnvironmentCloudLayer: CLOUD_QUALITY_LOW, _MEDIUM, nothing at high, _ULTRAHIGH
TextureMesh_Weapon: QUALITYLOW, QUALITYMEDIUM, QUALITYHIGH; Mesh_Skin and Mesh_Vehicle lose NORMALMAP at low
WaterWater and WaterRiver lose HIGHQUALITYNORMALS below veryhigh, and more below high
VegetationAAA, AAALeaf, Mesh_BigLeaf and RealtreeTrunk lose features at the lower levels; Mesh_Grass gets GRASSQUALITYLOW, MEDIUM, CONSOLE at high, HIGH at veryhigh
TerrainTerrain loses PER_PIXEL at low; Road loses PARALLAX at every level but ultrahigh

The weapon and grass quality options are never named in Dunia.dll; this data is the only thing that sets them. Shadows are the other quality switch: the off level, which the low preset picks, sets DisableShadow and DisableShadowGeneration, so no shadow pass and no shadow receiver draws. That last step is inferred from the setting's names, not traced.

The remaining options do not follow the presets:

  • the shadow filter is picked by the GPU when the renderer starts (0x10385300): HW_SM_COMPARE where the card compares depth in hardware, else FETCH4 where it has Fetch4, else SIMPLE_SHADOWMAP;
  • SAMPLES2 and SAMPLES4 follow the anti-aliasing setting, ALPHA_TO_COVERAGE its own setting;
  • HEMI_*, SHADOW_CRUDE_BIG_KERNEL, RECEIVE_SINGLE_CASCADE and the material LOD masks are chosen per draw. HemiQuality is 2 at every PC level, so it changes nothing between presets.

jackall-cli shader label applies these rules to every permutation that loads an object, so it can say which presets draw that object.

The Map option​

A material's Generic shader is AAA in the shader tables, and the material's Map integer sets its MAP option, which the map's paper (MAPTOP) carries. Comparing a permutation with and without it (SUN, AMBIENT, HEMI_SIMPLE, RECEIVE_SHADOWS, DIFFUSE_MAP_BASE), read from the compiled objects:

  • Ambient. Without MAP the vertex shader blends the hemisphere's ground and sky colours by which way the surface faces and by its height. With it, every vertex takes the sky colour at half strength, whichever way it faces.
  • Shade. The pixel shader adds 0.2 to the sun's shadow term, so a map in shade keeps a fifth of the sun.
  • Colour. The pixel shader skips the blend from DiffuseColorBase to DiffuseColor1 by the vertex colour and takes DiffuseColor1 alone.

So a material with Map is lit flatly and never fully shaded. Without it, Map Overhaul's sheet takes the world's light like the hands holding it (seen in game).

Tooling​

jackall-cli shader index engine/shaders/obj --shader celestialbody
jackall-cli shader extract shadernumber_3ffcc3dd.pso -n names.txt
jackall-cli shader build shadernumber_3ffcc3dd.bin
jackall-cli shader label --game <dir> -o fc2.shaderlabels.tsv

label writes one line per D3D9 object: what its shaders draw, its passes, the options all its permutations share, the presets that draw it, the settings that decide that, and one of its permutations' names. tools/asset-tags/build.py turns them into the shader tags JackAll's Files tab shows and searches with tag:.

extract splits an object into its bytecode (.bin, which fxc /dumpbin disassembles) and its binding table (.xml); build reassembles them, dropping the constant table fxc emits so the result matches the shipped convention. See replacing a shader for the whole loop.