shaderGen.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "shaderGen/shaderGen.h"
  24. #include "shaderGen/conditionerFeature.h"
  25. #include "core/stream/fileStream.h"
  26. #include "shaderGen/featureMgr.h"
  27. #include "shaderGen/shaderOp.h"
  28. #include "gfx/gfxDevice.h"
  29. #include "core/memVolume.h"
  30. #include "core/module.h"
  31. #ifdef TORQUE_D3D11
  32. #include "shaderGen/HLSL/customFeatureHLSL.h"
  33. #endif
  34. #ifdef TORQUE_OPENGL
  35. #include "shaderGen/GLSL/customFeatureGLSL.h"
  36. #endif
  37. MODULE_BEGIN( ShaderGen )
  38. MODULE_INIT_BEFORE( GFX )
  39. MODULE_SHUTDOWN_AFTER( GFX )
  40. MODULE_INIT
  41. {
  42. ManagedSingleton< ShaderGen >::createSingleton();
  43. }
  44. MODULE_SHUTDOWN
  45. {
  46. ManagedSingleton< ShaderGen >::deleteSingleton();
  47. }
  48. MODULE_END;
  49. String ShaderGen::smCommonShaderPath("shaders/common");
  50. ShaderGen::ShaderGen()
  51. {
  52. mInit = false;
  53. GFXDevice::getDeviceEventSignal().notify(this, &ShaderGen::_handleGFXEvent);
  54. mOutput = NULL;
  55. }
  56. ShaderGen::~ShaderGen()
  57. {
  58. GFXDevice::getDeviceEventSignal().remove(this, &ShaderGen::_handleGFXEvent);
  59. _uninit();
  60. }
  61. void ShaderGen::registerInitDelegate(GFXAdapterType adapterType, ShaderGenInitDelegate& initDelegate)
  62. {
  63. mInitDelegates[(U32)adapterType] = initDelegate;
  64. }
  65. bool ShaderGen::_handleGFXEvent(GFXDevice::GFXDeviceEventType event)
  66. {
  67. switch (event)
  68. {
  69. case GFXDevice::deInit :
  70. initShaderGen();
  71. break;
  72. case GFXDevice::deDestroy :
  73. {
  74. flushProceduralShaders();
  75. }
  76. break;
  77. default :
  78. break;
  79. }
  80. return true;
  81. }
  82. void ShaderGen::initShaderGen()
  83. {
  84. if (mInit)
  85. return;
  86. const GFXAdapterType adapterType = GFX->getAdapterType();
  87. if (!mInitDelegates[adapterType])
  88. return;
  89. smCommonShaderPath = String(Con::getVariable("$Core::CommonShaderPath", "shaders/common"));
  90. mInitDelegates[adapterType](this);
  91. mFeatureInitSignal.trigger( adapterType );
  92. mInit = true;
  93. String shaderPath = Con::getVariable( "$shaderGen::cachePath");
  94. if (!shaderPath.equal( "shadergen:" ) && !shaderPath.isEmpty() )
  95. {
  96. // this is necessary, especially under Windows with UAC enabled
  97. if (!Torque::FS::VerifyWriteAccess(shaderPath))
  98. {
  99. // we don't have write access so enable the virtualized memory store
  100. Con::warnf("ShaderGen: Write permission unavailable, switching to virtualized memory storage");
  101. shaderPath.clear();
  102. }
  103. }
  104. if ( shaderPath.equal( "shadergen:" ) || shaderPath.isEmpty() )
  105. {
  106. // If we didn't get a path then we're gonna cache the shaders to
  107. // a virtualized memory file system.
  108. mMemFS = new Torque::Mem::MemFileSystem( "shadergen:/" );
  109. Torque::FS::Mount( "shadergen", mMemFS );
  110. }
  111. else
  112. Torque::FS::Mount( "shadergen", shaderPath + "/" );
  113. // Delete the auto-generated conditioner include file.
  114. Torque::FS::Remove( "shadergen:/" + ConditionerFeature::ConditionerIncludeFileName );
  115. }
  116. void ShaderGen::generateShader( const MaterialFeatureData &featureData,
  117. char *vertFile,
  118. char *pixFile,
  119. F32 *pixVersion,
  120. const GFXVertexFormat *vertexFormat,
  121. const char* cacheName,
  122. Vector<GFXShaderMacro> &macros)
  123. {
  124. PROFILE_SCOPE( ShaderGen_GenerateShader );
  125. mFeatureData = featureData;
  126. mVertexFormat = vertexFormat;
  127. _uninit();
  128. _init();
  129. char vertShaderName[256];
  130. char pixShaderName[256];
  131. // Note: We use a postfix of _V/_P here so that it sorts the matching
  132. // vert and pixel shaders together when listed alphabetically.
  133. dSprintf( vertShaderName, sizeof(vertShaderName), "shadergen:/%s_V.%s", cacheName, mFileEnding.c_str() );
  134. dSprintf( pixShaderName, sizeof(pixShaderName), "shadergen:/%s_P.%s", cacheName, mFileEnding.c_str() );
  135. dStrcpy( vertFile, vertShaderName, 256 );
  136. dStrcpy( pixFile, pixShaderName, 256 );
  137. // this needs to change - need to optimize down to ps v.1.1
  138. *pixVersion = GFX->getPixelShaderVersion();
  139. if ( !Con::getBoolVariable( "ShaderGen::GenNewShaders", true ) )
  140. {
  141. // If we are not regenerating the shader we will return here.
  142. // But we must fill in the shader macros first!
  143. _processVertFeatures( macros, true );
  144. _processPixFeatures( macros, true );
  145. return;
  146. }
  147. // create vertex shader
  148. //------------------------
  149. FileStream* s = new FileStream();
  150. if(!s->open(vertShaderName, Torque::FS::File::Write ))
  151. {
  152. AssertFatal(false, "Failed to open Shader Stream" );
  153. return;
  154. }
  155. mOutput = new MultiLine;
  156. mInstancingFormat.clear();
  157. _processVertFeatures(macros);
  158. _printVertShader( *s );
  159. delete s;
  160. ((ShaderConnector*)mComponents[C_CONNECTOR])->reset();
  161. LangElement::deleteElements();
  162. // create pixel shader
  163. //------------------------
  164. s = new FileStream();
  165. if(!s->open(pixShaderName, Torque::FS::File::Write ))
  166. {
  167. AssertFatal(false, "Failed to open Shader Stream" );
  168. delete s;
  169. return;
  170. }
  171. mOutput = new MultiLine;
  172. _processPixFeatures(macros);
  173. _printPixShader( *s );
  174. delete s;
  175. LangElement::deleteElements();
  176. }
  177. void ShaderGen::_init()
  178. {
  179. _createComponents();
  180. }
  181. void ShaderGen::_uninit()
  182. {
  183. for( U32 i=0; i<mComponents.size(); i++ )
  184. {
  185. delete mComponents[i];
  186. mComponents[i] = NULL;
  187. }
  188. mComponents.setSize(0);
  189. LangElement::deleteElements();
  190. Var::reset();
  191. }
  192. void ShaderGen::_createComponents()
  193. {
  194. ShaderComponent* vertComp = mComponentFactory->createVertexInputConnector( *mVertexFormat );
  195. mComponents.push_back(vertComp);
  196. ShaderComponent* vertPixelCon = mComponentFactory->createVertexPixelConnector();
  197. mComponents.push_back(vertPixelCon);
  198. ShaderComponent* vertParamDef = mComponentFactory->createVertexParamsDef();
  199. mComponents.push_back(vertParamDef);
  200. ShaderComponent* pixParamDef = mComponentFactory->createPixelParamsDef();
  201. mComponents.push_back(pixParamDef);
  202. }
  203. //----------------------------------------------------------------------------
  204. // Process features
  205. //----------------------------------------------------------------------------
  206. void ShaderGen::_processVertFeatures( Vector<GFXShaderMacro> &macros, bool macrosOnly )
  207. {
  208. const FeatureSet &features = mFeatureData.features;
  209. for( U32 i=0; i < features.getCount(); i++ )
  210. {
  211. S32 index;
  212. const FeatureType &type = features.getAt( i, &index );
  213. ShaderFeature* feature = FEATUREMGR->getByType( type );
  214. if ( feature )
  215. {
  216. feature->setProcessIndex( index );
  217. feature->processVertMacros( macros, mFeatureData );
  218. if ( macrosOnly )
  219. continue;
  220. feature->setInstancingFormat( &mInstancingFormat );
  221. feature->mVertexFormat = mVertexFormat;
  222. feature->processVert( mComponents, mFeatureData );
  223. String line;
  224. if ( index > -1 )
  225. line = String::ToString( " // %s %d\r\n", feature->getName().c_str(), index );
  226. else
  227. line = String::ToString( " // %s\r\n", feature->getName().c_str() );
  228. mOutput->addStatement( new GenOp( line ) );
  229. if ( feature->getOutput() )
  230. mOutput->addStatement( feature->getOutput() );
  231. feature->reset();
  232. mOutput->addStatement( new GenOp( " \r\n" ) );
  233. }
  234. }
  235. ShaderConnector *connect = dynamic_cast<ShaderConnector *>( mComponents[C_CONNECTOR] );
  236. connect->sortVars();
  237. }
  238. void ShaderGen::_processPixFeatures( Vector<GFXShaderMacro> &macros, bool macrosOnly )
  239. {
  240. const FeatureSet &features = mFeatureData.features;
  241. for( U32 i=0; i < features.getCount(); i++ )
  242. {
  243. S32 index;
  244. const FeatureType &type = features.getAt( i, &index );
  245. ShaderFeature* feature = FEATUREMGR->getByType( type );
  246. if ( feature )
  247. {
  248. feature->setProcessIndex( index );
  249. feature->processPixMacros( macros, mFeatureData );
  250. if ( macrosOnly )
  251. continue;
  252. feature->setInstancingFormat( &mInstancingFormat );
  253. feature->processPix( mComponents, mFeatureData );
  254. String line;
  255. if ( index > -1 )
  256. line = String::ToString( " // %s %d\r\n", feature->getName().c_str(), index );
  257. else
  258. line = String::ToString( " // %s\r\n", feature->getName().c_str() );
  259. mOutput->addStatement( new GenOp( line ) );
  260. if ( feature->getOutput() )
  261. mOutput->addStatement( feature->getOutput() );
  262. feature->reset();
  263. mOutput->addStatement( new GenOp( " \r\n" ) );
  264. }
  265. }
  266. ShaderConnector *connect = dynamic_cast<ShaderConnector *>( mComponents[C_CONNECTOR] );
  267. connect->sortVars();
  268. }
  269. void ShaderGen::_printFeatureList(Stream &stream)
  270. {
  271. mPrinter->printLine(stream, "// Features:");
  272. const FeatureSet &features = mFeatureData.features;
  273. for( U32 i=0; i < features.getCount(); i++ )
  274. {
  275. S32 index;
  276. const FeatureType &type = features.getAt( i, &index );
  277. ShaderFeature* feature = FEATUREMGR->getByType( type );
  278. if ( feature )
  279. {
  280. String line;
  281. if ( index > -1 )
  282. line = String::ToString( "// %s %d", feature->getName().c_str(), index );
  283. else
  284. line = String::ToString( "// %s", feature->getName().c_str() );
  285. mPrinter->printLine( stream, line );
  286. }
  287. }
  288. mPrinter->printLine(stream, "");
  289. }
  290. void ShaderGen::_printDependencies(Stream &stream)
  291. {
  292. Vector<const ShaderDependency *> dependencies;
  293. for( U32 i=0; i < FEATUREMGR->getFeatureCount(); i++ )
  294. {
  295. const FeatureInfo &info = FEATUREMGR->getAt( i );
  296. if ( mFeatureData.features.hasFeature( *info.type ) )
  297. dependencies.merge( info.feature->getDependencies() );
  298. }
  299. // Do a quick loop removing any duplicate dependancies.
  300. for( U32 i=0; i < dependencies.size(); )
  301. {
  302. bool dup = false;
  303. for( U32 j=0; j < dependencies.size(); j++ )
  304. {
  305. if ( j != i &&
  306. *dependencies[i] == *dependencies[j] )
  307. {
  308. dup = true;
  309. break;
  310. }
  311. }
  312. if ( dup )
  313. dependencies.erase( i );
  314. else
  315. i++;
  316. }
  317. // Print dependencies
  318. if( dependencies.size() > 0 )
  319. {
  320. mPrinter->printLine(stream, "// Dependencies:");
  321. for( S32 i = 0; i < dependencies.size(); i++ )
  322. dependencies[i]->print( stream );
  323. mPrinter->printLine(stream, "");
  324. }
  325. }
  326. void ShaderGen::_printFeatures( Stream &stream )
  327. {
  328. mOutput->print( stream );
  329. }
  330. void ShaderGen::_printVertShader( Stream &stream )
  331. {
  332. mPrinter->printShaderHeader(stream);
  333. _printDependencies(stream); // TODO: Split into vert and pix dependencies?
  334. _printFeatureList(stream);
  335. // print out structures
  336. mComponents[C_VERT_STRUCT]->print( stream, true );
  337. mComponents[C_CONNECTOR]->print( stream, true );
  338. mPrinter->printMainComment(stream);
  339. mComponents[C_VERT_MAIN]->print( stream, true );
  340. mComponents[C_VERT_STRUCT]->printOnMain( stream, true );
  341. // print out the function
  342. _printFeatures( stream );
  343. mPrinter->printVertexShaderCloser(stream);
  344. }
  345. void ShaderGen::_printPixShader( Stream &stream )
  346. {
  347. mPrinter->printShaderHeader(stream);
  348. _printDependencies(stream); // TODO: Split into vert and pix dependencies?
  349. _printFeatureList(stream);
  350. mComponents[C_CONNECTOR]->print( stream, false );
  351. mPrinter->printPixelShaderOutputStruct(stream, mFeatureData);
  352. mPrinter->printMainComment(stream);
  353. mComponents[C_PIX_MAIN]->print( stream, false );
  354. mComponents[C_CONNECTOR]->printOnMain( stream, false );
  355. // print out the function
  356. _printFeatures( stream );
  357. mPrinter->printPixelShaderCloser(stream);
  358. }
  359. GFXShader* ShaderGen::getShader( const MaterialFeatureData &featureData, const GFXVertexFormat *vertexFormat, const Vector<GFXShaderMacro> *macros, const Vector<String> &samplers )
  360. {
  361. PROFILE_SCOPE( ShaderGen_GetShader );
  362. const FeatureSet &features = featureData.codify();
  363. // Build a description string from the features
  364. // and vertex format combination ( and macros ).
  365. String shaderDescription = vertexFormat->getDescription() + features.getDescription();
  366. // Generate a single 64bit hash from the description string.
  367. //
  368. // Don't get paranoid! This has 1 in 18446744073709551616
  369. // chance for collision... it won't happen in this lifetime.
  370. //
  371. shaderDescription.replace("\n", " ");
  372. U64 hash = Torque::hash64( (const U8*)shaderDescription.c_str(), shaderDescription.length(), 0 );
  373. hash = convertHostToLEndian(hash);
  374. U32 high = (U32)( hash >> 32 );
  375. U32 low = (U32)( hash & 0x00000000FFFFFFFF );
  376. String cacheKey = String::ToString( "%x%x", high, low );
  377. // return shader if exists
  378. GFXShader *match = mProcShaders[cacheKey];
  379. if ( match )
  380. return match;
  381. // if not, then create it
  382. char vertFile[256];
  383. char pixFile[256];
  384. F32 pixVersion;
  385. Vector<GFXShaderMacro> shaderMacros;
  386. shaderMacros.push_back( GFXShaderMacro( "TORQUE_SHADERGEN" ) );
  387. if ( macros )
  388. shaderMacros.merge( *macros );
  389. generateShader( featureData, vertFile, pixFile, &pixVersion, vertexFormat, cacheKey, shaderMacros );
  390. GFXShader *shader = GFX->createShader();
  391. shader->setShaderStageFile(GFXShaderStage::VERTEX_SHADER, vertFile);
  392. shader->setShaderStageFile(GFXShaderStage::PIXEL_SHADER, pixFile);
  393. if (!shader->init(pixVersion, shaderMacros, samplers, &mInstancingFormat))
  394. {
  395. delete shader;
  396. return NULL;
  397. }
  398. mProcShaders[cacheKey] = shader;
  399. return shader;
  400. }
  401. void ShaderGen::flushProceduralShaders()
  402. {
  403. // The shaders are reference counted, so we
  404. // just need to clear the map.
  405. mProcShaders.clear();
  406. }