SPH
MeshRenderer.cpp
Go to the documentation of this file.
2 #include "gui/objects/Camera.h"
3 #include "gui/objects/Color.h"
7 #include "system/Profiler.h"
8 #include "system/Statistics.h"
9 #include "thread/CheckFunction.h"
10 
12 
14  : scheduler(scheduler) {
15  surfaceLevel = gui.get<Float>(GuiSettingsId::SURFACE_LEVEL);
16  surfaceResolution = gui.get<Float>(GuiSettingsId::SURFACE_RESOLUTION);
18  sunIntensity = float(gui.get<Float>(GuiSettingsId::SURFACE_SUN_INTENSITY));
19  ambient = float(gui.get<Float>(GuiSettingsId::SURFACE_AMBIENT));
20 
21  RunSettings settings;
23  finder = Factory::getFinder(settings);
24  kernel = Factory::getKernel<3>(settings);
25 }
26 
27 void MeshRenderer::initialize(const Storage& storage,
28  const IColorizer& colorizer,
29  const ICamera& UNUSED(camera)) {
30  cached.colors.clear();
31 
32  const Box boundingBox = getBoundingBox(storage);
33  const Float dim = maxElement(boundingBox.size());
34 
35  McConfig config;
36  // clamp to avoid extreme resolution (which would most likely cause bad alloc)
37  config.gridResolution = clamp(surfaceResolution, 0.001_f * dim, 0.1_f * dim);
38  config.surfaceLevel = surfaceLevel;
39 
40  // get the surface as triangles
41  cached.triangles = getSurfaceMesh(*scheduler, storage, config);
42 
44  finder->build(*scheduler, r);
46 
47  for (Triangle& t : cached.triangles) {
48  const Vector pos = t.center();
49  finder->findAll(pos, 4._f * config.gridResolution, neighs);
50 
51  Rgba colorSum(0._f);
52  float weightSum = 0.f;
53  for (auto& n : neighs) {
54  const Size i = n.index;
55  const Rgba color = colorizer.evalColor(i);
57  const float w = float(max(kernel.value(r[i] - pos, r[i][H]), EPS));
58  colorSum += color * w;
59  weightSum += w;
60  }
61 
62  if (weightSum == 0._f) {
63  // we somehow didn't find any neighbours, indicate the error by red triangle
64  cached.colors.push(Rgba::red());
65  } else {
66  // supersimple diffuse shading
67  const float gray = ambient + sunIntensity * max(0.f, float(dot(sunPosition, t.normal())));
68  cached.colors.push(colorSum / weightSum * gray);
69  }
70  }
71 }
72 
74  return !cached.triangles.empty();
75 }
76 
77 void MeshRenderer::render(const RenderParams& params, Statistics& stats, IRenderOutput& output) const {
78  const Pixel size = params.camera->getSize();
79  Bitmap<Rgba> bitmap(size);
80  PreviewRenderContext<OverPixelOp> context(bitmap);
81 
82  // draw black background
83  context.fill(Rgba::transparent());
84 
85  // sort the arrays by z-depth
86  Order triangleOrder(cached.triangles.size());
87  const Vector cameraDir = params.camera->getFrame().row(2);
88  triangleOrder.shuffle([this, &cameraDir](const Size i1, const Size i2) {
89  const Vector v1 = cached.triangles[i1].center();
90  const Vector v2 = cached.triangles[i2].center();
91  return dot(cameraDir, v1) > dot(cameraDir, v2);
92  });
93 
94  // draw all triangles, starting from the ones with largest z-depth
95  for (Size i = 0; i < cached.triangles.size(); ++i) {
96  const Size idx = triangleOrder[i];
97  context.setColor(cached.colors[idx], ColorFlag::LINE | ColorFlag::FILL);
98 
99  Optional<ProjectedPoint> p1 = params.camera->project(cached.triangles[idx][0]);
100  Optional<ProjectedPoint> p2 = params.camera->project(cached.triangles[idx][1]);
101  Optional<ProjectedPoint> p3 = params.camera->project(cached.triangles[idx][2]);
102  if (!p1 || !p2 || !p3) {
103  continue;
104  }
105  context.drawTriangle(p1->coords, p2->coords, p3->coords);
106  }
107 
108  if (stats.has(StatisticsId::RUN_TIME)) {
109  const int64_t time = int64_t(stats.get<Float>(StatisticsId::RUN_TIME));
110  context.drawText(Coords(0, 0), TextAlign::RIGHT | TextAlign::BOTTOM, getFormattedTime(time * 1000));
111  }
112 
113  output.update(bitmap, context.getLabels(), true);
114 }
115 
NAMESPACE_SPH_BEGIN
Definition: BarnesHut.cpp:13
Defines projection transforming 3D particles onto 2D screen.
Helper functions to check the internal consistency of the code.
Object converting quantity values of particles into colors.
INLINE Float maxElement(const T &value)
Returns maximum element, simply the value iself by default.
Definition: Generic.h:29
uint32_t Size
Integral type used to index arrays (by default).
Definition: Globals.h:16
double Float
Precision used withing the code. Use Float instead of float or double where precision is important.
Definition: Globals.h:13
Array< Triangle > getSurfaceMesh(IScheduler &scheduler, const Storage &storage, const McConfig &config)
Returns the triangle mesh of the body surface (or surfaces of bodies).
constexpr INLINE T max(const T &f1, const T &f2)
Definition: MathBasic.h:20
constexpr INLINE T clamp(const T &f, const T &f1, const T &f2)
Definition: MathBasic.h:35
constexpr Float EPS
Definition: MathUtils.h:30
Renderer visualizing the surface as triangle mesh.
#define UNUSED(x)
Definition: Object.h:37
#define NAMESPACE_SPH_END
Definition: Object.h:12
Helper object defining permutation.
Tool to measure time spent in functions and profile the code.
@ POSITION
Positions (velocities, accelerations) of particles, always a vector quantity,.
Statistics gathered and periodically displayed during the run.
@ RUN_TIME
Current time of the simulation in code units. Does not necessarily have to be 0 when run starts.
Box getBoundingBox(const Storage &storage, const Float radius)
Convenience function to get the bounding box of all particles.
Definition: Storage.cpp:832
String getFormattedTime(const String &format)
Utility functions.
Definition: String.cpp:128
INLINE float dot(const BasicVector< float > &v1, const BasicVector< float > &v2)
Make sure the vector is trivially constructible and destructible, needed for fast initialization of a...
Definition: Vector.h:548
@ H
Definition: Vector.h:25
INLINE Vector row(const Size idx) const
Definition: AffineMatrix.h:44
Object providing safe access to continuous memory of data.
Definition: ArrayView.h:17
Helper object defining three-dimensional interval (box).
Definition: Box.h:17
INLINE Vector size() const
Returns box dimensions.
Definition: Box.h:106
INLINE TValue get(const GuiSettingsId id) const
Definition: Settings.h:245
void build(IScheduler &scheduler, ArrayView< const Vector > points)
Constructs the struct with an array of vectors.
virtual Size findAll(const Size index, const Float radius, Array< NeighbourRecord > &neighbours) const =0
Finds all neighbours within given radius from the point given by index.
Interface defining a camera or view, used by a renderer.
Definition: Camera.h:62
virtual Pixel getSize() const =0
Returns the current resolution of the camera.
virtual AffineMatrix getFrame() const =0
Returns the transformation matrix converting camera space to world space.
virtual Optional< ProjectedPoint > project(const Vector &r) const =0
Returns projected position of particle on the image.
Interface for objects assigning colors to particles.
Definition: Colorizer.h:34
virtual Rgba evalColor(const Size idx) const =0
Returns the color of idx-th particle.
virtual void update(const Bitmap< Rgba > &bitmap, Array< Label > &&labels, const bool isFinal)=0
May be called once after render finishes or multiple times for progressive renderers.
INLINE Float value(const Vector &r, const Float h) const noexcept
Definition: Kernel.h:26
virtual bool isInitialized() const override
Checks if the renderer has been initialized.
MeshRenderer(SharedPtr< IScheduler > scheduler, const GuiSettings &settings)
virtual void initialize(const Storage &storage, const IColorizer &colorizer, const ICamera &camera) override
Prepares the objects for rendering and updates its data.
virtual void render(const RenderParams &params, Statistics &stats, IRenderOutput &output) const override
Can only be called from main thread.
Wrapper of type value of which may or may not be present.
Definition: Optional.h:23
Permutation, i.e. (discrete) invertible function int->int.
Definition: Order.h:18
void shuffle(TBinaryPredicate &&predicate)
Shuffles the order using a binary predicate.
Definition: Order.h:47
virtual Array< IRenderOutput::Label > getLabels() const override
virtual void setColor(const Rgba &color, const Flags< ColorFlag > flags) override
Selects the color for one or more drawing modes.
virtual void drawTriangle(const Coords p1, const Coords p2, const Coords p3) override
Draws a triangle given three points.
virtual void drawText(const Coords p, const Flags< TextAlign > align, const std::string &s) override
Definition: Color.h:8
static Rgba transparent()
Definition: Color.h:202
static Rgba red()
Definition: Color.h:178
Settings & set(const TEnum idx, TValue &&value, std::enable_if_t<!std::is_enum< std::decay_t< TValue >>::value, int >=0)
Saves a value into the settings.
Definition: Settings.h:226
Object holding various statistics about current run.
Definition: Statistics.h:22
TValue get(const StatisticsId idx) const
Returns value of a statistic.
Definition: Statistics.h:88
bool has(const StatisticsId idx) const
Checks if the object contains a statistic with given ID.
Definition: Statistics.h:44
Container storing all quantities used within the simulations.
Definition: Storage.h:230
Array< TValue > & getValue(const QuantityId key)
Retrieves a quantity values from the storage, given its key and value type.
Definition: Storage.cpp:191
Triangle.h.
Definition: Triangle.h:14
INLINE Vector normal() const
Definition: Triangle.h:48
INLINE Vector center() const
Definition: Triangle.h:44
@ KD_TREE
Using K-d tree.
@ SPH_FINDER
Structure for searching nearest neighbours of particles.
@ SURFACE_RESOLUTION
Size of the grid used in MarchingCubes (in code units, not h).
@ SURFACE_LEVEL
Value of iso-surface being constructed; lower value means larget bodies.
@ SURFACE_SUN_INTENSITY
Intentity of the sun.
@ SURFACE_SUN_POSITION
Direction to the sun used for shading.
@ SURFACE_AMBIENT
Ambient color for surface renderer.
AutoPtr< ISymmetricFinder > getFinder(const RunSettings &settings)
Definition: Factory.cpp:156
Definition: Point.h:115
Float gridResolution
Absolute size of each produced triangle.
Float surfaceLevel
Definition: Point.h:101
Parameters of the rendered image.
Definition: IRenderer.h:60
AutoPtr< ICamera > camera
Camera used for rendering.
Definition: IRenderer.h:63