summaryrefslogtreecommitdiff
path: root/Runtime/Camera/SceneCulling.cpp
blob: ad5e4ed9cec39d2f069ba9c825905e5505634810 (plain)
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
#include "UnityPrefix.h"
#include "SceneCulling.h"
#include "CullingParameters.h"
#include "Runtime/Geometry/Intersection.h"
#include "UmbraBackwardsCompatibility.h"
#include "SceneNode.h"
#include "Runtime/Geometry/AABB.h"


using Umbra::OcclusionBuffer;

static bool IsLayerDistanceCulled (UInt32 layer, const AABB& aabb, const SceneCullingParameters& params);
static void ExtractUmbraCameraTransformFromCullingParameters (const CullingParameters& params, Umbra::CameraTransform& output);
static void CullSceneWithLegacyUmbraDeprecated (SceneCullingParameters& cullingParams, CullingOutput& output, Umbra::Query* q, const Umbra_3_0::Tome* t);
	
// Reduce the index list using Scene::IsNodeVisible.
// Takes the index list as input and output, after the function the indices that are not visible will have been removed.
static void ProcessIndexListIsNodeVisible (IndexList& list, const SceneNode* nodes, const AABB* bounds, const SceneCullingParameters& params)
{
	int size = list.size;
	// Check layers and cull distances
	int visibleCountNodes = 0;
	for (int i = 0; i < size; ++i)
	{
		int index = list.indices[i];
		const SceneNode& node = nodes[index];
		const AABB& aabb = bounds[index];
		if (IsNodeVisible(node, aabb, params))
			list.indices[visibleCountNodes++] = index;
	}
	
	list.size = visibleCountNodes;
}


static void CullDynamicObjectsWithoutUmbra (IndexList& visibleObjects, const SceneCullingParameters& cullingParams, const AABB* aabbs, size_t count)
{
	int visibleIndex = 0;
	for (int i=0;i<count;i++)
	{
		const AABB& bounds = aabbs[i];
		if (IntersectAABBPlaneBounds(bounds, cullingParams.cullingPlanes, cullingParams.cullingPlaneCount))
			visibleObjects[visibleIndex++] = i;
	}
	
	visibleObjects.size = visibleIndex;
}

static void CullDynamicObjectsUmbra (IndexList& visibleObjects, const AABB* aabbs, size_t count, OcclusionBuffer* occlusionBuffer)
{
    // TODO dynamic objects with legacy Tomes properly
	int visibleIndex = 0;
	for (int i=0;i<count;i++)
	{
		const AABB& bounds = aabbs[i];
		
		Vector3f mn = bounds.GetMin();
		Vector3f mx = bounds.GetMax();
		Umbra::OcclusionBuffer::VisibilityTestResult result = occlusionBuffer->testAABBVisibility((Umbra::Vector3&)mn, (Umbra::Vector3&)mx);
		
		if (result != OcclusionBuffer::OCCLUDED)
			visibleObjects[visibleIndex++] = i;
	}
	
	visibleObjects.size = visibleIndex;
}

void CullSceneWithoutUmbra (const SceneCullingParameters& cullingParams, CullingOutput& output)
{
	for (int i=0;i<kVisibleListCount;i++)
	{
		CullDynamicObjectsWithoutUmbra (output.visible[i], cullingParams, cullingParams.renderers[i].bounds, cullingParams.renderers[i].rendererCount);
		ProcessIndexListIsNodeVisible  (output.visible[i], cullingParams.renderers[i].nodes, cullingParams.renderers[i].bounds, cullingParams);
	}
}

