shadowvolumes.cpp 80 KB

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