Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add FluidSimulation2D example #71

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ option(WITH_BOX2D_EXAMPLE "Build Box2D integration example" OFF)
option(WITH_BULLET_EXAMPLE "Build Bullet integration example (requires the BulletIntegration library)" OFF)
cmake_dependent_option(WITH_CUBEMAP_EXAMPLE "Build CubeMap example (requires some JPEG importer plugin)" OFF "NOT MAGNUM_TARGET_GLES" OFF)
option(WITH_DART_EXAMPLE "Build DART integration example (requires the DartIntegration library)" OFF)
option(WITH_FLUIDSIMULATION2D_EXAMPLE "Build 2D Fluid Simulation example (requires the ImGui integration)" OFF)
option(WITH_FLUIDSIMULATION3D_EXAMPLE "Build 3D Fluid Simulation example (requires the ImGui integration)" OFF)
option(WITH_IMGUI_EXAMPLE "Build ImGui example" OFF)
option(WITH_LEAPMOTION_EXAMPLE "Build LeapMotion example" OFF)
Expand Down
4 changes: 4 additions & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ if(WITH_DART_EXAMPLE)
add_subdirectory(dart)
endif()

if(WITH_FLUIDSIMULATION2D_EXAMPLE)
add_subdirectory(fluidsimulation2d)
endif()

if(WITH_FLUIDSIMULATION3D_EXAMPLE)
add_subdirectory(fluidsimulation3d)
endif()
Expand Down
87 changes: 87 additions & 0 deletions src/fluidsimulation2d/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#
# This file is part of Magnum.
#
# Original authors — credit is appreciated but not required:
#
# 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
# Vladimír Vondruš <[email protected]>
# 2019 — Nghia Truong <[email protected]>
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or distribute
# this software, either in source code form or as a compiled binary, for any
# purpose, commercial or non-commercial, and by any means.
#
# In jurisdictions that recognize copyright laws, the author or authors of
# this software dedicate any and all copyright interest in the software to
# the public domain. We make this dedication for the benefit of the public
# at large and to the detriment of our heirs and successors. We intend this
# dedication to be an overt act of relinquishment in perpetuity of all
# present and future rights to this software under copyright law.
#
# 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 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.
#

cmake_minimum_required(VERSION 3.4)
project(magnum-fluidsimulation2d)

# Add module path in case this is project root
if(PROJECT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/../../modules/" ${CMAKE_MODULE_PATH})
endif()

find_package(Corrade REQUIRED Main)
find_package(Magnum REQUIRED
GL
MeshTools
Primitives
SceneGraph
Shaders
Sdl2Application)
find_package(MagnumIntegration REQUIRED ImGui)

set_directory_properties(PROPERTIES CORRADE_USE_PEDANTIC_FLAGS ON)

corrade_add_resource(FluidSimulation2D_RESOURCES resources.conf)

add_executable(magnum-fluidsimulation2d WIN32
FluidSimulation2DExample.cpp
DataStructures/Array2X.h
DataStructures/MathHelpers.h
DataStructures/PCGSolver.h
DataStructures/SDFObject.h
DataStructures/SparseMatrix.h
DrawableObjects/FlatShadeObject2D.h
DrawableObjects/ParticleGroup2D.h
DrawableObjects/ParticleGroup2D.cpp
DrawableObjects/WireframeObject2D.h
FluidSolver/SolverData.h
FluidSolver/ApicSolver2D.h
FluidSolver/ApicSolver2D.cpp
Shaders/ParticleSphereShader2D.h
Shaders/ParticleSphereShader2D.cpp
${FluidSimulation2D_RESOURCES})
target_link_libraries(magnum-fluidsimulation2d PRIVATE
Corrade::Main
Magnum::Application
Magnum::GL
Magnum::Magnum
Magnum::MeshTools
Magnum::Primitives
Magnum::SceneGraph
Magnum::Shaders
MagnumIntegration::ImGui)
target_include_directories(magnum-fluidsimulation2d PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR})

install(TARGETS magnum-fluidsimulation2d DESTINATION ${MAGNUM_BINARY_INSTALL_DIR})

