shadowvolumes.cpp 78 KB

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