CCPURibbonTrail.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /****************************************************************************
  2. Copyright (C) 2013 Henry van Merode. All rights reserved.
  3. Copyright (c) 2015-2017 Chukong Technologies Inc.
  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 "extensions/Particle3D/PU/CCPURibbonTrail.h"
  22. #include "extensions/Particle3D/PU/CCPUParticleSystem3D.h"
  23. #include "base/CCDirector.h"
  24. #include "renderer/CCMeshCommand.h"
  25. #include "renderer/CCRenderer.h"
  26. #include "renderer/CCTextureCache.h"
  27. #include "renderer/CCGLProgramState.h"
  28. #include "renderer/CCGLProgramCache.h"
  29. #include "renderer/CCVertexIndexBuffer.h"
  30. #include "2d/CCCamera.h"
  31. #include "3d/CCSprite3D.h"
  32. NS_CC_BEGIN
  33. PURibbonTrail::PURibbonTrail(const std::string& name, const std::string &texFile, size_t maxElements,
  34. size_t numberOfChains, bool useTextureCoords, bool useColours)
  35. :PUBillboardChain(name, texFile, maxElements, 0, useTextureCoords, useColours, true),
  36. _parentNode(nullptr),
  37. _needTimeUpdate(false)
  38. {
  39. setTrailLength(100);
  40. setNumberOfChains(numberOfChains);
  41. // use V as varying texture coord, so we can use 1D textures to 'smear'
  42. setTextureCoordDirection(TCD_V);
  43. }
  44. //-----------------------------------------------------------------------
  45. PURibbonTrail::~PURibbonTrail()
  46. {
  47. }
  48. //-----------------------------------------------------------------------
  49. void PURibbonTrail::addNode(Node* n)
  50. {
  51. if (_nodeList.size() == _chainCount)
  52. {
  53. CCASSERT(false, " cannot monitor any more nodes, chain count exceeded");
  54. }
  55. //if (n->getListener())
  56. //{
  57. // OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
  58. // mName + " cannot monitor node " + n->getName() + " since it already has a listener.",
  59. // "RibbonTrail::addNode");
  60. //}
  61. // get chain index
  62. size_t chainIndex = _freeChains.back();
  63. _freeChains.pop_back();
  64. _nodeToChainSegment.push_back(chainIndex);
  65. _nodeToSegMap[n] = chainIndex;
  66. // initialise the chain
  67. resetTrail(chainIndex, n);
  68. _nodeList.push_back(n);
  69. //n->setListener(this);
  70. }
  71. //-----------------------------------------------------------------------
  72. size_t PURibbonTrail::getChainIndexForNode(const Node* n)
  73. {
  74. NodeToChainSegmentMap::const_iterator i = _nodeToSegMap.find(n);
  75. if (i == _nodeToSegMap.end())
  76. {
  77. CCASSERT(false, "This node is not being tracked");
  78. }
  79. return i->second;
  80. }
  81. //-----------------------------------------------------------------------
  82. void PURibbonTrail::removeNode(Node* n)
  83. {
  84. NodeList::iterator i = std::find(_nodeList.begin(), _nodeList.end(), n);
  85. if (i != _nodeList.end())
  86. {
  87. // also get matching chain segment
  88. size_t index = std::distance(_nodeList.begin(), i);
  89. IndexVector::iterator mi = _nodeToChainSegment.begin();
  90. std::advance(mi, index);
  91. size_t chainIndex = *mi;
  92. PUBillboardChain::clearChain(chainIndex);
  93. // mark as free now
  94. _freeChains.push_back(chainIndex);
  95. //n->setListener(0);
  96. _nodeList.erase(i);
  97. _nodeToChainSegment.erase(mi);
  98. _nodeToSegMap.erase(_nodeToSegMap.find(n));
  99. }
  100. }
  101. //-----------------------------------------------------------------------
  102. void PURibbonTrail::setTrailLength(float len)
  103. {
  104. _trailLength = len;
  105. _elemLength = _trailLength / _maxElementsPerChain;
  106. _squaredElemLength = _elemLength * _elemLength;
  107. }
  108. //-----------------------------------------------------------------------
  109. void PURibbonTrail::setMaxChainElements(size_t maxElements)
  110. {
  111. PUBillboardChain::setMaxChainElements(maxElements);
  112. _elemLength = _trailLength / _maxElementsPerChain;
  113. _squaredElemLength = _elemLength * _elemLength;
  114. resetAllTrails();
  115. }
  116. //-----------------------------------------------------------------------
  117. void PURibbonTrail::setNumberOfChains(size_t numChains)
  118. {
  119. CCASSERT(numChains >= _nodeList.size(), "Can't shrink the number of chains less than number of tracking nodes");
  120. size_t oldChains = getNumberOfChains();
  121. PUBillboardChain::setNumberOfChains(numChains);
  122. _initialColor.resize(numChains, Vec4::ONE);
  123. _deltaColor.resize(numChains, Vec4::ZERO);
  124. _initialWidth.resize(numChains, 10);
  125. _deltaWidth.resize(numChains, 0);
  126. if (oldChains > numChains)
  127. {
  128. // remove free chains
  129. for (IndexVector::iterator i = _freeChains.begin(); i != _freeChains.end();)
  130. {
  131. if (*i >= numChains)
  132. i = _freeChains.erase(i);
  133. else
  134. ++i;
  135. }
  136. }
  137. else if (oldChains < numChains)
  138. {
  139. // add new chains, at front to preserve previous ordering (pop_back)
  140. for (size_t i = oldChains; i < numChains; ++i)
  141. _freeChains.insert(_freeChains.begin(), i);
  142. }
  143. resetAllTrails();
  144. }
  145. //-----------------------------------------------------------------------
  146. void PURibbonTrail::clearChain(size_t chainIndex)
  147. {
  148. PUBillboardChain::clearChain(chainIndex);
  149. // Reset if we are tracking for this chain
  150. IndexVector::iterator i = std::find(_nodeToChainSegment.begin(), _nodeToChainSegment.end(), chainIndex);
  151. if (i != _nodeToChainSegment.end())
  152. {
  153. size_t nodeIndex = std::distance(_nodeToChainSegment.begin(), i);
  154. resetTrail(*i, _nodeList[nodeIndex]);
  155. }
  156. }
  157. //-----------------------------------------------------------------------
  158. void PURibbonTrail::setInitialColour(size_t chainIndex, const Vec4& col)
  159. {
  160. setInitialColour(chainIndex, col.x, col.y, col.z, col.w);
  161. }
  162. //-----------------------------------------------------------------------
  163. void PURibbonTrail::setInitialColour(size_t chainIndex, float r, float g, float b, float a)
  164. {
  165. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  166. _initialColor[chainIndex].x = r;
  167. _initialColor[chainIndex].y = g;
  168. _initialColor[chainIndex].z = b;
  169. _initialColor[chainIndex].w = a;
  170. }
  171. //-----------------------------------------------------------------------
  172. const Vec4& PURibbonTrail::getInitialColour(size_t chainIndex) const
  173. {
  174. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  175. return _initialColor[chainIndex];
  176. }
  177. //-----------------------------------------------------------------------
  178. void PURibbonTrail::setInitialWidth(size_t chainIndex, float width)
  179. {
  180. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  181. _initialWidth[chainIndex] = width;
  182. }
  183. //-----------------------------------------------------------------------
  184. float PURibbonTrail::getInitialWidth(size_t chainIndex) const
  185. {
  186. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  187. return _initialWidth[chainIndex];
  188. }
  189. //-----------------------------------------------------------------------
  190. void PURibbonTrail::setColourChange(size_t chainIndex, const Vec4& valuePerSecond)
  191. {
  192. setColourChange(chainIndex,
  193. valuePerSecond.x, valuePerSecond.y, valuePerSecond.z, valuePerSecond.w);
  194. }
  195. //-----------------------------------------------------------------------
  196. void PURibbonTrail::setColourChange(size_t chainIndex, float r, float g, float b, float a)
  197. {
  198. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  199. _deltaColor[chainIndex].x = r;
  200. _deltaColor[chainIndex].y = g;
  201. _deltaColor[chainIndex].z = b;
  202. _deltaColor[chainIndex].w = a;
  203. manageController();
  204. }
  205. //-----------------------------------------------------------------------
  206. const Vec4& PURibbonTrail::getColourChange(size_t chainIndex) const
  207. {
  208. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  209. return _deltaColor[chainIndex];
  210. }
  211. //-----------------------------------------------------------------------
  212. void PURibbonTrail::setWidthChange(size_t chainIndex, float widthDeltaPerSecond)
  213. {
  214. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  215. _deltaWidth[chainIndex] = widthDeltaPerSecond;
  216. manageController();
  217. }
  218. //-----------------------------------------------------------------------
  219. float PURibbonTrail::getWidthChange(size_t chainIndex) const
  220. {
  221. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  222. return _deltaWidth[chainIndex];
  223. }
  224. //-----------------------------------------------------------------------
  225. void PURibbonTrail::manageController(void)
  226. {
  227. _needTimeUpdate = false;
  228. for (size_t i = 0; i < _chainCount; ++i)
  229. {
  230. if (_deltaWidth[i] != 0 || _deltaColor[i] != Vec4::ZERO)
  231. {
  232. _needTimeUpdate = true;
  233. break;
  234. }
  235. }
  236. }
  237. //-----------------------------------------------------------------------
  238. void PURibbonTrail::nodeUpdated(const Node* node)
  239. {
  240. size_t chainIndex = getChainIndexForNode(node);
  241. updateTrail(chainIndex, node);
  242. }
  243. //-----------------------------------------------------------------------
  244. void PURibbonTrail::nodeDestroyed(const Node* node)
  245. {
  246. removeNode(const_cast<Node*>(node));
  247. }
  248. //-----------------------------------------------------------------------
  249. void PURibbonTrail::updateTrail(size_t index, const Node* node)
  250. {
  251. // Repeat this entire process if chain is stretched beyond its natural length
  252. bool done = false;
  253. while (!done)
  254. {
  255. // Node has changed somehow, we're only interested in the derived position
  256. ChainSegment& seg = _chainSegmentList[index];
  257. Element& headElem = _chainElementList[seg.start + seg.head];
  258. size_t nextElemIdx = seg.head + 1;
  259. // wrap
  260. if (nextElemIdx == _maxElementsPerChain)
  261. nextElemIdx = 0;
  262. Element& nextElem = _chainElementList[seg.start + nextElemIdx];
  263. // Vary the head elem, but bake new version if that exceeds element len
  264. Vec3 newPos = node->getPosition3D();
  265. if (_parentNode)
  266. {
  267. // Transform position to ourself space
  268. _parentNode->getWorldToNodeTransform().transformPoint(newPos, &newPos);
  269. }
  270. Vec3 diff = newPos - nextElem.position;
  271. float sqlen = diff.lengthSquared();
  272. if (sqlen >= _squaredElemLength)
  273. {
  274. // Move existing head to mElemLength
  275. Vec3 scaledDiff = diff * (_elemLength / sqrtf(sqlen));
  276. headElem.position = nextElem.position + scaledDiff;
  277. // Add a new element to be the new head
  278. Element newElem( newPos, _initialWidth[index], 0.0f,
  279. _initialColor[index], node->getRotationQuat() );
  280. addChainElement(index, newElem);
  281. // alter diff to represent new head size
  282. diff = newPos - headElem.position;
  283. // check whether another step is needed or not
  284. if (diff.lengthSquared() <= _squaredElemLength)
  285. done = true;
  286. }
  287. else
  288. {
  289. // Extend existing head
  290. headElem.position = newPos;
  291. done = true;
  292. }
  293. // Is this segment full?
  294. if ((seg.tail + 1) % _maxElementsPerChain == seg.head)
  295. {
  296. // If so, shrink tail gradually to match head extension
  297. Element& tailElem = _chainElementList[seg.start + seg.tail];
  298. size_t preTailIdx;
  299. if (seg.tail == 0)
  300. preTailIdx = _maxElementsPerChain - 1;
  301. else
  302. preTailIdx = seg.tail - 1;
  303. Element& preTailElem = _chainElementList[seg.start + preTailIdx];
  304. // Measure tail diff from pretail to tail
  305. Vec3 taildiff = tailElem.position - preTailElem.position;
  306. float taillen = taildiff.length();
  307. if (taillen > 1e-06)
  308. {
  309. float tailsize = _elemLength - diff.length();
  310. taildiff *= tailsize / taillen;
  311. tailElem.position = preTailElem.position + taildiff;
  312. }
  313. }
  314. } // end while
  315. _vertexContentDirty = true;
  316. // Need to dirty the parent node, but can't do it using needUpdate() here
  317. // since we're in the middle of the scene graph update (node listener),
  318. // so re-entrant calls don't work. Queue.
  319. //if (mParentNode)
  320. //{
  321. // Node::queueNeedUpdate(getParentSceneNode());
  322. //}
  323. }
  324. //-----------------------------------------------------------------------
  325. void PURibbonTrail::timeUpdate(float time)
  326. {
  327. // Apply all segment effects
  328. for (size_t s = 0; s < _chainSegmentList.size(); ++s)
  329. {
  330. ChainSegment& seg = _chainSegmentList[s];
  331. if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail)
  332. {
  333. for(size_t e = seg.head + 1;; ++e) // until break
  334. {
  335. e = e % _maxElementsPerChain;
  336. Element& elem = _chainElementList[seg.start + e];
  337. elem.width = elem.width - (time * _deltaWidth[s]);
  338. elem.width = 0.0f < elem.width? elem.width: 0.0f;
  339. elem.color = elem.color - (_deltaColor[s] * time);
  340. elem.color.clamp(Vec4(0.0f, 0.0f, 0.0f, 0.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f));
  341. if (e == seg.tail)
  342. break;
  343. }
  344. }
  345. }
  346. }
  347. //-----------------------------------------------------------------------
  348. void PURibbonTrail::resetTrail(size_t index, const Node* node)
  349. {
  350. assert(index < _chainCount);
  351. ChainSegment& seg = _chainSegmentList[index];
  352. // set up this segment
  353. seg.head = seg.tail = SEGMENT_EMPTY;
  354. // Create new element, v coord is always 0.0f
  355. // need to convert to take parent node's position into account
  356. Vec3 position = node->getPosition3D();
  357. if (_parentNode)
  358. {
  359. // Transform position to ourself space
  360. _parentNode->getWorldToNodeTransform().transformPoint(position, &position);
  361. }
  362. Element e(position,
  363. _initialWidth[index], 0.0f, _initialColor[index], node->getRotationQuat());
  364. // Add the start position
  365. addChainElement(index, e);
  366. // Add another on the same spot, this will extend
  367. addChainElement(index, e);
  368. }
  369. //-----------------------------------------------------------------------
  370. void PURibbonTrail::resetAllTrails(void)
  371. {
  372. for (size_t i = 0; i < _nodeList.size(); ++i)
  373. {
  374. resetTrail(i, _nodeList[i]);
  375. }
  376. }
  377. void PURibbonTrail::update( float deltaTime )
  378. {
  379. if (_needTimeUpdate){
  380. static float lastUpdateTime = 0.0f;
  381. if (0.5f < lastUpdateTime){
  382. timeUpdate(deltaTime);
  383. lastUpdateTime = 0.0f;
  384. }
  385. lastUpdateTime += deltaTime;
  386. }
  387. for (auto iter : _nodeToSegMap){
  388. updateTrail(iter.second, iter.first);
  389. }
  390. }
  391. NS_CC_END