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
#include "Headers/Water.h"

#include "Core/Headers/ParamHandler.h"
#include "Core/Math/Headers/Transform.h"
#include "Managers/Headers/SceneManager.h"
#include "Platform/Video/Headers/RenderStateBlock.h"
#include "Geometry/Material/Headers/Material.h"

namespace Divide {

WaterPlane::WaterPlane()
    : SceneNode(SceneNodeType::TYPE_WATER),
      Reflector(TYPE_WATER_SURFACE, vec2<U16>(1024, 1024)),
      _plane(nullptr),
      _waterLevel(0),
      _waterDepth(0),
      _refractionPlaneID(ClipPlaneIndex::ClipPlaneIndex_PLACEHOLDER),
      _reflectionPlaneID(ClipPlaneIndex::ClipPlaneIndex_PLACEHOLDER),
      _reflectionRendering(false),
      _refractionRendering(false),
      _refractionTexture(nullptr),
      _dirty(true),
      _paramsDirty(true),
      _cameraUnderWater(false),
      _cameraMgr(Application::getInstance().getKernel().getCameraMgr()) {
    // Set water plane to be single-sided
    P32 quadMask;
    quadMask.i = 0;
    quadMask.b.b0 = true;

    setParams(50.0f, vec2<F32>(10.0f, 10.0f), vec2<F32>(0.1f, 0.1f), 0.34f);

    ResourceDescriptor waterPlane("waterPlane");
    waterPlane.setFlag(true);  // No default material
    waterPlane.setBoolMask(quadMask);
    _plane = CreateResource<Quad3D>(waterPlane);
    _farPlane = 2.0f *
                GET_ACTIVE_SCENE()
                    ->state()
                    .getRenderState()
                    .getCameraConst()
                    .getZPlanes()
                    .y;
    _plane->setCorner(Quad3D::TOP_LEFT,
                      vec3<F32>(-_farPlane * 1.5f, 0, -_farPlane * 1.5f));
    _plane->setCorner(Quad3D::TOP_RIGHT,
                      vec3<F32>(_farPlane * 1.5f, 0, -_farPlane * 1.5f));
    _plane->setCorner(Quad3D::BOTTOM_LEFT,
                      vec3<F32>(-_farPlane * 1.5f, 0, _farPlane * 1.5f));
    _plane->setCorner(Quad3D::BOTTOM_RIGHT,
                      vec3<F32>(_farPlane * 1.5f, 0, _farPlane * 1.5f));
    _plane->setNormal(Quad3D::CORNER_ALL, WORLD_Y_AXIS);
    _plane->renderState().setDrawState(false);
    // The water doesn't cast shadows, doesn't need ambient occlusion and
    // doesn't have real "depth"
    renderState().addToDrawExclusionMask(RenderStage::SHADOW_STAGE);
    Console::printfn(Locale::get("REFRACTION_INIT_FB"), _resolution.x,
                     _resolution.y);
    SamplerDescriptor refractionSampler;
    refractionSampler.setWrapMode(TextureWrap::TEXTURE_CLAMP_TO_EDGE);
    refractionSampler.toggleMipMaps(false);
    // Less precision for reflections
    TextureDescriptor refractionDescriptor(TextureType::TEXTURE_2D,
                                           GFXImageFormat::RGBA8,
                                           GFXDataFormat::UNSIGNED_BYTE);  
    refractionDescriptor.setSampler(refractionSampler);

    _refractionTexture = GFX_DEVICE.newFB();
    _refractionTexture->AddAttachment(refractionDescriptor,
                                      TextureDescriptor::Color0);
    _refractionTexture->toggleDepthBuffer(true);
    _refractionTexture->Create(_resolution.x, _resolution.y);
}

void WaterPlane::postLoad(SceneGraphNode& sgn) {
    sgn.addNode(_plane);
    SceneNode::postLoad(sgn);
}

bool WaterPlane::computeBoundingBox(SceneGraphNode& sgn) {
    BoundingBox& bb = sgn.getBoundingBox();

    if (bb.isComputed()) {
        return true;
    }
    SceneGraphNode* planeSGN = sgn.getChildren()[0];
    _waterLevel = GET_ACTIVE_SCENE()->state().getWaterLevel();
    _waterDepth = GET_ACTIVE_SCENE()->state().getWaterDepth();
    planeSGN->getComponent<PhysicsComponent>()->setPositionY(_waterLevel);
    bb.set(vec3<F32>(-_farPlane, _waterLevel - _waterDepth, -_farPlane),
           vec3<F32>(_farPlane, _waterLevel, _farPlane));
    planeSGN->getBoundingBox().Add(bb);
    Console::printfn(Locale::get("WATER_CREATE_DETAILS_1"), bb.getMax().y);
    Console::printfn(Locale::get("WATER_CREATE_DETAILS_2"), bb.getMin().y);
    _dirty = true;
    return SceneNode::computeBoundingBox(sgn);
}

bool WaterPlane::unload() {
    bool state = false;
    state = SceneNode::unload();
    return state;
}

void WaterPlane::setParams(F32 shininess, const vec2<F32>& noiseTile,
                           const vec2<F32>& noiseFactor, F32 transparency) {
    _shininess = shininess;
    _noiseTile = noiseTile;
    _noiseFactor = noiseFactor;
    _transparency = transparency;
    _paramsDirty = true;
}

void WaterPlane::sceneUpdate(const U64 deltaTime, SceneGraphNode& sgn,
                             SceneState& sceneState) {
    _cameraUnderWater =
        isPointUnderWater(sceneState.getRenderState().getCamera().getEye());
    if (_dirty) {
        sgn.getBoundingSphere().fromBoundingBox(sgn.getBoundingBoxConst());
        _dirty = false;
    }
    if (_paramsDirty) {
        RenderingComponent* rComp = sgn.getComponent<RenderingComponent>();
        ShaderProgram* shader = rComp->getMaterialInstance()
                                    ->getShaderInfo(RenderStage::FINAL_STAGE)
                                    .getProgram();
        shader->Uniform("_waterShininess", _shininess);
        shader->Uniform("_noiseFactor", _noiseFactor);
        shader->Uniform("_noiseTile", _noiseTile);
        shader->Uniform("_transparencyBias", _transparency);
        _paramsDirty = false;
    }
}

bool WaterPlane::onDraw(SceneGraphNode& sgn,
                        const RenderStage& currentStage) {
    const Quaternion<F32>& orientation =
        sgn.getComponent<PhysicsComponent>()->getOrientation();
    if (!_orientation.compare(orientation)) {
        _orientation.set(orientation);
        updatePlaneEquation();
    }
    return true;
}

void WaterPlane::postDraw(SceneGraphNode& sgn,
                          const RenderStage& currentStage) {}

void WaterPlane::getDrawCommands(
    SceneGraphNode& sgn, const RenderStage& currentRenderStage,
    SceneRenderState& sceneRenderState,
    vectorImpl<GenericDrawCommand>& drawCommandsOut) {
    bool depthPass = GFX_DEVICE.isCurrentRenderStage(RenderStage::DEPTH_STAGE);
    RenderingComponent* const renderable =
        sgn.getComponent<RenderingComponent>();
    assert(renderable != nullptr);

    ShaderProgram* drawShader =
        renderable->getDrawShader(depthPass ? RenderStage::Z_PRE_PASS_STAGE : RenderStage::FINAL_STAGE);
    drawShader->Uniform("underwater", _cameraUnderWater);
    GenericDrawCommand cmd(PrimitiveType::TRIANGLE_STRIP, 0, 0);
    cmd.renderWireframe(renderable->renderWireframe());
    cmd.stateHash(
        renderable->getMaterialInstance()->getRenderStateBlock(RenderStage::FINAL_STAGE));
    cmd.shaderProgram(drawShader);
    cmd.sourceBuffer(_plane->getGeometryVB());
    drawCommandsOut.push_back(cmd);
}

void WaterPlane::render(SceneGraphNode& sgn,
                        const SceneRenderState& sceneRenderState,
                        const RenderStage& currentRenderStage) {
    if (!_plane->onDraw(currentRenderStage)) {
        return;
    }
    if (!GFX_DEVICE.isCurrentRenderStage(RenderStage::DEPTH_STAGE)) {
        _reflectedTexture->Bind(1);
        if (!_cameraUnderWater) {
            _refractionTexture->Bind(2);
        }
    }

    GFX_DEVICE.submitRenderCommand(
        sgn.getComponent<RenderingComponent>()->getDrawCommands());
}

bool WaterPlane::getDrawState(const RenderStage& currentStage) {
    // Wait for the Reflector to update
    if (!_createdFB) {
        return false;
    }

    // Make sure we are not drawing our self unless this is desired
    if ((currentStage == RenderStage::REFLECTION_STAGE || _reflectionRendering ||
         _refractionRendering) &&
        !_updateSelf) {
        return false;
    }

    // Else, process normal exclusion
    return SceneNode::getDrawState(currentStage);
}

/// update water refraction
void WaterPlane::updateRefraction() {
    if (_cameraUnderWater) {
        return;
    }
    // Early out check for render callback
    if (!_renderCallback) {
        return;
    }
    _refractionRendering = true;
    // If we are above water, process the plane's reflection. If we are below,
    // we render the scene normally
    RenderStage prevRenderStage = GFX_DEVICE.setRenderStage(RenderStage::FINAL_STAGE);
    GFX_DEVICE.toggleClipPlane(_refractionPlaneID, true);
    _cameraMgr.getActiveCamera()->renderLookAt();
    // bind the refractive texture
    _refractionTexture->Begin(Framebuffer::defaultPolicy());
    // render to the reflective texture
    _refractionCallback();
    _refractionTexture->End();

    GFX_DEVICE.toggleClipPlane(_refractionPlaneID, false);
    GFX_DEVICE.setRenderStage(prevRenderStage);

    _refractionRendering = false;
}

/// Update water reflections
void WaterPlane::updateReflection() {
    // Early out check for render callback
    if (_renderCallback) {
        // ToDo: this will cause problems later with multiple reflectors. Fix
        // it! -Ionut
        _reflectionRendering = true;

        RenderStage prevRenderStage = GFX_DEVICE.setRenderStage(
            _cameraUnderWater ? RenderStage::FINAL_STAGE : RenderStage::REFLECTION_STAGE);
        GFX_DEVICE.toggleClipPlane(_reflectionPlaneID, true);

        _cameraUnderWater ? _cameraMgr.getActiveCamera()->renderLookAt()
                          : _cameraMgr.getActiveCamera()->renderLookAtReflected(
                                getReflectionPlane());

        _reflectedTexture->Begin(Framebuffer::defaultPolicy());
        _renderCallback();  //< render to the reflective texture
        _reflectedTexture->End();

        GFX_DEVICE.toggleClipPlane(_reflectionPlaneID, false);
        GFX_DEVICE.setRenderStage(prevRenderStage);

        _reflectionRendering = false;
    }
    updateRefraction();
}

void WaterPlane::updatePlaneEquation() {
    vec3<F32> reflectionNormal(_orientation * WORLD_Y_AXIS);
    reflectionNormal.normalize();
    vec3<F32> refractionNormal(_orientation * WORLD_Y_NEG_AXIS);
    refractionNormal.normalize();
    _reflectionPlane.set(reflectionNormal, -_waterLevel);
    _reflectionPlane.active(false);
    _refractionPlane.set(refractionNormal, -_waterLevel);
    _refractionPlane.active(false);
    _reflectionPlaneID = ClipPlaneIndex::CLIP_PLANE_0;
    _refractionPlaneID = ClipPlaneIndex::CLIP_PLANE_1;

    GFX_DEVICE.setClipPlane(_reflectionPlaneID, _reflectionPlane);
    GFX_DEVICE.setClipPlane(_refractionPlaneID, _refractionPlane);

    _dirty = true;
}

void WaterPlane::previewReflection() {
#ifdef _DEBUG
    if (_previewReflection) {
        F32 height = _resolution.y * 0.333f;
        _refractionTexture->Bind();
        vec4<I32> viewport(
            _resolution.x * 0.333f,
            Application::getInstance().getResolution().y - height,
            _resolution.x * 0.666f, height);
        GFX_DEVICE.renderInViewport(
            viewport,
            DELEGATE_BIND(
                (void (GFXDevice::*)(U32, size_t, ShaderProgram* const)) &
                    GFXDevice::drawPoints,
                &GFX_DEVICE, 1, GFX_DEVICE.getDefaultStateBlock(true),
                _previewReflectionShader));
    }
#endif
    Reflector::previewReflection();
}
};

