renderer_d3d9.cpp 98 KB

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