shadowvolumes.cpp 78 KB

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