Commits for Divide-Framework/trunk/Source Code/Environment/Water/Water.cpp

Diff revisions: vs.
Revision Author Commited Message
365 Diff Diff IonutCava picture IonutCava Sun 08 Mar, 2015 21:26:10 +0000

[Ionut]
- More enum-related type safety changes

354 Diff Diff IonutCava picture IonutCava Fri 20 Feb, 2015 17:17:37 +0000

[Ionut]
- Replaced GLEW with glbinding (requires a CEGUI recompile. It currently crashes)
- Replaced most “SceneGraphNode* const sgn” expressions with "SceneGraphNode& sgn"
- Replaced some pointers to kernel to references to kernel
- Fixed compilation issues with EASTL
- Removed NPOT -> POT texture conversion code. Modern GPUs handle NPOT textures perfectly fine

350 Diff Diff IonutCava picture IonutCava Tue 10 Feb, 2015 16:25:39 +0000

[Ionut]
- Simplified some Util-namespace level functions by using STL algorithms where possible
- Formatted the entire codebase using clang-format with the following style: "{BasedOnStyle: Google, IndentWidth: 4}"
- Attempted to make ProfileTimer thread-safe (temp fix until std::chrono works properly in Visual Studio)

349 Diff Diff IonutCava picture IonutCava Fri 06 Feb, 2015 17:11:39 +0000

