shadowvolumes.cpp 78 KB

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