-
Notifications
You must be signed in to change notification settings - Fork 868
Expand file tree
/
Copy pathProbeGIBaking.VirtualOffset.cs
More file actions
492 lines (404 loc) · 20.2 KB
/
ProbeGIBaking.VirtualOffset.cs
File metadata and controls
492 lines (404 loc) · 20.2 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEditor;
using UnityEngine.Rendering.UnifiedRayTracing;
namespace UnityEngine.Rendering
{
partial class AdaptiveProbeVolumes
{
/// <summary>
/// Virtual offset baker
/// </summary>
public abstract class VirtualOffsetBaker : IDisposable
{
/// <summary>The current baking step.</summary>
public abstract ulong currentStep { get; }
/// <summary>The total amount of step.</summary>
public abstract ulong stepCount { get; }
/// <summary>Array storing the resulting virtual offsets to be applied to probe positions.</summary>
public abstract NativeArray<Vector3> offsets { get; }
/// <summary>
/// This is called before the start of baking to allow allocating necessary resources.
/// </summary>
/// <param name="bakingSet">The baking set that is currently baked.</param>
/// <param name="probePositions">The probe positions.</param>
public abstract void Initialize(ProbeVolumeBakingSet bakingSet, NativeArray<Vector3> probePositions);
/// <summary>
/// Run a step of virtual offset baking. Baking is considered done when currentStep property equals stepCount.
/// </summary>
/// <returns>Return false if bake failed and should be stopped.</returns>
public abstract bool Step();
/// <summary>
/// Performs necessary tasks to free allocated resources.
/// </summary>
public abstract void Dispose();
}
class DefaultVirtualOffset : VirtualOffsetBaker
{
static int k_MaxProbeCountPerBatch = 65535;
static readonly int _Probes = Shader.PropertyToID("_Probes");
static readonly int _Offsets = Shader.PropertyToID("_Offsets");
// Duplicated in HLSL
struct ProbeData
{
public Vector3 position;
public float originBias;
public float tMax;
public float geometryBias;
public int probeIndex;
public float validityThreshold;
};
int batchPosIdx;
NativeArray<Vector3> positions;
NativeArray<Vector3> results;
Dictionary<int, TouchupsPerCell> cellToVolumes;
ProbeData[] probeData;
Vector3[] batchResult;
float scaleForSearchDist;
float rayOriginBias;
float geometryBias;
float validityThreshold;
// Output buffer
public override NativeArray<Vector3> offsets => results;
private AccelStructAdapter m_AccelerationStructure;
private GraphicsBuffer probeBuffer;
private GraphicsBuffer offsetBuffer;
private GraphicsBuffer scratchBuffer;
public override ulong currentStep => (ulong)batchPosIdx;
public override ulong stepCount => batchResult == null ? 0 : (ulong)positions.Length;
public override void Initialize(ProbeVolumeBakingSet bakingSet, NativeArray<Vector3> probePositions)
{
var voSettings = bakingSet.settings.virtualOffsetSettings;
if (!voSettings.useVirtualOffset)
return;
batchPosIdx = 0;
scaleForSearchDist = voSettings.searchMultiplier;
rayOriginBias = voSettings.rayOriginBias;
geometryBias = voSettings.outOfGeoOffset;
validityThreshold = voSettings.validityThreshold;
results = new NativeArray<Vector3>(probePositions.Length, Allocator.Persistent);
cellToVolumes = GetTouchupsPerCell(out bool hasAppliers);
if (scaleForSearchDist == 0.0f)
{
if (hasAppliers)
DoApplyVirtualOffsetsFromAdjustmentVolumes(probePositions, results, cellToVolumes);
return;
}
positions = probePositions;
probeData = new ProbeData[k_MaxProbeCountPerBatch];
batchResult = new Vector3[k_MaxProbeCountPerBatch];
var computeBufferTarget = GraphicsBuffer.Target.CopyDestination | GraphicsBuffer.Target.CopySource
| GraphicsBuffer.Target.Structured;
// Create acceletation structure
m_AccelerationStructure = BuildAccelerationStructure(voSettings.collisionMask);
var virtualOffsetShader = s_TracingContext.shaderVO;
probeBuffer = new GraphicsBuffer(computeBufferTarget, k_MaxProbeCountPerBatch, Marshal.SizeOf<ProbeData>());
offsetBuffer = new GraphicsBuffer(computeBufferTarget, k_MaxProbeCountPerBatch, Marshal.SizeOf<Vector3>());
scratchBuffer = RayTracingHelper.CreateScratchBufferForBuildAndDispatch(m_AccelerationStructure.GetAccelerationStructure(), virtualOffsetShader,
(uint)k_MaxProbeCountPerBatch, 1, 1);
var cmd = new CommandBuffer();
m_AccelerationStructure.Build(cmd, ref scratchBuffer);
Graphics.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
static AccelStructAdapter BuildAccelerationStructure(int mask)
{
var accelStruct = s_TracingContext.CreateAccelerationStructure();
var contributors = m_BakingBatch.contributors;
foreach (var renderer in contributors.renderers)
{
int layerMask = 1 << renderer.component.gameObject.layer;
if ((layerMask & mask) == 0)
continue;
if (!s_TracingContext.TryGetMeshForAccelerationStructure(renderer.component, out var mesh))
continue;
if (renderer.component is SkinnedMeshRenderer)
continue;
int subMeshCount = mesh.subMeshCount;
var maskAndMatDummy = new uint[subMeshCount];
System.Array.Fill(maskAndMatDummy, 0xFFFFFFFF);
Span<bool> perSubMeshOpaqueness = stackalloc bool[subMeshCount];
perSubMeshOpaqueness.Fill(true);
accelStruct.AddInstance(EntityId.ToULong(renderer.component.GetEntityId()), renderer.component, maskAndMatDummy, maskAndMatDummy, perSubMeshOpaqueness, 1);
}
foreach (var terrain in contributors.terrains)
{
int layerMask = 1 << terrain.component.gameObject.layer;
if ((layerMask & mask) == 0)
continue;
accelStruct.AddInstance(EntityId.ToULong(terrain.component.GetEntityId()), terrain.component, new uint[1] { 0xFFFFFFFF }, new uint[1] { 0xFFFFFFFF }, new bool[1] { true }, 1);
}
return accelStruct;
}
public override bool Step()
{
if (currentStep >= stepCount)
return true;
float minBrickSize = m_ProfileInfo.minBrickSize;
// Prepare batch
int probeCountInBatch = 0;
do
{
int subdivLevel = m_BakingBatch.GetSubdivLevelAt(positions[batchPosIdx]);
var brickSize = ProbeReferenceVolume.CellSize(subdivLevel);
var searchDistance = (brickSize * minBrickSize) / ProbeBrickPool.kBrickCellCount;
var distanceSearch = scaleForSearchDist * searchDistance;
int cellIndex = PosToIndex(m_ProfileInfo.PositionToCell(positions[batchPosIdx]));
if (cellToVolumes.TryGetValue(cellIndex, out var volumes))
{
bool adjusted = false;
foreach (var (touchup, obb, center, offset) in volumes.appliers)
{
if (touchup.ContainsPoint(obb, center, positions[batchPosIdx]))
{
results[batchPosIdx] = offset;
adjusted = true;
break;
}
}
if (adjusted)
continue;
foreach (var (touchup, obb, center) in volumes.overriders)
{
if (touchup.ContainsPoint(obb, center, positions[batchPosIdx]))
{
rayOriginBias = touchup.rayOriginBias;
geometryBias = touchup.geometryBias;
validityThreshold = 1.0f - touchup.virtualOffsetThreshold;
break;
}
}
}
probeData[probeCountInBatch++] = new ProbeData
{
position = positions[batchPosIdx],
originBias = rayOriginBias,
tMax = distanceSearch,
geometryBias = geometryBias,
validityThreshold = validityThreshold,
probeIndex = batchPosIdx,
};
}
while (++batchPosIdx < positions.Length && probeCountInBatch < k_MaxProbeCountPerBatch);
if (probeCountInBatch == 0)
return true;
// Execute job
var cmd = new CommandBuffer();
var virtualOffsetShader = s_TracingContext.shaderVO;
m_AccelerationStructure.Bind(cmd, "_AccelStruct", virtualOffsetShader);
virtualOffsetShader.SetBufferParam(cmd, _Probes, probeBuffer);
virtualOffsetShader.SetBufferParam(cmd, _Offsets, offsetBuffer);
cmd.SetBufferData(probeBuffer, probeData);
virtualOffsetShader.Dispatch(cmd, scratchBuffer, (uint)probeCountInBatch, 1, 1);
Graphics.ExecuteCommandBuffer(cmd);
cmd.Clear();
offsetBuffer.GetData(batchResult);
for (int i = 0; i < probeCountInBatch; i++)
results[probeData[i].probeIndex] = batchResult[i];
cmd.Dispose();
return true;
}
public override void Dispose()
{
if (results.IsCreated)
results.Dispose();
if (batchResult == null)
return;
m_AccelerationStructure.Dispose();
probeBuffer.Dispose();
offsetBuffer.Dispose();
scratchBuffer?.Dispose();
}
}
static internal void RecomputeVOForDebugOnly()
{
var prv = ProbeReferenceVolume.instance;
if (prv.perSceneDataList.Count == 0)
return;
SetBakingContext(prv.perSceneDataList);
if (!m_BakingSet.HasBeenBaked())
return;
globalBounds = prv.globalBounds;
CellCountInDirections(out minCellPosition, out maxCellPosition, prv.MaxBrickSize(), prv.ProbeOffset());
cellCount = maxCellPosition + Vector3Int.one - minCellPosition;
m_BakingBatch = new BakingBatch(cellCount, ProbeReferenceVolume.instance);
m_ProfileInfo = new ProbeVolumeProfileInfo();
ModifyProfileFromLoadedData(m_BakingSet);
var positionList = new NativeList<Vector3>(Allocator.Persistent);
Dictionary<int, int> positionToIndex = new();
foreach (var cell in ProbeReferenceVolume.instance.cells.Values)
{
var bakingCell = ConvertCellToBakingCell(cell.desc, cell.data);
int numProbes = bakingCell.probePositions.Length;
int uniqueIndex = positionToIndex.Count;
var indices = new int[numProbes];
// DeduplicateProbePositions
for (int i = 0; i < numProbes; i++)
{
var pos = bakingCell.probePositions[i];
int brickSubdiv = bakingCell.bricks[i / 64].subdivisionLevel;
int probeHash = m_BakingBatch.GetProbePositionHash(pos);
if (positionToIndex.TryGetValue(probeHash, out var index))
{
indices[i] = index;
int oldBrickLevel = m_BakingBatch.uniqueBrickSubdiv[probeHash];
if (brickSubdiv < oldBrickLevel)
m_BakingBatch.uniqueBrickSubdiv[probeHash] = brickSubdiv;
}
else
{
positionToIndex[probeHash] = uniqueIndex;
indices[i] = uniqueIndex;
m_BakingBatch.uniqueBrickSubdiv[probeHash] = brickSubdiv;
positionList.Add(pos);
uniqueIndex++;
}
}
bakingCell.probeIndices = indices;
m_BakingBatch.cells.Add(bakingCell);
// We need to force rebuild debug stuff.
cell.debugProbes = null;
}
VirtualOffsetBaker job = virtualOffsetOverride ?? new DefaultVirtualOffset();
job.Initialize(m_BakingSet, positionList.AsArray());
while (job.currentStep < job.stepCount)
job.Step();
foreach (var cell in m_BakingBatch.cells)
{
int numProbes = cell.probePositions.Length;
for (int i = 0; i < numProbes; ++i)
{
int j = cell.probeIndices[i];
cell.offsetVectors[i] = job.offsets[j];
}
}
job.Dispose();
// Unload it all as we are gonna load back with newly written cells.
foreach (var sceneData in prv.perSceneDataList)
prv.AddPendingSceneRemoval(sceneData.sceneGUID);
// Make sure unloading happens.
prv.PerformPendingOperations();
// Validate baking cells size before writing
var bakingCellsArray = m_BakingBatch.cells.ToArray();
var chunkSizeInProbes = ProbeBrickPool.GetChunkSizeInProbeCount();
var hasVirtualOffsets = m_BakingSet.settings.virtualOffsetSettings.useVirtualOffset;
var hasRenderingLayers = m_BakingSet.useRenderingLayers;
if (ValidateBakingCellsSize(bakingCellsArray, chunkSizeInProbes, hasVirtualOffsets, hasRenderingLayers))
{
// Write back the assets.
WriteBakingCells(bakingCellsArray);
}
m_BakingBatch?.Dispose();
m_BakingBatch = null;
foreach (var data in prv.perSceneDataList)
data.ResolveCellData();
// We can now finally reload.
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
foreach (var sceneData in prv.perSceneDataList)
{
prv.AddPendingSceneLoading(sceneData.sceneGUID, sceneData.serializedBakingSet);
}
prv.PerformPendingOperations();
}
}
partial class AdaptiveProbeVolumes
{
struct TouchupsPerCell
{
public List<(ProbeAdjustmentVolume touchup, ProbeReferenceVolume.Volume obb, Vector3 center, Vector3 offset)> appliers;
public List<(ProbeAdjustmentVolume touchup, ProbeReferenceVolume.Volume obb, Vector3 center)> overriders;
}
static Dictionary<int, TouchupsPerCell> GetTouchupsPerCell(out bool hasAppliers)
{
hasAppliers = false;
var adjustmentVolumes = s_AdjustmentVolumes != null ? s_AdjustmentVolumes : GetAdjustementVolumes();
Dictionary<int, TouchupsPerCell> cellToVolumes = new();
foreach (var adjustment in adjustmentVolumes)
{
var volume = adjustment.volume;
var mode = volume.mode;
if (mode != ProbeAdjustmentVolume.Mode.ApplyVirtualOffset && mode != ProbeAdjustmentVolume.Mode.OverrideVirtualOffsetSettings)
continue;
hasAppliers |= mode == ProbeAdjustmentVolume.Mode.ApplyVirtualOffset;
Vector3Int min = Vector3Int.Max(m_ProfileInfo.PositionToCell(adjustment.aabb.min), minCellPosition);
Vector3Int max = Vector3Int.Min(m_ProfileInfo.PositionToCell(adjustment.aabb.max), maxCellPosition);
for (int x = min.x; x <= max.x; x++)
{
for (int y = min.y; y <= max.y; y++)
{
for (int z = min.z; z <= max.z; z++)
{
var cell = PosToIndex(new Vector3Int(x, y, z));
if (!cellToVolumes.TryGetValue(cell, out var volumes))
cellToVolumes[cell] = volumes = new TouchupsPerCell() { appliers = new(), overriders = new() };
if (mode == ProbeAdjustmentVolume.Mode.ApplyVirtualOffset)
volumes.appliers.Add((volume, adjustment.obb, volume.transform.position, volume.GetVirtualOffset()));
else
volumes.overriders.Add((volume, adjustment.obb, volume.transform.position));
}
}
}
}
return cellToVolumes;
}
static void DoApplyVirtualOffsetsFromAdjustmentVolumes(NativeArray<Vector3> positions, NativeArray<Vector3> offsets, Dictionary<int, TouchupsPerCell> cellToVolumes)
{
for (int i = 0; i < positions.Length; i++)
{
var cellPos = m_ProfileInfo.PositionToCell(positions[i]);
cellPos.Clamp(minCellPosition, maxCellPosition);
int cellIndex = PosToIndex(cellPos);
if (cellToVolumes.TryGetValue(cellIndex, out var volumes))
{
foreach (var (touchup, obb, center, offset) in volumes.appliers)
{
if (touchup.ContainsPoint(obb, center, positions[i]))
{
offsets[i] = offset;
break;
}
}
}
}
}
enum InstanceFlags
{
DIRECT_RAY_VIS_MASK = 1,
INDIRECT_RAY_VIS_MASK = 2,
SHADOW_RAY_VIS_MASK = 4,
}
private static uint GetInstanceMask(ShadowCastingMode shadowMode)
{
uint instanceMask = 0u;
if (shadowMode != ShadowCastingMode.Off)
instanceMask |= (uint)InstanceFlags.SHADOW_RAY_VIS_MASK;
if (shadowMode != ShadowCastingMode.ShadowsOnly)
{
instanceMask |= (uint)InstanceFlags.DIRECT_RAY_VIS_MASK;
instanceMask |= (uint)InstanceFlags.INDIRECT_RAY_VIS_MASK;
}
return instanceMask;
}
static uint[] GetMaterialIndices(Renderer renderer)
{
int submeshCount = 1;
var meshFilter = renderer.GetComponent<MeshFilter>();
if (meshFilter)
submeshCount = renderer.GetComponent<MeshFilter>().sharedMesh.subMeshCount;
uint[] matIndices = new uint[submeshCount];
for (int i = 0; i < matIndices.Length; ++i)
{
Debug.Assert(UnsafeUtility.SizeOf<EntityId>() == sizeof(int), "If this assert is firing, the size of EntityId has changed. This downcase to uint is unsafe.");
if (i < renderer.sharedMaterials.Length && renderer.sharedMaterials[i] != null)
matIndices[i] = (uint)EntityId.ToULong(renderer.sharedMaterials[i].GetEntityId());
else
matIndices[i] = 0;
}
return matIndices;
}
}
}