acdream/src/AcDream.Core/Meshing/CellMesh.cs
Erik 517d17b4b3 fix #426: extract solid-colour (NO_POS_UVS) faces; skip untextured subsets only on building shells and cells like retail
The Holtburg windmill axle (GfxObj 0x010010CE, 8 polygons, all
Stippling.NoPos + SurfaceType.Base1Solid) extracted to a 0-vertex mesh.
NoPos ("NO_POS_UVS", acclient.h:7380-7388) means "this side has no
texture coordinates" — true of every solid-colour polygon, since
nothing samples them — not "there is no positive face". Extraction read
it as the latter and dropped the polygon entirely, client-wide, for
every untextured polygon on every object.

Retail's D3DPolyRender::DrawMesh (@0x0059d4a0, named-retail decomp
~line 426048) draws an untextured subset on an ordinary object exactly
like a textured one; the only retail cases that skip an untextured
subset are a building shell (RenderDeviceD3D::DrawBuilding @0x0059f2a0
sets ObjBuildingOrBuildingPart=1) or an EnvCell interior
(RenderDeviceD3D::DrawEnvCell @0x0059f170, arg4=1). The #119
investigation's "retail's skipNoTexture never draws them either"
conclusion was itself wrong as a general rule.

- MeshExtractor.PrepareGfxObjMeshData / GfxObjMesh.Build: emit the
  positive side whenever PosSurface is a valid index, regardless of
  NoPos; the existing UV-index-0 fallback already produces zero
  texcoords for a NoPos polygon with no UVs on the wire.
