CCMesh.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. /****************************************************************************
  2. Copyright (c) 2014-2017 Chukong Technologies Inc.
  3. http://www.cocos2d-x.org
  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 deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #include "3d/CCMesh.h"
  21. #include "3d/CCMeshSkin.h"
  22. #include "3d/CCSkeleton3D.h"
  23. #include "3d/CCMeshVertexIndexData.h"
  24. #include "2d/CCLight.h"
  25. #include "2d/CCScene.h"
  26. #include "base/CCEventDispatcher.h"
  27. #include "base/CCDirector.h"
  28. #include "base/CCConfiguration.h"
  29. #include "renderer/CCTextureCache.h"
  30. #include "renderer/CCGLProgramState.h"
  31. #include "renderer/CCMaterial.h"
  32. #include "renderer/CCTechnique.h"
  33. #include "renderer/CCPass.h"
  34. #include "renderer/CCRenderer.h"
  35. #include "renderer/CCVertexAttribBinding.h"
  36. #include "math/Mat4.h"
  37. using namespace std;
  38. NS_CC_BEGIN
  39. // Helpers
  40. //sampler uniform names, only diffuse and normal texture are supported for now
  41. std::string s_uniformSamplerName[] =
  42. {
  43. "",//NTextureData::Usage::Unknown,
  44. "",//NTextureData::Usage::None
  45. "",//NTextureData::Usage::Diffuse
  46. "",//NTextureData::Usage::Emissive
  47. "",//NTextureData::Usage::Ambient
  48. "",//NTextureData::Usage::Specular
  49. "",//NTextureData::Usage::Shininess
  50. "u_normalTex",//NTextureData::Usage::Normal
  51. "",//NTextureData::Usage::Bump
  52. "",//NTextureData::Usage::Transparency
  53. "",//NTextureData::Usage::Reflection
  54. };
  55. static const char *s_dirLightUniformColorName = "u_DirLightSourceColor";
  56. static const char *s_dirLightUniformDirName = "u_DirLightSourceDirection";
  57. static const char *s_pointLightUniformColorName = "u_PointLightSourceColor";
  58. static const char *s_pointLightUniformPositionName = "u_PointLightSourcePosition";
  59. static const char *s_pointLightUniformRangeInverseName = "u_PointLightSourceRangeInverse";
  60. static const char *s_spotLightUniformColorName = "u_SpotLightSourceColor";
  61. static const char *s_spotLightUniformPositionName = "u_SpotLightSourcePosition";
  62. static const char *s_spotLightUniformDirName = "u_SpotLightSourceDirection";
  63. static const char *s_spotLightUniformInnerAngleCosName = "u_SpotLightSourceInnerAngleCos";
  64. static const char *s_spotLightUniformOuterAngleCosName = "u_SpotLightSourceOuterAngleCos";
  65. static const char *s_spotLightUniformRangeInverseName = "u_SpotLightSourceRangeInverse";
  66. static const char *s_ambientLightUniformColorName = "u_AmbientLightSourceColor";
  67. // helpers
  68. void Mesh::resetLightUniformValues()
  69. {
  70. const auto& conf = Configuration::getInstance();
  71. int maxDirLight = conf->getMaxSupportDirLightInShader();
  72. int maxPointLight = conf->getMaxSupportPointLightInShader();
  73. int maxSpotLight = conf->getMaxSupportSpotLightInShader();
  74. _dirLightUniformColorValues.assign(maxDirLight, Vec3::ZERO);
  75. _dirLightUniformDirValues.assign(maxDirLight, Vec3::ZERO);
  76. _pointLightUniformColorValues.assign(maxPointLight, Vec3::ZERO);
  77. _pointLightUniformPositionValues.assign(maxPointLight, Vec3::ZERO);
  78. _pointLightUniformRangeInverseValues.assign(maxPointLight, 0.0f);
  79. _spotLightUniformColorValues.assign(maxSpotLight, Vec3::ZERO);
  80. _spotLightUniformPositionValues.assign(maxSpotLight, Vec3::ZERO);
  81. _spotLightUniformDirValues.assign(maxSpotLight, Vec3::ZERO);
  82. _spotLightUniformInnerAngleCosValues.assign(maxSpotLight, 1.0f);
  83. _spotLightUniformOuterAngleCosValues.assign(maxSpotLight, 0.0f);
  84. _spotLightUniformRangeInverseValues.assign(maxSpotLight, 0.0f);
  85. }
  86. //Generate a dummy texture when the texture file is missing
  87. static Texture2D * getDummyTexture()
  88. {
  89. auto texture = Director::getInstance()->getTextureCache()->getTextureForKey("/dummyTexture");
  90. if(!texture)
  91. {
  92. #ifdef NDEBUG
  93. unsigned char data[] ={0,0,0,0};//1*1 transparent picture
  94. #else
  95. unsigned char data[] ={255,0,0,255};//1*1 red picture
  96. #endif
  97. Image * image =new (std::nothrow) Image();
  98. image->initWithRawData(data,sizeof(data),1,1,sizeof(unsigned char));
  99. texture=Director::getInstance()->getTextureCache()->addImage(image,"/dummyTexture");
  100. image->release();
  101. }
  102. return texture;
  103. }
  104. Mesh::Mesh()
  105. : _skin(nullptr)
  106. , _visible(true)
  107. , _isTransparent(false)
  108. , _force2DQueue(false)
  109. , _meshIndexData(nullptr)
  110. , _glProgramState(nullptr)
  111. , _blend(BlendFunc::ALPHA_NON_PREMULTIPLIED)
  112. , _blendDirty(true)
  113. , _material(nullptr)
  114. , _texFile("")
  115. {
  116. }
  117. Mesh::~Mesh()
  118. {
  119. for (auto &tex : _textures){
  120. CC_SAFE_RELEASE(tex.second);
  121. }
  122. CC_SAFE_RELEASE(_skin);
  123. CC_SAFE_RELEASE(_meshIndexData);
  124. CC_SAFE_RELEASE(_material);
  125. CC_SAFE_RELEASE(_glProgramState);
  126. }
  127. GLuint Mesh::getVertexBuffer() const
  128. {
  129. return _meshIndexData->getVertexBuffer()->getVBO();
  130. }
  131. bool Mesh::hasVertexAttrib(int attrib) const
  132. {
  133. return _meshIndexData->getMeshVertexData()->hasVertexAttrib(attrib);
  134. }
  135. ssize_t Mesh::getMeshVertexAttribCount() const
  136. {
  137. return _meshIndexData->getMeshVertexData()->getMeshVertexAttribCount();
  138. }
  139. const MeshVertexAttrib& Mesh::getMeshVertexAttribute(int idx)
  140. {
  141. return _meshIndexData->getMeshVertexData()->getMeshVertexAttrib(idx);
  142. }
  143. int Mesh::getVertexSizeInBytes() const
  144. {
  145. return _meshIndexData->getVertexBuffer()->getSizePerVertex();
  146. }
  147. Mesh* Mesh::create(const std::vector<float>& positions, const std::vector<float>& normals, const std::vector<float>& texs, const IndexArray& indices)
  148. {
  149. int perVertexSizeInFloat = 0;
  150. std::vector<float> vertices;
  151. std::vector<MeshVertexAttrib> attribs;
  152. MeshVertexAttrib att;
  153. att.size = 3;
  154. att.type = GL_FLOAT;
  155. att.attribSizeBytes = att.size * sizeof(float);
  156. if (positions.size())
  157. {
  158. perVertexSizeInFloat += 3;
  159. att.vertexAttrib = GLProgram::VERTEX_ATTRIB_POSITION;
  160. attribs.push_back(att);
  161. }
  162. if (normals.size())
  163. {
  164. perVertexSizeInFloat += 3;
  165. att.vertexAttrib = GLProgram::VERTEX_ATTRIB_NORMAL;
  166. attribs.push_back(att);
  167. }
  168. if (texs.size())
  169. {
  170. perVertexSizeInFloat += 2;
  171. att.vertexAttrib = GLProgram::VERTEX_ATTRIB_TEX_COORD;
  172. att.size = 2;
  173. att.attribSizeBytes = att.size * sizeof(float);
  174. attribs.push_back(att);
  175. }
  176. bool hasNormal = (normals.size() != 0);
  177. bool hasTexCoord = (texs.size() != 0);
  178. //position, normal, texCoordinate into _vertexs
  179. size_t vertexNum = positions.size() / 3;
  180. for(size_t i = 0; i < vertexNum; i++)
  181. {
  182. vertices.push_back(positions[i * 3]);
  183. vertices.push_back(positions[i * 3 + 1]);
  184. vertices.push_back(positions[i * 3 + 2]);
  185. if (hasNormal)
  186. {
  187. vertices.push_back(normals[i * 3]);
  188. vertices.push_back(normals[i * 3 + 1]);
  189. vertices.push_back(normals[i * 3 + 2]);
  190. }
  191. if (hasTexCoord)
  192. {
  193. vertices.push_back(texs[i * 2]);
  194. vertices.push_back(texs[i * 2 + 1]);
  195. }
  196. }
  197. return create(vertices, perVertexSizeInFloat, indices, attribs);
  198. }
  199. Mesh* Mesh::create(const std::vector<float>& vertices, int /*perVertexSizeInFloat*/, const IndexArray& indices, const std::vector<MeshVertexAttrib>& attribs)
  200. {
  201. MeshData meshdata;
  202. meshdata.attribs = attribs;
  203. meshdata.vertex = vertices;
  204. meshdata.subMeshIndices.push_back(indices);
  205. meshdata.subMeshIds.push_back("");
  206. auto meshvertexdata = MeshVertexData::create(meshdata);
  207. auto indexData = meshvertexdata->getMeshIndexDataByIndex(0);
  208. return create("", indexData);
  209. }
  210. Mesh* Mesh::create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin)
  211. {
  212. auto state = new (std::nothrow) Mesh();
  213. state->autorelease();
  214. state->bindMeshCommand();
  215. state->_name = name;
  216. state->setMeshIndexData(indexData);
  217. state->setSkin(skin);
  218. return state;
  219. }
  220. void Mesh::setVisible(bool visible)
  221. {
  222. if (_visible != visible)
  223. {
  224. _visible = visible;
  225. if (_visibleChanged)
  226. _visibleChanged();
  227. }
  228. }
  229. bool Mesh::isVisible() const
  230. {
  231. return _visible;
  232. }
  233. void Mesh::setTexture(const std::string& texPath)
  234. {
  235. _texFile = texPath;
  236. auto tex = Director::getInstance()->getTextureCache()->addImage(texPath);
  237. setTexture(tex, NTextureData::Usage::Diffuse);
  238. }
  239. void Mesh::setTexture(Texture2D* tex)
  240. {
  241. setTexture(tex, NTextureData::Usage::Diffuse);
  242. }
  243. void Mesh::setTexture(Texture2D* tex, NTextureData::Usage usage, bool cacheFileName)
  244. {
  245. // Texture must be saved for future use
  246. // it doesn't matter if the material is already set or not
  247. // This functionality is added for compatibility issues
  248. if (tex == nullptr)
  249. tex = getDummyTexture();
  250. CC_SAFE_RETAIN(tex);
  251. CC_SAFE_RELEASE(_textures[usage]);
  252. _textures[usage] = tex;
  253. if (usage == NTextureData::Usage::Diffuse){
  254. if (_material) {
  255. auto technique = _material->_currentTechnique;
  256. for(auto& pass: technique->_passes)
  257. {
  258. // FIXME: Ideally it should use glProgramState->setUniformTexture()
  259. // and set CC_Texture0 that way. But trying to it, will trigger
  260. // another bug
  261. pass->setTexture(tex);
  262. }
  263. }
  264. bindMeshCommand();
  265. if (cacheFileName)
  266. _texFile = tex->getPath();
  267. }
  268. else if (usage == NTextureData::Usage::Normal) // currently only diffuse and normal are supported
  269. {
  270. if (_material){
  271. auto technique = _material->_currentTechnique;
  272. for(auto& pass: technique->_passes)
  273. {
  274. pass->getGLProgramState()->setUniformTexture(s_uniformSamplerName[(int)usage], tex);
  275. }
  276. }
  277. }
  278. }
  279. void Mesh::setTexture(const std::string& texPath, NTextureData::Usage usage)
  280. {
  281. auto tex = Director::getInstance()->getTextureCache()->addImage(texPath);
  282. setTexture(tex, usage);
  283. }
  284. Texture2D* Mesh::getTexture() const
  285. {
  286. return _textures.at(NTextureData::Usage::Diffuse);
  287. }
  288. Texture2D* Mesh::getTexture(NTextureData::Usage usage)
  289. {
  290. return _textures[usage];
  291. }
  292. void Mesh::setMaterial(Material* material)
  293. {
  294. if (_material != material) {
  295. CC_SAFE_RELEASE(_material);
  296. _material = material;
  297. CC_SAFE_RETAIN(_material);
  298. }
  299. if (_material)
  300. {
  301. for (auto technique: _material->getTechniques())
  302. {
  303. for (auto pass: technique->getPasses())
  304. {
  305. auto vertexAttribBinding = VertexAttribBinding::create(_meshIndexData, pass->getGLProgramState());
  306. pass->setVertexAttribBinding(vertexAttribBinding);
  307. }
  308. }
  309. }
  310. // Was the texture set before the GLProgramState ? Set it
  311. for(auto& tex : _textures)
  312. setTexture(tex.second, tex.first);
  313. if (_blendDirty)
  314. setBlendFunc(_blend);
  315. bindMeshCommand();
  316. }
  317. Material* Mesh::getMaterial() const
  318. {
  319. return _material;
  320. }
  321. void Mesh::draw(Renderer* renderer, float globalZOrder, const Mat4& transform, uint32_t flags, unsigned int lightMask, const Vec4& color, bool forceDepthWrite)
  322. {
  323. if (! isVisible())
  324. return;
  325. bool isTransparent = (_isTransparent || color.w < 1.f);
  326. float globalZ = isTransparent ? 0 : globalZOrder;
  327. if (isTransparent)
  328. flags |= Node::FLAGS_RENDER_AS_3D;
  329. _meshCommand.init(globalZ,
  330. _material,
  331. getVertexBuffer(),
  332. getIndexBuffer(),
  333. getPrimitiveType(),
  334. getIndexFormat(),
  335. getIndexCount(),
  336. transform,
  337. flags);
  338. if (isTransparent && !forceDepthWrite)
  339. _material->getStateBlock()->setDepthWrite(false);
  340. else
  341. _material->getStateBlock()->setDepthWrite(true);
  342. _meshCommand.setSkipBatching(isTransparent);
  343. _meshCommand.setTransparent(isTransparent);
  344. _meshCommand.set3D(!_force2DQueue);
  345. _material->getStateBlock()->setBlend(_force2DQueue || isTransparent);
  346. // set default uniforms for Mesh
  347. // 'u_color' and others
  348. const auto scene = Director::getInstance()->getRunningScene();
  349. auto technique = _material->_currentTechnique;
  350. for(const auto pass : technique->_passes)
  351. {
  352. auto programState = pass->getGLProgramState();
  353. programState->setUniformVec4("u_color", color);
  354. if (_skin)
  355. programState->setUniformVec4v("u_matrixPalette", (GLsizei)_skin->getMatrixPaletteSize(), _skin->getMatrixPalette());
  356. if (scene && scene->getLights().size() > 0)
  357. setLightUniforms(pass, scene, color, lightMask);
  358. }
  359. renderer->addCommand(&_meshCommand);
  360. }
  361. void Mesh::setSkin(MeshSkin* skin)
  362. {
  363. if (_skin != skin)
  364. {
  365. CC_SAFE_RETAIN(skin);
  366. CC_SAFE_RELEASE(_skin);
  367. _skin = skin;
  368. calculateAABB();
  369. }
  370. }
  371. void Mesh::setMeshIndexData(MeshIndexData* subMesh)
  372. {
  373. if (_meshIndexData != subMesh)
  374. {
  375. CC_SAFE_RETAIN(subMesh);
  376. CC_SAFE_RELEASE(_meshIndexData);
  377. _meshIndexData = subMesh;
  378. calculateAABB();
  379. bindMeshCommand();
  380. }
  381. }
  382. void Mesh::setGLProgramState(GLProgramState* glProgramState)
  383. {
  384. // XXX create dummy texture
  385. auto material = Material::createWithGLStateProgram(glProgramState);
  386. if (_material)
  387. material->setStateBlock(_material->getStateBlock());
  388. setMaterial(material);
  389. }
  390. GLProgramState* Mesh::getGLProgramState() const
  391. {
  392. return _material ?
  393. _material->_currentTechnique->_passes.at(0)->getGLProgramState()
  394. : nullptr;
  395. }
  396. void Mesh::calculateAABB()
  397. {
  398. if (_meshIndexData)
  399. {
  400. _aabb = _meshIndexData->getAABB();
  401. if (_skin)
  402. {
  403. //get skin root
  404. Bone3D* root = nullptr;
  405. Mat4 invBindPose;
  406. if (_skin->_skinBones.size())
  407. {
  408. root = _skin->_skinBones.at(0);
  409. while (root) {
  410. auto parent = root->getParentBone();
  411. bool parentInSkinBone = false;
  412. for (const auto& bone : _skin->_skinBones) {
  413. if (bone == parent)
  414. {
  415. parentInSkinBone = true;
  416. break;
  417. }
  418. }
  419. if (!parentInSkinBone)
  420. break;
  421. root = parent;
  422. }
  423. }
  424. if (root)
  425. {
  426. _aabb.transform(root->getWorldMat() * _skin->getInvBindPose(root));
  427. }
  428. }
  429. }
  430. }
  431. void Mesh::bindMeshCommand()
  432. {
  433. if (_material && _meshIndexData)
  434. {
  435. auto pass = _material->_currentTechnique->_passes.at(0);
  436. auto glprogramstate = pass->getGLProgramState();
  437. auto texture = pass->getTexture();
  438. auto textureid = texture ? texture->getName() : 0;
  439. // XXX
  440. // auto blend = pass->getStateBlock()->getBlendFunc();
  441. auto blend = BlendFunc::ALPHA_PREMULTIPLIED;
  442. _meshCommand.genMaterialID(textureid, glprogramstate, _meshIndexData->getVertexBuffer()->getVBO(), _meshIndexData->getIndexBuffer()->getVBO(), blend);
  443. _material->getStateBlock()->setCullFace(true);
  444. _material->getStateBlock()->setDepthTest(true);
  445. }
  446. }
  447. void Mesh::setLightUniforms(Pass* pass, Scene* scene, const Vec4& color, unsigned int lightmask)
  448. {
  449. CCASSERT(pass, "Invalid Pass");
  450. CCASSERT(scene, "Invalid scene");
  451. const auto& conf = Configuration::getInstance();
  452. int maxDirLight = conf->getMaxSupportDirLightInShader();
  453. int maxPointLight = conf->getMaxSupportPointLightInShader();
  454. int maxSpotLight = conf->getMaxSupportSpotLightInShader();
  455. auto &lights = scene->getLights();
  456. auto glProgramState = pass->getGLProgramState();
  457. auto attributes = pass->getVertexAttributeBinding()->getVertexAttribsFlags();
  458. if (attributes & (1 << GLProgram::VERTEX_ATTRIB_NORMAL))
  459. {
  460. resetLightUniformValues();
  461. GLint enabledDirLightNum = 0;
  462. GLint enabledPointLightNum = 0;
  463. GLint enabledSpotLightNum = 0;
  464. Vec3 ambientColor;
  465. for (const auto& light : lights)
  466. {
  467. bool useLight = light->isEnabled() && ((unsigned int)light->getLightFlag() & lightmask);
  468. if (useLight)
  469. {
  470. float intensity = light->getIntensity();
  471. switch (light->getLightType())
  472. {
  473. case LightType::DIRECTIONAL:
  474. {
  475. if(enabledDirLightNum < maxDirLight)
  476. {
  477. auto dirLight = static_cast<DirectionLight *>(light);
  478. Vec3 dir = dirLight->getDirectionInWorld();
  479. dir.normalize();
  480. const Color3B &col = dirLight->getDisplayedColor();
  481. _dirLightUniformColorValues[enabledDirLightNum].set(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity);
  482. _dirLightUniformDirValues[enabledDirLightNum] = dir;
  483. ++enabledDirLightNum;
  484. }
  485. }
  486. break;
  487. case LightType::POINT:
  488. {
  489. if(enabledPointLightNum < maxPointLight)
  490. {
  491. auto pointLight = static_cast<PointLight *>(light);
  492. Mat4 mat= pointLight->getNodeToWorldTransform();
  493. const Color3B &col = pointLight->getDisplayedColor();
  494. _pointLightUniformColorValues[enabledPointLightNum].set(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity);
  495. _pointLightUniformPositionValues[enabledPointLightNum].set(mat.m[12], mat.m[13], mat.m[14]);
  496. _pointLightUniformRangeInverseValues[enabledPointLightNum] = 1.0f / pointLight->getRange();
  497. ++enabledPointLightNum;
  498. }
  499. }
  500. break;
  501. case LightType::SPOT:
  502. {
  503. if(enabledSpotLightNum < maxSpotLight)
  504. {
  505. auto spotLight = static_cast<SpotLight *>(light);
  506. Vec3 dir = spotLight->getDirectionInWorld();
  507. dir.normalize();
  508. Mat4 mat= light->getNodeToWorldTransform();
  509. const Color3B &col = spotLight->getDisplayedColor();
  510. _spotLightUniformColorValues[enabledSpotLightNum].set(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity);
  511. _spotLightUniformPositionValues[enabledSpotLightNum].set(mat.m[12], mat.m[13], mat.m[14]);
  512. _spotLightUniformDirValues[enabledSpotLightNum] = dir;
  513. _spotLightUniformInnerAngleCosValues[enabledSpotLightNum] = spotLight->getCosInnerAngle();
  514. _spotLightUniformOuterAngleCosValues[enabledSpotLightNum] = spotLight->getCosOuterAngle();
  515. _spotLightUniformRangeInverseValues[enabledSpotLightNum] = 1.0f / spotLight->getRange();
  516. ++enabledSpotLightNum;
  517. }
  518. }
  519. break;
  520. case LightType::AMBIENT:
  521. {
  522. auto ambLight = static_cast<AmbientLight *>(light);
  523. const Color3B &col = ambLight->getDisplayedColor();
  524. ambientColor.add(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity);
  525. }
  526. break;
  527. default:
  528. break;
  529. }
  530. }
  531. }
  532. if (0 < maxDirLight)
  533. {
  534. glProgramState->setUniformVec3v(s_dirLightUniformColorName, _dirLightUniformColorValues.size(), &_dirLightUniformColorValues[0]);
  535. glProgramState->setUniformVec3v(s_dirLightUniformDirName, _dirLightUniformDirValues.size(), &_dirLightUniformDirValues[0]);
  536. }
  537. if (0 < maxPointLight)
  538. {
  539. glProgramState->setUniformVec3v(s_pointLightUniformColorName, _pointLightUniformColorValues.size(), &_pointLightUniformColorValues[0]);
  540. glProgramState->setUniformVec3v(s_pointLightUniformPositionName, _pointLightUniformPositionValues.size(), &_pointLightUniformPositionValues[0]);
  541. glProgramState->setUniformFloatv(s_pointLightUniformRangeInverseName, _pointLightUniformRangeInverseValues.size(), &_pointLightUniformRangeInverseValues[0]);
  542. }
  543. if (0 < maxSpotLight)
  544. {
  545. glProgramState->setUniformVec3v(s_spotLightUniformColorName, _spotLightUniformColorValues.size(), &_spotLightUniformColorValues[0]);
  546. glProgramState->setUniformVec3v(s_spotLightUniformPositionName, _spotLightUniformPositionValues.size(), &_spotLightUniformPositionValues[0]);
  547. glProgramState->setUniformVec3v(s_spotLightUniformDirName, _spotLightUniformDirValues.size(), &_spotLightUniformDirValues[0]);
  548. glProgramState->setUniformFloatv(s_spotLightUniformInnerAngleCosName, _spotLightUniformInnerAngleCosValues.size(), &_spotLightUniformInnerAngleCosValues[0]);
  549. glProgramState->setUniformFloatv(s_spotLightUniformOuterAngleCosName, _spotLightUniformOuterAngleCosValues.size(), &_spotLightUniformOuterAngleCosValues[0]);
  550. glProgramState->setUniformFloatv(s_spotLightUniformRangeInverseName, _spotLightUniformRangeInverseValues.size(), &_spotLightUniformRangeInverseValues[0]);
  551. }
  552. glProgramState->setUniformVec3(s_ambientLightUniformColorName, Vec3(ambientColor.x, ambientColor.y, ambientColor.z));
  553. }
  554. else // normal does not exist
  555. {
  556. Vec3 ambient(0.0f, 0.0f, 0.0f);
  557. bool hasAmbient = false;
  558. for (const auto& light : lights)
  559. {
  560. if (light->getLightType() == LightType::AMBIENT)
  561. {
  562. bool useLight = light->isEnabled() && ((unsigned int)light->getLightFlag() & lightmask);
  563. if (useLight)
  564. {
  565. hasAmbient = true;
  566. const Color3B &col = light->getDisplayedColor();
  567. ambient.x += col.r * light->getIntensity();
  568. ambient.y += col.g * light->getIntensity();
  569. ambient.z += col.b * light->getIntensity();
  570. }
  571. }
  572. }
  573. if (hasAmbient)
  574. {
  575. ambient.x /= 255.f; ambient.y /= 255.f; ambient.z /= 255.f;
  576. //override the uniform value of u_color using the calculated color
  577. glProgramState->setUniformVec4("u_color", Vec4(color.x * ambient.x, color.y * ambient.y, color.z * ambient.z, color.w));
  578. }
  579. }
  580. }
  581. void Mesh::setBlendFunc(const BlendFunc &blendFunc)
  582. {
  583. // Blend must be saved for future use
  584. // it doesn't matter if the material is already set or not
  585. // This functionality is added for compatibility issues
  586. if(_blend != blendFunc)
  587. {
  588. _blendDirty = true;
  589. _blend = blendFunc;
  590. }
  591. if (_material) {
  592. _material->getStateBlock()->setBlendFunc(blendFunc);
  593. bindMeshCommand();
  594. }
  595. }
  596. const BlendFunc& Mesh::getBlendFunc() const
  597. {
  598. // return _material->_currentTechnique->_passes.at(0)->getBlendFunc();
  599. return _blend;
  600. }
  601. GLenum Mesh::getPrimitiveType() const
  602. {
  603. return _meshIndexData->getPrimitiveType();
  604. }
  605. ssize_t Mesh::getIndexCount() const
  606. {
  607. return _meshIndexData->getIndexBuffer()->getIndexNumber();
  608. }
  609. GLenum Mesh::getIndexFormat() const
  610. {
  611. return GL_UNSIGNED_SHORT;
  612. }
  613. GLuint Mesh::getIndexBuffer() const
  614. {
  615. return _meshIndexData->getIndexBuffer()->getVBO();
  616. }
  617. NS_CC_END