Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

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
#include "stdafx.h"

#include "config.h"

#include "Headers/ParticleEmitter.h"

#include "Core/Headers/Kernel.h"
#include "Core/Headers/TaskPool.h"
#include "Scenes/Headers/Scene.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Headers/RenderStateBlock.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Core/Time/Headers/ApplicationTimer.h"
#include "Scenes/Headers/SceneState.h"
#include "Geometry/Material/Headers/Material.h"
#include "Rendering/Camera/Headers/Camera.h"
#include "Platform/Video/Buffers/RenderTarget/Headers/RenderTarget.h"
#include "Platform/Video/Buffers/VertexBuffer/GenericBuffer/Headers/GenericVertexData.h"

namespace Divide {
namespace {
    // 3 should always be enough for round-robin GPU updates to avoid stalls:
    // 1 in ram, 1 in driver and 1 in VRAM
    static const U32 g_particleBufferSizeFactor = 3;
    static const U32 g_particleGeometryBuffer = 0;
    static const U32 g_particlePositionBuffer = g_particleGeometryBuffer + 1;
    static const U32 g_particleColourBuffer = g_particlePositionBuffer* + 2;

    static const U64 g_updateInterval = Time::MillisecondsToMicroseconds(33);
};

ParticleEmitter::ParticleEmitter(GFXDevice& context, ResourceCache& parentCache, size_t descriptorHash, const stringImpl& name)
    : SceneNode(parentCache, descriptorHash, name, SceneNodeType::TYPE_PARTICLE_EMITTER),
      _context(context),
      _drawImpostor(false),
      _particleStateBlockHash(0),
      _particleStateBlockHashDepth(0),
      _enabled(false),
      _particleTexture(nullptr),
      _particleShader(nullptr),
      _particleDepthShader(nullptr)
{
    _tempBB.set(-VECTOR3_UNIT, VECTOR3_UNIT);
    for (U8 i = 0; i < s_MaxPlayerBuffers; ++i) {
        for (U8 j = 0; j < to_base(RenderStage::COUNT); ++j) {
            _particleGPUBuffers[i][j] = _context.newGVD(g_particleBufferSizeFactor);
        }
    }

    _buffersDirty.fill(false);
}

ParticleEmitter::~ParticleEmitter()
{ 
    unload(); 
}

GenericVertexData& ParticleEmitter::getDataBuffer(RenderStage stage, PlayerIndex idx) {
    return *_particleGPUBuffers[idx % s_MaxPlayerBuffers][to_U32(stage)];
}

bool ParticleEmitter::initData(const std::shared_ptr<ParticleData>& particleData) {
    // assert if double init!
    DIVIDE_ASSERT(particleData.get() != nullptr, "ParticleEmitter::updateData error: Invalid particle data!");
    _particles = particleData;
    const vectorImpl<vec3<F32>>& geometry = particleData->particleGeometryVertices();
    const vectorImpl<U32>& indices = particleData->particleGeometryIndices();

    for (U8 i = 0; i < s_MaxPlayerBuffers; ++i) {
        for (U8 j = 0; j < to_base(RenderStage::COUNT); ++j) {
            GenericVertexData& buffer = getDataBuffer(static_cast<RenderStage>(j), i);

            buffer.create(3);
            buffer.setBuffer(g_particleGeometryBuffer,
                             to_U32(geometry.size()),
                             sizeof(vec3<F32>),
                             false,
                             (bufferPtr)geometry.data(),
                             BufferUpdateFrequency::ONCE);
            if (!indices.empty()) {
                GenericVertexData::IndexBuffer idxBuff;
                idxBuff.smallIndices = false;
                idxBuff.count = to_U32(indices.size());
                idxBuff.data = (bufferPtr)(indices.data());

                buffer.setIndexBuffer(idxBuff, BufferUpdateFrequency::ONCE);
            }

            AttributeDescriptor& desc = buffer.attribDescriptor(to_base(AttribLocation::VERTEX_POSITION));
            desc.set(g_particleGeometryBuffer, 3, GFXDataFormat::FLOAT_32);
        }
    }

    updateData(particleData);

    // Generate a render state
    RenderStateBlock particleRenderState;
    particleRenderState.setCullMode(CullMode::NONE);
    _particleStateBlockHash = particleRenderState.getHash();

    particleRenderState.setZFunc(ComparisonFunction::LESS);
    _particleStateBlockHashDepth = particleRenderState.getHash();

    bool useTexture = _particleTexture != nullptr;
    ResourceDescriptor particleShaderDescriptor(useTexture ? "particles.WithTexture" : "particles.NoTexture");
    if (useTexture){
        particleShaderDescriptor.setPropertyList("HAS_TEXTURE");
    }
    _particleShader = CreateResource<ShaderProgram>(_parentCache, particleShaderDescriptor);

    ResourceDescriptor particleDepthShaderDescriptor("particles.Depth");
    _particleDepthShader = CreateResource<ShaderProgram>(_parentCache, particleDepthShaderDescriptor);

    if (_particleShader != nullptr) {
        Material_ptr mat = CreateResource<Material>(_parentCache, ResourceDescriptor("Material_particles"));

        mat->setShaderProgram(_particleShader);
        mat->setShaderProgram(_particleDepthShader, RenderStage::SHADOW);
        mat->setRenderStateBlock(_particleStateBlockHash, RenderPassType::COLOUR_PASS);
        mat->setRenderStateBlock(_particleStateBlockHashDepth, RenderPassType::DEPTH_PASS);
        setMaterialTpl(mat);

        return true;
    }

    return false;
}

bool ParticleEmitter::updateData(const std::shared_ptr<ParticleData>& particleData) {
    static const U32 positionAttribLocation = 13;
    static const U32 colourAttribLocation = to_base(AttribLocation::VERTEX_COLOR);

    U32 particleCount = _particles->totalCount();

    for (U8 i = 0; i < s_MaxPlayerBuffers; ++i) {
        for (U8 j = 0; j < to_base(RenderStage::COUNT); ++j) {
            GenericVertexData& buffer = getDataBuffer(static_cast<RenderStage>(j), i);

            buffer.setBuffer(g_particlePositionBuffer,
                             particleCount,
                             sizeof(vec4<F32>),
                             true,
                             NULL,
                             BufferUpdateFrequency::OFTEN);
            buffer.setBuffer(g_particleColourBuffer,
                             particleCount,
                             sizeof(UColour),
                             true,
                             NULL,
                             BufferUpdateFrequency::OFTEN);

            buffer.attribDescriptor(positionAttribLocation).set(g_particlePositionBuffer,
                                                                4,
                                                                GFXDataFormat::FLOAT_32,
                                                                false,
                                                                0,
                                                                1);

            buffer.attribDescriptor(colourAttribLocation).set(g_particleColourBuffer,
                                                              4,
                                                              GFXDataFormat::UNSIGNED_BYTE,
                                                              true,
                                                              0,
                                                              1);
        }
    }

    for (U32 i = 0; i < particleCount; ++i) {
        // Distance to camera (squared)
        _particles->_misc[i].w = -1.0f;
    }

    if (!_particles->_textureFileName.empty()) {
        SamplerDescriptor textureSampler;
        textureSampler.toggleSRGBColourSpace(true);

        TextureDescriptor textureDescriptor(TextureType::TEXTURE_2D);
        textureDescriptor.setSampler(textureSampler);

        ResourceDescriptor texture(_particles->_textureFileName);
        texture.setPropertyDescriptor(textureDescriptor);

        _particleTexture = CreateResource<Texture>(_parentCache, texture);
    }

    return true;
}

bool ParticleEmitter::unload() {
    if (getState() != ResourceState::RES_LOADED &&
        getState() != ResourceState::RES_LOADING) {
        return true;
    }
    
    _particles.reset();

    return SceneNode::unload();
}

void ParticleEmitter::postLoad(SceneGraphNode& sgn) {
    if (_particleTexture) {
        sgn.get<RenderingComponent>()->registerTextureDependency(_particleTexture->getData(),
                                                                 to_U8(ShaderProgram::TextureUsage::UNIT0));
    }

    setFlag(UpdateFlag::BOUNDS_CHANGED);

    sgn.get<BoundsComponent>()->lockBBTransforms(true);

    SceneNode::postLoad(sgn);
}

void ParticleEmitter::buildDrawCommands(SceneGraphNode& sgn,
                                        const RenderStagePass& renderStagePass,
                                        RenderPackage& pkgInOut) {

    U32 indexCount = to_U32(_particles->particleGeometryIndices().size());
    if (indexCount == 0) {
        indexCount = to_U32(_particles->particleGeometryVertices().size());
    }

    GenericDrawCommand cmd(_particles->particleGeometryType(), 0, indexCount);
    GFX::DrawCommand drawCommand;
    drawCommand._drawCommands.push_back(cmd);
    pkgInOut.addDrawCommand(drawCommand);

    const Pipeline* pipeline = pkgInOut.pipeline(0);
    PipelineDescriptor pipeDesc = pipeline->descriptor();

    pipeDesc._stateHash = (_context.isDepthStage(renderStagePass) ? _particleStateBlockHashDepth
                                                                  : _particleStateBlockHash); 
    pkgInOut.pipeline(0, _context.newPipeline(pipeDesc));
    

    SceneNode::buildDrawCommands(sgn, renderStagePass, pkgInOut);
}

void ParticleEmitter::prepareForRender(const RenderStagePass& renderStagePass, const Camera& crtCamera) {
    if (renderStagePass.pass() != RenderPassType::DEPTH_PASS) {
        return;
    }

    const vec3<F32>& eyePos = crtCamera.getEye();
    U32 aliveCount = getAliveParticleCount();

    vectorImplBest<vec4<F32>>& misc = _particles->_misc;
    vectorImplBest<vec4<F32>>& pos = _particles->_position;

    auto updateDistToCamera = [&eyePos, &misc, &pos](const Task& parent, U32 start, U32 end) {
        for (U32 i = start; i < end; ++i) {
            misc[i].w = pos[i].xyz().distanceSquared(eyePos);
        }
    };

    parallel_for(_context.parent().platformContext(), updateDistToCamera, aliveCount, 1000);

    _bufferUpdate.emplace_back(CreateTask(_context.parent().platformContext(),
        [this, aliveCount, &renderStagePass](const Task& parentTask) {
        // invalidateCache means that the existing particle data is no longer partially sorted
        _particles->sort(true);
        _buffersDirty[to_U32(renderStagePass.stage())] = true;
    }));

    _bufferUpdate.back().startTask(Task::TaskPriority::HIGH);
}

/// The onRender call will emit particles
bool ParticleEmitter::onRender(SceneGraphNode& sgn,
                               const SceneRenderState& sceneRenderState,
                               const RenderStagePass& renderStagePass) {
    if ( _enabled &&  getAliveParticleCount() > 0) {
        for (TaskHandle& task : _bufferUpdate) {
            task.wait();
        }

        _bufferUpdate.clear();

        if (renderStagePass.pass() != RenderPassType::DEPTH_PASS && _buffersDirty[to_U32(renderStagePass.stage())]) {
            GenericVertexData& buffer = getDataBuffer(renderStagePass.stage(), sceneRenderState.playerPass());
            buffer.updateBuffer(g_particlePositionBuffer, to_U32(_particles->_renderingPositions.size()), 0, _particles->_renderingPositions.data());
            buffer.updateBuffer(g_particleColourBuffer, to_U32(_particles->_renderingColours.size()), 0, _particles->_renderingColours.data());
            buffer.incQueue();
            _buffersDirty[to_U32(renderStagePass.stage())] = false;
        }

        RenderingComponent* renderComp = sgn.get<RenderingComponent>();
        RenderPackage& pkg = renderComp->getDrawPackage(renderStagePass);

        GenericDrawCommand cmd = pkg.drawCommand(0, 0);
        cmd.cmd().primCount = to_U32(_particles->_renderingPositions.size());
        cmd.sourceBuffer(&getDataBuffer(renderStagePass.stage(), sceneRenderState.playerPass()));
        pkg.drawCommand(0, 0, cmd);

        prepareForRender(renderStagePass, *sceneRenderState.parentScene().playerCamera());

        return SceneNode::onRender(sgn, sceneRenderState, renderStagePass);
    }

    return false;
}


/// Pre-process particles
void ParticleEmitter::sceneUpdate(const U64 deltaTimeUS,
                                  SceneGraphNode& sgn,
                                  SceneState& sceneState) {

    static const U32 s_particlesPerThread = 1024;

    if (_enabled) {
        U32 aliveCount = getAliveParticleCount();
        renderState().setDrawState(aliveCount > 0);

        TransformComponent* transform = sgn.get<TransformComponent>();

        const vec3<F32>& pos = transform->getPosition();
        const Quaternion<F32>& rot = transform->getOrientation();

        F32 averageEmitRate = 0;
        for (std::shared_ptr<ParticleSource>& source : _sources) {
            source->updateTransform(pos, rot);
            source->emit(g_updateInterval, _particles);
            averageEmitRate += source->emitRate();
        }
        averageEmitRate /= _sources.size();

        aliveCount = getAliveParticleCount();

        auto updateSize = [this](const Task& parentTask, U32 start, U32 end) {
            for (U32 i = start; i < end; ++i) {
                _particles->_position[i].w = _particles->_misc[i].z;
                _particles->_acceleration[i].set(0.0f);
            }
        };

        parallel_for(_context.parent().platformContext(), updateSize, aliveCount, s_particlesPerThread, Task::TaskPriority::HIGH);

        ParticleData& data = *_particles;
        for (std::shared_ptr<ParticleUpdater>& up : _updaters) {
            up->update(g_updateInterval, data);
        }

        for (TaskHandle& task : _bbUpdate) {
            task.wait();
        }
        _bufferUpdate.clear();
        _bbUpdate.emplace_back(CreateTask(_context.parent().platformContext(), 
              [this, aliveCount, averageEmitRate](const Task& parentTask)
        {
            _tempBB.reset();
            for (U32 i = 0; i < aliveCount; i += to_U32(averageEmitRate) / 4) {
                _tempBB.add(_particles->_position[i]);
            }
            setFlag(UpdateFlag::BOUNDS_CHANGED);
        }));
        _bbUpdate.back().startTask(Task::TaskPriority::HIGH);
    }

    SceneNode::sceneUpdate(deltaTimeUS, sgn, sceneState);
}

U32 ParticleEmitter::getAliveParticleCount() const {
    if (!_particles.get()) {
        return 0;
    }
    return _particles->aliveCount();
}

void ParticleEmitter::updateBoundsInternal(SceneGraphNode& sgn) {
    for (TaskHandle& task : _bbUpdate) {
        task.wait();
    }
    _bufferUpdate.clear();

    U32 aliveCount = getAliveParticleCount();
    if (aliveCount > 2) {
        _boundingBox.set(_tempBB);
    } else {
        _boundingBox.set(-VECTOR3_UNIT, VECTOR3_UNIT);
    }

    SceneNode::updateBoundsInternal(sgn);
}

};