- RetailUntexturedSurfacePolicy.IsUntextured(SurfaceType): the one
  place that answers "is this surface textured"
  ((type & (Base1Image|Base1ClipMap)) == 0), replacing the old
  `isSolid = NoPos || Base1Solid` (which also mis-classified a NEG-side
  batch by the POS-side's NoPos flag).
- RetailUntexturedSubsetPolicy.Draws(isBuildingShell, isUntextured):
  the shared draw-time gate wired into WbDrawDispatcher.ClassifyBatches,
  .PackedOracle.ClassifyPackedBatches, and
  .DirectionalShadows.AddDirectionalShadowBatches — one predicate so the
  three walks cannot drift (Campaign VM VM6 lesson).
- CellMesh.cs / MeshExtractor.PrepareCellStructMeshData deliberately
  KEEP their NoPos-gated skip for cell-wall geometry — retail's
  DrawEnvCell really does skip untextured subsets there; register row
  AP-234 documents the NoPos-vs-Surface.Type approximation.
- PakFormat.CurrentBakeToolVersion 4->5 (LauncherInstallRecordStore in
  lockstep): a pak baked by an older tool is missing every untextured
  face. No bake was run as part of this commit.

Also fixed: WorldBuilder's own upstream ObjectMeshManager.cs has the
identical NoPos bug (ObjectMeshManager.cs:959,984) — our port had
faithfully carried it over, and our own conformance test
(Build_NoPosFlag_OnlyEmitsNegSide) asserted the bug as correct WB
conformance. Renamed/reworded to Build_NoPosFlag_EmitsBothPosAndNegSide
with a citation for why retail decomp overrides WB here.

Issue119UpNullGfxObjDumpTests re-run against the installed DAT:
#119's own two objects (0x010002B4 9/9 polys, 0x010008A8 1/1 poly) now
gate DRAWS on every polygon instead of extracting to nothing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 11:20:24 +02:00

141 lines
6 KiB
C#

using System.Numerics;
using AcDream.Core.Terrain;
using DatReaderWriter;
using DatReaderWriter.DBObjs;
using AcDream.Core.Content;
using DatReaderWriter.Types;
namespace AcDream.Core.Meshing;
/// <summary>
/// Builds renderable sub-meshes from an EnvCell's room geometry (walls,
/// floors, ceilings). The geometry lives in the linked Environment dat:
/// EnvCell.EnvironmentId → Environment → Cells[CellStructure] → CellStruct.
/// This mirrors GfxObjMesh.Build but reads surfaces from EnvCell.Surfaces
/// (not from the CellStruct itself) and uses the same fan-triangulation
/// and per-surface deduplication pattern.
/// </summary>
public static class CellMesh
{
/// <summary>
/// Walk a CellStruct's polygons and produce one <see cref="GfxObjSubMesh"/>
/// per referenced Surface. Surfaces are resolved from <paramref name="envCell"/>.Surfaces
/// (OR'd with 0x08000000 to form the full dat id). Polygons are triangulated as fans.
/// </summary>
/// <param name="envCell">The EnvCell that owns the surface list.</param>
/// <param name="cellStruct">The CellStruct containing the polygon + vertex geometry.</param>
/// <param name="dats">
/// Optional dat collection used to read Surface.Type flags and set
/// <see cref="GfxObjSubMesh.Translucency"/>. When null (e.g. offline tests)
/// all sub-meshes default to <see cref="TranslucencyKind.Opaque"/>.
/// </param>
public static IReadOnlyList<GfxObjSubMesh> Build(EnvCell envCell, CellStruct cellStruct, IDatObjectSource? dats = null)
{
// Group output vertices and indices per surface dat id.
var perSurface = new Dictionary<uint, (List<Vertex> Vertices, List<uint> Indices, Dictionary<(int pos, int uv), uint> Dedupe)>();
foreach (var kvp in cellStruct.Polygons)
{
var poly = kvp.Value;
if (poly.VertexIds.Count < 3)
continue; // degenerate polygon
// Retail's RenderDeviceD3D::DrawEnvCell (@0x0059f170) calls
// D3DPolyRender::DrawMesh with arg4=1, which skips every
// UNTEXTURED subset inside an EnvCell interior — unlike ordinary
// objects, which draw them (see RetailUntexturedSurfacePolicy /
// RetailUntexturedSubsetPolicy, #426). We approximate
// "untextured" here with the polygon's own NoPos stippling flag
// rather than resolving the Surface's own Type
// (Base1Image/Base1ClipMap) before this per-polygon decision —
// see docs/architecture/retail-divergence-register.md AP-234. Do
// NOT remove this gate the way #426 removed the matching gate in
// GfxObjMesh.Build/MeshExtractor.PrepareGfxObjMeshData — retail
// genuinely skips untextured cell geometry, unlike ordinary
// objects.
if (poly.Stippling.HasFlag(DatReaderWriter.Enums.StipplingType.NoPos))
continue;
int surfaceIdx = poly.PosSurface;
if (surfaceIdx < 0 || surfaceIdx >= envCell.Surfaces.Count)
continue; // out-of-range surface index
// Surfaces on EnvCell are unqualified ids; OR with 0x08000000 for the full dat id.
uint surfaceId = (uint)envCell.Surfaces[surfaceIdx] | 0x08000000u;
if (!perSurface.TryGetValue(surfaceId, out var bucket))
{
bucket = (new List<Vertex>(), new List<uint>(), new Dictionary<(int, int), uint>());
perSurface[surfaceId] = bucket;
}
// Collect output vertex indices for this polygon.
var polyOut = new List<uint>(poly.VertexIds.Count);
bool skipPoly = false;
for (int i = 0; i < poly.VertexIds.Count; i++)
{
int posIdx = poly.VertexIds[i];
int uvIdx = i < poly.PosUVIndices.Count ? poly.PosUVIndices[i] : 0;
if (!cellStruct.VertexArray.Vertices.TryGetValue((ushort)posIdx, out var sw))
{
skipPoly = true;
break;
}
var texcoord = uvIdx >= 0 && uvIdx < sw.UVs.Count
? new Vector2(sw.UVs[uvIdx].U, sw.UVs[uvIdx].V)
: Vector2.Zero;
// Use normal from vertex data; fall back to up-vector if missing.
var normal = sw.Normal != Vector3.Zero ? sw.Normal : Vector3.UnitZ;
var key = (posIdx, uvIdx);
if (!bucket.Dedupe.TryGetValue(key, out var outIdx))
{
outIdx = (uint)bucket.Vertices.Count;
bucket.Vertices.Add(new Vertex(sw.Origin, normal, texcoord, TerrainLayer: 0));
bucket.Dedupe[key] = outIdx;
}
polyOut.Add(outIdx);
}
if (skipPoly || polyOut.Count < 3)
continue;
// Fan triangulation: (v0, v1, v2), (v0, v2, v3), ...
for (int i = 1; i < polyOut.Count - 1; i++)
{
bucket.Indices.Add(polyOut[0]);
bucket.Indices.Add(polyOut[i]);
bucket.Indices.Add(polyOut[i + 1]);
}
}
// Emit one sub-mesh per surface.
var result = new List<GfxObjSubMesh>(perSurface.Count);
foreach (var kvp in perSurface)
{
// Resolve Surface.Type flags when a DatCollection is available so the
// renderer can split the draw into opaque and translucent passes.
var translucency = TranslucencyKind.Opaque;
if (dats is not null)
{
var surface = dats.Get<Surface>(kvp.Key);
if (surface is not null)
translucency = TranslucencyKindExtensions.FromSurfaceType(surface.Type);
}
result.Add(new GfxObjSubMesh(
SurfaceId: kvp.Key,
Vertices: kvp.Value.Vertices.ToArray(),
Indices: kvp.Value.Indices.ToArray())
{
Translucency = translucency,
});
}
return result;
}
}