# Make the executable a default target to build & run in Visual Studio
set_property(DIRECTORY ${PROJECT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT magnum-fluidsimulation2d)
185 changes: 185 additions & 0 deletions src/fluidsimulation2d/DataStructures/Array2X.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
#ifndef Magnum_Examples_FluidSimulation2D_Array2X_h
#define Magnum_Examples_FluidSimulation2D_Array2X_h
/*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
Vladimír Vondruš <[email protected]>
2019 — Nghia Truong <[email protected]>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
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 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 <cassert>
#include <vector>
#include <Corrade/Utility/Debug.h>
#include <Magnum/Math/Vector2.h>

#include "MathHelpers.h"

namespace Magnum { namespace Examples {
template<class T>
class Array2X {
Copy link
Contributor Author

@ttnghia ttnghia Nov 17, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really want to make Array1X/2X/3X be part of magnum. Currently, Array1D/2D/3D in mangum only have fixed size (1-2-3 elements). Dynamic size arrays are more useful.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(I finally got around to merge this, hopefully finishing later today -- sorry for the long and demotivating delay.)

Re Array -- I'd say there's two different use cases and I don't think combining those two (like Eigen does) makes sense. The matrices and vectors in Math have compile-time size (2, 4, 17, ... elements) and are suited for basic geometry work where you don't want any allocations or uncontrolled memory access patterns, but definitely not for anything huge -- you don't want to use algorithms that perform well on a 4x4 matrix on a 100-element matrix, and vice versa.

For dynamic multidimensional arrays there's StridedArrayView and the way forward I see is providing a set of algorithms operating on it. Very few things are already in Math/FunctionsBatch.h, and the MeshTools provides an increasing set of mesh-oriented algos operating on top of this data structure. And with mosra/magnum#306 I'm aiming to have all those SIMD-accelerated.

The most time-consuming about all this is not the code itself, but ensuring it's all well-documented, thoroughly tested and with a consistent interface that isn't annoying to use :)

public:
Array2X() = default;
Array2X(std::size_t nx, std::size_t ny) : _size{nx, ny}, _data(nx * ny) {}
Array2X(std::size_t nx, std::size_t ny, const T& value) : _size{nx, ny}, _data(nx * ny, value) {}

Array2X<T>& operator=(const Array2X<T>& other) {
if(other.size_x() != size_x() || other.size_y() != size_y()) {
Fatal{} << "Copy array with different size!";
}
std::memcpy(data(), other.data(), count() * sizeof(T));
return *this;
}

/******************************* Accessors *******************************/
template<class IntType>
const T& operator()(IntType i, IntType j) const {
assert(i >= 0
&& j >= 0
&& static_cast<std::size_t>(i) < _size[0]
&& static_cast<std::size_t>(j) < _size[1]);
return _data[i + _size[0] * j];
}

template<class IntType>
T& operator()(IntType i, IntType j) {
assert(i >= 0
&& j >= 0
&& static_cast<std::size_t>(i) < _size[0]
&& static_cast<std::size_t>(j) < _size[1]);
return _data[i + _size[0] * j];
}

template<class IntType>
const T& operator()(const Math::Vector2<IntType>& coord) const { return (*this)(coord[0], coord[1]); }

template<class IntType>
T& operator()(const Math::Vector2<IntType>& coord) { return (*this)(coord[0], coord[1]); }

const T* data() const { return _data.data(); }
T* data() { return _data.data(); }

std::size_t size_x() const { return _size[0]; }
std::size_t size_y() const { return _size[1]; }
std::size_t count() const { return _data.size(); }

/******************************* Modifiers *******************************/
void assign(const T& value) { _data.assign(_data.size(), value); }
void set_zero() { _data.assign(_data.size(), T(0)); }

template<class IntType>
void resize(IntType nx, IntType ny) {
_size[0] = static_cast<std::size_t>(nx);
_size[1] = static_cast<std::size_t>(ny);
_data.resize(_size[0] * _size[1]);
}

template<class IntType>
void resize(IntType nx, IntType ny, const T& value) {
_size = { static_cast<std::size_t>(nx), static_cast<std::size_t>(ny) };
_data.resize(_size[0] * _size[1], value);
}

void swapContent(Array2X<T>& other) {
/* Only allow to swap content of array having the same sizes */
if(other.size_x() != size_x() || other.size_y() != size_y()) {
Fatal{} << "Swap content of arrays having different sizes!";
}
_data.swap(other._data);
}

/*************************** Data manimupations ***************************/
template<class Function>
void loop1D(Function&& func) const {
for(std::size_t i = 0, iend = count(); i < iend; ++i) {
func(i);
}
}

template<class Function>
void loop2D(Function&& func) const {
for(std::size_t j = 0; j < size_y(); ++j) {
for(std::size_t i = 0; i < size_x(); ++i) {
func(i, j);
}
}
}

T interpolateValue(const Math::Vector2<T>& point) const {
Int i, j;
T fx, fy;
barycentric(point[0], i, fx, 0, Int(size_x()));
barycentric(point[1], j, fy, 0, Int(size_y()));
T v00 = (*this)(i, j);
T v10 = (*this)(i + 1, j);
T v01 = (*this)(i, j + 1);
T v11 = (*this)(i + 1, j + 1);
return bilerp(v00, v10, v01, v11, fx, fy);
}

Math::Vector2<T> affineInterpolateValue(const Math::Vector2<T>& point) const {
Int i, j;
T fx, fy;
barycentric(point[0], i, fx, 0, Int(size_x()));
barycentric(point[1], j, fy, 0, Int(size_y()));
T v00 = (*this)(i, j);
T v10 = (*this)(i + 1, j);
T v01 = (*this)(i, j + 1);
T v11 = (*this)(i + 1, j + 1);
return bilerpGradient(v00, v10, v01, v11, fx, fy);
}

Math::Vector2<T> interpolateGradient(const Math::Vector2<T>& point) const {
Int i, j;
T fx, fy;
barycentric(point[0], i, fx, 0, Int(size_x()));
barycentric(point[1], j, fy, 0, Int(size_y()));
T v00 = (*this)(i, j);
T v01 = (*this)(i, j + 1);
T v10 = (*this)(i + 1, j);
T v11 = (*this)(i + 1, j + 1);
T ddy0 = (v01 - v00);
T ddy1 = (v11 - v10);
T ddx0 = (v10 - v00);
T ddx1 = (v11 - v01);

Math::Vector2<T> grad(
Math::lerp(ddx0, ddx1, fy),
Math::lerp(ddy0, ddy1, fx)
);
const auto magSqr = grad.dot();
if(magSqr > T(1e-20)) {
grad /= std::sqrt(magSqr);
}
return grad;
}

private:
std::size_t _size[2] { 0, 0 };
std::vector<T> _data;
};
} }