Commits for Divide-Framework/trunk/Source Code/Dynamics/Entities/Particles/ParticleEmitter.cpp

Diff revisions: vs.
Revision Author Commited Message
1004 Diff Diff IonutCava picture IonutCava Wed 20 Dec, 2017 17:16:32 +0000

[Ionut]
- More GUI cleanup (added multiple GUIButton events)
- Typedef vec4<U8> and vec4<F32> to UColour and FColour respectively for easier to read code.

1001 Diff Diff IonutCava picture IonutCava Sun 17 Dec, 2017 20:55:45 +0000

[Ionut]
- Fix IMGUI rendering with GenericVertexData
- Fix persistent buffer locking issue (lock after every draw call, even if it overlaps)

999 Diff Diff IonutCava picture IonutCava Thu 14 Dec, 2017 00:27:08 +0000

[Ionut]
- Simply GenericVertexData class a lot
- Move IMGUI to GenericVertexData based rendering (still has rendering issues)
- Fix some crash issues on shutdown if the rendering API failed to initialize
- Disable some GL debugging flags as they seem to cause issues with the new 17.12.1 AMD driver

996 Diff Diff IonutCava picture IonutCava Tue 12 Dec, 2017 17:16:54 +0000

[Ionut]
- Update and improve SGN creation and destruction
- Fix cleanup issues
- Fix GPU object memory leaks
- Fix duplicate GUID values being generated
- Misc cleanups and optimizations