void CullSceneWithUmbra (SceneCullingParameters& cullingParams, CullingOutput& output)
{
#if SUPPORT_BACKWARDS_COMPATIBLE_UMBRA
	if (cullingParams.umbraTome.IsLegacyTome())
    {
        CullSceneWithLegacyUmbraDeprecated(cullingParams, output, cullingParams.umbraQuery, cullingParams.umbraTome.legacyTome);
		return;
    }
#endif
	
	DebugAssert(cullingParams.useOcclusionCulling);
	
	const Umbra::Tome* tome = cullingParams.umbraTome.tome;
	Umbra::QueryExt* query = cullingParams.umbraQuery;
	
	Assert(tome != NULL);
	
	Umbra::CameraTransform camera;
	ExtractUmbraCameraTransformFromCullingParameters(cullingParams, camera);
	
	Umbra::Query::ErrorCode e;
	
	Umbra::UINT32 umbraFlags = cullingParams.umbraDebugFlags;
	query->setDebugRenderer(cullingParams.umbraDebugRenderer);

    // Legacy Umbra queries for PVS Tomes
	Assert(tome->getStatistic(Umbra::Tome::STAT_PORTAL_DATA_SIZE) != 0);
	e = query->queryPortalVisibility(umbraFlags, *output.umbraVisibility, camera);

	//If camera is out of generated view volumes (case 554981), fall back to view frustum culling
	if (e == Umbra::Query::ERROR_OUTSIDE_SCENE)
	{
		cullingParams.useOcclusionCulling = false;
		cullingParams.useShadowCasterCulling = false;
		CullSceneWithoutUmbra( cullingParams, output );
		return;
	}

	// Process static objects with Unity specific culling (cullingMask / LOD etc)
	IndexList& staticObjects = output.visible[kStaticRenderers];
	staticObjects.size = output.umbraVisibility->getOutputObjects()->getSize();
	
	ProcessIndexListIsNodeVisible(output.visible[kStaticRenderers], cullingParams.renderers[kStaticRenderers].nodes, cullingParams.renderers[kStaticRenderers].bounds, cullingParams);
	output.umbraVisibility->getOutputObjects()->setSize(staticObjects.size);
	
	// Process dynamic objects
	for (int i=kDynamicRenderer;i<kVisibleListCount;i++)
	{
		CullDynamicObjectsUmbra      (output.visible[i], cullingParams.renderers[i].bounds, cullingParams.renderers[i].rendererCount, output.umbraVisibility->getOutputBuffer());
		ProcessIndexListIsNodeVisible(output.visible[i], cullingParams.renderers[i].nodes, cullingParams.renderers[i].bounds, cullingParams);
	}
}

static void SplitCombinedDynamicList (Umbra::IndexList& indices, CullingOutput& sceneCullingOutput)
{
	int startIndices[kVisibleListCount];
	startIndices[kStaticRenderers] = -1;
	int offset = 0;
	for (int t=kDynamicRenderer;t<kVisibleListCount;t++)
	{
		startIndices[t] = offset;
		offset += sceneCullingOutput.visible[t].reservedSize;
	}
	
	int *indexPtr = indices.getPtr();
	for (int i=0;i<indices.getSize();i++)
	{
		int index = indexPtr[i];

		for (int t=kVisibleListCount-1; t>= 0 ;t--)
		{
			DebugAssert(t != kStaticRenderers);
			if (index >= startIndices[t])
			{
				IndexList& indices = sceneCullingOutput.visible[t];
				indices[indices.size++] = index - startIndices[t];
				break;
			}
		}
	}
}

// Unity has multiple dynamic bounding volume arrays.
// Umbra's shadow caster culling needs a single list of all dynamic renderers
static void GenerateCombinedDynamicList (const CullingOutput& sceneCullingOutput, const RendererCullData* renderers, dynamic_array<int>& indexList, dynamic_array<Vector3f>& minMaxBounds)
{
	size_t visibleSize = 0;
	size_t totalSize = 0;
	for (int t=kDynamicRenderer;t<kVisibleListCount;t++)
	{
		visibleSize += sceneCullingOutput.visible[t].size;
		totalSize += sceneCullingOutput.visible[t].reservedSize;
	}
	
	indexList.resize_uninitialized(visibleSize);
	minMaxBounds.resize_uninitialized(totalSize * 2);
	
	// Make one big index list indexing into the combined bounding volume array
	int index = 0;
	int baseOffset = 0;
	for (int t=kDynamicRenderer;t<kVisibleListCount;t++)
	{
		int* visibleDynamic = sceneCullingOutput.visible[t].indices;
		for (int i=0;i<sceneCullingOutput.visible[t].size;i++)
			indexList[index++] = visibleDynamic[i] + baseOffset;
		
		baseOffset += sceneCullingOutput.visible[t].reservedSize;
	}

	// Create one big bounding volume array
	index = 0;
	for (int t=kDynamicRenderer;t<kVisibleListCount;t++)
	{
		const AABB* aabbs = renderers[t].bounds;
		
		Assert(renderers[t].rendererCount == sceneCullingOutput.visible[t].reservedSize);
		for (int i=0;i<renderers[t].rendererCount;i++)
		{
			minMaxBounds[index++] = aabbs[i].GetMin();
			minMaxBounds[index++] = aabbs[i].GetMax();
		}
	}
}

