CCSprite3D.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. /****************************************************************************
  2. Copyright (c) 2014-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "3d/CCSprite3D.h"
  22. #include "3d/CCObjLoader.h"
  23. #include "3d/CCMeshSkin.h"
  24. #include "3d/CCBundle3D.h"
  25. #include "3d/CCSprite3DMaterial.h"
  26. #include "3d/CCAttachNode.h"
  27. #include "3d/CCMesh.h"
  28. #include "base/CCDirector.h"
  29. #include "base/CCAsyncTaskPool.h"
  30. #include "base/ccUTF8.h"
  31. #include "2d/CCLight.h"
  32. #include "2d/CCCamera.h"
  33. #include "base/ccMacros.h"
  34. #include "platform/CCPlatformMacros.h"
  35. #include "platform/CCFileUtils.h"
  36. #include "renderer/CCTextureCache.h"
  37. #include "renderer/CCRenderer.h"
  38. #include "renderer/CCGLProgramState.h"
  39. #include "renderer/CCGLProgramCache.h"
  40. #include "renderer/CCMaterial.h"
  41. #include "renderer/CCTechnique.h"
  42. #include "renderer/CCPass.h"
  43. NS_CC_BEGIN
  44. static Sprite3DMaterial* getSprite3DMaterialForAttribs(MeshVertexData* meshVertexData, bool usesLight);
  45. Sprite3D* Sprite3D::create()
  46. {
  47. //
  48. auto sprite = new (std::nothrow) Sprite3D();
  49. if (sprite && sprite->init())
  50. {
  51. sprite->autorelease();
  52. return sprite;
  53. }
  54. CC_SAFE_DELETE(sprite);
  55. return nullptr;
  56. }
  57. Sprite3D* Sprite3D::create(const std::string& modelPath)
  58. {
  59. CCASSERT(modelPath.length() >= 4, "invalid filename for Sprite3D");
  60. auto sprite = new (std::nothrow) Sprite3D();
  61. if (sprite && sprite->initWithFile(modelPath))
  62. {
  63. sprite->_contentSize = sprite->getBoundingBox().size;
  64. sprite->autorelease();
  65. return sprite;
  66. }
  67. CC_SAFE_DELETE(sprite);
  68. return nullptr;
  69. }
  70. Sprite3D* Sprite3D::create(const std::string& modelPath, const std::string& texturePath)
  71. {
  72. auto sprite = create(modelPath);
  73. if (sprite)
  74. {
  75. sprite->setTexture(texturePath);
  76. }
  77. return sprite;
  78. }
  79. void Sprite3D::createAsync(const std::string& modelPath, const std::function<void(Sprite3D*, void*)>& callback, void* callbackparam)
  80. {
  81. createAsync(modelPath, "", callback, callbackparam);
  82. }
  83. void Sprite3D::createAsync(const std::string& modelPath, const std::string& texturePath, const std::function<void(Sprite3D*, void*)>& callback, void* callbackparam)
  84. {
  85. Sprite3D *sprite = new (std::nothrow) Sprite3D();
  86. if (sprite->loadFromCache(modelPath))
  87. {
  88. sprite->autorelease();
  89. if (!texturePath.empty())
  90. sprite->setTexture(texturePath);
  91. callback(sprite, callbackparam);
  92. return;
  93. }
  94. sprite->_asyncLoadParam.afterLoadCallback = callback;
  95. sprite->_asyncLoadParam.texPath = texturePath;
  96. sprite->_asyncLoadParam.modelPath = modelPath;
  97. sprite->_asyncLoadParam.callbackParam = callbackparam;
  98. sprite->_asyncLoadParam.materialdatas = new (std::nothrow) MaterialDatas();
  99. sprite->_asyncLoadParam.meshdatas = new (std::nothrow) MeshDatas();
  100. sprite->_asyncLoadParam.nodeDatas = new (std::nothrow) NodeDatas();
  101. AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_IO, CC_CALLBACK_1(Sprite3D::afterAsyncLoad, sprite), (void*)(&sprite->_asyncLoadParam), [sprite]()
  102. {
  103. sprite->_asyncLoadParam.result = sprite->loadFromFile(sprite->_asyncLoadParam.modelPath, sprite->_asyncLoadParam.nodeDatas, sprite->_asyncLoadParam.meshdatas, sprite->_asyncLoadParam.materialdatas);
  104. });
  105. }
  106. void Sprite3D::afterAsyncLoad(void* param)
  107. {
  108. Sprite3D::AsyncLoadParam* asyncParam = (Sprite3D::AsyncLoadParam*)param;
  109. autorelease();
  110. if (asyncParam)
  111. {
  112. if (asyncParam->result)
  113. {
  114. _meshes.clear();
  115. _meshVertexDatas.clear();
  116. CC_SAFE_RELEASE_NULL(_skeleton);
  117. removeAllAttachNode();
  118. //create in the main thread
  119. auto& meshdatas = asyncParam->meshdatas;
  120. auto& materialdatas = asyncParam->materialdatas;
  121. auto& nodeDatas = asyncParam->nodeDatas;
  122. if (initFrom(*nodeDatas, *meshdatas, *materialdatas))
  123. {
  124. auto spritedata = Sprite3DCache::getInstance()->getSpriteData(asyncParam->modelPath);
  125. if (spritedata == nullptr)
  126. {
  127. //add to cache
  128. auto data = new (std::nothrow) Sprite3DCache::Sprite3DData();
  129. data->materialdatas = materialdatas;
  130. data->nodedatas = nodeDatas;
  131. data->meshVertexDatas = _meshVertexDatas;
  132. for (const auto mesh : _meshes) {
  133. data->glProgramStates.pushBack(mesh->getGLProgramState());
  134. }
  135. Sprite3DCache::getInstance()->addSprite3DData(asyncParam->modelPath, data);
  136. CC_SAFE_DELETE(meshdatas);
  137. materialdatas = nullptr;
  138. nodeDatas = nullptr;
  139. }
  140. }
  141. CC_SAFE_DELETE(meshdatas);
  142. CC_SAFE_DELETE(materialdatas);
  143. CC_SAFE_DELETE(nodeDatas);
  144. if (asyncParam->texPath != "")
  145. {
  146. setTexture(asyncParam->texPath);
  147. }
  148. }
  149. else
  150. {
  151. CCLOG("file load failed: %s ", asyncParam->modelPath.c_str());
  152. }
  153. asyncParam->afterLoadCallback(this, asyncParam->callbackParam);
  154. }
  155. }
  156. AABB Sprite3D::getAABBRecursivelyImp(Node *node)
  157. {
  158. AABB aabb;
  159. for (auto iter : node->getChildren()){
  160. aabb.merge(getAABBRecursivelyImp(iter));
  161. }
  162. Sprite3D *sprite3d = dynamic_cast<Sprite3D*>(node);
  163. if (sprite3d)
  164. aabb.merge(sprite3d->getAABB());
  165. return aabb;
  166. }
  167. bool Sprite3D::loadFromCache(const std::string& path)
  168. {
  169. auto spritedata = Sprite3DCache::getInstance()->getSpriteData(path);
  170. if (spritedata)
  171. {
  172. for (auto it : spritedata->meshVertexDatas) {
  173. _meshVertexDatas.pushBack(it);
  174. }
  175. _skeleton = Skeleton3D::create(spritedata->nodedatas->skeleton);
  176. CC_SAFE_RETAIN(_skeleton);
  177. const bool singleSprite = (spritedata->nodedatas->nodes.size() == 1);
  178. for(const auto& it : spritedata->nodedatas->nodes)
  179. {
  180. if(it)
  181. {
  182. createNode(it, this, *(spritedata->materialdatas), singleSprite);
  183. }
  184. }
  185. for(const auto& it : spritedata->nodedatas->skeleton)
  186. {
  187. if(it)
  188. {
  189. createAttachSprite3DNode(it,*(spritedata->materialdatas));
  190. }
  191. }
  192. for (ssize_t i = 0, size = _meshes.size(); i < size; ++i) {
  193. // cloning is needed in order to have one state per sprite
  194. auto glstate = spritedata->glProgramStates.at(i);
  195. _meshes.at(i)->setGLProgramState(glstate->clone());
  196. }
  197. return true;
  198. }
  199. return false;
  200. }
  201. bool Sprite3D::loadFromFile(const std::string& path, NodeDatas* nodedatas, MeshDatas* meshdatas, MaterialDatas* materialdatas)
  202. {
  203. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path);
  204. std::string ext = FileUtils::getInstance()->getFileExtension(path);
  205. if (ext == ".obj")
  206. {
  207. return Bundle3D::loadObj(*meshdatas, *materialdatas, *nodedatas, fullPath);
  208. }
  209. else if (ext == ".c3b" || ext == ".c3t")
  210. {
  211. //load from .c3b or .c3t
  212. auto bundle = Bundle3D::createBundle();
  213. if (!bundle->load(fullPath))
  214. {
  215. Bundle3D::destroyBundle(bundle);
  216. return false;
  217. }
  218. auto ret = bundle->loadMeshDatas(*meshdatas)
  219. && bundle->loadMaterials(*materialdatas) && bundle->loadNodes(*nodedatas);
  220. Bundle3D::destroyBundle(bundle);
  221. return ret;
  222. }
  223. return false;
  224. }
  225. Sprite3D::Sprite3D()
  226. : _skeleton(nullptr)
  227. , _blend(BlendFunc::ALPHA_NON_PREMULTIPLIED)
  228. , _aabbDirty(true)
  229. , _lightMask(-1)
  230. , _shaderUsingLight(false)
  231. , _forceDepthWrite(false)
  232. , _usingAutogeneratedGLProgram(true)
  233. {
  234. }
  235. Sprite3D::~Sprite3D()
  236. {
  237. _meshes.clear();
  238. _meshVertexDatas.clear();
  239. CC_SAFE_RELEASE_NULL(_skeleton);
  240. removeAllAttachNode();
  241. }
  242. bool Sprite3D::init()
  243. {
  244. if(Node::init())
  245. {
  246. return true;
  247. }
  248. return false;
  249. }
  250. bool Sprite3D::initWithFile(const std::string& path)
  251. {
  252. _aabbDirty = true;
  253. _meshes.clear();
  254. _meshVertexDatas.clear();
  255. CC_SAFE_RELEASE_NULL(_skeleton);
  256. removeAllAttachNode();
  257. if (loadFromCache(path))
  258. return true;
  259. MeshDatas* meshdatas = new (std::nothrow) MeshDatas();
  260. MaterialDatas* materialdatas = new (std::nothrow) MaterialDatas();
  261. NodeDatas* nodeDatas = new (std::nothrow) NodeDatas();
  262. if (loadFromFile(path, nodeDatas, meshdatas, materialdatas))
  263. {
  264. if (initFrom(*nodeDatas, *meshdatas, *materialdatas))
  265. {
  266. //add to cache
  267. auto data = new (std::nothrow) Sprite3DCache::Sprite3DData();
  268. data->materialdatas = materialdatas;
  269. data->nodedatas = nodeDatas;
  270. data->meshVertexDatas = _meshVertexDatas;
  271. for (const auto mesh : _meshes) {
  272. data->glProgramStates.pushBack(mesh->getGLProgramState());
  273. }
  274. Sprite3DCache::getInstance()->addSprite3DData(path, data);
  275. CC_SAFE_DELETE(meshdatas);
  276. _contentSize = getBoundingBox().size;
  277. return true;
  278. }
  279. }
  280. CC_SAFE_DELETE(meshdatas);
  281. CC_SAFE_DELETE(materialdatas);
  282. CC_SAFE_DELETE(nodeDatas);
  283. return false;
  284. }
  285. bool Sprite3D::initFrom(const NodeDatas& nodeDatas, const MeshDatas& meshdatas, const MaterialDatas& materialdatas)
  286. {
  287. for(const auto& it : meshdatas.meshDatas)
  288. {
  289. if(it)
  290. {
  291. // Mesh* mesh = Mesh::create(*it);
  292. // _meshes.pushBack(mesh);
  293. auto meshvertex = MeshVertexData::create(*it);
  294. _meshVertexDatas.pushBack(meshvertex);
  295. }
  296. }
  297. _skeleton = Skeleton3D::create(nodeDatas.skeleton);
  298. CC_SAFE_RETAIN(_skeleton);
  299. auto size = nodeDatas.nodes.size();
  300. for(const auto& it : nodeDatas.nodes)
  301. {
  302. if(it)
  303. {
  304. createNode(it, this, materialdatas, size == 1);
  305. }
  306. }
  307. for(const auto& it : nodeDatas.skeleton)
  308. {
  309. if(it)
  310. {
  311. createAttachSprite3DNode(it,materialdatas);
  312. }
  313. }
  314. genMaterial();
  315. return true;
  316. }
  317. Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,const MaterialDatas& materialdatas)
  318. {
  319. auto sprite = new (std::nothrow) Sprite3D();
  320. if (sprite)
  321. {
  322. sprite->setName(nodedata->id);
  323. auto mesh = Mesh::create(nodedata->id, getMeshIndexData(modeldata->subMeshId));
  324. if (_skeleton && modeldata->bones.size())
  325. {
  326. auto skin = MeshSkin::create(_skeleton, modeldata->bones, modeldata->invBindPose);
  327. mesh->setSkin(skin);
  328. }
  329. if (modeldata->materialId == "" && materialdatas.materials.size())
  330. {
  331. const NTextureData* textureData = materialdatas.materials[0].getTextureData(NTextureData::Usage::Diffuse);
  332. mesh->setTexture(textureData->filename);
  333. }
  334. else
  335. {
  336. const NMaterialData* materialData = materialdatas.getMaterialData(modeldata->materialId);
  337. if(materialData)
  338. {
  339. const NTextureData* textureData = materialData->getTextureData(NTextureData::Usage::Diffuse);
  340. if(textureData)
  341. {
  342. mesh->setTexture(textureData->filename);
  343. auto tex = mesh->getTexture();
  344. if(tex)
  345. {
  346. Texture2D::TexParams texParams;
  347. texParams.minFilter = GL_LINEAR;
  348. texParams.magFilter = GL_LINEAR;
  349. texParams.wrapS = textureData->wrapS;
  350. texParams.wrapT = textureData->wrapT;
  351. tex->setTexParameters(texParams);
  352. mesh->_isTransparent = (materialData->getTextureData(NTextureData::Usage::Transparency) != nullptr);
  353. }
  354. }
  355. textureData = materialData->getTextureData(NTextureData::Usage::Normal);
  356. if (textureData)
  357. {
  358. auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename);
  359. if(tex)
  360. {
  361. Texture2D::TexParams texParams;
  362. texParams.minFilter = GL_LINEAR;
  363. texParams.magFilter = GL_LINEAR;
  364. texParams.wrapS = textureData->wrapS;
  365. texParams.wrapT = textureData->wrapT;
  366. tex->setTexParameters(texParams);
  367. }
  368. mesh->setTexture(tex, NTextureData::Usage::Normal);
  369. }
  370. }
  371. }
  372. // set locale transform
  373. Vec3 pos;
  374. Quaternion qua;
  375. Vec3 scale;
  376. nodedata->transform.decompose(&scale, &qua, &pos);
  377. sprite->setPosition3D(pos);
  378. sprite->setRotationQuat(qua);
  379. sprite->setScaleX(scale.x);
  380. sprite->setScaleY(scale.y);
  381. sprite->setScaleZ(scale.z);
  382. sprite->addMesh(mesh);
  383. sprite->autorelease();
  384. sprite->genMaterial();
  385. }
  386. return sprite;
  387. }
  388. void Sprite3D::createAttachSprite3DNode(NodeData* nodedata, const MaterialDatas& materialdatas)
  389. {
  390. for(const auto& it : nodedata->modelNodeDatas)
  391. {
  392. if(it && getAttachNode(nodedata->id))
  393. {
  394. auto sprite = createSprite3DNode(nodedata,it,materialdatas);
  395. if (sprite)
  396. {
  397. getAttachNode(nodedata->id)->addChild(sprite);
  398. }
  399. }
  400. }
  401. for(const auto& it : nodedata->children)
  402. {
  403. createAttachSprite3DNode(it,materialdatas);
  404. }
  405. }
  406. void Sprite3D::setMaterial(Material *material)
  407. {
  408. setMaterial(material, -1);
  409. }
  410. void Sprite3D::setMaterial(Material *material, int meshIndex)
  411. {
  412. CCASSERT(material, "Invalid Material");
  413. CCASSERT(meshIndex == -1 || (meshIndex >=0 && meshIndex < _meshes.size()), "Invalid meshIndex");
  414. if (meshIndex == -1)
  415. {
  416. for (ssize_t i = 0, size = _meshes.size(); i < size; ++i)
  417. {
  418. _meshes.at(i)->setMaterial(i == 0 ? material : material->clone());
  419. }
  420. }
  421. else
  422. {
  423. auto mesh = _meshes.at(meshIndex);
  424. mesh->setMaterial(material);
  425. }
  426. _usingAutogeneratedGLProgram = false;
  427. }
  428. Material* Sprite3D::getMaterial(int meshIndex) const
  429. {
  430. CCASSERT(meshIndex >=0 && meshIndex < _meshes.size(), "Invalid meshIndex");
  431. return _meshes.at(meshIndex)->getMaterial();
  432. }
  433. void Sprite3D::genMaterial(bool useLight)
  434. {
  435. _shaderUsingLight = useLight;
  436. std::unordered_map<const MeshVertexData*, Sprite3DMaterial*> materials;
  437. for(auto meshVertexData : _meshVertexDatas)
  438. {
  439. auto material = getSprite3DMaterialForAttribs(meshVertexData, useLight);
  440. materials[meshVertexData] = material;
  441. }
  442. for (auto& mesh: _meshes)
  443. {
  444. auto material = materials[mesh->getMeshIndexData()->getMeshVertexData()];
  445. //keep original state block if exist
  446. auto oldmaterial = mesh->getMaterial();
  447. if (oldmaterial)
  448. {
  449. material->setStateBlock(oldmaterial->getStateBlock());
  450. }
  451. if (material->getReferenceCount() == 1)
  452. mesh->setMaterial(material);
  453. else
  454. mesh->setMaterial(material->clone());
  455. }
  456. }
  457. void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& materialdatas, bool singleSprite)
  458. {
  459. Node* node=nullptr;
  460. for(const auto& it : nodedata->modelNodeDatas)
  461. {
  462. if(it)
  463. {
  464. if(it->bones.size() > 0 || singleSprite)
  465. {
  466. if(singleSprite && root!=nullptr)
  467. root->setName(nodedata->id);
  468. auto mesh = Mesh::create(nodedata->id, getMeshIndexData(it->subMeshId));
  469. if(mesh)
  470. {
  471. _meshes.pushBack(mesh);
  472. if (_skeleton && it->bones.size())
  473. {
  474. auto skin = MeshSkin::create(_skeleton, it->bones, it->invBindPose);
  475. mesh->setSkin(skin);
  476. }
  477. mesh->_visibleChanged = std::bind(&Sprite3D::onAABBDirty, this);
  478. if (it->materialId == "" && materialdatas.materials.size())
  479. {
  480. const NTextureData* textureData = materialdatas.materials[0].getTextureData(NTextureData::Usage::Diffuse);
  481. mesh->setTexture(textureData->filename);
  482. }
  483. else
  484. {
  485. const NMaterialData* materialData = materialdatas.getMaterialData(it->materialId);
  486. if(materialData)
  487. {
  488. const NTextureData* textureData = materialData->getTextureData(NTextureData::Usage::Diffuse);
  489. if(textureData)
  490. {
  491. mesh->setTexture(textureData->filename);
  492. auto tex = mesh->getTexture();
  493. if(tex)
  494. {
  495. Texture2D::TexParams texParams;
  496. texParams.minFilter = GL_LINEAR;
  497. texParams.magFilter = GL_LINEAR;
  498. texParams.wrapS = textureData->wrapS;
  499. texParams.wrapT = textureData->wrapT;
  500. tex->setTexParameters(texParams);
  501. mesh->_isTransparent = (materialData->getTextureData(NTextureData::Usage::Transparency) != nullptr);
  502. }
  503. }
  504. textureData = materialData->getTextureData(NTextureData::Usage::Normal);
  505. if (textureData)
  506. {
  507. auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename);
  508. if (tex)
  509. {
  510. Texture2D::TexParams texParams;
  511. texParams.minFilter = GL_LINEAR;
  512. texParams.magFilter = GL_LINEAR;
  513. texParams.wrapS = textureData->wrapS;
  514. texParams.wrapT = textureData->wrapT;
  515. tex->setTexParameters(texParams);
  516. }
  517. mesh->setTexture(tex, NTextureData::Usage::Normal);
  518. }
  519. }
  520. }
  521. Vec3 pos;
  522. Quaternion qua;
  523. Vec3 scale;
  524. nodedata->transform.decompose(&scale, &qua, &pos);
  525. setPosition3D(pos);
  526. setRotationQuat(qua);
  527. setScaleX(scale.x);
  528. setScaleY(scale.y);
  529. setScaleZ(scale.z);
  530. node = this;
  531. }
  532. }
  533. else
  534. {
  535. auto sprite = createSprite3DNode(nodedata,it,materialdatas);
  536. if (sprite)
  537. {
  538. if(root)
  539. {
  540. root->addChild(sprite);
  541. }
  542. }
  543. node=sprite;
  544. }
  545. }
  546. }
  547. if(nodedata->modelNodeDatas.size() ==0 )
  548. {
  549. node= Node::create();
  550. if(node)
  551. {
  552. node->setName(nodedata->id);
  553. // set locale transform
  554. Vec3 pos;
  555. Quaternion qua;
  556. Vec3 scale;
  557. nodedata->transform.decompose(&scale, &qua, &pos);
  558. node->setPosition3D(pos);
  559. node->setRotationQuat(qua);
  560. node->setScaleX(scale.x);
  561. node->setScaleY(scale.y);
  562. node->setScaleZ(scale.z);
  563. if(root)
  564. {
  565. root->addChild(node);
  566. }
  567. }
  568. }
  569. auto size = nodedata->children.size();
  570. for(const auto& it : nodedata->children)
  571. {
  572. createNode(it,node, materialdatas, size == 1);
  573. }
  574. }
  575. MeshIndexData* Sprite3D::getMeshIndexData(const std::string& indexId) const
  576. {
  577. for (auto it : _meshVertexDatas) {
  578. auto index = it->getMeshIndexDataById(indexId);
  579. if (index)
  580. return index;
  581. }
  582. return nullptr;
  583. }
  584. void Sprite3D::addMesh(Mesh* mesh)
  585. {
  586. auto meshVertex = mesh->getMeshIndexData()->_vertexData;
  587. _meshVertexDatas.pushBack(meshVertex);
  588. _meshes.pushBack(mesh);
  589. }
  590. void Sprite3D::setTexture(const std::string& texFile)
  591. {
  592. auto tex = Director::getInstance()->getTextureCache()->addImage(texFile);
  593. setTexture(tex);
  594. }
  595. void Sprite3D::setTexture(Texture2D* texture)
  596. {
  597. for (auto mesh: _meshes) {
  598. mesh->setTexture(texture);
  599. }
  600. }
  601. AttachNode* Sprite3D::getAttachNode(const std::string& boneName)
  602. {
  603. auto it = _attachments.find(boneName);
  604. if (it != _attachments.end())
  605. return it->second;
  606. if (_skeleton)
  607. {
  608. auto bone = _skeleton->getBoneByName(boneName);
  609. if (bone)
  610. {
  611. auto attachNode = AttachNode::create(bone);
  612. addChild(attachNode);
  613. _attachments[boneName] = attachNode;
  614. return attachNode;
  615. }
  616. }
  617. return nullptr;
  618. }
  619. void Sprite3D::removeAttachNode(const std::string& boneName)
  620. {
  621. auto it = _attachments.find(boneName);
  622. if (it != _attachments.end())
  623. {
  624. removeChild(it->second);
  625. _attachments.erase(it);
  626. }
  627. }
  628. void Sprite3D::removeAllAttachNode()
  629. {
  630. for (auto& it : _attachments) {
  631. removeChild(it.second);
  632. }
  633. _attachments.clear();
  634. }
  635. void Sprite3D::visit(cocos2d::Renderer *renderer, const cocos2d::Mat4 &parentTransform, uint32_t parentFlags)
  636. {
  637. // quick return if not visible. children won't be drawn.
  638. if (!_visible)
  639. {
  640. return;
  641. }
  642. uint32_t flags = processParentFlags(parentTransform, parentFlags);
  643. flags |= FLAGS_RENDER_AS_3D;
  644. //
  645. Director* director = Director::getInstance();
  646. director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  647. director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
  648. bool visibleByCamera = isVisitableByVisitingCamera();
  649. int i = 0;
  650. if(!_children.empty())
  651. {
  652. sortAllChildren();
  653. // draw children zOrder < 0
  654. for(auto size = _children.size() ; i < size; i++ )
  655. {
  656. auto node = _children.at(i);
  657. if (node && node->getLocalZOrder() < 0)
  658. node->visit(renderer, _modelViewTransform, flags);
  659. else
  660. break;
  661. }
  662. // self draw
  663. if (visibleByCamera)
  664. this->draw(renderer, _modelViewTransform, flags);
  665. for(auto it=_children.cbegin()+i, itCend = _children.cend(); it != itCend; ++it)
  666. (*it)->visit(renderer, _modelViewTransform, flags);
  667. }
  668. else if (visibleByCamera)
  669. {
  670. this->draw(renderer, _modelViewTransform, flags);
  671. }
  672. director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  673. }
  674. void Sprite3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
  675. {
  676. #if CC_USE_CULLING
  677. // camera clipping
  678. if(_children.size() == 0 && Camera::getVisitingCamera() && !Camera::getVisitingCamera()->isVisibleInFrustum(&getAABB()))
  679. return;
  680. #endif
  681. if (_skeleton)
  682. _skeleton->updateBoneMatrix();
  683. Color4F color(getDisplayedColor());
  684. color.a = getDisplayedOpacity() / 255.0f;
  685. //check light and determine the shader used
  686. const auto& scene = Director::getInstance()->getRunningScene();
  687. // Don't override GLProgramState if using manually set Material
  688. if (_usingAutogeneratedGLProgram && scene)
  689. {
  690. const auto lights = scene->getLights();
  691. bool usingLight = false;
  692. for (const auto light : lights) {
  693. usingLight = light->isEnabled() && ((static_cast<unsigned int>(light->getLightFlag()) & _lightMask) > 0);
  694. if (usingLight)
  695. break;
  696. }
  697. if (usingLight != _shaderUsingLight)
  698. {
  699. genMaterial(usingLight);
  700. }
  701. }
  702. for (auto mesh: _meshes)
  703. {
  704. mesh->draw(renderer,
  705. _globalZOrder,
  706. transform,
  707. flags,
  708. _lightMask,
  709. Vec4(color.r, color.g, color.b, color.a),
  710. _forceDepthWrite);
  711. }
  712. }
  713. void Sprite3D::setGLProgramState(GLProgramState* glProgramState)
  714. {
  715. Node::setGLProgramState(glProgramState);
  716. for (auto state : _meshes) {
  717. state->setGLProgramState(glProgramState);
  718. }
  719. }
  720. void Sprite3D::setGLProgram(GLProgram* glprogram)
  721. {
  722. auto glProgramState = GLProgramState::create(glprogram);
  723. setGLProgramState(glProgramState);
  724. }
  725. void Sprite3D::setBlendFunc(const BlendFunc& blendFunc)
  726. {
  727. if(_blend.src != blendFunc.src || _blend.dst != blendFunc.dst)
  728. {
  729. _blend = blendFunc;
  730. for(auto mesh: _meshes)
  731. {
  732. mesh->setBlendFunc(blendFunc);
  733. }
  734. }
  735. }
  736. const BlendFunc& Sprite3D::getBlendFunc() const
  737. {
  738. return _blend;
  739. }
  740. AABB Sprite3D::getAABBRecursively()
  741. {
  742. return getAABBRecursivelyImp(this);
  743. }
  744. const AABB& Sprite3D::getAABB() const
  745. {
  746. Mat4 nodeToWorldTransform(getNodeToWorldTransform());
  747. // If nodeToWorldTransform matrix isn't changed, we don't need to transform aabb.
  748. if (memcmp(_nodeToWorldTransform.m, nodeToWorldTransform.m, sizeof(Mat4)) == 0 && !_aabbDirty)
  749. {
  750. return _aabb;
  751. }
  752. else
  753. {
  754. _aabb.reset();
  755. if (_meshes.size())
  756. {
  757. Mat4 transform(nodeToWorldTransform);
  758. for (const auto& it : _meshes) {
  759. if (it->isVisible())
  760. _aabb.merge(it->getAABB());
  761. }
  762. _aabb.transform(transform);
  763. _nodeToWorldTransform = nodeToWorldTransform;
  764. _aabbDirty = false;
  765. }
  766. }
  767. return _aabb;
  768. }
  769. Action* Sprite3D::runAction(Action *action)
  770. {
  771. setForceDepthWrite(true);
  772. return Node::runAction(action);
  773. }
  774. Rect Sprite3D::getBoundingBox() const
  775. {
  776. AABB aabb = getAABB();
  777. Rect ret(aabb._min.x, aabb._min.y, (aabb._max.x - aabb._min.x), (aabb._max.y - aabb._min.y));
  778. return ret;
  779. }
  780. void Sprite3D::setCullFace(GLenum cullFace)
  781. {
  782. for (auto& it : _meshes) {
  783. it->getMaterial()->getStateBlock()->setCullFaceSide((RenderState::CullFaceSide)cullFace);
  784. // it->getMeshCommand().setCullFace(cullFace);
  785. }
  786. }
  787. void Sprite3D::setCullFaceEnabled(bool enable)
  788. {
  789. for (auto& it : _meshes) {
  790. it->getMaterial()->getStateBlock()->setCullFace(enable);
  791. // it->getMeshCommand().setCullFaceEnabled(enable);
  792. }
  793. }
  794. Mesh* Sprite3D::getMeshByIndex(int index) const
  795. {
  796. CCASSERT(index < _meshes.size(), "invalid index");
  797. return _meshes.at(index);
  798. }
  799. /**get Mesh by Name */
  800. Mesh* Sprite3D::getMeshByName(const std::string& name) const
  801. {
  802. for (const auto& it : _meshes) {
  803. if (it->getName() == name)
  804. return it;
  805. }
  806. return nullptr;
  807. }
  808. std::vector<Mesh*> Sprite3D::getMeshArrayByName(const std::string& name) const
  809. {
  810. std::vector<Mesh*> meshes;
  811. for (const auto& it : _meshes) {
  812. if (it->getName() == name)
  813. meshes.push_back(it);
  814. }
  815. return meshes;
  816. }
  817. Mesh* Sprite3D::getMesh() const
  818. {
  819. if(_meshes.empty())
  820. {
  821. return nullptr;
  822. }
  823. return _meshes.at(0);
  824. }
  825. MeshSkin* Sprite3D::getSkin() const
  826. {
  827. for (const auto& it : _meshes) {
  828. if (it->getSkin())
  829. return it->getSkin();
  830. }
  831. return nullptr;
  832. }
  833. void Sprite3D::setForce2DQueue(bool force2D)
  834. {
  835. for (const auto &mesh : _meshes) {
  836. mesh->setForce2DQueue(force2D);
  837. }
  838. }
  839. ///////////////////////////////////////////////////////////////////////////////////
  840. Sprite3DCache* Sprite3DCache::_cacheInstance = nullptr;
  841. Sprite3DCache* Sprite3DCache::getInstance()
  842. {
  843. if (_cacheInstance == nullptr)
  844. _cacheInstance = new (std::nothrow) Sprite3DCache();
  845. return _cacheInstance;
  846. }
  847. void Sprite3DCache::destroyInstance()
  848. {
  849. if (_cacheInstance)
  850. {
  851. delete _cacheInstance;
  852. _cacheInstance = nullptr;
  853. }
  854. }
  855. Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(const std::string& key) const
  856. {
  857. auto it = _spriteDatas.find(key);
  858. if (it != _spriteDatas.end())
  859. return it->second;
  860. return nullptr;
  861. }
  862. bool Sprite3DCache::addSprite3DData(const std::string& key, Sprite3DCache::Sprite3DData* spritedata)
  863. {
  864. auto it = _spriteDatas.find(key);
  865. if (it == _spriteDatas.end())
  866. {
  867. _spriteDatas[key] = spritedata;
  868. return true;
  869. }
  870. return false;
  871. }
  872. void Sprite3DCache::removeSprite3DData(const std::string& key)
  873. {
  874. auto it = _spriteDatas.find(key);
  875. if (it != _spriteDatas.end())
  876. {
  877. delete it->second;
  878. _spriteDatas.erase(it);
  879. }
  880. }
  881. void Sprite3DCache::removeAllSprite3DData()
  882. {
  883. for (auto& it : _spriteDatas) {
  884. delete it.second;
  885. }
  886. _spriteDatas.clear();
  887. }
  888. Sprite3DCache::Sprite3DCache()
  889. {
  890. }
  891. Sprite3DCache::~Sprite3DCache()
  892. {
  893. removeAllSprite3DData();
  894. }
  895. //
  896. // MARK: Helpers
  897. //
  898. static Sprite3DMaterial* getSprite3DMaterialForAttribs(MeshVertexData* meshVertexData, bool usesLight)
  899. {
  900. bool textured = meshVertexData->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_TEX_COORD);
  901. bool hasSkin = meshVertexData->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_BLEND_INDEX)
  902. && meshVertexData->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_BLEND_WEIGHT);
  903. bool hasNormal = meshVertexData->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_NORMAL);
  904. bool hasTangentSpace = meshVertexData->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_TANGENT)
  905. && meshVertexData->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_BINORMAL);
  906. Sprite3DMaterial::MaterialType type;
  907. if(textured)
  908. {
  909. if (hasTangentSpace){
  910. type = hasNormal && usesLight ? Sprite3DMaterial::MaterialType::BUMPED_DIFFUSE : Sprite3DMaterial::MaterialType::UNLIT;
  911. }
  912. else{
  913. type = hasNormal && usesLight ? Sprite3DMaterial::MaterialType::DIFFUSE : Sprite3DMaterial::MaterialType::UNLIT;
  914. }
  915. }
  916. else
  917. {
  918. type = hasNormal && usesLight ? Sprite3DMaterial::MaterialType::DIFFUSE_NOTEX : Sprite3DMaterial::MaterialType::UNLIT_NOTEX;
  919. }
  920. return Sprite3DMaterial::createBuiltInMaterial(type, hasSkin);
  921. }
  922. NS_CC_END