CmD3D9HLSLProgram.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmD3D9HLSLProgram.h"
  25. #include "CmGpuProgramManager.h"
  26. #include "CmD3D9GpuProgram.h"
  27. #include "CmException.h"
  28. #include "CmRenderSystem.h"
  29. #include "CmRenderSystemManager.h"
  30. namespace CamelotEngine {
  31. class CM_D3D9_EXPORT HLSLIncludeHandler : public ID3DXInclude
  32. {
  33. public:
  34. HLSLIncludeHandler(HighLevelGpuProgram* sourceProgram)
  35. : mProgram(sourceProgram) {}
  36. ~HLSLIncludeHandler() {}
  37. STDMETHOD(Open)(D3DXINCLUDE_TYPE IncludeType,
  38. LPCSTR pFileName,
  39. LPCVOID pParentData,
  40. LPCVOID *ppData,
  41. UINT *pByteLen
  42. )
  43. {
  44. // TODO PORT - I'm not sure what to do with this. It will probably break something in its current state.
  45. //// find & load source code
  46. //DataStreamPtr stream =
  47. // ResourceGroupManager::getSingleton().openResource(
  48. // String(pFileName), mProgram->getGroup(), true, mProgram);
  49. //String source = stream->getAsString();
  50. //// copy into separate c-string
  51. //// Note - must NOT copy the null terminator, otherwise this will terminate
  52. //// the entire program string!
  53. //*pByteLen = static_cast<UINT>(source.length());
  54. //char* pChar = new char[*pByteLen];
  55. //memcpy(pChar, source.c_str(), *pByteLen);
  56. //*ppData = pChar;
  57. assert(false); // TODO - Include files not supported until I can figure out how to handle them
  58. return S_OK;
  59. }
  60. STDMETHOD(Close)(LPCVOID pData)
  61. {
  62. char* pChar = (char*)pData;
  63. delete [] pChar;
  64. return S_OK;
  65. }
  66. protected:
  67. HighLevelGpuProgram* mProgram;
  68. };
  69. //-----------------------------------------------------------------------
  70. //-----------------------------------------------------------------------
  71. void D3D9HLSLProgram::loadFromSource(void)
  72. {
  73. // Populate preprocessor defines
  74. String stringBuffer;
  75. vector<D3DXMACRO>::type defines;
  76. const D3DXMACRO* pDefines = 0;
  77. if (!mPreprocessorDefines.empty())
  78. {
  79. stringBuffer = mPreprocessorDefines;
  80. // Split preprocessor defines and build up macro array
  81. D3DXMACRO macro;
  82. String::size_type pos = 0;
  83. while (pos != String::npos)
  84. {
  85. macro.Name = &stringBuffer[pos];
  86. macro.Definition = 0;
  87. String::size_type start_pos=pos;
  88. // Find delims
  89. pos = stringBuffer.find_first_of(";,=", pos);
  90. if(start_pos==pos)
  91. {
  92. if(pos==stringBuffer.length())
  93. {
  94. break;
  95. }
  96. pos++;
  97. continue;
  98. }
  99. if (pos != String::npos)
  100. {
  101. // Check definition part
  102. if (stringBuffer[pos] == '=')
  103. {
  104. // Setup null character for macro name
  105. stringBuffer[pos++] = '\0';
  106. macro.Definition = &stringBuffer[pos];
  107. pos = stringBuffer.find_first_of(";,", pos);
  108. }
  109. else
  110. {
  111. // No definition part, define as "1"
  112. macro.Definition = "1";
  113. }
  114. if (pos != String::npos)
  115. {
  116. // Setup null character for macro name or definition
  117. stringBuffer[pos++] = '\0';
  118. }
  119. }
  120. else
  121. {
  122. macro.Definition = "1";
  123. }
  124. if(strlen(macro.Name)>0)
  125. {
  126. defines.push_back(macro);
  127. }
  128. else
  129. {
  130. break;
  131. }
  132. }
  133. // Add NULL terminator
  134. macro.Name = 0;
  135. macro.Definition = 0;
  136. defines.push_back(macro);
  137. pDefines = &defines[0];
  138. }
  139. // Populate compile flags
  140. DWORD compileFlags = 0;
  141. if (mColumnMajorMatrices)
  142. compileFlags |= D3DXSHADER_PACKMATRIX_COLUMNMAJOR;
  143. else
  144. compileFlags |= D3DXSHADER_PACKMATRIX_ROWMAJOR;
  145. #if CM_DEBUG_MODE
  146. compileFlags |= D3DXSHADER_DEBUG;
  147. #endif
  148. switch (mOptimisationLevel)
  149. {
  150. case OPT_DEFAULT:
  151. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1;
  152. break;
  153. case OPT_NONE:
  154. compileFlags |= D3DXSHADER_SKIPOPTIMIZATION;
  155. break;
  156. case OPT_0:
  157. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL0;
  158. break;
  159. case OPT_1:
  160. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1;
  161. break;
  162. case OPT_2:
  163. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL2;
  164. break;
  165. case OPT_3:
  166. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL3;
  167. break;
  168. }
  169. LPD3DXBUFFER errors = 0;
  170. // include handler
  171. HLSLIncludeHandler includeHandler(this);
  172. String hlslProfile = GpuProgramManager::instance().gpuProgProfileToRSSpecificProfile(mProfile);
  173. // Compile & assemble into microcode
  174. HRESULT hr = D3DXCompileShader(
  175. mSource.c_str(),
  176. static_cast<UINT>(mSource.length()),
  177. pDefines,
  178. &includeHandler,
  179. mEntryPoint.c_str(),
  180. hlslProfile.c_str(),
  181. compileFlags,
  182. &mpMicroCode,
  183. &errors,
  184. &mpConstTable);
  185. if (FAILED(hr))
  186. {
  187. String message = "Cannot assemble D3D9 high-level shader ";
  188. if( errors )
  189. {
  190. message += String(" Errors:\n") + static_cast<const char*>(errors->GetBufferPointer());
  191. errors->Release();
  192. }
  193. CM_EXCEPT(RenderingAPIException, message);
  194. }
  195. }
  196. //-----------------------------------------------------------------------
  197. void D3D9HLSLProgram::createLowLevelImpl(void)
  198. {
  199. if (!mCompileError)
  200. {
  201. String hlslProfile = GpuProgramManager::instance().gpuProgProfileToRSSpecificProfile(mProfile);
  202. // Create a low-level program, give it the same name as us
  203. mAssemblerProgram =
  204. GpuProgramManager::instance().createProgram(
  205. "",// dummy source, since we'll be using microcode
  206. mType,
  207. hlslProfile);
  208. static_cast<D3D9GpuProgram*>(mAssemblerProgram.get())->setExternalMicrocode(mpMicroCode);
  209. }
  210. }
  211. //-----------------------------------------------------------------------
  212. void D3D9HLSLProgram::unloadHighLevelImpl(void)
  213. {
  214. SAFE_RELEASE(mpMicroCode);
  215. SAFE_RELEASE(mpConstTable);
  216. }
  217. //-----------------------------------------------------------------------
  218. void D3D9HLSLProgram::buildConstantDefinitions() const
  219. {
  220. // Derive parameter names from const table
  221. assert(mpConstTable && "Program not loaded!");
  222. // Get contents of the constant table
  223. D3DXCONSTANTTABLE_DESC desc;
  224. HRESULT hr = mpConstTable->GetDesc(&desc);
  225. createParameterMappingStructures(true);
  226. if (FAILED(hr))
  227. {
  228. CM_EXCEPT(InternalErrorException, "Cannot retrieve constant descriptions from HLSL program.");
  229. }
  230. // Iterate over the constants
  231. for (unsigned int i = 0; i < desc.Constants; ++i)
  232. {
  233. // Recursively descend through the structure levels
  234. processParamElement(NULL, "", i);
  235. }
  236. }
  237. //-----------------------------------------------------------------------
  238. void D3D9HLSLProgram::processParamElement(D3DXHANDLE parent, String prefix,
  239. unsigned int index) const
  240. {
  241. D3DXHANDLE hConstant = mpConstTable->GetConstant(parent, index);
  242. // Since D3D HLSL doesn't deal with naming of array and struct parameters
  243. // automatically, we have to do it by hand
  244. D3DXCONSTANT_DESC desc;
  245. unsigned int numParams = 1;
  246. HRESULT hr = mpConstTable->GetConstantDesc(hConstant, &desc, &numParams);
  247. if (FAILED(hr))
  248. {
  249. CM_EXCEPT(InternalErrorException, "Cannot retrieve constant description from HLSL program.");
  250. }
  251. String paramName = desc.Name;
  252. // trim the odd '$' which appears at the start of the names in HLSL
  253. if (paramName.at(0) == '$')
  254. paramName.erase(paramName.begin());
  255. // Also trim the '[0]' suffix if it exists, we will add our own indexing later
  256. if (StringUtil::endsWith(paramName, "[0]", false))
  257. {
  258. paramName.erase(paramName.size() - 3);
  259. }
  260. if (desc.Class == D3DXPC_STRUCT)
  261. {
  262. // work out a new prefix for nested members, if it's an array, we need an index
  263. prefix = prefix + paramName + ".";
  264. // Cascade into struct
  265. for (unsigned int i = 0; i < desc.StructMembers; ++i)
  266. {
  267. processParamElement(hConstant, prefix, i);
  268. }
  269. }
  270. else
  271. {
  272. // Process params
  273. if (desc.Type == D3DXPT_FLOAT || desc.Type == D3DXPT_INT || desc.Type == D3DXPT_BOOL)
  274. {
  275. size_t paramIndex = desc.RegisterIndex;
  276. String name = prefix + paramName;
  277. GpuConstantDefinition def;
  278. def.logicalIndex = paramIndex;
  279. // populate type, array size & element size
  280. populateDef(desc, def);
  281. if (def.isFloat())
  282. {
  283. def.physicalIndex = mFloatLogicalToPhysical->bufferSize;
  284. CM_LOCK_MUTEX(mFloatLogicalToPhysical->mutex)
  285. mFloatLogicalToPhysical->map.insert(
  286. GpuLogicalIndexUseMap::value_type(paramIndex,
  287. GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL)));
  288. mFloatLogicalToPhysical->bufferSize += def.arraySize * def.elementSize;
  289. mConstantDefs->floatBufferSize = mFloatLogicalToPhysical->bufferSize;
  290. }
  291. else
  292. {
  293. def.physicalIndex = mIntLogicalToPhysical->bufferSize;
  294. CM_LOCK_MUTEX(mIntLogicalToPhysical->mutex)
  295. mIntLogicalToPhysical->map.insert(
  296. GpuLogicalIndexUseMap::value_type(paramIndex,
  297. GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL)));
  298. mIntLogicalToPhysical->bufferSize += def.arraySize * def.elementSize;
  299. mConstantDefs->intBufferSize = mIntLogicalToPhysical->bufferSize;
  300. }
  301. mConstantDefs->map.insert(GpuConstantDefinitionMap::value_type(name, def));
  302. // Now deal with arrays
  303. mConstantDefs->generateConstantDefinitionArrayEntries(name, def);
  304. }
  305. }
  306. }
  307. //-----------------------------------------------------------------------
  308. void D3D9HLSLProgram::populateDef(D3DXCONSTANT_DESC& d3dDesc, GpuConstantDefinition& def) const
  309. {
  310. def.arraySize = d3dDesc.Elements;
  311. switch(d3dDesc.Type)
  312. {
  313. case D3DXPT_INT:
  314. switch(d3dDesc.Columns)
  315. {
  316. case 1:
  317. def.constType = GCT_INT1;
  318. break;
  319. case 2:
  320. def.constType = GCT_INT2;
  321. break;
  322. case 3:
  323. def.constType = GCT_INT3;
  324. break;
  325. case 4:
  326. def.constType = GCT_INT4;
  327. break;
  328. } // columns
  329. break;
  330. case D3DXPT_FLOAT:
  331. switch(d3dDesc.Class)
  332. {
  333. case D3DXPC_MATRIX_COLUMNS:
  334. case D3DXPC_MATRIX_ROWS:
  335. {
  336. int firstDim, secondDim;
  337. firstDim = d3dDesc.RegisterCount / d3dDesc.Elements;
  338. if (d3dDesc.Class == D3DXPC_MATRIX_ROWS)
  339. {
  340. secondDim = d3dDesc.Columns;
  341. }
  342. else
  343. {
  344. secondDim = d3dDesc.Rows;
  345. }
  346. switch(firstDim)
  347. {
  348. case 2:
  349. switch(secondDim)
  350. {
  351. case 2:
  352. def.constType = GCT_MATRIX_2X2;
  353. def.elementSize = 8; // HLSL always packs
  354. break;
  355. case 3:
  356. def.constType = GCT_MATRIX_2X3;
  357. def.elementSize = 8; // HLSL always packs
  358. break;
  359. case 4:
  360. def.constType = GCT_MATRIX_2X4;
  361. def.elementSize = 8;
  362. break;
  363. } // columns
  364. break;
  365. case 3:
  366. switch(secondDim)
  367. {
  368. case 2:
  369. def.constType = GCT_MATRIX_3X2;
  370. def.elementSize = 12; // HLSL always packs
  371. break;
  372. case 3:
  373. def.constType = GCT_MATRIX_3X3;
  374. def.elementSize = 12; // HLSL always packs
  375. break;
  376. case 4:
  377. def.constType = GCT_MATRIX_3X4;
  378. def.elementSize = 12;
  379. break;
  380. } // columns
  381. break;
  382. case 4:
  383. switch(secondDim)
  384. {
  385. case 2:
  386. def.constType = GCT_MATRIX_4X2;
  387. def.elementSize = 16; // HLSL always packs
  388. break;
  389. case 3:
  390. def.constType = GCT_MATRIX_4X3;
  391. def.elementSize = 16; // HLSL always packs
  392. break;
  393. case 4:
  394. def.constType = GCT_MATRIX_4X4;
  395. def.elementSize = 16;
  396. break;
  397. } // secondDim
  398. break;
  399. } // firstDim
  400. }
  401. break;
  402. case D3DXPC_SCALAR:
  403. case D3DXPC_VECTOR:
  404. switch(d3dDesc.Columns)
  405. {
  406. case 1:
  407. def.constType = GCT_FLOAT1;
  408. break;
  409. case 2:
  410. def.constType = GCT_FLOAT2;
  411. break;
  412. case 3:
  413. def.constType = GCT_FLOAT3;
  414. break;
  415. case 4:
  416. def.constType = GCT_FLOAT4;
  417. break;
  418. } // columns
  419. break;
  420. }
  421. default:
  422. // not mapping samplers, don't need to take the space
  423. break;
  424. };
  425. // D3D9 pads to 4 elements
  426. def.elementSize = GpuConstantDefinition::getElementSize(def.constType, true);
  427. }
  428. LPD3DXBUFFER D3D9HLSLProgram::getMicroCode()
  429. {
  430. return mpMicroCode;
  431. }
  432. const String D3D9HLSLProgram::getTarget(void) const
  433. {
  434. return GpuProgramManager::instance().gpuProgProfileToRSSpecificProfile(mProfile);
  435. }
  436. //-----------------------------------------------------------------------
  437. D3D9HLSLProgram::D3D9HLSLProgram()
  438. : HighLevelGpuProgram()
  439. , mPreprocessorDefines()
  440. , mColumnMajorMatrices(true)
  441. , mpMicroCode(NULL), mpConstTable(NULL)
  442. , mOptimisationLevel(OPT_DEFAULT)
  443. {
  444. }
  445. //-----------------------------------------------------------------------
  446. D3D9HLSLProgram::~D3D9HLSLProgram()
  447. {
  448. unloadHighLevel();
  449. }
  450. //-----------------------------------------------------------------------
  451. bool D3D9HLSLProgram::isSupported(void) const
  452. {
  453. if (mCompileError || !isRequiredCapabilitiesSupported())
  454. return false;
  455. String hlslProfile = GpuProgramManager::instance().gpuProgProfileToRSSpecificProfile(mProfile);
  456. RenderSystem* rs = CamelotEngine::RenderSystemManager::getActive();
  457. return rs->getCapabilities()->isShaderProfileSupported(hlslProfile);
  458. }
  459. //-----------------------------------------------------------------------
  460. GpuProgramParametersSharedPtr D3D9HLSLProgram::createParameters(void)
  461. {
  462. // Call superclass
  463. GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters();
  464. // Need to transpose matrices if compiled with column-major matrices
  465. params->setTransposeMatrices(mColumnMajorMatrices);
  466. return params;
  467. }
  468. //-----------------------------------------------------------------------
  469. void D3D9HLSLProgram::setTarget(const String& target)
  470. {
  471. //mTarget = target;
  472. }
  473. //-----------------------------------------------------------------------
  474. const String& D3D9HLSLProgram::getLanguage(void) const
  475. {
  476. static const String language = "hlsl";
  477. return language;
  478. }
  479. }