void CullShadowCastersWithUmbra (const SceneCullingParameters& cullingParams, CullingOutput& output)
{
	DebugAssert(cullingParams.useShadowCasterCulling && cullingParams.useOcclusionCulling);
	
	Assert( cullingParams.umbraTome.tome != NULL);
	Umbra::QueryExt* query = (Umbra::QueryExt*)cullingParams.umbraQuery;

	Umbra::CameraTransform camera;
	ExtractUmbraCameraTransformFromCullingParameters(cullingParams, camera);

	const Umbra::Visibility* inputSceneVisibility = cullingParams.sceneVisbilityForShadowCulling->umbraVisibility;

	dynamic_array<int> visibleSceneIndexListCombined (kMemTempAlloc);
	dynamic_array<Vector3f> dynamicBounds (kMemTempAlloc);

	////@TODO: This extra copying could maybe be removed or moved to not be per light?
	GenerateCombinedDynamicList (*cullingParams.sceneVisbilityForShadowCulling, cullingParams.renderers, visibleSceneIndexListCombined, dynamicBounds);

	size_t totalDynamicCount = dynamicBounds.size() / 2;
	size_t totalStaticCount = cullingParams.renderers[kStaticRenderers].rendererCount;
	
	int* dynamicCasterIndices;
	ALLOC_TEMP(dynamicCasterIndices, int, totalDynamicCount);
	
	// The output visible static & dynamic caster index lists
	Umbra::IndexList staticCasterList (output.visible[kStaticRenderers].indices, totalStaticCount);
	Umbra::IndexList dynamicCasterList(dynamicCasterIndices, totalDynamicCount);
	
	// The current scene visibility (input for umbra occlusion culling)
	const Umbra::IndexList sceneVisibleDynamicIndexList (visibleSceneIndexListCombined.begin(), visibleSceneIndexListCombined.size(), visibleSceneIndexListCombined.size());

    
	query->setDebugRenderer(cullingParams.umbraDebugRenderer);

    // TODO: this can be done right after the visibility query and only needs to be done once
    // per camera position
    // TODO: store shadowCuller so that it can be shared across threads
    Umbra::ShadowCullerExt* shadowCuller;
    ALLOC_TEMP(shadowCuller, Umbra::ShadowCullerExt, 1);
    new (shadowCuller) Umbra::ShadowCullerExt(
        cullingParams.umbraTome.tome,
        inputSceneVisibility,
        (Umbra::Vector3&)cullingParams.lightDir,
        (const Umbra::Vector3*)dynamicBounds.data(),
		totalDynamicCount,
		&sceneVisibleDynamicIndexList);

    // The last two parameters: jobIdx, numTotalJobs. These can be called from mulitple threads
    query->queryStaticShadowCasters (*shadowCuller, staticCasterList, 0, 1);
    query->queryDynamicShadowCasters(*shadowCuller, dynamicCasterList, (const Umbra::Vector3*)dynamicBounds.data(), totalDynamicCount);

	output.visible[kStaticRenderers].size = staticCasterList.getSize();
	SplitCombinedDynamicList (dynamicCasterList, output);
	
	for (int i=0;i<kVisibleListCount;i++)
		ProcessIndexListIsNodeVisible  (output.visible[i], cullingParams.renderers[i].nodes, cullingParams.renderers[i].bounds, cullingParams);
}


bool IsNodeVisible (const SceneNode& node, const AABB& aabb, const SceneCullingParameters& params)
{
	UInt32 layermask = 1 << node.layer;
	if ((layermask & params.cullingMask) == 0)
		return false;
	
	// Static renderers are not deleted from the renderer objects list.
	// This is because we ensure that static objects come first and the pvxIndex in umbra matches the index in m_RendererNodes array.
	// However the layerMask is set to 0 thus it should be culled at this point
	if (node.renderer == NULL)
		return false;
	
	// Check if node was deleted but not removed from list yet.
	if (node.disable)
		return false;
	
	if (node.lodIndexMask != 0)
	{
		DebugAssert(node.lodGroup < params.lodGroupCount);
		if ((params.lodMasks[node.lodGroup] & node.lodIndexMask) == 0)
			return false;
	}
	
	if (IsLayerDistanceCulled(node.layer, aabb, params))
		return false;
	
	return true;
}


static bool IsLayerDistanceCulled (UInt32 layer, const AABB& aabb, const SceneCullingParameters& params)
{
	switch (params.layerCull)
	{
		case CullingParameters::kLayerCullPlanar:
		{
			Assert(params.cullingPlaneCount == kPlaneFrustumNum);
			Plane farPlane = params.cullingPlanes[kPlaneFrustumFar];
			farPlane.distance = params.layerFarCullDistances[layer];
			return !IntersectAABBPlaneBounds (aabb, &farPlane, 1);
		}
		case CullingParameters::kLayerCullSpherical:
		{
			float cullDist = params.layerFarCullDistances[layer];
			if (cullDist == 0.0f)
				return false;
			return (SqrMagnitude(aabb.GetCenter() - params.position) > Sqr(cullDist));
		}
		default:
			return false;
	}
}
	
void ExtractUmbraCameraTransformFromCullingParameters (const CullingParameters& params, Umbra::CameraTransform& output)
{
	if  (params.cullingPlaneCount > 6)
		output.setUserClipPlanes((Umbra::Vector4*)&params.cullingPlanes[6], params.cullingPlaneCount-6);
	output.set((Umbra::Matrix4x4&)params.worldToClipMatrix, (Umbra::Vector3&)params.position);
}