992 Diff Diff IonutCava picture IonutCava Thu 07 Dec, 2017 18:01:51 +0000

[Ionut]
- Split PhysicsComponent into 2, ECS-based, components: TransformComponent and RigidBodyComponent
UNTESTED

968 Diff Diff IonutCava picture IonutCava Tue 07 Nov, 2017 17:32:31 +0000

[Ionut]
- Consistent naming between timing variables

957 Diff Diff IonutCava picture IonutCava Tue 31 Oct, 2017 17:15:51 +0000

[Ionut]
- Some SGN node search refactoring
- typedef PlayerIndex

953 Diff Diff IonutCava picture IonutCava Sat 28 Oct, 2017 21:57:10 +0000

[Ionut]
- Fix blinking issue by caching and hashing pipelines to that we don’t overwrite pipelines used by other elements

950 Diff Diff IonutCava picture IonutCava Sun 22 Oct, 2017 22:25:05 +0000

[Ionut]
- Revamp camera management
- More work on improving the command buffer system:
— Performance tweaks
— Validation
— Debug features
- Some code cleanup for Object3D stuff (preRender/onRender changes)

Still haven’t fixed random flashing issue

949 IonutCava picture IonutCava Thu 19 Oct, 2017 21:48:37 +0000

[Ionut]
- More command buffer refactoring