renderer_d3d9.cpp 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254
  1. /*
  2. * Copyright 2011-2014 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "bgfx_p.h"
  6. #if BGFX_CONFIG_RENDERER_DIRECT3D9
  7. # include "renderer_d3d9.h"
  8. namespace bgfx
  9. {
  10. static wchar_t s_viewNameW[BGFX_CONFIG_MAX_VIEWS][256];
  11. struct PrimInfo
  12. {
  13. D3DPRIMITIVETYPE m_type;
  14. uint32_t m_min;
  15. uint32_t m_div;
  16. uint32_t m_sub;
  17. };
  18. static const PrimInfo s_primInfo[] =
  19. {
  20. { D3DPT_TRIANGLELIST, 3, 3, 0 },
  21. { D3DPT_TRIANGLESTRIP, 3, 1, 2 },
  22. { D3DPT_LINELIST, 2, 2, 0 },
  23. { D3DPT_POINTLIST, 1, 1, 0 },
  24. };
  25. static const char* s_primName[] =
  26. {
  27. "TriList",
  28. "TriStrip",
  29. "Line",
  30. "Point",
  31. };
  32. static const D3DMULTISAMPLE_TYPE s_checkMsaa[] =
  33. {
  34. D3DMULTISAMPLE_NONE,
  35. D3DMULTISAMPLE_2_SAMPLES,
  36. D3DMULTISAMPLE_4_SAMPLES,
  37. D3DMULTISAMPLE_8_SAMPLES,
  38. D3DMULTISAMPLE_16_SAMPLES,
  39. };
  40. static Msaa s_msaa[] =
  41. {
  42. { D3DMULTISAMPLE_NONE, 0 },
  43. { D3DMULTISAMPLE_2_SAMPLES, 0 },
  44. { D3DMULTISAMPLE_4_SAMPLES, 0 },
  45. { D3DMULTISAMPLE_8_SAMPLES, 0 },
  46. { D3DMULTISAMPLE_16_SAMPLES, 0 },
  47. };
  48. struct Blend
  49. {
  50. D3DBLEND m_src;
  51. D3DBLEND m_dst;
  52. bool m_factor;
  53. };
  54. static const Blend s_blendFactor[] =
  55. {
  56. { (D3DBLEND)0, (D3DBLEND)0, false }, // ignored
  57. { D3DBLEND_ZERO, D3DBLEND_ZERO, false }, // ZERO
  58. { D3DBLEND_ONE, D3DBLEND_ONE, false }, // ONE
  59. { D3DBLEND_SRCCOLOR, D3DBLEND_SRCCOLOR, false }, // SRC_COLOR
  60. { D3DBLEND_INVSRCCOLOR, D3DBLEND_INVSRCCOLOR, false }, // INV_SRC_COLOR
  61. { D3DBLEND_SRCALPHA, D3DBLEND_SRCALPHA, false }, // SRC_ALPHA
  62. { D3DBLEND_INVSRCALPHA, D3DBLEND_INVSRCALPHA, false }, // INV_SRC_ALPHA
  63. { D3DBLEND_DESTALPHA, D3DBLEND_DESTALPHA, false }, // DST_ALPHA
  64. { D3DBLEND_INVDESTALPHA, D3DBLEND_INVDESTALPHA, false }, // INV_DST_ALPHA
  65. { D3DBLEND_DESTCOLOR, D3DBLEND_DESTCOLOR, false }, // DST_COLOR
  66. { D3DBLEND_INVDESTCOLOR, D3DBLEND_INVDESTCOLOR, false }, // INV_DST_COLOR
  67. { D3DBLEND_SRCALPHASAT, D3DBLEND_ONE, false }, // SRC_ALPHA_SAT
  68. { D3DBLEND_BLENDFACTOR, D3DBLEND_BLENDFACTOR, true }, // FACTOR
  69. { D3DBLEND_INVBLENDFACTOR, D3DBLEND_INVBLENDFACTOR, true }, // INV_FACTOR
  70. };
  71. static const D3DBLENDOP s_blendEquation[] =
  72. {
  73. D3DBLENDOP_ADD,
  74. D3DBLENDOP_SUBTRACT,
  75. D3DBLENDOP_REVSUBTRACT,
  76. D3DBLENDOP_MIN,
  77. D3DBLENDOP_MAX,
  78. };
  79. static const D3DCMPFUNC s_cmpFunc[] =
  80. {
  81. (D3DCMPFUNC)0, // ignored
  82. D3DCMP_LESS,
  83. D3DCMP_LESSEQUAL,
  84. D3DCMP_EQUAL,
  85. D3DCMP_GREATEREQUAL,
  86. D3DCMP_GREATER,
  87. D3DCMP_NOTEQUAL,
  88. D3DCMP_NEVER,
  89. D3DCMP_ALWAYS,
  90. };
  91. static const D3DSTENCILOP s_stencilOp[] =
  92. {
  93. D3DSTENCILOP_ZERO,
  94. D3DSTENCILOP_KEEP,
  95. D3DSTENCILOP_REPLACE,
  96. D3DSTENCILOP_INCR,
  97. D3DSTENCILOP_INCRSAT,
  98. D3DSTENCILOP_DECR,
  99. D3DSTENCILOP_DECRSAT,
  100. D3DSTENCILOP_INVERT,
  101. };
  102. static const D3DRENDERSTATETYPE s_stencilFuncRs[] =
  103. {
  104. D3DRS_STENCILFUNC,
  105. D3DRS_CCW_STENCILFUNC,
  106. };
  107. static const D3DRENDERSTATETYPE s_stencilFailRs[] =
  108. {
  109. D3DRS_STENCILFAIL,
  110. D3DRS_CCW_STENCILFAIL,
  111. };
  112. static const D3DRENDERSTATETYPE s_stencilZFailRs[] =
  113. {
  114. D3DRS_STENCILZFAIL,
  115. D3DRS_CCW_STENCILZFAIL,
  116. };
  117. static const D3DRENDERSTATETYPE s_stencilZPassRs[] =
  118. {
  119. D3DRS_STENCILPASS,
  120. D3DRS_CCW_STENCILPASS,
  121. };
  122. static const D3DCULL s_cullMode[] =
  123. {
  124. D3DCULL_NONE,
  125. D3DCULL_CW,
  126. D3DCULL_CCW,
  127. };
  128. static const D3DFORMAT s_checkColorFormats[] =
  129. {
  130. D3DFMT_UNKNOWN,
  131. D3DFMT_A8R8G8B8, D3DFMT_UNKNOWN,
  132. D3DFMT_R32F, D3DFMT_R16F, D3DFMT_G16R16, D3DFMT_A8R8G8B8, D3DFMT_UNKNOWN,
  133. D3DFMT_UNKNOWN, // terminator
  134. };
  135. static D3DFORMAT s_colorFormat[] =
  136. {
  137. D3DFMT_UNKNOWN, // ignored
  138. D3DFMT_A8R8G8B8,
  139. D3DFMT_A2B10G10R10,
  140. D3DFMT_A16B16G16R16,
  141. D3DFMT_A16B16G16R16F,
  142. D3DFMT_R16F,
  143. D3DFMT_R32F,
  144. };
  145. static const D3DTEXTUREADDRESS s_textureAddress[] =
  146. {
  147. D3DTADDRESS_WRAP,
  148. D3DTADDRESS_MIRROR,
  149. D3DTADDRESS_CLAMP,
  150. };
  151. static const D3DTEXTUREFILTERTYPE s_textureFilter[] =
  152. {
  153. D3DTEXF_LINEAR,
  154. D3DTEXF_POINT,
  155. D3DTEXF_ANISOTROPIC,
  156. };
  157. struct TextureFormatInfo
  158. {
  159. D3DFORMAT m_fmt;
  160. };
  161. static TextureFormatInfo s_textureFormat[] =
  162. {
  163. { D3DFMT_DXT1 }, // BC1
  164. { D3DFMT_DXT3 }, // BC2
  165. { D3DFMT_DXT5 }, // BC3
  166. { D3DFMT_UNKNOWN }, // BC4
  167. { D3DFMT_UNKNOWN }, // BC5
  168. { D3DFMT_UNKNOWN }, // ETC1
  169. { D3DFMT_UNKNOWN }, // ETC2
  170. { D3DFMT_UNKNOWN }, // ETC2A
  171. { D3DFMT_UNKNOWN }, // ETC2A1
  172. { D3DFMT_UNKNOWN }, // PTC12
  173. { D3DFMT_UNKNOWN }, // PTC14
  174. { D3DFMT_UNKNOWN }, // PTC12A
  175. { D3DFMT_UNKNOWN }, // PTC14A
  176. { D3DFMT_UNKNOWN }, // PTC22
  177. { D3DFMT_UNKNOWN }, // PTC24
  178. { D3DFMT_UNKNOWN }, // Unknown
  179. { D3DFMT_L8 }, // R8
  180. { D3DFMT_G16R16 }, // R16
  181. { D3DFMT_R16F }, // R16F
  182. { D3DFMT_UNKNOWN }, // R32
  183. { D3DFMT_R32F }, // R32F
  184. { D3DFMT_A8L8 }, // RG8
  185. { D3DFMT_G16R16 }, // RG16
  186. { D3DFMT_G16R16F }, // RG16F
  187. { D3DFMT_UNKNOWN }, // RG32
  188. { D3DFMT_G32R32F }, // RG32F
  189. { D3DFMT_A8R8G8B8 }, // BGRA8
  190. { D3DFMT_A16B16G16R16 }, // RGBA16
  191. { D3DFMT_A16B16G16R16F }, // RGBA16F
  192. { D3DFMT_UNKNOWN }, // RGBA32
  193. { D3DFMT_A32B32G32R32F }, // RGBA32F
  194. { D3DFMT_R5G6B5 }, // R5G6B5
  195. { D3DFMT_A4R4G4B4 }, // RGBA4
  196. { D3DFMT_A1R5G5B5 }, // RGB5A1
  197. { D3DFMT_A2B10G10R10 }, // RGB10A2
  198. { D3DFMT_UNKNOWN }, // UnknownDepth
  199. { D3DFMT_D16 }, // D16
  200. { D3DFMT_D24X8 }, // D24
  201. { D3DFMT_D24S8 }, // D24S8
  202. { D3DFMT_D32 }, // D32
  203. { D3DFMT_DF16 }, // D16F
  204. { D3DFMT_DF24 }, // D24F
  205. { D3DFMT_D32F_LOCKABLE }, // D32F
  206. #if defined(D3D_DISABLE_9EX)
  207. { D3DFMT_UNKNOWN }, // D0S8
  208. #else
  209. { D3DFMT_INTZ /*D3DFMT_S8_LOCKABLE*/ }, // D0S8
  210. #endif // defined(D3D_DISABLE_9EX)
  211. };
  212. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  213. static ExtendedFormat s_extendedFormats[ExtendedFormat::Count] =
  214. {
  215. { D3DFMT_ATI1, 0, D3DRTYPE_TEXTURE, false },
  216. { D3DFMT_ATI2, 0, D3DRTYPE_TEXTURE, false },
  217. { D3DFMT_DF16, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  218. { D3DFMT_DF24, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  219. { D3DFMT_INST, 0, D3DRTYPE_SURFACE, false },
  220. { D3DFMT_INTZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  221. { D3DFMT_NULL, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  222. { D3DFMT_RESZ, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  223. { D3DFMT_RAWZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  224. };
  225. static const GUID IID_IDirect3D9 = { 0x81bdcbca, 0x64d4, 0x426d, { 0xae, 0x8d, 0xad, 0x1, 0x47, 0xf4, 0x27, 0x5c } };
  226. static const GUID IID_IDirect3DDevice9Ex = { 0xb18b10ce, 0x2649, 0x405a, { 0x87, 0xf, 0x95, 0xf7, 0x77, 0xd4, 0x31, 0x3a } };
  227. struct RendererContextD3D9 : public RendererContextI
  228. {
  229. RendererContextD3D9()
  230. : m_d3d9(NULL)
  231. , m_device(NULL)
  232. , m_backBufferColor(NULL)
  233. , m_backBufferDepthStencil(NULL)
  234. , m_captureTexture(NULL)
  235. , m_captureSurface(NULL)
  236. , m_captureResolve(NULL)
  237. , m_flags(BGFX_RESET_NONE)
  238. , m_initialized(false)
  239. , m_amd(false)
  240. , m_nvidia(false)
  241. , m_instancing(false)
  242. , m_rtMsaa(false)
  243. {
  244. m_fbh.idx = invalidHandle;
  245. memset(m_uniforms, 0, sizeof(m_uniforms) );
  246. memset(&m_resolution, 0, sizeof(m_resolution) );
  247. D3DFORMAT adapterFormat = D3DFMT_X8R8G8B8;
  248. // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172588%28v=vs.85%29.aspx
  249. memset(&m_params, 0, sizeof(m_params) );
  250. m_params.BackBufferWidth = BGFX_DEFAULT_WIDTH;
  251. m_params.BackBufferHeight = BGFX_DEFAULT_HEIGHT;
  252. m_params.BackBufferFormat = adapterFormat;
  253. m_params.BackBufferCount = 1;
  254. m_params.MultiSampleType = D3DMULTISAMPLE_NONE;
  255. m_params.MultiSampleQuality = 0;
  256. m_params.EnableAutoDepthStencil = TRUE;
  257. m_params.AutoDepthStencilFormat = D3DFMT_D24S8;
  258. m_params.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
  259. #if BX_PLATFORM_WINDOWS
  260. m_params.FullScreen_RefreshRateInHz = 0;
  261. m_params.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  262. m_params.SwapEffect = D3DSWAPEFFECT_DISCARD;
  263. m_params.hDeviceWindow = g_bgfxHwnd;
  264. m_params.Windowed = true;
  265. RECT rect;
  266. GetWindowRect(g_bgfxHwnd, &rect);
  267. m_params.BackBufferWidth = rect.right-rect.left;
  268. m_params.BackBufferHeight = rect.bottom-rect.top;
  269. m_d3d9dll = bx::dlopen("d3d9.dll");
  270. BGFX_FATAL(NULL != m_d3d9dll, Fatal::UnableToInitialize, "Failed to load d3d9.dll.");
  271. #if BGFX_CONFIG_DEBUG_PIX
  272. m_D3DPERF_SetMarker = (D3DPERF_SetMarkerFunc)bx::dlsym(m_d3d9dll, "D3DPERF_SetMarker");
  273. m_D3DPERF_BeginEvent = (D3DPERF_BeginEventFunc)bx::dlsym(m_d3d9dll, "D3DPERF_BeginEvent");
  274. m_D3DPERF_EndEvent = (D3DPERF_EndEventFunc)bx::dlsym(m_d3d9dll, "D3DPERF_EndEvent");
  275. BX_CHECK(NULL != m_D3DPERF_SetMarker
  276. && NULL != m_D3DPERF_BeginEvent
  277. && NULL != m_D3DPERF_EndEvent
  278. , "Failed to initialize PIX events."
  279. );
  280. #endif // BGFX_CONFIG_DEBUG_PIX
  281. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  282. m_d3d9ex = NULL;
  283. Direct3DCreate9ExFn direct3DCreate9Ex = (Direct3DCreate9ExFn)bx::dlsym(m_d3d9dll, "Direct3DCreate9Ex");
  284. if (NULL != direct3DCreate9Ex)
  285. {
  286. direct3DCreate9Ex(D3D_SDK_VERSION, &m_d3d9ex);
  287. DX_CHECK(m_d3d9ex->QueryInterface(IID_IDirect3D9, (void**)&m_d3d9) );
  288. m_pool = D3DPOOL_DEFAULT;
  289. }
  290. else
  291. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  292. {
  293. Direct3DCreate9Fn direct3DCreate9 = (Direct3DCreate9Fn)bx::dlsym(m_d3d9dll, "Direct3DCreate9");
  294. BGFX_FATAL(NULL != direct3DCreate9, Fatal::UnableToInitialize, "Function Direct3DCreate9 not found.");
  295. m_d3d9 = direct3DCreate9(D3D_SDK_VERSION);
  296. m_pool = D3DPOOL_MANAGED;
  297. }
  298. BGFX_FATAL(m_d3d9, Fatal::UnableToInitialize, "Unable to create Direct3D.");
  299. m_adapter = D3DADAPTER_DEFAULT;
  300. m_deviceType = D3DDEVTYPE_HAL;
  301. uint32_t adapterCount = m_d3d9->GetAdapterCount();
  302. for (uint32_t ii = 0; ii < adapterCount; ++ii)
  303. {
  304. D3DADAPTER_IDENTIFIER9 identifier;
  305. HRESULT hr = m_d3d9->GetAdapterIdentifier(ii, 0, &identifier);
  306. if (SUCCEEDED(hr) )
  307. {
  308. BX_TRACE("Adapter #%d", ii);
  309. BX_TRACE("\tDriver: %s", identifier.Driver);
  310. BX_TRACE("\tDescription: %s", identifier.Description);
  311. BX_TRACE("\tDeviceName: %s", identifier.DeviceName);
  312. BX_TRACE("\tVendorId: 0x%08x, DeviceId: 0x%08x, SubSysId: 0x%08x, Revision: 0x%08x"
  313. , identifier.VendorId
  314. , identifier.DeviceId
  315. , identifier.SubSysId
  316. , identifier.Revision
  317. );
  318. #if BGFX_CONFIG_DEBUG_PERFHUD
  319. if (0 != strstr(identifier.Description, "PerfHUD") )
  320. {
  321. m_adapter = ii;
  322. m_deviceType = D3DDEVTYPE_REF;
  323. }
  324. #endif // BGFX_CONFIG_DEBUG_PERFHUD
  325. }
  326. }
  327. DX_CHECK(m_d3d9->GetAdapterIdentifier(m_adapter, 0, &m_identifier) );
  328. m_amd = m_identifier.VendorId == 0x1002;
  329. m_nvidia = m_identifier.VendorId == 0x10de;
  330. uint32_t behaviorFlags[] =
  331. {
  332. D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_PUREDEVICE|D3DCREATE_FPU_PRESERVE,
  333. D3DCREATE_MIXED_VERTEXPROCESSING|D3DCREATE_FPU_PRESERVE,
  334. D3DCREATE_SOFTWARE_VERTEXPROCESSING|D3DCREATE_FPU_PRESERVE,
  335. };
  336. for (uint32_t ii = 0; ii < BX_COUNTOF(behaviorFlags) && NULL == m_device; ++ii)
  337. {
  338. #if 0 // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  339. DX_CHECK(m_d3d9->CreateDeviceEx(m_adapter
  340. , m_deviceType
  341. , g_bgfxHwnd
  342. , behaviorFlags[ii]
  343. , &m_params
  344. , NULL
  345. , &m_device
  346. ) );
  347. #else
  348. DX_CHECK(m_d3d9->CreateDevice(m_adapter
  349. , m_deviceType
  350. , g_bgfxHwnd
  351. , behaviorFlags[ii]
  352. , &m_params
  353. , &m_device
  354. ) );
  355. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  356. }
  357. BGFX_FATAL(m_device, Fatal::UnableToInitialize, "Unable to create Direct3D9 device.");
  358. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  359. if (NULL != m_d3d9ex)
  360. {
  361. DX_CHECK(m_device->QueryInterface(IID_IDirect3DDevice9Ex, (void**)&m_deviceEx) );
  362. }
  363. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  364. DX_CHECK(m_device->GetDeviceCaps(&m_caps) );
  365. // For shit GPUs that can create DX9 device but can't do simple stuff. GTFO!
  366. BGFX_FATAL( (D3DPTEXTURECAPS_SQUAREONLY & m_caps.TextureCaps) == 0, Fatal::MinimumRequiredSpecs, "D3DPTEXTURECAPS_SQUAREONLY");
  367. BGFX_FATAL( (D3DPTEXTURECAPS_MIPMAP & m_caps.TextureCaps) == D3DPTEXTURECAPS_MIPMAP, Fatal::MinimumRequiredSpecs, "D3DPTEXTURECAPS_MIPMAP");
  368. BGFX_FATAL( (D3DPTEXTURECAPS_ALPHA & m_caps.TextureCaps) == D3DPTEXTURECAPS_ALPHA, Fatal::MinimumRequiredSpecs, "D3DPTEXTURECAPS_ALPHA");
  369. BGFX_FATAL(m_caps.VertexShaderVersion >= D3DVS_VERSION(2, 0) && m_caps.PixelShaderVersion >= D3DPS_VERSION(2, 1)
  370. , Fatal::MinimumRequiredSpecs
  371. , "Shader Model Version (vs: %x, ps: %x)."
  372. , m_caps.VertexShaderVersion
  373. , m_caps.PixelShaderVersion
  374. );
  375. BX_TRACE("Max vertex shader 3.0 instr. slots: %d", m_caps.MaxVertexShader30InstructionSlots);
  376. BX_TRACE("Max vertex shader constants: %d", m_caps.MaxVertexShaderConst);
  377. BX_TRACE("Max fragment shader 2.0 instr. slots: %d", m_caps.PS20Caps.NumInstructionSlots);
  378. BX_TRACE("Max fragment shader 3.0 instr. slots: %d", m_caps.MaxPixelShader30InstructionSlots);
  379. BX_TRACE("Num simultaneous render targets: %d", m_caps.NumSimultaneousRTs);
  380. g_caps.supported |= ( 0
  381. | BGFX_CAPS_TEXTURE_3D
  382. | BGFX_CAPS_TEXTURE_COMPARE_LEQUAL
  383. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  384. | BGFX_CAPS_FRAGMENT_DEPTH
  385. );
  386. g_caps.maxTextureSize = bx::uint32_min(m_caps.MaxTextureWidth, m_caps.MaxTextureHeight);
  387. m_caps.NumSimultaneousRTs = bx::uint32_min(m_caps.NumSimultaneousRTs, BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS);
  388. g_caps.maxFBAttachments = (uint8_t)m_caps.NumSimultaneousRTs;
  389. #if BGFX_CONFIG_RENDERER_USE_EXTENSIONS
  390. BX_TRACE("Extended formats:");
  391. for (uint32_t ii = 0; ii < ExtendedFormat::Count; ++ii)
  392. {
  393. ExtendedFormat& fmt = s_extendedFormats[ii];
  394. fmt.m_supported = SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter, m_deviceType, adapterFormat, fmt.m_usage, fmt.m_type, fmt.m_fmt) );
  395. const char* fourcc = (const char*)&fmt.m_fmt;
  396. BX_TRACE("\t%2d: %c%c%c%c %s", ii, fourcc[0], fourcc[1], fourcc[2], fourcc[3], fmt.m_supported ? "supported" : "");
  397. BX_UNUSED(fourcc);
  398. }
  399. m_instancing = false
  400. || s_extendedFormats[ExtendedFormat::Inst].m_supported
  401. || (m_caps.VertexShaderVersion >= D3DVS_VERSION(3, 0) )
  402. ;
  403. if (m_amd
  404. && s_extendedFormats[ExtendedFormat::Inst].m_supported)
  405. {
  406. // AMD only
  407. m_device->SetRenderState(D3DRS_POINTSIZE, D3DFMT_INST);
  408. }
  409. if (s_extendedFormats[ExtendedFormat::Intz].m_supported)
  410. {
  411. s_textureFormat[TextureFormat::D24].m_fmt = D3DFMT_INTZ;
  412. s_textureFormat[TextureFormat::D32].m_fmt = D3DFMT_INTZ;
  413. }
  414. s_textureFormat[TextureFormat::BC4].m_fmt = s_extendedFormats[ExtendedFormat::Ati1].m_supported ? D3DFMT_ATI1 : D3DFMT_UNKNOWN;
  415. s_textureFormat[TextureFormat::BC5].m_fmt = s_extendedFormats[ExtendedFormat::Ati2].m_supported ? D3DFMT_ATI2 : D3DFMT_UNKNOWN;
  416. g_caps.supported |= m_instancing ? BGFX_CAPS_INSTANCING : 0;
  417. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  418. {
  419. g_caps.formats[ii] = SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  420. , m_deviceType
  421. , adapterFormat
  422. , 0
  423. , D3DRTYPE_TEXTURE
  424. , s_textureFormat[ii].m_fmt
  425. ) ) ? 1 : 0;
  426. }
  427. #endif // BGFX_CONFIG_RENDERER_USE_EXTENSIONS
  428. uint32_t index = 1;
  429. for (const D3DFORMAT* fmt = &s_checkColorFormats[index]; *fmt != D3DFMT_UNKNOWN; ++fmt, ++index)
  430. {
  431. for (; *fmt != D3DFMT_UNKNOWN; ++fmt)
  432. {
  433. if (SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter, m_deviceType, adapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, *fmt) ) )
  434. {
  435. s_colorFormat[index] = *fmt;
  436. break;
  437. }
  438. }
  439. for (; *fmt != D3DFMT_UNKNOWN; ++fmt);
  440. }
  441. m_fmtDepth = D3DFMT_D24S8;
  442. #elif BX_PLATFORM_XBOX360
  443. m_params.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  444. m_params.DisableAutoBackBuffer = FALSE;
  445. m_params.DisableAutoFrontBuffer = FALSE;
  446. m_params.FrontBufferFormat = D3DFMT_X8R8G8B8;
  447. m_params.FrontBufferColorSpace = D3DCOLORSPACE_RGB;
  448. m_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
  449. BX_TRACE("Creating D3D9 %p", m_d3d9);
  450. XVIDEO_MODE videoMode;
  451. XGetVideoMode(&videoMode);
  452. if (!videoMode.fIsWideScreen)
  453. {
  454. m_params.Flags |= D3DPRESENTFLAG_NO_LETTERBOX;
  455. }
  456. BX_TRACE("Creating device");
  457. DX_CHECK(m_d3d9->CreateDevice(m_adapter
  458. , m_deviceType
  459. , NULL
  460. , D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES
  461. , &m_params
  462. , &m_device
  463. ) );
  464. BX_TRACE("Device %p", m_device);
  465. m_fmtDepth = D3DFMT_D24FS8;
  466. #endif // BX_PLATFORM_WINDOWS
  467. postReset();
  468. m_initialized = true;
  469. }
  470. ~RendererContextD3D9()
  471. {
  472. preReset();
  473. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  474. {
  475. m_indexBuffers[ii].destroy();
  476. }
  477. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  478. {
  479. m_vertexBuffers[ii].destroy();
  480. }
  481. for (uint32_t ii = 0; ii < BX_COUNTOF(m_shaders); ++ii)
  482. {
  483. m_shaders[ii].destroy();
  484. }
  485. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  486. {
  487. m_textures[ii].destroy();
  488. }
  489. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexDecls); ++ii)
  490. {
  491. m_vertexDecls[ii].destroy();
  492. }
  493. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  494. if (NULL != m_d3d9ex)
  495. {
  496. DX_RELEASE(m_deviceEx, 1);
  497. DX_RELEASE(m_device, 0);
  498. DX_RELEASE(m_d3d9, 1);
  499. DX_RELEASE(m_d3d9ex, 0);
  500. }
  501. else
  502. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  503. {
  504. DX_RELEASE(m_device, 0);
  505. DX_RELEASE(m_d3d9, 0);
  506. }
  507. #if BX_PLATFORM_WINDOWS
  508. bx::dlclose(m_d3d9dll);
  509. #endif // BX_PLATFORM_WINDOWS
  510. m_initialized = false;
  511. }
  512. RendererType::Enum getRendererType() const BX_OVERRIDE
  513. {
  514. return RendererType::Direct3D9;
  515. }
  516. const char* getRendererName() const BX_OVERRIDE
  517. {
  518. return BGFX_RENDERER_DIRECT3D9_NAME;
  519. }
  520. void createIndexBuffer(IndexBufferHandle _handle, Memory* _mem) BX_OVERRIDE
  521. {
  522. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data);
  523. }
  524. void destroyIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  525. {
  526. m_indexBuffers[_handle.idx].destroy();
  527. }
  528. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) BX_OVERRIDE
  529. {
  530. m_vertexDecls[_handle.idx].create(_decl);
  531. }
  532. void destroyVertexDecl(VertexDeclHandle _handle) BX_OVERRIDE
  533. {
  534. m_vertexDecls[_handle.idx].destroy();
  535. }
  536. void createVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle) BX_OVERRIDE
  537. {
  538. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle);
  539. }
  540. void destroyVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  541. {
  542. m_vertexBuffers[_handle.idx].destroy();
  543. }
  544. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size) BX_OVERRIDE
  545. {
  546. m_indexBuffers[_handle.idx].create(_size, NULL);
  547. }
  548. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  549. {
  550. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  551. }
  552. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  553. {
  554. m_indexBuffers[_handle.idx].destroy();
  555. }
  556. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size) BX_OVERRIDE
  557. {
  558. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  559. m_vertexBuffers[_handle.idx].create(_size, NULL, decl);
  560. }
  561. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  562. {
  563. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  564. }
  565. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  566. {
  567. m_vertexBuffers[_handle.idx].destroy();
  568. }
  569. void createShader(ShaderHandle _handle, Memory* _mem) BX_OVERRIDE
  570. {
  571. m_shaders[_handle.idx].create(_mem);
  572. }
  573. void destroyShader(ShaderHandle _handle) BX_OVERRIDE
  574. {
  575. m_shaders[_handle.idx].destroy();
  576. }
  577. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) BX_OVERRIDE
  578. {
  579. m_program[_handle.idx].create(m_shaders[_vsh.idx], m_shaders[_fsh.idx]);
  580. }
  581. void destroyProgram(ProgramHandle _handle) BX_OVERRIDE
  582. {
  583. m_program[_handle.idx].destroy();
  584. }
  585. void createTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags, uint8_t _skip) BX_OVERRIDE
  586. {
  587. m_textures[_handle.idx].create(_mem, _flags, _skip);
  588. }
  589. void updateTextureBegin(TextureHandle _handle, uint8_t _side, uint8_t _mip) BX_OVERRIDE
  590. {
  591. m_updateTexture = &m_textures[_handle.idx];
  592. m_updateTexture->updateBegin(_side, _mip);
  593. }
  594. void updateTexture(TextureHandle /*_handle*/, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) BX_OVERRIDE
  595. {
  596. m_updateTexture->update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  597. }
  598. void updateTextureEnd() BX_OVERRIDE
  599. {
  600. m_updateTexture->updateEnd();
  601. m_updateTexture = NULL;
  602. }
  603. void destroyTexture(TextureHandle _handle) BX_OVERRIDE
  604. {
  605. m_textures[_handle.idx].destroy();
  606. }
  607. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const TextureHandle* _textureHandles) BX_OVERRIDE
  608. {
  609. m_frameBuffers[_handle.idx].create(_num, _textureHandles);
  610. }
  611. void destroyFrameBuffer(FrameBufferHandle _handle) BX_OVERRIDE
  612. {
  613. m_frameBuffers[_handle.idx].destroy();
  614. }
  615. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) BX_OVERRIDE
  616. {
  617. if (NULL != m_uniforms[_handle.idx])
  618. {
  619. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  620. }
  621. uint32_t size = BX_ALIGN_16(g_uniformTypeSize[_type]*_num);
  622. void* data = BX_ALLOC(g_allocator, size);
  623. memset(data, 0, size);
  624. m_uniforms[_handle.idx] = data;
  625. m_uniformReg.add(_handle, _name, data);
  626. }
  627. void destroyUniform(UniformHandle _handle) BX_OVERRIDE
  628. {
  629. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  630. m_uniforms[_handle.idx] = NULL;
  631. }
  632. void saveScreenShot(const char* _filePath) BX_OVERRIDE
  633. {
  634. #if BX_PLATFORM_WINDOWS
  635. IDirect3DSurface9* surface;
  636. D3DDEVICE_CREATION_PARAMETERS dcp;
  637. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  638. D3DDISPLAYMODE dm;
  639. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  640. DX_CHECK(m_device->CreateOffscreenPlainSurface(dm.Width
  641. , dm.Height
  642. , D3DFMT_A8R8G8B8
  643. , D3DPOOL_SCRATCH
  644. , &surface
  645. , NULL
  646. ) );
  647. DX_CHECK(m_device->GetFrontBufferData(0, surface) );
  648. D3DLOCKED_RECT rect;
  649. DX_CHECK(surface->LockRect(&rect
  650. , NULL
  651. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  652. ) );
  653. RECT rc;
  654. GetClientRect(g_bgfxHwnd, &rc);
  655. POINT point;
  656. point.x = rc.left;
  657. point.y = rc.top;
  658. ClientToScreen(g_bgfxHwnd, &point);
  659. uint8_t* data = (uint8_t*)rect.pBits;
  660. uint32_t bytesPerPixel = rect.Pitch/dm.Width;
  661. g_callback->screenShot(_filePath
  662. , m_params.BackBufferWidth
  663. , m_params.BackBufferHeight
  664. , rect.Pitch
  665. , &data[point.y*rect.Pitch+point.x*bytesPerPixel]
  666. , m_params.BackBufferHeight*rect.Pitch
  667. , false
  668. );
  669. DX_CHECK(surface->UnlockRect() );
  670. DX_RELEASE(surface, 0);
  671. #endif // BX_PLATFORM_WINDOWS
  672. }
  673. void updateViewName(uint8_t _id, const char* _name) BX_OVERRIDE
  674. {
  675. mbstowcs(&s_viewNameW[_id][0], _name, BX_COUNTOF(s_viewNameW[0]) );
  676. }
  677. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) BX_OVERRIDE
  678. {
  679. memcpy(m_uniforms[_loc], _data, _size);
  680. }
  681. void setMarker(const char* _marker, uint32_t _size) BX_OVERRIDE
  682. {
  683. #if BGFX_CONFIG_DEBUG_PIX
  684. uint32_t size = _size*sizeof(wchar_t);
  685. wchar_t* name = (wchar_t*)alloca(size);
  686. mbstowcs(name, _marker, size-2);
  687. PIX_SETMARKER(D3DCOLOR_RGBA(0xff, 0xff, 0xff, 0xff), name);
  688. #endif // BGFX_CONFIG_DEBUG_PIX
  689. BX_UNUSED(_marker, _size);
  690. }
  691. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) BX_OVERRIDE;
  692. void blitSetup(TextVideoMemBlitter& _blitter) BX_OVERRIDE
  693. {
  694. uint32_t width = m_params.BackBufferWidth;
  695. uint32_t height = m_params.BackBufferHeight;
  696. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  697. setFrameBuffer(fbh, false);
  698. D3DVIEWPORT9 vp;
  699. vp.X = 0;
  700. vp.Y = 0;
  701. vp.Width = width;
  702. vp.Height = height;
  703. vp.MinZ = 0.0f;
  704. vp.MaxZ = 1.0f;
  705. IDirect3DDevice9* device = m_device;
  706. DX_CHECK(device->SetViewport(&vp) );
  707. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  708. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, FALSE) );
  709. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS) );
  710. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  711. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  712. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  713. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE) );
  714. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID) );
  715. ProgramD3D9& program = m_program[_blitter.m_program.idx];
  716. DX_CHECK(device->SetVertexShader(program.m_vsh->m_vertexShader) );
  717. DX_CHECK(device->SetPixelShader(program.m_fsh->m_pixelShader) );
  718. VertexBufferD3D9& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  719. VertexDeclaration& vertexDecl = m_vertexDecls[_blitter.m_vb->decl.idx];
  720. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, vertexDecl.m_decl.m_stride) );
  721. DX_CHECK(device->SetVertexDeclaration(vertexDecl.m_ptr) );
  722. IndexBufferD3D9& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  723. DX_CHECK(device->SetIndices(ib.m_ptr) );
  724. float proj[16];
  725. mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  726. PredefinedUniform& predefined = program.m_predefined[0];
  727. uint8_t flags = predefined.m_type;
  728. setShaderConstantF(flags, predefined.m_loc, proj, 4);
  729. m_textures[_blitter.m_texture.idx].commit(0);
  730. }
  731. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) BX_OVERRIDE
  732. {
  733. uint32_t numVertices = _numIndices*4/6;
  734. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices*2, _blitter.m_ib->data, true);
  735. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data, true);
  736. DX_CHECK(m_device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST
  737. , 0
  738. , 0
  739. , numVertices
  740. , 0
  741. , _numIndices/3
  742. ) );
  743. }
  744. void updateMsaa()
  745. {
  746. for (uint32_t ii = 1, last = 0; ii < BX_COUNTOF(s_checkMsaa); ++ii)
  747. {
  748. D3DMULTISAMPLE_TYPE msaa = s_checkMsaa[ii];
  749. DWORD quality;
  750. HRESULT hr = m_d3d9->CheckDeviceMultiSampleType(m_adapter
  751. , m_deviceType
  752. , m_params.BackBufferFormat
  753. , m_params.Windowed
  754. , msaa
  755. , &quality
  756. );
  757. if (SUCCEEDED(hr) )
  758. {
  759. s_msaa[ii].m_type = msaa;
  760. s_msaa[ii].m_quality = bx::uint32_imax(0, quality-1);
  761. last = ii;
  762. }
  763. else
  764. {
  765. s_msaa[ii] = s_msaa[last];
  766. }
  767. }
  768. }
  769. void updateResolution(const Resolution& _resolution)
  770. {
  771. if (m_params.BackBufferWidth != _resolution.m_width
  772. || m_params.BackBufferHeight != _resolution.m_height
  773. || m_flags != _resolution.m_flags)
  774. {
  775. m_flags = _resolution.m_flags;
  776. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  777. m_textVideoMem.clear();
  778. #if BX_PLATFORM_WINDOWS
  779. D3DDEVICE_CREATION_PARAMETERS dcp;
  780. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  781. D3DDISPLAYMODE dm;
  782. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  783. m_params.BackBufferFormat = dm.Format;
  784. #endif // BX_PLATFORM_WINDOWS
  785. m_params.BackBufferWidth = _resolution.m_width;
  786. m_params.BackBufferHeight = _resolution.m_height;
  787. m_params.FullScreen_RefreshRateInHz = BGFX_RESET_FULLSCREEN == (m_flags&BGFX_RESET_FULLSCREEN_MASK) ? 60 : 0;
  788. m_params.PresentationInterval = !!(m_flags&BGFX_RESET_VSYNC) ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
  789. updateMsaa();
  790. Msaa& msaa = s_msaa[(m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT];
  791. m_params.MultiSampleType = msaa.m_type;
  792. m_params.MultiSampleQuality = msaa.m_quality;
  793. m_resolution = _resolution;
  794. preReset();
  795. DX_CHECK(m_device->Reset(&m_params) );
  796. postReset();
  797. }
  798. }
  799. void setFrameBuffer(FrameBufferHandle _fbh, bool _msaa = true)
  800. {
  801. if (!isValid(_fbh) )
  802. {
  803. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  804. for (uint32_t ii = 1, num = g_caps.maxFBAttachments; ii < num; ++ii)
  805. {
  806. DX_CHECK(m_device->SetRenderTarget(ii, NULL) );
  807. }
  808. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  809. }
  810. else
  811. {
  812. const FrameBufferD3D9& frameBuffer = m_frameBuffers[_fbh.idx];
  813. // If frame buffer has only depth attachement D3DFMT_NULL
  814. // render target is created.
  815. uint32_t fbnum = bx::uint32_max(1, frameBuffer.m_num);
  816. for (uint32_t ii = 0; ii < fbnum; ++ii)
  817. {
  818. DX_CHECK(m_device->SetRenderTarget(ii, frameBuffer.m_color[ii]) );
  819. }
  820. for (uint32_t ii = fbnum, num = g_caps.maxFBAttachments; ii < num; ++ii)
  821. {
  822. DX_CHECK(m_device->SetRenderTarget(ii, NULL) );
  823. }
  824. IDirect3DSurface9* depthStencil = frameBuffer.m_depthStencil;
  825. DX_CHECK(m_device->SetDepthStencilSurface(NULL != depthStencil ? depthStencil : m_backBufferDepthStencil) );
  826. }
  827. if (isValid(m_fbh)
  828. && m_fbh.idx != _fbh.idx
  829. && m_rtMsaa)
  830. {
  831. FrameBufferD3D9& frameBuffer = m_frameBuffers[m_fbh.idx];
  832. frameBuffer.resolve();
  833. }
  834. m_fbh = _fbh;
  835. m_rtMsaa = _msaa;
  836. }
  837. void setShaderConstantF(uint8_t _flags, uint16_t _regIndex, const float* _val, uint16_t _numRegs)
  838. {
  839. if (_flags&BGFX_UNIFORM_FRAGMENTBIT)
  840. {
  841. DX_CHECK(m_device->SetPixelShaderConstantF(_regIndex, _val, _numRegs) );
  842. }
  843. else
  844. {
  845. DX_CHECK(m_device->SetVertexShaderConstantF(_regIndex, _val, _numRegs) );
  846. }
  847. }
  848. void reset()
  849. {
  850. preReset();
  851. HRESULT hr;
  852. do
  853. {
  854. hr = m_device->Reset(&m_params);
  855. } while (FAILED(hr) );
  856. postReset();
  857. }
  858. bool isLost(HRESULT _hr) const
  859. {
  860. return D3DERR_DEVICELOST == _hr
  861. || D3DERR_DRIVERINTERNALERROR == _hr
  862. #if !defined(D3D_DISABLE_9EX)
  863. || D3DERR_DEVICEHUNG == _hr
  864. || D3DERR_DEVICEREMOVED == _hr
  865. #endif // !defined(D3D_DISABLE_9EX)
  866. ;
  867. }
  868. void flip() BX_OVERRIDE
  869. {
  870. if (NULL != m_device)
  871. {
  872. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  873. if (NULL != m_deviceEx)
  874. {
  875. DX_CHECK(m_deviceEx->WaitForVBlank(0) );
  876. }
  877. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  878. HRESULT hr;
  879. hr = m_device->Present(NULL, NULL, NULL, NULL);
  880. #if BX_PLATFORM_WINDOWS
  881. if (isLost(hr) )
  882. {
  883. do
  884. {
  885. do
  886. {
  887. hr = m_device->TestCooperativeLevel();
  888. }
  889. while (D3DERR_DEVICENOTRESET != hr);
  890. reset();
  891. hr = m_device->TestCooperativeLevel();
  892. }
  893. while (FAILED(hr) );
  894. }
  895. else if (FAILED(hr) )
  896. {
  897. BX_TRACE("Present failed with err 0x%08x.", hr);
  898. }
  899. #endif // BX_PLATFORM_
  900. }
  901. }
  902. void preReset()
  903. {
  904. invalidateSamplerState();
  905. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  906. {
  907. DX_CHECK(m_device->SetTexture(stage, NULL) );
  908. }
  909. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  910. for (uint32_t ii = 1, num = g_caps.maxFBAttachments; ii < num; ++ii)
  911. {
  912. DX_CHECK(m_device->SetRenderTarget(ii, NULL) );
  913. }
  914. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  915. DX_CHECK(m_device->SetVertexShader(NULL) );
  916. DX_CHECK(m_device->SetPixelShader(NULL) );
  917. DX_CHECK(m_device->SetStreamSource(0, NULL, 0, 0) );
  918. DX_CHECK(m_device->SetIndices(NULL) );
  919. DX_RELEASE(m_backBufferColor, 0);
  920. DX_RELEASE(m_backBufferDepthStencil, 0);
  921. capturePreReset();
  922. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  923. {
  924. m_indexBuffers[ii].preReset();
  925. }
  926. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  927. {
  928. m_vertexBuffers[ii].preReset();
  929. }
  930. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  931. {
  932. m_frameBuffers[ii].preReset();
  933. }
  934. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  935. {
  936. m_textures[ii].preReset();
  937. }
  938. }
  939. void postReset()
  940. {
  941. DX_CHECK(m_device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &m_backBufferColor) );
  942. DX_CHECK(m_device->GetDepthStencilSurface(&m_backBufferDepthStencil) );
  943. capturePostReset();
  944. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  945. {
  946. m_indexBuffers[ii].postReset();
  947. }
  948. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  949. {
  950. m_vertexBuffers[ii].postReset();
  951. }
  952. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  953. {
  954. m_textures[ii].postReset();
  955. }
  956. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  957. {
  958. m_frameBuffers[ii].postReset();
  959. }
  960. }
  961. void invalidateSamplerState()
  962. {
  963. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  964. {
  965. m_samplerFlags[stage] = UINT32_MAX;
  966. }
  967. }
  968. void setSamplerState(uint8_t _stage, uint32_t _flags)
  969. {
  970. const uint32_t flags = _flags&( (~BGFX_TEXTURE_RESERVED_MASK) | BGFX_TEXTURE_SAMPLER_BITS_MASK);
  971. if (m_samplerFlags[_stage] != flags)
  972. {
  973. m_samplerFlags[_stage] = flags;
  974. IDirect3DDevice9* device = m_device;
  975. D3DTEXTUREADDRESS tau = s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT];
  976. D3DTEXTUREADDRESS tav = s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT];
  977. D3DTEXTUREADDRESS taw = s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT];
  978. D3DTEXTUREFILTERTYPE minFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT];
  979. D3DTEXTUREFILTERTYPE magFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT];
  980. D3DTEXTUREFILTERTYPE mipFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT];
  981. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_ADDRESSU, tau) );
  982. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_ADDRESSV, tav) );
  983. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_MINFILTER, minFilter) );
  984. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_MAGFILTER, magFilter) );
  985. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_MIPFILTER, mipFilter) );
  986. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_ADDRESSW, taw) );
  987. }
  988. }
  989. void capturePreReset()
  990. {
  991. if (NULL != m_captureSurface)
  992. {
  993. g_callback->captureEnd();
  994. }
  995. DX_RELEASE(m_captureSurface, 1);
  996. DX_RELEASE(m_captureTexture, 0);
  997. DX_RELEASE(m_captureResolve, 0);
  998. }
  999. void capturePostReset()
  1000. {
  1001. if (m_flags&BGFX_RESET_CAPTURE)
  1002. {
  1003. uint32_t width = m_params.BackBufferWidth;
  1004. uint32_t height = m_params.BackBufferHeight;
  1005. D3DFORMAT fmt = m_params.BackBufferFormat;
  1006. DX_CHECK(m_device->CreateTexture(width
  1007. , height
  1008. , 1
  1009. , 0
  1010. , fmt
  1011. , D3DPOOL_SYSTEMMEM
  1012. , &m_captureTexture
  1013. , NULL
  1014. ) );
  1015. DX_CHECK(m_captureTexture->GetSurfaceLevel(0
  1016. , &m_captureSurface
  1017. ) );
  1018. if (m_params.MultiSampleType != D3DMULTISAMPLE_NONE)
  1019. {
  1020. DX_CHECK(m_device->CreateRenderTarget(width
  1021. , height
  1022. , fmt
  1023. , D3DMULTISAMPLE_NONE
  1024. , 0
  1025. , false
  1026. , &m_captureResolve
  1027. , NULL
  1028. ) );
  1029. }
  1030. g_callback->captureBegin(width, height, width*4, TextureFormat::BGRA8, false);
  1031. }
  1032. }
  1033. void capture()
  1034. {
  1035. if (NULL != m_captureSurface)
  1036. {
  1037. IDirect3DSurface9* resolve = m_backBufferColor;
  1038. if (NULL != m_captureResolve)
  1039. {
  1040. resolve = m_captureResolve;
  1041. DX_CHECK(m_device->StretchRect(m_backBufferColor
  1042. , 0
  1043. , m_captureResolve
  1044. , NULL
  1045. , D3DTEXF_NONE
  1046. ) );
  1047. }
  1048. HRESULT hr = m_device->GetRenderTargetData(resolve, m_captureSurface);
  1049. if (SUCCEEDED(hr) )
  1050. {
  1051. D3DLOCKED_RECT rect;
  1052. DX_CHECK(m_captureSurface->LockRect(&rect
  1053. , NULL
  1054. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  1055. ) );
  1056. g_callback->captureFrame(rect.pBits, m_params.BackBufferHeight*rect.Pitch);
  1057. DX_CHECK(m_captureSurface->UnlockRect() );
  1058. }
  1059. }
  1060. }
  1061. void commit(ConstantBuffer& _constantBuffer)
  1062. {
  1063. _constantBuffer.reset();
  1064. IDirect3DDevice9* device = m_device;
  1065. for (;;)
  1066. {
  1067. uint32_t opcode = _constantBuffer.read();
  1068. if (UniformType::End == opcode)
  1069. {
  1070. break;
  1071. }
  1072. UniformType::Enum type;
  1073. uint16_t loc;
  1074. uint16_t num;
  1075. uint16_t copy;
  1076. ConstantBuffer::decodeOpcode(opcode, type, loc, num, copy);
  1077. const char* data;
  1078. if (copy)
  1079. {
  1080. data = _constantBuffer.read(g_uniformTypeSize[type]*num);
  1081. }
  1082. else
  1083. {
  1084. UniformHandle handle;
  1085. memcpy(&handle, _constantBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  1086. data = (const char*)m_uniforms[handle.idx];
  1087. }
  1088. #define CASE_IMPLEMENT_UNIFORM(_uniform, _dxsuffix, _type) \
  1089. case UniformType::_uniform: \
  1090. { \
  1091. _type* value = (_type*)data; \
  1092. DX_CHECK(device->SetVertexShaderConstant##_dxsuffix(loc, value, num) ); \
  1093. } \
  1094. break; \
  1095. \
  1096. case UniformType::_uniform|BGFX_UNIFORM_FRAGMENTBIT: \
  1097. { \
  1098. _type* value = (_type*)data; \
  1099. DX_CHECK(device->SetPixelShaderConstant##_dxsuffix(loc, value, num) ); \
  1100. } \
  1101. break
  1102. switch ( (int32_t)type)
  1103. {
  1104. case UniformType::Uniform3x3fv:
  1105. {
  1106. float* value = (float*)data;
  1107. for (uint32_t ii = 0, count = num/3; ii < count; ++ii, loc += 3, value += 9)
  1108. {
  1109. Matrix4 mtx;
  1110. mtx.un.val[ 0] = value[0];
  1111. mtx.un.val[ 1] = value[1];
  1112. mtx.un.val[ 2] = value[2];
  1113. mtx.un.val[ 3] = 0.0f;
  1114. mtx.un.val[ 4] = value[3];
  1115. mtx.un.val[ 5] = value[4];
  1116. mtx.un.val[ 6] = value[5];
  1117. mtx.un.val[ 7] = 0.0f;
  1118. mtx.un.val[ 8] = value[6];
  1119. mtx.un.val[ 9] = value[7];
  1120. mtx.un.val[10] = value[8];
  1121. mtx.un.val[11] = 0.0f;
  1122. DX_CHECK(device->SetVertexShaderConstantF(loc, &mtx.un.val[0], 3) );
  1123. }
  1124. }
  1125. break;
  1126. case UniformType::Uniform3x3fv|BGFX_UNIFORM_FRAGMENTBIT:
  1127. {
  1128. float* value = (float*)data;
  1129. for (uint32_t ii = 0, count = num/3; ii < count; ++ii, loc += 3, value += 9)
  1130. {
  1131. Matrix4 mtx;
  1132. mtx.un.val[ 0] = value[0];
  1133. mtx.un.val[ 1] = value[1];
  1134. mtx.un.val[ 2] = value[2];
  1135. mtx.un.val[ 3] = 0.0f;
  1136. mtx.un.val[ 4] = value[3];
  1137. mtx.un.val[ 5] = value[4];
  1138. mtx.un.val[ 6] = value[5];
  1139. mtx.un.val[ 7] = 0.0f;
  1140. mtx.un.val[ 8] = value[6];
  1141. mtx.un.val[ 9] = value[7];
  1142. mtx.un.val[10] = value[8];
  1143. mtx.un.val[11] = 0.0f;
  1144. DX_CHECK(device->SetPixelShaderConstantF(loc, &mtx.un.val[0], 3) );
  1145. }
  1146. }
  1147. break;
  1148. CASE_IMPLEMENT_UNIFORM(Uniform1i, I, int);
  1149. CASE_IMPLEMENT_UNIFORM(Uniform1f, F, float);
  1150. CASE_IMPLEMENT_UNIFORM(Uniform1iv, I, int);
  1151. CASE_IMPLEMENT_UNIFORM(Uniform1fv, F, float);
  1152. CASE_IMPLEMENT_UNIFORM(Uniform2fv, F, float);
  1153. CASE_IMPLEMENT_UNIFORM(Uniform3fv, F, float);
  1154. CASE_IMPLEMENT_UNIFORM(Uniform4fv, F, float);
  1155. CASE_IMPLEMENT_UNIFORM(Uniform4x4fv, F, float);
  1156. case UniformType::End:
  1157. break;
  1158. default:
  1159. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _constantBuffer.getPos(), opcode, type, loc, num, copy);
  1160. break;
  1161. }
  1162. #undef CASE_IMPLEMENT_UNIFORM
  1163. }
  1164. }
  1165. #if BX_PLATFORM_WINDOWS
  1166. D3DCAPS9 m_caps;
  1167. # if BGFX_CONFIG_DEBUG_PIX
  1168. D3DPERF_SetMarkerFunc m_D3DPERF_SetMarker;
  1169. D3DPERF_BeginEventFunc m_D3DPERF_BeginEvent;
  1170. D3DPERF_EndEventFunc m_D3DPERF_EndEvent;
  1171. # endif // BGFX_CONFIG_DEBUG_PIX
  1172. #endif // BX_PLATFORM_WINDOWS
  1173. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  1174. IDirect3D9Ex* m_d3d9ex;
  1175. IDirect3DDevice9Ex* m_deviceEx;
  1176. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  1177. IDirect3D9* m_d3d9;
  1178. IDirect3DDevice9* m_device;
  1179. D3DPOOL m_pool;
  1180. IDirect3DSurface9* m_backBufferColor;
  1181. IDirect3DSurface9* m_backBufferDepthStencil;
  1182. IDirect3DTexture9* m_captureTexture;
  1183. IDirect3DSurface9* m_captureSurface;
  1184. IDirect3DSurface9* m_captureResolve;
  1185. IDirect3DVertexDeclaration9* m_instanceDataDecls[BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  1186. void* m_d3d9dll;
  1187. uint32_t m_adapter;
  1188. D3DDEVTYPE m_deviceType;
  1189. D3DPRESENT_PARAMETERS m_params;
  1190. uint32_t m_flags;
  1191. D3DADAPTER_IDENTIFIER9 m_identifier;
  1192. Resolution m_resolution;
  1193. bool m_initialized;
  1194. bool m_amd;
  1195. bool m_nvidia;
  1196. bool m_instancing;
  1197. D3DFORMAT m_fmtDepth;
  1198. IndexBufferD3D9 m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  1199. VertexBufferD3D9 m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  1200. ShaderD3D9 m_shaders[BGFX_CONFIG_MAX_SHADERS];
  1201. ProgramD3D9 m_program[BGFX_CONFIG_MAX_PROGRAMS];
  1202. TextureD3D9 m_textures[BGFX_CONFIG_MAX_TEXTURES];
  1203. VertexDeclaration m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  1204. FrameBufferD3D9 m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1205. UniformRegistry m_uniformReg;
  1206. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  1207. uint32_t m_samplerFlags[BGFX_CONFIG_MAX_TEXTURE_SAMPLERS];
  1208. TextureD3D9* m_updateTexture;
  1209. uint8_t* m_updateTextureBits;
  1210. uint32_t m_updateTexturePitch;
  1211. uint8_t m_updateTextureSide;
  1212. uint8_t m_updateTextureMip;
  1213. TextVideoMem m_textVideoMem;
  1214. FrameBufferHandle m_fbh;
  1215. bool m_rtMsaa;
  1216. };
  1217. static RendererContextD3D9* s_renderD3D9;
  1218. RendererContextI* rendererCreateD3D9()
  1219. {
  1220. s_renderD3D9 = BX_NEW(g_allocator, RendererContextD3D9);
  1221. return s_renderD3D9;
  1222. }
  1223. void rendererDestroyD3D9()
  1224. {
  1225. BX_DELETE(g_allocator, s_renderD3D9);
  1226. s_renderD3D9 = NULL;
  1227. }
  1228. void IndexBufferD3D9::create(uint32_t _size, void* _data)
  1229. {
  1230. m_size = _size;
  1231. m_dynamic = NULL == _data;
  1232. uint32_t usage = D3DUSAGE_WRITEONLY;
  1233. D3DPOOL pool = s_renderD3D9->m_pool;
  1234. if (m_dynamic)
  1235. {
  1236. usage |= D3DUSAGE_DYNAMIC;
  1237. pool = D3DPOOL_DEFAULT;
  1238. }
  1239. DX_CHECK(s_renderD3D9->m_device->CreateIndexBuffer(m_size
  1240. , usage
  1241. , D3DFMT_INDEX16
  1242. , pool
  1243. , &m_ptr
  1244. , NULL
  1245. ) );
  1246. if (NULL != _data)
  1247. {
  1248. update(0, _size, _data);
  1249. }
  1250. }
  1251. void IndexBufferD3D9::preReset()
  1252. {
  1253. if (m_dynamic)
  1254. {
  1255. DX_RELEASE(m_ptr, 0);
  1256. }
  1257. }
  1258. void IndexBufferD3D9::postReset()
  1259. {
  1260. if (m_dynamic)
  1261. {
  1262. DX_CHECK(s_renderD3D9->m_device->CreateIndexBuffer(m_size
  1263. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  1264. , D3DFMT_INDEX16
  1265. , D3DPOOL_DEFAULT
  1266. , &m_ptr
  1267. , NULL
  1268. ) );
  1269. }
  1270. }
  1271. void VertexBufferD3D9::create(uint32_t _size, void* _data, VertexDeclHandle _declHandle)
  1272. {
  1273. m_size = _size;
  1274. m_decl = _declHandle;
  1275. m_dynamic = NULL == _data;
  1276. uint32_t usage = D3DUSAGE_WRITEONLY;
  1277. D3DPOOL pool = s_renderD3D9->m_pool;
  1278. if (m_dynamic)
  1279. {
  1280. usage |= D3DUSAGE_DYNAMIC;
  1281. pool = D3DPOOL_DEFAULT;
  1282. }
  1283. DX_CHECK(s_renderD3D9->m_device->CreateVertexBuffer(m_size
  1284. , usage
  1285. , 0
  1286. , pool
  1287. , &m_ptr
  1288. , NULL
  1289. ) );
  1290. if (NULL != _data)
  1291. {
  1292. update(0, _size, _data);
  1293. }
  1294. }
  1295. void VertexBufferD3D9::preReset()
  1296. {
  1297. if (m_dynamic)
  1298. {
  1299. DX_RELEASE(m_ptr, 0);
  1300. }
  1301. }
  1302. void VertexBufferD3D9::postReset()
  1303. {
  1304. if (m_dynamic)
  1305. {
  1306. DX_CHECK(s_renderD3D9->m_device->CreateVertexBuffer(m_size
  1307. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  1308. , 0
  1309. , D3DPOOL_DEFAULT
  1310. , &m_ptr
  1311. , NULL
  1312. ) );
  1313. }
  1314. }
  1315. static const D3DVERTEXELEMENT9 s_attrib[Attrib::Count+1] =
  1316. {
  1317. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
  1318. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
  1319. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 },
  1320. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
  1321. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 1 },
  1322. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
  1323. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
  1324. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
  1325. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
  1326. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 },
  1327. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 },
  1328. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 },
  1329. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 },
  1330. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 6 },
  1331. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 7 },
  1332. D3DDECL_END()
  1333. };
  1334. static const D3DDECLTYPE s_attribType[AttribType::Count][4][2] =
  1335. {
  1336. {
  1337. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1338. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1339. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1340. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1341. },
  1342. {
  1343. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  1344. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  1345. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  1346. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  1347. },
  1348. {
  1349. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  1350. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  1351. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  1352. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  1353. },
  1354. {
  1355. { D3DDECLTYPE_FLOAT1, D3DDECLTYPE_FLOAT1 },
  1356. { D3DDECLTYPE_FLOAT2, D3DDECLTYPE_FLOAT2 },
  1357. { D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT3 },
  1358. { D3DDECLTYPE_FLOAT4, D3DDECLTYPE_FLOAT4 },
  1359. },
  1360. };
  1361. static D3DVERTEXELEMENT9* fillVertexDecl(D3DVERTEXELEMENT9* _out, const VertexDecl& _decl)
  1362. {
  1363. D3DVERTEXELEMENT9* elem = _out;
  1364. for (uint32_t attr = 0; attr < Attrib::Count; ++attr)
  1365. {
  1366. if (0xff != _decl.m_attributes[attr])
  1367. {
  1368. uint8_t num;
  1369. AttribType::Enum type;
  1370. bool normalized;
  1371. bool asInt;
  1372. _decl.decode(Attrib::Enum(attr), num, type, normalized, asInt);
  1373. memcpy(elem, &s_attrib[attr], sizeof(D3DVERTEXELEMENT9) );
  1374. elem->Type = s_attribType[type][num-1][normalized];
  1375. elem->Offset = _decl.m_offset[attr];
  1376. ++elem;
  1377. }
  1378. }
  1379. return elem;
  1380. }
  1381. static IDirect3DVertexDeclaration9* createVertexDeclaration(const VertexDecl& _decl, uint8_t _numInstanceData)
  1382. {
  1383. D3DVERTEXELEMENT9 vertexElements[Attrib::Count+1+BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  1384. D3DVERTEXELEMENT9* elem = fillVertexDecl(vertexElements, _decl);
  1385. const D3DVERTEXELEMENT9 inst = { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 };
  1386. for (uint32_t ii = 0; ii < _numInstanceData; ++ii)
  1387. {
  1388. memcpy(elem, &inst, sizeof(D3DVERTEXELEMENT9) );
  1389. elem->UsageIndex = 8-_numInstanceData+ii;
  1390. elem->Offset = ii*16;
  1391. ++elem;
  1392. }
  1393. memcpy(elem, &s_attrib[Attrib::Count], sizeof(D3DVERTEXELEMENT9) );
  1394. IDirect3DVertexDeclaration9* ptr;
  1395. DX_CHECK(s_renderD3D9->m_device->CreateVertexDeclaration(vertexElements, &ptr) );
  1396. return ptr;
  1397. }
  1398. void VertexDeclaration::create(const VertexDecl& _decl)
  1399. {
  1400. memcpy(&m_decl, &_decl, sizeof(VertexDecl) );
  1401. dump(m_decl);
  1402. m_ptr = createVertexDeclaration(_decl, 0);
  1403. }
  1404. void ShaderD3D9::create(const Memory* _mem)
  1405. {
  1406. bx::MemoryReader reader(_mem->data, _mem->size);
  1407. uint32_t magic;
  1408. bx::read(&reader, magic);
  1409. switch (magic)
  1410. {
  1411. case BGFX_CHUNK_MAGIC_FSH:
  1412. case BGFX_CHUNK_MAGIC_VSH:
  1413. break;
  1414. default:
  1415. BGFX_FATAL(false, Fatal::InvalidShader, "Unknown shader format %x.", magic);
  1416. break;
  1417. }
  1418. bool fragment = BGFX_CHUNK_MAGIC_FSH == magic;
  1419. uint32_t iohash;
  1420. bx::read(&reader, iohash);
  1421. uint16_t count;
  1422. bx::read(&reader, count);
  1423. m_numPredefined = 0;
  1424. BX_TRACE("Shader consts %d", count);
  1425. uint8_t fragmentBit = fragment ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  1426. if (0 < count)
  1427. {
  1428. m_constantBuffer = ConstantBuffer::create(1024);
  1429. for (uint32_t ii = 0; ii < count; ++ii)
  1430. {
  1431. uint8_t nameSize;
  1432. bx::read(&reader, nameSize);
  1433. char name[256];
  1434. bx::read(&reader, &name, nameSize);
  1435. name[nameSize] = '\0';
  1436. uint8_t type;
  1437. bx::read(&reader, type);
  1438. uint8_t num;
  1439. bx::read(&reader, num);
  1440. uint16_t regIndex;
  1441. bx::read(&reader, regIndex);
  1442. uint16_t regCount;
  1443. bx::read(&reader, regCount);
  1444. const char* kind = "invalid";
  1445. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  1446. if (PredefinedUniform::Count != predefined)
  1447. {
  1448. kind = "predefined";
  1449. m_predefined[m_numPredefined].m_loc = regIndex;
  1450. m_predefined[m_numPredefined].m_count = regCount;
  1451. m_predefined[m_numPredefined].m_type = predefined|fragmentBit;
  1452. m_numPredefined++;
  1453. }
  1454. else
  1455. {
  1456. const UniformInfo* info = s_renderD3D9->m_uniformReg.find(name);
  1457. BX_CHECK(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  1458. if (NULL != info)
  1459. {
  1460. kind = "user";
  1461. m_constantBuffer->writeUniformHandle( (UniformType::Enum)(type|fragmentBit), regIndex, info->m_handle, regCount);
  1462. }
  1463. }
  1464. BX_TRACE("\t%s: %s, type %2d, num %2d, r.index %3d, r.count %2d"
  1465. , kind
  1466. , name
  1467. , type
  1468. , num
  1469. , regIndex
  1470. , regCount
  1471. );
  1472. BX_UNUSED(kind);
  1473. }
  1474. m_constantBuffer->finish();
  1475. }
  1476. uint16_t shaderSize;
  1477. bx::read(&reader, shaderSize);
  1478. const DWORD* code = (const DWORD*)reader.getDataPtr();
  1479. if (fragment)
  1480. {
  1481. m_type = 1;
  1482. DX_CHECK(s_renderD3D9->m_device->CreatePixelShader(code, &m_pixelShader) );
  1483. BGFX_FATAL(NULL != m_pixelShader, bgfx::Fatal::InvalidShader, "Failed to create fragment shader.");
  1484. }
  1485. else
  1486. {
  1487. m_type = 0;
  1488. DX_CHECK(s_renderD3D9->m_device->CreateVertexShader(code, &m_vertexShader) );
  1489. BGFX_FATAL(NULL != m_vertexShader, bgfx::Fatal::InvalidShader, "Failed to create vertex shader.");
  1490. }
  1491. }
  1492. void TextureD3D9::createTexture(uint32_t _width, uint32_t _height, uint8_t _numMips)
  1493. {
  1494. m_width = (uint16_t)_width;
  1495. m_height = (uint16_t)_height;
  1496. m_numMips = _numMips;
  1497. m_type = Texture2D;
  1498. const TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  1499. DWORD usage = 0;
  1500. D3DPOOL pool = s_renderD3D9->m_pool;
  1501. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  1502. if (isDepth(fmt) )
  1503. {
  1504. usage = D3DUSAGE_DEPTHSTENCIL;
  1505. pool = D3DPOOL_DEFAULT;
  1506. }
  1507. else if (renderTarget)
  1508. {
  1509. usage = D3DUSAGE_RENDERTARGET;
  1510. pool = D3DPOOL_DEFAULT;
  1511. }
  1512. if (renderTarget)
  1513. {
  1514. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  1515. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  1516. bool bufferOnly = 0 != (m_flags&BGFX_TEXTURE_RT_BUFFER_ONLY);
  1517. if (0 != msaaQuality
  1518. || bufferOnly)
  1519. {
  1520. const Msaa& msaa = s_msaa[msaaQuality];
  1521. if (isDepth(fmt) )
  1522. {
  1523. DX_CHECK(s_renderD3D9->m_device->CreateDepthStencilSurface(
  1524. m_width
  1525. , m_height
  1526. , s_textureFormat[m_textureFormat].m_fmt
  1527. , msaa.m_type
  1528. , msaa.m_quality
  1529. , FALSE
  1530. , &m_surface
  1531. , NULL
  1532. ) );
  1533. }
  1534. else
  1535. {
  1536. DX_CHECK(s_renderD3D9->m_device->CreateRenderTarget(
  1537. m_width
  1538. , m_height
  1539. , s_textureFormat[m_textureFormat].m_fmt
  1540. , msaa.m_type
  1541. , msaa.m_quality
  1542. , FALSE
  1543. , &m_surface
  1544. , NULL
  1545. ) );
  1546. }
  1547. if (bufferOnly)
  1548. {
  1549. // This is render buffer, there is no sampling, no need
  1550. // to create texture.
  1551. return;
  1552. }
  1553. }
  1554. }
  1555. DX_CHECK(s_renderD3D9->m_device->CreateTexture(_width
  1556. , _height
  1557. , _numMips
  1558. , usage
  1559. , s_textureFormat[fmt].m_fmt
  1560. , pool
  1561. , &m_texture2d
  1562. , NULL
  1563. ) );
  1564. BGFX_FATAL(NULL != m_texture2d, Fatal::UnableToCreateTexture, "Failed to create texture (size: %dx%d, mips: %d, fmt: %d)."
  1565. , _width
  1566. , _height
  1567. , _numMips
  1568. , getName(fmt)
  1569. );
  1570. }
  1571. void TextureD3D9::createVolumeTexture(uint32_t _width, uint32_t _height, uint32_t _depth, uint32_t _numMips)
  1572. {
  1573. m_type = Texture3D;
  1574. const TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  1575. DX_CHECK(s_renderD3D9->m_device->CreateVolumeTexture(_width
  1576. , _height
  1577. , _depth
  1578. , _numMips
  1579. , 0
  1580. , s_textureFormat[fmt].m_fmt
  1581. , s_renderD3D9->m_pool
  1582. , &m_texture3d
  1583. , NULL
  1584. ) );
  1585. BGFX_FATAL(NULL != m_texture3d, Fatal::UnableToCreateTexture, "Failed to create volume texture (size: %dx%dx%d, mips: %d, fmt: %s)."
  1586. , _width
  1587. , _height
  1588. , _depth
  1589. , _numMips
  1590. , getName(fmt)
  1591. );
  1592. }
  1593. void TextureD3D9::createCubeTexture(uint32_t _edge, uint32_t _numMips)
  1594. {
  1595. m_type = TextureCube;
  1596. const TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  1597. DX_CHECK(s_renderD3D9->m_device->CreateCubeTexture(_edge
  1598. , _numMips
  1599. , 0
  1600. , s_textureFormat[fmt].m_fmt
  1601. , s_renderD3D9->m_pool
  1602. , &m_textureCube
  1603. , NULL
  1604. ) );
  1605. BGFX_FATAL(NULL != m_textureCube, Fatal::UnableToCreateTexture, "Failed to create cube texture (edge: %d, mips: %d, fmt: %s)."
  1606. , _edge
  1607. , _numMips
  1608. , getName(fmt)
  1609. );
  1610. }
  1611. uint8_t* TextureD3D9::lock(uint8_t _side, uint8_t _lod, uint32_t& _pitch, uint32_t& _slicePitch, const Rect* _rect)
  1612. {
  1613. switch (m_type)
  1614. {
  1615. case Texture2D:
  1616. {
  1617. D3DLOCKED_RECT lockedRect;
  1618. if (NULL != _rect)
  1619. {
  1620. RECT rect;
  1621. rect.left = _rect->m_x;
  1622. rect.top = _rect->m_y;
  1623. rect.right = rect.left + _rect->m_width;
  1624. rect.bottom = rect.top + _rect->m_height;
  1625. DX_CHECK(m_texture2d->LockRect(_lod, &lockedRect, &rect, 0) );
  1626. }
  1627. else
  1628. {
  1629. DX_CHECK(m_texture2d->LockRect(_lod, &lockedRect, NULL, 0) );
  1630. }
  1631. _pitch = lockedRect.Pitch;
  1632. _slicePitch = 0;
  1633. return (uint8_t*)lockedRect.pBits;
  1634. }
  1635. case Texture3D:
  1636. {
  1637. D3DLOCKED_BOX box;
  1638. DX_CHECK(m_texture3d->LockBox(_lod, &box, NULL, 0) );
  1639. _pitch = box.RowPitch;
  1640. _slicePitch = box.SlicePitch;
  1641. return (uint8_t*)box.pBits;
  1642. }
  1643. case TextureCube:
  1644. {
  1645. D3DLOCKED_RECT lockedRect;
  1646. if (NULL != _rect)
  1647. {
  1648. RECT rect;
  1649. rect.left = _rect->m_x;
  1650. rect.top = _rect->m_y;
  1651. rect.right = rect.left + _rect->m_width;
  1652. rect.bottom = rect.top + _rect->m_height;
  1653. DX_CHECK(m_textureCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, &rect, 0) );
  1654. }
  1655. else
  1656. {
  1657. DX_CHECK(m_textureCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, NULL, 0) );
  1658. }
  1659. _pitch = lockedRect.Pitch;
  1660. _slicePitch = 0;
  1661. return (uint8_t*)lockedRect.pBits;
  1662. }
  1663. }
  1664. BX_CHECK(false, "You should not be here.");
  1665. _pitch = 0;
  1666. _slicePitch = 0;
  1667. return NULL;
  1668. }
  1669. void TextureD3D9::unlock(uint8_t _side, uint8_t _lod)
  1670. {
  1671. switch (m_type)
  1672. {
  1673. case Texture2D:
  1674. {
  1675. DX_CHECK(m_texture2d->UnlockRect(_lod) );
  1676. }
  1677. return;
  1678. case Texture3D:
  1679. {
  1680. DX_CHECK(m_texture3d->UnlockBox(_lod) );
  1681. }
  1682. return;
  1683. case TextureCube:
  1684. {
  1685. DX_CHECK(m_textureCube->UnlockRect(D3DCUBEMAP_FACES(_side), _lod) );
  1686. }
  1687. return;
  1688. }
  1689. BX_CHECK(false, "You should not be here.");
  1690. }
  1691. void TextureD3D9::dirty(uint8_t _side, const Rect& _rect, uint16_t _z, uint16_t _depth)
  1692. {
  1693. switch (m_type)
  1694. {
  1695. case Texture2D:
  1696. {
  1697. RECT rect;
  1698. rect.left = _rect.m_x;
  1699. rect.top = _rect.m_y;
  1700. rect.right = rect.left + _rect.m_width;
  1701. rect.bottom = rect.top + _rect.m_height;
  1702. DX_CHECK(m_texture2d->AddDirtyRect(&rect) );
  1703. }
  1704. return;
  1705. case Texture3D:
  1706. {
  1707. D3DBOX box;
  1708. box.Left = _rect.m_x;
  1709. box.Top = _rect.m_y;
  1710. box.Right = box.Left + _rect.m_width;
  1711. box.Bottom = box.Top + _rect.m_height;
  1712. box.Front = _z;
  1713. box.Back = box.Front + _depth;
  1714. DX_CHECK(m_texture3d->AddDirtyBox(&box) );
  1715. }
  1716. return;
  1717. case TextureCube:
  1718. {
  1719. RECT rect;
  1720. rect.left = _rect.m_x;
  1721. rect.top = _rect.m_y;
  1722. rect.right = rect.left + _rect.m_width;
  1723. rect.bottom = rect.top + _rect.m_height;
  1724. DX_CHECK(m_textureCube->AddDirtyRect(D3DCUBEMAP_FACES(_side), &rect) );
  1725. }
  1726. return;
  1727. }
  1728. BX_CHECK(false, "You should not be here.");
  1729. }
  1730. void TextureD3D9::create(const Memory* _mem, uint32_t _flags, uint8_t _skip)
  1731. {
  1732. m_flags = _flags;
  1733. ImageContainer imageContainer;
  1734. if (imageParse(imageContainer, _mem->data, _mem->size) )
  1735. {
  1736. uint8_t numMips = imageContainer.m_numMips;
  1737. const uint32_t startLod = bx::uint32_min(_skip, numMips-1);
  1738. numMips -= startLod;
  1739. const ImageBlockInfo& blockInfo = getBlockInfo(TextureFormat::Enum(imageContainer.m_format) );
  1740. const uint32_t textureWidth = bx::uint32_max(blockInfo.blockWidth, imageContainer.m_width >>startLod);
  1741. const uint32_t textureHeight = bx::uint32_max(blockInfo.blockHeight, imageContainer.m_height>>startLod);
  1742. m_requestedFormat = imageContainer.m_format;
  1743. m_textureFormat = imageContainer.m_format;
  1744. const TextureFormatInfo& tfi = s_textureFormat[m_requestedFormat];
  1745. const bool convert = D3DFMT_UNKNOWN == tfi.m_fmt;
  1746. uint8_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  1747. if (convert)
  1748. {
  1749. m_textureFormat = (uint8_t)TextureFormat::BGRA8;
  1750. bpp = 32;
  1751. }
  1752. if (imageContainer.m_cubeMap)
  1753. {
  1754. createCubeTexture(textureWidth, numMips);
  1755. }
  1756. else if (imageContainer.m_depth > 1)
  1757. {
  1758. createVolumeTexture(textureWidth, textureHeight, imageContainer.m_depth, numMips);
  1759. }
  1760. else
  1761. {
  1762. createTexture(textureWidth, textureHeight, numMips);
  1763. }
  1764. BX_TRACE("Texture %3d: %s (requested: %s), %dx%d%s%s."
  1765. , this - s_renderD3D9->m_textures
  1766. , getName( (TextureFormat::Enum)m_textureFormat)
  1767. , getName( (TextureFormat::Enum)m_requestedFormat)
  1768. , textureWidth
  1769. , textureHeight
  1770. , imageContainer.m_cubeMap ? "x6" : ""
  1771. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  1772. );
  1773. if (0 != (_flags&BGFX_TEXTURE_RT_BUFFER_ONLY) )
  1774. {
  1775. return;
  1776. }
  1777. // For BC4 and B5 in DX9 LockRect returns wrong number of
  1778. // bytes. If actual mip size is used it causes memory corruption.
  1779. // http://www.aras-p.info/texts/D3D9GPUHacks.html#3dc
  1780. const bool useMipSize = true
  1781. && imageContainer.m_format != TextureFormat::BC4
  1782. && imageContainer.m_format != TextureFormat::BC5
  1783. ;
  1784. for (uint8_t side = 0, numSides = imageContainer.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1785. {
  1786. uint32_t width = textureWidth;
  1787. uint32_t height = textureHeight;
  1788. uint32_t depth = imageContainer.m_depth;
  1789. uint32_t mipWidth = imageContainer.m_width;
  1790. uint32_t mipHeight = imageContainer.m_height;
  1791. for (uint32_t lod = 0, num = numMips; lod < num; ++lod)
  1792. {
  1793. width = bx::uint32_max(1, width);
  1794. height = bx::uint32_max(1, height);
  1795. depth = bx::uint32_max(1, depth);
  1796. mipWidth = bx::uint32_max(blockInfo.blockWidth, mipWidth);
  1797. mipHeight = bx::uint32_max(blockInfo.blockHeight, mipHeight);
  1798. uint32_t mipSize = width*height*depth*bpp/8;
  1799. ImageMip mip;
  1800. if (imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  1801. {
  1802. uint32_t pitch;
  1803. uint32_t slicePitch;
  1804. uint8_t* bits = lock(side, lod, pitch, slicePitch);
  1805. if (convert)
  1806. {
  1807. if (width != mipWidth
  1808. || height != mipHeight)
  1809. {
  1810. uint32_t srcpitch = mipWidth*bpp/8;
  1811. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, srcpitch*mipHeight);
  1812. imageDecodeToBgra8(temp, mip.m_data, mip.m_width, mip.m_height, srcpitch, mip.m_format);
  1813. uint32_t dstpitch = pitch;
  1814. for (uint32_t yy = 0; yy < height; ++yy)
  1815. {
  1816. uint8_t* src = &temp[yy*srcpitch];
  1817. uint8_t* dst = &bits[yy*dstpitch];
  1818. memcpy(dst, src, dstpitch);
  1819. }
  1820. BX_FREE(g_allocator, temp);
  1821. }
  1822. else
  1823. {
  1824. imageDecodeToBgra8(bits, mip.m_data, mip.m_width, mip.m_height, pitch, mip.m_format);
  1825. }
  1826. }
  1827. else
  1828. {
  1829. uint32_t size = useMipSize ? mip.m_size : mipSize;
  1830. memcpy(bits, mip.m_data, size);
  1831. }
  1832. unlock(side, lod);
  1833. }
  1834. width >>= 1;
  1835. height >>= 1;
  1836. depth >>= 1;
  1837. mipWidth >>= 1;
  1838. mipHeight >>= 1;
  1839. }
  1840. }
  1841. }
  1842. }
  1843. void TextureD3D9::updateBegin(uint8_t _side, uint8_t _mip)
  1844. {
  1845. uint32_t slicePitch;
  1846. s_renderD3D9->m_updateTextureSide = _side;
  1847. s_renderD3D9->m_updateTextureMip = _mip;
  1848. s_renderD3D9->m_updateTextureBits = lock(_side, _mip, s_renderD3D9->m_updateTexturePitch, slicePitch);
  1849. }
  1850. void TextureD3D9::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  1851. {
  1852. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  1853. const uint32_t rectpitch = _rect.m_width*bpp/8;
  1854. const uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  1855. const uint32_t dstpitch = s_renderD3D9->m_updateTexturePitch;
  1856. uint8_t* bits = s_renderD3D9->m_updateTextureBits + _rect.m_y*dstpitch + _rect.m_x*bpp/8;
  1857. const bool convert = m_textureFormat != m_requestedFormat;
  1858. uint8_t* data = _mem->data;
  1859. uint8_t* temp = NULL;
  1860. if (convert)
  1861. {
  1862. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*_rect.m_height);
  1863. imageDecodeToBgra8(temp, data, _rect.m_width, _rect.m_height, srcpitch, m_requestedFormat);
  1864. data = temp;
  1865. }
  1866. {
  1867. uint8_t* src = data;
  1868. uint8_t* dst = bits;
  1869. for (uint32_t yy = 0, height = _rect.m_height; yy < height; ++yy)
  1870. {
  1871. memcpy(dst, src, rectpitch);
  1872. src += srcpitch;
  1873. dst += dstpitch;
  1874. }
  1875. }
  1876. if (NULL != temp)
  1877. {
  1878. BX_FREE(g_allocator, temp);
  1879. }
  1880. if (0 == _mip)
  1881. {
  1882. dirty(_side, _rect, _z, _depth);
  1883. }
  1884. }
  1885. void TextureD3D9::updateEnd()
  1886. {
  1887. unlock(s_renderD3D9->m_updateTextureSide, s_renderD3D9->m_updateTextureMip);
  1888. }
  1889. void TextureD3D9::commit(uint8_t _stage, uint32_t _flags)
  1890. {
  1891. s_renderD3D9->setSamplerState(_stage, 0 == (BGFX_SAMPLER_DEFAULT_FLAGS & _flags) ? _flags : m_flags);
  1892. DX_CHECK(s_renderD3D9->m_device->SetTexture(_stage, m_ptr) );
  1893. }
  1894. void TextureD3D9::resolve() const
  1895. {
  1896. if (NULL != m_surface
  1897. && NULL != m_texture2d)
  1898. {
  1899. IDirect3DSurface9* surface;
  1900. DX_CHECK(m_texture2d->GetSurfaceLevel(0, &surface) );
  1901. DX_CHECK(s_renderD3D9->m_device->StretchRect(m_surface
  1902. , NULL
  1903. , surface
  1904. , NULL
  1905. , D3DTEXF_LINEAR
  1906. ) );
  1907. DX_RELEASE(surface, 1);
  1908. }
  1909. }
  1910. void TextureD3D9::preReset()
  1911. {
  1912. TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  1913. if (TextureFormat::Unknown != fmt
  1914. && (isDepth(fmt) || !!(m_flags&BGFX_TEXTURE_RT_MASK) ) )
  1915. {
  1916. DX_RELEASE(m_ptr, 0);
  1917. DX_RELEASE(m_surface, 0);
  1918. }
  1919. }
  1920. void TextureD3D9::postReset()
  1921. {
  1922. TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  1923. if (TextureFormat::Unknown != fmt
  1924. && (isDepth(fmt) || !!(m_flags&BGFX_TEXTURE_RT_MASK) ) )
  1925. {
  1926. createTexture(m_width, m_height, m_numMips);
  1927. }
  1928. }
  1929. void FrameBufferD3D9::create(uint8_t _num, const TextureHandle* _handles)
  1930. {
  1931. for (uint32_t ii = 0; ii < BX_COUNTOF(m_color); ++ii)
  1932. {
  1933. m_color[ii] = NULL;
  1934. }
  1935. m_depthStencil = NULL;
  1936. m_num = 0;
  1937. m_needResolve = false;
  1938. for (uint32_t ii = 0; ii < _num; ++ii)
  1939. {
  1940. TextureHandle handle = _handles[ii];
  1941. if (isValid(handle) )
  1942. {
  1943. const TextureD3D9& texture = s_renderD3D9->m_textures[handle.idx];
  1944. if (isDepth( (TextureFormat::Enum)texture.m_textureFormat) )
  1945. {
  1946. m_depthHandle = handle;
  1947. if (NULL != texture.m_surface)
  1948. {
  1949. m_depthStencil = texture.m_surface;
  1950. m_depthStencil->AddRef();
  1951. }
  1952. else
  1953. {
  1954. DX_CHECK(texture.m_texture2d->GetSurfaceLevel(0, &m_depthStencil) );
  1955. }
  1956. }
  1957. else
  1958. {
  1959. m_colorHandle[m_num] = handle;
  1960. if (NULL != texture.m_surface)
  1961. {
  1962. m_color[m_num] = texture.m_surface;
  1963. m_color[m_num]->AddRef();
  1964. }
  1965. else
  1966. {
  1967. DX_CHECK(texture.m_texture2d->GetSurfaceLevel(0, &m_color[m_num]) );
  1968. }
  1969. m_num++;
  1970. }
  1971. m_needResolve |= (NULL != texture.m_surface) && (NULL != texture.m_texture2d);
  1972. }
  1973. }
  1974. if (0 == m_num)
  1975. {
  1976. createNullColorRT();
  1977. }
  1978. }
  1979. void FrameBufferD3D9::destroy()
  1980. {
  1981. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  1982. {
  1983. m_colorHandle[ii].idx = invalidHandle;
  1984. IDirect3DSurface9* ptr = m_color[ii];
  1985. if (NULL != ptr)
  1986. {
  1987. ptr->Release();
  1988. m_color[ii] = NULL;
  1989. }
  1990. }
  1991. if (NULL != m_depthStencil)
  1992. {
  1993. if (0 == m_num)
  1994. {
  1995. IDirect3DSurface9* ptr = m_color[0];
  1996. if (NULL != ptr)
  1997. {
  1998. ptr->Release();
  1999. m_color[0] = NULL;
  2000. }
  2001. }
  2002. m_depthStencil->Release();
  2003. m_depthStencil = NULL;
  2004. }
  2005. m_num = 0;
  2006. m_depthHandle.idx = invalidHandle;
  2007. }
  2008. void FrameBufferD3D9::resolve() const
  2009. {
  2010. if (m_needResolve)
  2011. {
  2012. if (isValid(m_depthHandle) )
  2013. {
  2014. const TextureD3D9& texture = s_renderD3D9->m_textures[m_depthHandle.idx];
  2015. texture.resolve();
  2016. }
  2017. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  2018. {
  2019. const TextureD3D9& texture = s_renderD3D9->m_textures[m_colorHandle[ii].idx];
  2020. texture.resolve();
  2021. }
  2022. }
  2023. }
  2024. void FrameBufferD3D9::preReset()
  2025. {
  2026. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  2027. {
  2028. m_color[ii]->Release();
  2029. m_color[ii] = NULL;
  2030. }
  2031. if (isValid(m_depthHandle) )
  2032. {
  2033. if (0 == m_num)
  2034. {
  2035. m_color[0]->Release();
  2036. m_color[0] = NULL;
  2037. }
  2038. m_depthStencil->Release();
  2039. m_depthStencil = NULL;
  2040. }
  2041. }
  2042. void FrameBufferD3D9::postReset()
  2043. {
  2044. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  2045. {
  2046. TextureD3D9& texture = s_renderD3D9->m_textures[m_colorHandle[ii].idx];
  2047. if (NULL != texture.m_surface)
  2048. {
  2049. m_color[ii] = texture.m_surface;
  2050. m_color[ii]->AddRef();
  2051. }
  2052. else
  2053. {
  2054. DX_CHECK(texture.m_texture2d->GetSurfaceLevel(0, &m_color[ii]) );
  2055. }
  2056. }
  2057. if (isValid(m_depthHandle) )
  2058. {
  2059. TextureD3D9& texture = s_renderD3D9->m_textures[m_depthHandle.idx];
  2060. if (NULL != texture.m_surface)
  2061. {
  2062. m_depthStencil = texture.m_surface;
  2063. m_depthStencil->AddRef();
  2064. }
  2065. else
  2066. {
  2067. DX_CHECK(texture.m_texture2d->GetSurfaceLevel(0, &m_depthStencil) );
  2068. }
  2069. if (0 == m_num)
  2070. {
  2071. createNullColorRT();
  2072. }
  2073. }
  2074. }
  2075. void FrameBufferD3D9::createNullColorRT()
  2076. {
  2077. const TextureD3D9& texture = s_renderD3D9->m_textures[m_depthHandle.idx];
  2078. DX_CHECK(s_renderD3D9->m_device->CreateRenderTarget(texture.m_width
  2079. , texture.m_height
  2080. , D3DFMT_NULL
  2081. , D3DMULTISAMPLE_NONE
  2082. , 0
  2083. , false
  2084. , &m_color[0]
  2085. , NULL
  2086. ) );
  2087. }
  2088. void RendererContextD3D9::submit(Frame* _render, ClearQuad& /*_clearQuad*/, TextVideoMemBlitter& _textVideoMemBlitter)
  2089. {
  2090. IDirect3DDevice9* device = m_device;
  2091. PIX_BEGINEVENT(D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), L"rendererSubmit");
  2092. updateResolution(_render->m_resolution);
  2093. int64_t elapsed = -bx::getHPCounter();
  2094. int64_t captureElapsed = 0;
  2095. device->BeginScene();
  2096. if (0 < _render->m_iboffset)
  2097. {
  2098. TransientIndexBuffer* ib = _render->m_transientIb;
  2099. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data, true);
  2100. }
  2101. if (0 < _render->m_vboffset)
  2102. {
  2103. TransientVertexBuffer* vb = _render->m_transientVb;
  2104. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data, true);
  2105. }
  2106. _render->sort();
  2107. RenderDraw currentState;
  2108. currentState.clear();
  2109. currentState.m_flags = BGFX_STATE_NONE;
  2110. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  2111. Matrix4 viewProj[BGFX_CONFIG_MAX_VIEWS];
  2112. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  2113. {
  2114. bx::float4x4_mul(&viewProj[ii].un.f4x4, &_render->m_view[ii].un.f4x4, &_render->m_proj[ii].un.f4x4);
  2115. }
  2116. Matrix4 invView;
  2117. Matrix4 invProj;
  2118. Matrix4 invViewProj;
  2119. uint8_t invViewCached = 0xff;
  2120. uint8_t invProjCached = 0xff;
  2121. uint8_t invViewProjCached = 0xff;
  2122. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, _render->m_debug&BGFX_DEBUG_WIREFRAME ? D3DFILL_WIREFRAME : D3DFILL_SOLID) );
  2123. uint16_t programIdx = invalidHandle;
  2124. SortKey key;
  2125. uint8_t view = 0xff;
  2126. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  2127. float alphaRef = 0.0f;
  2128. uint32_t blendFactor = 0;
  2129. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : 0;
  2130. uint8_t primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  2131. PrimInfo prim = s_primInfo[primIndex];
  2132. bool viewHasScissor = false;
  2133. Rect viewScissorRect;
  2134. viewScissorRect.clear();
  2135. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  2136. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  2137. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  2138. uint32_t statsNumIndices = 0;
  2139. invalidateSamplerState();
  2140. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  2141. {
  2142. for (uint32_t item = 0, numItems = _render->m_num; item < numItems; ++item)
  2143. {
  2144. const bool isCompute = key.decode(_render->m_sortKeys[item]);
  2145. if (isCompute)
  2146. {
  2147. BX_CHECK(false, "Compute is not supported on DirectX 9.");
  2148. continue;
  2149. }
  2150. const RenderDraw& draw = _render->m_renderItem[_render->m_sortValues[item] ].draw;
  2151. const uint64_t newFlags = draw.m_flags;
  2152. uint64_t changedFlags = currentState.m_flags ^ draw.m_flags;
  2153. currentState.m_flags = newFlags;
  2154. const uint64_t newStencil = draw.m_stencil;
  2155. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  2156. currentState.m_stencil = newStencil;
  2157. if (key.m_view != view)
  2158. {
  2159. currentState.clear();
  2160. currentState.m_scissor = !draw.m_scissor;
  2161. changedFlags = BGFX_STATE_MASK;
  2162. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  2163. currentState.m_flags = newFlags;
  2164. currentState.m_stencil = newStencil;
  2165. PIX_ENDEVENT();
  2166. PIX_BEGINEVENT(D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), s_viewNameW[key.m_view]);
  2167. view = key.m_view;
  2168. programIdx = invalidHandle;
  2169. if (_render->m_fb[view].idx != fbh.idx)
  2170. {
  2171. fbh = _render->m_fb[view];
  2172. setFrameBuffer(fbh);
  2173. }
  2174. const Rect& rect = _render->m_rect[view];
  2175. const Rect& scissorRect = _render->m_scissor[view];
  2176. viewHasScissor = !scissorRect.isZero();
  2177. viewScissorRect = viewHasScissor ? scissorRect : rect;
  2178. D3DVIEWPORT9 vp;
  2179. vp.X = rect.m_x;
  2180. vp.Y = rect.m_y;
  2181. vp.Width = rect.m_width;
  2182. vp.Height = rect.m_height;
  2183. vp.MinZ = 0.0f;
  2184. vp.MaxZ = 1.0f;
  2185. DX_CHECK(device->SetViewport(&vp) );
  2186. Clear& clear = _render->m_clear[view];
  2187. if (BGFX_CLEAR_NONE != clear.m_flags)
  2188. {
  2189. D3DCOLOR color = 0;
  2190. DWORD flags = 0;
  2191. if (BGFX_CLEAR_COLOR_BIT & clear.m_flags)
  2192. {
  2193. flags |= D3DCLEAR_TARGET;
  2194. uint32_t rgba = clear.m_rgba;
  2195. color = D3DCOLOR_RGBA(rgba>>24, (rgba>>16)&0xff, (rgba>>8)&0xff, rgba&0xff);
  2196. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_ALPHA) );
  2197. }
  2198. if (BGFX_CLEAR_DEPTH_BIT & clear.m_flags)
  2199. {
  2200. flags |= D3DCLEAR_ZBUFFER;
  2201. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE) );
  2202. }
  2203. if (BGFX_CLEAR_STENCIL_BIT & clear.m_flags)
  2204. {
  2205. flags |= D3DCLEAR_STENCIL;
  2206. }
  2207. if (0 != flags)
  2208. {
  2209. RECT rc;
  2210. rc.left = rect.m_x;
  2211. rc.top = rect.m_y;
  2212. rc.right = rect.m_x + rect.m_width;
  2213. rc.bottom = rect.m_y + rect.m_height;
  2214. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE) );
  2215. DX_CHECK(device->SetScissorRect(&rc) );
  2216. DX_CHECK(device->Clear(0, NULL, flags, color, clear.m_depth, clear.m_stencil) );
  2217. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE) );
  2218. }
  2219. }
  2220. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  2221. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, TRUE) );
  2222. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESS) );
  2223. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  2224. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  2225. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  2226. }
  2227. uint16_t scissor = draw.m_scissor;
  2228. if (currentState.m_scissor != scissor)
  2229. {
  2230. currentState.m_scissor = scissor;
  2231. if (UINT16_MAX == scissor)
  2232. {
  2233. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, viewHasScissor) );
  2234. if (viewHasScissor)
  2235. {
  2236. RECT rc;
  2237. rc.left = viewScissorRect.m_x;
  2238. rc.top = viewScissorRect.m_y;
  2239. rc.right = viewScissorRect.m_x + viewScissorRect.m_width;
  2240. rc.bottom = viewScissorRect.m_y + viewScissorRect.m_height;
  2241. DX_CHECK(device->SetScissorRect(&rc) );
  2242. }
  2243. }
  2244. else
  2245. {
  2246. Rect scissorRect;
  2247. scissorRect.intersect(viewScissorRect, _render->m_rectCache.m_cache[scissor]);
  2248. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, true) );
  2249. RECT rc;
  2250. rc.left = scissorRect.m_x;
  2251. rc.top = scissorRect.m_y;
  2252. rc.right = scissorRect.m_x + scissorRect.m_width;
  2253. rc.bottom = scissorRect.m_y + scissorRect.m_height;
  2254. DX_CHECK(device->SetScissorRect(&rc) );
  2255. }
  2256. }
  2257. if (0 != changedStencil)
  2258. {
  2259. bool enable = 0 != newStencil;
  2260. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, enable) );
  2261. if (0 != newStencil)
  2262. {
  2263. uint32_t fstencil = unpackStencil(0, newStencil);
  2264. uint32_t bstencil = unpackStencil(1, newStencil);
  2265. uint32_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != fstencil;
  2266. DX_CHECK(device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, 0 != frontAndBack) );
  2267. uint32_t fchanged = unpackStencil(0, changedStencil);
  2268. if ( (BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & fchanged)
  2269. {
  2270. uint32_t ref = (fstencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  2271. DX_CHECK(device->SetRenderState(D3DRS_STENCILREF, ref) );
  2272. uint32_t rmask = (fstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2273. DX_CHECK(device->SetRenderState(D3DRS_STENCILMASK, rmask) );
  2274. }
  2275. // uint32_t bchanged = unpackStencil(1, changedStencil);
  2276. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  2277. // {
  2278. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2279. // DX_CHECK(device->SetRenderState(D3DRS_STENCILWRITEMASK, wmask) );
  2280. // }
  2281. for (uint32_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  2282. {
  2283. uint32_t stencil = unpackStencil(ii, newStencil);
  2284. uint32_t changed = unpackStencil(ii, changedStencil);
  2285. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  2286. {
  2287. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  2288. DX_CHECK(device->SetRenderState(s_stencilFuncRs[ii], s_cmpFunc[func]) );
  2289. }
  2290. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  2291. {
  2292. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  2293. DX_CHECK(device->SetRenderState(s_stencilFailRs[ii], s_stencilOp[sfail]) );
  2294. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  2295. DX_CHECK(device->SetRenderState(s_stencilZFailRs[ii], s_stencilOp[zfail]) );
  2296. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  2297. DX_CHECK(device->SetRenderState(s_stencilZPassRs[ii], s_stencilOp[zpass]) );
  2298. }
  2299. }
  2300. }
  2301. }
  2302. if ( (0
  2303. | BGFX_STATE_CULL_MASK
  2304. | BGFX_STATE_DEPTH_WRITE
  2305. | BGFX_STATE_DEPTH_TEST_MASK
  2306. | BGFX_STATE_RGB_WRITE
  2307. | BGFX_STATE_ALPHA_WRITE
  2308. | BGFX_STATE_BLEND_MASK
  2309. | BGFX_STATE_BLEND_EQUATION_MASK
  2310. | BGFX_STATE_ALPHA_REF_MASK
  2311. | BGFX_STATE_PT_MASK
  2312. | BGFX_STATE_POINT_SIZE_MASK
  2313. | BGFX_STATE_MSAA
  2314. ) & changedFlags)
  2315. {
  2316. if (BGFX_STATE_CULL_MASK & changedFlags)
  2317. {
  2318. uint32_t cull = (newFlags&BGFX_STATE_CULL_MASK)>>BGFX_STATE_CULL_SHIFT;
  2319. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, s_cullMode[cull]) );
  2320. }
  2321. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  2322. {
  2323. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, !!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  2324. }
  2325. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  2326. {
  2327. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  2328. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, 0 != func) );
  2329. if (0 != func)
  2330. {
  2331. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, s_cmpFunc[func]) );
  2332. }
  2333. }
  2334. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  2335. {
  2336. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  2337. alphaRef = ref/255.0f;
  2338. }
  2339. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  2340. {
  2341. DX_CHECK(device->SetRenderState(D3DRS_POINTSIZE, castfu( (float)( (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) ) ) );
  2342. }
  2343. if (BGFX_STATE_MSAA & changedFlags)
  2344. {
  2345. DX_CHECK(device->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, (newFlags&BGFX_STATE_MSAA) == BGFX_STATE_MSAA) );
  2346. }
  2347. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  2348. {
  2349. uint32_t writeEnable = (newFlags&BGFX_STATE_ALPHA_WRITE) ? D3DCOLORWRITEENABLE_ALPHA : 0;
  2350. writeEnable |= (newFlags&BGFX_STATE_RGB_WRITE) ? D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE : 0;
  2351. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, writeEnable) );
  2352. }
  2353. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK) & changedFlags
  2354. || blendFactor != draw.m_rgba)
  2355. {
  2356. bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  2357. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, enabled) );
  2358. if (enabled)
  2359. {
  2360. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  2361. const uint32_t equation = uint32_t( (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  2362. const uint32_t srcRGB = (blend )&0xf;
  2363. const uint32_t dstRGB = (blend>> 4)&0xf;
  2364. const uint32_t srcA = (blend>> 8)&0xf;
  2365. const uint32_t dstA = (blend>>12)&0xf;
  2366. const uint32_t equRGB = (equation )&0x7;
  2367. const uint32_t equA = (equation>>3)&0x7;
  2368. DX_CHECK(device->SetRenderState(D3DRS_SRCBLEND, s_blendFactor[srcRGB].m_src) );
  2369. DX_CHECK(device->SetRenderState(D3DRS_DESTBLEND, s_blendFactor[dstRGB].m_dst) );
  2370. DX_CHECK(device->SetRenderState(D3DRS_BLENDOP, s_blendEquation[equRGB]) );
  2371. const bool separate = srcRGB != srcA || dstRGB != dstA || equRGB != equA;
  2372. DX_CHECK(device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, separate) );
  2373. if (separate)
  2374. {
  2375. DX_CHECK(device->SetRenderState(D3DRS_SRCBLENDALPHA, s_blendFactor[srcA].m_src) );
  2376. DX_CHECK(device->SetRenderState(D3DRS_DESTBLENDALPHA, s_blendFactor[dstA].m_dst) );
  2377. DX_CHECK(device->SetRenderState(D3DRS_BLENDOPALPHA, s_blendEquation[equA]) );
  2378. }
  2379. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  2380. && blendFactor != draw.m_rgba)
  2381. {
  2382. const uint32_t rgba = draw.m_rgba;
  2383. D3DCOLOR color = D3DCOLOR_RGBA(rgba>>24
  2384. , (rgba>>16)&0xff
  2385. , (rgba>> 8)&0xff
  2386. , (rgba )&0xff
  2387. );
  2388. DX_CHECK(device->SetRenderState(D3DRS_BLENDFACTOR, color) );
  2389. }
  2390. }
  2391. blendFactor = draw.m_rgba;
  2392. }
  2393. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : newFlags&BGFX_STATE_PT_MASK;
  2394. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  2395. prim = s_primInfo[primIndex];
  2396. }
  2397. bool programChanged = false;
  2398. bool constantsChanged = draw.m_constBegin < draw.m_constEnd;
  2399. rendererUpdateUniforms(this, _render->m_constantBuffer, draw.m_constBegin, draw.m_constEnd);
  2400. if (key.m_program != programIdx)
  2401. {
  2402. programIdx = key.m_program;
  2403. if (invalidHandle == programIdx)
  2404. {
  2405. device->SetVertexShader(NULL);
  2406. device->SetPixelShader(NULL);
  2407. }
  2408. else
  2409. {
  2410. ProgramD3D9& program = m_program[programIdx];
  2411. device->SetVertexShader(program.m_vsh->m_vertexShader);
  2412. device->SetPixelShader(program.m_fsh->m_pixelShader);
  2413. }
  2414. programChanged =
  2415. constantsChanged = true;
  2416. }
  2417. if (invalidHandle != programIdx)
  2418. {
  2419. ProgramD3D9& program = m_program[programIdx];
  2420. if (constantsChanged)
  2421. {
  2422. ConstantBuffer* vcb = program.m_vsh->m_constantBuffer;
  2423. if (NULL != vcb)
  2424. {
  2425. commit(*vcb);
  2426. }
  2427. ConstantBuffer* fcb = program.m_fsh->m_constantBuffer;
  2428. if (NULL != fcb)
  2429. {
  2430. commit(*fcb);
  2431. }
  2432. }
  2433. for (uint32_t ii = 0, num = program.m_numPredefined; ii < num; ++ii)
  2434. {
  2435. PredefinedUniform& predefined = program.m_predefined[ii];
  2436. uint8_t flags = predefined.m_type&BGFX_UNIFORM_FRAGMENTBIT;
  2437. switch (predefined.m_type&(~BGFX_UNIFORM_FRAGMENTBIT) )
  2438. {
  2439. case PredefinedUniform::ViewRect:
  2440. {
  2441. float rect[4];
  2442. rect[0] = _render->m_rect[view].m_x;
  2443. rect[1] = _render->m_rect[view].m_y;
  2444. rect[2] = _render->m_rect[view].m_width;
  2445. rect[3] = _render->m_rect[view].m_height;
  2446. setShaderConstantF(flags, predefined.m_loc, &rect[0], 1);
  2447. }
  2448. break;
  2449. case PredefinedUniform::ViewTexel:
  2450. {
  2451. float rect[4];
  2452. rect[0] = 1.0f/float(_render->m_rect[view].m_width);
  2453. rect[1] = 1.0f/float(_render->m_rect[view].m_height);
  2454. setShaderConstantF(flags, predefined.m_loc, &rect[0], 1);
  2455. }
  2456. break;
  2457. case PredefinedUniform::View:
  2458. {
  2459. setShaderConstantF(flags, predefined.m_loc, _render->m_view[view].un.val, bx::uint32_min(4, predefined.m_count) );
  2460. }
  2461. break;
  2462. case PredefinedUniform::InvView:
  2463. {
  2464. if (view != invViewCached)
  2465. {
  2466. invViewCached = view;
  2467. bx::float4x4_inverse(&invView.un.f4x4, &_render->m_view[view].un.f4x4);
  2468. }
  2469. setShaderConstantF(flags, predefined.m_loc, invView.un.val, bx::uint32_min(4, predefined.m_count) );
  2470. }
  2471. break;
  2472. case PredefinedUniform::Proj:
  2473. {
  2474. setShaderConstantF(flags, predefined.m_loc, _render->m_proj[view].un.val, bx::uint32_min(4, predefined.m_count) );
  2475. }
  2476. break;
  2477. case PredefinedUniform::InvProj:
  2478. {
  2479. if (view != invProjCached)
  2480. {
  2481. invProjCached = view;
  2482. bx::float4x4_inverse(&invProj.un.f4x4, &_render->m_proj[view].un.f4x4);
  2483. }
  2484. setShaderConstantF(flags, predefined.m_loc, invProj.un.val, bx::uint32_min(4, predefined.m_count) );
  2485. }
  2486. break;
  2487. case PredefinedUniform::ViewProj:
  2488. {
  2489. setShaderConstantF(flags, predefined.m_loc, viewProj[view].un.val, bx::uint32_min(4, predefined.m_count) );
  2490. }
  2491. break;
  2492. case PredefinedUniform::InvViewProj:
  2493. {
  2494. if (view != invViewProjCached)
  2495. {
  2496. invViewProjCached = view;
  2497. bx::float4x4_inverse(&invViewProj.un.f4x4, &viewProj[view].un.f4x4);
  2498. }
  2499. setShaderConstantF(flags, predefined.m_loc, invViewProj.un.val, bx::uint32_min(4, predefined.m_count) );
  2500. }
  2501. break;
  2502. case PredefinedUniform::Model:
  2503. {
  2504. const Matrix4& model = _render->m_matrixCache.m_cache[draw.m_matrix];
  2505. setShaderConstantF(flags, predefined.m_loc, model.un.val, bx::uint32_min(draw.m_num*4, predefined.m_count) );
  2506. }
  2507. break;
  2508. case PredefinedUniform::ModelView:
  2509. {
  2510. Matrix4 modelView;
  2511. const Matrix4& model = _render->m_matrixCache.m_cache[draw.m_matrix];
  2512. bx::float4x4_mul(&modelView.un.f4x4, &model.un.f4x4, &_render->m_view[view].un.f4x4);
  2513. setShaderConstantF(flags, predefined.m_loc, modelView.un.val, bx::uint32_min(4, predefined.m_count) );
  2514. }
  2515. break;
  2516. case PredefinedUniform::ModelViewProj:
  2517. {
  2518. Matrix4 modelViewProj;
  2519. const Matrix4& model = _render->m_matrixCache.m_cache[draw.m_matrix];
  2520. bx::float4x4_mul(&modelViewProj.un.f4x4, &model.un.f4x4, &viewProj[view].un.f4x4);
  2521. setShaderConstantF(flags, predefined.m_loc, modelViewProj.un.val, bx::uint32_min(4, predefined.m_count) );
  2522. }
  2523. break;
  2524. case PredefinedUniform::AlphaRef:
  2525. {
  2526. setShaderConstantF(flags, predefined.m_loc, &alphaRef, 1);
  2527. }
  2528. break;
  2529. default:
  2530. BX_CHECK(false, "predefined %d not handled", predefined.m_type);
  2531. break;
  2532. }
  2533. }
  2534. }
  2535. {
  2536. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  2537. {
  2538. const Sampler& sampler = draw.m_sampler[stage];
  2539. Sampler& current = currentState.m_sampler[stage];
  2540. if (current.m_idx != sampler.m_idx
  2541. || current.m_flags != sampler.m_flags
  2542. || programChanged)
  2543. {
  2544. if (invalidHandle != sampler.m_idx)
  2545. {
  2546. m_textures[sampler.m_idx].commit(stage, sampler.m_flags);
  2547. }
  2548. else
  2549. {
  2550. DX_CHECK(device->SetTexture(stage, NULL) );
  2551. }
  2552. }
  2553. current = sampler;
  2554. }
  2555. }
  2556. if (programChanged
  2557. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  2558. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  2559. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  2560. || currentState.m_instanceDataStride != draw.m_instanceDataStride)
  2561. {
  2562. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  2563. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  2564. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  2565. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  2566. uint16_t handle = draw.m_vertexBuffer.idx;
  2567. if (invalidHandle != handle)
  2568. {
  2569. const VertexBufferD3D9& vb = m_vertexBuffers[handle];
  2570. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  2571. const VertexDeclaration& vertexDecl = m_vertexDecls[decl];
  2572. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, vertexDecl.m_decl.m_stride) );
  2573. if (isValid(draw.m_instanceDataBuffer)
  2574. && m_instancing)
  2575. {
  2576. const VertexBufferD3D9& inst = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  2577. DX_CHECK(device->SetStreamSourceFreq(0, D3DSTREAMSOURCE_INDEXEDDATA|draw.m_numInstances) );
  2578. DX_CHECK(device->SetStreamSourceFreq(1, UINT(D3DSTREAMSOURCE_INSTANCEDATA|1) ) );
  2579. DX_CHECK(device->SetStreamSource(1, inst.m_ptr, draw.m_instanceDataOffset, draw.m_instanceDataStride) );
  2580. IDirect3DVertexDeclaration9* ptr = createVertexDeclaration(vertexDecl.m_decl, draw.m_instanceDataStride/16);
  2581. DX_CHECK(device->SetVertexDeclaration(ptr) );
  2582. DX_RELEASE(ptr, 0);
  2583. }
  2584. else
  2585. {
  2586. DX_CHECK(device->SetStreamSourceFreq(0, 1) );
  2587. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  2588. DX_CHECK(device->SetVertexDeclaration(vertexDecl.m_ptr) );
  2589. }
  2590. }
  2591. else
  2592. {
  2593. DX_CHECK(device->SetStreamSource(0, NULL, 0, 0) );
  2594. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  2595. }
  2596. }
  2597. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  2598. {
  2599. currentState.m_indexBuffer = draw.m_indexBuffer;
  2600. uint16_t handle = draw.m_indexBuffer.idx;
  2601. if (invalidHandle != handle)
  2602. {
  2603. const IndexBufferD3D9& ib = m_indexBuffers[handle];
  2604. DX_CHECK(device->SetIndices(ib.m_ptr) );
  2605. }
  2606. else
  2607. {
  2608. DX_CHECK(device->SetIndices(NULL) );
  2609. }
  2610. }
  2611. if (isValid(currentState.m_vertexBuffer) )
  2612. {
  2613. uint32_t numVertices = draw.m_numVertices;
  2614. if (UINT32_MAX == numVertices)
  2615. {
  2616. const VertexBufferD3D9& vb = m_vertexBuffers[currentState.m_vertexBuffer.idx];
  2617. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  2618. const VertexDeclaration& vertexDecl = m_vertexDecls[decl];
  2619. numVertices = vb.m_size/vertexDecl.m_decl.m_stride;
  2620. }
  2621. uint32_t numIndices = 0;
  2622. uint32_t numPrimsSubmitted = 0;
  2623. uint32_t numInstances = 0;
  2624. uint32_t numPrimsRendered = 0;
  2625. if (isValid(draw.m_indexBuffer) )
  2626. {
  2627. if (UINT32_MAX == draw.m_numIndices)
  2628. {
  2629. numIndices = m_indexBuffers[draw.m_indexBuffer.idx].m_size/2;
  2630. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  2631. numInstances = draw.m_numInstances;
  2632. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  2633. DX_CHECK(device->DrawIndexedPrimitive(prim.m_type
  2634. , draw.m_startVertex
  2635. , 0
  2636. , numVertices
  2637. , 0
  2638. , numPrimsSubmitted
  2639. ) );
  2640. }
  2641. else if (prim.m_min <= draw.m_numIndices)
  2642. {
  2643. numIndices = draw.m_numIndices;
  2644. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  2645. numInstances = draw.m_numInstances;
  2646. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  2647. DX_CHECK(device->DrawIndexedPrimitive(prim.m_type
  2648. , draw.m_startVertex
  2649. , 0
  2650. , numVertices
  2651. , draw.m_startIndex
  2652. , numPrimsSubmitted
  2653. ) );
  2654. }
  2655. }
  2656. else
  2657. {
  2658. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  2659. numInstances = draw.m_numInstances;
  2660. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  2661. DX_CHECK(device->DrawPrimitive(prim.m_type
  2662. , draw.m_startVertex
  2663. , numPrimsSubmitted
  2664. ) );
  2665. }
  2666. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  2667. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  2668. statsNumInstances[primIndex] += numInstances;
  2669. statsNumIndices += numIndices;
  2670. }
  2671. }
  2672. PIX_ENDEVENT();
  2673. if (0 < _render->m_num)
  2674. {
  2675. captureElapsed = -bx::getHPCounter();
  2676. capture();
  2677. captureElapsed += bx::getHPCounter();
  2678. }
  2679. }
  2680. int64_t now = bx::getHPCounter();
  2681. elapsed += now;
  2682. static int64_t last = now;
  2683. int64_t frameTime = now - last;
  2684. last = now;
  2685. static int64_t min = frameTime;
  2686. static int64_t max = frameTime;
  2687. min = min > frameTime ? frameTime : min;
  2688. max = max < frameTime ? frameTime : max;
  2689. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  2690. {
  2691. PIX_BEGINEVENT(D3DCOLOR_RGBA(0x40, 0x40, 0x40, 0xff), L"debugstats");
  2692. TextVideoMem& tvm = m_textVideoMem;
  2693. static int64_t next = now;
  2694. if (now >= next)
  2695. {
  2696. next = now + bx::getHPFrequency();
  2697. double freq = double(bx::getHPFrequency() );
  2698. double toMs = 1000.0/freq;
  2699. tvm.clear();
  2700. uint16_t pos = 0;
  2701. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  2702. , getRendererName()
  2703. );
  2704. const D3DADAPTER_IDENTIFIER9& identifier = m_identifier;
  2705. tvm.printf(0, pos++, 0x0f, " Device: %s (%s)", identifier.Description, identifier.Driver);
  2706. pos = 10;
  2707. tvm.printf(10, pos++, 0x8e, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  2708. , double(frameTime)*toMs
  2709. , double(min)*toMs
  2710. , double(max)*toMs
  2711. , freq/frameTime
  2712. );
  2713. const uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  2714. tvm.printf(10, pos++, 0x8e, " Reset flags: [%c] vsync, [%c] MSAAx%d "
  2715. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  2716. , 0 != msaa ? '\xfe' : ' '
  2717. , 1<<msaa
  2718. );
  2719. double elapsedCpuMs = double(elapsed)*toMs;
  2720. tvm.printf(10, pos++, 0x8e, " Draw calls: %4d / CPU %3.4f [ms]"
  2721. , _render->m_num
  2722. , elapsedCpuMs
  2723. );
  2724. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primInfo); ++ii)
  2725. {
  2726. tvm.printf(10, pos++, 0x8e, " %8s: %7d (#inst: %5d), submitted: %7d"
  2727. , s_primName[ii]
  2728. , statsNumPrimsRendered[ii]
  2729. , statsNumInstances[ii]
  2730. , statsNumPrimsSubmitted[ii]
  2731. );
  2732. }
  2733. tvm.printf(10, pos++, 0x8e, " Indices: %7d", statsNumIndices);
  2734. tvm.printf(10, pos++, 0x8e, " DVB size: %7d", _render->m_vboffset);
  2735. tvm.printf(10, pos++, 0x8e, " DIB size: %7d", _render->m_iboffset);
  2736. double captureMs = double(captureElapsed)*toMs;
  2737. tvm.printf(10, pos++, 0x8e, " Capture: %3.4f [ms]", captureMs);
  2738. uint8_t attr[2] = { 0x89, 0x8a };
  2739. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  2740. tvm.printf(10, pos++, attr[attrIndex&1], " Submit wait: %3.4f [ms]", _render->m_waitSubmit*toMs);
  2741. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %3.4f [ms]", _render->m_waitRender*toMs);
  2742. min = frameTime;
  2743. max = frameTime;
  2744. }
  2745. blit(this, _textVideoMemBlitter, tvm);
  2746. PIX_ENDEVENT();
  2747. }
  2748. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  2749. {
  2750. PIX_BEGINEVENT(D3DCOLOR_RGBA(0x40, 0x40, 0x40, 0xff), L"debugtext");
  2751. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  2752. PIX_ENDEVENT();
  2753. }
  2754. device->EndScene();
  2755. }
  2756. } // namespace bgfx
  2757. #else
  2758. namespace bgfx
  2759. {
  2760. RendererContextI* rendererCreateD3D9()
  2761. {
  2762. return NULL;
  2763. }
  2764. void rendererDestroyD3D9()
  2765. {
  2766. }
  2767. } // namespace bgfx
  2768. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9