#endif
104 changes: 104 additions & 0 deletions src/fluidsimulation2d/DataStructures/MathHelpers.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#ifndef Magnum_Examples_FluidSimulation2D_MathHelpers_h
#define Magnum_Examples_FluidSimulation2D_MathHelpers_h
/*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
Vladimír Vondruš <[email protected]>
2019 — Nghia Truong <[email protected]>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
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 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 <Magnum/Magnum.h>
#include <Magnum/Math/Functions.h>
#include <Magnum/Math/Vector2.h>
#include <Magnum/Math/Matrix.h>

namespace Magnum { namespace Examples {
template<class T>
inline T fractionInside(T phi_left, T phi_right) {
if(phi_left < 0 && phi_right < 0) {
return T(1);
}
if(phi_left < 0 && phi_right >= 0) {
return phi_left / (phi_left - phi_right);
}
if(phi_left >= 0 && phi_right < 0) {
return phi_right / (phi_right - phi_left);
} else {
return T(0);
}
}

template<class T>
inline void barycentric(T x, int& i, T& f, int i_low, int i_high) {
T s = std::floor(x);
i = static_cast<int>(s);
if(i < i_low) {
i = i_low;
f = 0;
} else if(i > i_high - 2) {
i = i_high - 2;
f = 1;
} else {
f = T(x - s);
}
}

template<class T>
inline T bilerp(const T& v00, const T& v10,
const T& v01, const T& v11,
T fx, T fy) {
return Math::lerp(Math::lerp(v00, v10, fx),
Math::lerp(v01, v11, fx),
fy);
}

template<class T>
inline Math::Vector2<T> bilerpGradient(const T& v00, const T& v10,
const T& v01, const T& v11,
T fx, T fy) {
const Math::Vector2<T> f00(fy - T(1), fx - T(1));
const Math::Vector2<T> f10(T(1) - fy, -fx);
const Math::Vector2<T> f01(-fy, T(1) - fx);
const Math::Vector2<T> f11(fy, fx);
return f00 * v00 + f10 * v10 + f01 * v01 + f11 * v11;
}

template<class T>
inline T smoothKernel(T r2, T h2) {
const auto t = T(1) - r2 / h2;
const auto t_exp3 = t * t * t;
return Math::max(t_exp3, T(0));
}

template<class T>
inline T linearKernel(const Math::Vector2<T>& d, T hInv) {
const auto tx = T(1) - std::abs(d.x() * hInv);
const auto ty = T(1) - std::abs(d.y() * hInv);
return Math::max(tx * ty, T(0));
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These look like they could be great additions to the core math lib itself -- I'll see where these could fit.

} }

#endif
Loading