1 /*
2  * Copyright 2013-2014 Dario Manesku. All rights reserved.
3  * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
4  */
5 
6 #include <string>
7 #include <vector>
8 #include <map>
9 #include <tinystl/allocator.h>
10 #include <tinystl/unordered_map.h>
11 namespace stl = tinystl;
12 
13 #include "common.h"
14 #include "bgfx_utils.h"
15 
16 #include <bgfx/bgfx.h>
17 #include <bx/timer.h>
18 #include <bx/allocator.h>
19 #include <bx/hash.h>
20 #include <bx/simd_t.h>
21 #include <bx/math.h>
22 #include <bx/file.h>
23 #include "entry/entry.h"
24 #include "camera.h"
25 #include "imgui/imgui.h"
26 
27 namespace bgfx
28 {
29 	int32_t read(bx::ReaderI* _reader, bgfx::VertexLayout& _layout, bx::Error* _err = NULL);
30 }
31 
32 namespace
33 {
34 
35 #define SV_USE_SIMD 1
36 #define MAX_INSTANCE_COUNT 25
37 #define MAX_LIGHTS_COUNT 5
38 
39 #define VIEWID_RANGE1_PASS0     1
40 #define VIEWID_RANGE1_RT_PASS1  2
41 #define VIEWID_RANGE15_PASS2    3
42 #define VIEWID_RANGE1_PASS3    20
43 
44 struct PosNormalTexcoordVertex
45 {
46 	float    m_x;
47 	float    m_y;
48 	float    m_z;
49 	uint32_t m_normal;
50 	float    m_u;
51 	float    m_v;
52 
init__anon4ff006020111::PosNormalTexcoordVertex53 	static void init()
54 	{
55 		ms_layout
56 			.begin()
57 			.add(bgfx::Attrib::Position,  3, bgfx::AttribType::Float)
58 			.add(bgfx::Attrib::Normal,    4, bgfx::AttribType::Uint8, true, true)
59 			.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
60 			.end();
61 	}
62 
63 	static bgfx::VertexLayout ms_layout;
64 };
65 
66 bgfx::VertexLayout PosNormalTexcoordVertex::ms_layout;
67 
68 static const float s_texcoord = 50.0f;
69 static PosNormalTexcoordVertex s_hplaneVertices[] =
70 {
71 	{ -1.0f, 0.0f,  1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f), s_texcoord, s_texcoord },
72 	{  1.0f, 0.0f,  1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f), s_texcoord, 0.0f       },
73 	{ -1.0f, 0.0f, -1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f), 0.0f,       s_texcoord },
74 	{  1.0f, 0.0f, -1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f), 0.0f,       0.0f       },
75 };
76 
77 static PosNormalTexcoordVertex s_vplaneVertices[] =
78 {
79 	{ -1.0f,  1.0f, 0.0f, encodeNormalRgba8(0.0f, 0.0f, -1.0f), 1.0f, 1.0f },
80 	{  1.0f,  1.0f, 0.0f, encodeNormalRgba8(0.0f, 0.0f, -1.0f), 1.0f, 0.0f },
81 	{ -1.0f, -1.0f, 0.0f, encodeNormalRgba8(0.0f, 0.0f, -1.0f), 0.0f, 1.0f },
82 	{  1.0f, -1.0f, 0.0f, encodeNormalRgba8(0.0f, 0.0f, -1.0f), 0.0f, 0.0f },
83 };
84 
85 static const uint16_t s_planeIndices[] =
86 {
87 	0, 1, 2,
88 	1, 3, 2,
89 };
90 
91 static bool s_oglNdc = false;
92 static float s_texelHalf = 0.0f;
93 
94 static uint32_t s_viewMask = 0;
95 
96 static bgfx::UniformHandle s_texColor;
97 static bgfx::UniformHandle s_texStencil;
98 static bgfx::FrameBufferHandle s_stencilFb;
99 
setViewClearMask(uint32_t _viewMask,uint8_t _flags,uint32_t _rgba,float _depth,uint8_t _stencil)100 void setViewClearMask(uint32_t _viewMask, uint8_t _flags, uint32_t _rgba, float _depth, uint8_t _stencil)
101 {
102 	for (uint32_t view = 0, viewMask = _viewMask; 0 != viewMask; viewMask >>= 1, view += 1 )
103 	{
104 		const uint32_t ntz = bx::uint32_cnttz(viewMask);
105 		viewMask >>= ntz;
106 		view += ntz;
107 
108 		bgfx::setViewClear( (uint8_t)view, _flags, _rgba, _depth, _stencil);
109 	}
110 }
111 
setViewTransformMask(uint32_t _viewMask,const void * _view,const void * _proj)112 void setViewTransformMask(uint32_t _viewMask, const void* _view, const void* _proj)
113 {
114 	for (uint32_t view = 0, viewMask = _viewMask; 0 != viewMask; viewMask >>= 1, view += 1 )
115 	{
116         const uint32_t ntz = bx::uint32_cnttz(viewMask);
117 		viewMask >>= ntz;
118 		view += ntz;
119 
120 		bgfx::setViewTransform( (uint8_t)view, _view, _proj);
121 	}
122 }
123 
setViewRectMask(uint32_t _viewMask,uint16_t _x,uint16_t _y,uint16_t _width,uint16_t _height)124 void setViewRectMask(uint32_t _viewMask, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
125 {
126 	for (uint32_t view = 0, viewMask = _viewMask; 0 != viewMask; viewMask >>= 1, view += 1 )
127 	{
128         const uint32_t ntz = bx::uint32_cnttz(viewMask);
129 		viewMask >>= ntz;
130 		view += ntz;
131 
132 		bgfx::setViewRect( (uint8_t)view, _x, _y, _width, _height);
133 	}
134 }
135 
mtxBillboard(float * _result,const float * _view,const float * _pos,const float * _scale)136 void mtxBillboard(
137 	  float* _result
138 	, const float* _view
139 	, const float* _pos
140 	, const float* _scale
141 	)
142 {
143 	_result[ 0] = _view[0]  * _scale[0];
144 	_result[ 1] = _view[4]  * _scale[0];
145 	_result[ 2] = _view[8]  * _scale[0];
146 	_result[ 3] = 0.0f;
147 	_result[ 4] = _view[1]  * _scale[1];
148 	_result[ 5] = _view[5]  * _scale[1];
149 	_result[ 6] = _view[9]  * _scale[1];
150 	_result[ 7] = 0.0f;
151 	_result[ 8] = _view[2]  * _scale[2];
152 	_result[ 9] = _view[6]  * _scale[2];
153 	_result[10] = _view[10] * _scale[2];
154 	_result[11] = 0.0f;
155 	_result[12] = _pos[0];
156 	_result[13] = _pos[1];
157 	_result[14] = _pos[2];
158 	_result[15] = 1.0f;
159 }
160 
planeNormal(float * _result,const float * _v0,const float * _v1,const float * _v2)161 void planeNormal(
162 	  float* _result
163 	, const float* _v0
164 	, const float* _v1
165 	, const float* _v2
166 	)
167 {
168 	const bx::Vec3 v0    = bx::load<bx::Vec3>(_v0);
169 	const bx::Vec3 v1    = bx::load<bx::Vec3>(_v1);
170 	const bx::Vec3 v2    = bx::load<bx::Vec3>(_v2);
171 	const bx::Vec3 vec0  = bx::sub(v1, v0);
172 	const bx::Vec3 vec1  = bx::sub(v2, v1);
173 	const bx::Vec3 cross = bx::cross(vec0, vec1);
174 
175 	bx::store(_result, bx::normalize(cross) );
176 
177 	_result[3] = -bx::dot(bx::load<bx::Vec3>(_result), bx::load<bx::Vec3>(_v0) );
178 }
179 
180 struct Uniforms
181 {
init__anon4ff006020111::Uniforms182 	void init()
183 	{
184 		m_params.m_ambientPass   = 1.0f;
185 		m_params.m_lightingPass  = 1.0f;
186 		m_params.m_texelHalf     = 0.0f;
187 
188 		m_ambient[0] = 0.05f;
189 		m_ambient[1] = 0.05f;
190 		m_ambient[2] = 0.05f;
191 		m_ambient[3] = 0.0f; //unused
192 
193 		m_diffuse[0] = 0.8f;
194 		m_diffuse[1] = 0.8f;
195 		m_diffuse[2] = 0.8f;
196 		m_diffuse[3] = 0.0f; //unused
197 
198 		m_specular_shininess[0] = 1.0f;
199 		m_specular_shininess[1] = 1.0f;
200 		m_specular_shininess[2] = 1.0f;
201 		m_specular_shininess[3] = 25.0f; //shininess
202 
203 		m_fog[0] = 0.0f; //color
204 		m_fog[1] = 0.0f;
205 		m_fog[2] = 0.0f;
206 		m_fog[3] = 0.0055f; //density
207 
208 		m_color[0] = 1.0f;
209 		m_color[1] = 1.0f;
210 		m_color[2] = 1.0f;
211 		m_color[3] = 1.0f;
212 
213 		m_time = 0.0f;
214 
215 		m_lightPosRadius[0] = 0.0f;
216 		m_lightPosRadius[1] = 0.0f;
217 		m_lightPosRadius[2] = 0.0f;
218 		m_lightPosRadius[3] = 1.0f;
219 
220 		m_lightRgbInnerR[0] = 0.0f;
221 		m_lightRgbInnerR[1] = 0.0f;
222 		m_lightRgbInnerR[2] = 0.0f;
223 		m_lightRgbInnerR[3] = 1.0f;
224 
225 		m_virtualLightPos_extrusionDist[0] = 0.0f;
226 		m_virtualLightPos_extrusionDist[1] = 0.0f;
227 		m_virtualLightPos_extrusionDist[2] = 0.0f;
228 		m_virtualLightPos_extrusionDist[3] = 100.0f;
229 
230 		u_params                        = bgfx::createUniform("u_params",                        bgfx::UniformType::Vec4);
231 		u_svparams                      = bgfx::createUniform("u_svparams",                      bgfx::UniformType::Vec4);
232 		u_ambient                       = bgfx::createUniform("u_ambient",                       bgfx::UniformType::Vec4);
233 		u_diffuse                       = bgfx::createUniform("u_diffuse",                       bgfx::UniformType::Vec4);
234 		u_specular_shininess            = bgfx::createUniform("u_specular_shininess",            bgfx::UniformType::Vec4);
235 		u_fog                           = bgfx::createUniform("u_fog",                           bgfx::UniformType::Vec4);
236 		u_color                         = bgfx::createUniform("u_color",                         bgfx::UniformType::Vec4);
237 		u_lightPosRadius                = bgfx::createUniform("u_lightPosRadius",                bgfx::UniformType::Vec4);
238 		u_lightRgbInnerR                = bgfx::createUniform("u_lightRgbInnerR",                bgfx::UniformType::Vec4);
239 		u_virtualLightPos_extrusionDist = bgfx::createUniform("u_virtualLightPos_extrusionDist", bgfx::UniformType::Vec4);
240 	}
241 
242 	//call this once at initialization
submitConstUniforms__anon4ff006020111::Uniforms243 	void submitConstUniforms()
244 	{
245 		bgfx::setUniform(u_ambient,            &m_ambient);
246 		bgfx::setUniform(u_diffuse,            &m_diffuse);
247 		bgfx::setUniform(u_specular_shininess, &m_specular_shininess);
248 		bgfx::setUniform(u_fog,                &m_fog);
249 	}
250 
251 	//call this before each draw call
submitPerDrawUniforms__anon4ff006020111::Uniforms252 	void submitPerDrawUniforms()
253 	{
254 		bgfx::setUniform(u_params,                        &m_params);
255 		bgfx::setUniform(u_svparams,                      &m_svparams);
256 		bgfx::setUniform(u_color,                         &m_color);
257 		bgfx::setUniform(u_lightPosRadius,                &m_lightPosRadius);
258 		bgfx::setUniform(u_lightRgbInnerR,                &m_lightRgbInnerR);
259 		bgfx::setUniform(u_virtualLightPos_extrusionDist, &m_virtualLightPos_extrusionDist);
260 	}
261 
destroy__anon4ff006020111::Uniforms262 	void destroy()
263 	{
264 		bgfx::destroy(u_params);
265 		bgfx::destroy(u_svparams);
266 		bgfx::destroy(u_ambient);
267 		bgfx::destroy(u_diffuse);
268 		bgfx::destroy(u_specular_shininess);
269 		bgfx::destroy(u_fog);
270 		bgfx::destroy(u_color);
271 		bgfx::destroy(u_lightPosRadius);
272 		bgfx::destroy(u_lightRgbInnerR);
273 		bgfx::destroy(u_virtualLightPos_extrusionDist);
274 	}
275 
276 	struct Params
277 	{
278 		float m_ambientPass;
279 		float m_lightingPass;
280 		float m_texelHalf;
281 		float m_unused00;
282 	};
283 
284 	struct SvParams
285 	{
286 		float m_useStencilTex;
287 		float m_dfail;
288 		float m_unused10;
289 		float m_unused11;
290 	};
291 
292 	Params m_params;
293 	SvParams m_svparams;
294 	float m_ambient[4];
295 	float m_diffuse[4];
296 	float m_specular_shininess[4];
297 	float m_fog[4];
298 	float m_color[4];
299 	float m_time;
300 	float m_lightPosRadius[4];
301 	float m_lightRgbInnerR[4];
302 	float m_virtualLightPos_extrusionDist[4];
303 
304 	/**
305 	 * u_params.x - u_ambientPass
306 	 * u_params.y - u_lightingPass
307 	 * u_params.z - u_texelHalf
308 	 * u_params.w - unused
309 
310 	 * u_svparams.x - u_useStencilTex
311 	 * u_svparams.y - u_dfail
312 	 * u_svparams.z - unused
313 	 * u_svparams.w - unused
314 	 */
315 
316 	bgfx::UniformHandle u_params;
317 	bgfx::UniformHandle u_svparams;
318 	bgfx::UniformHandle u_ambient;
319 	bgfx::UniformHandle u_diffuse;
320 	bgfx::UniformHandle u_specular_shininess;
321 	bgfx::UniformHandle u_fog;
322 	bgfx::UniformHandle u_color;
323 	bgfx::UniformHandle u_lightPosRadius;
324 	bgfx::UniformHandle u_lightRgbInnerR;
325 	bgfx::UniformHandle u_virtualLightPos_extrusionDist;
326 };
327 
328 static Uniforms s_uniforms;
329 
330 struct RenderState
331 {
332 	enum Enum
333 	{
334 		ShadowVolume_UsingStencilTexture_DrawAmbient = 0,
335 		ShadowVolume_UsingStencilTexture_BuildDepth,
336 		ShadowVolume_UsingStencilTexture_CraftStencil_DepthPass,
337 		ShadowVolume_UsingStencilTexture_CraftStencil_DepthFail,
338 		ShadowVolume_UsingStencilTexture_DrawDiffuse,
339 
340 		ShadowVolume_UsingStencilBuffer_DrawAmbient,
341 		ShadowVolume_UsingStencilBuffer_CraftStencil_DepthPass,
342 		ShadowVolume_UsingStencilBuffer_CraftStencil_DepthFail,
343 		ShadowVolume_UsingStencilBuffer_DrawDiffuse,
344 
345 		Custom_Default,
346 		Custom_BlendLightTexture,
347 		Custom_DrawPlaneBottom,
348 		Custom_DrawShadowVolume_Lines,
349 
350 		Count
351 	};
352 
353 	uint64_t m_state;
354 	uint32_t m_blendFactorRgba;
355 	uint32_t m_fstencil;
356 	uint32_t m_bstencil;
357 };
358 
setRenderState(const RenderState & _renderState)359 static void setRenderState(const RenderState& _renderState)
360 {
361 	bgfx::setStencil(_renderState.m_fstencil, _renderState.m_bstencil);
362 	bgfx::setState(_renderState.m_state, _renderState.m_blendFactorRgba);
363 }
364 
365 static RenderState s_renderStates[RenderState::Count]  =
366 {
367 	{ // ShadowVolume_UsingStencilTexture_DrawAmbient
368 		BGFX_STATE_WRITE_RGB
369 		| BGFX_STATE_WRITE_A
370 		| BGFX_STATE_WRITE_Z
371 		| BGFX_STATE_DEPTH_TEST_LESS
372 		| BGFX_STATE_CULL_CCW
373 		| BGFX_STATE_MSAA
374 		, UINT32_MAX
375 		, BGFX_STENCIL_NONE
376 		, BGFX_STENCIL_NONE
377 	},
378 	{ // ShadowVolume_UsingStencilTexture_BuildDepth
379 		BGFX_STATE_WRITE_Z
380 		| BGFX_STATE_DEPTH_TEST_LESS
381 		| BGFX_STATE_CULL_CCW
382 		| BGFX_STATE_MSAA
383 		, UINT32_MAX
384 		, BGFX_STENCIL_NONE
385 		, BGFX_STENCIL_NONE
386 	},
387 	{ // ShadowVolume_UsingStencilTexture_CraftStencil_DepthPass
388 		BGFX_STATE_WRITE_RGB
389 		| BGFX_STATE_WRITE_A
390 		| BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)
391 		| BGFX_STATE_DEPTH_TEST_LEQUAL
392 		| BGFX_STATE_MSAA
393 		, UINT32_MAX
394 		, BGFX_STENCIL_NONE
395 		, BGFX_STENCIL_NONE
396 	},
397 	{ // ShadowVolume_UsingStencilTexture_CraftStencil_DepthFail
398 		BGFX_STATE_WRITE_RGB
399 		| BGFX_STATE_WRITE_A
400 		| BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)
401 		| BGFX_STATE_DEPTH_TEST_GEQUAL
402 		| BGFX_STATE_MSAA
403 		, UINT32_MAX
404 		, BGFX_STENCIL_NONE
405 		, BGFX_STENCIL_NONE
406 		},
407 	{ // ShadowVolume_UsingStencilTexture_DrawDiffuse
408 		BGFX_STATE_WRITE_RGB
409 		| BGFX_STATE_WRITE_A
410 		| BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)
411 		| BGFX_STATE_WRITE_Z
412 		| BGFX_STATE_DEPTH_TEST_EQUAL
413 		| BGFX_STATE_CULL_CCW
414 		| BGFX_STATE_MSAA
415 		, UINT32_MAX
416 		, BGFX_STENCIL_NONE
417 		, BGFX_STENCIL_NONE
418 	},
419 	{ // ShadowVolume_UsingStencilBuffer_DrawAmbient
420 		BGFX_STATE_WRITE_RGB
421 		| BGFX_STATE_WRITE_A
422 		| BGFX_STATE_WRITE_Z
423 		| BGFX_STATE_DEPTH_TEST_LESS
424 		| BGFX_STATE_CULL_CCW
425 		| BGFX_STATE_MSAA
426 		, UINT32_MAX
427 		, BGFX_STENCIL_NONE
428 		, BGFX_STENCIL_NONE
429 	},
430 	{ // ShadowVolume_UsingStencilBuffer_CraftStencil_DepthPass
431 		BGFX_STATE_DEPTH_TEST_LEQUAL
432 		| BGFX_STATE_MSAA
433 		, UINT32_MAX
434 		, BGFX_STENCIL_TEST_ALWAYS
435 		| BGFX_STENCIL_FUNC_REF(1)
436 		| BGFX_STENCIL_FUNC_RMASK(0xff)
437 		| BGFX_STENCIL_OP_FAIL_S_KEEP
438 		| BGFX_STENCIL_OP_FAIL_Z_KEEP
439 		| BGFX_STENCIL_OP_PASS_Z_DECR
440 		, BGFX_STENCIL_TEST_ALWAYS
441 		| BGFX_STENCIL_FUNC_REF(1)
442 		| BGFX_STENCIL_FUNC_RMASK(0xff)
443 		| BGFX_STENCIL_OP_FAIL_S_KEEP
444 		| BGFX_STENCIL_OP_FAIL_Z_KEEP
445 		| BGFX_STENCIL_OP_PASS_Z_INCR
446 	},
447 	{ // ShadowVolume_UsingStencilBuffer_CraftStencil_DepthFail
448 		BGFX_STATE_DEPTH_TEST_LEQUAL
449 		| BGFX_STATE_MSAA
450 		, UINT32_MAX
451 		, BGFX_STENCIL_TEST_ALWAYS
452 		| BGFX_STENCIL_FUNC_REF(1)
453 		| BGFX_STENCIL_FUNC_RMASK(0xff)
454 		| BGFX_STENCIL_OP_FAIL_S_KEEP
455 		| BGFX_STENCIL_OP_FAIL_Z_INCR
456 		| BGFX_STENCIL_OP_PASS_Z_KEEP
457 		, BGFX_STENCIL_TEST_ALWAYS
458 		| BGFX_STENCIL_FUNC_REF(1)
459 		| BGFX_STENCIL_FUNC_RMASK(0xff)
460 		| BGFX_STENCIL_OP_FAIL_S_KEEP
461 		| BGFX_STENCIL_OP_FAIL_Z_DECR
462 		| BGFX_STENCIL_OP_PASS_Z_KEEP
463 	},
464 	{ // ShadowVolume_UsingStencilBuffer_DrawDiffuse
465 		BGFX_STATE_WRITE_RGB
466 		| BGFX_STATE_WRITE_A
467 		| BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)
468 		| BGFX_STATE_DEPTH_TEST_EQUAL
469 		| BGFX_STATE_CULL_CCW
470 		| BGFX_STATE_MSAA
471 		, UINT32_MAX
472 		, BGFX_STENCIL_TEST_EQUAL
473 		| BGFX_STENCIL_FUNC_REF(0)
474 		| BGFX_STENCIL_FUNC_RMASK(0xff)
475 		| BGFX_STENCIL_OP_FAIL_S_KEEP
476 		| BGFX_STENCIL_OP_FAIL_Z_KEEP
477 		| BGFX_STENCIL_OP_PASS_Z_KEEP
478 		, BGFX_STENCIL_NONE
479 	},
480 	{ // Custom_Default
481 		BGFX_STATE_WRITE_RGB
482 		| BGFX_STATE_WRITE_A
483 		| BGFX_STATE_WRITE_Z
484 		| BGFX_STATE_DEPTH_TEST_LESS
485 		| BGFX_STATE_CULL_CCW
486 		| BGFX_STATE_MSAA
487 		, UINT32_MAX
488 		, BGFX_STENCIL_NONE
489 		, BGFX_STENCIL_NONE
490 	},
491 	{ // Custom_BlendLightTexture
492 		BGFX_STATE_WRITE_RGB
493 		| BGFX_STATE_WRITE_A
494 		| BGFX_STATE_WRITE_Z
495 		| BGFX_STATE_DEPTH_TEST_LESS
496 		| BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_COLOR, BGFX_STATE_BLEND_INV_SRC_COLOR)
497 		| BGFX_STATE_CULL_CCW
498 		| BGFX_STATE_MSAA
499 		, UINT32_MAX
500 		, BGFX_STENCIL_NONE
501 		, BGFX_STENCIL_NONE
502 	},
503 	{ // Custom_DrawPlaneBottom
504 		BGFX_STATE_WRITE_RGB
505 		| BGFX_STATE_WRITE_A
506 		| BGFX_STATE_WRITE_Z
507 		| BGFX_STATE_CULL_CW
508 		| BGFX_STATE_MSAA
509 		, UINT32_MAX
510 		, BGFX_STENCIL_NONE
511 		, BGFX_STENCIL_NONE
512 	},
513 	{ // Custom_DrawShadowVolume_Lines
514 		BGFX_STATE_WRITE_RGB
515 		| BGFX_STATE_DEPTH_TEST_LESS
516 		| BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_FACTOR, BGFX_STATE_BLEND_SRC_ALPHA)
517 		| BGFX_STATE_PT_LINES
518 		| BGFX_STATE_MSAA
519 		, 0x0f0f0fff
520 		, BGFX_STENCIL_NONE
521 		, BGFX_STENCIL_NONE
522 	}
523 };
524 
525 struct ViewState
526 {
ViewState__anon4ff006020111::ViewState527 	ViewState(uint32_t _width = 0, uint32_t _height = 0)
528 		: m_width(_width)
529 		, m_height(_height)
530 	{
531 	}
532 
533 	uint32_t m_width;
534 	uint32_t m_height;
535 
536 	float m_view[16];
537 	float m_proj[16];
538 };
539 
540 struct ClearValues
541 {
542 	uint32_t m_clearRgba;
543 	float    m_clearDepth;
544 	uint8_t  m_clearStencil;
545 };
546 
submit(bgfx::ViewId _id,bgfx::ProgramHandle _handle,int32_t _depth=0)547 void submit(bgfx::ViewId _id, bgfx::ProgramHandle _handle, int32_t _depth = 0)
548 {
549 	bgfx::submit(_id, _handle, _depth);
550 
551 	// Keep track of submited view ids.
552 	s_viewMask |= 1 << _id;
553 }
554 
touch(bgfx::ViewId _id)555 void touch(bgfx::ViewId _id)
556 {
557 	bgfx::ProgramHandle handle = BGFX_INVALID_HANDLE;
558 	::submit(_id, handle);
559 }
560 
561 struct Face
562 {
563 	uint16_t m_i[3];
564 	float m_plane[4];
565 };
566 typedef std::vector<Face> FaceArray;
567 
568 struct Edge
569 {
570 	bool m_faceReverseOrder[2];
571 	uint8_t m_faceIndex;
572 	uint16_t m_i0, m_i1;
573 };
574 
575 struct Plane
576 {
577 	float m_plane[4];
578 };
579 
580 struct HalfEdge
581 {
582 #define INVALID_EDGE_INDEX UINT16_MAX
583 	uint16_t m_secondIndex;
584 	bool m_marked;
585 };
586 
587 struct HalfEdges
588 {
HalfEdges__anon4ff006020111::HalfEdges589 	HalfEdges()
590 		: m_data()
591 		, m_offsets()
592 		, m_endPtr()
593 	{
594 	}
595 
init__anon4ff006020111::HalfEdges596 	void init(uint16_t* _indices, uint32_t _numIndices)
597 	{
598 		m_data = (HalfEdge*)malloc(2 * _numIndices * sizeof(HalfEdge) );
599 
600 		stl::unordered_map<uint16_t, std::vector<uint16_t> > edges;
601 		for (uint32_t ii = 0; ii < _numIndices; ii+=3)
602 		{
603 			uint16_t idx0 = _indices[ii];
604 			uint16_t idx1 = _indices[ii+1];
605 			uint16_t idx2 = _indices[ii+2];
606 
607 			edges[idx0].push_back(idx1);
608 			edges[idx1].push_back(idx2);
609 			edges[idx2].push_back(idx0);
610 		}
611 
612 		uint32_t numRows = (uint32_t)edges.size();
613 		m_offsets = (uint32_t*)malloc(numRows * sizeof(uint32_t) );
614 
615 		HalfEdge* he = m_data;
616 		for (uint16_t ii = 0; ii < numRows; ++ii)
617 		{
618 			m_offsets[ii] = uint32_t(he - m_data);
619 
620 			std::vector<uint16_t>& row = edges[ii];
621 			for (uint32_t jj = 0, size = (uint32_t)row.size(); jj < size; ++jj)
622 			{
623 				he->m_secondIndex = row[jj];
624 				he->m_marked = false;
625 				++he;
626 			}
627 			he->m_secondIndex = INVALID_EDGE_INDEX;
628 			++he;
629 		}
630 		he->m_secondIndex = 0;
631 		m_endPtr = he;
632 	}
633 
destroy__anon4ff006020111::HalfEdges634 	void destroy()
635 	{
636 		free(m_data);
637 		m_data = NULL;
638 		free(m_offsets);
639 		m_offsets = NULL;
640 	}
641 
mark__anon4ff006020111::HalfEdges642 	void mark(uint16_t _firstIndex, uint16_t _secondIndex)
643 	{
644 		HalfEdge* ptr = &m_data[m_offsets[_firstIndex]];
645 		while (INVALID_EDGE_INDEX != ptr->m_secondIndex)
646 		{
647 			if (ptr->m_secondIndex == _secondIndex)
648 			{
649 				ptr->m_marked = true;
650 				break;
651 			}
652 			++ptr;
653 		}
654 	}
655 
unmark__anon4ff006020111::HalfEdges656 	bool unmark(uint16_t _firstIndex, uint16_t _secondIndex)
657 	{
658 		bool ret = false;
659 		HalfEdge* ptr = &m_data[m_offsets[_firstIndex]];
660 		while (INVALID_EDGE_INDEX != ptr->m_secondIndex)
661 		{
662 			if (ptr->m_secondIndex == _secondIndex && ptr->m_marked)
663 			{
664 				ptr->m_marked = false;
665 				ret = true;
666 				break;
667 			}
668 			++ptr;
669 		}
670 		return ret;
671 	}
672 
begin__anon4ff006020111::HalfEdges673 	inline HalfEdge* begin() const
674 	{
675 		return m_data;
676 	}
677 
end__anon4ff006020111::HalfEdges678 	inline HalfEdge* end() const
679 	{
680 		return m_endPtr;
681 	}
682 
683 	HalfEdge* m_data;
684 	uint32_t* m_offsets;
685 	HalfEdge* m_endPtr;
686 };
687 
688 struct WeldedVertex
689 {
690 	uint16_t m_v;
691 	bool m_welded;
692 };
693 
sqLength(const float _a[3],const float _b[3])694 inline float sqLength(const float _a[3], const float _b[3])
695 {
696 	const float xx = _a[0] - _b[0];
697 	const float yy = _a[1] - _b[1];
698 	const float zz = _a[2] - _b[2];
699 	return xx*xx + yy*yy + zz*zz;
700 }
701 
weldVertices(WeldedVertex * _output,const bgfx::VertexLayout & _layout,const void * _data,uint16_t _num,float _epsilon)702 uint16_t weldVertices(WeldedVertex* _output, const bgfx::VertexLayout& _layout, const void* _data, uint16_t _num, float _epsilon)
703 {
704 	const uint32_t hashSize = bx::uint32_nextpow2(_num);
705 	const uint32_t hashMask = hashSize-1;
706 	const float epsilonSq = _epsilon*_epsilon;
707 
708 	uint16_t numVertices = 0;
709 
710 	const uint32_t size = sizeof(uint16_t)*(hashSize + _num);
711 	uint16_t* hashTable = (uint16_t*)alloca(size);
712 	bx::memSet(hashTable, 0xff, size);
713 
714 	uint16_t* next = hashTable + hashSize;
715 
716 	for (uint16_t ii = 0; ii < _num; ++ii)
717 	{
718 		float pos[4];
719 		vertexUnpack(pos, bgfx::Attrib::Position, _layout, _data, ii);
720 		uint32_t hashValue = bx::hash<bx::HashMurmur2A>(pos, 3*sizeof(float) ) & hashMask;
721 
722 		uint16_t offset = hashTable[hashValue];
723 		for (; UINT16_MAX != offset; offset = next[offset])
724 		{
725 			float test[4];
726 			vertexUnpack(test, bgfx::Attrib::Position, _layout, _data, _output[offset].m_v);
727 
728 			if (sqLength(test, pos) < epsilonSq)
729 			{
730 				_output[ii].m_v = _output[offset].m_v;
731 				_output[ii].m_welded = true;
732 				break;
733 			}
734 		}
735 
736 		if (UINT16_MAX == offset)
737 		{
738 			_output[ii].m_v = ii;
739 			_output[ii].m_welded = false;
740 			next[ii] = hashTable[hashValue];
741 			hashTable[hashValue] = ii;
742 			numVertices++;
743 		}
744 	}
745 
746 	return numVertices;
747 }
748 
749 struct Group
750 {
Group__anon4ff006020111::Group751 	Group()
752 	{
753 		reset();
754 	}
755 
reset__anon4ff006020111::Group756 	void reset()
757 	{
758 		m_vbh.idx = bgfx::kInvalidHandle;
759 		m_ibh.idx = bgfx::kInvalidHandle;
760 		m_numVertices = 0;
761 		m_vertices = NULL;
762 		m_numIndices = 0;
763 		m_indices = NULL;
764 		m_numEdges = 0;
765 		m_edges = NULL;
766 		m_edgePlanesUnalignedPtr = NULL;
767 		m_prims.clear();
768 	}
769 
770 	typedef struct { float f[6]; } f6_t;
771 
772 	struct EdgeAndPlane
773 	{
EdgeAndPlane__anon4ff006020111::Group::EdgeAndPlane774 		EdgeAndPlane(uint16_t _i0, uint16_t _i1)
775 			: m_faceIndex(0)
776 			, m_i0(_i0)
777 			, m_i1(_i1)
778 		{
779 		}
780 
781 		bool m_faceReverseOrder[2];
782 		uint8_t m_faceIndex;
783 		uint16_t m_i0, m_i1;
784 		Plane m_plane[2];
785 	};
786 
fillStructures__anon4ff006020111::Group787 	void fillStructures(const bgfx::VertexLayout& _layout)
788 	{
789 		uint16_t stride = _layout.getStride();
790 		m_faces.clear();
791 		m_halfEdges.destroy();
792 
793 		//Init halfedges.
794 		m_halfEdges.init(m_indices, m_numIndices);
795 
796 		//Init faces and edges.
797 		m_faces.reserve(m_numIndices/3); //1 face = 3 indices
798 		m_edges = (Edge*)malloc(m_numIndices * sizeof(Edge) ); //1 triangle = 3 indices = 3 edges.
799 		m_edgePlanesUnalignedPtr = (Plane*)malloc(m_numIndices * sizeof(Plane) + 15);
800 		m_edgePlanes = (Plane*)bx::alignPtr(m_edgePlanesUnalignedPtr, 0, 16);
801 
802 		typedef std::map<std::pair<uint16_t, uint16_t>, EdgeAndPlane> EdgeMap;
803 		EdgeMap edgeMap;
804 
805 		//Get unique indices.
806 		WeldedVertex* uniqueVertices = (WeldedVertex*)malloc(m_numVertices*sizeof(WeldedVertex) );
807 		::weldVertices(uniqueVertices, _layout, m_vertices, m_numVertices, 0.0001f);
808 		uint16_t* uniqueIndices = (uint16_t*)malloc(m_numIndices*sizeof(uint16_t) );
809 		for (uint32_t ii = 0; ii < m_numIndices; ++ii)
810 		{
811 			uint16_t index = m_indices[ii];
812 			if (uniqueVertices[index].m_welded)
813 			{
814 				uniqueIndices[ii] = uniqueVertices[index].m_v;
815 			}
816 			else
817 			{
818 				uniqueIndices[ii] = index;
819 			}
820 		}
821 		free(uniqueVertices);
822 
823 		for (uint32_t ii = 0, size = m_numIndices/3; ii < size; ++ii)
824 		{
825 			const uint16_t* indices = &m_indices[ii*3];
826 			uint16_t i0 = indices[0];
827 			uint16_t i1 = indices[1];
828 			uint16_t i2 = indices[2];
829 			const float* v0 = (float*)&m_vertices[i0*stride];
830 			const float* v1 = (float*)&m_vertices[i1*stride];
831 			const float* v2 = (float*)&m_vertices[i2*stride];
832 
833 			float plane[4];
834 			planeNormal(plane, v0, v2, v1);
835 
836 			Face face;
837 			face.m_i[0] = i0;
838 			face.m_i[1] = i1;
839 			face.m_i[2] = i2;
840 			bx::memCopy(face.m_plane, plane, 4*sizeof(float) );
841 			m_faces.push_back(face);
842 
843 			//Use unique indices for EdgeMap.
844 			const uint16_t* uindices = &uniqueIndices[ii*3];
845 			i0 = uindices[0];
846 			i1 = uindices[1];
847 			i2 = uindices[2];
848 
849 			const uint16_t triangleEdge[3][2] =
850 			{
851 				{ i0, i1 },
852 				{ i1, i2 },
853 				{ i2, i0 },
854 			};
855 
856 			for (uint8_t jj = 0; jj < 3; ++jj)
857 			{
858 				const uint16_t ui0 = triangleEdge[jj][0];
859 				const uint16_t ui1 = triangleEdge[jj][1];
860 
861 				std::pair<uint16_t, uint16_t> key    = std::make_pair(ui0, ui1);
862 				std::pair<uint16_t, uint16_t> keyInv = std::make_pair(ui1, ui0);
863 
864 				EdgeMap::iterator iter = edgeMap.find(keyInv);
865 				if (iter != edgeMap.end() )
866 				{
867 					EdgeAndPlane& ep = iter->second;
868 					bx::memCopy(ep.m_plane[ep.m_faceIndex].m_plane, plane, 4*sizeof(float) );
869 					ep.m_faceReverseOrder[ep.m_faceIndex] = true;
870 				}
871 				else
872 				{
873 					std::pair<EdgeMap::iterator, bool> result = edgeMap.insert(std::make_pair(key, EdgeAndPlane(ui0, ui1) ) );
874 					EdgeAndPlane& ep = result.first->second;
875 					bx::memCopy(ep.m_plane[ep.m_faceIndex].m_plane, plane, 4*sizeof(float) );
876 					ep.m_faceReverseOrder[ep.m_faceIndex] = false;
877 					ep.m_faceIndex++;
878 				}
879 			}
880 		}
881 
882 		free(uniqueIndices);
883 
884 		uint32_t index = 0;
885 		for (EdgeMap::const_iterator iter = edgeMap.begin(), end = edgeMap.end(); iter != end; ++iter)
886 		{
887 			Edge* edge = &m_edges[m_numEdges];
888 			Plane* plane = &m_edgePlanes[index];
889 
890 			bx::memCopy(edge, iter->second.m_faceReverseOrder, sizeof(Edge) );
891 			bx::memCopy(plane, iter->second.m_plane, 2 * sizeof(Plane) );
892 
893 			m_numEdges++;
894 			index += 2;
895 		}
896 	}
897 
unload__anon4ff006020111::Group898 	void unload()
899 	{
900 		bgfx::destroy(m_vbh);
901 		if (bgfx::kInvalidHandle != m_ibh.idx)
902 		{
903 			bgfx::destroy(m_ibh);
904 		}
905 		free(m_vertices);
906 		m_vertices = NULL;
907 		free(m_indices);
908 		m_indices = NULL;
909 		free(m_edges);
910 		m_edges = NULL;
911 		free(m_edgePlanesUnalignedPtr);
912 		m_edgePlanesUnalignedPtr = NULL;
913 		m_halfEdges.destroy();
914 	}
915 
916 	bgfx::VertexBufferHandle m_vbh;
917 	bgfx::IndexBufferHandle m_ibh;
918 	uint16_t m_numVertices;
919 	uint8_t* m_vertices;
920 	uint32_t m_numIndices;
921 	uint16_t* m_indices;
922 	Sphere m_sphere;
923 	Aabb m_aabb;
924 	Obb m_obb;
925 	PrimitiveArray m_prims;
926 	uint32_t m_numEdges;
927 	Edge* m_edges;
928 	Plane* m_edgePlanesUnalignedPtr;
929 	Plane* m_edgePlanes;
930 	FaceArray m_faces;
931 	HalfEdges m_halfEdges;
932 };
933 
934 typedef std::vector<Group> GroupArray;
935 
936 struct Mesh
937 {
load__anon4ff006020111::Mesh938 	void load(const void* _vertices, uint16_t _numVertices, const bgfx::VertexLayout _layout, const uint16_t* _indices, uint32_t _numIndices)
939 	{
940 		Group group;
941 		const bgfx::Memory* mem;
942 		uint32_t size;
943 
944 		//vertices
945 		group.m_numVertices = _numVertices;
946 		size = _numVertices*_layout.getStride();
947 
948 		group.m_vertices = (uint8_t*)malloc(size);
949 		bx::memCopy(group.m_vertices, _vertices, size);
950 
951 		mem = bgfx::makeRef(group.m_vertices, size);
952 		group.m_vbh = bgfx::createVertexBuffer(mem, _layout);
953 
954 		//indices
955 		group.m_numIndices = _numIndices;
956 		size = _numIndices*2;
957 
958 		group.m_indices = (uint16_t*)malloc(size);
959 		bx::memCopy(group.m_indices, _indices, size);
960 
961 		mem = bgfx::makeRef(group.m_indices, size);
962 		group.m_ibh = bgfx::createIndexBuffer(mem);
963 
964 		m_groups.push_back(group);
965 	}
966 
load__anon4ff006020111::Mesh967 	void load(const char* _filePath)
968 	{
969 		::Mesh* mesh = ::meshLoad(_filePath, true);
970 		m_layout = mesh->m_layout;
971 		uint16_t stride = m_layout.getStride();
972 
973 		for (::GroupArray::iterator it = mesh->m_groups.begin(), itEnd = mesh->m_groups.end(); it != itEnd; ++it)
974 		{
975 			Group group;
976 			group.m_numVertices = it->m_numVertices;
977 			const uint32_t vertexSize = group.m_numVertices*stride;
978 			group.m_vertices = (uint8_t*)malloc(vertexSize);
979 			bx::memCopy(group.m_vertices, it->m_vertices, vertexSize);
980 
981 			const bgfx::Memory* mem = bgfx::makeRef(group.m_vertices, vertexSize);
982 			group.m_vbh = bgfx::createVertexBuffer(mem, m_layout);
983 
984 			group.m_numIndices = it->m_numIndices;
985 			const uint32_t indexSize = 2 * group.m_numIndices;
986 			group.m_indices = (uint16_t*)malloc(indexSize);
987 			bx::memCopy(group.m_indices, it->m_indices, indexSize);
988 
989 			mem = bgfx::makeRef(group.m_indices, indexSize);
990 			group.m_ibh = bgfx::createIndexBuffer(mem);
991 
992 			group.m_sphere = it->m_sphere;
993 			group.m_aabb = it->m_aabb;
994 			group.m_obb = it->m_obb;
995 			group.m_prims = it->m_prims;
996 
997 			m_groups.push_back(group);
998 		}
999 		::meshUnload(mesh);
1000 
1001 		for (GroupArray::iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
1002 		{
1003 			it->fillStructures(m_layout);
1004 		}
1005 	}
1006 
unload__anon4ff006020111::Mesh1007 	void unload()
1008 	{
1009 		for (GroupArray::iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
1010 		{
1011 			it->unload();
1012 		}
1013 		m_groups.clear();
1014 	}
1015 
1016 	bgfx::VertexLayout m_layout;
1017 	GroupArray m_groups;
1018 };
1019 
1020 struct Model
1021 {
Model__anon4ff006020111::Model1022 	Model()
1023 	{
1024 		m_program.idx = bgfx::kInvalidHandle;
1025 		m_texture.idx = bgfx::kInvalidHandle;
1026 	}
1027 
load__anon4ff006020111::Model1028 	void load(const void* _vertices, uint16_t _numVertices, const bgfx::VertexLayout _layout, const uint16_t* _indices, uint32_t _numIndices)
1029 	{
1030 		m_mesh.load(_vertices, _numVertices, _layout, _indices, _numIndices);
1031 	}
1032 
load__anon4ff006020111::Model1033 	void load(const char* _meshFilePath)
1034 	{
1035 		m_mesh.load(_meshFilePath);
1036 	}
1037 
unload__anon4ff006020111::Model1038 	void unload()
1039 	{
1040 		m_mesh.unload();
1041 	}
1042 
submit__anon4ff006020111::Model1043 	void submit(uint8_t _viewId, float* _mtx, const RenderState& _renderState)
1044 	{
1045 		for (GroupArray::const_iterator it = m_mesh.m_groups.begin(), itEnd = m_mesh.m_groups.end(); it != itEnd; ++it)
1046 		{
1047 			const Group& group = *it;
1048 
1049 			// Set uniforms
1050 			s_uniforms.submitPerDrawUniforms();
1051 
1052 			// Set transform
1053 			bgfx::setTransform(_mtx);
1054 
1055 			// Set buffers
1056 			bgfx::setIndexBuffer(group.m_ibh);
1057 			bgfx::setVertexBuffer(0, group.m_vbh);
1058 
1059 			// Set textures
1060 			if (bgfx::kInvalidHandle != m_texture.idx)
1061 			{
1062 				bgfx::setTexture(0, s_texColor, m_texture);
1063 			}
1064 			bgfx::setTexture(1, s_texStencil, bgfx::getTexture(s_stencilFb) );
1065 
1066 			// Apply render state
1067 			::setRenderState(_renderState);
1068 
1069 			// Submit
1070 			BX_CHECK(bgfx::kInvalidHandle != m_program, "Error, program is not set.");
1071 			::submit(_viewId, m_program);
1072 		}
1073 	}
1074 
1075 	Mesh m_mesh;
1076 	bgfx::ProgramHandle m_program;
1077 	bgfx::TextureHandle m_texture;
1078 };
1079 
1080 struct Instance
1081 {
Instance__anon4ff006020111::Instance1082 	Instance()
1083 		: m_svExtrusionDistance(150.0f)
1084 	{
1085 		m_color[0] = 1.0f;
1086 		m_color[1] = 1.0f;
1087 		m_color[2] = 1.0f;
1088 	}
1089 
submit__anon4ff006020111::Instance1090 	void submit(uint8_t _viewId, const RenderState& _renderState)
1091 	{
1092 		bx::memCopy(s_uniforms.m_color, m_color, 3*sizeof(float) );
1093 
1094 		float mtx[16];
1095 		bx::mtxSRT(mtx
1096 			, m_scale[0]
1097 			, m_scale[1]
1098 			, m_scale[2]
1099 			, m_rotation[0]
1100 			, m_rotation[1]
1101 			, m_rotation[2]
1102 			, m_pos[0]
1103 			, m_pos[1]
1104 			, m_pos[2]
1105 			);
1106 
1107 		BX_CHECK(NULL != m_model, "Instance model cannot be NULL!");
1108 		m_model->submit(_viewId, mtx, _renderState);
1109 	}
1110 
1111 	float m_scale[3];
1112 	float m_rotation[3];
1113 	float m_pos[3];
1114 
1115 	float m_color[3];
1116 	float m_svExtrusionDistance;
1117 
1118 	Model* m_model;
1119 };
1120 
1121 #define SV_INSTANCE_MEM_SIZE (1500 << 10)
1122 #define SV_INSTANCE_COUNT ( (25 > MAX_INSTANCE_COUNT) ? 25 : MAX_INSTANCE_COUNT)
1123 #define SV_PAGE_SIZE (SV_INSTANCE_MEM_SIZE * SV_INSTANCE_COUNT * MAX_LIGHTS_COUNT)
1124 
1125 struct ShadowVolumeAllocator
1126 {
ShadowVolumeAllocator__anon4ff006020111::ShadowVolumeAllocator1127 	ShadowVolumeAllocator()
1128 	{
1129 		m_mem = (uint8_t*)malloc(SV_PAGE_SIZE*2);
1130 		m_ptr = m_mem;
1131 		m_firstPage = true;
1132 	}
1133 
~ShadowVolumeAllocator__anon4ff006020111::ShadowVolumeAllocator1134 	~ShadowVolumeAllocator()
1135 	{
1136 		free(m_mem);
1137 	}
1138 
alloc__anon4ff006020111::ShadowVolumeAllocator1139 	void* alloc(uint32_t _size)
1140 	{
1141 		void* ret = (void*)m_ptr;
1142 		m_ptr += _size;
1143 		BX_CHECK(m_ptr - m_mem < (m_firstPage ? SV_PAGE_SIZE : 2 * SV_PAGE_SIZE), "Buffer overflow!");
1144 		return ret;
1145 	}
1146 
swap__anon4ff006020111::ShadowVolumeAllocator1147 	void swap()
1148 	{
1149 		m_ptr = m_firstPage ? m_mem + SV_PAGE_SIZE : m_mem;
1150 		m_firstPage = !m_firstPage;
1151 	}
1152 
1153 	uint8_t* m_mem;
1154 	uint8_t* m_ptr;
1155 	bool m_firstPage;
1156 };
1157 static ShadowVolumeAllocator s_svAllocator;
1158 
1159 struct ShadowVolumeImpl
1160 {
1161 	enum Enum
1162 	{
1163 		DepthPass,
1164 		DepthFail,
1165 	};
1166 };
1167 
1168 struct ShadowVolumeAlgorithm
1169 {
1170 	enum Enum
1171 	{
1172 		FaceBased,
1173 		EdgeBased,
1174 	};
1175 };
1176 
1177 struct ShadowVolume
1178 {
1179 	bgfx::VertexBufferHandle m_vbSides;
1180 	bgfx::IndexBufferHandle m_ibSides;
1181 	bgfx::IndexBufferHandle m_ibFrontCap;
1182 	bgfx::IndexBufferHandle m_ibBackCap;
1183 
1184 	uint32_t m_numVertices;
1185 	uint32_t m_numIndices;
1186 
1187 	const float* m_mtx;
1188 	const float* m_lightPos;
1189 
1190 	bool m_cap;
1191 };
1192 
shadowVolumeLightTransform(float * _outLightPos,const float * _scale,const float * _rotate,const float * _translate,const float * _lightPos)1193 void shadowVolumeLightTransform(
1194 	  float* _outLightPos
1195 	, const float* _scale
1196 	, const float* _rotate
1197 	, const float* _translate
1198 	, const float* _lightPos // world pos
1199 	)
1200 {
1201 	/**
1202 	 * Instead of transforming all the vertices, transform light instead:
1203 	 * mtx = pivotTranslate -> rotateZYX -> invScale
1204 	 * light = mtx * origin
1205 	 */
1206 
1207 	float pivot[16];
1208 	bx::mtxTranslate(pivot
1209 		, _lightPos[0] - _translate[0]
1210 		, _lightPos[1] - _translate[1]
1211 		, _lightPos[2] - _translate[2]
1212 		);
1213 
1214 	float mzyx[16];
1215 	bx::mtxRotateZYX(mzyx
1216 		, -_rotate[0]
1217 		, -_rotate[1]
1218 		, -_rotate[2]
1219 		);
1220 
1221 	float invScale[16];
1222 	bx::mtxScale(invScale
1223 		, 1.0f / _scale[0]
1224 		, 1.0f / _scale[1]
1225 		, 1.0f / _scale[2]
1226 		);
1227 
1228 	float tmp0[16];
1229 	bx::mtxMul(tmp0, pivot, mzyx);
1230 
1231 	float mtx[16];
1232 	bx::mtxMul(mtx, tmp0, invScale);
1233 
1234 	bx::store(_outLightPos, bx::mul({ 0.0f, 0.0f, 0.0f }, mtx) );
1235 }
1236 
shadowVolumeCreate(ShadowVolume & _shadowVolume,Group & _group,uint16_t _stride,const float * _mtx,const float * _light,ShadowVolumeImpl::Enum _impl=ShadowVolumeImpl::DepthPass,ShadowVolumeAlgorithm::Enum _algo=ShadowVolumeAlgorithm::FaceBased,bool _textureAsStencil=false)1237 void shadowVolumeCreate(
1238 	  ShadowVolume& _shadowVolume
1239 	, Group& _group
1240 	, uint16_t _stride
1241 	, const float* _mtx
1242 	, const float* _light // in model space
1243 	, ShadowVolumeImpl::Enum _impl = ShadowVolumeImpl::DepthPass
1244 	, ShadowVolumeAlgorithm::Enum _algo = ShadowVolumeAlgorithm::FaceBased
1245 	, bool _textureAsStencil = false
1246 	)
1247 {
1248 	const uint8_t*    vertices   = _group.m_vertices;
1249 	const FaceArray&  faces      = _group.m_faces;
1250 	const Edge*       edges      = _group.m_edges;
1251 	const Plane*      edgePlanes = _group.m_edgePlanes;
1252 	const uint32_t    numEdges   = _group.m_numEdges;
1253 	HalfEdges&        halfEdges  = _group.m_halfEdges;
1254 
1255 	struct VertexData
1256 	{
1257 		VertexData()
1258 		{
1259 		}
1260 
1261 		VertexData(const float* _v3, float _extrude = 0.0f, float _k = 1.0f)
1262 		{
1263 			bx::memCopy(m_v, _v3, 3*sizeof(float) );
1264 			m_extrude = _extrude;
1265 			m_k = _k;
1266 		}
1267 
1268 		float m_v[3];
1269 		float m_extrude;
1270 		float m_k;
1271 	};
1272 
1273 	bool cap = (ShadowVolumeImpl::DepthFail == _impl);
1274 
1275 	VertexData* verticesSide    = (VertexData*) s_svAllocator.alloc(20000 * sizeof(VertexData) );
1276 	uint16_t*   indicesSide     = (uint16_t*)   s_svAllocator.alloc(20000 * 3*sizeof(uint16_t) );
1277 	uint16_t*   indicesFrontCap = 0;
1278 	uint16_t*   indicesBackCap  = 0;
1279 
1280 	if (cap)
1281 	{
1282 		indicesFrontCap = (uint16_t*)s_svAllocator.alloc(80000 * 3*sizeof(uint16_t) );
1283 		indicesBackCap  = (uint16_t*)s_svAllocator.alloc(80000 * 3*sizeof(uint16_t) );
1284 	}
1285 
1286 	uint32_t vsideI    = 0;
1287 	uint32_t sideI     = 0;
1288 	uint32_t frontCapI = 0;
1289 	uint32_t backCapI  = 0;
1290 
1291 	uint16_t indexSide = 0;
1292 
1293 	if (ShadowVolumeAlgorithm::FaceBased == _algo)
1294 	{
1295 		for (FaceArray::const_iterator iter = faces.begin(), end = faces.end(); iter != end; ++iter)
1296 		{
1297 			const Face& face = *iter;
1298 
1299 			bool frontFacing = false;
1300 			const float f = bx::dot(bx::load<bx::Vec3>(face.m_plane), bx::load<bx::Vec3>(_light) ) + face.m_plane[3];
1301 			if (f > 0.0f)
1302 			{
1303 				frontFacing = true;
1304 				uint16_t triangleEdges[3][2] =
1305 				{
1306 					{ face.m_i[0], face.m_i[1] },
1307 					{ face.m_i[1], face.m_i[2] },
1308 					{ face.m_i[2], face.m_i[0] },
1309 				};
1310 
1311 				for (uint8_t ii = 0; ii < 3; ++ii)
1312 				{
1313 					uint16_t first  = triangleEdges[ii][0];
1314 					uint16_t second = triangleEdges[ii][1];
1315 
1316 					if (!halfEdges.unmark(second, first) )
1317 					{
1318 						halfEdges.mark(first, second);
1319 					}
1320 				}
1321 			}
1322 
1323 			if (cap)
1324 			{
1325 				if (frontFacing)
1326 				{
1327 					indicesFrontCap[frontCapI++] = face.m_i[0];
1328 					indicesFrontCap[frontCapI++] = face.m_i[1];
1329 					indicesFrontCap[frontCapI++] = face.m_i[2];
1330 				}
1331 				else
1332 				{
1333 					indicesBackCap[backCapI++] = face.m_i[0];
1334 					indicesBackCap[backCapI++] = face.m_i[1];
1335 					indicesBackCap[backCapI++] = face.m_i[2];
1336 				}
1337 
1338 				/**
1339 				 * if '_useFrontFacingFacesAsBackCap' is needed, implement it as such:
1340 				 *
1341 				 * bool condition0 = frontFacing && _useFrontFacingFacesAsBackCap;
1342 				 * bool condition1 = !frontFacing && !_useFrontFacingFacesAsBackCap;
1343 				 * if (condition0 || condition1)
1344 				 * {
1345 				 *      indicesBackCap[backCapI++] = face.m_i[0];
1346 				 *      indicesBackCap[backCapI++] = face.m_i[1+condition0];
1347 				 *      indicesBackCap[backCapI++] = face.m_i[2-condition0];
1348 				 * }
1349 				 */
1350 			}
1351 		}
1352 
1353 		// Fill side arrays.
1354 		uint16_t firstIndex = 0;
1355 		HalfEdge* he = halfEdges.begin();
1356 		while (halfEdges.end() != he)
1357 		{
1358 			if (he->m_marked)
1359 			{
1360 				he->m_marked = false;
1361 
1362 				const float* v0 = (float*)&vertices[firstIndex*_stride];
1363 				const float* v1 = (float*)&vertices[he->m_secondIndex*_stride];
1364 
1365 				verticesSide[vsideI++] = VertexData(v0, 0.0f);
1366 				verticesSide[vsideI++] = VertexData(v0, 1.0f);
1367 				verticesSide[vsideI++] = VertexData(v1, 0.0f);
1368 				verticesSide[vsideI++] = VertexData(v1, 1.0f);
1369 
1370 				indicesSide[sideI++] = indexSide+0;
1371 				indicesSide[sideI++] = indexSide+1;
1372 				indicesSide[sideI++] = indexSide+2;
1373 
1374 				indicesSide[sideI++] = indexSide+2;
1375 				indicesSide[sideI++] = indexSide+1;
1376 				indicesSide[sideI++] = indexSide+3;
1377 
1378 				indexSide += 4;
1379 			}
1380 
1381 			++he;
1382 			if (INVALID_EDGE_INDEX == he->m_secondIndex)
1383 			{
1384 				++he;
1385 				++firstIndex;
1386 			}
1387 		}
1388 	}
1389 	else // ShadowVolumeAlgorithm::EdgeBased:
1390 	{
1391 		{
1392 			uint32_t ii = 0;
1393 
1394 #if SV_USE_SIMD
1395 			uint32_t numEdgesRounded = numEdges & (~0x1);
1396 
1397 			using namespace bx;
1398 
1399 			const simd128_t lx = simd_splat(_light[0]);
1400 			const simd128_t ly = simd_splat(_light[1]);
1401 			const simd128_t lz = simd_splat(_light[2]);
1402 
1403 			for (; ii < numEdgesRounded; ii+=2)
1404 			{
1405 				const Edge& edge0 = edges[ii];
1406 				const Edge& edge1 = edges[ii+1];
1407 				const Plane* edgePlane0 = &edgePlanes[ii*2];
1408 				const Plane* edgePlane1 = &edgePlanes[ii*2 + 2];
1409 
1410 				const simd128_t reverse =
1411 					simd_ild(edge0.m_faceReverseOrder[0]
1412 							, edge1.m_faceReverseOrder[0]
1413 							, edge0.m_faceReverseOrder[1]
1414 							, edge1.m_faceReverseOrder[1]
1415 							);
1416 
1417 				const simd128_t p00 = simd_ld(edgePlane0[0].m_plane);
1418 				const simd128_t p10 = simd_ld(edgePlane1[0].m_plane);
1419 				const simd128_t p01 = simd_ld(edgePlane0[1].m_plane);
1420 				const simd128_t p11 = simd_ld(edgePlane1[1].m_plane);
1421 
1422 				const simd128_t xxyy0 = simd_shuf_xAyB(p00, p01);
1423 				const simd128_t zzww0 = simd_shuf_zCwD(p00, p01);
1424 				const simd128_t xxyy1 = simd_shuf_xAyB(p10, p11);
1425 				const simd128_t zzww1 = simd_shuf_zCwD(p10, p11);
1426 
1427 				const simd128_t vX = simd_shuf_xAyB(xxyy0, xxyy1);
1428 				const simd128_t vY = simd_shuf_zCwD(xxyy0, xxyy1);
1429 				const simd128_t vZ = simd_shuf_xAyB(zzww0, zzww1);
1430 				const simd128_t vW = simd_shuf_zCwD(zzww0, zzww1);
1431 
1432 				const simd128_t r0 = simd_mul(vX, lx);
1433 				const simd128_t r1 = simd_mul(vY, ly);
1434 				const simd128_t r2 = simd_mul(vZ, lz);
1435 
1436 				const simd128_t dot = simd_add(r0, simd_add(r1, r2) );
1437 				const simd128_t f = simd_add(dot, vW);
1438 
1439 				const simd128_t zero = simd_zero();
1440 				const simd128_t mask = simd_cmpgt(f, zero);
1441 				const simd128_t onef = simd_splat(1.0f);
1442 				const simd128_t tmp0 = simd_and(mask, onef);
1443 				const simd128_t tmp1 = simd_ftoi(tmp0);
1444 				const simd128_t tmp2 = simd_xor(tmp1, reverse);
1445 				const simd128_t tmp3 = simd_sll(tmp2, 1);
1446 				const simd128_t onei = simd_isplat(1);
1447 				const simd128_t tmp4 = simd_isub(tmp3, onei);
1448 
1449 				BX_ALIGN_DECL_16(int32_t res[4]);
1450 				simd_st(&res, tmp4);
1451 
1452 				for (uint16_t jj = 0; jj < 2; ++jj)
1453 				{
1454 					int32_t kk = res[jj] + res[jj+2];
1455 					if (kk != 0)
1456 					{
1457 						float* v0 = (float*)&vertices[edges[ii+jj].m_i0*_stride];
1458 						float* v1 = (float*)&vertices[edges[ii+jj].m_i1*_stride];
1459 						verticesSide[vsideI++] = VertexData(v0, 0.0f, float(kk) );
1460 						verticesSide[vsideI++] = VertexData(v0, 1.0f, float(kk) );
1461 						verticesSide[vsideI++] = VertexData(v1, 0.0f, float(kk) );
1462 						verticesSide[vsideI++] = VertexData(v1, 1.0f, float(kk) );
1463 
1464 						kk = _textureAsStencil ? 1 : kk;
1465 						uint16_t winding = uint16_t(kk > 0);
1466 						for (int32_t ll = 0, end = abs(kk); ll < end; ++ll)
1467 						{
1468 							indicesSide[sideI++] = indexSide;
1469 							indicesSide[sideI++] = indexSide + 2 - winding;
1470 							indicesSide[sideI++] = indexSide + 1 + winding;
1471 
1472 							indicesSide[sideI++] = indexSide + 2;
1473 							indicesSide[sideI++] = indexSide + 3 - winding*2;
1474 							indicesSide[sideI++] = indexSide + 1 + winding*2;
1475 						}
1476 
1477 						indexSide += 4;
1478 					}
1479 				}
1480 			}
1481 #endif
1482 
1483 			for (; ii < numEdges; ++ii)
1484 			{
1485 				const Edge& edge = edges[ii];
1486 				const Plane* edgePlane = &edgePlanes[ii*2];
1487 
1488 				int16_t s0 = ( (bx::dot(bx::load<bx::Vec3>(edgePlane[0].m_plane), bx::load<bx::Vec3>(_light) ) + edgePlane[0].m_plane[3]) > 0.0f) ^ edge.m_faceReverseOrder[0];
1489 				int16_t s1 = ( (bx::dot(bx::load<bx::Vec3>(edgePlane[1].m_plane), bx::load<bx::Vec3>(_light) ) + edgePlane[1].m_plane[3]) > 0.0f) ^ edge.m_faceReverseOrder[1];
1490 				int16_t kk = ( (s0 + s1) << 1) - 2;
1491 
1492 				if (kk != 0)
1493 				{
1494 					float* v0 = (float*)&vertices[edge.m_i0*_stride];
1495 					float* v1 = (float*)&vertices[edge.m_i1*_stride];
1496 					verticesSide[vsideI++] = VertexData(v0, 0.0f, kk);
1497 					verticesSide[vsideI++] = VertexData(v0, 1.0f, kk);
1498 					verticesSide[vsideI++] = VertexData(v1, 0.0f, kk);
1499 					verticesSide[vsideI++] = VertexData(v1, 1.0f, kk);
1500 
1501 					kk = _textureAsStencil ? 1 : kk;
1502 					uint16_t winding = uint16_t(kk > 0);
1503 					for (int32_t jj = 0, end = abs(kk); jj < end; ++jj)
1504 					{
1505 						indicesSide[sideI++] = indexSide;
1506 						indicesSide[sideI++] = indexSide + 2 - winding;
1507 						indicesSide[sideI++] = indexSide + 1 + winding;
1508 
1509 						indicesSide[sideI++] = indexSide + 2;
1510 						indicesSide[sideI++] = indexSide + 3 - winding*2;
1511 						indicesSide[sideI++] = indexSide + 1 + winding*2;
1512 					}
1513 
1514 					indexSide += 4;
1515 				}
1516 			}
1517 		}
1518 
1519 		if (cap)
1520 		{
1521 			// This could/should be done on GPU!
1522 			for (FaceArray::const_iterator iter = faces.begin(), end = faces.end(); iter != end; ++iter)
1523 			{
1524 				const Face& face = *iter;
1525 
1526 				const float f = bx::dot(bx::load<bx::Vec3>(face.m_plane), bx::load<bx::Vec3>(_light) ) + face.m_plane[3];
1527 				bool frontFacing = (f > 0.0f);
1528 
1529 				for (uint8_t ii = 0, num = 1 + uint8_t(!_textureAsStencil); ii < num; ++ii)
1530 				{
1531 					if (frontFacing)
1532 					{
1533 						indicesFrontCap[frontCapI++] = face.m_i[0];
1534 						indicesFrontCap[frontCapI++] = face.m_i[1];
1535 						indicesFrontCap[frontCapI++] = face.m_i[2];
1536 					}
1537 					else
1538 					{
1539 						indicesBackCap[backCapI++] = face.m_i[0];
1540 						indicesBackCap[backCapI++] = face.m_i[1];
1541 						indicesBackCap[backCapI++] = face.m_i[2];
1542 					}
1543 				}
1544 			}
1545 		}
1546 	}
1547 
1548 	bgfx::VertexLayout layout;
1549 	layout.begin()
1550 		.add(bgfx::Attrib::Position,  3, bgfx::AttribType::Float)
1551 		.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
1552 		.end();
1553 
1554 	//fill the structure
1555 	_shadowVolume.m_numVertices = vsideI;
1556 	_shadowVolume.m_numIndices  = sideI + frontCapI + backCapI;
1557 	_shadowVolume.m_mtx         = _mtx;
1558 	_shadowVolume.m_lightPos    = _light;
1559 	_shadowVolume.m_cap         = cap;
1560 
1561 	const bgfx::Memory* mem;
1562 
1563 	//sides
1564 	uint32_t vsize = vsideI * 5*sizeof(float);
1565 	uint32_t isize = sideI * sizeof(uint16_t);
1566 
1567 	mem = bgfx::makeRef(verticesSide, vsize);
1568 	_shadowVolume.m_vbSides = bgfx::createVertexBuffer(mem, layout);
1569 
1570 	mem = bgfx::makeRef(indicesSide, isize);
1571 	_shadowVolume.m_ibSides = bgfx::createIndexBuffer(mem);
1572 
1573 	// bgfx::destroy*Buffer doesn't actually destroy buffers now.
1574 	// Instead, these bgfx::destroy*Buffer commands get queued to be executed after the end of the next frame.
1575 	bgfx::destroy(_shadowVolume.m_vbSides);
1576 	bgfx::destroy(_shadowVolume.m_ibSides);
1577 
1578 	if (cap)
1579 	{
1580 		//front cap
1581 		isize = frontCapI * sizeof(uint16_t);
1582 		mem = bgfx::makeRef(indicesFrontCap, isize);
1583 		_shadowVolume.m_ibFrontCap = bgfx::createIndexBuffer(mem);
1584 
1585 		//gets destroyed after the end of the next frame
1586 		bgfx::destroy(_shadowVolume.m_ibFrontCap);
1587 
1588 		//back cap
1589 		isize = backCapI * sizeof(uint16_t);
1590 		mem = bgfx::makeRef(indicesBackCap, isize);
1591 		_shadowVolume.m_ibBackCap = bgfx::createIndexBuffer(mem);
1592 
1593 		//gets destroyed after the end of the next frame
1594 		bgfx::destroy(_shadowVolume.m_ibBackCap);
1595 	}
1596 }
1597 
createNearClipVolume(float * _outPlanes24f,float * _lightPos,float * _view,float _fovy,float _aspect,float _near)1598 void createNearClipVolume(
1599 	  float* _outPlanes24f
1600 	, float* _lightPos
1601 	, float* _view
1602 	, float _fovy
1603 	, float _aspect
1604 	, float _near
1605 	)
1606 {
1607 	float (*volumePlanes)[4] = (float(*)[4])_outPlanes24f;
1608 
1609 	float mtxViewInv[16];
1610 	float mtxViewTrans[16];
1611 	bx::mtxInverse(mtxViewInv, _view);
1612 	bx::mtxTranspose(mtxViewTrans, _view);
1613 
1614 	float lightPosV[4];
1615 	bx::vec4MulMtx(lightPosV, _lightPos, _view);
1616 
1617 	const float delta = 0.1f;
1618 
1619 	const float nearNormal[4] = { 0.0f, 0.0f, 1.0f, _near };
1620 	const float d = bx::dot(bx::load<bx::Vec3>(lightPosV), bx::load<bx::Vec3>(nearNormal) ) + lightPosV[3] * nearNormal[3];
1621 
1622 	// Light is:
1623 	//  1.0f - in front of near plane
1624 	//  0.0f - on the near plane
1625 	// -1.0f - behind near plane
1626 	const float lightSide = float( (d > delta) - (d < -delta) );
1627 
1628 	const float t = bx::tan(bx::toRad(_fovy)*0.5f) * _near;
1629 	const float b = -t;
1630 	const float r = t * _aspect;
1631 	const float l = -r;
1632 
1633 	const bx::Vec3 corners[4] =
1634 	{
1635 		bx::mul({ r, t, _near }, mtxViewInv),
1636 		bx::mul({ l, t, _near }, mtxViewInv),
1637 		bx::mul({ l, b, _near }, mtxViewInv),
1638 		bx::mul({ r, b, _near }, mtxViewInv),
1639 	};
1640 
1641 	float planeNormals[4][3];
1642 	for (uint8_t ii = 0; ii < 4; ++ii)
1643 	{
1644 		float* outNormal = planeNormals[ii];
1645 		float* outPlane  = volumePlanes[ii];
1646 
1647 		const bx::Vec3 c0       = corners[ii];
1648 		const bx::Vec3 planeVec = bx::sub(c0, corners[(ii-1)&3]);
1649 		const bx::Vec3 light    = bx::sub(bx::load<bx::Vec3>(_lightPos), bx::mul(c0, _lightPos[3]) );
1650 		const bx::Vec3 normal   = bx::mul(bx::cross(planeVec, light), lightSide);
1651 
1652 		const float invLen = 1.0f / bx::sqrt(bx::dot(normal, normal) );
1653 
1654 		bx::store(outNormal, normal);
1655 		bx::store(outPlane, bx::mul(normal, invLen) );
1656 		outPlane[3] = -bx::dot(normal, c0) * invLen;
1657 	}
1658 
1659 	float nearPlaneV[4] =
1660 	{
1661 		0.0f * lightSide,
1662 		0.0f * lightSide,
1663 		1.0f * lightSide,
1664 		_near * lightSide,
1665 	};
1666 	bx::vec4MulMtx(volumePlanes[4], nearPlaneV, mtxViewTrans);
1667 
1668 	float* lightPlane = volumePlanes[5];
1669 	const bx::Vec3 lightPlaneNormal = bx::sub(bx::mul({ 0.0f, 0.0f, -_near * lightSide }, mtxViewInv), bx::load<bx::Vec3>(_lightPos) );
1670 
1671 	float lenInv = 1.0f / bx::sqrt(bx::dot(lightPlaneNormal, lightPlaneNormal) );
1672 
1673 	lightPlane[0] = lightPlaneNormal.x * lenInv;
1674 	lightPlane[1] = lightPlaneNormal.y * lenInv;
1675 	lightPlane[2] = lightPlaneNormal.z * lenInv;
1676 	lightPlane[3] = -bx::dot(lightPlaneNormal, bx::load<bx::Vec3>(_lightPos) ) * lenInv;
1677 }
1678 
clipTest(const float * _planes,uint8_t _planeNum,const Mesh & _mesh,const float * _scale,const float * _translate)1679 bool clipTest(const float* _planes, uint8_t _planeNum, const Mesh& _mesh, const float* _scale, const float* _translate)
1680 {
1681 	float (*volumePlanes)[4] = (float(*)[4])_planes;
1682 	float scale = bx::max(_scale[0], _scale[1], _scale[2]);
1683 
1684 	const GroupArray& groups = _mesh.m_groups;
1685 	for (GroupArray::const_iterator it = groups.begin(), itEnd = groups.end(); it != itEnd; ++it)
1686 	{
1687 		const Group& group = *it;
1688 
1689 		Sphere sphere = group.m_sphere;
1690 		sphere.center.x = sphere.center.x * scale + _translate[0];
1691 		sphere.center.y = sphere.center.y * scale + _translate[1];
1692 		sphere.center.z = sphere.center.z * scale + _translate[2];
1693 		sphere.radius *= (scale+0.4f);
1694 
1695 		bool isInside = true;
1696 		for (uint8_t ii = 0; ii < _planeNum; ++ii)
1697 		{
1698 			const float* plane = volumePlanes[ii];
1699 
1700 			float positiveSide = bx::dot(bx::load<bx::Vec3>(plane), sphere.center ) + plane[3] + sphere.radius;
1701 
1702 			if (positiveSide < 0.0f)
1703 			{
1704 				isInside = false;
1705 				break;
1706 			}
1707 		}
1708 
1709 		if (isInside)
1710 		{
1711 			return true;
1712 		}
1713 	}
1714 
1715 	return false;
1716 }
1717 
1718 struct ShadowVolumeProgramType
1719 {
1720 	enum Enum
1721 	{
1722 		Blank = 0,
1723 		Color,
1724 		Tex1,
1725 		Tex2,
1726 
1727 		Count
1728 	};
1729 };
1730 
1731 struct ShadowVolumePart
1732 {
1733 	enum Enum
1734 	{
1735 		Back = 0,
1736 		Side,
1737 		Front,
1738 
1739 		Count
1740 	};
1741 };
1742 
1743 enum LightPattern
1744 {
1745 	LightPattern0 = 0,
1746 	LightPattern1
1747 };
1748 
1749 enum MeshChoice
1750 {
1751 	BunnyHighPoly = 0,
1752 	BunnyLowPoly
1753 };
1754 
1755 enum Scene
1756 {
1757 	Scene0 = 0,
1758 	Scene1,
1759 
1760 	SceneCount
1761 };
1762 
1763 class ExampleShadowVolumes : public entry::AppI
1764 {
1765 public:
ExampleShadowVolumes(const char * _name,const char * _description,const char * _url)1766 	ExampleShadowVolumes(const char* _name, const char* _description, const char* _url)
1767 		: entry::AppI(_name, _description, _url)
1768 	{
1769 	}
1770 
init(int32_t _argc,const char * const * _argv,uint32_t _width,uint32_t _height)1771 	void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
1772 	{
1773 		Args args(_argc, _argv);
1774 
1775 		m_viewState   = ViewState(_width, _height);
1776 		m_clearValues = { 0x00000000, 1.0f, 0 };
1777 
1778 		m_debug = BGFX_DEBUG_TEXT;
1779 		m_reset = BGFX_RESET_VSYNC;
1780 
1781 		bgfx::Init init;
1782 		init.type     = args.m_type;
1783 		init.vendorId = args.m_pciId;
1784 		init.resolution.width  = m_viewState.m_width;
1785 		init.resolution.height = m_viewState.m_height;
1786 		init.resolution.reset  = m_reset;
1787 		bgfx::init(init);
1788 
1789 		// Enable debug text.
1790 		bgfx::setDebug(m_debug);
1791 
1792 		const bgfx::Caps* caps = bgfx::getCaps();
1793 		s_oglNdc    = caps->homogeneousDepth;
1794 		s_texelHalf = bgfx::RendererType::Direct3D9 == caps->rendererType ? 0.5f : 0.0f;
1795 
1796 		// Imgui
1797 		imguiCreate();
1798 
1799 		PosNormalTexcoordVertex::init();
1800 
1801 		s_uniforms.init();
1802 
1803 		m_figureTex     = loadTexture("textures/figure-rgba.dds");
1804 		m_flareTex      = loadTexture("textures/flare.dds");
1805 		m_fieldstoneTex = loadTexture("textures/fieldstone-rgba.dds");
1806 
1807 		bgfx::TextureHandle fbtextures[] =
1808 		{
1809 			bgfx::createTexture2D(uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_SAMPLER_U_CLAMP | BGFX_SAMPLER_V_CLAMP | BGFX_TEXTURE_RT),
1810 			bgfx::createTexture2D(uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height), false, 1, bgfx::TextureFormat::D16,   BGFX_TEXTURE_RT_WRITE_ONLY),
1811 		};
1812 
1813 		s_stencilFb  = bgfx::createFrameBuffer(BX_COUNTOF(fbtextures), fbtextures, true);
1814 
1815 		s_texColor   = bgfx::createUniform("s_texColor",   bgfx::UniformType::Sampler);
1816 		s_texStencil = bgfx::createUniform("s_texStencil", bgfx::UniformType::Sampler);
1817 
1818 		m_programTextureLighting = loadProgram("vs_shadowvolume_texture_lighting", "fs_shadowvolume_texture_lighting");
1819 		m_programColorLighting   = loadProgram("vs_shadowvolume_color_lighting",   "fs_shadowvolume_color_lighting"  );
1820 		m_programColorTexture    = loadProgram("vs_shadowvolume_color_texture",    "fs_shadowvolume_color_texture"   );
1821 		m_programTexture         = loadProgram("vs_shadowvolume_texture",          "fs_shadowvolume_texture"         );
1822 
1823 		m_programBackBlank       = loadProgram("vs_shadowvolume_svback",  "fs_shadowvolume_svbackblank" );
1824 		m_programSideBlank       = loadProgram("vs_shadowvolume_svside",  "fs_shadowvolume_svsideblank" );
1825 		m_programFrontBlank      = loadProgram("vs_shadowvolume_svfront", "fs_shadowvolume_svfrontblank");
1826 
1827 		m_programBackColor       = loadProgram("vs_shadowvolume_svback",  "fs_shadowvolume_svbackcolor" );
1828 		m_programSideColor       = loadProgram("vs_shadowvolume_svside",  "fs_shadowvolume_svsidecolor" );
1829 		m_programFrontColor      = loadProgram("vs_shadowvolume_svfront", "fs_shadowvolume_svfrontcolor");
1830 
1831 		m_programSideTex         = loadProgram("vs_shadowvolume_svside",  "fs_shadowvolume_svsidetex"   );
1832 		m_programBackTex1        = loadProgram("vs_shadowvolume_svback",  "fs_shadowvolume_svbacktex1"  );
1833 		m_programBackTex2        = loadProgram("vs_shadowvolume_svback",  "fs_shadowvolume_svbacktex2"  );
1834 		m_programFrontTex1       = loadProgram("vs_shadowvolume_svfront", "fs_shadowvolume_svfronttex1" );
1835 		m_programFrontTex2       = loadProgram("vs_shadowvolume_svfront", "fs_shadowvolume_svfronttex2" );
1836 
1837 		bgfx::ProgramHandle svProgs[ShadowVolumeProgramType::Count][ShadowVolumePart::Count] =
1838 		{
1839 			{ m_programBackBlank, m_programSideBlank, m_programFrontBlank }, // Blank
1840 			{ m_programBackColor, m_programSideColor, m_programFrontColor }, // Color
1841 			{ m_programBackTex1,  m_programSideTex,   m_programFrontTex1  }, // Tex1
1842 			{ m_programBackTex2,  m_programSideTex,   m_programFrontTex2  }, // Tex2
1843 		};
1844 		bx::memCopy(m_svProgs, svProgs, sizeof(svProgs));
1845 
1846 		m_bunnyHighPolyModel.load("meshes/bunny_patched.bin");
1847 		m_bunnyHighPolyModel.m_program = m_programColorLighting;
1848 
1849 		m_bunnyLowPolyModel.load("meshes/bunny_decimated.bin");
1850 		m_bunnyLowPolyModel.m_program = m_programColorLighting;
1851 
1852 		m_columnModel.load("meshes/column.bin");
1853 		m_columnModel.m_program = m_programColorLighting;
1854 
1855 		m_platformModel.load("meshes/platform.bin");
1856 		m_platformModel.m_program = m_programTextureLighting;
1857 		m_platformModel.m_texture = m_figureTex;
1858 
1859 		m_cubeModel.load("meshes/cube.bin");
1860 		m_cubeModel.m_program = m_programTextureLighting;
1861 		m_cubeModel.m_texture = m_figureTex;
1862 
1863 		m_hplaneFieldModel.load(s_hplaneVertices
1864 			, BX_COUNTOF(s_hplaneVertices)
1865 			, PosNormalTexcoordVertex::ms_layout
1866 			, s_planeIndices
1867 			, BX_COUNTOF(s_planeIndices)
1868 			);
1869 		m_hplaneFieldModel.m_program = m_programTextureLighting;
1870 		m_hplaneFieldModel.m_texture = m_fieldstoneTex;
1871 
1872 		m_hplaneFigureModel.load(s_hplaneVertices
1873 			, BX_COUNTOF(s_hplaneVertices)
1874 			, PosNormalTexcoordVertex::ms_layout
1875 			, s_planeIndices
1876 			, BX_COUNTOF(s_planeIndices)
1877 			);
1878 		m_hplaneFigureModel.m_program = m_programTextureLighting;
1879 		m_hplaneFigureModel.m_texture = m_figureTex;
1880 
1881 		m_vplaneModel.load(s_vplaneVertices
1882 			, BX_COUNTOF(s_vplaneVertices)
1883 			, PosNormalTexcoordVertex::ms_layout
1884 			, s_planeIndices
1885 			, BX_COUNTOF(s_planeIndices)
1886 			);
1887 		m_vplaneModel.m_program = m_programColorTexture;
1888 		m_vplaneModel.m_texture = m_flareTex;
1889 
1890 		// Setup lights.
1891 		const float rgbInnerR[MAX_LIGHTS_COUNT][4] =
1892 		{
1893 			{ 1.0f, 0.7f, 0.2f, 0.0f }, //yellow
1894 			{ 0.7f, 0.2f, 1.0f, 0.0f }, //purple
1895 			{ 0.2f, 1.0f, 0.7f, 0.0f }, //cyan
1896 			{ 1.0f, 0.4f, 0.2f, 0.0f }, //orange
1897 			{ 0.7f, 0.7f, 0.7f, 0.0f }, //white
1898 		};
1899 
1900 		for (uint8_t ii = 0, jj = 0; ii < MAX_LIGHTS_COUNT; ++ii, ++jj)
1901 		{
1902 			const uint8_t index = jj%MAX_LIGHTS_COUNT;
1903 			m_lightRgbInnerR[ii][0] = rgbInnerR[index][0];
1904 			m_lightRgbInnerR[ii][1] = rgbInnerR[index][1];
1905 			m_lightRgbInnerR[ii][2] = rgbInnerR[index][2];
1906 			m_lightRgbInnerR[ii][3] = rgbInnerR[index][3];
1907 		}
1908 
1909 		m_profTime = 0;
1910 		m_timeOffset = bx::getHPCounter();
1911 
1912 		m_numShadowVolumeVertices = 0;
1913 		m_numShadowVolumeIndices  = 0;
1914 
1915 		m_oldWidth = 0;
1916 		m_oldHeight = 0;
1917 
1918 		// Imgui.
1919 		m_showHelp          = false;
1920 		m_updateLights      = true;
1921 		m_updateScene       = true;
1922 		m_mixedSvImpl       = true;
1923 		m_useStencilTexture = false;
1924 		m_drawShadowVolumes = false;
1925 		m_numLights         = 1;
1926 		m_instanceCount     = 9;
1927 		m_shadowVolumeImpl      = ShadowVolumeImpl::DepthFail;
1928 		m_shadowVolumeAlgorithm = ShadowVolumeAlgorithm::EdgeBased;
1929 
1930 		m_lightPattern = LightPattern0;
1931 		m_currentMesh  = BunnyLowPoly;
1932 		m_currentScene = Scene0;
1933 
1934 		// Set view matrix
1935 		cameraCreate();
1936 		cameraSetPosition({ 3.0f, 20.0f, -58.0f });
1937 		cameraSetVerticalAngle(-0.25f);
1938 		cameraGetViewMtx(m_viewState.m_view);
1939 	}
1940 
shutdown()1941 	virtual int shutdown() override
1942 	{
1943 		// Cleanup
1944 		m_bunnyLowPolyModel.unload();
1945 		m_bunnyHighPolyModel.unload();
1946 		m_columnModel.unload();
1947 		m_cubeModel.unload();
1948 		m_platformModel.unload();
1949 		m_hplaneFieldModel.unload();
1950 		m_hplaneFigureModel.unload();
1951 		m_vplaneModel.unload();
1952 
1953 		s_uniforms.destroy();
1954 
1955 		bgfx::destroy(s_texColor);
1956 		bgfx::destroy(s_texStencil);
1957 		bgfx::destroy(s_stencilFb);
1958 
1959 		bgfx::destroy(m_figureTex);
1960 		bgfx::destroy(m_fieldstoneTex);
1961 		bgfx::destroy(m_flareTex);
1962 
1963 		bgfx::destroy(m_programTextureLighting);
1964 		bgfx::destroy(m_programColorLighting);
1965 		bgfx::destroy(m_programColorTexture);
1966 		bgfx::destroy(m_programTexture);
1967 
1968 		bgfx::destroy(m_programBackBlank);
1969 		bgfx::destroy(m_programSideBlank);
1970 		bgfx::destroy(m_programFrontBlank);
1971 		bgfx::destroy(m_programBackColor);
1972 		bgfx::destroy(m_programSideColor);
1973 		bgfx::destroy(m_programFrontColor);
1974 		bgfx::destroy(m_programSideTex);
1975 		bgfx::destroy(m_programBackTex1);
1976 		bgfx::destroy(m_programBackTex2);
1977 		bgfx::destroy(m_programFrontTex1);
1978 		bgfx::destroy(m_programFrontTex2);
1979 
1980 		cameraDestroy();
1981 		imguiDestroy();
1982 
1983 		// Shutdown bgfx.
1984 		bgfx::shutdown();
1985 
1986 		return 0;
1987 	}
1988 
update()1989 	bool update() override
1990 	{
1991 		if (!entry::processEvents(m_viewState.m_width, m_viewState.m_height, m_debug, m_reset, &m_mouseState) )
1992 		{
1993 			s_uniforms.submitConstUniforms();
1994 
1995 			// Set projection matrices.
1996 			const float fov = 60.0f;
1997 			const float aspect = float(m_viewState.m_width)/float(m_viewState.m_height);
1998 			const float nearPlane = 1.0f;
1999 			const float farPlane = 1000.0f;
2000 
2001 			// Respond properly on resize.
2002 			if (m_oldWidth  != m_viewState.m_width
2003 			||  m_oldHeight != m_viewState.m_height)
2004 			{
2005 				m_oldWidth  = m_viewState.m_width;
2006 				m_oldHeight = m_viewState.m_height;
2007 
2008 				bgfx::destroy(s_stencilFb);
2009 
2010 				bgfx::TextureHandle fbtextures[] =
2011 				{
2012 					bgfx::createTexture2D(uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_SAMPLER_U_CLAMP|BGFX_SAMPLER_V_CLAMP|BGFX_TEXTURE_RT),
2013 					bgfx::createTexture2D(uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height), false, 1, bgfx::TextureFormat::D16, BGFX_TEXTURE_RT_WRITE_ONLY)
2014 				};
2015 				s_stencilFb = bgfx::createFrameBuffer(BX_COUNTOF(fbtextures), fbtextures, true);
2016 			}
2017 
2018 			// Time.
2019 			int64_t now = bx::getHPCounter();
2020 			static int64_t last = now;
2021 			const int64_t frameTime = now - last;
2022 			last = now;
2023 			const double freq = double(bx::getHPFrequency() );
2024 			const double toMs = 1000.0/freq;
2025 			float time = (float)( (now - m_timeOffset)/double(bx::getHPFrequency() ) );
2026 			const float deltaTime = float(frameTime/freq);
2027 			s_uniforms.m_time = time;
2028 
2029 			// Update camera.
2030 			cameraUpdate(deltaTime, m_mouseState);
2031 
2032 			// Set view and projection matrix for view 0.
2033 			{
2034 				cameraGetViewMtx(m_viewState.m_view);
2035 				bx::mtxProj(m_viewState.m_proj, fov, aspect, nearPlane, farPlane, s_oglNdc);
2036 			}
2037 
2038 			imguiBeginFrame(
2039 				   m_mouseState.m_mx
2040 				,  m_mouseState.m_my
2041 				, (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
2042 				| (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
2043 				| (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
2044 				,  m_mouseState.m_mz
2045 				, uint16_t(m_viewState.m_width)
2046 				, uint16_t(m_viewState.m_height)
2047 				);
2048 
2049 			showExampleDialog(this);
2050 
2051 			ImGui::SetNextWindowPos(
2052 				  ImVec2(m_viewState.m_width - 256.0f, 10.0f)
2053 				, ImGuiCond_FirstUseEver
2054 				);
2055 			ImGui::SetNextWindowSize(
2056 				  ImVec2(256.0f, 700.0f)
2057 				, ImGuiCond_FirstUseEver
2058 				);
2059 			ImGui::Begin("Settings"
2060 				, NULL
2061 				, 0
2062 				);
2063 
2064 			const char* titles[2] =
2065 			{
2066 				"Scene 0",
2067 				"Scene 1",
2068 			};
2069 
2070 			if (ImGui::RadioButton(titles[Scene0], Scene0 == m_currentScene) )
2071 			{
2072 				m_currentScene = Scene0;
2073 			}
2074 
2075 			if (ImGui::RadioButton(titles[Scene1], Scene1 == m_currentScene) )
2076 			{
2077 				m_currentScene = Scene1;
2078 			}
2079 
2080 			ImGui::SliderInt("Lights", &m_numLights, 1, MAX_LIGHTS_COUNT);
2081 			ImGui::Checkbox("Update lights", &m_updateLights);
2082 			ImGui::Indent();
2083 
2084 			if (ImGui::RadioButton("Light pattern 0", LightPattern0 == m_lightPattern) )
2085 			{
2086 				m_lightPattern = LightPattern0;
2087 			}
2088 
2089 			if (ImGui::RadioButton("Light pattern 1", LightPattern1 == m_lightPattern) )
2090 			{
2091 				m_lightPattern = LightPattern1;
2092 			}
2093 
2094 			ImGui::Unindent();
2095 
2096 			if ( Scene0 == m_currentScene )
2097 			{
2098 				ImGui::Checkbox("Update scene", &m_updateScene);
2099 			}
2100 
2101 			ImGui::Separator();
2102 
2103 			ImGui::Text("Stencil buffer implementation:");
2104 			ImGui::Checkbox("Mixed", &m_mixedSvImpl);
2105 			if (!m_mixedSvImpl)
2106 			{
2107 				m_shadowVolumeImpl = (ImGui::RadioButton("Depth fail", ShadowVolumeImpl::DepthFail == m_shadowVolumeImpl) ? ShadowVolumeImpl::DepthFail : m_shadowVolumeImpl);
2108 				m_shadowVolumeImpl = (ImGui::RadioButton("Depth pass", ShadowVolumeImpl::DepthPass == m_shadowVolumeImpl) ? ShadowVolumeImpl::DepthPass : m_shadowVolumeImpl);
2109 			}
2110 
2111 			ImGui::Text("Shadow volume implementation:");
2112 			m_shadowVolumeAlgorithm = (ImGui::RadioButton("Face based impl.", ShadowVolumeAlgorithm::FaceBased == m_shadowVolumeAlgorithm) ? ShadowVolumeAlgorithm::FaceBased : m_shadowVolumeAlgorithm);
2113 			m_shadowVolumeAlgorithm = (ImGui::RadioButton("Edge based impl.", ShadowVolumeAlgorithm::EdgeBased == m_shadowVolumeAlgorithm) ? ShadowVolumeAlgorithm::EdgeBased : m_shadowVolumeAlgorithm);
2114 
2115 			ImGui::Text("Stencil:");
2116 			if (ImGui::RadioButton("Use stencil buffer", !m_useStencilTexture) )
2117 			{
2118 				if (m_useStencilTexture)
2119 				{
2120 					m_useStencilTexture = false;
2121 				}
2122 			}
2123 			if (ImGui::RadioButton("Use texture as stencil", m_useStencilTexture) )
2124 			{
2125 				if (!m_useStencilTexture)
2126 				{
2127 					m_useStencilTexture = true;
2128 				}
2129 			}
2130 
2131 			ImGui::Separator();
2132 			ImGui::Text("Mesh:");
2133 			if (ImGui::RadioButton("Bunny - high poly", BunnyHighPoly == m_currentMesh) )
2134 			{
2135 				m_currentMesh = BunnyHighPoly;
2136 			}
2137 
2138 			if (ImGui::RadioButton("Bunny - low poly",  BunnyLowPoly  == m_currentMesh) )
2139 			{
2140 				m_currentMesh = BunnyLowPoly;
2141 			}
2142 
2143 			if (Scene1 == m_currentScene)
2144 			{
2145 				ImGui::SliderInt("Instance count", &m_instanceCount, 1, MAX_INSTANCE_COUNT);
2146 			}
2147 
2148 			ImGui::Text("CPU Time: %7.1f [ms]", double(m_profTime)*toMs);
2149 			ImGui::Text("Volume Vertices: %5.uk", m_numShadowVolumeVertices/1000);
2150 			ImGui::Text("Volume Indices: %6.uk", m_numShadowVolumeIndices/1000);
2151 			m_numShadowVolumeVertices = 0;
2152 			m_numShadowVolumeIndices = 0;
2153 
2154 			ImGui::Separator();
2155 			ImGui::Checkbox("Draw Shadow Volumes", &m_drawShadowVolumes);
2156 
2157 			ImGui::End();
2158 
2159 			ImGui::SetNextWindowPos(
2160 				  ImVec2(10, float(m_viewState.m_height) - 77.0f - 10.0f)
2161 				, ImGuiCond_FirstUseEver
2162 				);
2163 			ImGui::SetNextWindowSize(
2164 				  ImVec2(120.0f, 77.0f)
2165 				, ImGuiCond_FirstUseEver
2166 				);
2167 			ImGui::Begin("Show help:"
2168 				, NULL
2169 				, 0
2170 				);
2171 
2172 			if (ImGui::Button(m_showHelp ? "ON" : "OFF") )
2173 			{
2174 				m_showHelp = !m_showHelp;
2175 			}
2176 
2177 			ImGui::End();
2178 
2179 			imguiEndFrame();
2180 
2181 			//update settings
2182 			s_uniforms.m_params.m_ambientPass     = 1.0f;
2183 			s_uniforms.m_params.m_lightingPass    = 1.0f;
2184 			s_uniforms.m_params.m_texelHalf       = s_texelHalf;
2185 			s_uniforms.m_svparams.m_useStencilTex = float(m_useStencilTexture);
2186 
2187 			//set picked bunny model
2188 			Model* bunnyModel = BunnyLowPoly == m_currentMesh ? &m_bunnyLowPolyModel : &m_bunnyHighPolyModel;
2189 
2190 			//update time accumulators
2191 			static float sceneTimeAccumulator = 0.0f;
2192 			if (m_updateScene)
2193 			{
2194 				sceneTimeAccumulator += deltaTime;
2195 			}
2196 
2197 			static float lightTimeAccumulator = 0.0f;
2198 			if (m_updateLights)
2199 			{
2200 				lightTimeAccumulator += deltaTime;
2201 			}
2202 
2203 			//setup light positions
2204 			float lightPosRadius[MAX_LIGHTS_COUNT][4];
2205 			if (LightPattern0 == m_lightPattern)
2206 			{
2207 				for (uint8_t ii = 0; ii < m_numLights; ++ii)
2208 				{
2209 					lightPosRadius[ii][0] = bx::cos(2.0f*bx::kPi/float(m_numLights) * float(ii) + lightTimeAccumulator * 1.1f + 3.0f) * 20.0f;
2210 					lightPosRadius[ii][1] = 20.0f;
2211 					lightPosRadius[ii][2] = bx::sin(2.0f*bx::kPi/float(m_numLights) * float(ii) + lightTimeAccumulator * 1.1f + 3.0f) * 20.0f;
2212 					lightPosRadius[ii][3] = 20.0f;
2213 				}
2214 			}
2215 			else
2216 			{
2217 				for (uint8_t ii = 0; ii < m_numLights; ++ii)
2218 				{
2219 					lightPosRadius[ii][0] = bx::cos(float(ii) * 2.0f/float(m_numLights) + lightTimeAccumulator * 1.3f + bx::kPi) * 40.0f;
2220 					lightPosRadius[ii][1] = 20.0f;
2221 					lightPosRadius[ii][2] = bx::sin(float(ii) * 2.0f/float(m_numLights) + lightTimeAccumulator * 1.3f + bx::kPi) * 40.0f;
2222 					lightPosRadius[ii][3] = 20.0f;
2223 				}
2224 			}
2225 
2226 			if (m_showHelp)
2227 			{
2228 				uint8_t row = 18;
2229 				bgfx::dbgTextPrintf(3, row++, 0x0f, "Stencil buffer implementation:");
2230 				bgfx::dbgTextPrintf(8, row++, 0x0f, "Depth fail - Robust, but slower than 'Depth pass'. Requires computing and drawing of shadow volume caps.");
2231 				bgfx::dbgTextPrintf(8, row++, 0x0f, "Depth pass - Faster, but not stable. Shadows are wrong when camera is in the shadow.");
2232 				bgfx::dbgTextPrintf(8, row++, 0x0f, "Mixed      - 'Depth pass' where possible, 'Depth fail' where necessary. Best of both words.");
2233 
2234 				row++;
2235 				bgfx::dbgTextPrintf(3, row++, 0x0f, "Shadow volume implementation:");
2236 				bgfx::dbgTextPrintf(8, row++, 0x0f, "Face Based - Slower. Works fine with either stencil buffer or texture as stencil.");
2237 				bgfx::dbgTextPrintf(8, row++, 0x0f, "Edge Based - Faster, but requires +2 incr/decr on stencil buffer. To avoid massive redraw, use RGBA texture as stencil.");
2238 
2239 				row++;
2240 				bgfx::dbgTextPrintf(3, row++, 0x0f, "Stencil:");
2241 				bgfx::dbgTextPrintf(8, row++, 0x0f, "Stencil buffer     - Faster, but capable only of +1 incr.");
2242 				bgfx::dbgTextPrintf(8, row++, 0x0f, "Texture as stencil - Slower, but capable of +2 incr.");
2243 			}
2244 			else
2245 			{
2246 				bgfx::dbgTextClear();
2247 			}
2248 
2249 			// Setup instances
2250 			Instance shadowCasters[SceneCount][60];
2251 			uint16_t shadowCastersCount[SceneCount];
2252 			for (uint8_t ii = 0; ii < SceneCount; ++ii)
2253 			{
2254 				shadowCastersCount[ii] = 0;
2255 			}
2256 
2257 			Instance shadowReceivers[SceneCount][10];
2258 			uint16_t shadowReceiversCount[SceneCount];
2259 			for (uint8_t ii = 0; ii < SceneCount; ++ii)
2260 			{
2261 				shadowReceiversCount[ii] = 0;
2262 			}
2263 
2264 			// Scene 0 - shadow casters - Bunny
2265 			{
2266 				Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
2267 				inst.m_scale[0]    = 5.0f;
2268 				inst.m_scale[1]    = 5.0f;
2269 				inst.m_scale[2]    = 5.0f;
2270 				inst.m_rotation[0] = 0.0f;
2271 				inst.m_rotation[1] = float(4.0f - sceneTimeAccumulator * 0.7f);
2272 				inst.m_rotation[2] = 0.0f;
2273 				inst.m_pos[0]      = 0.0f;
2274 				inst.m_pos[1]      = 10.0f;
2275 				inst.m_pos[2]      = 0.0f;
2276 				inst.m_color[0]    = 0.68f;
2277 				inst.m_color[1]    = 0.65f;
2278 				inst.m_color[2]    = 0.60f;
2279 				inst.m_model       = bunnyModel;
2280 			}
2281 
2282 			// Scene 0 - shadow casters - Cubes top.
2283 			const uint8_t numCubesTop = 9;
2284 			for (uint16_t ii = 0; ii < numCubesTop; ++ii)
2285 			{
2286 				Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
2287 				inst.m_scale[0]    = 1.0f;
2288 				inst.m_scale[1]    = 1.0f;
2289 				inst.m_scale[2]    = 1.0f;
2290 				inst.m_rotation[0] = 0.0f;
2291 				inst.m_rotation[1] = 0.0f;
2292 				inst.m_rotation[2] = 0.0f;
2293 				inst.m_pos[0]      = bx::sin(ii * 2.0f + 13.0f + sceneTimeAccumulator * 1.1f) * 13.0f;
2294 				inst.m_pos[1]      = 6.0f;
2295 				inst.m_pos[2]      = bx::cos(ii * 2.0f + 13.0f + sceneTimeAccumulator * 1.1f) * 13.0f;
2296 				inst.m_model       = &m_cubeModel;
2297 			}
2298 
2299 			// Scene 0 - shadow casters - Cubes bottom.
2300 			const uint8_t numCubesBottom = 9;
2301 			for (uint16_t ii = 0; ii < numCubesBottom; ++ii)
2302 			{
2303 				Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
2304 				inst.m_scale[0]    = 1.0f;
2305 				inst.m_scale[1]    = 1.0f;
2306 				inst.m_scale[2]    = 1.0f;
2307 				inst.m_rotation[0] = 0.0f;
2308 				inst.m_rotation[1] = 0.0f;
2309 				inst.m_rotation[2] = 0.0f;
2310 				inst.m_pos[0]      = bx::sin(ii * 2.0f + 13.0f + sceneTimeAccumulator * 1.1f) * 13.0f;
2311 				inst.m_pos[1]      = 22.0f;
2312 				inst.m_pos[2]      = bx::cos(ii * 2.0f + 13.0f + sceneTimeAccumulator * 1.1f) * 13.0f;
2313 				inst.m_model       = &m_cubeModel;
2314 			}
2315 
2316 			// Scene 0 - shadow casters - Columns.
2317 			const float dist = 16.0f;
2318 			const float columnPositions[][3] =
2319 			{
2320 				{  dist, 3.3f,  dist },
2321 				{ -dist, 3.3f,  dist },
2322 				{  dist, 3.3f, -dist },
2323 				{ -dist, 3.3f, -dist },
2324 			};
2325 
2326 			for (uint8_t ii = 0; ii < 4; ++ii)
2327 			{
2328 				Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
2329 				inst.m_scale[0]    = 1.5f;
2330 				inst.m_scale[1]    = 1.5f;
2331 				inst.m_scale[2]    = 1.5f;
2332 				inst.m_rotation[0] = 0.0f;
2333 				inst.m_rotation[1] = 1.57f;
2334 				inst.m_rotation[2] = 0.0f;
2335 				inst.m_pos[0]      = columnPositions[ii][0];
2336 				inst.m_pos[1]      = columnPositions[ii][1];
2337 				inst.m_pos[2]      = columnPositions[ii][2];
2338 				inst.m_color[0]    = 0.25f;
2339 				inst.m_color[1]    = 0.25f;
2340 				inst.m_color[2]    = 0.25f;
2341 				inst.m_model       = &m_columnModel;
2342 			}
2343 
2344 			// Scene 0 - shadow casters - Ceiling.
2345 			{
2346 				Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
2347 				inst.m_scale[0]    = 21.0f;
2348 				inst.m_scale[1]    = 21.0f;
2349 				inst.m_scale[2]    = 21.0f;
2350 				inst.m_rotation[0] = bx::kPi;
2351 				inst.m_rotation[1] = 0.0f;
2352 				inst.m_rotation[2] = 0.0f;
2353 				inst.m_pos[0]      = 0.0f;
2354 				inst.m_pos[1]      = 28.2f;
2355 				inst.m_pos[2]      = 0.0f;
2356 				inst.m_model       = &m_platformModel;
2357 				inst.m_svExtrusionDistance = 2.0f; //prevent culling on tight view frustum
2358 			}
2359 
2360 			// Scene 0 - shadow casters - Platform.
2361 			{
2362 				Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
2363 				inst.m_scale[0]    = 24.0f;
2364 				inst.m_scale[1]    = 24.0f;
2365 				inst.m_scale[2]    = 24.0f;
2366 				inst.m_rotation[0] = 0.0f;
2367 				inst.m_rotation[1] = 0.0f;
2368 				inst.m_rotation[2] = 0.0f;
2369 				inst.m_pos[0]      = 0.0f;
2370 				inst.m_pos[1]      = 0.0f;
2371 				inst.m_pos[2]      = 0.0f;
2372 				inst.m_model       = &m_platformModel;
2373 				inst.m_svExtrusionDistance = 2.0f; //prevent culling on tight view frustum
2374 			}
2375 
2376 			// Scene 0 - shadow receivers - Floor.
2377 			{
2378 				Instance& inst = shadowReceivers[Scene0][shadowReceiversCount[Scene0]++];
2379 				inst.m_scale[0]    = 500.0f;
2380 				inst.m_scale[1]    = 500.0f;
2381 				inst.m_scale[2]    = 500.0f;
2382 				inst.m_rotation[0] = 0.0f;
2383 				inst.m_rotation[1] = 0.0f;
2384 				inst.m_rotation[2] = 0.0f;
2385 				inst.m_pos[0]      = 0.0f;
2386 				inst.m_pos[1]      = 0.0f;
2387 				inst.m_pos[2]      = 0.0f;
2388 				inst.m_model       = &m_hplaneFieldModel;
2389 			}
2390 
2391 			// Scene 1 - shadow casters - Bunny instances
2392 			{
2393 				enum Direction
2394 				{
2395 					Left  = 0x0,
2396 					Down  = 0x1,
2397 					Right = 0x2,
2398 					Up    = 0x3,
2399 				};
2400 				const uint8_t directionMask = 0x3;
2401 
2402 				uint8_t currentDirection = Left;
2403 				float currX = 0.0f;
2404 				float currY = 0.0f;
2405 				const float stepX = 20.0f;
2406 				const float stepY = 20.0f;
2407 				uint8_t stateStep = 0;
2408 				uint8_t stateChange = 1;
2409 
2410 				for (uint8_t ii = 0; ii < m_instanceCount; ++ii)
2411 				{
2412 					Instance& inst = shadowCasters[Scene1][shadowCastersCount[Scene1]++];
2413 					inst.m_scale[0]    = 5.0f;
2414 					inst.m_scale[1]    = 5.0f;
2415 					inst.m_scale[2]    = 5.0f;
2416 					inst.m_rotation[0] = 0.0f;
2417 					inst.m_rotation[1] = bx::kPi;
2418 					inst.m_rotation[2] = 0.0f;
2419 					inst.m_pos[0]      = currX;
2420 					inst.m_pos[1]      = 0.0f;
2421 					inst.m_pos[2]      = currY;
2422 					inst.m_model       = bunnyModel;
2423 
2424 					++stateStep;
2425 					if (stateStep >= ( (stateChange & ~0x1) >> 1) )
2426 					{
2427 						currentDirection = (currentDirection + 1) & directionMask;
2428 						stateStep = 0;
2429 						++stateChange;
2430 					}
2431 
2432 					switch (currentDirection)
2433 					{
2434 					case Left:  currX -= stepX; break;
2435 					case Down:  currY -= stepY; break;
2436 					case Right: currX += stepX; break;
2437 					case Up:    currY += stepY; break;
2438 					}
2439 				}
2440 			}
2441 
2442 			// Scene 1 - shadow receivers - Floor.
2443 			{
2444 				Instance& inst = shadowReceivers[Scene1][shadowReceiversCount[Scene1]++];
2445 				inst.m_scale[0]    = 500.0f;
2446 				inst.m_scale[1]    = 500.0f;
2447 				inst.m_scale[2]    = 500.0f;
2448 				inst.m_rotation[0] = 0.0f;
2449 				inst.m_rotation[1] = 0.0f;
2450 				inst.m_rotation[2] = 0.0f;
2451 				inst.m_pos[0]      = 0.0f;
2452 				inst.m_pos[1]      = 0.0f;
2453 				inst.m_pos[2]      = 0.0f;
2454 				inst.m_model       = &m_hplaneFigureModel;
2455 			}
2456 
2457 			// Make sure at the beginning everything gets cleared.
2458 			bgfx::setViewClear(0
2459 				, BGFX_CLEAR_COLOR
2460 				| BGFX_CLEAR_DEPTH
2461 				| BGFX_CLEAR_STENCIL
2462 				, m_clearValues.m_clearRgba
2463 				, m_clearValues.m_clearDepth
2464 				, m_clearValues.m_clearStencil
2465 				);
2466 
2467 			::touch(0);
2468 
2469 			// Draw ambient only.
2470 			s_uniforms.m_params.m_ambientPass = 1.0f;
2471 			s_uniforms.m_params.m_lightingPass = 0.0f;
2472 
2473 			s_uniforms.m_color[0] = 1.0f;
2474 			s_uniforms.m_color[1] = 1.0f;
2475 			s_uniforms.m_color[2] = 1.0f;
2476 
2477 			const RenderState& drawAmbient = m_useStencilTexture
2478 				? s_renderStates[RenderState::ShadowVolume_UsingStencilTexture_DrawAmbient]
2479 				: s_renderStates[RenderState::ShadowVolume_UsingStencilBuffer_DrawAmbient]
2480 				;
2481 
2482 			// Draw shadow casters.
2483 			for (uint8_t ii = 0; ii < shadowCastersCount[m_currentScene]; ++ii)
2484 			{
2485 				shadowCasters[m_currentScene][ii].submit(VIEWID_RANGE1_PASS0, drawAmbient);
2486 			}
2487 
2488 			// Draw shadow receivers.
2489 			for (uint8_t ii = 0; ii < shadowReceiversCount[m_currentScene]; ++ii)
2490 			{
2491 				shadowReceivers[m_currentScene][ii].submit(VIEWID_RANGE1_PASS0, drawAmbient);
2492 			}
2493 
2494 			// Using stencil texture requires rendering to separate render target. first pass is building depth buffer.
2495 			if (m_useStencilTexture)
2496 			{
2497 				bgfx::setViewClear(VIEWID_RANGE1_RT_PASS1, BGFX_CLEAR_DEPTH, 0x00000000, 1.0f, 0);
2498 				bgfx::setViewFrameBuffer(VIEWID_RANGE1_RT_PASS1, s_stencilFb);
2499 
2500 				const RenderState& renderState = s_renderStates[RenderState::ShadowVolume_UsingStencilTexture_BuildDepth];
2501 
2502 				for (uint8_t ii = 0; ii < shadowCastersCount[m_currentScene]; ++ii)
2503 				{
2504 					shadowCasters[m_currentScene][ii].submit(VIEWID_RANGE1_RT_PASS1, renderState);
2505 				}
2506 
2507 				for (uint8_t ii = 0; ii < shadowReceiversCount[m_currentScene]; ++ii)
2508 				{
2509 					shadowReceivers[m_currentScene][ii].submit(VIEWID_RANGE1_RT_PASS1, renderState);
2510 				}
2511 			}
2512 
2513 			m_profTime = bx::getHPCounter();
2514 
2515 			/**
2516 			 * For each light:
2517 			 * 1. Compute and draw shadow volume to stencil buffer
2518 			 * 2. Draw diffuse with stencil test
2519 			 */
2520 			for (uint8_t ii = 0, viewId = VIEWID_RANGE15_PASS2; ii < m_numLights; ++ii, ++viewId)
2521 			{
2522 				const float* lightPos = lightPosRadius[ii];
2523 
2524 				bx::memCopy(s_uniforms.m_lightPosRadius, lightPosRadius[ii],   4*sizeof(float) );
2525 				bx::memCopy(s_uniforms.m_lightRgbInnerR, m_lightRgbInnerR[ii], 3*sizeof(float) );
2526 				bx::memCopy(s_uniforms.m_color,          m_lightRgbInnerR[ii], 3*sizeof(float) );
2527 
2528 				if (m_useStencilTexture)
2529 				{
2530 					bgfx::setViewFrameBuffer(viewId, s_stencilFb);
2531 
2532 					bgfx::setViewClear(viewId
2533 						, BGFX_CLEAR_COLOR
2534 						, 0x00000000
2535 						, 1.0f
2536 						, 0
2537 						);
2538 				}
2539 				else
2540 				{
2541 					const bgfx::FrameBufferHandle invalid = BGFX_INVALID_HANDLE;
2542 					bgfx::setViewFrameBuffer(viewId, invalid);
2543 
2544 					bgfx::setViewClear(viewId
2545 						, BGFX_CLEAR_STENCIL
2546 						, m_clearValues.m_clearRgba
2547 						, m_clearValues.m_clearDepth
2548 						, m_clearValues.m_clearStencil
2549 						);
2550 				}
2551 
2552 				// Create near clip volume for current light.
2553 				float nearClipVolume[6 * 4] = {};
2554 				float pointLight[4];
2555 				if (m_mixedSvImpl)
2556 				{
2557 					pointLight[0] = lightPos[0];
2558 					pointLight[1] = lightPos[1];
2559 					pointLight[2] = lightPos[2];
2560 					pointLight[3] = 1.0f;
2561 					createNearClipVolume(nearClipVolume, pointLight, m_viewState.m_view, fov, aspect, nearPlane);
2562 				}
2563 
2564 				for (uint8_t jj = 0; jj < shadowCastersCount[m_currentScene]; ++jj)
2565 				{
2566 					const Instance& instance = shadowCasters[m_currentScene][jj];
2567 					Model* model = instance.m_model;
2568 
2569 					ShadowVolumeImpl::Enum shadowVolumeImpl = m_shadowVolumeImpl;
2570 					if (m_mixedSvImpl)
2571 					{
2572 						// If instance is inside near clip volume, depth fail must be used, else depth pass is fine.
2573 						bool isInsideVolume = clipTest(nearClipVolume, 6, model->m_mesh, instance.m_scale, instance.m_pos);
2574 						shadowVolumeImpl = (isInsideVolume ? ShadowVolumeImpl::DepthFail : ShadowVolumeImpl::DepthPass);
2575 					}
2576 					s_uniforms.m_svparams.m_dfail = float(ShadowVolumeImpl::DepthFail == shadowVolumeImpl);
2577 
2578 					// Compute virtual light position for shadow volume generation.
2579 					float transformedLightPos[3];
2580 					shadowVolumeLightTransform(transformedLightPos
2581 						, instance.m_scale
2582 						, instance.m_rotation
2583 						, instance.m_pos
2584 						, lightPos
2585 						);
2586 
2587 					// Set virtual light pos.
2588 					bx::memCopy(s_uniforms.m_virtualLightPos_extrusionDist, transformedLightPos, 3*sizeof(float) );
2589 					s_uniforms.m_virtualLightPos_extrusionDist[3] = instance.m_svExtrusionDistance;
2590 
2591 					// Compute transform for shadow volume.
2592 					float shadowVolumeMtx[16];
2593 					bx::mtxSRT(shadowVolumeMtx
2594 						, instance.m_scale[0]
2595 						, instance.m_scale[1]
2596 						, instance.m_scale[2]
2597 						, instance.m_rotation[0]
2598 						, instance.m_rotation[1]
2599 						, instance.m_rotation[2]
2600 						, instance.m_pos[0]
2601 						, instance.m_pos[1]
2602 						, instance.m_pos[2]
2603 						);
2604 
2605 					GroupArray& groups = model->m_mesh.m_groups;
2606 					const uint16_t stride = model->m_mesh.m_layout.getStride();
2607 					for (GroupArray::iterator it = groups.begin(), itEnd = groups.end(); it != itEnd; ++it)
2608 					{
2609 						Group& group = *it;
2610 
2611 						// Create shadow volume.
2612 						ShadowVolume shadowVolume;
2613 						shadowVolumeCreate(shadowVolume
2614 							, group
2615 							, stride
2616 							, shadowVolumeMtx
2617 							, transformedLightPos
2618 							, shadowVolumeImpl
2619 							, m_shadowVolumeAlgorithm
2620 							, m_useStencilTexture
2621 							);
2622 
2623 						m_numShadowVolumeVertices += shadowVolume.m_numVertices;
2624 						m_numShadowVolumeIndices += shadowVolume.m_numIndices;
2625 
2626 						ShadowVolumeProgramType::Enum programIndex = ShadowVolumeProgramType::Blank;
2627 						RenderState::Enum renderStateIndex;
2628 						if (m_useStencilTexture)
2629 						{
2630 							renderStateIndex = ShadowVolumeImpl::DepthFail == shadowVolumeImpl
2631 								? RenderState::ShadowVolume_UsingStencilTexture_CraftStencil_DepthFail
2632 								: RenderState::ShadowVolume_UsingStencilTexture_CraftStencil_DepthPass
2633 								;
2634 
2635 							programIndex = ShadowVolumeAlgorithm::FaceBased == m_shadowVolumeAlgorithm
2636 								? ShadowVolumeProgramType::Tex1
2637 								: ShadowVolumeProgramType::Tex2
2638 								;
2639 						}
2640 						else
2641 						{
2642 							renderStateIndex = ShadowVolumeImpl::DepthFail == shadowVolumeImpl
2643 								? RenderState::ShadowVolume_UsingStencilBuffer_CraftStencil_DepthFail
2644 								: RenderState::ShadowVolume_UsingStencilBuffer_CraftStencil_DepthPass
2645 								;
2646 						}
2647 						const RenderState& renderStateCraftStencil = s_renderStates[renderStateIndex];
2648 
2649 						s_uniforms.submitPerDrawUniforms();
2650 						bgfx::setTransform(shadowVolumeMtx);
2651 						bgfx::setVertexBuffer(0, shadowVolume.m_vbSides);
2652 						bgfx::setIndexBuffer(shadowVolume.m_ibSides);
2653 						setRenderState(renderStateCraftStencil);
2654 						::submit(viewId, m_svProgs[programIndex][ShadowVolumePart::Side]);
2655 
2656 						if (shadowVolume.m_cap)
2657 						{
2658 							s_uniforms.submitPerDrawUniforms();
2659 							bgfx::setTransform(shadowVolumeMtx);
2660 							bgfx::setVertexBuffer(0, group.m_vbh);
2661 							bgfx::setIndexBuffer(shadowVolume.m_ibFrontCap);
2662 							setRenderState(renderStateCraftStencil);
2663 							::submit(viewId, m_svProgs[programIndex][ShadowVolumePart::Front]);
2664 
2665 							s_uniforms.submitPerDrawUniforms();
2666 							bgfx::setTransform(shadowVolumeMtx);
2667 							bgfx::setVertexBuffer(0, group.m_vbh);
2668 							bgfx::setIndexBuffer(shadowVolume.m_ibBackCap);
2669 							::setRenderState(renderStateCraftStencil);
2670 							::submit(viewId, m_svProgs[programIndex][ShadowVolumePart::Back]);
2671 						}
2672 
2673 						if (m_drawShadowVolumes)
2674 						{
2675 							const RenderState& renderState = s_renderStates[RenderState::Custom_DrawShadowVolume_Lines];
2676 
2677 							s_uniforms.submitPerDrawUniforms();
2678 							bgfx::setTransform(shadowVolumeMtx);
2679 							bgfx::setVertexBuffer(0, shadowVolume.m_vbSides);
2680 							bgfx::setIndexBuffer(shadowVolume.m_ibSides);
2681 							::setRenderState(renderState);
2682 							::submit(VIEWID_RANGE1_PASS3, m_svProgs[ShadowVolumeProgramType::Color][ShadowVolumePart::Side]);
2683 
2684 							if (shadowVolume.m_cap)
2685 							{
2686 								s_uniforms.submitPerDrawUniforms();
2687 								bgfx::setTransform(shadowVolumeMtx);
2688 								bgfx::setVertexBuffer(0, group.m_vbh);
2689 								bgfx::setIndexBuffer(shadowVolume.m_ibFrontCap);
2690 								::setRenderState(renderState);
2691 								::submit(VIEWID_RANGE1_PASS3, m_svProgs[ShadowVolumeProgramType::Color][ShadowVolumePart::Front]);
2692 
2693 								s_uniforms.submitPerDrawUniforms();
2694 								bgfx::setTransform(shadowVolumeMtx);
2695 								bgfx::setVertexBuffer(0, group.m_vbh);
2696 								bgfx::setIndexBuffer(shadowVolume.m_ibBackCap);
2697 								::setRenderState(renderState);
2698 								::submit(VIEWID_RANGE1_PASS3, m_svProgs[ShadowVolumeProgramType::Color][ShadowVolumePart::Back]);
2699 							}
2700 						}
2701 					}
2702 				}
2703 
2704 				// Draw diffuse only.
2705 				s_uniforms.m_params.m_ambientPass = 0.0f;
2706 				s_uniforms.m_params.m_lightingPass = 1.0f;
2707 
2708 				RenderState& drawDiffuse = m_useStencilTexture
2709 					? s_renderStates[RenderState::ShadowVolume_UsingStencilTexture_DrawDiffuse]
2710 					: s_renderStates[RenderState::ShadowVolume_UsingStencilBuffer_DrawDiffuse]
2711 					;
2712 
2713 				// If using stencil texture, viewId is set to render target. Incr it to render to default back buffer.
2714 				viewId += uint8_t(m_useStencilTexture);
2715 
2716 				// Draw shadow casters.
2717 				for (uint8_t jj = 0; jj < shadowCastersCount[m_currentScene]; ++jj)
2718 				{
2719 					shadowCasters[m_currentScene][jj].submit(viewId, drawDiffuse);
2720 				}
2721 
2722 				// Draw shadow receivers.
2723 				for (uint8_t jj = 0; jj < shadowReceiversCount[m_currentScene]; ++jj)
2724 				{
2725 					shadowReceivers[m_currentScene][jj].submit(viewId, drawDiffuse);
2726 				}
2727 			}
2728 
2729 			m_profTime = bx::getHPCounter() - m_profTime;
2730 
2731 			// Lights.
2732 			const float lightScale[3] = { 1.5f, 1.5f, 1.5f };
2733 			for (uint8_t ii = 0; ii < m_numLights; ++ii)
2734 			{
2735 				bx::memCopy(s_uniforms.m_color, m_lightRgbInnerR[ii], 3*sizeof(float) );
2736 
2737 				float lightMtx[16];
2738 				mtxBillboard(lightMtx, m_viewState.m_view, lightPosRadius[ii], lightScale);
2739 
2740 				m_vplaneModel.submit(VIEWID_RANGE1_PASS3, lightMtx, s_renderStates[RenderState::Custom_BlendLightTexture]);
2741 			}
2742 
2743 			// Setup view rect and transform for all used views.
2744 			setViewRectMask(s_viewMask, 0, 0, uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height) );
2745 			setViewTransformMask(s_viewMask, m_viewState.m_view, m_viewState.m_proj);
2746 			s_viewMask = 0;
2747 
2748 			// Advance to next frame. Rendering thread will be kicked to
2749 			// process submitted rendering primitives.
2750 			bgfx::frame();
2751 
2752 			// Swap memory pages.
2753 			s_svAllocator.swap();
2754 
2755 			// Reset clear values.
2756 			setViewClearMask(UINT32_MAX
2757 				, BGFX_CLEAR_NONE
2758 				, m_clearValues.m_clearRgba
2759 				, m_clearValues.m_clearDepth
2760 				, m_clearValues.m_clearStencil
2761 				);
2762 
2763 			return true;
2764 		}
2765 
2766 		return false;
2767 	}
2768 
2769 	ViewState m_viewState;
2770 	ClearValues m_clearValues;
2771 
2772 	uint32_t m_debug;
2773 	uint32_t m_reset;
2774 
2775 	bgfx::TextureHandle m_figureTex;
2776 	bgfx::TextureHandle m_flareTex;
2777 	bgfx::TextureHandle m_fieldstoneTex;
2778 
2779 	bgfx::ProgramHandle m_programTextureLighting;
2780 	bgfx::ProgramHandle m_programColorLighting;
2781 	bgfx::ProgramHandle m_programColorTexture;
2782 	bgfx::ProgramHandle m_programTexture;
2783 
2784 	bgfx::ProgramHandle m_programBackBlank;
2785 	bgfx::ProgramHandle m_programSideBlank;
2786 	bgfx::ProgramHandle m_programFrontBlank;
2787 
2788 	bgfx::ProgramHandle m_programBackColor;
2789 	bgfx::ProgramHandle m_programSideColor;
2790 	bgfx::ProgramHandle m_programFrontColor;
2791 
2792 	bgfx::ProgramHandle m_programSideTex;
2793 	bgfx::ProgramHandle m_programBackTex1;
2794 	bgfx::ProgramHandle m_programBackTex2;
2795 	bgfx::ProgramHandle m_programFrontTex1;
2796 	bgfx::ProgramHandle m_programFrontTex2;
2797 
2798 	bgfx::ProgramHandle m_svProgs[ShadowVolumeProgramType::Count][ShadowVolumePart::Count];
2799 
2800 	Model m_bunnyLowPolyModel;
2801 	Model m_bunnyHighPolyModel;
2802 	Model m_columnModel;
2803 	Model m_platformModel;
2804 	Model m_cubeModel;
2805 	Model m_hplaneFieldModel;
2806 	Model m_hplaneFigureModel;
2807 	Model m_vplaneModel;
2808 
2809 	float m_lightRgbInnerR[MAX_LIGHTS_COUNT][4];
2810 
2811 	int64_t m_profTime;
2812 	int64_t m_timeOffset;
2813 
2814 	uint32_t m_numShadowVolumeVertices;
2815 	uint32_t m_numShadowVolumeIndices;
2816 
2817 	uint32_t m_oldWidth;
2818 	uint32_t m_oldHeight;
2819 
2820 	int32_t m_numLights;
2821 	int32_t m_instanceCount;
2822 	bool m_showHelp;
2823 	bool m_updateLights;
2824 	bool m_updateScene;
2825 	bool m_mixedSvImpl;
2826 	bool m_useStencilTexture;
2827 	bool m_drawShadowVolumes;
2828 	ShadowVolumeImpl::Enum      m_shadowVolumeImpl;
2829 	ShadowVolumeAlgorithm::Enum m_shadowVolumeAlgorithm;
2830 
2831 	LightPattern m_lightPattern;
2832 	MeshChoice   m_currentMesh;
2833 	Scene        m_currentScene;
2834 
2835 	entry::MouseState m_mouseState;
2836 };
2837 
2838 } // namespace
2839 
2840 ENTRY_IMPLEMENT_MAIN(
2841 	  ExampleShadowVolumes
2842 	, "14-shadowvolumes"
2843 	, "Shadow volumes."
2844 	, "https://bkaradzic.github.io/bgfx/examples.html#shadowvolumes");
2845