-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGhostMesh.cs
More file actions
234 lines (204 loc) · 7.82 KB
/
Copy pathGhostMesh.cs
File metadata and controls
234 lines (204 loc) · 7.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
using System;
using System.IO;
using Vintagestory.API.Client;
using Vintagestory.API.Common;
using Vintagestory.API.Datastructures;
using Vintagestory.API.MathTools;
using Vintagestory.API.Util;
namespace Fieldwright;
/// <summary>
/// Builds a translucent ghost mesh for a schematic, split into one MultiTextureMeshRef
/// per Y layer so the renderer can hide layers from the top down (PgUp / PgDn) without
/// rebuilding the upload. Layer N contains every block whose dy == N in the schematic.
/// </summary>
public class GhostMesh : IDisposable
{
private const string Component = "ghost-mesh";
// BlockSchematic position bit-packing, see BlockSchematic.PosBitMask + Pack().
private const uint PosBitMask = 0x3ff;
private readonly ICoreClientAPI capi;
private MultiTextureMeshRef?[] layerMeshes;
public Vec3i Size { get; }
public Vec3i AnchorOffset { get; }
public int BlockCount { get; private set; }
public int SkippedCount { get; private set; }
public int LayerCount => layerMeshes?.Length ?? 0;
public MultiTextureMeshRef? GetLayerMesh(int layer) =>
(layer >= 0 && layer < layerMeshes.Length) ? layerMeshes[layer] : null;
public bool HasMesh
{
get
{
if (layerMeshes == null) return false;
foreach (var m in layerMeshes)
if (m != null && m.Initialized) return true;
return false;
}
}
public GhostMesh(ICoreClientAPI capi, BlockSchematic schematic, Vec3i anchorOffset, float alpha = 0.3f)
{
this.capi = capi;
this.Size = new Vec3i(schematic.SizeX, schematic.SizeY, schematic.SizeZ);
this.AnchorOffset = anchorOffset;
this.layerMeshes = new MultiTextureMeshRef?[Math.Max(1, schematic.SizeY)];
BuildMesh(schematic, alpha);
}
private void BuildMesh(BlockSchematic schematic, float alpha)
{
// One MeshData per Y layer; each accumulates that layer's blocks before upload.
var perLayer = new MeshData[schematic.SizeY];
for (int y = 0; y < schematic.SizeY; y++)
{
perLayer[y] = new MeshData(256, 512);
perLayer[y].WithColorMaps();
perLayer[y].WithXyzFaces();
perLayer[y].WithRenderpasses();
}
byte alphaByte = (byte)Math.Clamp((int)(alpha * 255), 0, 255);
int built = 0;
int skipped = 0;
for (int i = 0; i < schematic.Indices.Count; i++)
{
uint encoded = schematic.Indices[i];
int dx = (int)(encoded & PosBitMask);
int dy = (int)((encoded >> 20) & PosBitMask);
int dz = (int)((encoded >> 10) & PosBitMask);
if (dy < 0 || dy >= schematic.SizeY)
{
skipped++;
continue;
}
int storedId = schematic.BlockIds[i];
if (!schematic.BlockCodes.TryGetValue(storedId, out var assetLoc))
{
skipped++;
continue;
}
var block = capi.World.GetBlock(assetLoc);
if (block == null || block.Id == 0)
{
skipped++;
continue;
}
var blockMesh = BuildCellMesh(block, schematic, encoded);
if (blockMesh == null || blockMesh.VerticesCount == 0)
{
skipped++;
continue;
}
ApplyAlpha(blockMesh, alphaByte);
// Keep dy in the per-block offset so the model matrix in GhostRenderer
// continues to position each block at its absolute schematic-local Y.
// Each layer's mesh has vertices only within Y in [dy, dy+1].
perLayer[dy].AddMeshData(blockMesh, dx, dy, dz);
built++;
}
BlockCount = built;
SkippedCount = skipped;
int uploadedLayers = 0;
for (int y = 0; y < schematic.SizeY; y++)
{
if (perLayer[y].VerticesCount == 0) continue;
layerMeshes[y] = capi.Render.UploadMultiTextureMesh(perLayer[y]);
uploadedLayers++;
}
if (uploadedLayers == 0)
{
FieldwrightLogger.Warn(capi, Component, "ghost mesh has zero vertices, nothing to render");
return;
}
FieldwrightLogger.Info(capi, Component,
$"built ghost mesh: {built} blocks, {skipped} skipped across {uploadedLayers} non-empty Y layers, " +
$"size {Size.X}×{Size.Y}×{Size.Z}");
}
/// <summary>
/// Resolve the mesh for one cell. The pipeline is:
/// 1. If a BEMeshSource handles this block family, let it provide the mesh
/// (chest meshAngle, crate from temp BE, chisel substrate, ...).
/// 2. Else fall back to the engine's bare TesselateBlock, which is correct
/// for ordinary blocks (planks, doors, slanted roofing, stairs).
/// Source.Provide returning null is treated as "I don't handle this", so the
/// caller falls through to the default tessellation rather than skipping the
/// cell, e.g. when chisel BE data is missing on a fallback-saved blueprint.
/// </summary>
private MeshData? BuildCellMesh(Block block, BlockSchematic schematic, uint encoded)
{
var path = block.Code?.Path;
var source = path != null ? BEMeshSourceRegistry.Lookup(path) : null;
ITreeAttribute? beTree = null;
if (schematic.BlockEntities.TryGetValue(encoded, out var ascii85))
{
beTree = DecodeBETree(ascii85);
}
if (source != null)
{
try
{
var fromSource = source.Provide(capi, block, beTree);
if (fromSource != null && fromSource.VerticesCount > 0) return fromSource;
}
catch (Exception ex)
{
FieldwrightLogger.Warn(capi, Component,
$"BE mesh source '{source.Prefix}' threw on {block.Code}: {ex.GetType().Name}: {ex.Message}");
// Fall through to default tessellation.
}
}
try
{
capi.Tesselator.TesselateBlock(block, out var mesh);
return mesh;
}
catch (Exception ex)
{
FieldwrightLogger.Warn(capi, Component,
$"failed to tessellate {block.Code}: {ex.Message}");
return null;
}
}
/// <summary>
/// Decode an Ascii85-encoded TreeAttribute payload from BlockSchematic.BlockEntities.
/// Returns null on any decoding failure so callers can skip the cell silently rather
/// than killing the whole ghost build.
/// </summary>
private ITreeAttribute? DecodeBETree(string ascii85)
{
try
{
byte[] bytes = Ascii85.Decode(ascii85);
var tree = new TreeAttribute();
using var ms = new MemoryStream(bytes);
using var br = new BinaryReader(ms);
tree.FromBytes(br);
return tree;
}
catch (Exception ex)
{
FieldwrightLogger.Warn(capi, Component, $"failed to decode BE tree: {ex.Message}");
return null;
}
}
private static void ApplyAlpha(MeshData mesh, byte alphaByte)
{
if (mesh.Rgba == null) return;
// Rgba layout: 4 bytes per vertex (R, G, B, A). Multiply existing alpha by
// (alphaByte / 255) so already-translucent blocks (glass, etc.) stay
// proportionally see-through.
for (int i = 3; i < mesh.Rgba.Length; i += 4)
{
int existing = mesh.Rgba[i];
mesh.Rgba[i] = (byte)((existing * alphaByte) / 255);
}
}
public void Dispose()
{
if (layerMeshes != null)
{
for (int i = 0; i < layerMeshes.Length; i++)
{
layerMeshes[i]?.Dispose();
layerMeshes[i] = null;
}
}
}
}