[Ionut]
- More raw pointer replacements
- Removed some redundant parameters to a few scene and application functions

343 Diff Diff IonutCava picture IonutCava Thu 15 Jan, 2015 17:30:12 +0000

[Ionut]
- Refactored 2 singletons into static classes (Console and TerrainLoader)
- Changed some C-casts to static_casts
- Updated copyright notices

337 Diff Diff IonutCava picture IonutCava Wed 17 Dec, 2014 17:25:16 +0000

[Ionut]
- Replaced all tabs with 4 spaces (some spacing may be off now. no way to check all the files.)
- Moved implementation details for ParamHandler, BoundingBox, BoundingSphere and ProfileTimer to proper .inl and .cpp files. (more to follow)
- Update all forward declared enums with the required storage type (as requested by the C++11 standard)

334 Diff Diff IonutCava picture IonutCava Wed 10 Dec, 2014 17:21:22 +0000

[Ionut]
- Reorganized the Hardware project and renamed to "Platform"
- Reorganized the Server project

331 Diff Diff IonutCava picture IonutCava Sat 06 Dec, 2014 20:53:45 +0000

[Ionut]
- Limited line length to 132 characters to improve readability and diff-comparisons
- Refactored memory allocation/deallocation functions
- Fixed a few compatibility issues with HashMap.h
- Fixed a bug in GPU Skinning shaders (cast a float to int)

330 Diff Diff IonutCava picture IonutCava Fri 10 Oct, 2014 17:19:11 +0000

[Ionut]
- New rendering algorithm :
— Perform second pass for visible nodes gathering all render commands and uploading them to an indirect draw buffer
— Render geometry with indirect draw commands
— Removed per-node range binding of the node buffer. Instead, bind the entire buffer once and index data in shaders
— Use “baseInstance” parameter from IndirectDrawCommand as a node buffer index
— Prefer DSA extensions for updating buffer data where applicable
- Moved all rendering specific code from SceneGraphNode to a new RenderingComponent
- Optimized “toString” utility function

328 IonutCava picture IonutCava Sat 04 Oct, 2014 18:03:36 +0000

[Ionut]
- Added per SceneGraphNode material instances. (Cloned from the SceneNode’s material)
- Improved shader loading for materials