CmGLSLProgram.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 "CmGpuProgram.h"
  25. #include "CmRenderSystem.h"
  26. #include "CmRenderSystemCapabilities.h"
  27. #include "CmGpuProgramManager.h"
  28. #include "CmHighLevelGpuProgramManager.h"
  29. #include "CmException.h"
  30. #include "CmGLSLProgram.h"
  31. #include "CmGLSLGpuProgram.h"
  32. #include "CmGLSLExtSupport.h"
  33. #include "CmGLSLLinkProgramManager.h"
  34. #include "CmGLSLPreprocessor.h"
  35. namespace CamelotEngine {
  36. //---------------------------------------------------------------------------
  37. GLSLProgram::~GLSLProgram()
  38. {
  39. unload();
  40. }
  41. //-----------------------------------------------------------------------
  42. void GLSLProgram::loadFromSource(void)
  43. {
  44. // only create a shader object if glsl is supported
  45. if (isSupported())
  46. {
  47. checkForGLSLError( "GLSLProgram::loadFromSource", "GL Errors before creating shader object", 0 );
  48. // create shader object
  49. GLenum shaderType = 0x0000;
  50. switch (mType)
  51. {
  52. case GPT_VERTEX_PROGRAM:
  53. shaderType = GL_VERTEX_SHADER_ARB;
  54. break;
  55. case GPT_FRAGMENT_PROGRAM:
  56. shaderType = GL_FRAGMENT_SHADER_ARB;
  57. break;
  58. case GPT_GEOMETRY_PROGRAM:
  59. shaderType = GL_GEOMETRY_SHADER_EXT;
  60. break;
  61. }
  62. mGLHandle = glCreateShaderObjectARB(shaderType);
  63. checkForGLSLError( "GLSLProgram::loadFromSource", "Error creating GLSL shader object", 0 );
  64. }
  65. // Preprocess the GLSL shader in order to get a clean source
  66. CPreprocessor cpp;
  67. // Pass all user-defined macros to preprocessor
  68. if (!mPreprocessorDefines.empty ())
  69. {
  70. String::size_type pos = 0;
  71. while (pos != String::npos)
  72. {
  73. // Find delims
  74. String::size_type endPos = mPreprocessorDefines.find_first_of(";,=", pos);
  75. if (endPos != String::npos)
  76. {
  77. String::size_type macro_name_start = pos;
  78. size_t macro_name_len = endPos - pos;
  79. pos = endPos;
  80. // Check definition part
  81. if (mPreprocessorDefines[pos] == '=')
  82. {
  83. // set up a definition, skip delim
  84. ++pos;
  85. String::size_type macro_val_start = pos;
  86. size_t macro_val_len;
  87. endPos = mPreprocessorDefines.find_first_of(";,", pos);
  88. if (endPos == String::npos)
  89. {
  90. macro_val_len = mPreprocessorDefines.size () - pos;
  91. pos = endPos;
  92. }
  93. else
  94. {
  95. macro_val_len = endPos - pos;
  96. pos = endPos+1;
  97. }
  98. cpp.Define (
  99. mPreprocessorDefines.c_str () + macro_name_start, macro_name_len,
  100. mPreprocessorDefines.c_str () + macro_val_start, macro_val_len);
  101. }
  102. else
  103. {
  104. // No definition part, define as "1"
  105. ++pos;
  106. cpp.Define (
  107. mPreprocessorDefines.c_str () + macro_name_start, macro_name_len, 1);
  108. }
  109. }
  110. else
  111. pos = endPos;
  112. }
  113. }
  114. size_t out_size = 0;
  115. const char *src = mSource.c_str ();
  116. size_t src_len = mSource.size ();
  117. char *out = cpp.Parse (src, src_len, out_size);
  118. if (!out || !out_size)
  119. // Failed to preprocess, break out
  120. CM_EXCEPT(RenderingAPIException,
  121. "Failed to preprocess shader ");
  122. mSource = String (out, out_size);
  123. if (out < src || out > src + src_len)
  124. free (out);
  125. // Add preprocessor extras and main source
  126. if (!mSource.empty())
  127. {
  128. const char *source = mSource.c_str();
  129. glShaderSourceARB(mGLHandle, 1, &source, NULL);
  130. // check for load errors
  131. checkForGLSLError( "GLSLProgram::loadFromSource", "Cannot load GLSL high-level shader source : ", 0 );
  132. }
  133. compile();
  134. }
  135. //---------------------------------------------------------------------------
  136. bool GLSLProgram::compile(const bool checkErrors)
  137. {
  138. if (checkErrors)
  139. {
  140. logObjectInfo("GLSL compiling: ", mGLHandle);
  141. }
  142. glCompileShaderARB(mGLHandle);
  143. // check for compile errors
  144. glGetObjectParameterivARB(mGLHandle, GL_OBJECT_COMPILE_STATUS_ARB, &mCompiled);
  145. // force exception if not compiled
  146. if (checkErrors)
  147. {
  148. checkForGLSLError( "GLSLProgram::compile", "Cannot compile GLSL high-level shader : ", mGLHandle, !mCompiled, !mCompiled );
  149. if (mCompiled)
  150. {
  151. logObjectInfo("GLSL compiled : ", mGLHandle);
  152. }
  153. }
  154. return (mCompiled == 1);
  155. }
  156. //-----------------------------------------------------------------------
  157. void GLSLProgram::createLowLevelImpl(void)
  158. {
  159. mAssemblerProgram = GpuProgramPtr(new GLSLGpuProgram( this ));
  160. }
  161. //---------------------------------------------------------------------------
  162. void GLSLProgram::unloadImpl()
  163. {
  164. // We didn't create mAssemblerProgram through a manager, so override this
  165. // implementation so that we don't try to remove it from one. Since getCreator()
  166. // is used, it might target a different matching handle!
  167. mAssemblerProgram = nullptr;
  168. unloadHighLevel();
  169. }
  170. //-----------------------------------------------------------------------
  171. void GLSLProgram::unloadHighLevelImpl(void)
  172. {
  173. if (isSupported())
  174. {
  175. glDeleteObjectARB(mGLHandle);
  176. }
  177. }
  178. //-----------------------------------------------------------------------
  179. void GLSLProgram::populateParameterNames(GpuProgramParametersSharedPtr params)
  180. {
  181. getConstantDefinitions();
  182. params->_setNamedConstants(mConstantDefs);
  183. // Don't set logical / physical maps here, as we can't access parameters by logical index in GLHL.
  184. }
  185. //-----------------------------------------------------------------------
  186. void GLSLProgram::buildConstantDefinitions() const
  187. {
  188. // We need an accurate list of all the uniforms in the shader, but we
  189. // can't get at them until we link all the shaders into a program object.
  190. // Therefore instead, parse the source code manually and extract the uniforms
  191. createParameterMappingStructures(true);
  192. GLSLLinkProgramManager::getSingleton().extractConstantDefs(
  193. mSource, *mConstantDefs.get(), "");
  194. // Also parse any attached sources
  195. for (GLSLProgramContainer::const_iterator i = mAttachedGLSLPrograms.begin();
  196. i != mAttachedGLSLPrograms.end(); ++i)
  197. {
  198. GLSLProgram* childShader = *i;
  199. GLSLLinkProgramManager::getSingleton().extractConstantDefs(
  200. childShader->getSource(), *mConstantDefs.get(), "");
  201. }
  202. }
  203. //-----------------------------------------------------------------------
  204. GLSLProgram::GLSLProgram()
  205. : HighLevelGpuProgram(),
  206. mInputOperationType(RenderOperation::OT_TRIANGLE_LIST),
  207. mOutputOperationType(RenderOperation::OT_TRIANGLE_LIST), mMaxOutputVertices(3)
  208. {
  209. // Manually assign language now since we use it immediately
  210. mSyntaxCode = "glsl";
  211. }
  212. //---------------------------------------------------------------------
  213. bool GLSLProgram::getPassSurfaceAndLightStates(void) const
  214. {
  215. // scenemanager should pass on light & material state to the rendersystem
  216. return true;
  217. }
  218. //---------------------------------------------------------------------
  219. bool GLSLProgram::getPassTransformStates(void) const
  220. {
  221. // scenemanager should pass on transform state to the rendersystem
  222. return true;
  223. }
  224. //-----------------------------------------------------------------------
  225. void GLSLProgram::attachChildShader(const String& name)
  226. {
  227. // is the name valid and already loaded?
  228. // check with the high level program manager to see if it was loaded
  229. // TODO PORT - I'm not sure what is this for but I don't support it
  230. //HighLevelGpuProgramPtr hlProgram = HighLevelGpuProgramManager::getSingleton().getByName(name);
  231. //if (!hlProgram.isNull())
  232. //{
  233. // if (hlProgram->getSyntaxCode() == "glsl")
  234. // {
  235. // // make sure attached program source gets loaded and compiled
  236. // // don't need a low level implementation for attached shader objects
  237. // // loadHighLevelImpl will only load the source and compile once
  238. // // so don't worry about calling it several times
  239. // GLSLProgram* childShader = static_cast<GLSLProgram*>(hlProgram.getPointer());
  240. // // load the source and attach the child shader only if supported
  241. // if (isSupported())
  242. // {
  243. // childShader->loadHighLevelImpl();
  244. // // add to the container
  245. // mAttachedGLSLPrograms.push_back( childShader );
  246. // mAttachedShaderNames += name + " ";
  247. // }
  248. // }
  249. //}
  250. }
  251. //-----------------------------------------------------------------------
  252. void GLSLProgram::attachToProgramObject( const GLhandleARB programObject )
  253. {
  254. // attach child objects
  255. GLSLProgramContainerIterator childprogramcurrent = mAttachedGLSLPrograms.begin();
  256. GLSLProgramContainerIterator childprogramend = mAttachedGLSLPrograms.end();
  257. while (childprogramcurrent != childprogramend)
  258. {
  259. GLSLProgram* childShader = *childprogramcurrent;
  260. // bug in ATI GLSL linker : modules without main function must be recompiled each time
  261. // they are linked to a different program object
  262. // don't check for compile errors since there won't be any
  263. // *** minor inconvenience until ATI fixes there driver
  264. childShader->compile(false);
  265. childShader->attachToProgramObject( programObject );
  266. ++childprogramcurrent;
  267. }
  268. glAttachObjectARB( programObject, mGLHandle );
  269. checkForGLSLError( "GLSLProgram::attachToProgramObject",
  270. "Error attaching shader object to GLSL Program Object", programObject );
  271. }
  272. //-----------------------------------------------------------------------
  273. void GLSLProgram::detachFromProgramObject( const GLhandleARB programObject )
  274. {
  275. glDetachObjectARB(programObject, mGLHandle);
  276. checkForGLSLError( "GLSLProgram::detachFromProgramObject",
  277. "Error detaching shader object from GLSL Program Object", programObject );
  278. // attach child objects
  279. GLSLProgramContainerIterator childprogramcurrent = mAttachedGLSLPrograms.begin();
  280. GLSLProgramContainerIterator childprogramend = mAttachedGLSLPrograms.end();
  281. while (childprogramcurrent != childprogramend)
  282. {
  283. GLSLProgram* childShader = *childprogramcurrent;
  284. childShader->detachFromProgramObject( programObject );
  285. ++childprogramcurrent;
  286. }
  287. }
  288. //-----------------------------------------------------------------------
  289. const String& GLSLProgram::getLanguage(void) const
  290. {
  291. static const String language = "glsl";
  292. return language;
  293. }
  294. //-----------------------------------------------------------------------
  295. RenderOperation::OperationType parseOperationType(const String& val)
  296. {
  297. if (val == "point_list")
  298. {
  299. return RenderOperation::OT_POINT_LIST;
  300. }
  301. else if (val == "line_list")
  302. {
  303. return RenderOperation::OT_LINE_LIST;
  304. }
  305. else if (val == "line_strip")
  306. {
  307. return RenderOperation::OT_LINE_STRIP;
  308. }
  309. else if (val == "triangle_strip")
  310. {
  311. return RenderOperation::OT_TRIANGLE_STRIP;
  312. }
  313. else if (val == "triangle_fan")
  314. {
  315. return RenderOperation::OT_TRIANGLE_FAN;
  316. }
  317. else
  318. {
  319. //Triangle list is the default fallback. Keep it this way?
  320. return RenderOperation::OT_TRIANGLE_LIST;
  321. }
  322. }
  323. //-----------------------------------------------------------------------
  324. String operationTypeToString(RenderOperation::OperationType val)
  325. {
  326. switch (val)
  327. {
  328. case RenderOperation::OT_POINT_LIST:
  329. return "point_list";
  330. break;
  331. case RenderOperation::OT_LINE_LIST:
  332. return "line_list";
  333. break;
  334. case RenderOperation::OT_LINE_STRIP:
  335. return "line_strip";
  336. break;
  337. case RenderOperation::OT_TRIANGLE_STRIP:
  338. return "triangle_strip";
  339. break;
  340. case RenderOperation::OT_TRIANGLE_FAN:
  341. return "triangle_fan";
  342. break;
  343. case RenderOperation::OT_TRIANGLE_LIST:
  344. default:
  345. return "triangle_list";
  346. break;
  347. }
  348. }
  349. }