CCPURibbonTrail.cpp 15.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
/****************************************************************************
 Copyright (C) 2013 Henry van Merode. All rights reserved.
 Copyright (c) 2015-2016 Chukong Technologies Inc.
 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
 http://www.cocos2d-x.org
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#include "extensions/Particle3D/PU/CCPURibbonTrail.h"
#include "extensions/Particle3D/PU/CCPUParticleSystem3D.h"
#include "base/CCDirector.h"
#include "renderer/CCMeshCommand.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCTextureCache.h"
#include "renderer/backend/ProgramState.h"
#include "2d/CCCamera.h"
#include "3d/CCSprite3D.h"

NS_CC_BEGIN

PURibbonTrail::PURibbonTrail(const std::string& name, const std::string &texFile, size_t maxElements, 
    size_t numberOfChains, bool useTextureCoords, bool useColours)
    :PUBillboardChain(name, texFile, maxElements, 0, useTextureCoords, useColours, true),
    _parentNode(nullptr),
    _needTimeUpdate(false)
{
    setTrailLength(100);
    setNumberOfChains(numberOfChains);

    // use V as varying texture coord, so we can use 1D textures to 'smear'
    setTextureCoordDirection(TCD_V);
}
//-----------------------------------------------------------------------
PURibbonTrail::~PURibbonTrail()
{
}
//-----------------------------------------------------------------------
void PURibbonTrail::addNode(Node* n)
{
    if (_nodeList.size() == _chainCount)
    {
        CCASSERT(false, " cannot monitor any more nodes, chain count exceeded");
    }

    //if (n->getListener())
    //{
    //	OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
    //		mName + " cannot monitor node " + n->getName() + " since it already has a listener.",
    //		"RibbonTrail::addNode");
    //}

    // get chain index
    size_t chainIndex = _freeChains.back();
    _freeChains.pop_back();
    _nodeToChainSegment.push_back(chainIndex);
    _nodeToSegMap[n] = chainIndex;

    // initialise the chain
    resetTrail(chainIndex, n);

    _nodeList.push_back(n);
    //n->setListener(this);

}
//-----------------------------------------------------------------------
size_t PURibbonTrail::getChainIndexForNode(const Node* n)
{
    NodeToChainSegmentMap::const_iterator i = _nodeToSegMap.find(n);
    if (i == _nodeToSegMap.end())
    {
        CCASSERT(false, "This node is not being tracked");
    }
    return i->second;
}
//-----------------------------------------------------------------------
void PURibbonTrail::removeNode(Node* n)
{
    NodeList::iterator i = std::find(_nodeList.begin(), _nodeList.end(), n);
    if (i != _nodeList.end())
    {
        // also get matching chain segment
        size_t index = std::distance(_nodeList.begin(), i);
        IndexVector::iterator mi = _nodeToChainSegment.begin();
        std::advance(mi, index);
        size_t chainIndex = *mi;
        PUBillboardChain::clearChain(chainIndex);
        // mark as free now
        _freeChains.push_back(chainIndex);
        //n->setListener(0);
        _nodeList.erase(i);
        _nodeToChainSegment.erase(mi);
        _nodeToSegMap.erase(_nodeToSegMap.find(n));
    }
}
//-----------------------------------------------------------------------
void PURibbonTrail::setTrailLength(float len)
{
    _trailLength = len;
    _elemLength = _trailLength / _maxElementsPerChain;
    _squaredElemLength = _elemLength * _elemLength;
}
//-----------------------------------------------------------------------
void PURibbonTrail::setMaxChainElements(size_t maxElements)
{
    PUBillboardChain::setMaxChainElements(maxElements);
    _elemLength = _trailLength / _maxElementsPerChain;
    _squaredElemLength = _elemLength * _elemLength;

    resetAllTrails();
}
//-----------------------------------------------------------------------
void PURibbonTrail::setNumberOfChains(size_t numChains)
{
    CCASSERT(numChains >= _nodeList.size(), "Can't shrink the number of chains less than number of tracking nodes");

    size_t oldChains = getNumberOfChains();

    PUBillboardChain::setNumberOfChains(numChains);

    _initialColor.resize(numChains, Vec4::ONE);
    _deltaColor.resize(numChains, Vec4::ZERO);
    _initialWidth.resize(numChains, 10);
    _deltaWidth.resize(numChains, 0);

    if (oldChains > numChains)
    {
        // remove free chains
        for (IndexVector::iterator i = _freeChains.begin(); i != _freeChains.end();)
        {
            if (*i >= numChains)
                i = _freeChains.erase(i);
            else
                ++i;
        }
    }
    else if (oldChains < numChains)
    {
        // add new chains, at front to preserve previous ordering (pop_back)
        for (size_t i = oldChains; i < numChains; ++i)
            _freeChains.insert(_freeChains.begin(), i);
    }
    resetAllTrails();
}
//-----------------------------------------------------------------------
void PURibbonTrail::clearChain(size_t chainIndex)
{
    PUBillboardChain::clearChain(chainIndex);

    // Reset if we are tracking for this chain
    IndexVector::iterator i = std::find(_nodeToChainSegment.begin(), _nodeToChainSegment.end(), chainIndex);
    if (i != _nodeToChainSegment.end())
    {
        size_t nodeIndex = std::distance(_nodeToChainSegment.begin(), i);
        resetTrail(*i, _nodeList[nodeIndex]);
    }
}
//-----------------------------------------------------------------------
void PURibbonTrail::setInitialColour(size_t chainIndex, const Vec4& col)
{
    setInitialColour(chainIndex, col.x, col.y, col.z, col.w);
}
//-----------------------------------------------------------------------
void PURibbonTrail::setInitialColour(size_t chainIndex, float r, float g, float b, float a)
{
    CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
    _initialColor[chainIndex].x = r;
    _initialColor[chainIndex].y = g;
    _initialColor[chainIndex].z = b;
    _initialColor[chainIndex].w = a;
}
//-----------------------------------------------------------------------
const Vec4& PURibbonTrail::getInitialColour(size_t chainIndex) const
{
    CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
    return _initialColor[chainIndex];
}
//-----------------------------------------------------------------------
void PURibbonTrail::setInitialWidth(size_t chainIndex, float width)
{
    CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
    _initialWidth[chainIndex] = width;
}
//-----------------------------------------------------------------------
float PURibbonTrail::getInitialWidth(size_t chainIndex) const
{
    CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
    return _initialWidth[chainIndex];
}
//-----------------------------------------------------------------------
void PURibbonTrail::setColourChange(size_t chainIndex, const Vec4& valuePerSecond)
{
    setColourChange(chainIndex, 
        valuePerSecond.x, valuePerSecond.y, valuePerSecond.z, valuePerSecond.w);
}
//-----------------------------------------------------------------------
void PURibbonTrail::setColourChange(size_t chainIndex, float r, float g, float b, float a)
{
    CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
    _deltaColor[chainIndex].x = r;
    _deltaColor[chainIndex].y = g;
    _deltaColor[chainIndex].z = b;
    _deltaColor[chainIndex].w = a;

    manageController();

}
//-----------------------------------------------------------------------
const Vec4& PURibbonTrail::getColourChange(size_t chainIndex) const
{
    CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
    return _deltaColor[chainIndex];
}
//-----------------------------------------------------------------------
void PURibbonTrail::setWidthChange(size_t chainIndex, float widthDeltaPerSecond)
{
    CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
    _deltaWidth[chainIndex] = widthDeltaPerSecond;
    manageController();
}
//-----------------------------------------------------------------------
float PURibbonTrail::getWidthChange(size_t chainIndex) const
{
    CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
    return _deltaWidth[chainIndex];

}
//-----------------------------------------------------------------------
void PURibbonTrail::manageController()
{
    _needTimeUpdate = false;
    for (size_t i = 0; i < _chainCount; ++i)
    {
        if (_deltaWidth[i] != 0 || _deltaColor[i] != Vec4::ZERO)
        {
            _needTimeUpdate = true;
            break;
        }
    }
}
//-----------------------------------------------------------------------
void PURibbonTrail::nodeUpdated(const Node* node)
{
    size_t chainIndex = getChainIndexForNode(node);
    updateTrail(chainIndex, node);
}
//-----------------------------------------------------------------------
void PURibbonTrail::nodeDestroyed(const Node* node)
{
    removeNode(const_cast<Node*>(node));
}
//-----------------------------------------------------------------------
void PURibbonTrail::updateTrail(size_t index, const Node* node)
{
    // Repeat this entire process if chain is stretched beyond its natural length
    bool done = false;
    while (!done)
    {
        // Node has changed somehow, we're only interested in the derived position
        ChainSegment& seg = _chainSegmentList[index];
        Element& headElem = _chainElementList[seg.start + seg.head];
        size_t nextElemIdx = seg.head + 1;
        // wrap
        if (nextElemIdx == _maxElementsPerChain)
            nextElemIdx = 0;
        Element& nextElem = _chainElementList[seg.start + nextElemIdx];

        // Vary the head elem, but bake new version if that exceeds element len
        Vec3 newPos = node->getPosition3D();
        if (_parentNode)
        {
            // Transform position to ourself space
            _parentNode->getWorldToNodeTransform().transformPoint(newPos, &newPos);
        }
        Vec3 diff = newPos - nextElem.position;
        float sqlen = diff.lengthSquared();
        if (sqlen >= _squaredElemLength)
        {
            // Move existing head to mElemLength
            Vec3 scaledDiff = diff * (_elemLength / sqrtf(sqlen));
            headElem.position = nextElem.position + scaledDiff;
            // Add a new element to be the new head
            Element newElem( newPos, _initialWidth[index], 0.0f,
                _initialColor[index], node->getRotationQuat() );
            addChainElement(index, newElem);
            // alter diff to represent new head size
            diff = newPos - headElem.position;
            // check whether another step is needed or not
            if (diff.lengthSquared() <= _squaredElemLength)   
                done = true;

        }
        else
        {
            // Extend existing head
            headElem.position = newPos;
            done = true;
        }

        // Is this segment full?
        if ((seg.tail + 1) % _maxElementsPerChain == seg.head)
        {
            // If so, shrink tail gradually to match head extension
            Element& tailElem = _chainElementList[seg.start + seg.tail];
            size_t preTailIdx;
            if (seg.tail == 0)
                preTailIdx = _maxElementsPerChain - 1;
            else
                preTailIdx = seg.tail - 1;
            Element& preTailElem = _chainElementList[seg.start + preTailIdx];

            // Measure tail diff from pretail to tail
            Vec3 taildiff = tailElem.position - preTailElem.position;
            float taillen = taildiff.length();
            if (taillen > 1e-06)
            {
                float tailsize = _elemLength - diff.length();
                taildiff *= tailsize / taillen;
                tailElem.position = preTailElem.position + taildiff;
            }

        }
    } // end while

    _vertexContentDirty = true;
    // Need to dirty the parent node, but can't do it using needUpdate() here 
    // since we're in the middle of the scene graph update (node listener), 
    // so re-entrant calls don't work. Queue.
    //if (mParentNode)
    //{
    //	Node::queueNeedUpdate(getParentSceneNode());
    //}

}
//-----------------------------------------------------------------------
void PURibbonTrail::timeUpdate(float time)
{
    // Apply all segment effects
    for (size_t s = 0; s < _chainSegmentList.size(); ++s)
    {
        ChainSegment& seg = _chainSegmentList[s];
        if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail)
        {

            for(size_t e = seg.head + 1;; ++e) // until break
            {
                e = e % _maxElementsPerChain;

                Element& elem = _chainElementList[seg.start + e];
                elem.width = elem.width - (time * _deltaWidth[s]);
                elem.width = 0.0f < elem.width? elem.width: 0.0f;
                elem.color = elem.color - (_deltaColor[s] * time);
                elem.color.clamp(Vec4(0.0f, 0.0f, 0.0f, 0.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f));

                if (e == seg.tail)
                    break;

            }
        }

    }

}
//-----------------------------------------------------------------------
void PURibbonTrail::resetTrail(size_t index, const Node* node)
{
    assert(index < _chainCount);

    ChainSegment& seg = _chainSegmentList[index];
    // set up this segment
    seg.head = seg.tail = SEGMENT_EMPTY;
    // Create new element, v coord is always 0.0f
    // need to convert to take parent node's position into account
    Vec3 position = node->getPosition3D();
    if (_parentNode)
    {
        // Transform position to ourself space
        _parentNode->getWorldToNodeTransform().transformPoint(position, &position);
    }
    Element e(position,
        _initialWidth[index], 0.0f, _initialColor[index], node->getRotationQuat());
    // Add the start position
    addChainElement(index, e);
    // Add another on the same spot, this will extend
    addChainElement(index, e);
}
//-----------------------------------------------------------------------
void PURibbonTrail::resetAllTrails()
{
    for (size_t i = 0; i < _nodeList.size(); ++i)
    {
        resetTrail(i, _nodeList[i]);
    }
}

void PURibbonTrail::update( float deltaTime )
{
    if (_needTimeUpdate){
        static float lastUpdateTime = 0.0f;
        if (0.5f < lastUpdateTime){
            timeUpdate(deltaTime);
            lastUpdateTime = 0.0f;
        }
        lastUpdateTime += deltaTime;
    }

    for (auto iter : _nodeToSegMap){
        updateTrail(iter.second, iter.first);
    }
}

NS_CC_END