gfxGLShader.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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 "gfx/gl/gfxGLShader.h"
  24. #include "gfx/gl/gfxGLVertexAttribLocation.h"
  25. #include "core/frameAllocator.h"
  26. #include "core/stream/fileStream.h"
  27. #include "core/strings/stringFunctions.h"
  28. #include "math/mPoint2.h"
  29. #include "gfx/gfxStructs.h"
  30. #include "console/console.h"
  31. class GFXGLShaderConstHandle : public GFXShaderConstHandle
  32. {
  33. friend class GFXGLShader;
  34. public:
  35. GFXGLShaderConstHandle( GFXGLShader *shader );
  36. GFXGLShaderConstHandle( GFXGLShader *shader, const GFXShaderConstDesc &desc, GLuint loc, S32 samplerNum );
  37. virtual ~GFXGLShaderConstHandle();
  38. void reinit( const GFXShaderConstDesc &desc, GLuint loc, S32 samplerNum );
  39. const String& getName() const { return mDesc.name; }
  40. GFXShaderConstType getType() const { return mDesc.constType; }
  41. U32 getArraySize() const { return mDesc.arraySize; }
  42. U32 getSize() const;
  43. void setValid( bool valid ) { mValid = valid; }
  44. /// @warning This will always return the value assigned when the shader was
  45. /// initialized. If the value is later changed this method won't reflect that.
  46. S32 getSamplerRegister() const { return mSamplerNum; }
  47. GFXShaderConstDesc mDesc;
  48. GFXGLShader* mShader;
  49. GLuint mLocation;
  50. U32 mOffset;
  51. U32 mSize;
  52. S32 mSamplerNum;
  53. bool mInstancingConstant;
  54. };
  55. GFXGLShaderConstHandle::GFXGLShaderConstHandle( GFXGLShader *shader )
  56. : mShader( shader ), mLocation(0), mOffset(0), mSize(0), mSamplerNum(-1), mInstancingConstant(false)
  57. {
  58. mValid = false;
  59. }
  60. static U32 shaderConstTypeSize(GFXShaderConstType type)
  61. {
  62. switch(type)
  63. {
  64. case GFXSCT_Float:
  65. case GFXSCT_Int:
  66. case GFXSCT_Sampler:
  67. case GFXSCT_SamplerCube:
  68. return 4;
  69. case GFXSCT_Float2:
  70. case GFXSCT_Int2:
  71. return 8;
  72. case GFXSCT_Float3:
  73. case GFXSCT_Int3:
  74. return 12;
  75. case GFXSCT_Float4:
  76. case GFXSCT_Int4:
  77. return 16;
  78. case GFXSCT_Float2x2:
  79. return 16;
  80. case GFXSCT_Float3x3:
  81. return 36;
  82. case GFXSCT_Float4x4:
  83. return 64;
  84. default:
  85. AssertFatal(false,"shaderConstTypeSize - Unrecognized constant type");
  86. return 0;
  87. }
  88. }
  89. GFXGLShaderConstHandle::GFXGLShaderConstHandle( GFXGLShader *shader, const GFXShaderConstDesc &desc, GLuint loc, S32 samplerNum )
  90. : mShader(shader), mInstancingConstant(false)
  91. {
  92. reinit(desc, loc, samplerNum);
  93. }
  94. void GFXGLShaderConstHandle::reinit( const GFXShaderConstDesc& desc, GLuint loc, S32 samplerNum )
  95. {
  96. mDesc = desc;
  97. mLocation = loc;
  98. mSamplerNum = samplerNum;
  99. mOffset = 0;
  100. mInstancingConstant = false;
  101. U32 elemSize = shaderConstTypeSize(mDesc.constType);
  102. AssertFatal(elemSize, "GFXGLShaderConst::GFXGLShaderConst - elemSize is 0");
  103. mSize = mDesc.arraySize * elemSize;
  104. mValid = true;
  105. }
  106. U32 GFXGLShaderConstHandle::getSize() const
  107. {
  108. return mSize;
  109. }
  110. GFXGLShaderConstHandle::~GFXGLShaderConstHandle()
  111. {
  112. }
  113. GFXGLShaderConstBuffer::GFXGLShaderConstBuffer(GFXGLShader* shader, U32 bufSize, U8* existingConstants)
  114. {
  115. mShader = shader;
  116. mBuffer = new U8[bufSize];
  117. mWasLost = true;
  118. // Copy the existing constant buffer to preserve sampler numbers
  119. /// @warning This preserves a lot more than sampler numbers, obviously. If there
  120. /// is any code that assumes a new constant buffer will have everything set to
  121. /// 0, it will break.
  122. dMemcpy(mBuffer, existingConstants, bufSize);
  123. }
  124. GFXGLShaderConstBuffer::~GFXGLShaderConstBuffer()
  125. {
  126. delete[] mBuffer;
  127. if ( mShader )
  128. mShader->_unlinkBuffer( this );
  129. }
  130. template<typename ConstType>
  131. void GFXGLShaderConstBuffer::internalSet(GFXShaderConstHandle* handle, const ConstType& param)
  132. {
  133. AssertFatal(handle, "GFXGLShaderConstBuffer::internalSet - Handle is NULL!" );
  134. AssertFatal(handle->isValid(), "GFXGLShaderConstBuffer::internalSet - Handle is not valid!" );
  135. AssertFatal(dynamic_cast<GFXGLShaderConstHandle*>(handle), "GFXGLShaderConstBuffer::set - Incorrect const buffer type");
  136. GFXGLShaderConstHandle* _glHandle = static_cast<GFXGLShaderConstHandle*>(handle);
  137. AssertFatal(mShader == _glHandle->mShader, "GFXGLShaderConstBuffer::set - Should only set handles which are owned by our shader");
  138. U8 *buf = mBuffer + _glHandle->mOffset;
  139. if(_glHandle->mInstancingConstant)
  140. buf = mInstPtr + _glHandle->mOffset;
  141. dMemcpy(buf, &param, sizeof(ConstType));
  142. }
  143. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const F32 fv)
  144. {
  145. internalSet(handle, fv);
  146. }
  147. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2F& fv)
  148. {
  149. internalSet(handle, fv);
  150. }
  151. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3F& fv)
  152. {
  153. internalSet(handle, fv);
  154. }
  155. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4F& fv)
  156. {
  157. internalSet(handle, fv);
  158. }
  159. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const PlaneF& fv)
  160. {
  161. internalSet(handle, fv);
  162. }
  163. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const ColorF& fv)
  164. {
  165. internalSet(handle, fv);
  166. }
  167. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const S32 fv)
  168. {
  169. internalSet(handle, fv);
  170. }
  171. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2I& fv)
  172. {
  173. internalSet(handle, fv);
  174. }
  175. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3I& fv)
  176. {
  177. internalSet(handle, fv);
  178. }
  179. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4I& fv)
  180. {
  181. internalSet(handle, fv);
  182. }
  183. template<typename ConstType>
  184. void GFXGLShaderConstBuffer::internalSet(GFXShaderConstHandle* handle, const AlignedArray<ConstType>& fv)
  185. {
  186. AssertFatal(handle, "GFXGLShaderConstBuffer::internalSet - Handle is NULL!" );
  187. AssertFatal(handle->isValid(), "GFXGLShaderConstBuffer::internalSet - Handle is not valid!" );
  188. AssertFatal(dynamic_cast<GFXGLShaderConstHandle*>(handle), "GFXGLShaderConstBuffer::set - Incorrect const buffer type");
  189. GFXGLShaderConstHandle* _glHandle = static_cast<GFXGLShaderConstHandle*>(handle);
  190. AssertFatal(mShader == _glHandle->mShader, "GFXGLShaderConstBuffer::set - Should only set handles which are owned by our shader");
  191. AssertFatal(!_glHandle->mInstancingConstant, "GFXGLShaderConstBuffer::set - Instancing not supported for array");
  192. const U8* fvBuffer = static_cast<const U8*>(fv.getBuffer());
  193. for(U32 i = 0; i < fv.size(); ++i)
  194. {
  195. dMemcpy(mBuffer + _glHandle->mOffset + i * sizeof(ConstType), fvBuffer, sizeof(ConstType));
  196. fvBuffer += fv.getElementSize();
  197. }
  198. }
  199. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<F32>& fv)
  200. {
  201. internalSet(handle, fv);
  202. }
  203. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point2F>& fv)
  204. {
  205. internalSet(handle, fv);
  206. }
  207. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point3F>& fv)
  208. {
  209. internalSet(handle, fv);
  210. }
  211. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point4F>& fv)
  212. {
  213. internalSet(handle, fv);
  214. }
  215. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<S32>& fv)
  216. {
  217. internalSet(handle, fv);
  218. }
  219. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point2I>& fv)
  220. {
  221. internalSet(handle, fv);
  222. }
  223. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point3I>& fv)
  224. {
  225. internalSet(handle, fv);
  226. }
  227. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point4I>& fv)
  228. {
  229. internalSet(handle, fv);
  230. }
  231. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF& mat, const GFXShaderConstType matType)
  232. {
  233. AssertFatal(handle, "GFXGLShaderConstBuffer::set - Handle is NULL!" );
  234. AssertFatal(handle->isValid(), "GFXGLShaderConstBuffer::set - Handle is not valid!" );
  235. AssertFatal(dynamic_cast<GFXGLShaderConstHandle*>(handle), "GFXGLShaderConstBuffer::set - Incorrect const buffer type");
  236. GFXGLShaderConstHandle* _glHandle = static_cast<GFXGLShaderConstHandle*>(handle);
  237. AssertFatal(mShader == _glHandle->mShader, "GFXGLShaderConstBuffer::set - Should only set handles which are owned by our shader");
  238. AssertFatal(!_glHandle->mInstancingConstant || matType == GFXSCT_Float4x4, "GFXGLShaderConstBuffer::set - Only support GFXSCT_Float4x4 for instancing");
  239. switch(matType)
  240. {
  241. case GFXSCT_Float2x2:
  242. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[0] = mat[0];
  243. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[1] = mat[1];
  244. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[2] = mat[4];
  245. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[3] = mat[5];
  246. break;
  247. case GFXSCT_Float3x3:
  248. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[0] = mat[0];
  249. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[1] = mat[1];
  250. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[2] = mat[2];
  251. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[3] = mat[4];
  252. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[4] = mat[5];
  253. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[5] = mat[6];
  254. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[6] = mat[8];
  255. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[7] = mat[9];
  256. reinterpret_cast<F32*>(mBuffer + _glHandle->mOffset)[8] = mat[10];
  257. break;
  258. case GFXSCT_Float4x4:
  259. {
  260. if(_glHandle->mInstancingConstant)
  261. {
  262. MatrixF transposed;
  263. mat.transposeTo(transposed);
  264. dMemcpy( mInstPtr + _glHandle->mOffset, (const F32*)transposed, sizeof(MatrixF) );
  265. return;
  266. }
  267. dMemcpy(mBuffer + _glHandle->mOffset, (const F32*)mat, sizeof(MatrixF));
  268. break;
  269. }
  270. default:
  271. AssertFatal(false, "GFXGLShaderConstBuffer::set - Invalid matrix type");
  272. break;
  273. }
  274. }
  275. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF* mat, const U32 arraySize, const GFXShaderConstType matrixType)
  276. {
  277. AssertFatal(handle, "GFXGLShaderConstBuffer::set - Handle is NULL!" );
  278. AssertFatal(handle->isValid(), "GFXGLShaderConstBuffer::set - Handle is not valid!" );
  279. GFXGLShaderConstHandle* _glHandle = static_cast<GFXGLShaderConstHandle*>(handle);
  280. AssertFatal(mShader == _glHandle->mShader, "GFXGLShaderConstBuffer::set - Should only set handles which are owned by our shader");
  281. AssertFatal(!_glHandle->mInstancingConstant, "GFXGLShaderConstBuffer::set - Instancing not supported for matrix arrays");
  282. switch (matrixType) {
  283. case GFXSCT_Float4x4:
  284. dMemcpy(mBuffer + _glHandle->mOffset, (F32*)mat, _glHandle->getSize());
  285. break;
  286. default:
  287. AssertFatal(false, "GFXGLShaderConstBuffer::set - setting array of non 4x4 matrices!");
  288. break;
  289. }
  290. }
  291. void GFXGLShaderConstBuffer::activate()
  292. {
  293. mShader->setConstantsFromBuffer(this);
  294. mWasLost = false;
  295. }
  296. const String GFXGLShaderConstBuffer::describeSelf() const
  297. {
  298. return String();
  299. }
  300. void GFXGLShaderConstBuffer::onShaderReload( GFXGLShader *shader )
  301. {
  302. AssertFatal( shader == mShader, "GFXGLShaderConstBuffer::onShaderReload, mismatched shaders!" );
  303. delete[] mBuffer;
  304. mBuffer = new U8[mShader->mConstBufferSize];
  305. dMemset(mBuffer, 0, mShader->mConstBufferSize);
  306. mWasLost = true;
  307. }
  308. GFXGLShader::GFXGLShader() :
  309. mVertexShader(0),
  310. mPixelShader(0),
  311. mProgram(0),
  312. mConstBufferSize(0),
  313. mConstBuffer(NULL)
  314. {
  315. }
  316. GFXGLShader::~GFXGLShader()
  317. {
  318. clearShaders();
  319. for(HandleMap::Iterator i = mHandles.begin(); i != mHandles.end(); i++)
  320. delete i->value;
  321. delete[] mConstBuffer;
  322. }
  323. void GFXGLShader::clearShaders()
  324. {
  325. glDeleteProgram(mProgram);
  326. glDeleteShader(mVertexShader);
  327. glDeleteShader(mPixelShader);
  328. mProgram = 0;
  329. mVertexShader = 0;
  330. mPixelShader = 0;
  331. }
  332. bool GFXGLShader::_init()
  333. {
  334. // Don't initialize empty shaders.
  335. if ( mVertexFile.isEmpty() && mPixelFile.isEmpty() )
  336. return false;
  337. clearShaders();
  338. mProgram = glCreateProgram();
  339. // Set the macros and add the global ones.
  340. Vector<GFXShaderMacro> macros;
  341. macros.merge( mMacros );
  342. macros.merge( smGlobalMacros );
  343. // Add the shader version to the macros.
  344. const U32 mjVer = (U32)mFloor( mPixVersion );
  345. const U32 mnVer = (U32)( ( mPixVersion - F32( mjVer ) ) * 10.01f );
  346. macros.increment();
  347. macros.last().name = "TORQUE_SM";
  348. macros.last().value = String::ToString( mjVer * 10 + mnVer );
  349. macros.increment();
  350. macros.last().name = "TORQUE_VERTEX_SHADER";
  351. macros.last().value = "";
  352. // Default to true so we're "successful" if a vertex/pixel shader wasn't specified.
  353. bool compiledVertexShader = true;
  354. bool compiledPixelShader = true;
  355. // Compile the vertex and pixel shaders if specified.
  356. if(!mVertexFile.isEmpty())
  357. compiledVertexShader = initShader(mVertexFile, true, macros);
  358. macros.last().name = "TORQUE_PIXEL_SHADER";
  359. if(!mPixelFile.isEmpty())
  360. compiledPixelShader = initShader(mPixelFile, false, macros);
  361. // If either shader was present and failed to compile, bail.
  362. if(!compiledVertexShader || !compiledPixelShader)
  363. return false;
  364. //bind vertex attributes
  365. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_Position, "vPosition");
  366. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_Normal, "vNormal");
  367. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_Color, "vColor");
  368. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_Tangent, "vTangent");
  369. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TangentW, "vTangentW");
  370. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_Binormal, "vBinormal");
  371. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord0, "vTexCoord0");
  372. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord1, "vTexCoord1");
  373. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord2, "vTexCoord2");
  374. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord3, "vTexCoord3");
  375. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord4, "vTexCoord4");
  376. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord5, "vTexCoord5");
  377. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord6, "vTexCoord6");
  378. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord7, "vTexCoord7");
  379. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord8, "vTexCoord8");
  380. glBindAttribLocation(mProgram, Torque::GL_VertexAttrib_TexCoord9, "vTexCoord9");
  381. //bind fragment out color
  382. glBindFragDataLocation(mProgram, 0, "OUT_col");
  383. glBindFragDataLocation(mProgram, 1, "OUT_col1");
  384. glBindFragDataLocation(mProgram, 2, "OUT_col2");
  385. glBindFragDataLocation(mProgram, 3, "OUT_col3");
  386. // Link it!
  387. glLinkProgram( mProgram );
  388. GLint linkStatus;
  389. glGetProgramiv( mProgram, GL_LINK_STATUS, &linkStatus );
  390. // Dump the info log to the console
  391. U32 logLength = 0;
  392. glGetProgramiv(mProgram, GL_INFO_LOG_LENGTH, (GLint*)&logLength);
  393. if ( logLength )
  394. {
  395. FrameAllocatorMarker fam;
  396. char* log = (char*)fam.alloc( logLength );
  397. glGetProgramInfoLog( mProgram, logLength, NULL, log );
  398. if ( linkStatus == GL_FALSE )
  399. {
  400. if ( smLogErrors )
  401. {
  402. Con::errorf( "GFXGLShader::init - Error linking shader!" );
  403. Con::errorf( "Program %s / %s: %s",
  404. mVertexFile.getFullPath().c_str(), mPixelFile.getFullPath().c_str(), log);
  405. }
  406. }
  407. else if ( smLogWarnings )
  408. {
  409. Con::warnf( "Program %s / %s: %s",
  410. mVertexFile.getFullPath().c_str(), mPixelFile.getFullPath().c_str(), log);
  411. }
  412. }
  413. // If we failed to link, bail.
  414. if ( linkStatus == GL_FALSE )
  415. return false;
  416. initConstantDescs();
  417. initHandles();
  418. // Notify Buffers we might have changed in size.
  419. // If this was our first init then we won't have any activeBuffers
  420. // to worry about unnecessarily calling.
  421. Vector<GFXShaderConstBuffer*>::iterator biter = mActiveBuffers.begin();
  422. for ( ; biter != mActiveBuffers.end(); biter++ )
  423. ((GFXGLShaderConstBuffer*)(*biter))->onShaderReload( this );
  424. return true;
  425. }
  426. void GFXGLShader::initConstantDescs()
  427. {
  428. mConstants.clear();
  429. GLint numUniforms;
  430. glGetProgramiv(mProgram, GL_ACTIVE_UNIFORMS, &numUniforms);
  431. GLint maxNameLength;
  432. glGetProgramiv(mProgram, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxNameLength);
  433. if(!maxNameLength)
  434. return;
  435. FrameTemp<GLchar> uniformName(maxNameLength);
  436. for(U32 i = 0; i < numUniforms; i++)
  437. {
  438. GLint size;
  439. GLenum type;
  440. glGetActiveUniform(mProgram, i, maxNameLength, NULL, &size, &type, uniformName);
  441. GFXShaderConstDesc desc;
  442. desc.name = String((char*)uniformName);
  443. // Remove array brackets from the name
  444. desc.name = desc.name.substr(0, desc.name.find('['));
  445. // Insert $ to match D3D behavior of having a $ prepended to parameters to main.
  446. desc.name.insert(0, '$');
  447. desc.arraySize = size;
  448. switch(type)
  449. {
  450. case GL_FLOAT:
  451. desc.constType = GFXSCT_Float;
  452. break;
  453. case GL_FLOAT_VEC2:
  454. desc.constType = GFXSCT_Float2;
  455. break;
  456. case GL_FLOAT_VEC3:
  457. desc.constType = GFXSCT_Float3;
  458. break;
  459. case GL_FLOAT_VEC4:
  460. desc.constType = GFXSCT_Float4;
  461. break;
  462. case GL_INT:
  463. desc.constType = GFXSCT_Int;
  464. break;
  465. case GL_INT_VEC2:
  466. desc.constType = GFXSCT_Int2;
  467. break;
  468. case GL_INT_VEC3:
  469. desc.constType = GFXSCT_Int3;
  470. break;
  471. case GL_INT_VEC4:
  472. desc.constType = GFXSCT_Int4;
  473. break;
  474. case GL_FLOAT_MAT2:
  475. desc.constType = GFXSCT_Float2x2;
  476. break;
  477. case GL_FLOAT_MAT3:
  478. desc.constType = GFXSCT_Float3x3;
  479. break;
  480. case GL_FLOAT_MAT4:
  481. desc.constType = GFXSCT_Float4x4;
  482. break;
  483. case GL_SAMPLER_1D:
  484. case GL_SAMPLER_2D:
  485. case GL_SAMPLER_3D:
  486. case GL_SAMPLER_1D_SHADOW:
  487. case GL_SAMPLER_2D_SHADOW:
  488. desc.constType = GFXSCT_Sampler;
  489. break;
  490. case GL_SAMPLER_CUBE:
  491. desc.constType = GFXSCT_SamplerCube;
  492. break;
  493. default:
  494. AssertFatal(false, "GFXGLShader::initConstantDescs - unrecognized uniform type");
  495. // If we don't recognize the constant don't add its description.
  496. continue;
  497. }
  498. mConstants.push_back(desc);
  499. }
  500. }
  501. void GFXGLShader::initHandles()
  502. {
  503. // Mark all existing handles as invalid.
  504. // Those that are found when parsing the descriptions will then be marked valid again.
  505. for ( HandleMap::Iterator iter = mHandles.begin(); iter != mHandles.end(); ++iter )
  506. (iter->value)->setValid( false );
  507. mValidHandles.clear();
  508. // Loop through all ConstantDescriptions,
  509. // if they aren't in the HandleMap add them, if they are reinitialize them.
  510. for ( U32 i = 0; i < mConstants.size(); i++ )
  511. {
  512. GFXShaderConstDesc &desc = mConstants[i];
  513. // Index element 1 of the name to skip the '$' we inserted earier.
  514. GLint loc = glGetUniformLocation(mProgram, &desc.name.c_str()[1]);
  515. AssertFatal(loc != -1, "");
  516. HandleMap::Iterator handle = mHandles.find(desc.name);
  517. S32 sampler = -1;
  518. if(desc.constType == GFXSCT_Sampler || desc.constType == GFXSCT_SamplerCube)
  519. {
  520. S32 idx = mSamplerNamesOrdered.find_next(desc.name);
  521. AssertFatal(idx != -1, "");
  522. sampler = idx; //assignedSamplerNum++;
  523. }
  524. if ( handle != mHandles.end() )
  525. {
  526. handle->value->reinit( desc, loc, sampler );
  527. }
  528. else
  529. {
  530. mHandles[desc.name] = new GFXGLShaderConstHandle( this, desc, loc, sampler );
  531. }
  532. }
  533. // Loop through handles once more to set their offset and calculate our
  534. // constBuffer size.
  535. if ( mConstBuffer )
  536. delete[] mConstBuffer;
  537. mConstBufferSize = 0;
  538. for ( HandleMap::Iterator iter = mHandles.begin(); iter != mHandles.end(); ++iter )
  539. {
  540. GFXGLShaderConstHandle* handle = iter->value;
  541. if ( handle->isValid() )
  542. {
  543. mValidHandles.push_back(handle);
  544. handle->mOffset = mConstBufferSize;
  545. mConstBufferSize += handle->getSize();
  546. }
  547. }
  548. mConstBuffer = new U8[mConstBufferSize];
  549. dMemset(mConstBuffer, 0, mConstBufferSize);
  550. // Set our program so uniforms are assigned properly.
  551. glUseProgram(mProgram);
  552. // Iterate through uniforms to set sampler numbers.
  553. for (HandleMap::Iterator iter = mHandles.begin(); iter != mHandles.end(); ++iter)
  554. {
  555. GFXGLShaderConstHandle* handle = iter->value;
  556. if(handle->isValid() && (handle->getType() == GFXSCT_Sampler || handle->getType() == GFXSCT_SamplerCube))
  557. {
  558. // Set sampler number on our program.
  559. glUniform1i(handle->mLocation, handle->mSamplerNum);
  560. // Set sampler in constant buffer so it does not get unset later.
  561. dMemcpy(mConstBuffer + handle->mOffset, &handle->mSamplerNum, handle->getSize());
  562. }
  563. }
  564. glUseProgram(0);
  565. //instancing
  566. U32 offset = 0;
  567. for ( U32 i=0; i < mInstancingFormat.getElementCount(); i++ )
  568. {
  569. const GFXVertexElement &element = mInstancingFormat.getElement( i );
  570. String constName = String::ToString( "$%s", element.getSemantic().c_str() );
  571. HandleMap::Iterator handle = mHandles.find(constName);
  572. if ( handle != mHandles.end() )
  573. {
  574. AssertFatal(0, "");
  575. }
  576. else
  577. {
  578. GFXShaderConstDesc desc;
  579. desc.name = constName;
  580. desc.arraySize = 1;
  581. switch(element.getType())
  582. {
  583. case GFXDeclType_Float4:
  584. desc.constType = GFXSCT_Float4;
  585. break;
  586. default:
  587. desc.constType = GFXSCT_Float;
  588. break;
  589. }
  590. GFXGLShaderConstHandle *h = new GFXGLShaderConstHandle( this, desc, -1, -1 );
  591. h->mInstancingConstant = true;
  592. h->mOffset = offset;
  593. mHandles[constName] = h;
  594. offset += element.getSizeInBytes();
  595. ++i;
  596. // If this is a matrix we will have 2 or 3 more of these
  597. // semantics with the same name after it.
  598. for ( ; i < mInstancingFormat.getElementCount(); i++ )
  599. {
  600. const GFXVertexElement &nextElement = mInstancingFormat.getElement( i );
  601. if ( nextElement.getSemantic() != element.getSemantic() )
  602. {
  603. i--;
  604. break;
  605. }
  606. ++desc.arraySize;
  607. if(desc.arraySize == 4 && desc.constType == GFXSCT_Float4)
  608. {
  609. desc.arraySize = 1;
  610. desc.constType = GFXSCT_Float4x4;
  611. }
  612. offset += nextElement.getSizeInBytes();
  613. }
  614. }
  615. }
  616. }
  617. GFXShaderConstHandle* GFXGLShader::getShaderConstHandle(const String& name)
  618. {
  619. HandleMap::Iterator i = mHandles.find(name);
  620. if(i != mHandles.end())
  621. return i->value;
  622. else
  623. {
  624. GFXGLShaderConstHandle* handle = new GFXGLShaderConstHandle( this );
  625. mHandles[ name ] = handle;
  626. return handle;
  627. }
  628. }
  629. GFXShaderConstHandle* GFXGLShader::findShaderConstHandle(const String& name)
  630. {
  631. HandleMap::Iterator i = mHandles.find(name);
  632. if(i != mHandles.end())
  633. return i->value;
  634. else
  635. {
  636. return NULL;
  637. }
  638. }
  639. void GFXGLShader::setConstantsFromBuffer(GFXGLShaderConstBuffer* buffer)
  640. {
  641. for(Vector<GFXGLShaderConstHandle*>::iterator i = mValidHandles.begin(); i != mValidHandles.end(); ++i)
  642. {
  643. GFXGLShaderConstHandle* handle = *i;
  644. AssertFatal(handle, "GFXGLShader::setConstantsFromBuffer - Null handle");
  645. if(handle->mInstancingConstant)
  646. continue;
  647. // Don't set if the value has not be changed.
  648. if(dMemcmp(mConstBuffer + handle->mOffset, buffer->mBuffer + handle->mOffset, handle->getSize()) == 0)
  649. continue;
  650. // Copy new value into our const buffer and set in GL.
  651. dMemcpy(mConstBuffer + handle->mOffset, buffer->mBuffer + handle->mOffset, handle->getSize());
  652. switch(handle->mDesc.constType)
  653. {
  654. case GFXSCT_Float:
  655. glUniform1fv(handle->mLocation, handle->mDesc.arraySize, (GLfloat*)(mConstBuffer + handle->mOffset));
  656. break;
  657. case GFXSCT_Float2:
  658. glUniform2fv(handle->mLocation, handle->mDesc.arraySize, (GLfloat*)(mConstBuffer + handle->mOffset));
  659. break;
  660. case GFXSCT_Float3:
  661. glUniform3fv(handle->mLocation, handle->mDesc.arraySize, (GLfloat*)(mConstBuffer + handle->mOffset));
  662. break;
  663. case GFXSCT_Float4:
  664. glUniform4fv(handle->mLocation, handle->mDesc.arraySize, (GLfloat*)(mConstBuffer + handle->mOffset));
  665. break;
  666. case GFXSCT_Int:
  667. case GFXSCT_Sampler:
  668. case GFXSCT_SamplerCube:
  669. glUniform1iv(handle->mLocation, handle->mDesc.arraySize, (GLint*)(mConstBuffer + handle->mOffset));
  670. break;
  671. case GFXSCT_Int2:
  672. glUniform2iv(handle->mLocation, handle->mDesc.arraySize, (GLint*)(mConstBuffer + handle->mOffset));
  673. break;
  674. case GFXSCT_Int3:
  675. glUniform3iv(handle->mLocation, handle->mDesc.arraySize, (GLint*)(mConstBuffer + handle->mOffset));
  676. break;
  677. case GFXSCT_Int4:
  678. glUniform4iv(handle->mLocation, handle->mDesc.arraySize, (GLint*)(mConstBuffer + handle->mOffset));
  679. break;
  680. case GFXSCT_Float2x2:
  681. glUniformMatrix2fv(handle->mLocation, handle->mDesc.arraySize, true, (GLfloat*)(mConstBuffer + handle->mOffset));
  682. break;
  683. case GFXSCT_Float3x3:
  684. glUniformMatrix3fv(handle->mLocation, handle->mDesc.arraySize, true, (GLfloat*)(mConstBuffer + handle->mOffset));
  685. break;
  686. case GFXSCT_Float4x4:
  687. glUniformMatrix4fv(handle->mLocation, handle->mDesc.arraySize, true, (GLfloat*)(mConstBuffer + handle->mOffset));
  688. break;
  689. default:
  690. AssertFatal(0,"");
  691. break;
  692. }
  693. }
  694. }
  695. GFXShaderConstBufferRef GFXGLShader::allocConstBuffer()
  696. {
  697. GFXGLShaderConstBuffer* buffer = new GFXGLShaderConstBuffer(this, mConstBufferSize, mConstBuffer);
  698. buffer->registerResourceWithDevice(getOwningDevice());
  699. mActiveBuffers.push_back( buffer );
  700. return buffer;
  701. }
  702. void GFXGLShader::useProgram()
  703. {
  704. glUseProgram(mProgram);
  705. }
  706. void GFXGLShader::zombify()
  707. {
  708. clearShaders();
  709. dMemset(mConstBuffer, 0, mConstBufferSize);
  710. }
  711. char* GFXGLShader::_handleIncludes( const Torque::Path& path, FileStream *s )
  712. {
  713. // TODO: The #line pragma on GLSL takes something called a
  714. // "source-string-number" which it then never explains.
  715. //
  716. // Until i resolve this mystery i disabled this.
  717. //
  718. //String linePragma = String::ToString( "#line 1 \r\n");
  719. //U32 linePragmaLen = linePragma.length();
  720. U32 shaderLen = s->getStreamSize();
  721. char* buffer = (char*)dMalloc(shaderLen + 1);
  722. //dStrncpy( buffer, linePragma.c_str(), linePragmaLen );
  723. s->read(shaderLen, buffer);
  724. buffer[shaderLen] = 0;
  725. char* p = dStrstr(buffer, "#include");
  726. while(p)
  727. {
  728. char* q = p;
  729. p += 8;
  730. if(dIsspace(*p))
  731. {
  732. U32 n = 0;
  733. while(dIsspace(*p)) ++p;
  734. AssertFatal(*p == '"', "Bad #include directive");
  735. ++p;
  736. static char includeFile[256];
  737. while(*p != '"')
  738. {
  739. AssertFatal(*p != 0, "Bad #include directive");
  740. includeFile[n++] = *p++;
  741. AssertFatal(n < sizeof(includeFile), "#include directive too long");
  742. }
  743. ++p;
  744. includeFile[n] = 0;
  745. // First try it as a local file.
  746. Torque::Path includePath = Torque::Path::Join(path.getPath(), '/', includeFile);
  747. includePath = Torque::Path::CompressPath(includePath);
  748. FileStream includeStream;
  749. if ( !includeStream.open( includePath, Torque::FS::File::Read ) )
  750. {
  751. // Try again assuming the path is absolute
  752. // and/or relative.
  753. includePath = String( includeFile );
  754. includePath = Torque::Path::CompressPath(includePath);
  755. if ( !includeStream.open( includePath, Torque::FS::File::Read ) )
  756. {
  757. AssertISV(false, avar("failed to open include '%s'.", includePath.getFullPath().c_str()));
  758. if ( smLogErrors )
  759. Con::errorf( "GFXGLShader::_handleIncludes - Failed to open include '%s'.",
  760. includePath.getFullPath().c_str() );
  761. // Fail... don't return the buffer.
  762. dFree(buffer);
  763. return NULL;
  764. }
  765. }
  766. char* includedText = _handleIncludes(includePath, &includeStream);
  767. // If a sub-include fails... cleanup and return.
  768. if ( !includedText )
  769. {
  770. dFree(buffer);
  771. return NULL;
  772. }
  773. // TODO: Disabled till this is fixed correctly.
  774. //
  775. // Count the number of lines in the file
  776. // before the include.
  777. /*
  778. U32 includeLine = 0;
  779. {
  780. char* nl = dStrstr( buffer, "\n" );
  781. while ( nl )
  782. {
  783. includeLine++;
  784. nl = dStrstr( nl, "\n" );
  785. if(nl) ++nl;
  786. }
  787. }
  788. */
  789. String manip(buffer);
  790. manip.erase(q-buffer, p-q);
  791. String sItx(includedText);
  792. // TODO: Disabled till this is fixed correctly.
  793. //
  794. // Add a new line pragma to restore the proper
  795. // file and line number after the include.
  796. //sItx += String::ToString( "\r\n#line %d \r\n", includeLine );
  797. dFree(includedText);
  798. manip.insert(q-buffer, sItx);
  799. char* manipBuf = dStrdup(manip.c_str());
  800. p = manipBuf + (q - buffer);
  801. dFree(buffer);
  802. buffer = manipBuf;
  803. }
  804. p = dStrstr(p, "#include");
  805. }
  806. return buffer;
  807. }
  808. bool GFXGLShader::_loadShaderFromStream( GLuint shader,
  809. const Torque::Path &path,
  810. FileStream *s,
  811. const Vector<GFXShaderMacro> &macros )
  812. {
  813. Vector<char*> buffers;
  814. Vector<U32> lengths;
  815. // The GLSL version declaration must go first!
  816. const char *versionDecl = "#version 150\r\n";
  817. buffers.push_back( dStrdup( versionDecl ) );
  818. lengths.push_back( dStrlen( versionDecl ) );
  819. if(gglHasExtension(ARB_gpu_shader5))
  820. {
  821. const char *extension = "#extension GL_ARB_gpu_shader5 : enable\r\n";
  822. buffers.push_back( dStrdup( extension ) );
  823. lengths.push_back( dStrlen( extension ) );
  824. }
  825. const char *newLine = "\r\n";
  826. buffers.push_back( dStrdup( newLine ) );
  827. lengths.push_back( dStrlen( newLine ) );
  828. // Now add all the macros.
  829. for( U32 i = 0; i < macros.size(); i++ )
  830. {
  831. if(macros[i].name.isEmpty()) // TODO OPENGL
  832. continue;
  833. String define = String::ToString( "#define %s %s\n", macros[i].name.c_str(), macros[i].value.c_str() );
  834. buffers.push_back( dStrdup( define.c_str() ) );
  835. lengths.push_back( define.length() );
  836. }
  837. // Now finally add the shader source.
  838. U32 shaderLen = s->getStreamSize();
  839. char *buffer = _handleIncludes(path, s);
  840. if ( !buffer )
  841. return false;
  842. buffers.push_back(buffer);
  843. lengths.push_back(shaderLen);
  844. glShaderSource(shader, buffers.size(), (const GLchar**)const_cast<const char**>(buffers.address()), NULL);
  845. #if defined(TORQUE_DEBUG) && defined(TORQUE_DEBUG_GFX)
  846. FileStream stream;
  847. if ( !stream.open( path.getFullPath()+"_DEBUG", Torque::FS::File::Write ) )
  848. {
  849. AssertISV(false, avar("GFXGLShader::initShader - failed to write debug shader '%s'.", path.getFullPath().c_str()));
  850. }
  851. for(int i = 0; i < buffers.size(); ++i)
  852. stream.writeText(buffers[i]);
  853. #endif
  854. // Cleanup the shader source buffer.
  855. for ( U32 i=0; i < buffers.size(); i++ )
  856. dFree( buffers[i] );
  857. glCompileShader(shader);
  858. return true;
  859. }
  860. bool GFXGLShader::initShader( const Torque::Path &file,
  861. bool isVertex,
  862. const Vector<GFXShaderMacro> &macros )
  863. {
  864. GLuint activeShader = glCreateShader(isVertex ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER);
  865. if(isVertex)
  866. mVertexShader = activeShader;
  867. else
  868. mPixelShader = activeShader;
  869. glAttachShader(mProgram, activeShader);
  870. // Ok it's not in the shader gen manager, so ask Torque for it
  871. FileStream stream;
  872. if ( !stream.open( file, Torque::FS::File::Read ) )
  873. {
  874. AssertISV(false, avar("GFXGLShader::initShader - failed to open shader '%s'.", file.getFullPath().c_str()));
  875. if ( smLogErrors )
  876. Con::errorf( "GFXGLShader::initShader - Failed to open shader file '%s'.",
  877. file.getFullPath().c_str() );
  878. return false;
  879. }
  880. if ( !_loadShaderFromStream( activeShader, file, &stream, macros ) )
  881. return false;
  882. GLint compile;
  883. glGetShaderiv(activeShader, GL_COMPILE_STATUS, &compile);
  884. // Dump the info log to the console
  885. U32 logLength = 0;
  886. glGetShaderiv(activeShader, GL_INFO_LOG_LENGTH, (GLint*)&logLength);
  887. GLint compileStatus = GL_TRUE;
  888. if ( logLength )
  889. {
  890. FrameAllocatorMarker fam;
  891. char* log = (char*)fam.alloc(logLength);
  892. glGetShaderInfoLog(activeShader, logLength, NULL, log);
  893. // Always print errors
  894. glGetShaderiv( activeShader, GL_COMPILE_STATUS, &compileStatus );
  895. if ( compileStatus == GL_FALSE )
  896. {
  897. if ( smLogErrors )
  898. {
  899. Con::errorf( "GFXGLShader::initShader - Error compiling shader!" );
  900. Con::errorf( "Program %s: %s", file.getFullPath().c_str(), log );
  901. }
  902. }
  903. else if ( smLogWarnings )
  904. Con::warnf( "Program %s: %s", file.getFullPath().c_str(), log );
  905. }
  906. return compileStatus != GL_FALSE;
  907. }
  908. /// Returns our list of shader constants, the material can get this and just set the constants it knows about
  909. const Vector<GFXShaderConstDesc>& GFXGLShader::getShaderConstDesc() const
  910. {
  911. return mConstants;
  912. }
  913. /// Returns the alignment value for constType
  914. U32 GFXGLShader::getAlignmentValue(const GFXShaderConstType constType) const
  915. {
  916. // Alignment is the same thing as size for us.
  917. return shaderConstTypeSize(constType);
  918. }
  919. const String GFXGLShader::describeSelf() const
  920. {
  921. String ret;
  922. ret = String::ToString(" Program: %i", mProgram);
  923. ret += String::ToString(" Vertex Path: %s", mVertexFile.getFullPath().c_str());
  924. ret += String::ToString(" Pixel Path: %s", mPixelFile.getFullPath().c_str());
  925. return ret;
  926. }