#if SUPPORT_BACKWARDS_COMPATIBLE_UMBRA

static void CullDynamicObjectsUmbraDeprecated (IndexList& visibleObjects, const AABB* aabbs, size_t count, Umbra_3_0::Region* region)
{
    // TODO dynamic objects with legacy Tomes properly
	int visibleIndex = 0;
	for (int i=0;i<count;i++)
	{
		const AABB& bounds = aabbs[i];
		
		Vector3f mn = bounds.GetMin();
		Vector3f mx = bounds.GetMax();
		
        bool isVisible = region->isAABBVisible((Umbra_3_0::Vector3&)mn, (Umbra_3_0::Vector3&)mx);
		
		if (isVisible)
			visibleObjects[visibleIndex++] = i;
	}
	
	visibleObjects.size = visibleIndex;
}

static void CullDynamicObjectsWithoutUmbraInOut (IndexList& visibleObjects, const SceneCullingParameters& cullingParams, const AABB* aabbs)
{
	int visibleIndex = 0;
	for (int i=0;i<visibleObjects.size;i++)
	{
		int index = visibleObjects[i];
		const AABB& bounds = aabbs[index];
		if (IntersectAABBPlaneBounds(bounds, cullingParams.cullingPlanes, cullingParams.cullingPlaneCount))
			visibleObjects[visibleIndex++] = index;
	}
	
	visibleObjects.size = visibleIndex;
}

static void CullSceneWithLegacyUmbraDeprecated (SceneCullingParameters& cullingParams, CullingOutput& output, Umbra::Query* q, const Umbra_3_0::Tome* tome)
{
	///@TODO: Review if output.umbraVisibility makes any sense????
	
    Umbra_3_0::QueryExt*    query   = (Umbra_3_0::QueryExt*)q;
	
    query->init(tome);
	
	Umbra_3_0::Region* region;
	ALLOC_TEMP(region, Umbra_3_0::Region, 1);
	region->init();
	query->setVisibilityRegionOutput(region);
	
	
    Umbra_3_0::CameraTransform camera;
    if  (cullingParams.cullingPlaneCount > 6)
	    camera.setUserClipPlanes((Umbra_3_0::Vector4*)&cullingParams.cullingPlanes[6], cullingParams.cullingPlaneCount-6);
	
    camera.set((Umbra_3_0::Matrix4x4&)cullingParams.worldToClipMatrix, (Umbra_3_0::Vector3&)cullingParams.position);
	
    Umbra_3_0::IndexList staticObjs(output.visible[kStaticRenderers].indices, output.visible[kStaticRenderers].reservedSize);
	
    Umbra_3_0::Query::ErrorCode e;
	
    int flags = 0;
    if (tome->getStatistic(Umbra_3_0::Tome::STAT_PORTAL_DATA_SIZE))
        flags |= Umbra_3_0::Query::QUERYFLAG_PORTAL;
    else    // TODO: handle other cases?
        flags |= Umbra_3_0::Query::QUERYFLAG_PVS;
    
    e = query->queryCameraVisibility(flags, &staticObjs, NULL, camera);
	//Fallback to view frustum culling if queryCameraVisibility failed
	if (e != Umbra_3_0::Query::ERROR_OK)
	{
		cullingParams.useOcclusionCulling = false;
		cullingParams.useShadowCasterCulling = false;
		CullSceneWithoutUmbra(cullingParams, output);
		return;
	}
	output.visible[kStaticRenderers].size = staticObjs.getSize();
	
	// camera can move outside view volume Assert(e == Umbra::Query::ERROR_OK);
    // Extract visible indices
    if (!query->supportVFCulling())
		CullDynamicObjectsWithoutUmbraInOut (output.visible[kStaticRenderers], cullingParams, cullingParams.renderers[kStaticRenderers].bounds);

	//output.umbraVisibility->getOutputObjects()->setSize(output.visible[kStaticRenderers].size);

	ProcessIndexListIsNodeVisible(output.visible[kStaticRenderers], cullingParams.renderers[kStaticRenderers].nodes, cullingParams.renderers[kStaticRenderers].bounds, cullingParams);
	
	for (int i=kDynamicRenderer;i<kVisibleListCount;i++)
	{
		CullDynamicObjectsUmbraDeprecated (output.visible[i], cullingParams.renderers[i].bounds, cullingParams.renderers[i].rendererCount, region);
		ProcessIndexListIsNodeVisible(output.visible[i], cullingParams.renderers[i].nodes, cullingParams.renderers[i].bounds, cullingParams);
	}
}
#endif // SUPPORT_BACKWARDS_COMPATIBLE_UMBRA