shadowvolumes.cpp 78 KB

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