shadowvolumes.cpp 78 KB

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