diff --git a/Makefile b/Makefile index a8ada53..198544d 100644 --- a/Makefile +++ b/Makefile @@ -7,6 +7,9 @@ PATH:=${QTSDK}/bin:${PATH} all:build +format: + find src \( \( -name '*.cpp' -or -name '*.h' \) -and \! -path '*/googletest/*' \) -exec clang-format -i \{\} \; + dirs: mkdir -p ${BUILDPATH} diff --git a/src/.clang-format b/src/.clang-format new file mode 100644 index 0000000..b236686 --- /dev/null +++ b/src/.clang-format @@ -0,0 +1,6 @@ +BasedOnStyle: LLVM +IndentWidth: 4 +ColumnLimit: 120 +AllowShortFunctionsOnASingleLine: false +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false diff --git a/src/basics/BoundingBox.cpp b/src/basics/BoundingBox.cpp index f42c9d7..8932eb6 100644 --- a/src/basics/BoundingBox.cpp +++ b/src/basics/BoundingBox.cpp @@ -2,13 +2,11 @@ #include "Vector3.h" -BoundingBox::BoundingBox() -{ +BoundingBox::BoundingBox() { reset(); } -void BoundingBox::reset() -{ +void BoundingBox::reset() { empty = 1; xmin = 10000000000.0; xmax = -10000000000.0; @@ -18,31 +16,24 @@ void BoundingBox::reset() zmax = -10000000000.0; } -void BoundingBox::pushPoint(const Vector3 &point) -{ +void BoundingBox::pushPoint(const Vector3 &point) { empty = 0; - if (point.x < xmin) - { + if (point.x < xmin) { xmin = point.x; } - if (point.x > xmax) - { + if (point.x > xmax) { xmax = point.x; } - if (point.y < ymin) - { + if (point.y < ymin) { ymin = point.y; } - if (point.y > ymax) - { + if (point.y > ymax) { ymax = point.y; } - if (point.z < zmin) - { + if (point.z < zmin) { zmin = point.z; } - if (point.z > zmax) - { + if (point.z > zmax) { zmax = point.z; } } diff --git a/src/basics/BoundingBox.h b/src/basics/BoundingBox.h index 1c9654c..1eb74f4 100644 --- a/src/basics/BoundingBox.h +++ b/src/basics/BoundingBox.h @@ -6,15 +6,14 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT BoundingBox -{ -public: +class BASICSSHARED_EXPORT BoundingBox { + public: BoundingBox(); void reset(); void pushPoint(const Vector3 &point); -public: + public: int empty; double xmin; double xmax; @@ -23,7 +22,6 @@ public: double zmin; double zmax; }; - } } diff --git a/src/basics/CappedCylinder.cpp b/src/basics/CappedCylinder.cpp index 908c295..8997e97 100644 --- a/src/basics/CappedCylinder.cpp +++ b/src/basics/CappedCylinder.cpp @@ -3,77 +3,56 @@ #include "Vector3.h" #include "PackStream.h" -CappedCylinder::CappedCylinder() -{ +CappedCylinder::CappedCylinder() { } -CappedCylinder::CappedCylinder(const Vector3 &base, const Vector3 &direction, double radius, double length): - InfiniteCylinder(InfiniteRay(base, direction), radius), length(length) -{ +CappedCylinder::CappedCylinder(const Vector3 &base, const Vector3 &direction, double radius, double length) + : InfiniteCylinder(InfiniteRay(base, direction), radius), length(length) { } -int CappedCylinder::checkRayIntersection(const InfiniteRay &ray, Vector3 *first_intersection, Vector3 *second_intersection) const -{ +int CappedCylinder::checkRayIntersection(const InfiniteRay &ray, Vector3 *first_intersection, + Vector3 *second_intersection) const { // TODO Apply the caps int count = InfiniteCylinder::checkRayIntersection(ray, first_intersection, second_intersection); - if (count == 0) - { + if (count == 0) { return 0; - } - else if (count == 2) - { - if (checkPointProjection(first_intersection)) - { - if (checkPointProjection(second_intersection)) - { + } else if (count == 2) { + if (checkPointProjection(first_intersection)) { + if (checkPointProjection(second_intersection)) { return 2; - } - else - { + } else { return 1; } - } - else - { - if (checkPointProjection(second_intersection)) - { + } else { + if (checkPointProjection(second_intersection)) { *first_intersection = *second_intersection; return 1; - } - else - { + } else { return 0; } } - } - else // count == 1 + } else // count == 1 { - if (checkPointProjection(first_intersection)) - { + if (checkPointProjection(first_intersection)) { return 1; - } - else - { + } else { return 0; } } } -bool CappedCylinder::checkPointProjection(Vector3 *point) const -{ +bool CappedCylinder::checkPointProjection(Vector3 *point) const { double proj_length = axis.getDirection().dotProduct(point->sub(axis.getOrigin())); return 0.0 <= proj_length && proj_length <= length; } -void CappedCylinder::save(PackStream *stream) const -{ +void CappedCylinder::save(PackStream *stream) const { InfiniteCylinder::save(stream); stream->write(&length); } -void CappedCylinder::load(PackStream *stream) -{ +void CappedCylinder::load(PackStream *stream) { InfiniteCylinder::load(stream); stream->read(&length); } diff --git a/src/basics/CappedCylinder.h b/src/basics/CappedCylinder.h index 75eb2e7..0b92956 100644 --- a/src/basics/CappedCylinder.h +++ b/src/basics/CappedCylinder.h @@ -11,13 +11,14 @@ namespace basics { /** * Geometric cylinder, with capped ends (not infinite). */ -class BASICSSHARED_EXPORT CappedCylinder: public InfiniteCylinder -{ -public: +class BASICSSHARED_EXPORT CappedCylinder : public InfiniteCylinder { + public: CappedCylinder(); CappedCylinder(const Vector3 &base, const Vector3 &direction, double radius, double length); - inline double getLength() const {return length;} + inline double getLength() const { + return length; + } /** * Check the intersection between the cylinder and an infinite ray. @@ -32,10 +33,9 @@ public: virtual void save(PackStream *stream) const override; virtual void load(PackStream *stream) override; -private: + private: double length; }; - } } diff --git a/src/basics/Color.cpp b/src/basics/Color.cpp index 4b8b5aa..321275c 100644 --- a/src/basics/Color.cpp +++ b/src/basics/Color.cpp @@ -11,16 +11,14 @@ const Color paysages::basics::COLOR_BLUE = {0.0, 0.0, 1.0, 1.0}; const Color paysages::basics::COLOR_WHITE = {1.0, 1.0, 1.0, 1.0}; const Color paysages::basics::COLOR_GREY = {0.5, 0.5, 0.5, 1.0}; -void Color::save(PackStream* stream) const -{ +void Color::save(PackStream *stream) const { stream->write(&r); stream->write(&g); stream->write(&b); stream->write(&a); } -void Color::load(PackStream* stream) -{ +void Color::load(PackStream *stream) { stream->read(&r); stream->read(&g); stream->read(&b); diff --git a/src/basics/Color.h b/src/basics/Color.h index bc3e83f..a305fdb 100644 --- a/src/basics/Color.h +++ b/src/basics/Color.h @@ -6,15 +6,14 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT Color -{ -public: +class BASICSSHARED_EXPORT Color { + public: Color() = default; Color(const Color &col); - Color(double r, double g, double b, double a=1.0); + Color(double r, double g, double b, double a = 1.0); - void save(PackStream* stream) const; - void load(PackStream* stream); + void save(PackStream *stream) const; + void load(PackStream *stream); unsigned int to32BitRGBA() const; unsigned int to32BitBGRA() const; @@ -26,16 +25,16 @@ public: static Color from32BitARGB(unsigned int col); static Color from32BitABGR(unsigned int col); - void mask(const Color& mask); + void mask(const Color &mask); double normalize(); double getValue() const; double getPower() const; void limitPower(double max_power); - Color add(const Color& other) const; - Color lerp(const Color& other, double f) const; + Color add(const Color &other) const; + Color lerp(const Color &other, double f) const; -public: + public: double r; double g; double b; @@ -49,7 +48,6 @@ BASICSSHARED_EXPORT extern const Color COLOR_GREEN; BASICSSHARED_EXPORT extern const Color COLOR_BLUE; BASICSSHARED_EXPORT extern const Color COLOR_WHITE; BASICSSHARED_EXPORT extern const Color COLOR_GREY; - } } diff --git a/src/basics/Color.inline.cpp b/src/basics/Color.inline.cpp index c72de09..5e1cfcd 100644 --- a/src/basics/Color.inline.cpp +++ b/src/basics/Color.inline.cpp @@ -6,84 +6,59 @@ #endif #ifdef COLOR_H -# define METHSPEC inline +#define METHSPEC inline #else -# include "Color.h" -# define METHSPEC +#include "Color.h" +#define METHSPEC #endif -METHSPEC Color::Color(double r, double g, double b, double a): - r(r), g(g), b(b), a(a) -{ +METHSPEC Color::Color(double r, double g, double b, double a) : r(r), g(g), b(b), a(a) { } -METHSPEC Color::Color(const Color &col): - r(col.r), g(col.g), b(col.b), a(col.a) -{ +METHSPEC Color::Color(const Color &col) : r(col.r), g(col.g), b(col.b), a(col.a) { } -METHSPEC unsigned int Color::to32BitRGBA() const -{ - return (((unsigned int) (a * 255.0)) << 24) | (((unsigned int) (b * 255.0)) << 16) | (((unsigned int) (g * 255.0)) << 8) | ((unsigned int) (r * 255.0)); +METHSPEC unsigned int Color::to32BitRGBA() const { + return (((unsigned int)(a * 255.0)) << 24) | (((unsigned int)(b * 255.0)) << 16) | + (((unsigned int)(g * 255.0)) << 8) | ((unsigned int)(r * 255.0)); } -METHSPEC unsigned int Color::to32BitBGRA() const -{ - return (((unsigned int) (a * 255.0)) << 24) | (((unsigned int) (r * 255.0)) << 16) | (((unsigned int) (g * 255.0)) << 8) | ((unsigned int) (b * 255.0)); +METHSPEC unsigned int Color::to32BitBGRA() const { + return (((unsigned int)(a * 255.0)) << 24) | (((unsigned int)(r * 255.0)) << 16) | + (((unsigned int)(g * 255.0)) << 8) | ((unsigned int)(b * 255.0)); } -METHSPEC unsigned int Color::to32BitARGB() const -{ - return (((unsigned int) (b * 255.0)) << 24) | (((unsigned int) (g * 255.0)) << 16) | (((unsigned int) (r * 255.0)) << 8) | ((unsigned int) (a * 255.0)); +METHSPEC unsigned int Color::to32BitARGB() const { + return (((unsigned int)(b * 255.0)) << 24) | (((unsigned int)(g * 255.0)) << 16) | + (((unsigned int)(r * 255.0)) << 8) | ((unsigned int)(a * 255.0)); } -METHSPEC unsigned int Color::to32BitABGR() const -{ - return (((unsigned int) (r * 255.0)) << 24) | (((unsigned int) (g * 255.0)) << 16) | (((unsigned int) (b * 255.0)) << 8) | ((unsigned int) (a * 255.0)); +METHSPEC unsigned int Color::to32BitABGR() const { + return (((unsigned int)(r * 255.0)) << 24) | (((unsigned int)(g * 255.0)) << 16) | + (((unsigned int)(b * 255.0)) << 8) | ((unsigned int)(a * 255.0)); } -METHSPEC Color Color::from32BitRGBA(unsigned int col) -{ - return Color( - ((double) (col & 0x000000FF)) / 255.0, - ((double) ((col & 0x0000FF00) >> 8)) / 255.0, - ((double) ((col & 0x00FF0000) >> 16)) / 255.0, - ((double) ((col & 0xFF000000) >> 24)) / 255.0 - ); +METHSPEC Color Color::from32BitRGBA(unsigned int col) { + return Color(((double)(col & 0x000000FF)) / 255.0, ((double)((col & 0x0000FF00) >> 8)) / 255.0, + ((double)((col & 0x00FF0000) >> 16)) / 255.0, ((double)((col & 0xFF000000) >> 24)) / 255.0); } -METHSPEC Color Color::from32BitBGRA(unsigned int col) -{ - return Color( - ((double) (col & 0x000000FF)) / 255.0, - ((double) ((col & 0x0000FF00) >> 8)) / 255.0, - ((double) ((col & 0x00FF0000) >> 16)) / 255.0, - ((double) ((col & 0xFF000000) >> 24)) / 255.0 - ); +METHSPEC Color Color::from32BitBGRA(unsigned int col) { + return Color(((double)(col & 0x000000FF)) / 255.0, ((double)((col & 0x0000FF00) >> 8)) / 255.0, + ((double)((col & 0x00FF0000) >> 16)) / 255.0, ((double)((col & 0xFF000000) >> 24)) / 255.0); } -METHSPEC Color Color::from32BitARGB(unsigned int col) -{ - return Color( - ((double) (col & 0x000000FF)) / 255.0, - ((double) ((col & 0x0000FF00) >> 8)) / 255.0, - ((double) ((col & 0x00FF0000) >> 16)) / 255.0, - ((double) ((col & 0xFF000000) >> 24)) / 255.0 - ); +METHSPEC Color Color::from32BitARGB(unsigned int col) { + return Color(((double)(col & 0x000000FF)) / 255.0, ((double)((col & 0x0000FF00) >> 8)) / 255.0, + ((double)((col & 0x00FF0000) >> 16)) / 255.0, ((double)((col & 0xFF000000) >> 24)) / 255.0); } -METHSPEC Color Color::from32BitABGR(unsigned int col) -{ - return Color( - ((double) (col & 0x000000FF)) / 255.0, - ((double) ((col & 0x0000FF00) >> 8)) / 255.0, - ((double) ((col & 0x00FF0000) >> 16)) / 255.0, - ((double) ((col & 0xFF000000) >> 24)) / 255.0 - ); +METHSPEC Color Color::from32BitABGR(unsigned int col) { + return Color(((double)(col & 0x000000FF)) / 255.0, ((double)((col & 0x0000FF00) >> 8)) / 255.0, + ((double)((col & 0x00FF0000) >> 16)) / 255.0, ((double)((col & 0xFF000000) >> 24)) / 255.0); } -METHSPEC void Color::mask(const Color& mask) -{ +METHSPEC void Color::mask(const Color &mask) { double new_a; new_a = a + mask.a - (a * mask.a); r = (mask.r * mask.a + r * a - r * a * mask.a) / new_a; @@ -100,8 +75,7 @@ METHSPEC void Color::mask(const Color& mask) base->a = base->a + mask_weight * (1.0 - base->a);*/ } -METHSPEC double Color::normalize() -{ +METHSPEC double Color::normalize() { #ifndef NDEBUG assert(r >= 0.0); assert(g >= 0.0); @@ -121,16 +95,13 @@ METHSPEC double Color::normalize() #endif #endif - if (r > 1.0) - { + if (r > 1.0) { r = 1.0; } - if (g > 1.0) - { + if (g > 1.0) { g = 1.0; } - if (b > 1.0) - { + if (b > 1.0) { b = 1.0; } return 1.0; @@ -147,33 +118,27 @@ METHSPEC double Color::normalize() return max;*/ } -METHSPEC double Color::getValue() const -{ +METHSPEC double Color::getValue() const { double max; max = r; - if (g > max) - { + if (g > max) { max = g; } - if (b > max) - { + if (b > max) { max = b; } return max; } -METHSPEC double Color::getPower() const -{ +METHSPEC double Color::getPower() const { return r + g + b; } -METHSPEC void Color::limitPower(double max_power) -{ +METHSPEC void Color::limitPower(double max_power) { double power = r + g + b; - if (power > max_power) - { + if (power > max_power) { double factor = max_power / power; r *= factor; @@ -182,18 +147,12 @@ METHSPEC void Color::limitPower(double max_power) } } -METHSPEC Color Color::add(const Color& other) const -{ +METHSPEC Color Color::add(const Color &other) const { return Color(r + other.r, g + other.g, b + other.b, a); } -METHSPEC Color Color::lerp(const Color& other, double f) const -{ - Color result( - r * (1.0 - f) + other.r * f, - g * (1.0 - f) + other.g * f, - b * (1.0 - f) + other.b * f, - a * (1.0 - f) + other.a * f - ); +METHSPEC Color Color::lerp(const Color &other, double f) const { + Color result(r * (1.0 - f) + other.r * f, g * (1.0 - f) + other.g * f, b * (1.0 - f) + other.b * f, + a * (1.0 - f) + other.a * f); return result; } diff --git a/src/basics/ColorHSL.cpp b/src/basics/ColorHSL.cpp index ff1614f..a184688 100644 --- a/src/basics/ColorHSL.cpp +++ b/src/basics/ColorHSL.cpp @@ -2,26 +2,26 @@ #include "Color.h" -static inline double _hue2rgb(double p, double q, double t) -{ - if (t < 0.0) t += 1; - if (t > 1.0) t -= 1; - if (t < 1.0 / 6.0) return p + (q - p) * 6.0 * t; - if (t < 1.0 / 2.0) return q; - if (t < 2.0 / 3.0) return p + (q - p) * (2.0 / 3.0 - t) * 6.0; +static inline double _hue2rgb(double p, double q, double t) { + if (t < 0.0) + t += 1; + if (t > 1.0) + t -= 1; + if (t < 1.0 / 6.0) + return p + (q - p) * 6.0 * t; + if (t < 1.0 / 2.0) + return q; + if (t < 2.0 / 3.0) + return p + (q - p) * (2.0 / 3.0 - t) * 6.0; return p; } -Color colorFromHSL(const ColorHSL &col) -{ +Color colorFromHSL(const ColorHSL &col) { Color result; - if (col.s == 0) - { + if (col.s == 0) { result.r = result.g = result.b = col.l; - } - else - { + } else { double q = col.l < 0.5 ? col.l * (1.0 + col.s) : col.l + col.s - col.l * col.s; double p = 2 * col.l - q; result.r = _hue2rgb(p, q, col.h + 1.0 / 3.0); @@ -34,8 +34,7 @@ Color colorFromHSL(const ColorHSL &col) return result; } -ColorHSL colorToHSL(const Color &col) -{ +ColorHSL colorToHSL(const Color &col) { ColorHSL result; double min, max; @@ -47,24 +46,16 @@ ColorHSL colorToHSL(const Color &col) result.h = result.s = result.l = (max + min) / 2.0; - if (max == min) - { + if (max == min) { result.h = result.s = 0.0; - } - else - { + } else { double d = max - min; result.s = result.l > 0.5 ? d / (2.0 - max - min) : d / (max + min); - if (max == col.r) - { + if (max == col.r) { result.h = (col.g - col.b) / d + (col.g < col.b ? 6.0 : 0); - } - else if (max == col.g) - { + } else if (max == col.g) { result.h = (col.b - col.r) / d + 2.0; - } - else - { + } else { result.h = (col.r - col.g) / d + 4.0; } result.h /= 6.0; @@ -75,8 +66,7 @@ ColorHSL colorToHSL(const Color &col) return result; } -ColorHSL colorHSLFromValues(double h, double s, double l, double a) -{ +ColorHSL colorHSLFromValues(double h, double s, double l, double a) { ColorHSL result; result.h = h; diff --git a/src/basics/ColorHSL.h b/src/basics/ColorHSL.h index fce0b1e..025639d 100644 --- a/src/basics/ColorHSL.h +++ b/src/basics/ColorHSL.h @@ -3,8 +3,7 @@ #include "basics_global.h" -typedef struct -{ +typedef struct { double h; double s; double l; diff --git a/src/basics/ColorProfile.cpp b/src/basics/ColorProfile.cpp index 99af627..cfeaf13 100644 --- a/src/basics/ColorProfile.cpp +++ b/src/basics/ColorProfile.cpp @@ -2,18 +2,15 @@ #include "PackStream.h" -ColorProfile::ColorProfile() -{ +ColorProfile::ColorProfile() { setToneMapping(TONE_MAPPING_UNCHARTED, 1.6); } -ColorProfile::ColorProfile(ToneMappingOperator tonemapper, double exposure) -{ +ColorProfile::ColorProfile(ToneMappingOperator tonemapper, double exposure) { setToneMapping(tonemapper, exposure); } -static inline double _uncharted2Tonemap(double x) -{ +static inline double _uncharted2Tonemap(double x) { double A = 0.15; double B = 0.50; double C = 0.10; @@ -24,61 +21,43 @@ static inline double _uncharted2Tonemap(double x) return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F; } -static inline Color _toneMappingUncharted(const Color &pixel, double exposure) -{ +static inline Color _toneMappingUncharted(const Color &pixel, double exposure) { static const double W = 11.2; static const double white_scale = 1.0 / _uncharted2Tonemap(W); static const double factor = 1.0 / 2.2; - Color result( - pow(_uncharted2Tonemap(pixel.r * exposure) * white_scale, factor), - pow(_uncharted2Tonemap(pixel.g * exposure) * white_scale, factor), - pow(_uncharted2Tonemap(pixel.b * exposure) * white_scale, factor), - pixel.a - ); + Color result(pow(_uncharted2Tonemap(pixel.r * exposure) * white_scale, factor), + pow(_uncharted2Tonemap(pixel.g * exposure) * white_scale, factor), + pow(_uncharted2Tonemap(pixel.b * exposure) * white_scale, factor), pixel.a); return result; } -static inline Color _toneMappingReinhard(const Color &pixel, double exposure) -{ - Color result( - (pixel.r * exposure) / (1.0 + pixel.r * exposure), - (pixel.g * exposure) / (1.0 + pixel.g * exposure), - (pixel.b * exposure) / (1.0 + pixel.b * exposure), - pixel.a - ); +static inline Color _toneMappingReinhard(const Color &pixel, double exposure) { + Color result((pixel.r * exposure) / (1.0 + pixel.r * exposure), (pixel.g * exposure) / (1.0 + pixel.g * exposure), + (pixel.b * exposure) / (1.0 + pixel.b * exposure), pixel.a); return result; } -static inline Color _toneMappingClamp(const Color &pixel) -{ - Color result( - pixel.r > 1.0 ? 1.0 : pixel.r, - pixel.g > 1.0 ? 1.0 : pixel.g, - pixel.b > 1.0 ? 1.0 : pixel.b, - pixel.a - ); +static inline Color _toneMappingClamp(const Color &pixel) { + Color result(pixel.r > 1.0 ? 1.0 : pixel.r, pixel.g > 1.0 ? 1.0 : pixel.g, pixel.b > 1.0 ? 1.0 : pixel.b, pixel.a); return result; } -void ColorProfile::setToneMapping(ToneMappingOperator tonemapper, double exposure) -{ +void ColorProfile::setToneMapping(ToneMappingOperator tonemapper, double exposure) { this->mapper = tonemapper; this->exposure = exposure; } -void ColorProfile::save(PackStream* stream) const -{ +void ColorProfile::save(PackStream *stream) const { int imapper = (int)mapper; stream->write(&imapper); stream->write(&exposure); } -void ColorProfile::load(PackStream* stream) -{ +void ColorProfile::load(PackStream *stream) { int imapper = (int)mapper; stream->read(&imapper); stream->read(&exposure); @@ -86,16 +65,13 @@ void ColorProfile::load(PackStream* stream) mapper = (ToneMappingOperator)imapper; } -void ColorProfile::copy(ColorProfile* destination) const -{ +void ColorProfile::copy(ColorProfile *destination) const { destination->mapper = mapper; destination->exposure = exposure; } -Color ColorProfile::apply(const Color &pixel) const -{ - switch (mapper) - { +Color ColorProfile::apply(const Color &pixel) const { + switch (mapper) { case TONE_MAPPING_REIHNARD: return _toneMappingReinhard(pixel, exposure); case TONE_MAPPING_UNCHARTED: diff --git a/src/basics/ColorProfile.h b/src/basics/ColorProfile.h index 0f84445..4827068 100644 --- a/src/basics/ColorProfile.h +++ b/src/basics/ColorProfile.h @@ -8,33 +8,26 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT ColorProfile -{ -public: - typedef enum - { - TONE_MAPPING_UNCHARTED, - TONE_MAPPING_REIHNARD, - TONE_MAPPING_CLAMP - } ToneMappingOperator; +class BASICSSHARED_EXPORT ColorProfile { + public: + typedef enum { TONE_MAPPING_UNCHARTED, TONE_MAPPING_REIHNARD, TONE_MAPPING_CLAMP } ToneMappingOperator; -public: + public: ColorProfile(); ColorProfile(ToneMappingOperator tonemapper, double exposure); void setToneMapping(ToneMappingOperator tonemapper, double exposure); - void save(PackStream* stream) const; - void load(PackStream* stream); - void copy(ColorProfile* destination) const; + void save(PackStream *stream) const; + void load(PackStream *stream); + void copy(ColorProfile *destination) const; Color apply(const Color &pixel) const; -private: + private: ToneMappingOperator mapper; double exposure; }; - } } diff --git a/src/basics/Curve.cpp b/src/basics/Curve.cpp index ce469bc..68adfb5 100644 --- a/src/basics/Curve.cpp +++ b/src/basics/Curve.cpp @@ -5,167 +5,123 @@ const int MAX_NB_POINTS = 30; -Curve::Curve() -{ +Curve::Curve() { nbpoints = 0; default_value = 0.0; points = new CurvePoint[MAX_NB_POINTS]; } -Curve::~Curve() -{ +Curve::~Curve() { delete[] points; } -void Curve::copy(Curve* destination) const -{ +void Curve::copy(Curve *destination) const { destination->nbpoints = nbpoints; destination->default_value = default_value; - for (int i = 0; i < nbpoints; i++) - { + for (int i = 0; i < nbpoints; i++) { destination->points[i] = points[i]; } } -void Curve::save(PackStream* stream) const -{ +void Curve::save(PackStream *stream) const { stream->write(&default_value); stream->write(&nbpoints); - for (int i = 0; i < nbpoints; i++) - { + for (int i = 0; i < nbpoints; i++) { stream->write(&points[i].position); stream->write(&points[i].value); } } -void Curve::load(PackStream* stream) -{ +void Curve::load(PackStream *stream) { stream->read(&default_value); stream->read(&nbpoints); - for (int i = 0; i < nbpoints; i++) - { + for (int i = 0; i < nbpoints; i++) { stream->read(&points[i].position); stream->read(&points[i].value); } } -void Curve::clear() -{ +void Curve::clear() { nbpoints = 0; } -void Curve::setDefault(double value) -{ +void Curve::setDefault(double value) { default_value = value; } -int Curve::addPoint(const CurvePoint &point) -{ - if (nbpoints < MAX_NB_POINTS) - { +int Curve::addPoint(const CurvePoint &point) { + if (nbpoints < MAX_NB_POINTS) { points[nbpoints] = point; return nbpoints++; - } - else - { + } else { return -1; } } -int Curve::addPoint(double position, double value) -{ +int Curve::addPoint(double position, double value) { CurvePoint point = {position, value}; return addPoint(point); } -CurvePoint Curve::getPoint(int number) const -{ - if (number >= 0 && number < nbpoints) - { +CurvePoint Curve::getPoint(int number) const { + if (number >= 0 && number < nbpoints) { return points[number]; - } - else - { + } else { return {0.0, 0.0}; } } -bool Curve::getPoint(int number, CurvePoint *point) const -{ - if (number >= 0 && number < nbpoints) - { +bool Curve::getPoint(int number, CurvePoint *point) const { + if (number >= 0 && number < nbpoints) { *point = points[number]; return true; - } - else - { + } else { return false; } } -void Curve::setPoint(int number, const CurvePoint &point) -{ - if (number >= 0 && number < nbpoints) - { +void Curve::setPoint(int number, const CurvePoint &point) { + if (number >= 0 && number < nbpoints) { points[number] = point; } } -void Curve::removePoint(int number) -{ - if (number >= 0 && number < nbpoints) - { - if (nbpoints > 0 && number < nbpoints - 1) - { +void Curve::removePoint(int number) { + if (number >= 0 && number < nbpoints) { + if (nbpoints > 0 && number < nbpoints - 1) { memmove(points + number, points + number + 1, sizeof(CurvePoint) * (nbpoints - number - 1)); } nbpoints--; } } -int _point_compare(const void* part1, const void* part2) -{ - if (((CurvePoint*)part1)->position > ((CurvePoint*)part2)->position) - { +int _point_compare(const void *part1, const void *part2) { + if (((CurvePoint *)part1)->position > ((CurvePoint *)part2)->position) { return 1; - } - else - { + } else { return -1; } } -void Curve::validate() -{ - if (nbpoints > 1) - { +void Curve::validate() { + if (nbpoints > 1) { qsort(points, nbpoints, sizeof(CurvePoint), _point_compare); } } -double Curve::getValue(double position) const -{ +double Curve::getValue(double position) const { int i; double fact; - if (nbpoints == 0) - { + if (nbpoints == 0) { return default_value; - } - else if (nbpoints == 1 || position <= points[0].position) - { + } else if (nbpoints == 1 || position <= points[0].position) { return points[0].value; - } - else if (position >= points[nbpoints - 1].position) - { + } else if (position >= points[nbpoints - 1].position) { return points[nbpoints - 1].value; - } - else - { - for (i = 1; i < nbpoints; i++) - { - if (position < points[i].position) - { + } else { + for (i = 1; i < nbpoints; i++) { + if (position < points[i].position) { fact = (position - points[i - 1].position) / (points[i].position - points[i - 1].position); return points[i - 1].value + (points[i].value - points[i - 1].value) * fact; } diff --git a/src/basics/Curve.h b/src/basics/Curve.h index 0830871..e4f5218 100644 --- a/src/basics/Curve.h +++ b/src/basics/Curve.h @@ -11,18 +11,19 @@ typedef struct { double value; } CurvePoint; -class BASICSSHARED_EXPORT Curve -{ -public: +class BASICSSHARED_EXPORT Curve { + public: Curve(); ~Curve(); - void copy(Curve* destination) const; - void save(PackStream* stream) const; - void load(PackStream* stream); + void copy(Curve *destination) const; + void save(PackStream *stream) const; + void load(PackStream *stream); void validate(); - inline int getPointCount() const {return nbpoints;} + inline int getPointCount() const { + return nbpoints; + } CurvePoint getPoint(int number) const; bool getPoint(int number, CurvePoint *point) const; @@ -35,12 +36,11 @@ public: void setPoint(int number, const CurvePoint &point); void removePoint(int number); -private: + private: double default_value; int nbpoints; - CurvePoint* points; + CurvePoint *points; }; - } } diff --git a/src/basics/Disk.cpp b/src/basics/Disk.cpp index 3b1cbba..e8a2696 100644 --- a/src/basics/Disk.cpp +++ b/src/basics/Disk.cpp @@ -2,41 +2,32 @@ #include "PackStream.h" -Disk::Disk() -{ +Disk::Disk() { } -Disk::Disk(const Vector3 &point, const Vector3 &normal, double radius): - InfinitePlane(point, normal), radius(radius) -{ +Disk::Disk(const Vector3 &point, const Vector3 &normal, double radius) : InfinitePlane(point, normal), radius(radius) { radius2 = radius * radius; } -int Disk::checkRayIntersection(const InfiniteRay &ray, Vector3 *intersection) const -{ +int Disk::checkRayIntersection(const InfiniteRay &ray, Vector3 *intersection) const { int result = InfinitePlane::checkRayIntersection(ray, intersection); - if (result == 1) - { + if (result == 1) { Vector3 v = intersection->sub(getPoint()); double d2 = v.dotProduct(v); return (d2 <= radius2) ? 1 : 0; - } - else - { + } else { return result; } } -void Disk::save(PackStream *stream) const -{ +void Disk::save(PackStream *stream) const { InfinitePlane::save(stream); stream->write(&radius); stream->write(&radius2); } -void Disk::load(PackStream *stream) -{ +void Disk::load(PackStream *stream) { InfinitePlane::load(stream); stream->read(&radius); stream->read(&radius2); diff --git a/src/basics/Disk.h b/src/basics/Disk.h index 5493314..a72b803 100644 --- a/src/basics/Disk.h +++ b/src/basics/Disk.h @@ -11,13 +11,14 @@ namespace basics { /** * Geometric plane disk. */ -class BASICSSHARED_EXPORT Disk: public InfinitePlane -{ -public: +class BASICSSHARED_EXPORT Disk : public InfinitePlane { + public: Disk(); Disk(const Vector3 &point, const Vector3 &normal, double radius); - inline double getRadius() const {return radius;} + inline double getRadius() const { + return radius; + } /** * Check the intersection between the disk and an infinite ray. @@ -26,16 +27,15 @@ public: * * Returns -1 if the ray shares a segment with the disk. */ - int checkRayIntersection(const InfiniteRay& ray, Vector3 *intersection) const; + int checkRayIntersection(const InfiniteRay &ray, Vector3 *intersection) const; void save(PackStream *stream) const override; void load(PackStream *stream) override; -private: + private: double radius; double radius2; }; - } } diff --git a/src/basics/FractalNoise.cpp b/src/basics/FractalNoise.cpp index deab9f4..92e7266 100644 --- a/src/basics/FractalNoise.cpp +++ b/src/basics/FractalNoise.cpp @@ -1,7 +1,6 @@ #include "FractalNoise.h" -FractalNoise::FractalNoise() -{ +FractalNoise::FractalNoise() { scaling = 1.0; height = 1.0; step_scaling = 2.0; @@ -10,47 +9,39 @@ FractalNoise::FractalNoise() ridge = 0.0; } -FractalNoise::~FractalNoise() -{ +FractalNoise::~FractalNoise() { } -void FractalNoise::setScaling(double scaling, double height) -{ +void FractalNoise::setScaling(double scaling, double height) { this->scaling = scaling < 0.00000001 ? 0.0 : 1.0 / scaling; this->height = scaling * height; } -void FractalNoise::setStep(double scaling_factor, double height_factor) -{ +void FractalNoise::setStep(double scaling_factor, double height_factor) { this->step_scaling = scaling_factor < 0.00000001 ? 0.0 : 1.0 / scaling_factor; this->step_height = scaling_factor * height_factor; } -void FractalNoise::setSlope(double slope_factor) -{ +void FractalNoise::setSlope(double slope_factor) { this->slope = slope_factor; } -void FractalNoise::setRidge(double ridge_factor) -{ +void FractalNoise::setRidge(double ridge_factor) { this->ridge = ridge_factor; } -void FractalNoise::setState(const NoiseState &state) -{ +void FractalNoise::setState(const NoiseState &state) { state.copy(&this->state); } -double FractalNoise::get1d(double detail, double x) const -{ +double FractalNoise::get1d(double detail, double x) const { double current_scaling = scaling; double current_height = height; double result = 0.0; int state_level_count = state.level_offsets.size(); int i = 0; - while (current_height >= detail) - { + while (current_height >= detail) { const NoiseState::NoiseOffset &offset = state.level_offsets[i]; result += getBase1d(offset.x + x * current_scaling) * current_height; @@ -59,8 +50,7 @@ double FractalNoise::get1d(double detail, double x) const current_height *= step_height; i++; - if (i >= state_level_count) - { + if (i >= state_level_count) { i = 0; } } @@ -68,16 +58,14 @@ double FractalNoise::get1d(double detail, double x) const return result; } -double FractalNoise::get2d(double detail, double x, double y) const -{ +double FractalNoise::get2d(double detail, double x, double y) const { double current_scaling = scaling; double current_height = height; double result = 0.0; int state_level_count = state.level_offsets.size(); int i = 0; - while (current_height >= detail) - { + while (current_height >= detail) { const NoiseState::NoiseOffset &offset = state.level_offsets[i]; result += getBase2d(offset.x + x * current_scaling, offset.y + y * current_scaling) * current_height; @@ -86,8 +74,7 @@ double FractalNoise::get2d(double detail, double x, double y) const current_height *= step_height; i++; - if (i >= state_level_count) - { + if (i >= state_level_count) { i = 0; } } @@ -95,26 +82,25 @@ double FractalNoise::get2d(double detail, double x, double y) const return result; } -double FractalNoise::get3d(double detail, double x, double y, double z) const -{ +double FractalNoise::get3d(double detail, double x, double y, double z) const { double current_scaling = scaling; double current_height = height; double result = 0.0; int state_level_count = state.level_offsets.size(); int i = 0; - while (current_height >= detail) - { + while (current_height >= detail) { const NoiseState::NoiseOffset &offset = state.level_offsets[i]; - result += getBase3d(offset.x + x * current_scaling, offset.y + y * current_scaling, offset.z + z * current_scaling) * current_height; + result += + getBase3d(offset.x + x * current_scaling, offset.y + y * current_scaling, offset.z + z * current_scaling) * + current_height; current_scaling *= step_scaling; current_height *= step_height; i++; - if (i >= state_level_count) - { + if (i >= state_level_count) { i = 0; } } @@ -122,12 +108,10 @@ double FractalNoise::get3d(double detail, double x, double y, double z) const return result; } -double FractalNoise::getBase1d(double x) const -{ +double FractalNoise::getBase1d(double x) const { return getBase2d(x, 0.0); } -double FractalNoise::getBase2d(double x, double y) const -{ +double FractalNoise::getBase2d(double x, double y) const { return getBase3d(x, y, 0.0); } diff --git a/src/basics/FractalNoise.h b/src/basics/FractalNoise.h index 0fa2a79..0f77667 100644 --- a/src/basics/FractalNoise.h +++ b/src/basics/FractalNoise.h @@ -11,14 +11,13 @@ namespace basics { /*! * \brief Fractal noise generator, based on a sum of simple noise functions. */ -class BASICSSHARED_EXPORT FractalNoise -{ -public: +class BASICSSHARED_EXPORT FractalNoise { + public: FractalNoise(); virtual ~FractalNoise(); - void setScaling(double scaling, double height=1.0); - void setStep(double scaling_factor, double height_factor=1.0); + void setScaling(double scaling, double height = 1.0); + void setStep(double scaling_factor, double height_factor = 1.0); void setSlope(double slope_factor); void setRidge(double ridge_factor); void setState(const NoiseState &state); @@ -31,7 +30,7 @@ public: virtual double getBase2d(double x, double y) const; virtual double getBase3d(double x, double y, double z) const = 0; -private: + private: NoiseState state; double scaling; @@ -41,7 +40,6 @@ private: double slope; double ridge; }; - } } diff --git a/src/basics/Geometry.cpp b/src/basics/Geometry.cpp index 0b91062..0e873ce 100644 --- a/src/basics/Geometry.cpp +++ b/src/basics/Geometry.cpp @@ -3,22 +3,15 @@ #include #include "Vector3.h" -double Geometry::get2DAngle(double x, double y) -{ +double Geometry::get2DAngle(double x, double y) { double nx, ny, d, ret; - if (x == 0.0) - { - if (y == 0.0) - { + if (x == 0.0) { + if (y == 0.0) { return 0.0; - } - else if (y < 0.0) - { + } else if (y < 0.0) { return 3.0 * M_PI_2; - } - else - { + } else { return M_PI_2; } } @@ -28,54 +21,46 @@ double Geometry::get2DAngle(double x, double y) ny = y / d; ret = asin(ny); - if (nx < 0.0) - { + if (nx < 0.0) { ret = M_PI - ret; } return ret < 0.0 ? ret + 2.0 * M_PI : ret; } -Vector3 Geometry::getNormalFromTriangle(const Vector3 ¢er, const Vector3 &bottom, const Vector3 &right) -{ +Vector3 Geometry::getNormalFromTriangle(const Vector3 ¢er, const Vector3 &bottom, const Vector3 &right) { Vector3 dx = right.sub(center); Vector3 dz = bottom.sub(center); return dz.crossProduct(dx).normalize(); } -double Geometry::getDistance2D(double x1, double y1, double x2, double y2) -{ +double Geometry::getDistance2D(double x1, double y1, double x2, double y2) { double dx = x2 - x1; double dy = y2 - y1; return sqrt(dx * dx + dy * dy); } -int Geometry::rayIntersectSphere(const Vector3 &ray_point, const Vector3 &ray_direction, const Vector3 &sphere_center, double sphere_radius, Vector3 *hit1, Vector3 *hit2) -{ +int Geometry::rayIntersectSphere(const Vector3 &ray_point, const Vector3 &ray_direction, const Vector3 &sphere_center, + double sphere_radius, Vector3 *hit1, Vector3 *hit2) { Vector3 ray_direction_sphere = ray_point.sub(sphere_center); double a, b, c, d; a = ray_direction.x * ray_direction.x + ray_direction.y * ray_direction.y + ray_direction.z * ray_direction.z; - b = 2 * (ray_direction.x * ray_direction_sphere.x + ray_direction.y * ray_direction_sphere.y + ray_direction.z * ray_direction_sphere.z); - c = ray_direction_sphere.x * ray_direction_sphere.x + ray_direction_sphere.y * ray_direction_sphere.y + ray_direction_sphere.z * ray_direction_sphere.z - sphere_radius * sphere_radius; + b = 2 * (ray_direction.x * ray_direction_sphere.x + ray_direction.y * ray_direction_sphere.y + + ray_direction.z * ray_direction_sphere.z); + c = ray_direction_sphere.x * ray_direction_sphere.x + ray_direction_sphere.y * ray_direction_sphere.y + + ray_direction_sphere.z * ray_direction_sphere.z - sphere_radius * sphere_radius; d = b * b - 4 * a * c; - if (d < 0.0) - { + if (d < 0.0) { return 0; - } - else if (d > 0.0) - { - if (hit1 && hit2) - { + } else if (d > 0.0) { + if (hit1 && hit2) { *hit1 = ray_point.add(ray_direction.scale((-b - sqrt(d)) / (2 * a))); *hit2 = ray_point.add(ray_direction.scale((-b + sqrt(d)) / (2 * a))); } return 2; - } - else - { - if (hit1) - { + } else { + if (hit1) { *hit1 = ray_point.add(ray_direction.scale(-b / (2 * a))); } return 1; diff --git a/src/basics/Geometry.h b/src/basics/Geometry.h index 6a75f85..faf7b11 100644 --- a/src/basics/Geometry.h +++ b/src/basics/Geometry.h @@ -6,15 +6,14 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT Geometry -{ -public: +class BASICSSHARED_EXPORT Geometry { + public: static double get2DAngle(double x, double y); static Vector3 getNormalFromTriangle(const Vector3 ¢er, const Vector3 &bottom, const Vector3 &right); static double getDistance2D(double x1, double y1, double x2, double y2); - static int rayIntersectSphere(const Vector3 &ray_point, const Vector3 &ray_direction, const Vector3 &sphere_center, double sphere_radius, Vector3 *hit1, Vector3 *hit2); + static int rayIntersectSphere(const Vector3 &ray_point, const Vector3 &ray_direction, const Vector3 &sphere_center, + double sphere_radius, Vector3 *hit1, Vector3 *hit2); }; - } } diff --git a/src/basics/InfiniteCylinder.cpp b/src/basics/InfiniteCylinder.cpp index 0f81911..4a7ae64 100644 --- a/src/basics/InfiniteCylinder.cpp +++ b/src/basics/InfiniteCylinder.cpp @@ -4,17 +4,14 @@ #define EPS 1E-8 -InfiniteCylinder::InfiniteCylinder() -{ +InfiniteCylinder::InfiniteCylinder() { } -InfiniteCylinder::InfiniteCylinder(const InfiniteRay &axis, double radius): - axis(axis), radius(radius) -{ +InfiniteCylinder::InfiniteCylinder(const InfiniteRay &axis, double radius) : axis(axis), radius(radius) { } -int InfiniteCylinder::checkRayIntersection(const InfiniteRay &ray, Vector3 *first_intersection, Vector3 *second_intersection) const -{ +int InfiniteCylinder::checkRayIntersection(const InfiniteRay &ray, Vector3 *first_intersection, + Vector3 *second_intersection) const { /* * Original algorithm has been altered, because it didn't work with non-(0,0,0) axis origin. * Maybe some optimizations could be made from this. @@ -27,108 +24,108 @@ int InfiniteCylinder::checkRayIntersection(const InfiniteRay &ray, Vector3 *firs /* choose U, V so that U,V,F is orthonormal set */ - if ( fabs(F.x) > fabs(F.y) && fabs(F.x) > fabs(F.z) ) - { - length = sqrt(F.x*F.x+F.y*F.y); - invLength = 1.0/length; - U.x = -F.y*invLength; - U.y = +F.x*invLength; + if (fabs(F.x) > fabs(F.y) && fabs(F.x) > fabs(F.z)) { + length = sqrt(F.x * F.x + F.y * F.y); + invLength = 1.0 / length; + U.x = -F.y * invLength; + U.y = +F.x * invLength; U.z = 0.0; - prod = -F.z*invLength; - V.x = F.x*prod; - V.y = F.y*prod; + prod = -F.z * invLength; + V.x = F.x * prod; + V.y = F.y * prod; V.z = length; - } - else - { - length = sqrt(F.y*F.y+F.z*F.z); - invLength = 1.0/length; + } else { + length = sqrt(F.y * F.y + F.z * F.z); + invLength = 1.0 / length; U.x = 0.0; - U.y = -F.z*invLength; - U.z = +F.y*invLength; - prod = -F.x*invLength; + U.y = -F.z * invLength; + U.z = +F.y * invLength; + prod = -F.x * invLength; V.x = length; - V.y = F.y*prod; - V.z = F.z*prod; + V.y = F.y * prod; + V.z = F.z * prod; } /* orthonormal matrix */ - R[0][0] = U.x; R[0][1] = U.y; R[0][2] = U.z; - R[1][0] = V.x; R[1][1] = V.y; R[1][2] = V.z; - R[2][0] = F.x; R[2][1] = F.y; R[2][2] = F.z; + R[0][0] = U.x; + R[0][1] = U.y; + R[0][2] = U.z; + R[1][0] = V.x; + R[1][1] = V.y; + R[1][2] = V.z; + R[2][0] = F.x; + R[2][1] = F.y; + R[2][2] = F.z; /* matrix A */ - A[0][0] = R[0][0]*R[0][0]+R[1][0]*R[1][0]; - A[0][1] = R[0][0]*R[0][1]+R[1][0]*R[1][1]; - A[0][2] = R[0][0]*R[0][2]+R[1][0]*R[1][2]; + A[0][0] = R[0][0] * R[0][0] + R[1][0] * R[1][0]; + A[0][1] = R[0][0] * R[0][1] + R[1][0] * R[1][1]; + A[0][2] = R[0][0] * R[0][2] + R[1][0] * R[1][2]; - A[1][0] = R[0][1]*R[0][0]+R[1][1]*R[1][0]; - A[1][1] = R[0][1]*R[0][1]+R[1][1]*R[1][1]; - A[1][2] = R[0][1]*R[0][2]+R[1][1]*R[1][2]; + A[1][0] = R[0][1] * R[0][0] + R[1][1] * R[1][0]; + A[1][1] = R[0][1] * R[0][1] + R[1][1] * R[1][1]; + A[1][2] = R[0][1] * R[0][2] + R[1][1] * R[1][2]; - A[2][0] = R[0][2]*R[0][0]+R[1][2]*R[1][0]; - A[2][1] = R[0][2]*R[0][1]+R[1][2]*R[1][1]; - A[2][2] = R[0][2]*R[0][2]+R[1][2]*R[1][2]; + A[2][0] = R[0][2] * R[0][0] + R[1][2] * R[1][0]; + A[2][1] = R[0][2] * R[0][1] + R[1][2] * R[1][1]; + A[2][2] = R[0][2] * R[0][2] + R[1][2] * R[1][2]; /* vector B */ P = Vector3(0.0, 0.0, 0.0); - B.x = -2.0*P.x; B.y = -2.0*P.y; B.z = -2.0*P.z; + B.x = -2.0 * P.x; + B.y = -2.0 * P.y; + B.z = -2.0 * P.z; /* constant C */ - e0 = -2.0*(R[0][0]*P.x+R[0][1]*P.y+R[0][2]*P.z); - e1 = -2.0*(R[1][0]*P.x+R[1][1]*P.y+R[1][2]*P.z); - C = 0.25*(e0*e0+e1*e1) - radius*radius; + e0 = -2.0 * (R[0][0] * P.x + R[0][1] * P.y + R[0][2] * P.z); + e1 = -2.0 * (R[1][0] * P.x + R[1][1] * P.y + R[1][2] * P.z); + C = 0.25 * (e0 * e0 + e1 * e1) - radius * radius; /* line */ Q = ray.getOrigin().sub(axis.getOrigin()); G = ray.getDirection(); /* compute A*G */ - AG.x = A[0][0]*G.x+A[0][1]*G.y+A[0][2]*G.z; - AG.y = A[1][0]*G.x+A[1][1]*G.y+A[1][2]*G.z; - AG.z = A[2][0]*G.x+A[2][1]*G.y+A[2][2]*G.z; + AG.x = A[0][0] * G.x + A[0][1] * G.y + A[0][2] * G.z; + AG.y = A[1][0] * G.x + A[1][1] * G.y + A[1][2] * G.z; + AG.z = A[2][0] * G.x + A[2][1] * G.y + A[2][2] * G.z; /* compute A*Q */ - AQ.x = A[0][0]*Q.x+A[0][1]*Q.y+A[0][2]*Q.z; - AQ.y = A[1][0]*Q.x+A[1][1]*Q.y+A[1][2]*Q.z; - AQ.z = A[2][0]*Q.x+A[2][1]*Q.y+A[2][2]*Q.z; + AQ.x = A[0][0] * Q.x + A[0][1] * Q.y + A[0][2] * Q.z; + AQ.y = A[1][0] * Q.x + A[1][1] * Q.y + A[1][2] * Q.z; + AQ.z = A[2][0] * Q.x + A[2][1] * Q.y + A[2][2] * Q.z; /* compute quadratic equation c0+c1*t+c2*t^2 = 0 */ - c2 = G.x*AG.x+G.y*AG.y+G.z*AG.z; - c1 = B.x*G.x+B.y*G.y+B.z*G.z+2.0f*(Q.x*AG.x+Q.y*AG.y+Q.z*AG.z); - c0 = Q.x*AQ.x+Q.y*AQ.y+Q.z*AQ.z+B.x*Q.x+B.y*Q.y+B.z*Q.z+C; + c2 = G.x * AG.x + G.y * AG.y + G.z * AG.z; + c1 = B.x * G.x + B.y * G.y + B.z * G.z + 2.0f * (Q.x * AG.x + Q.y * AG.y + Q.z * AG.z); + c0 = Q.x * AQ.x + Q.y * AQ.y + Q.z * AQ.z + B.x * Q.x + B.y * Q.y + B.z * Q.z + C; /* solve for intersections */ int numIntersections; - discr = c1*c1-4.0*c0*c2; - if ( discr > EPS ) - { + discr = c1 * c1 - 4.0 * c0 * c2; + if (discr > EPS) { numIntersections = 2; discr = sqrt(discr); - invC2 = 1.0/c2; - root0 = -0.5*(c1+discr)*invC2; - root1 = -0.5*(c1-discr)*invC2; - first_intersection->x = Q.x+root0*G.x; - first_intersection->y = Q.y+root0*G.y; - first_intersection->z = Q.z+root0*G.z; - second_intersection->x = Q.x+root1*G.x; - second_intersection->y = Q.y+root1*G.y; - second_intersection->z = Q.z+root1*G.z; + invC2 = 1.0 / c2; + root0 = -0.5 * (c1 + discr) * invC2; + root1 = -0.5 * (c1 - discr) * invC2; + first_intersection->x = Q.x + root0 * G.x; + first_intersection->y = Q.y + root0 * G.y; + first_intersection->z = Q.z + root0 * G.z; + second_intersection->x = Q.x + root1 * G.x; + second_intersection->y = Q.y + root1 * G.y; + second_intersection->z = Q.z + root1 * G.z; *first_intersection = first_intersection->add(axis.getOrigin()); *second_intersection = second_intersection->add(axis.getOrigin()); - } - else if ( discr < -EPS ) - { + } else if (discr < -EPS) { numIntersections = 0; - } - else - { + } else { numIntersections = 1; - root = -0.5*c1/c2; - first_intersection->x = Q.x+root*G.x; - first_intersection->y = Q.y+root*G.y; - first_intersection->z = Q.z+root*G.z; + root = -0.5 * c1 / c2; + first_intersection->x = Q.x + root * G.x; + first_intersection->y = Q.y + root * G.y; + first_intersection->z = Q.z + root * G.z; *first_intersection = first_intersection->add(axis.getOrigin()); } @@ -136,14 +133,12 @@ int InfiniteCylinder::checkRayIntersection(const InfiniteRay &ray, Vector3 *firs return numIntersections; } -void InfiniteCylinder::save(PackStream *stream) const -{ +void InfiniteCylinder::save(PackStream *stream) const { axis.save(stream); stream->write(&radius); } -void InfiniteCylinder::load(PackStream *stream) -{ +void InfiniteCylinder::load(PackStream *stream) { axis.load(stream); stream->read(&radius); } diff --git a/src/basics/InfiniteCylinder.h b/src/basics/InfiniteCylinder.h index 8bcdc2f..dcb053a 100644 --- a/src/basics/InfiniteCylinder.h +++ b/src/basics/InfiniteCylinder.h @@ -11,30 +11,32 @@ namespace basics { /** * Geometric cylinder, with infinite length. */ -class BASICSSHARED_EXPORT InfiniteCylinder -{ -public: +class BASICSSHARED_EXPORT InfiniteCylinder { + public: InfiniteCylinder(); InfiniteCylinder(const InfiniteRay &axis, double radius); - inline const InfiniteRay& getAxis() const {return axis;} - inline double getRadius() const {return radius;} + inline const InfiniteRay &getAxis() const { + return axis; + } + inline double getRadius() const { + return radius; + } /** * Check the intersection between the cylinder and an infinite ray. * * Returns the number of intersections (0, 1 or 2) and fill the intersection points. */ - int checkRayIntersection(const InfiniteRay& ray, Vector3 *first_intersection, Vector3 *second_intersection) const; + int checkRayIntersection(const InfiniteRay &ray, Vector3 *first_intersection, Vector3 *second_intersection) const; virtual void save(PackStream *stream) const; virtual void load(PackStream *stream); -protected: + protected: InfiniteRay axis; double radius; }; - } } diff --git a/src/basics/InfinitePlane.cpp b/src/basics/InfinitePlane.cpp index a4b9ba8..eed1a7a 100644 --- a/src/basics/InfinitePlane.cpp +++ b/src/basics/InfinitePlane.cpp @@ -3,28 +3,20 @@ #include "PackStream.h" #include "InfiniteRay.h" -InfinitePlane::InfinitePlane() -{ +InfinitePlane::InfinitePlane() { } -InfinitePlane::InfinitePlane(const Vector3 &point, const Vector3 &normal): - point(point), normal(normal) -{ +InfinitePlane::InfinitePlane(const Vector3 &point, const Vector3 &normal) : point(point), normal(normal) { } -int InfinitePlane::checkRayIntersection(const InfiniteRay &ray, Vector3 *intersection) const -{ +int InfinitePlane::checkRayIntersection(const InfiniteRay &ray, Vector3 *intersection) const { Vector3 p1 = ray.getDirection(); double d = normal.dotProduct(p1); - if (fabs(d) < 1e-8) - { - if (normal.dotProduct(ray.getPointAtCursor(1.0).sub(point)) == 0) - { + if (fabs(d) < 1e-8) { + if (normal.dotProduct(ray.getPointAtCursor(1.0).sub(point)) == 0) { return -1; - } - else - { + } else { return 0; } } @@ -34,15 +26,12 @@ int InfinitePlane::checkRayIntersection(const InfiniteRay &ray, Vector3 *interse return 1; } -void InfinitePlane::save(PackStream *stream) const -{ +void InfinitePlane::save(PackStream *stream) const { point.save(stream); normal.save(stream); } -void InfinitePlane::load(PackStream *stream) -{ +void InfinitePlane::load(PackStream *stream) { point.load(stream); normal.load(stream); } - diff --git a/src/basics/InfinitePlane.h b/src/basics/InfinitePlane.h index e697311..e0198da 100644 --- a/src/basics/InfinitePlane.h +++ b/src/basics/InfinitePlane.h @@ -11,9 +11,8 @@ namespace basics { /** * Infinite 3d geometric plane. */ -class BASICSSHARED_EXPORT InfinitePlane -{ -public: +class BASICSSHARED_EXPORT InfinitePlane { + public: InfinitePlane(); InfinitePlane(const Vector3 &point, const Vector3 &normal); @@ -24,19 +23,22 @@ public: * * Returns -1 if the ray is on the plane, and make for an infinite number of intersection points. */ - int checkRayIntersection(const InfiniteRay& ray, Vector3 *intersection) const; + int checkRayIntersection(const InfiniteRay &ray, Vector3 *intersection) const; - inline const Vector3 &getPoint() const {return point;} - inline const Vector3 &getNormal() const {return normal;} + inline const Vector3 &getPoint() const { + return point; + } + inline const Vector3 &getNormal() const { + return normal; + } virtual void save(PackStream *stream) const; virtual void load(PackStream *stream); -private: + private: Vector3 point; Vector3 normal; }; - } } diff --git a/src/basics/InfiniteRay.cpp b/src/basics/InfiniteRay.cpp index f3baa08..8bf68b8 100644 --- a/src/basics/InfiniteRay.cpp +++ b/src/basics/InfiniteRay.cpp @@ -1,27 +1,22 @@ #include "InfiniteRay.h" -InfiniteRay::InfiniteRay() -{ +InfiniteRay::InfiniteRay() { } -InfiniteRay::InfiniteRay(const Vector3 &origin, const Vector3 &direction): - origin(origin), direction(direction.normalize()) -{ +InfiniteRay::InfiniteRay(const Vector3 &origin, const Vector3 &direction) + : origin(origin), direction(direction.normalize()) { } -InfiniteRay InfiniteRay::fromPoints(const Vector3 &point1, const Vector3 &point2) -{ +InfiniteRay InfiniteRay::fromPoints(const Vector3 &point1, const Vector3 &point2) { return InfiniteRay(point1, point2.sub(point1).normalize()); } -void InfiniteRay::save(PackStream *stream) const -{ +void InfiniteRay::save(PackStream *stream) const { origin.save(stream); direction.save(stream); } -void InfiniteRay::load(PackStream *stream) -{ +void InfiniteRay::load(PackStream *stream) { origin.load(stream); direction.load(stream); } diff --git a/src/basics/InfiniteRay.h b/src/basics/InfiniteRay.h index 0c12ccf..cbae484 100644 --- a/src/basics/InfiniteRay.h +++ b/src/basics/InfiniteRay.h @@ -11,28 +11,34 @@ namespace basics { /** * Infinite ray (line). */ -class BASICSSHARED_EXPORT InfiniteRay -{ -public: +class BASICSSHARED_EXPORT InfiniteRay { + public: InfiniteRay(); InfiniteRay(const Vector3 &origin, const Vector3 &direction); static InfiniteRay fromPoints(const Vector3 &point1, const Vector3 &point2); - inline const Vector3 &getOrigin() const {return origin;} - inline const Vector3 &getDirection() const {return direction;} + inline const Vector3 &getOrigin() const { + return origin; + } + inline const Vector3 &getDirection() const { + return direction; + } - inline double getCursor(const Vector3 &point) const {return point.sub(origin).dotProduct(direction);} - inline Vector3 getPointAtCursor(double distance) const {return origin.add(direction.scale(distance));} + inline double getCursor(const Vector3 &point) const { + return point.sub(origin).dotProduct(direction); + } + inline Vector3 getPointAtCursor(double distance) const { + return origin.add(direction.scale(distance)); + } void save(PackStream *stream) const; void load(PackStream *stream); -private: + private: Vector3 origin; Vector3 direction; }; - } } diff --git a/src/basics/Interpolation.cpp b/src/basics/Interpolation.cpp index 9ea3c6c..eac6846 100644 --- a/src/basics/Interpolation.cpp +++ b/src/basics/Interpolation.cpp @@ -1,7 +1,6 @@ #include "Interpolation.h" -double Interpolation::bicubic(double stencil[16], double x, double y) -{ +double Interpolation::bicubic(double stencil[16], double x, double y) { double buf_cubic_y[4]; buf_cubic_y[0] = Interpolation::cubic(stencil, x); @@ -12,15 +11,13 @@ double Interpolation::bicubic(double stencil[16], double x, double y) return Interpolation::cubic(buf_cubic_y, y); } -double Interpolation::bilinear(double p[4], double x, double y) -{ +double Interpolation::bilinear(double p[4], double x, double y) { double e1 = linear(p[0], p[1], x); double e2 = linear(p[3], p[2], x); return Interpolation::linear(e1, e2, y); } -double Interpolation::trilinear(double p[8], double x, double y, double z) -{ +double Interpolation::trilinear(double p[8], double x, double y, double z) { double f1 = bilinear(p, x, y); double f2 = bilinear(p + 4, x, y); return Interpolation::linear(f1, f2, z); diff --git a/src/basics/Interpolation.h b/src/basics/Interpolation.h index 77f35c5..2b3a90b 100644 --- a/src/basics/Interpolation.h +++ b/src/basics/Interpolation.h @@ -6,23 +6,21 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT Interpolation -{ -public: - static inline double linear(double p1, double p2, double x) - { +class BASICSSHARED_EXPORT Interpolation { + public: + static inline double linear(double p1, double p2, double x) { return p1 + x * (p2 - p1); } static double bilinear(double p[4], double x, double y); static double trilinear(double p[8], double x, double y, double z); - static inline double cubic(double p[4], double x) - { - return p[1] + 0.5 * x * (p[2] - p[0] + x * (2.0 * p[0] - 5.0 * p[1] + 4.0 * p[2] - p[3] + x * (3.0 * (p[1] - p[2]) + p[3] - p[0]))); + static inline double cubic(double p[4], double x) { + return p[1] + + 0.5 * x * (p[2] - p[0] + + x * (2.0 * p[0] - 5.0 * p[1] + 4.0 * p[2] - p[3] + x * (3.0 * (p[1] - p[2]) + p[3] - p[0]))); } static double bicubic(double stencil[16], double x, double y); }; - } } diff --git a/src/basics/Matrix4.cpp b/src/basics/Matrix4.cpp index b32fc05..69265cf 100644 --- a/src/basics/Matrix4.cpp +++ b/src/basics/Matrix4.cpp @@ -4,15 +4,13 @@ #include "PackStream.h" #include "Vector3.h" -Matrix4::Matrix4(bool identity) -{ +Matrix4::Matrix4(bool identity) { b = c = d = e = g = h = 0.0; i = j = l = m = n = o = 0.0; a = f = k = p = (identity ? 1.0 : 0.0); } -void Matrix4::save(PackStream* stream) const -{ +void Matrix4::save(PackStream *stream) const { stream->write(&a); stream->write(&b); stream->write(&c); @@ -31,8 +29,7 @@ void Matrix4::save(PackStream* stream) const stream->write(&p); } -void Matrix4::load(PackStream* stream) -{ +void Matrix4::load(PackStream *stream) { stream->read(&a); stream->read(&b); stream->read(&c); @@ -51,8 +48,7 @@ void Matrix4::load(PackStream* stream) stream->read(&p); } -Matrix4 Matrix4::mult(const Matrix4 &other) const -{ +Matrix4 Matrix4::mult(const Matrix4 &other) const { Matrix4 result; result.a = a * other.a + b * other.e + c * other.i + d * other.m; result.b = a * other.b + b * other.f + c * other.j + d * other.n; @@ -73,8 +69,7 @@ Matrix4 Matrix4::mult(const Matrix4 &other) const return result; } -Vector3 Matrix4::multPoint(const Vector3 &v) const -{ +Vector3 Matrix4::multPoint(const Vector3 &v) const { Vector3 result; result.x = a * v.x + b * v.y + c * v.z + d; result.y = e * v.x + f * v.y + g * v.z + h; @@ -82,30 +77,19 @@ Vector3 Matrix4::multPoint(const Vector3 &v) const return result; } -Vector3 Matrix4::transform(const Vector3 &v) const -{ +Vector3 Matrix4::transform(const Vector3 &v) const { double w = m * v.x + n * v.y + o * v.z + p; - if (w != 0.0) - { + if (w != 0.0) { w = 1.0 / w; - return Vector3( - (a * v.x + b * v.y + c * v.z + d) * w, - (e * v.x + f * v.y + g * v.z + h) * w, - (i * v.x + j * v.y + k * v.z + l) * w - ); - } - else - { - return Vector3( - a * v.x + b * v.y + c * v.z + d, - e * v.x + f * v.y + g * v.z + h, - i * v.x + j * v.y + k * v.z + l - ); + return Vector3((a * v.x + b * v.y + c * v.z + d) * w, (e * v.x + f * v.y + g * v.z + h) * w, + (i * v.x + j * v.y + k * v.z + l) * w); + } else { + return Vector3(a * v.x + b * v.y + c * v.z + d, e * v.x + f * v.y + g * v.z + h, + i * v.x + j * v.y + k * v.z + l); } } -Matrix4 Matrix4::transposed() const -{ +Matrix4 Matrix4::transposed() const { Matrix4 result; result.a = a; result.e = b; @@ -126,8 +110,7 @@ Matrix4 Matrix4::transposed() const return result; } -Matrix4 Matrix4::newScale(double x, double y, double z) -{ +Matrix4 Matrix4::newScale(double x, double y, double z) { Matrix4 result; result.a = x; result.f = y; @@ -135,8 +118,7 @@ Matrix4 Matrix4::newScale(double x, double y, double z) return result; } -Matrix4 Matrix4::newTranslate(double x, double y, double z) -{ +Matrix4 Matrix4::newTranslate(double x, double y, double z) { Matrix4 result; result.d = x; result.h = y; @@ -144,8 +126,7 @@ Matrix4 Matrix4::newTranslate(double x, double y, double z) return result; } -Matrix4 Matrix4::newRotateX(double angle) -{ +Matrix4 Matrix4::newRotateX(double angle) { Matrix4 result; double si = sin(angle); double co = cos(angle); @@ -155,8 +136,7 @@ Matrix4 Matrix4::newRotateX(double angle) return result; } -Matrix4 Matrix4::newRotateY(double angle) -{ +Matrix4 Matrix4::newRotateY(double angle) { Matrix4 result; double si = sin(angle); double co = cos(angle); @@ -166,8 +146,7 @@ Matrix4 Matrix4::newRotateY(double angle) return result; } -Matrix4 Matrix4::newRotateZ(double angle) -{ +Matrix4 Matrix4::newRotateZ(double angle) { Matrix4 result; double si = sin(angle); double co = cos(angle); @@ -177,8 +156,7 @@ Matrix4 Matrix4::newRotateZ(double angle) return result; } -Matrix4 Matrix4::newRotateAxis(double angle, const Vector3 &_axis) -{ +Matrix4 Matrix4::newRotateAxis(double angle, const Vector3 &_axis) { Matrix4 result; double si = sin(angle); double co = cos(angle); @@ -196,8 +174,7 @@ Matrix4 Matrix4::newRotateAxis(double angle, const Vector3 &_axis) return result; } -Matrix4 Matrix4::newRotateEuler(double heading, double attitude, double bank) -{ +Matrix4 Matrix4::newRotateEuler(double heading, double attitude, double bank) { Matrix4 result; double ch = cos(heading); double sh = sin(heading); @@ -217,8 +194,7 @@ Matrix4 Matrix4::newRotateEuler(double heading, double attitude, double bank) return result; } -Matrix4 Matrix4::newRotateTripleAxis(const Vector3 &x, const Vector3 &y, const Vector3 &z) -{ +Matrix4 Matrix4::newRotateTripleAxis(const Vector3 &x, const Vector3 &y, const Vector3 &z) { Matrix4 result; result.a = x.x; result.b = y.x; @@ -232,8 +208,7 @@ Matrix4 Matrix4::newRotateTripleAxis(const Vector3 &x, const Vector3 &y, const V return result; } -Matrix4 Matrix4::newLookAt(const Vector3 &eye, const Vector3 &at, const Vector3 &up) -{ +Matrix4 Matrix4::newLookAt(const Vector3 &eye, const Vector3 &at, const Vector3 &up) { Vector3 z = at.sub(eye).normalize(); Vector3 x = up.crossProduct(z).normalize(); Vector3 y = z.crossProduct(x); @@ -244,8 +219,7 @@ Matrix4 Matrix4::newLookAt(const Vector3 &eye, const Vector3 &at, const Vector3 return result.inversed(); } -Matrix4 Matrix4::newPerspective(double fov_y, double aspect, double near, double far) -{ +Matrix4 Matrix4::newPerspective(double fov_y, double aspect, double near, double far) { Matrix4 result; double fo = 1 / tan(fov_y / 2.0); result.a = fo / aspect; @@ -257,29 +231,16 @@ Matrix4 Matrix4::newPerspective(double fov_y, double aspect, double near, double return result; } -double Matrix4::getDeterminant() const -{ - return ((a * f - e * b) - * (k * p - o * l) - - (a * j - i * b) - * (g * p - o * h) - + (a * n - m * b) - * (g * l - k * h) - + (e * j - i * f) - * (c * p - o * d) - - (e * n - m * f) - * (c * l - k * d) - + (i * n - m * j) - * (c * h - g * d)); +double Matrix4::getDeterminant() const { + return ((a * f - e * b) * (k * p - o * l) - (a * j - i * b) * (g * p - o * h) + (a * n - m * b) * (g * l - k * h) + + (e * j - i * f) * (c * p - o * d) - (e * n - m * f) * (c * l - k * d) + (i * n - m * j) * (c * h - g * d)); } -Matrix4 Matrix4::inversed() const -{ +Matrix4 Matrix4::inversed() const { Matrix4 result; double det = getDeterminant(); - if (fabs(det) >= 0.00001) - { + if (fabs(det) >= 0.00001) { det = 1.0 / det; result.a = det * (f * (k * p - o * l) + j * (o * h - g * p) + n * (g * l - k * h)); @@ -301,7 +262,6 @@ Matrix4 Matrix4::inversed() const result.h = det * (c * (i * h - e * l) + g * (a * l - i * d) + k * (e * d - a * h)); result.l = det * (d * (i * f - e * j) + h * (a * j - i * b) + l * (e * b - a * f)); result.p = det * (a * (f * k - j * g) + e * (j * c - b * k) + i * (b * g - f * c)); - } return result; diff --git a/src/basics/Matrix4.h b/src/basics/Matrix4.h index 03c454f..5f185d1 100644 --- a/src/basics/Matrix4.h +++ b/src/basics/Matrix4.h @@ -10,13 +10,12 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT Matrix4 -{ -public: - Matrix4(bool identity=true); +class BASICSSHARED_EXPORT Matrix4 { + public: + Matrix4(bool identity = true); - void save(PackStream* stream) const; - void load(PackStream* stream); + void save(PackStream *stream) const; + void load(PackStream *stream); Matrix4 mult(const Matrix4 &other) const; Vector3 multPoint(const Vector3 &v) const; @@ -39,14 +38,11 @@ public: #ifdef QT_GUI_LIB inline QMatrix4x4 toQMatrix() const { - return QMatrix4x4(a, b, c, d, - e, f, g, h, - i, j, k, l, - m, n, o, p); + return QMatrix4x4(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p); } #endif -private: + private: double a; double b; double c; @@ -64,7 +60,6 @@ private: double o; double p; }; - } } diff --git a/src/basics/NoiseFunctionPerlin.cpp b/src/basics/NoiseFunctionPerlin.cpp index 761b38b..2b3117d 100644 --- a/src/basics/NoiseFunctionPerlin.cpp +++ b/src/basics/NoiseFunctionPerlin.cpp @@ -9,15 +9,14 @@ #include #include -NoiseFunctionPerlin::NoiseFunctionPerlin() -{ +NoiseFunctionPerlin::NoiseFunctionPerlin() { } #define B 0x100 #define BM 0xff #define N 0x1000 -#define NP 12 /* 2^N */ +#define NP 12 /* 2^N */ #define NM 0xfff static int p[B + B + 2]; @@ -25,108 +24,117 @@ static double g3[B + B + 2][3]; static double g2[B + B + 2][2]; static double g1[B + B + 2]; -#define s_curve(t) ( t * t * (3. - 2. * t) ) +#define s_curve(t) (t * t * (3. - 2. * t)) -#define lerp(t, a, b) ( a + t * (b - a) ) +#define lerp(t, a, b) (a + t * (b - a)) -#define setup(i,b0,b1,r0,r1)\ - t = vec[i] + N;\ - b0 = ((int)t) & BM;\ - b1 = (b0+1) & BM;\ - r0 = t - (int)t;\ +#define setup(i, b0, b1, r0, r1) \ + t = vec[i] + N; \ + b0 = ((int)t) & BM; \ + b1 = (b0 + 1) & BM; \ + r0 = t - (int)t; \ r1 = r0 - 1.; -double noisePerlinGet1DValue(double x) -{ - double vec[1] = {x*2.0}; +double noisePerlinGet1DValue(double x) { + double vec[1] = {x * 2.0}; int bx0, bx1; double rx0, rx1, sx, t, u, v; - setup(0, bx0,bx1, rx0,rx1); + setup(0, bx0, bx1, rx0, rx1); sx = s_curve(rx0); - u = rx0 * g1[ p[ bx0 ] ]; - v = rx1 * g1[ p[ bx1 ] ]; + u = rx0 * g1[p[bx0]]; + v = rx1 * g1[p[bx1]]; return lerp(sx, u, v) * 1.068 + 0.5; } -double noisePerlinGet2DValue(double x, double y) -{ - double vec[2] = {x*2.0, y*2.0}; +double noisePerlinGet2DValue(double x, double y) { + double vec[2] = {x * 2.0, y * 2.0}; int bx0, bx1, by0, by1, b00, b10, b01, b11; double rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v; int i, j; - setup(0, bx0,bx1, rx0,rx1); - setup(1, by0,by1, ry0,ry1); + setup(0, bx0, bx1, rx0, rx1); + setup(1, by0, by1, ry0, ry1); - i = p[ bx0 ]; - j = p[ bx1 ]; + i = p[bx0]; + j = p[bx1]; - b00 = p[ i + by0 ]; - b10 = p[ j + by0 ]; - b01 = p[ i + by1 ]; - b11 = p[ j + by1 ]; + b00 = p[i + by0]; + b10 = p[j + by0]; + b01 = p[i + by1]; + b11 = p[j + by1]; sx = s_curve(rx0); sy = s_curve(ry0); -#define at2(rx,ry) ( rx * q[0] + ry * q[1] ) +#define at2(rx, ry) (rx * q[0] + ry * q[1]) - q = g2[ b00 ] ; u = at2(rx0,ry0); - q = g2[ b10 ] ; v = at2(rx1,ry0); + q = g2[b00]; + u = at2(rx0, ry0); + q = g2[b10]; + v = at2(rx1, ry0); a = lerp(sx, u, v); - q = g2[ b01 ] ; u = at2(rx0,ry1); - q = g2[ b11 ] ; v = at2(rx1,ry1); + q = g2[b01]; + u = at2(rx0, ry1); + q = g2[b11]; + v = at2(rx1, ry1); b = lerp(sx, u, v); return lerp(sy, a, b) * 0.709 + 0.5; } -double noisePerlinGet3DValue(double x, double y, double z) -{ - double vec[3] = {x*2.0, y*2.0, z*2.0}; +double noisePerlinGet3DValue(double x, double y, double z) { + double vec[3] = {x * 2.0, y * 2.0, z * 2.0}; int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11; double rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v; int i, j; - setup(0, bx0,bx1, rx0,rx1); - setup(1, by0,by1, ry0,ry1); - setup(2, bz0,bz1, rz0,rz1); + setup(0, bx0, bx1, rx0, rx1); + setup(1, by0, by1, ry0, ry1); + setup(2, bz0, bz1, rz0, rz1); - i = p[ bx0 ]; - j = p[ bx1 ]; + i = p[bx0]; + j = p[bx1]; - b00 = p[ i + by0 ]; - b10 = p[ j + by0 ]; - b01 = p[ i + by1 ]; - b11 = p[ j + by1 ]; + b00 = p[i + by0]; + b10 = p[j + by0]; + b01 = p[i + by1]; + b11 = p[j + by1]; - t = s_curve(rx0); + t = s_curve(rx0); sy = s_curve(ry0); sz = s_curve(rz0); -#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] ) +#define at3(rx, ry, rz) (rx * q[0] + ry * q[1] + rz * q[2]) - q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0); - q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0); + q = g3[b00 + bz0]; + u = at3(rx0, ry0, rz0); + q = g3[b10 + bz0]; + v = at3(rx1, ry0, rz0); a = lerp(t, u, v); - q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0); - q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0); + q = g3[b01 + bz0]; + u = at3(rx0, ry1, rz0); + q = g3[b11 + bz0]; + v = at3(rx1, ry1, rz0); b = lerp(t, u, v); c = lerp(sy, a, b); - q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1); - q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1); + q = g3[b00 + bz1]; + u = at3(rx0, ry0, rz1); + q = g3[b10 + bz1]; + v = at3(rx1, ry0, rz1); a = lerp(t, u, v); - q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1); - q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1); + q = g3[b01 + bz1]; + u = at3(rx0, ry1, rz1); + q = g3[b11 + bz1]; + v = at3(rx1, ry1, rz1); b = lerp(t, u, v); d = lerp(sy, a, b); @@ -134,8 +142,7 @@ double noisePerlinGet3DValue(double x, double y, double z) return lerp(sz, c, d) * 0.661 + 0.5; } -static void _normalize2(double v[2]) -{ +static void _normalize2(double v[2]) { double s; s = sqrt(v[0] * v[0] + v[1] * v[1]); @@ -143,8 +150,7 @@ static void _normalize2(double v[2]) v[1] = v[1] / s; } -static void _normalize3(double v[3]) -{ +static void _normalize3(double v[3]) { double s; s = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); @@ -153,20 +159,19 @@ static void _normalize3(double v[3]) v[2] = v[2] / s; } -static int noisePerlinInit(void) -{ +static int noisePerlinInit(void) { int i, j, k; - for (i = 0 ; i < B ; i++) { + for (i = 0; i < B; i++) { p[i] = i; g1[i] = (double)((rand() % (B + B)) - B) / B; - for (j = 0 ; j < 2 ; j++) + for (j = 0; j < 2; j++) g2[i][j] = (double)((rand() % (B + B)) - B) / B; _normalize2(g2[i]); - for (j = 0 ; j < 3 ; j++) + for (j = 0; j < 3; j++) g3[i][j] = (double)((rand() % (B + B)) - B) / B; _normalize3(g3[i]); } @@ -177,12 +182,12 @@ static int noisePerlinInit(void) p[j] = k; } - for (i = 0 ; i < B + 2 ; i++) { + for (i = 0; i < B + 2; i++) { p[B + i] = p[i]; g1[B + i] = g1[i]; - for (j = 0 ; j < 2 ; j++) + for (j = 0; j < 2; j++) g2[B + i][j] = g2[i][j]; - for (j = 0 ; j < 3 ; j++) + for (j = 0; j < 3; j++) g3[B + i][j] = g3[i][j]; } diff --git a/src/basics/NoiseFunctionPerlin.h b/src/basics/NoiseFunctionPerlin.h index f9c6906..71c38d9 100644 --- a/src/basics/NoiseFunctionPerlin.h +++ b/src/basics/NoiseFunctionPerlin.h @@ -6,12 +6,10 @@ namespace paysages { namespace basics { -class NoiseFunctionPerlin -{ -public: +class NoiseFunctionPerlin { + public: NoiseFunctionPerlin(); }; - } } diff --git a/src/basics/NoiseFunctionSimplex.cpp b/src/basics/NoiseFunctionSimplex.cpp index d996db1..21c8acf 100644 --- a/src/basics/NoiseFunctionSimplex.cpp +++ b/src/basics/NoiseFunctionSimplex.cpp @@ -14,84 +14,78 @@ #include "Geometry.h" #include "Vector3.h" -typedef struct -{ +typedef struct { double x; double y; double z; } Grad3; -typedef struct -{ +typedef struct { double x; double y; double z; double w; } Grad4; -static Grad3 _grad3[] = { - {1, 1, 0}, - {-1, 1, 0}, - {1, -1, 0}, - {-1, -1, 0}, - {1, 0, 1}, - {-1, 0, 1}, - {1, 0, -1}, - {-1, 0, -1}, - {0, 1, 1}, - {0, -1, 1}, - {0, 1, -1}, - {0, -1, -1} -}; +static Grad3 _grad3[] = {{1, 1, 0}, + {-1, 1, 0}, + {1, -1, 0}, + {-1, -1, 0}, + {1, 0, 1}, + {-1, 0, 1}, + {1, 0, -1}, + {-1, 0, -1}, + {0, 1, 1}, + {0, -1, 1}, + {0, 1, -1}, + {0, -1, -1}}; -static Grad4 _grad4[] = { - {0, 1, 1, 1}, - {0, 1, 1, -1}, - {0, 1, -1, 1}, - {0, 1, -1, -1}, - {0, -1, 1, 1}, - {0, -1, 1, -1}, - {0, -1, -1, 1}, - {0, -1, -1, -1}, - {1, 0, 1, 1}, - {1, 0, 1, -1}, - {1, 0, -1, 1}, - {1, 0, -1, -1}, - {-1, 0, 1, 1}, - {-1, 0, 1, -1}, - {-1, 0, -1, 1}, - {-1, 0, -1, -1}, - {1, 1, 0, 1}, - {1, 1, 0, -1}, - {1, -1, 0, 1}, - {1, -1, 0, -1}, - {-1, 1, 0, 1}, - {-1, 1, 0, -1}, - {-1, -1, 0, 1}, - {-1, -1, 0, -1}, - {1, 1, 1, 0}, - {1, 1, -1, 0}, - {1, -1, 1, 0}, - {1, -1, -1, 0}, - {-1, 1, 1, 0}, - {-1, 1, -1, 0}, - {-1, -1, 1, 0}, - {-1, -1, -1, 0} -}; +static Grad4 _grad4[] = {{0, 1, 1, 1}, + {0, 1, 1, -1}, + {0, 1, -1, 1}, + {0, 1, -1, -1}, + {0, -1, 1, 1}, + {0, -1, 1, -1}, + {0, -1, -1, 1}, + {0, -1, -1, -1}, + {1, 0, 1, 1}, + {1, 0, 1, -1}, + {1, 0, -1, 1}, + {1, 0, -1, -1}, + {-1, 0, 1, 1}, + {-1, 0, 1, -1}, + {-1, 0, -1, 1}, + {-1, 0, -1, -1}, + {1, 1, 0, 1}, + {1, 1, 0, -1}, + {1, -1, 0, 1}, + {1, -1, 0, -1}, + {-1, 1, 0, 1}, + {-1, 1, 0, -1}, + {-1, -1, 0, 1}, + {-1, -1, 0, -1}, + {1, 1, 1, 0}, + {1, 1, -1, 0}, + {1, -1, 1, 0}, + {1, -1, -1, 0}, + {-1, 1, 1, 0}, + {-1, 1, -1, 0}, + {-1, -1, 1, 0}, + {-1, -1, -1, 0}}; -static short _permutations[] = {151, 160, 137, 91, 90, 15, - 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, - 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, - 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, - 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, - 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, - 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, - 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, - 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, - 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, - 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, - 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, - 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180}; +static short _permutations[] = { + 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, + 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, + 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, + 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, + 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, + 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, + 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, + 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, + 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, + 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, + 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, + 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180}; static short _permutations2[512]; static short _permutationsMod12[512]; @@ -102,36 +96,30 @@ static double _G3; static double _F4; static double _G4; -static inline int _fastfloor(double x) -{ - int xi = (int) x; +static inline int _fastfloor(double x) { + int xi = (int)x; return x < xi ? xi - 1 : xi; } -static inline double _dot2(Grad3 g, double x, double y) -{ +static inline double _dot2(Grad3 g, double x, double y) { return g.x * x + g.y * y; } -static inline double _dot3(Grad3 g, double x, double y, double z) -{ +static inline double _dot3(Grad3 g, double x, double y, double z) { return g.x * x + g.y * y + g.z * z; } -static inline double _dot4(Grad4 g, double x, double y, double z, double w) -{ +static inline double _dot4(Grad4 g, double x, double y, double z, double w) { return g.x * x + g.y * y + g.z * z + g.w * w; } -static int noiseSimplexInit() -{ +static int noiseSimplexInit() { int i; /* To remove the need for index wrapping, double the permutation table length */ - for (i = 0; i < 512; i++) - { + for (i = 0; i < 512; i++) { _permutations2[i] = _permutations[i & 255]; - _permutationsMod12[i] = (short) (_permutations2[i] % 12); + _permutationsMod12[i] = (short)(_permutations2[i] % 12); } /* Skewing and unskewing factors for 2, 3, and 4 dimensions */ @@ -147,14 +135,12 @@ static int noiseSimplexInit() static int _inited = noiseSimplexInit(); -double noiseSimplexGet1DValue(double x) -{ +double noiseSimplexGet1DValue(double x) { /* TODO Find custom function */ return noiseSimplexGet2DValue(x, 0.0); } -double noiseSimplexGet2DValue(double x, double y) -{ +double noiseSimplexGet2DValue(double x, double y) { double n0, n1, n2; /* Noise contributions from the three corners */ /* Skew the input space to determine which simplex cell we're in */ double s = (x + y) * _F2; /* Hairy factor for 2D */ @@ -168,19 +154,17 @@ double noiseSimplexGet2DValue(double x, double y) /* For the 2D case, the simplex shape is an equilateral triangle. Determine which simplex we are in. */ int i1, j1; /* Offsets for second (middle) corner of simplex in (i,j) coords */ - if (x0 > y0) - { + if (x0 > y0) { i1 = 1; j1 = 0; } /* lower triangle, XY order: (0,0)->(1,0)->(1,1) */ - else - { + else { i1 = 0; j1 = 1; - } /* upper triangle, YX order: (0,0)->(0,1)->(1,1) */ - /* A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and - a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where - c = (3-sqrt(3))/6 */ + } /* upper triangle, YX order: (0,0)->(0,1)->(1,1) */ + /* A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and + a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where + c = (3-sqrt(3))/6 */ double x1 = x0 - i1 + _G2; /* Offsets for middle corner in (x,y) unskewed coords */ double y1 = y0 - j1 + _G2; double x2 = x0 - 1.0 + 2.0 * _G2; /* Offsets for last corner in (x,y) unskewed coords */ @@ -192,24 +176,24 @@ double noiseSimplexGet2DValue(double x, double y) int gi1 = _permutationsMod12[ii + i1 + _permutations2[jj + j1]]; int gi2 = _permutationsMod12[ii + 1 + _permutations2[jj + 1]]; /* Calculate the contribution from the three corners */ - double t0 = 0.5 - x0 * x0 - y0*y0; - if (t0 < 0) n0 = 0.0; - else - { + double t0 = 0.5 - x0 * x0 - y0 * y0; + if (t0 < 0) + n0 = 0.0; + else { t0 *= t0; n0 = t0 * t0 * _dot2(_grad3[gi0], x0, y0); /* (x,y) of _grad3 used for 2D gradient */ } - double t1 = 0.5 - x1 * x1 - y1*y1; - if (t1 < 0) n1 = 0.0; - else - { + double t1 = 0.5 - x1 * x1 - y1 * y1; + if (t1 < 0) + n1 = 0.0; + else { t1 *= t1; n1 = t1 * t1 * _dot2(_grad3[gi1], x1, y1); } - double t2 = 0.5 - x2 * x2 - y2*y2; - if (t2 < 0) n2 = 0.0; - else - { + double t2 = 0.5 - x2 * x2 - y2 * y2; + if (t2 < 0) + n2 = 0.0; + else { t2 *= t2; n2 = t2 * t2 * _dot2(_grad3[gi2], x2, y2); } @@ -218,8 +202,7 @@ double noiseSimplexGet2DValue(double x, double y) return 35.0 * (n0 + n1 + n2) + 0.5; } -double noiseSimplexGet3DValue(double x, double y, double z) -{ +double noiseSimplexGet3DValue(double x, double y, double z) { double n0, n1, n2, n3; /* Noise contributions from the four corners */ /* Skew the input space to determine which simplex cell we're in */ double s = (x + y + z) * _F3; /* Very nice and simple skew factor for 3D */ @@ -237,10 +220,8 @@ double noiseSimplexGet3DValue(double x, double y, double z) Determine which simplex we are in. */ int i1, j1, k1; /* Offsets for second corner of simplex in (i,j,k) coords */ int i2, j2, k2; /* Offsets for third corner of simplex in (i,j,k) coords */ - if (x0 >= y0) - { - if (y0 >= z0) - { + if (x0 >= y0) { + if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; @@ -248,8 +229,7 @@ double noiseSimplexGet3DValue(double x, double y, double z) j2 = 1; k2 = 0; } /* X Y Z order */ - else if (x0 >= z0) - { + else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; @@ -257,20 +237,16 @@ double noiseSimplexGet3DValue(double x, double y, double z) j2 = 0; k2 = 1; } /* X Z Y order */ - else - { + else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; - } /* Z X Y order */ - } - else - { /* x0 y0) rankx++; - else ranky++; - if (x0 > z0) rankx++; - else rankz++; - if (x0 > w0) rankx++; - else rankw++; - if (y0 > z0) ranky++; - else rankz++; - if (y0 > w0) ranky++; - else rankw++; - if (z0 > w0) rankz++; - else rankw++; + if (x0 > y0) + rankx++; + else + ranky++; + if (x0 > z0) + rankx++; + else + rankz++; + if (x0 > w0) + rankx++; + else + rankw++; + if (y0 > z0) + ranky++; + else + rankz++; + if (y0 > w0) + ranky++; + else + rankw++; + if (z0 > w0) + rankz++; + else + rankw++; int i1, j1, k1, l1; /* The integer offsets for the second simplex corner */ int i2, j2, k2, l2; /* The integer offsets for the third simplex corner */ int i3, j3, k3, l3; /* The integer offsets for the fourth simplex corner */ - /* simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. - Many values of c will never occur, since e.g. x>y>z>w makes xy>z>w makes x= 3 ? 1 : 0; j1 = ranky >= 3 ? 1 : 0; k1 = rankz >= 3 ? 1 : 0; @@ -436,43 +421,46 @@ double noiseSimplexGet4DValue(double x, double y, double z, double w) int kk = k & 255; int ll = l & 255; int gi0 = _permutations2[ii + _permutations2[jj + _permutations2[kk + _permutations2[ll]]]] % 32; - int gi1 = _permutations2[ii + i1 + _permutations2[jj + j1 + _permutations2[kk + k1 + _permutations2[ll + l1]]]] % 32; - int gi2 = _permutations2[ii + i2 + _permutations2[jj + j2 + _permutations2[kk + k2 + _permutations2[ll + l2]]]] % 32; - int gi3 = _permutations2[ii + i3 + _permutations2[jj + j3 + _permutations2[kk + k3 + _permutations2[ll + l3]]]] % 32; + int gi1 = + _permutations2[ii + i1 + _permutations2[jj + j1 + _permutations2[kk + k1 + _permutations2[ll + l1]]]] % 32; + int gi2 = + _permutations2[ii + i2 + _permutations2[jj + j2 + _permutations2[kk + k2 + _permutations2[ll + l2]]]] % 32; + int gi3 = + _permutations2[ii + i3 + _permutations2[jj + j3 + _permutations2[kk + k3 + _permutations2[ll + l3]]]] % 32; int gi4 = _permutations2[ii + 1 + _permutations2[jj + 1 + _permutations2[kk + 1 + _permutations2[ll + 1]]]] % 32; /* Calculate the contribution from the five corners */ - double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0*w0; - if (t0 < 0) n0 = 0.0; - else - { + double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; + if (t0 < 0) + n0 = 0.0; + else { t0 *= t0; n0 = t0 * t0 * _dot4(_grad4[gi0], x0, y0, z0, w0); } - double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1*w1; - if (t1 < 0) n1 = 0.0; - else - { + double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; + if (t1 < 0) + n1 = 0.0; + else { t1 *= t1; n1 = t1 * t1 * _dot4(_grad4[gi1], x1, y1, z1, w1); } - double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2*w2; - if (t2 < 0) n2 = 0.0; - else - { + double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; + if (t2 < 0) + n2 = 0.0; + else { t2 *= t2; n2 = t2 * t2 * _dot4(_grad4[gi2], x2, y2, z2, w2); } - double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3*w3; - if (t3 < 0) n3 = 0.0; - else - { + double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; + if (t3 < 0) + n3 = 0.0; + else { t3 *= t3; n3 = t3 * t3 * _dot4(_grad4[gi3], x3, y3, z3, w3); } - double t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4*w4; - if (t4 < 0) n4 = 0.0; - else - { + double t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; + if (t4 < 0) + n4 = 0.0; + else { t4 *= t4; n4 = t4 * t4 * _dot4(_grad4[gi4], x4, y4, z4, w4); } @@ -480,31 +468,25 @@ double noiseSimplexGet4DValue(double x, double y, double z, double w) return 13.5 * (n0 + n1 + n2 + n3 + n4) + 0.5; } -double NoiseFunctionSimplex::getBase2d(double x, double y) const -{ +double NoiseFunctionSimplex::getBase2d(double x, double y) const { return noiseSimplexGet2DValue(x, y); } -double NoiseFunctionSimplex::getBase3d(double x, double y, double z) const -{ +double NoiseFunctionSimplex::getBase3d(double x, double y, double z) const { return noiseSimplexGet3DValue(x, y, z); } static Texture2D *_valueTexture = NULL; -const Texture2D *NoiseFunctionSimplex::getValueTexture() -{ - if (!_valueTexture) - { +const Texture2D *NoiseFunctionSimplex::getValueTexture() { + if (!_valueTexture) { const int width = 1024; const int height = 1024; _valueTexture = new Texture2D(width, height); - for (int x = 0; x < width; x++) - { - for (int z = 0; z < height; z++) - { + for (int x = 0; x < width; x++) { + for (int z = 0; z < height; z++) { double val = noiseSimplexGet2DValue((double)x, (double)z); _valueTexture->setPixel(x, z, Color(val, val, val)); } @@ -516,27 +498,21 @@ const Texture2D *NoiseFunctionSimplex::getValueTexture() static Texture2D *_normalTexture = NULL; -const Texture2D *NoiseFunctionSimplex::getNormalTexture() -{ - if (!_normalTexture) - { +const Texture2D *NoiseFunctionSimplex::getNormalTexture() { + if (!_normalTexture) { const int width = 1024; const int height = 1024; _normalTexture = new Texture2D(width, height); - for (int x = 0; x < width; x++) - { - for (int z = 0; z < height; z++) - { + for (int x = 0; x < width; x++) { + for (int z = 0; z < height; z++) { double vcenter = noiseSimplexGet2DValue(0.01 * (double)x, 0.01 * (double)z); double vsouth = noiseSimplexGet2DValue(0.01 * (double)x, 0.01 * (double)z + 0.001); double veast = noiseSimplexGet2DValue(0.01 * (double)x + 0.001, 0.01 * (double)z); - Vector3 normal = Geometry::getNormalFromTriangle(Vector3(0.0, vcenter, 0.0), - Vector3(0.0, vsouth, 0.01), - Vector3(0.01, veast, 0.0) - ); + Vector3 normal = Geometry::getNormalFromTriangle(Vector3(0.0, vcenter, 0.0), Vector3(0.0, vsouth, 0.01), + Vector3(0.01, veast, 0.0)); _normalTexture->setPixel(x, z, Color(normal.x, normal.y, normal.z)); } diff --git a/src/basics/NoiseFunctionSimplex.h b/src/basics/NoiseFunctionSimplex.h index 31308b8..21316c7 100644 --- a/src/basics/NoiseFunctionSimplex.h +++ b/src/basics/NoiseFunctionSimplex.h @@ -8,16 +8,14 @@ namespace paysages { namespace basics { -class NoiseFunctionSimplex:public FractalNoise -{ +class NoiseFunctionSimplex : public FractalNoise { virtual double getBase2d(double x, double y) const override; virtual double getBase3d(double x, double y, double z) const override; -public: + public: static const Texture2D *getValueTexture(); static const Texture2D *getNormalTexture(); }; - } } diff --git a/src/basics/NoiseGenerator.cpp b/src/basics/NoiseGenerator.cpp index cff55b3..549d95a 100644 --- a/src/basics/NoiseGenerator.cpp +++ b/src/basics/NoiseGenerator.cpp @@ -13,8 +13,7 @@ /* NoiseGenerator class */ -NoiseGenerator::NoiseGenerator() -{ +NoiseGenerator::NoiseGenerator() { function.algorithm = NOISE_FUNCTION_SIMPLEX; function.ridge_factor = 0.0; function.curve_factor = 0.0; @@ -25,12 +24,10 @@ NoiseGenerator::NoiseGenerator() validate(); } -NoiseGenerator::~NoiseGenerator() -{ +NoiseGenerator::~NoiseGenerator() { } -void NoiseGenerator::save(PackStream* stream) const -{ +void NoiseGenerator::save(PackStream *stream) const { int x; x = (int)function.algorithm; @@ -41,9 +38,8 @@ void NoiseGenerator::save(PackStream* stream) const stream->write(&height_offset); stream->write(&level_count); - for (x = 0; x < level_count; x++) - { - const NoiseLevel* level = levels + x; + for (x = 0; x < level_count; x++) { + const NoiseLevel *level = levels + x; stream->write(&level->frequency); stream->write(&level->amplitude); @@ -53,8 +49,7 @@ void NoiseGenerator::save(PackStream* stream) const state.save(stream); } -void NoiseGenerator::load(PackStream* stream) -{ +void NoiseGenerator::load(PackStream *stream) { int x; stream->read(&x); @@ -65,14 +60,12 @@ void NoiseGenerator::load(PackStream* stream) stream->read(&height_offset); stream->read(&level_count); - if (level_count > MAX_LEVEL_COUNT) - { + if (level_count > MAX_LEVEL_COUNT) { level_count = MAX_LEVEL_COUNT; } - for (x = 0; x < level_count; x++) - { - NoiseLevel* level = levels + x; + for (x = 0; x < level_count; x++) { + NoiseLevel *level = levels + x; stream->read(&level->frequency); stream->read(&level->amplitude); @@ -84,8 +77,7 @@ void NoiseGenerator::load(PackStream* stream) validate(); } -void NoiseGenerator::copy(NoiseGenerator* destination) const -{ +void NoiseGenerator::copy(NoiseGenerator *destination) const { destination->function = function; destination->height_offset = height_offset; destination->level_count = level_count; @@ -97,16 +89,13 @@ void NoiseGenerator::copy(NoiseGenerator* destination) const destination->validate(); } -void NoiseGenerator::validate() -{ +void NoiseGenerator::validate() { int x; - if (function.algorithm < 0 || function.algorithm > NOISE_FUNCTION_SIMPLEX) - { + if (function.algorithm < 0 || function.algorithm > NOISE_FUNCTION_SIMPLEX) { function.algorithm = NOISE_FUNCTION_SIMPLEX; } - switch (function.algorithm) - { + switch (function.algorithm) { case NOISE_FUNCTION_PERLIN: _func_noise_1d = noisePerlinGet1DValue; _func_noise_2d = noisePerlinGet2DValue; @@ -121,103 +110,86 @@ void NoiseGenerator::validate() break; } - if (function.ridge_factor > 0.5) - { + if (function.ridge_factor > 0.5) { function.ridge_factor = 0.5; } - if (function.ridge_factor < -0.5) - { + if (function.ridge_factor < -0.5) { function.ridge_factor = -0.5; } - if (function.curve_factor > 1.0) - { + if (function.curve_factor > 1.0) { function.curve_factor = 1.0; } - if (function.curve_factor < -1.0) - { + if (function.curve_factor < -1.0) { function.curve_factor = -1.0; } _min_value = height_offset; _max_value = height_offset; - for (x = 0; x < level_count; x++) - { + for (x = 0; x < level_count; x++) { _min_value += levels[x].minvalue; _max_value += levels[x].minvalue + levels[x].amplitude; } } -void NoiseGenerator::setState(const NoiseState &state) -{ +void NoiseGenerator::setState(const NoiseState &state) { state.copy(&this->state); } -void NoiseGenerator::randomizeOffsets() -{ +void NoiseGenerator::randomizeOffsets() { state.randomizeOffsets(); } -NoiseGenerator::NoiseFunction NoiseGenerator::getFunction() -{ +NoiseGenerator::NoiseFunction NoiseGenerator::getFunction() { return function; } -void NoiseGenerator::setFunction(NoiseFunction* function) -{ +void NoiseGenerator::setFunction(NoiseFunction *function) { this->function = *function; validate(); } -void NoiseGenerator::setCustomFunction(double (*func1d)(double x), double (*func2d)(double x, double y), double (*func3d)(double x, double y, double z)) -{ +void NoiseGenerator::setCustomFunction(double (*func1d)(double x), double (*func2d)(double x, double y), + double (*func3d)(double x, double y, double z)) { _func_noise_1d = func1d; _func_noise_2d = func2d; _func_noise_3d = func3d; function.algorithm = NOISE_FUNCTION_CUSTOM; } -void NoiseGenerator::setFunctionParams(NoiseFunctionAlgorithm algorithm, double ridge_factor, double curve_factor) -{ +void NoiseGenerator::setFunctionParams(NoiseFunctionAlgorithm algorithm, double ridge_factor, double curve_factor) { NoiseFunction function = {algorithm, ridge_factor, curve_factor}; setFunction(&function); } -void NoiseGenerator::forceValue(double value) -{ +void NoiseGenerator::forceValue(double value) { clearLevels(); height_offset = value; addLevelSimple(1.0, 0.0, 0.0); /* FIXME Should not be needed */ } -void NoiseGenerator::getRange(double* minvalue, double* maxvalue) const -{ +void NoiseGenerator::getRange(double *minvalue, double *maxvalue) const { *minvalue = _min_value; *maxvalue = _max_value; } -int NoiseGenerator::getLevelCount() const -{ +int NoiseGenerator::getLevelCount() const { return level_count; } -void NoiseGenerator::clearLevels() -{ +void NoiseGenerator::clearLevels() { level_count = 0; validate(); } -void NoiseGenerator::addLevel(NoiseLevel level) -{ - if (level_count < MAX_LEVEL_COUNT) - { +void NoiseGenerator::addLevel(NoiseLevel level) { + if (level_count < MAX_LEVEL_COUNT) { levels[level_count] = level; level_count++; validate(); } } -void NoiseGenerator::addLevelSimple(double scaling, double minvalue, double maxvalue) -{ +void NoiseGenerator::addLevelSimple(double scaling, double minvalue, double maxvalue) { NoiseLevel level; level.frequency = 1.0 / scaling; @@ -227,12 +199,11 @@ void NoiseGenerator::addLevelSimple(double scaling, double minvalue, double maxv addLevel(level); } -void NoiseGenerator::addLevels(int level_count, NoiseLevel start_level, double scaling_factor, double amplitude_factor, double center_factor) -{ +void NoiseGenerator::addLevels(int level_count, NoiseLevel start_level, double scaling_factor, double amplitude_factor, + double center_factor) { int i; - for (i = 0; i < level_count; i++) - { + for (i = 0; i < level_count; i++) { addLevel(start_level); start_level.minvalue += start_level.amplitude * (1.0 - amplitude_factor) * center_factor; start_level.frequency /= scaling_factor; @@ -240,8 +211,8 @@ void NoiseGenerator::addLevels(int level_count, NoiseLevel start_level, double s } } -void NoiseGenerator::addLevelsSimple(int level_count, double scaling, double minvalue, double maxvalue, double center_factor) -{ +void NoiseGenerator::addLevelsSimple(int level_count, double scaling, double minvalue, double maxvalue, + double center_factor) { NoiseLevel level; level.frequency = 1.0 / scaling; @@ -250,12 +221,9 @@ void NoiseGenerator::addLevelsSimple(int level_count, double scaling, double min addLevels(level_count, level, 0.5, 0.5, center_factor); } -void NoiseGenerator::removeLevel(int level) -{ - if (level >= 0 && level < level_count) - { - if (level_count > 1 && level < level_count - 1) - { +void NoiseGenerator::removeLevel(int level) { + if (level >= 0 && level < level_count) { + if (level_count > 1 && level < level_count - 1) { memmove(levels + level, levels + level + 1, sizeof(NoiseLevel) * (level_count - level - 1)); } level_count--; @@ -263,30 +231,23 @@ void NoiseGenerator::removeLevel(int level) } } -int NoiseGenerator::getLevel(int level, NoiseLevel* params) const -{ - if (level >= 0 && level < level_count) - { +int NoiseGenerator::getLevel(int level, NoiseLevel *params) const { + if (level >= 0 && level < level_count) { *params = levels[level]; return 1; - } - else - { + } else { return 0; } } -void NoiseGenerator::setLevel(int index, NoiseLevel level) -{ - if (index >= 0 && index < level_count) - { +void NoiseGenerator::setLevel(int index, NoiseLevel level) { + if (index >= 0 && index < level_count) { levels[index] = level; validate(); } } -void NoiseGenerator::setLevelSimple(int index, double scaling, double minvalue, double maxvalue) -{ +void NoiseGenerator::setLevelSimple(int index, double scaling, double minvalue, double maxvalue) { NoiseLevel level; level.frequency = 1.0 / scaling; @@ -296,14 +257,12 @@ void NoiseGenerator::setLevelSimple(int index, double scaling, double minvalue, setLevel(index, level); } -void NoiseGenerator::normalizeAmplitude(double minvalue, double maxvalue, int adjust_scaling) -{ +void NoiseGenerator::normalizeAmplitude(double minvalue, double maxvalue, int adjust_scaling) { int level; double current_minvalue, current_maxvalue, current_amplitude; double target_amplitude, factor; - if (level_count == 0) - { + if (level_count == 0) { return; } @@ -312,12 +271,10 @@ void NoiseGenerator::normalizeAmplitude(double minvalue, double maxvalue, int ad current_amplitude = current_maxvalue - current_minvalue; factor = target_amplitude / current_amplitude; - for (level = 0; level < level_count; level++) - { + for (level = 0; level < level_count; level++) { levels[level].minvalue *= factor; levels[level].amplitude *= factor; - if (adjust_scaling) - { + if (adjust_scaling) { levels[level].frequency /= factor; } } @@ -325,36 +282,24 @@ void NoiseGenerator::normalizeAmplitude(double minvalue, double maxvalue, int ad validate(); } -static inline double _fixValue(double value, double ridge, double curve) -{ - if (value < 0.0) - { +static inline double _fixValue(double value, double ridge, double curve) { + if (value < 0.0) { value = 0.0; - } - else if (value > 1.0) - { + } else if (value > 1.0) { value = 1.0; } - if (curve > 0.0) - { + if (curve > 0.0) { value = value * (1.0 - curve) + sqrt(value) * curve; - } - else if (curve < 0.0) - { + } else if (curve < 0.0) { value = value * (1.0 - curve) + value * value * curve; } - if (ridge > 0.0) - { + if (ridge > 0.0) { return fabs(value - ridge) / (1.0 - ridge); - } - else if (ridge < 0.0) - { + } else if (ridge < 0.0) { return 1.0 - fabs(value - 1.0 - ridge) / (1.0 + ridge); - } - else - { + } else { return value; } /*if (ridge > 0.0) @@ -371,55 +316,43 @@ static inline double _fixValue(double value, double ridge, double curve) }*/ } - - - -inline double NoiseGenerator::_get1DLevelValue(const NoiseLevel* level, const NoiseState::NoiseOffset &offset, double x) const -{ - return level->minvalue + _fixValue(_func_noise_1d(x * level->frequency + offset.x), function.ridge_factor, function.curve_factor) * level->amplitude; +inline double NoiseGenerator::_get1DLevelValue(const NoiseLevel *level, const NoiseState::NoiseOffset &offset, + double x) const { + return level->minvalue + + _fixValue(_func_noise_1d(x * level->frequency + offset.x), function.ridge_factor, function.curve_factor) * + level->amplitude; } -double NoiseGenerator::get1DLevel(int level, double x) const -{ - if (level >= 0 && level < level_count) - { +double NoiseGenerator::get1DLevel(int level, double x) const { + if (level >= 0 && level < level_count) { return _get1DLevelValue(levels + level, state.level_offsets[level], x); - } - else - { + } else { return 0.0; } } -double NoiseGenerator::get1DTotal(double x) const -{ +double NoiseGenerator::get1DTotal(double x) const { int level; double result; result = 0.0; - for (level = 0; level < level_count; level++) - { + for (level = 0; level < level_count; level++) { result += _get1DLevelValue(levels + level, state.level_offsets[level], x); } return result + height_offset; } -double NoiseGenerator::get1DDetail(double x, double detail) const -{ +double NoiseGenerator::get1DDetail(double x, double detail) const { int level; double result, height, factor; result = 0.0; - for (level = 0; level < level_count; level++) - { + for (level = 0; level < level_count; level++) { height = levels[level].amplitude; factor = 1.0; - if (height < detail * 0.25) - { + if (height < detail * 0.25) { break; - } - else if (height < detail * 0.5) - { + } else if (height < detail * 0.5) { factor = (detail * 0.5 - height) / 0.25; } @@ -428,55 +361,44 @@ double NoiseGenerator::get1DDetail(double x, double detail) const return result + height_offset; } - - - -inline double NoiseGenerator::_get2DLevelValue(const NoiseLevel* level, const NoiseState::NoiseOffset &offset, double x, double y) const -{ - return level->minvalue + _fixValue(_func_noise_2d(x * level->frequency + offset.x, y * level->frequency + offset.y), function.ridge_factor, function.curve_factor) * level->amplitude; +inline double NoiseGenerator::_get2DLevelValue(const NoiseLevel *level, const NoiseState::NoiseOffset &offset, double x, + double y) const { + return level->minvalue + + _fixValue(_func_noise_2d(x * level->frequency + offset.x, y * level->frequency + offset.y), + function.ridge_factor, function.curve_factor) * + level->amplitude; } -double NoiseGenerator::get2DLevel(int level, double x, double y) const -{ - if (level >= 0 && level < level_count) - { +double NoiseGenerator::get2DLevel(int level, double x, double y) const { + if (level >= 0 && level < level_count) { return _get2DLevelValue(levels + level, state.level_offsets[level], x, y); - } - else - { + } else { return 0.0; } } -double NoiseGenerator::get2DTotal(double x, double y) const -{ +double NoiseGenerator::get2DTotal(double x, double y) const { int level; double result; result = 0.0; - for (level = 0; level < level_count; level++) - { + for (level = 0; level < level_count; level++) { result += _get2DLevelValue(levels + level, state.level_offsets[level], x, y); } return result + height_offset; } -double NoiseGenerator::get2DDetail(double x, double y, double detail) const -{ +double NoiseGenerator::get2DDetail(double x, double y, double detail) const { int level; double result, height, factor; result = 0.0; - for (level = 0; level < level_count; level++) - { + for (level = 0; level < level_count; level++) { height = levels[level].amplitude; factor = 1.0; - if (height < detail * 0.25) - { + if (height < detail * 0.25) { break; - } - else if (height < detail * 0.5) - { + } else if (height < detail * 0.5) { factor = (detail * 0.5 - height) / 0.25; } @@ -485,55 +407,45 @@ double NoiseGenerator::get2DDetail(double x, double y, double detail) const return result + height_offset; } - - - -inline double NoiseGenerator::_get3DLevelValue(const NoiseLevel* level, const NoiseState::NoiseOffset &offset, double x, double y, double z) const -{ - return level->minvalue + _fixValue(_func_noise_3d(x * level->frequency + offset.x, y * level->frequency + offset.y, z * level->frequency + offset.z), function.ridge_factor, function.curve_factor) * level->amplitude; +inline double NoiseGenerator::_get3DLevelValue(const NoiseLevel *level, const NoiseState::NoiseOffset &offset, double x, + double y, double z) const { + return level->minvalue + + _fixValue(_func_noise_3d(x * level->frequency + offset.x, y * level->frequency + offset.y, + z * level->frequency + offset.z), + function.ridge_factor, function.curve_factor) * + level->amplitude; } -double NoiseGenerator::get3DLevel(int level, double x, double y, double z) const -{ - if (level >= 0 && level < level_count) - { +double NoiseGenerator::get3DLevel(int level, double x, double y, double z) const { + if (level >= 0 && level < level_count) { return _get3DLevelValue(levels + level, state.level_offsets[level], x, y, z); - } - else - { + } else { return 0.0; } } -double NoiseGenerator::get3DTotal(double x, double y, double z) const -{ +double NoiseGenerator::get3DTotal(double x, double y, double z) const { int level; double result; result = 0.0; - for (level = 0; level < level_count; level++) - { + for (level = 0; level < level_count; level++) { result += _get3DLevelValue(levels + level, state.level_offsets[level], x, y, z); } return result + height_offset; } -double NoiseGenerator::get3DDetail(double x, double y, double z, double detail) const -{ +double NoiseGenerator::get3DDetail(double x, double y, double z, double detail) const { int level; double result, height, factor; result = 0.0; - for (level = 0; level < level_count; level++) - { + for (level = 0; level < level_count; level++) { height = levels[level].amplitude; factor = 1.0; - if (height < detail * 0.25) - { + if (height < detail * 0.25) { break; - } - else if (height < detail * 0.5) - { + } else if (height < detail * 0.5) { factor = (detail * 0.5 - height) / 0.25; } diff --git a/src/basics/NoiseGenerator.h b/src/basics/NoiseGenerator.h index 20e3a6f..1d28850 100644 --- a/src/basics/NoiseGenerator.h +++ b/src/basics/NoiseGenerator.h @@ -9,57 +9,53 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT NoiseGenerator -{ -public: - typedef enum - { - NOISE_FUNCTION_PERLIN, - NOISE_FUNCTION_SIMPLEX, - NOISE_FUNCTION_CUSTOM - } NoiseFunctionAlgorithm; +class BASICSSHARED_EXPORT NoiseGenerator { + public: + typedef enum { NOISE_FUNCTION_PERLIN, NOISE_FUNCTION_SIMPLEX, NOISE_FUNCTION_CUSTOM } NoiseFunctionAlgorithm; - typedef struct - { + typedef struct { NoiseFunctionAlgorithm algorithm; double ridge_factor; /* -0.5;0.5 */ double curve_factor; /* -1.0;1.0 */ } NoiseFunction; - typedef struct - { + typedef struct { double frequency; double amplitude; double minvalue; } NoiseLevel; -public: + public: NoiseGenerator(); virtual ~NoiseGenerator(); - virtual void save(PackStream* stream) const; - virtual void load(PackStream* stream); - virtual void copy(NoiseGenerator* destination) const; + virtual void save(PackStream *stream) const; + virtual void load(PackStream *stream); + virtual void copy(NoiseGenerator *destination) const; virtual void validate(); - inline const NoiseState &getState() const {return state;} + inline const NoiseState &getState() const { + return state; + } void setState(const NoiseState &state); void randomizeOffsets(); NoiseFunction getFunction(); - void setCustomFunction(double (*func1d)(double x), double (*func2d)(double x, double y), double (*func3d)(double x, double y, double z)); - void setFunction(NoiseFunction* function); + void setCustomFunction(double (*func1d)(double x), double (*func2d)(double x, double y), + double (*func3d)(double x, double y, double z)); + void setFunction(NoiseFunction *function); void setFunctionParams(NoiseFunctionAlgorithm algorithm, double ridge_factor, double curve_factor); void forceValue(double value); - void getRange(double* minvalue, double* maxvalue) const; + void getRange(double *minvalue, double *maxvalue) const; int getLevelCount() const; void clearLevels(); void addLevel(NoiseLevel level); void addLevelSimple(double scaling, double minvalue, double maxvalue); - void addLevels(int level_count, NoiseLevel start_level, double scaling_factor, double amplitude_factor, double center_factor); + void addLevels(int level_count, NoiseLevel start_level, double scaling_factor, double amplitude_factor, + double center_factor); void addLevelsSimple(int level_count, double scaling, double minvalue, double maxvalue, double center_factor); void removeLevel(int level); - int getLevel(int level, NoiseLevel* params) const; + int getLevel(int level, NoiseLevel *params) const; void setLevel(int index, NoiseLevel level); void setLevelSimple(int index, double scaling, double minvalue, double maxvalue); void normalizeAmplitude(double minvalue, double maxvalue, int adjust_scaling); @@ -73,10 +69,11 @@ public: double get3DTotal(double x, double y, double z) const; double get3DDetail(double x, double y, double z, double detail) const; -private: - double _get1DLevelValue(const NoiseLevel* level, const NoiseState::NoiseOffset &offset, double x) const; - double _get2DLevelValue(const NoiseLevel* level, const NoiseState::NoiseOffset &offset, double x, double y) const; - double _get3DLevelValue(const NoiseLevel* level, const NoiseState::NoiseOffset &offset, double x, double y, double z) const; + private: + double _get1DLevelValue(const NoiseLevel *level, const NoiseState::NoiseOffset &offset, double x) const; + double _get2DLevelValue(const NoiseLevel *level, const NoiseState::NoiseOffset &offset, double x, double y) const; + double _get3DLevelValue(const NoiseLevel *level, const NoiseState::NoiseOffset &offset, double x, double y, + double z) const; NoiseFunction function; double height_offset; @@ -91,7 +88,6 @@ private: double (*_func_noise_2d)(double x, double y); double (*_func_noise_3d)(double x, double y, double z); }; - } } diff --git a/src/basics/NoiseState.cpp b/src/basics/NoiseState.cpp index 14019fe..4678947 100644 --- a/src/basics/NoiseState.cpp +++ b/src/basics/NoiseState.cpp @@ -3,40 +3,33 @@ #include "PackStream.h" #include "RandomGenerator.h" -NoiseState::NoiseState() -{ - for (int i = 0; i < 30; i++) - { +NoiseState::NoiseState() { + for (int i = 0; i < 30; i++) { level_offsets.push_back(NoiseOffset()); } randomizeOffsets(); } -void NoiseState::save(PackStream *stream) const -{ +void NoiseState::save(PackStream *stream) const { int levels = level_offsets.size(); stream->write(&levels); - for (const auto &level_offset:level_offsets) - { + for (const auto &level_offset : level_offsets) { stream->write(&level_offset.x); stream->write(&level_offset.y); stream->write(&level_offset.z); } } -void NoiseState::load(PackStream *stream) -{ +void NoiseState::load(PackStream *stream) { int levels; stream->read(&levels); level_offsets.clear(); - if (levels > 1000) - { + if (levels > 1000) { levels = 1000; } - for (int i = 0; i < levels; i++) - { + for (int i = 0; i < levels; i++) { NoiseOffset level_offset; stream->read(&level_offset.x); stream->read(&level_offset.y); @@ -45,38 +38,31 @@ void NoiseState::load(PackStream *stream) } } -void NoiseState::copy(NoiseState *destination) const -{ +void NoiseState::copy(NoiseState *destination) const { destination->level_offsets = level_offsets; } -void NoiseState::randomizeOffsets() -{ - for (auto &level_offset:level_offsets) - { +void NoiseState::randomizeOffsets() { + for (auto &level_offset : level_offsets) { level_offset.x = RandomGenerator::random(); level_offset.y = RandomGenerator::random(); level_offset.z = RandomGenerator::random(); } } -void NoiseState::resetOffsets(double x, double y, double z) -{ - for (auto &level_offset:level_offsets) - { +void NoiseState::resetOffsets(double x, double y, double z) { + for (auto &level_offset : level_offsets) { level_offset.x = x; level_offset.y = y; level_offset.z = z; } } -void NoiseState::setLevel(int level, double x, double y, double z) -{ +void NoiseState::setLevel(int level, double x, double y, double z) { NoiseOffset offset = {x, y, z}; level_offsets.at(level) = offset; } -void NoiseState::setLevelCount(int level_count) -{ +void NoiseState::setLevelCount(int level_count) { level_offsets.resize(level_count); } diff --git a/src/basics/NoiseState.h b/src/basics/NoiseState.h index c19b0ba..c4d8157 100644 --- a/src/basics/NoiseState.h +++ b/src/basics/NoiseState.h @@ -11,35 +11,33 @@ namespace basics { * * This state contains the noise offsets for noise layers. */ -class BASICSSHARED_EXPORT NoiseState -{ -public: +class BASICSSHARED_EXPORT NoiseState { + public: typedef struct { double x; double y; double z; } NoiseOffset; -public: + public: NoiseState(); - void save(PackStream* stream) const; - void load(PackStream* stream); - void copy(NoiseState* destination) const; + void save(PackStream *stream) const; + void load(PackStream *stream); + void copy(NoiseState *destination) const; void randomizeOffsets(); - void resetOffsets(double x=0.0, double y=0.0, double z=0.0); + void resetOffsets(double x = 0.0, double y = 0.0, double z = 0.0); void setLevel(int level, double x, double y, double z); void setLevelCount(int level_count); -private: + private: std::vector level_offsets; friend class NoiseGenerator; friend class FractalNoise; }; - } } diff --git a/src/basics/SpaceGridIterator.cpp b/src/basics/SpaceGridIterator.cpp index 21fb3d0..4e68622 100644 --- a/src/basics/SpaceGridIterator.cpp +++ b/src/basics/SpaceGridIterator.cpp @@ -1,5 +1,4 @@ #include "SpaceGridIterator.h" -SpaceGridIterator::SpaceGridIterator() -{ +SpaceGridIterator::SpaceGridIterator() { } diff --git a/src/basics/SpaceGridIterator.h b/src/basics/SpaceGridIterator.h index bec1944..749535e 100644 --- a/src/basics/SpaceGridIterator.h +++ b/src/basics/SpaceGridIterator.h @@ -11,9 +11,8 @@ namespace basics { * * This may be useful for ray marching algorithms for example. */ -class BASICSSHARED_EXPORT SpaceGridIterator -{ -public: +class BASICSSHARED_EXPORT SpaceGridIterator { + public: SpaceGridIterator(); /** @@ -23,7 +22,6 @@ public: */ virtual bool onCell(int x, int y, int z) = 0; }; - } } diff --git a/src/basics/SpaceSegment.cpp b/src/basics/SpaceSegment.cpp index bfec17e..0eb6595 100644 --- a/src/basics/SpaceSegment.cpp +++ b/src/basics/SpaceSegment.cpp @@ -3,54 +3,36 @@ #include #include "SpaceGridIterator.h" -SpaceSegment::SpaceSegment(const Vector3& start, const Vector3& end): - start(start), end(end) -{ +SpaceSegment::SpaceSegment(const Vector3 &start, const Vector3 &end) : start(start), end(end) { } -bool SpaceSegment::intersectYInterval(double ymin, double ymax) -{ - if (start.y > ymax) - { - if (end.y >= ymax) - { +bool SpaceSegment::intersectYInterval(double ymin, double ymax) { + if (start.y > ymax) { + if (end.y >= ymax) { return false; - } - else - { + } else { Vector3 diff = end.sub(start); start = start.add(diff.scale((ymax - start.y) / diff.y)); - if (end.y < ymin) - { + if (end.y < ymin) { end = end.add(diff.scale((ymin - end.y) / diff.y)); } } - } - else if (start.y < ymin) - { - if (end.y <= ymin) - { + } else if (start.y < ymin) { + if (end.y <= ymin) { return false; - } - else - { + } else { Vector3 diff = end.sub(start); start = start.add(diff.scale((ymin - start.y) / diff.y)); - if (end.y >= ymax) - { + if (end.y >= ymax) { end = end.add(diff.scale((ymax - end.y) / diff.y)); } } - } - else /* start is inside layer */ + } else /* start is inside layer */ { Vector3 diff = end.sub(start); - if (end.y > ymax) - { + if (end.y > ymax) { end = start.add(diff.scale((ymax - start.y) / diff.y)); - } - else if (end.y < ymin) - { + } else if (end.y < ymin) { end = start.add(diff.scale((ymin - start.y) / diff.y)); } } @@ -58,28 +40,23 @@ bool SpaceSegment::intersectYInterval(double ymin, double ymax) return true; } -SpaceSegment SpaceSegment::projectedOnXPlane(double x) const -{ +SpaceSegment SpaceSegment::projectedOnXPlane(double x) const { return SpaceSegment(Vector3(x, start.y, start.z), Vector3(x, end.y, end.z)); } -SpaceSegment SpaceSegment::projectedOnYPlane(double y) const -{ +SpaceSegment SpaceSegment::projectedOnYPlane(double y) const { return SpaceSegment(Vector3(start.x, y, start.z), Vector3(end.x, y, end.z)); } -SpaceSegment SpaceSegment::projectedOnZPlane(double z) const -{ +SpaceSegment SpaceSegment::projectedOnZPlane(double z) const { return SpaceSegment(Vector3(start.x, start.y, z), Vector3(end.x, end.y, z)); } -SpaceSegment SpaceSegment::scaled(double factor) const -{ +SpaceSegment SpaceSegment::scaled(double factor) const { return SpaceSegment(start.scale(factor), end.scale(factor)); } -bool SpaceSegment::iterateOnGrid(SpaceGridIterator &delegate) -{ +bool SpaceSegment::iterateOnGrid(SpaceGridIterator &delegate) { Vector3 diff = end.sub(start); int stepX = diff.x < 0.0 ? -1 : 1; @@ -98,36 +75,25 @@ bool SpaceSegment::iterateOnGrid(SpaceGridIterator &delegate) double tMaxY = diff.y == 0.0 ? INFINITY : ((double)(Y + (stepY > 0 ? 1 : 0)) - start.y) / diff.y; double tMaxZ = diff.z == 0.0 ? INFINITY : ((double)(Z + (stepZ > 0 ? 1 : 0)) - start.z) / diff.z; - do - { - if (not delegate.onCell(X, Y, Z)) - { + do { + if (not delegate.onCell(X, Y, Z)) { return false; } - if (tMaxX < tMaxY) - { - if (tMaxX < tMaxZ) - { + if (tMaxX < tMaxY) { + if (tMaxX < tMaxZ) { X = X + stepX; tMaxX = tMaxX + tDeltaX; - } - else - { + } else { Z = Z + stepZ; tMaxZ = tMaxZ + tDeltaZ; } - } - else - { - if(tMaxY < tMaxZ) - { + } else { + if (tMaxY < tMaxZ) { Y = Y + stepY; tMaxY = tMaxY + tDeltaY; - } - else - { - Z= Z + stepZ; + } else { + Z = Z + stepZ; tMaxZ = tMaxZ + tDeltaZ; } } diff --git a/src/basics/SpaceSegment.h b/src/basics/SpaceSegment.h index e6e0f4a..270e10a 100644 --- a/src/basics/SpaceSegment.h +++ b/src/basics/SpaceSegment.h @@ -11,20 +11,34 @@ namespace basics { /** * A delimited segment in 3D space (mainly useful for rays). */ -class BASICSSHARED_EXPORT SpaceSegment -{ -public: - SpaceSegment(const Vector3& start, const Vector3& end); - SpaceSegment(): SpaceSegment(Vector3(), Vector3()) {} +class BASICSSHARED_EXPORT SpaceSegment { + public: + SpaceSegment(const Vector3 &start, const Vector3 &end); + SpaceSegment() : SpaceSegment(Vector3(), Vector3()) { + } - inline const Vector3 &getStart() const {return start;} - inline const Vector3 &getEnd() const {return end;} - inline Vector3 getDirection() const {return end.sub(start);} - inline double getLength() const {return end.sub(start).getNorm();} + inline const Vector3 &getStart() const { + return start; + } + inline const Vector3 &getEnd() const { + return end; + } + inline Vector3 getDirection() const { + return end.sub(start); + } + inline double getLength() const { + return end.sub(start).getNorm(); + } - inline double getXDiff() const {return end.x - start.x;} - inline double getYDiff() const {return end.y - start.y;} - inline double getZDiff() const {return end.z - start.z;} + inline double getXDiff() const { + return end.x - start.x; + } + inline double getYDiff() const { + return end.y - start.y; + } + inline double getZDiff() const { + return end.z - start.z; + } /** * Keep only the intersection with a slice orthogonal to the Y axis. @@ -36,15 +50,15 @@ public: /** * Return a version of this segment, projected on a X plane. */ - SpaceSegment projectedOnXPlane(double x=0.0) const; + SpaceSegment projectedOnXPlane(double x = 0.0) const; /** * Return a version of this segment, projected on a Y plane. */ - SpaceSegment projectedOnYPlane(double y=0.0) const; + SpaceSegment projectedOnYPlane(double y = 0.0) const; /** * Return a version of this segment, projected on a Z plane. */ - SpaceSegment projectedOnZPlane(double z=0.0) const; + SpaceSegment projectedOnZPlane(double z = 0.0) const; /** * Return a scaled version of this segment. @@ -64,11 +78,10 @@ public: */ bool iterateOnGrid(SpaceGridIterator &delegate); -private: + private: Vector3 start; Vector3 end; }; - } } diff --git a/src/basics/Sphere.cpp b/src/basics/Sphere.cpp index e7885df..b1cda67 100644 --- a/src/basics/Sphere.cpp +++ b/src/basics/Sphere.cpp @@ -3,43 +3,32 @@ #include "PackStream.h" #include "InfiniteRay.h" -Sphere::Sphere() -{ +Sphere::Sphere() { } -Sphere::Sphere(const Vector3 ¢er, double radius): - center(center), radius(radius) -{ +Sphere::Sphere(const Vector3 ¢er, double radius) : center(center), radius(radius) { radius2 = radius * radius; } -int Sphere::checkRayIntersection(const InfiniteRay &ray, Vector3 *first_intersection, Vector3 *second_intersection) const -{ +int Sphere::checkRayIntersection(const InfiniteRay &ray, Vector3 *first_intersection, + Vector3 *second_intersection) const { Vector3 L = ray.getOrigin().sub(center); double b = 2.0 * ray.getDirection().dotProduct(L); double c = L.dotProduct(L) - radius2; double discr = b * b - 4.0 * c; - if (discr < 0) - { + if (discr < 0) { return 0; - } - else if (discr == 0) - { + } else if (discr == 0) { *first_intersection = ray.getPointAtCursor(-0.5 * b); return 1; - } - else - { + } else { double x0 = (b > 0.0) ? -0.5 * (b + sqrt(discr)) : -0.5 * (b - sqrt(discr)); double x1 = c / x0; - if (x0 > x1) - { + if (x0 > x1) { *first_intersection = ray.getPointAtCursor(x1); *second_intersection = ray.getPointAtCursor(x0); - } - else - { + } else { *first_intersection = ray.getPointAtCursor(x0); *second_intersection = ray.getPointAtCursor(x1); } @@ -47,15 +36,13 @@ int Sphere::checkRayIntersection(const InfiniteRay &ray, Vector3 *first_intersec } } -void Sphere::save(PackStream *stream) const -{ +void Sphere::save(PackStream *stream) const { center.save(stream); stream->write(&radius); stream->write(&radius2); } -void Sphere::load(PackStream *stream) -{ +void Sphere::load(PackStream *stream) { center.load(stream); stream->read(&radius); stream->read(&radius2); diff --git a/src/basics/Sphere.h b/src/basics/Sphere.h index c50d4a1..c1d0954 100644 --- a/src/basics/Sphere.h +++ b/src/basics/Sphere.h @@ -11,31 +11,33 @@ namespace basics { /** * Geometric sphere. */ -class BASICSSHARED_EXPORT Sphere -{ -public: +class BASICSSHARED_EXPORT Sphere { + public: Sphere(); Sphere(const Vector3 ¢er, double radius); - inline const Vector3 &getCenter() const {return center;} - inline const double &getRadius() const {return radius;} + inline const Vector3 &getCenter() const { + return center; + } + inline const double &getRadius() const { + return radius; + } /** * Check the intersection between the sphere and an infinite ray. * * Returns the number of intersections (0, 1 or 2) and fill the intersection points. */ - int checkRayIntersection(const InfiniteRay& ray, Vector3 *first_intersection, Vector3 *second_intersection) const; + int checkRayIntersection(const InfiniteRay &ray, Vector3 *first_intersection, Vector3 *second_intersection) const; void save(PackStream *stream) const; void load(PackStream *stream); -private: + private: Vector3 center; double radius; double radius2; }; - } } diff --git a/src/basics/Texture2D.cpp b/src/basics/Texture2D.cpp index 13e71e7..5cbc9cc 100644 --- a/src/basics/Texture2D.cpp +++ b/src/basics/Texture2D.cpp @@ -5,8 +5,7 @@ #include "PackStream.h" #include "PictureWriter.h" -Texture2D::Texture2D(int xsize, int ysize) -{ +Texture2D::Texture2D(int xsize, int ysize) { assert(xsize > 0 && ysize > 0); this->xsize = xsize; @@ -14,39 +13,38 @@ Texture2D::Texture2D(int xsize, int ysize) this->data = new Color[xsize * ysize]; } -Texture2D::~Texture2D() -{ +Texture2D::~Texture2D() { delete[] data; } -void Texture2D::getSize(int* xsize, int* ysize) const -{ +void Texture2D::getSize(int *xsize, int *ysize) const { *xsize = this->xsize; *ysize = this->ysize; } -void Texture2D::setPixel(int x, int y, Color col) -{ +void Texture2D::setPixel(int x, int y, Color col) { assert(x >= 0 && x < xsize); assert(y >= 0 && y < ysize); data[y * xsize + x] = col; } -Color Texture2D::getPixel(int x, int y) const -{ +Color Texture2D::getPixel(int x, int y) const { assert(x >= 0 && x < xsize); assert(y >= 0 && y < ysize); return data[y * xsize + x]; } -Color Texture2D::getNearest(double dx, double dy) const -{ - if (dx < 0.0) dx = 0.0; - if (dx > 1.0) dx = 1.0; - if (dy < 0.0) dy = 0.0; - if (dy > 1.0) dy = 1.0; +Color Texture2D::getNearest(double dx, double dy) const { + if (dx < 0.0) + dx = 0.0; + if (dx > 1.0) + dx = 1.0; + if (dy < 0.0) + dy = 0.0; + if (dy > 1.0) + dy = 1.0; int ix = (int)(dx * (double)(this->xsize - 1)); int iy = (int)(dy * (double)(this->ysize - 1)); @@ -57,31 +55,32 @@ Color Texture2D::getNearest(double dx, double dy) const return this->data[iy * this->xsize + ix]; } -Color Texture2D::getLinear(double dx, double dy) const -{ - if (dx < 0.0) dx = 0.0; - if (dx > 1.0) dx = 1.0; - if (dy < 0.0) dy = 0.0; - if (dy > 1.0) dy = 1.0; +Color Texture2D::getLinear(double dx, double dy) const { + if (dx < 0.0) + dx = 0.0; + if (dx > 1.0) + dx = 1.0; + if (dy < 0.0) + dy = 0.0; + if (dy > 1.0) + dy = 1.0; dx *= (double)(this->xsize - 1); dy *= (double)(this->ysize - 1); int ix = (int)floor(dx); - if (ix == this->xsize - 1) - { + if (ix == this->xsize - 1) { ix--; } int iy = (int)floor(dy); - if (iy == this->ysize - 1) - { + if (iy == this->ysize - 1) { iy--; } dx -= (double)ix; dy -= (double)iy; - Color* data = this->data + iy * this->xsize + ix; + Color *data = this->data + iy * this->xsize + ix; Color c1 = data->lerp(*(data + 1), dx); Color c2 = (data + this->xsize)->lerp(*(data + this->xsize + 1), dx); @@ -89,32 +88,27 @@ Color Texture2D::getLinear(double dx, double dy) const return c1.lerp(c2, dy); } -Color Texture2D::getCubic(double dx, double dy) const -{ +Color Texture2D::getCubic(double dx, double dy) const { /* TODO */ return getLinear(dx, dy); } -void Texture2D::fill(Color col) -{ +void Texture2D::fill(Color col) { int i, n; n = this->xsize * this->ysize; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { this->data[i] = col; } } -void Texture2D::add(Texture2D* source) -{ +void Texture2D::add(Texture2D *source) { int i, n; assert(source->xsize == this->xsize); assert(source->ysize == this->ysize); n = source->xsize * source->ysize; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { this->data[i].r += source->data[i].r; this->data[i].g += source->data[i].g; this->data[i].b += source->data[i].b; @@ -122,47 +116,42 @@ void Texture2D::add(Texture2D* source) } } -void Texture2D::save(PackStream* stream) const -{ +void Texture2D::save(PackStream *stream) const { int i, n; stream->write(&this->xsize); stream->write(&this->ysize); n = this->xsize * this->ysize; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { (this->data + i)->save(stream); } } -void Texture2D::load(PackStream* stream) -{ +void Texture2D::load(PackStream *stream) { int i, n; stream->read(&this->xsize); stream->read(&this->ysize); n = this->xsize * this->ysize; delete[] this->data; this->data = new Color[n]; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { (this->data + i)->load(stream); } } -class Texture2DWriter:public PictureWriter -{ -public: - Texture2DWriter(const Texture2D *tex): tex(tex) {} +class Texture2DWriter : public PictureWriter { + public: + Texture2DWriter(const Texture2D *tex) : tex(tex) { + } - virtual unsigned int getPixel(int x, int y) override - { + virtual unsigned int getPixel(int x, int y) override { return tex->getPixel(x, y).to32BitBGRA(); } -private: + + private: const Texture2D *tex; }; -void Texture2D::saveToFile(const std::string &filepath) const -{ +void Texture2D::saveToFile(const std::string &filepath) const { Texture2DWriter writer(this); writer.save(filepath, xsize, ysize); } diff --git a/src/basics/Texture2D.h b/src/basics/Texture2D.h index 1e762bb..b324d00 100644 --- a/src/basics/Texture2D.h +++ b/src/basics/Texture2D.h @@ -6,30 +6,28 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT Texture2D -{ -public: +class BASICSSHARED_EXPORT Texture2D { + public: Texture2D(int xsize, int ysize); ~Texture2D(); - void getSize(int* xsize, int* ysize) const; + void getSize(int *xsize, int *ysize) const; void setPixel(int x, int y, Color col); Color getPixel(int x, int y) const; Color getNearest(double dx, double dy) const; Color getLinear(double dx, double dy) const; Color getCubic(double dx, double dy) const; void fill(Color col); - void add(Texture2D* other); - void save(PackStream* stream) const; - void load(PackStream* stream); + void add(Texture2D *other); + void save(PackStream *stream) const; + void load(PackStream *stream); void saveToFile(const std::string &filepath) const; -private: + private: int xsize; int ysize; - Color* data; + Color *data; }; - } } diff --git a/src/basics/Texture3D.cpp b/src/basics/Texture3D.cpp index 55400e2..98ac93a 100644 --- a/src/basics/Texture3D.cpp +++ b/src/basics/Texture3D.cpp @@ -5,8 +5,7 @@ #include "PackStream.h" #include "PictureWriter.h" -Texture3D::Texture3D(int xsize, int ysize, int zsize) -{ +Texture3D::Texture3D(int xsize, int ysize, int zsize) { assert(xsize > 0 && ysize > 0 && zsize > 0); this->xsize = xsize; @@ -15,20 +14,17 @@ Texture3D::Texture3D(int xsize, int ysize, int zsize) this->data = new Color[xsize * ysize * zsize]; } -Texture3D::~Texture3D() -{ +Texture3D::~Texture3D() { delete[] data; } -void Texture3D::getSize(int* xsize, int* ysize, int* zsize) const -{ +void Texture3D::getSize(int *xsize, int *ysize, int *zsize) const { *xsize = this->xsize; *ysize = this->ysize; *zsize = this->zsize; } -void Texture3D::setPixel(int x, int y, int z, Color col) -{ +void Texture3D::setPixel(int x, int y, int z, Color col) { assert(x >= 0 && x < this->xsize); assert(y >= 0 && y < this->ysize); assert(z >= 0 && z < this->ysize); @@ -36,8 +32,7 @@ void Texture3D::setPixel(int x, int y, int z, Color col) this->data[z * this->xsize * this->ysize + y * this->xsize + x] = col; } -Color Texture3D::getPixel(int x, int y, int z) const -{ +Color Texture3D::getPixel(int x, int y, int z) const { assert(x >= 0 && x < this->xsize); assert(y >= 0 && y < this->ysize); assert(z >= 0 && z < this->zsize); @@ -45,14 +40,19 @@ Color Texture3D::getPixel(int x, int y, int z) const return this->data[z * this->xsize * this->ysize + y * this->xsize + x]; } -Color Texture3D::getNearest(double dx, double dy, double dz) const -{ - if (dx < 0.0) dx = 0.0; - if (dx > 1.0) dx = 1.0; - if (dy < 0.0) dy = 0.0; - if (dy > 1.0) dy = 1.0; - if (dz < 0.0) dz = 0.0; - if (dz > 1.0) dz = 1.0; +Color Texture3D::getNearest(double dx, double dy, double dz) const { + if (dx < 0.0) + dx = 0.0; + if (dx > 1.0) + dx = 1.0; + if (dy < 0.0) + dy = 0.0; + if (dy > 1.0) + dy = 1.0; + if (dz < 0.0) + dz = 0.0; + if (dz > 1.0) + dz = 1.0; int ix = (int)(dx * (double)(this->xsize - 1)); int iy = (int)(dy * (double)(this->ysize - 1)); @@ -65,32 +65,34 @@ Color Texture3D::getNearest(double dx, double dy, double dz) const return this->data[iz * this->xsize * this->ysize + iy * this->xsize + ix]; } -Color Texture3D::getLinear(double dx, double dy, double dz) const -{ - if (dx < 0.0) dx = 0.0; - if (dx > 1.0) dx = 1.0; - if (dy < 0.0) dy = 0.0; - if (dy > 1.0) dy = 1.0; - if (dz < 0.0) dz = 0.0; - if (dz > 1.0) dz = 1.0; +Color Texture3D::getLinear(double dx, double dy, double dz) const { + if (dx < 0.0) + dx = 0.0; + if (dx > 1.0) + dx = 1.0; + if (dy < 0.0) + dy = 0.0; + if (dy > 1.0) + dy = 1.0; + if (dz < 0.0) + dz = 0.0; + if (dz > 1.0) + dz = 1.0; dx *= (double)(this->xsize - 1); dy *= (double)(this->ysize - 1); dz *= (double)(this->zsize - 1); int ix = (int)floor(dx); - if (ix == this->xsize - 1) - { + if (ix == this->xsize - 1) { ix--; } int iy = (int)floor(dy); - if (iy == this->ysize - 1) - { + if (iy == this->ysize - 1) { iy--; } int iz = (int)floor(dz); - if (iz == this->zsize - 1) - { + if (iz == this->zsize - 1) { iz--; } @@ -98,7 +100,7 @@ Color Texture3D::getLinear(double dx, double dy, double dz) const dy -= (double)iy; dz -= (double)iz; - Color* data = this->data + iz * this->xsize * this->ysize + iy * this->xsize + ix; + Color *data = this->data + iz * this->xsize * this->ysize + iy * this->xsize + ix; Color cx1 = data->lerp(*(data + 1), dx); Color cx2 = (data + this->xsize)->lerp(*(data + this->xsize + 1), dx); @@ -112,24 +114,20 @@ Color Texture3D::getLinear(double dx, double dy, double dz) const return cy1.lerp(cy2, dz); } -Color Texture3D::getCubic(double dx, double dy, double dz) const -{ +Color Texture3D::getCubic(double dx, double dy, double dz) const { /* TODO */ return getLinear(dx, dy, dz); } -void Texture3D::fill(Color col) -{ +void Texture3D::fill(Color col) { int i, n; n = this->xsize * this->ysize * this->zsize; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { this->data[i] = col; } } -void Texture3D::add(Texture3D* source) -{ +void Texture3D::add(Texture3D *source) { int i, n; assert(source->xsize == this->xsize); @@ -137,8 +135,7 @@ void Texture3D::add(Texture3D* source) assert(source->zsize == this->zsize); n = source->xsize * source->ysize * source->zsize; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { this->data[i].r += source->data[i].r; this->data[i].g += source->data[i].g; this->data[i].b += source->data[i].b; @@ -146,21 +143,18 @@ void Texture3D::add(Texture3D* source) } } -void Texture3D::save(PackStream* stream) const -{ +void Texture3D::save(PackStream *stream) const { int i, n; stream->write(&this->xsize); stream->write(&this->ysize); stream->write(&this->zsize); n = this->xsize * this->ysize * this->zsize; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { (this->data + i)->save(stream); } } -void Texture3D::load(PackStream* stream) -{ +void Texture3D::load(PackStream *stream) { int i, n; stream->read(&this->xsize); stream->read(&this->ysize); @@ -168,19 +162,17 @@ void Texture3D::load(PackStream* stream) n = this->xsize * this->ysize * this->zsize; delete[] this->data; this->data = new Color[n]; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { (this->data + i)->load(stream); } } -class Texture3DWriter:public PictureWriter -{ -public: - Texture3DWriter(const Texture3D *tex): tex(tex) {} +class Texture3DWriter : public PictureWriter { + public: + Texture3DWriter(const Texture3D *tex) : tex(tex) { + } - virtual unsigned int getPixel(int x, int y) override - { + virtual unsigned int getPixel(int x, int y) override { int xsize, ysize, zsize; tex->getSize(&xsize, &ysize, &zsize); @@ -189,12 +181,12 @@ public: return tex->getPixel(x, y, z).to32BitBGRA(); } -private: + + private: const Texture3D *tex; }; -void Texture3D::saveToFile(const std::string &filepath) const -{ +void Texture3D::saveToFile(const std::string &filepath) const { Texture3DWriter writer(this); writer.save(filepath, xsize, ysize * zsize); } diff --git a/src/basics/Texture3D.h b/src/basics/Texture3D.h index b73301c..4cd9331 100644 --- a/src/basics/Texture3D.h +++ b/src/basics/Texture3D.h @@ -6,31 +6,29 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT Texture3D -{ -public: +class BASICSSHARED_EXPORT Texture3D { + public: Texture3D(int xsize, int ysize, int zsize); ~Texture3D(); - void getSize(int* xsize, int* ysize, int* zsize) const; + void getSize(int *xsize, int *ysize, int *zsize) const; void setPixel(int x, int y, int z, Color col); Color getPixel(int x, int y, int z) const; Color getNearest(double dx, double dy, double dz) const; Color getLinear(double dx, double dy, double dz) const; Color getCubic(double dx, double dy, double dz) const; void fill(Color col); - void add(Texture3D* other); - void save(PackStream* stream) const; - void load(PackStream* stream); + void add(Texture3D *other); + void save(PackStream *stream) const; + void load(PackStream *stream); void saveToFile(const std::string &filepath) const; -private: + private: int xsize; int ysize; int zsize; - Color* data; + Color *data; }; - } } diff --git a/src/basics/Texture4D.cpp b/src/basics/Texture4D.cpp index 877ea4b..b7cfcd5 100644 --- a/src/basics/Texture4D.cpp +++ b/src/basics/Texture4D.cpp @@ -5,8 +5,7 @@ #include "PackStream.h" #include "PictureWriter.h" -Texture4D::Texture4D(int xsize, int ysize, int zsize, int wsize) -{ +Texture4D::Texture4D(int xsize, int ysize, int zsize, int wsize) { assert(xsize > 0 && ysize > 0 && zsize > 0 && wsize > 0); this->xsize = xsize; @@ -16,21 +15,18 @@ Texture4D::Texture4D(int xsize, int ysize, int zsize, int wsize) this->data = new Color[xsize * ysize * zsize * wsize]; } -Texture4D::~Texture4D() -{ +Texture4D::~Texture4D() { delete[] data; } -void Texture4D::getSize(int* xsize, int* ysize, int* zsize, int* wsize) const -{ +void Texture4D::getSize(int *xsize, int *ysize, int *zsize, int *wsize) const { *xsize = this->xsize; *ysize = this->ysize; *zsize = this->zsize; *wsize = this->wsize; } -void Texture4D::setPixel(int x, int y, int z, int w, Color col) -{ +void Texture4D::setPixel(int x, int y, int z, int w, Color col) { assert(x >= 0 && x < this->xsize); assert(y >= 0 && y < this->ysize); assert(z >= 0 && z < this->zsize); @@ -39,26 +35,33 @@ void Texture4D::setPixel(int x, int y, int z, int w, Color col) this->data[w * this->xsize * this->ysize * this->zsize + z * this->xsize * this->ysize + y * this->xsize + x] = col; } -Color Texture4D::getPixel(int x, int y, int z, int w) const -{ +Color Texture4D::getPixel(int x, int y, int z, int w) const { assert(x >= 0 && x < this->xsize); assert(y >= 0 && y < this->ysize); assert(z >= 0 && z < this->zsize); assert(w >= 0 && w < this->wsize); - return this->data[w * this->xsize * this->ysize * this->zsize + z * this->xsize * this->ysize + y * this->xsize + x]; + return this + ->data[w * this->xsize * this->ysize * this->zsize + z * this->xsize * this->ysize + y * this->xsize + x]; } -Color Texture4D::getNearest(double dx, double dy, double dz, double dw) const -{ - if (dx < 0.0) dx = 0.0; - if (dx > 1.0) dx = 1.0; - if (dy < 0.0) dy = 0.0; - if (dy > 1.0) dy = 1.0; - if (dz < 0.0) dz = 0.0; - if (dz > 1.0) dz = 1.0; - if (dw < 0.0) dw = 0.0; - if (dw > 1.0) dw = 1.0; +Color Texture4D::getNearest(double dx, double dy, double dz, double dw) const { + if (dx < 0.0) + dx = 0.0; + if (dx > 1.0) + dx = 1.0; + if (dy < 0.0) + dy = 0.0; + if (dy > 1.0) + dy = 1.0; + if (dz < 0.0) + dz = 0.0; + if (dz > 1.0) + dz = 1.0; + if (dw < 0.0) + dw = 0.0; + if (dw > 1.0) + dw = 1.0; int ix = (int)(dx * (double)(this->xsize - 1)); int iy = (int)(dy * (double)(this->ysize - 1)); @@ -70,19 +73,27 @@ Color Texture4D::getNearest(double dx, double dy, double dz, double dw) const assert(iz >= 0 && iz < this->zsize); assert(iw >= 0 && iw < this->wsize); - return this->data[iw * this->xsize * this->ysize * this->zsize + iz * this->xsize * this->ysize + iy * this->xsize + ix]; + return this + ->data[iw * this->xsize * this->ysize * this->zsize + iz * this->xsize * this->ysize + iy * this->xsize + ix]; } -Color Texture4D::getLinear(double dx, double dy, double dz, double dw) const -{ - if (dx < 0.0) dx = 0.0; - if (dx > 1.0) dx = 1.0; - if (dy < 0.0) dy = 0.0; - if (dy > 1.0) dy = 1.0; - if (dz < 0.0) dz = 0.0; - if (dz > 1.0) dz = 1.0; - if (dw < 0.0) dw = 0.0; - if (dw > 1.0) dw = 1.0; +Color Texture4D::getLinear(double dx, double dy, double dz, double dw) const { + if (dx < 0.0) + dx = 0.0; + if (dx > 1.0) + dx = 1.0; + if (dy < 0.0) + dy = 0.0; + if (dy > 1.0) + dy = 1.0; + if (dz < 0.0) + dz = 0.0; + if (dz > 1.0) + dz = 1.0; + if (dw < 0.0) + dw = 0.0; + if (dw > 1.0) + dw = 1.0; dx *= (double)(this->xsize - 1); dy *= (double)(this->ysize - 1); @@ -90,23 +101,19 @@ Color Texture4D::getLinear(double dx, double dy, double dz, double dw) const dw *= (double)(this->wsize - 1); int ix = (int)floor(dx); - if (ix == this->xsize - 1) - { + if (ix == this->xsize - 1) { ix--; } int iy = (int)floor(dy); - if (iy == this->ysize - 1) - { + if (iy == this->ysize - 1) { iy--; } int iz = (int)floor(dz); - if (iz == this->zsize - 1) - { + if (iz == this->zsize - 1) { iz--; } int iw = (int)floor(dw); - if (iw == this->wsize - 1) - { + if (iw == this->wsize - 1) { iw--; } @@ -115,7 +122,8 @@ Color Texture4D::getLinear(double dx, double dy, double dz, double dw) const dz -= (double)iz; dw -= (double)iw; - Color* data = this->data + iw * this->xsize * this->ysize * this->zsize + iz * this->xsize * this->ysize + iy * this->xsize + ix; + Color *data = this->data + iw * this->xsize * this->ysize * this->zsize + iz * this->xsize * this->ysize + + iy * this->xsize + ix; Color cz1, cz2; Color cx1 = data->lerp(*(data + 1), dx); @@ -143,24 +151,20 @@ Color Texture4D::getLinear(double dx, double dy, double dz, double dw) const return cz1.lerp(cz2, dw); } -Color Texture4D::getCubic(double dx, double dy, double dz, double dw) const -{ +Color Texture4D::getCubic(double dx, double dy, double dz, double dw) const { /* TODO */ return getLinear(dx, dy, dz, dw); } -void Texture4D::fill(Color col) -{ +void Texture4D::fill(Color col) { int i, n; n = this->xsize * this->ysize * this->zsize * this->wsize; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { this->data[i] = col; } } -void Texture4D::add(Texture4D* source) -{ +void Texture4D::add(Texture4D *source) { int i, n; assert(source->xsize == this->xsize); @@ -169,8 +173,7 @@ void Texture4D::add(Texture4D* source) assert(source->wsize == this->wsize); n = source->xsize * source->ysize * source->zsize * source->wsize; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { this->data[i].r += source->data[i].r; this->data[i].g += source->data[i].g; this->data[i].b += source->data[i].b; @@ -178,22 +181,19 @@ void Texture4D::add(Texture4D* source) } } -void Texture4D::save(PackStream* stream) const -{ +void Texture4D::save(PackStream *stream) const { int i, n; stream->write(&this->xsize); stream->write(&this->ysize); stream->write(&this->zsize); stream->write(&this->wsize); n = this->xsize * this->ysize * this->zsize * this->wsize; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { (this->data + i)->save(stream); } } -void Texture4D::load(PackStream* stream) -{ +void Texture4D::load(PackStream *stream) { int i, n; stream->read(&this->xsize); stream->read(&this->ysize); @@ -202,20 +202,17 @@ void Texture4D::load(PackStream* stream) n = this->xsize * this->ysize * this->zsize * this->wsize; delete[] this->data; this->data = new Color[n]; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { (this->data + i)->load(stream); } } +class Texture4DWriter : public PictureWriter { + public: + Texture4DWriter(const Texture4D *tex) : tex(tex) { + } -class Texture4DWriter:public PictureWriter -{ -public: - Texture4DWriter(const Texture4D *tex): tex(tex) {} - - virtual unsigned int getPixel(int x, int y) override - { + virtual unsigned int getPixel(int x, int y) override { int xsize, ysize, zsize, wsize; tex->getSize(&xsize, &ysize, &zsize, &wsize); @@ -227,12 +224,12 @@ public: return tex->getPixel(x, y, z, w).to32BitBGRA(); } -private: + + private: const Texture4D *tex; }; -void Texture4D::saveToFile(const std::string &filepath) const -{ +void Texture4D::saveToFile(const std::string &filepath) const { Texture4DWriter writer(this); writer.save(filepath, xsize * wsize, ysize * zsize); } diff --git a/src/basics/Texture4D.h b/src/basics/Texture4D.h index 18a863f..7ab877e 100644 --- a/src/basics/Texture4D.h +++ b/src/basics/Texture4D.h @@ -6,32 +6,30 @@ namespace paysages { namespace basics { -class BASICSSHARED_EXPORT Texture4D -{ -public: +class BASICSSHARED_EXPORT Texture4D { + public: Texture4D(int xsize, int ysize, int zsize, int wsize); ~Texture4D(); - void getSize(int* xsize, int* ysize, int* zsize, int* wsize) const; + void getSize(int *xsize, int *ysize, int *zsize, int *wsize) const; void setPixel(int x, int y, int z, int w, Color col); Color getPixel(int x, int y, int z, int w) const; Color getNearest(double dx, double dy, double dz, double dw) const; Color getLinear(double dx, double dy, double dz, double dw) const; Color getCubic(double dx, double dy, double dz, double dw) const; void fill(Color col); - void add(Texture4D* other); - void save(PackStream* stream) const; - void load(PackStream* stream); + void add(Texture4D *other); + void save(PackStream *stream) const; + void load(PackStream *stream); void saveToFile(const std::string &filepath) const; -private: + private: int xsize; int ysize; int zsize; int wsize; - Color* data; + Color *data; }; - } } diff --git a/src/basics/Vector3.cpp b/src/basics/Vector3.cpp index 92db091..57e72f4 100644 --- a/src/basics/Vector3.cpp +++ b/src/basics/Vector3.cpp @@ -12,41 +12,31 @@ const Vector3 paysages::basics::VECTOR_SOUTH(0.0, 0.0, 1.0); const Vector3 paysages::basics::VECTOR_WEST(-1.0, 0.0, 0.0); const Vector3 paysages::basics::VECTOR_EAST(1.0, 0.0, 0.0); -Vector3::Vector3(const VectorSpherical &v): - x(v.r * cos(v.phi) * cos(v.theta)), y(v.r * sin(v.theta)), z(-v.r * sin(v.phi) * cos(v.theta)) -{ +Vector3::Vector3(const VectorSpherical &v) + : x(v.r * cos(v.phi) * cos(v.theta)), y(v.r * sin(v.theta)), z(-v.r * sin(v.phi) * cos(v.theta)) { } -void Vector3::save(PackStream* stream) const -{ +void Vector3::save(PackStream *stream) const { stream->write(&x); stream->write(&y); stream->write(&z); } -void Vector3::load(PackStream* stream) -{ +void Vector3::load(PackStream *stream) { stream->read(&x); stream->read(&y); stream->read(&z); } -static inline double _euclidGet2DAngle(double x, double y) -{ +static inline double _euclidGet2DAngle(double x, double y) { // TEMP Copy of old euclid.c double nx, ny, d, ret; - if (x == 0.0) - { - if (y == 0.0) - { + if (x == 0.0) { + if (y == 0.0) { return 0.0; - } - else if (y < 0.0) - { + } else if (y < 0.0) { return 3.0 * M_PI_2; - } - else - { + } else { return M_PI_2; } } @@ -56,21 +46,18 @@ static inline double _euclidGet2DAngle(double x, double y) ny = y / d; ret = asin(ny); - if (nx < 0.0) - { + if (nx < 0.0) { ret = M_PI - ret; } return ret < 0.0 ? ret + 2.0 * M_PI : ret; } -VectorSpherical Vector3::toSpherical() const -{ +VectorSpherical Vector3::toSpherical() const { VectorSpherical result; result.phi = _euclidGet2DAngle(x, -z); result.theta = _euclidGet2DAngle(sqrt(x * x + z * z), y); - if (y < 0.0) - { + if (y < 0.0) { result.theta -= 2.0 * M_PI; } result.r = getNorm(); @@ -78,19 +65,14 @@ VectorSpherical Vector3::toSpherical() const return result; } -Vector3 Vector3::midPointTo(const Vector3 &other) const -{ +Vector3 Vector3::midPointTo(const Vector3 &other) const { return Vector3((other.x + x) * 0.5, (other.y + y) * 0.5, (other.z + z) * 0.5); } -Vector3 Vector3::randomInSphere(double radius, bool only_surface) -{ +Vector3 Vector3::randomInSphere(double radius, bool only_surface) { // TODO More uniform spatial repartition // The current randomization clusters result near the center and at the poles - VectorSpherical vec = { - only_surface ? radius : RandomGenerator::random() * radius, - (RandomGenerator::random() - 0.5) * M_PI, - RandomGenerator::random() * M_2PI - }; + VectorSpherical vec = {only_surface ? radius : RandomGenerator::random() * radius, + (RandomGenerator::random() - 0.5) * M_PI, RandomGenerator::random() * M_2PI}; return Vector3(vec); } diff --git a/src/basics/Vector3.h b/src/basics/Vector3.h index c380241..bc77d13 100644 --- a/src/basics/Vector3.h +++ b/src/basics/Vector3.h @@ -33,16 +33,14 @@ namespace basics { * X=0 Y=-1 Z=0 => THETA=-PI/2 */ -typedef struct -{ +typedef struct { double r; double theta; double phi; } VectorSpherical; -class BASICSSHARED_EXPORT Vector3 -{ -public: +class BASICSSHARED_EXPORT Vector3 { + public: Vector3() = default; Vector3(double x, double y, double z); Vector3(const VectorSpherical &v); @@ -73,9 +71,9 @@ public: * * If *only_surface* is true, produce a vector with *radius* as length. */ - static Vector3 randomInSphere(double radius=1.0, bool only_surface=false); + static Vector3 randomInSphere(double radius = 1.0, bool only_surface = false); -public: + public: // TODO Make private double x; double y; @@ -89,7 +87,6 @@ BASICSSHARED_EXPORT extern const Vector3 VECTOR_NORTH; BASICSSHARED_EXPORT extern const Vector3 VECTOR_SOUTH; BASICSSHARED_EXPORT extern const Vector3 VECTOR_EAST; BASICSSHARED_EXPORT extern const Vector3 VECTOR_WEST; - } } diff --git a/src/basics/Vector3.inline.cpp b/src/basics/Vector3.inline.cpp index 38f0f7f..a92d61b 100644 --- a/src/basics/Vector3.inline.cpp +++ b/src/basics/Vector3.inline.cpp @@ -1,73 +1,55 @@ #define VECTOR3_INLINE_CPP #ifdef VECTOR3_H -# define METHSPEC inline +#define METHSPEC inline #else -# include "Vector3.h" -# define METHSPEC +#include "Vector3.h" +#define METHSPEC #endif #include -METHSPEC Vector3::Vector3(double x, double y, double z): - x(x), y(y), z(z) -{ +METHSPEC Vector3::Vector3(double x, double y, double z) : x(x), y(y), z(z) { } -METHSPEC Vector3 Vector3::add(double x, double y, double z) const -{ +METHSPEC Vector3 Vector3::add(double x, double y, double z) const { return Vector3(this->x + x, this->y + y, this->z + z); } -METHSPEC Vector3 Vector3::add(const Vector3 &other) const -{ +METHSPEC Vector3 Vector3::add(const Vector3 &other) const { return Vector3(x + other.x, y + other.y, z + other.z); } -METHSPEC Vector3 Vector3::sub(const Vector3 &other) const -{ +METHSPEC Vector3 Vector3::sub(const Vector3 &other) const { return Vector3(x - other.x, y - other.y, z - other.z); } -METHSPEC Vector3 Vector3::inverse() const -{ +METHSPEC Vector3 Vector3::inverse() const { return Vector3(-x, -y, -z); } -METHSPEC Vector3 Vector3::scale(double scaling) const -{ +METHSPEC Vector3 Vector3::scale(double scaling) const { return Vector3(x * scaling, y * scaling, z * scaling); } -METHSPEC double Vector3::getNorm() const -{ +METHSPEC double Vector3::getNorm() const { return sqrt(x * x + y * y + z * z); } -METHSPEC Vector3 Vector3::normalize() const -{ +METHSPEC Vector3 Vector3::normalize() const { double norm = sqrt(x * x + y * y + z * z); - if (norm == 0.0) - { + if (norm == 0.0) { return VECTOR_ZERO; - } - else - { + } else { norm = 1.0 / norm; return Vector3(x * norm, y * norm, z * norm); } } -METHSPEC double Vector3:: dotProduct(const Vector3 &other) const -{ +METHSPEC double Vector3::dotProduct(const Vector3 &other) const { return x * other.x + y * other.y + z * other.z; } -METHSPEC Vector3 Vector3::crossProduct(const Vector3 &other) const -{ - return Vector3( - y * other.z - z * other.y, - z * other.x - x * other.z, - x * other.y - y * other.x - ); +METHSPEC Vector3 Vector3::crossProduct(const Vector3 &other) const { + return Vector3(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x); } diff --git a/src/basics/basics_global.h b/src/basics/basics_global.h index 6190283..027eee7 100644 --- a/src/basics/basics_global.h +++ b/src/basics/basics_global.h @@ -3,33 +3,33 @@ #include #if defined(BASICS_LIBRARY) -# define BASICSSHARED_EXPORT Q_DECL_EXPORT +#define BASICSSHARED_EXPORT Q_DECL_EXPORT #else -# define BASICSSHARED_EXPORT Q_DECL_IMPORT +#define BASICSSHARED_EXPORT Q_DECL_IMPORT #endif #include "system_global.h" namespace paysages { namespace basics { - class Vector3; - class Matrix4; - class BoundingBox; - class SpaceGridIterator; - class SpaceSegment; - class Color; - class NoiseGenerator; - class NoiseState; - class FractalNoise; - class Curve; - class ColorProfile; - class Texture2D; - class Texture3D; - class Texture4D; - class CappedCylinder; - class InfiniteRay; - class Sphere; - class InfinitePlane; +class Vector3; +class Matrix4; +class BoundingBox; +class SpaceGridIterator; +class SpaceSegment; +class Color; +class NoiseGenerator; +class NoiseState; +class FractalNoise; +class Curve; +class ColorProfile; +class Texture2D; +class Texture3D; +class Texture4D; +class CappedCylinder; +class InfiniteRay; +class Sphere; +class InfinitePlane; } } using namespace paysages::basics; diff --git a/src/definition/AtmosphereDefinition.cpp b/src/definition/AtmosphereDefinition.cpp index e96c8cd..5ab7f1d 100644 --- a/src/definition/AtmosphereDefinition.cpp +++ b/src/definition/AtmosphereDefinition.cpp @@ -5,24 +5,21 @@ #include "FloatNode.h" #include "GodRaysDefinition.h" -AtmosphereDefinition::AtmosphereDefinition(DefinitionNode* parent): - DefinitionNode(parent, "atmosphere", "atmosphere") -{ +AtmosphereDefinition::AtmosphereDefinition(DefinitionNode *parent) + : DefinitionNode(parent, "atmosphere", "atmosphere") { godrays = new GodRaysDefinition(this); daytime = new FloatNode(this, "daytime"); humidity = new FloatNode(this, "humidity"); sun_radius = new FloatNode(this, "sun_radius"); } -AtmosphereDefinition::~AtmosphereDefinition() -{ +AtmosphereDefinition::~AtmosphereDefinition() { } -void AtmosphereDefinition::save(PackStream* stream) const -{ +void AtmosphereDefinition::save(PackStream *stream) const { DefinitionNode::save(stream); - stream->write((int*)&model); + stream->write((int *)&model); sun_color.save(stream); stream->write(&dome_lighting); stream->write(&moon_radius); @@ -31,19 +28,17 @@ void AtmosphereDefinition::save(PackStream* stream) const int star_count = stars.size(); stream->write(&star_count); - for (const auto &star : stars) - { + for (const auto &star : stars) { star.location.save(stream); star.col.save(stream); stream->write(&star.radius); } } -void AtmosphereDefinition::load(PackStream* stream) -{ +void AtmosphereDefinition::load(PackStream *stream) { DefinitionNode::load(stream); - stream->read((int*)&model); + stream->read((int *)&model); sun_color.load(stream); stream->read(&dome_lighting); stream->read(&moon_radius); @@ -52,8 +47,7 @@ void AtmosphereDefinition::load(PackStream* stream) int star_count; stream->read(&star_count); - for (int i = 0; i < star_count; i++) - { + for (int i = 0; i < star_count; i++) { Star star; star.location.load(stream); @@ -66,11 +60,10 @@ void AtmosphereDefinition::load(PackStream* stream) validate(); } -void AtmosphereDefinition::copy(DefinitionNode* _destination) const -{ +void AtmosphereDefinition::copy(DefinitionNode *_destination) const { DefinitionNode::copy(_destination); - AtmosphereDefinition* destination = (AtmosphereDefinition*)_destination; + AtmosphereDefinition *destination = (AtmosphereDefinition *)_destination; destination->model = model; destination->sun_color = sun_color; @@ -83,25 +76,19 @@ void AtmosphereDefinition::copy(DefinitionNode* _destination) const destination->validate(); } -void AtmosphereDefinition::setDayTime(double value) -{ +void AtmosphereDefinition::setDayTime(double value) { daytime->setValue(value); } -void AtmosphereDefinition::setDayTime(int hour, int minute, int second) -{ +void AtmosphereDefinition::setDayTime(int hour, int minute, int second) { setDayTime((double)hour / 24.0 + (double)minute / 1440.0 + (double)second / 86400.0); } -void AtmosphereDefinition::getHMS(int *hour, int *minute, int *second) const -{ +void AtmosphereDefinition::getHMS(int *hour, int *minute, int *second) const { double value = daytime->getValue(); - if (value >= 0.0) - { + if (value >= 0.0) { value = fmod(value, 1.0); - } - else - { + } else { value = 1.0 - fmod(-value, 1.0); } value *= 86400.0; @@ -111,8 +98,7 @@ void AtmosphereDefinition::getHMS(int *hour, int *minute, int *second) const *second = value - *minute * 60.0; } -void AtmosphereDefinition::applyPreset(AtmospherePreset preset) -{ +void AtmosphereDefinition::applyPreset(AtmospherePreset preset) { sun_color.r = 1.0; sun_color.g = 0.95; sun_color.b = 0.9; @@ -124,35 +110,34 @@ void AtmosphereDefinition::applyPreset(AtmospherePreset preset) model = ATMOSPHERE_MODEL_BRUNETON; - switch (preset) - { - case ATMOSPHERE_PRESET_CLEAR_DAY: - setDayTime(15); - humidity->setValue(0.1); - dome_lighting = 0.2; - break; - case ATMOSPHERE_PRESET_CLEAR_SUNSET: - setDayTime(17, 45); - humidity->setValue(0.1); - dome_lighting = 0.3; - break; - case ATMOSPHERE_PRESET_HAZY_MORNING: - setDayTime(8, 30); - humidity->setValue(0.4); - dome_lighting = 0.25; - break; - case ATMOSPHERE_PRESET_FOGGY: - setDayTime(15); - humidity->setValue(0.7); - dome_lighting = 0.1; - break; - case ATMOSPHERE_PRESET_STORMY: - setDayTime(15); - humidity->setValue(0.9); - dome_lighting = 0.05; - break; - default: - ; + switch (preset) { + case ATMOSPHERE_PRESET_CLEAR_DAY: + setDayTime(15); + humidity->setValue(0.1); + dome_lighting = 0.2; + break; + case ATMOSPHERE_PRESET_CLEAR_SUNSET: + setDayTime(17, 45); + humidity->setValue(0.1); + dome_lighting = 0.3; + break; + case ATMOSPHERE_PRESET_HAZY_MORNING: + setDayTime(8, 30); + humidity->setValue(0.4); + dome_lighting = 0.25; + break; + case ATMOSPHERE_PRESET_FOGGY: + setDayTime(15); + humidity->setValue(0.7); + dome_lighting = 0.1; + break; + case ATMOSPHERE_PRESET_STORMY: + setDayTime(15); + humidity->setValue(0.9); + dome_lighting = 0.05; + break; + default: + ; } generateStars(2000); @@ -160,22 +145,22 @@ void AtmosphereDefinition::applyPreset(AtmospherePreset preset) validate(); } -void AtmosphereDefinition::generateStars(int count) -{ +void AtmosphereDefinition::generateStars(int count) { stars.clear(); - for (int i = 0; i < count; ++i) - { + for (int i = 0; i < count; ++i) { Star star; - star.location = Vector3((RandomGenerator::random() - 0.5) * 100000.0, (RandomGenerator::random() * 0.5) * 100000.0, (RandomGenerator::random() - 0.5) * 100000.0); - if (star.location.getNorm() < 30000.0) - { + star.location = + Vector3((RandomGenerator::random() - 0.5) * 100000.0, (RandomGenerator::random() * 0.5) * 100000.0, + (RandomGenerator::random() - 0.5) * 100000.0); + if (star.location.getNorm() < 30000.0) { i--; continue; } double brillance = RandomGenerator::random() * 0.05 + 0.1; - star.col = Color(brillance + RandomGenerator::random() * 0.03, brillance + RandomGenerator::random() * 0.03, brillance + RandomGenerator::random() * 0.03, 1.0); + star.col = Color(brillance + RandomGenerator::random() * 0.03, brillance + RandomGenerator::random() * 0.03, + brillance + RandomGenerator::random() * 0.03, 1.0); star.radius = 30.0 + RandomGenerator::random() * 20.0; stars.push_back(star); diff --git a/src/definition/AtmosphereDefinition.h b/src/definition/AtmosphereDefinition.h index 20f43ee..a4affb0 100644 --- a/src/definition/AtmosphereDefinition.h +++ b/src/definition/AtmosphereDefinition.h @@ -11,24 +11,17 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT AtmosphereDefinition : public DefinitionNode -{ -public: - typedef struct - { +class DEFINITIONSHARED_EXPORT AtmosphereDefinition : public DefinitionNode { + public: + typedef struct { Vector3 location; double radius; Color col; } Star; -public: - typedef enum - { - ATMOSPHERE_MODEL_DISABLED = 0, - ATMOSPHERE_MODEL_BRUNETON = 1 - } AtmosphereModel; - typedef enum - { + public: + typedef enum { ATMOSPHERE_MODEL_DISABLED = 0, ATMOSPHERE_MODEL_BRUNETON = 1 } AtmosphereModel; + typedef enum { ATMOSPHERE_PRESET_CLEAR_DAY = 0, ATMOSPHERE_PRESET_CLEAR_SUNSET = 1, ATMOSPHERE_PRESET_HAZY_MORNING = 2, @@ -36,19 +29,27 @@ public: ATMOSPHERE_PRESET_STORMY = 4 } AtmospherePreset; -public: - AtmosphereDefinition(DefinitionNode* parent); + public: + AtmosphereDefinition(DefinitionNode *parent); virtual ~AtmosphereDefinition(); - virtual void save(PackStream* stream) const override; - virtual void load(PackStream* stream) override; + virtual void save(PackStream *stream) const override; + virtual void load(PackStream *stream) override; - virtual void copy(DefinitionNode* destination) const override; + virtual void copy(DefinitionNode *destination) const override; - inline GodRaysDefinition *childGodRays() const {return godrays;} - inline FloatNode *propDayTime() const {return daytime;} - inline FloatNode *propHumidity() const {return humidity;} - inline FloatNode *propSunRadius() const {return sun_radius;} + inline GodRaysDefinition *childGodRays() const { + return godrays; + } + inline FloatNode *propDayTime() const { + return daytime; + } + inline FloatNode *propHumidity() const { + return humidity; + } + inline FloatNode *propSunRadius() const { + return sun_radius; + } /** * Set the daytime from a 0.0-1.0 value. @@ -57,7 +58,7 @@ public: /** * Set the daytime from hour/minute/second info. */ - void setDayTime(int hour, int minute=0, int second=0); + void setDayTime(int hour, int minute = 0, int second = 0); /** * Get the daytime info, in hour/minute/second. */ @@ -66,7 +67,7 @@ public: void applyPreset(AtmospherePreset preset); void generateStars(int count); -public: + public: AtmosphereModel model; Color sun_color; @@ -78,13 +79,12 @@ public: std::vector stars; -private: + private: GodRaysDefinition *godrays; FloatNode *humidity; FloatNode *daytime; FloatNode *sun_radius; }; - } } diff --git a/src/definition/CameraDefinition.cpp b/src/definition/CameraDefinition.cpp index 817f258..e984f80 100644 --- a/src/definition/CameraDefinition.cpp +++ b/src/definition/CameraDefinition.cpp @@ -4,9 +4,7 @@ #include "PackStream.h" #include "BoundingBox.h" -CameraDefinition::CameraDefinition(DefinitionNode *parent): - DefinitionNode(parent, "camera", "camera") -{ +CameraDefinition::CameraDefinition(DefinitionNode *parent) : DefinitionNode(parent, "camera", "camera") { location.x = 0.0; location.y = 0.0; location.z = 0.0; @@ -25,8 +23,7 @@ CameraDefinition::CameraDefinition(DefinitionNode *parent): validate(); } -void CameraDefinition::save(PackStream* stream) const -{ +void CameraDefinition::save(PackStream *stream) const { location.save(stream); stream->write(&direction.r); stream->write(&direction.phi); @@ -35,8 +32,7 @@ void CameraDefinition::save(PackStream* stream) const stream->write(&perspective.yfov); } -void CameraDefinition::load(PackStream* stream) -{ +void CameraDefinition::load(PackStream *stream) { location.load(stream); stream->read(&direction.r); stream->read(&direction.phi); @@ -47,9 +43,8 @@ void CameraDefinition::load(PackStream* stream) validate(); } -void CameraDefinition::copy(DefinitionNode* _destination) const -{ - CameraDefinition* destination = (CameraDefinition*)_destination; +void CameraDefinition::copy(DefinitionNode *_destination) const { + CameraDefinition *destination = (CameraDefinition *)_destination; destination->location = location; destination->direction = direction; @@ -60,10 +55,8 @@ void CameraDefinition::copy(DefinitionNode* _destination) const destination->validate(); } -void CameraDefinition::validate() -{ - if (location.y > 300.0) - { +void CameraDefinition::validate() { + if (location.y > 300.0) { location.y = 300.0; } @@ -85,7 +78,8 @@ void CameraDefinition::validate() target = location.add(direction); - Matrix4 mperspective = Matrix4::newPerspective(perspective.yfov, perspective.xratio, perspective.znear, perspective.zfar); + Matrix4 mperspective = + Matrix4::newPerspective(perspective.yfov, perspective.xratio, perspective.znear, perspective.zfar); unperspective = mperspective.inversed(); projector = mperspective.mult(Matrix4::newLookAt(location, target, up)); @@ -95,33 +89,28 @@ void CameraDefinition::validate() inv_y_factor = 1.0 / (0.5 * height); } -double CameraDefinition::getRealDepth(const Vector3 &projected) const -{ +double CameraDefinition::getRealDepth(const Vector3 &projected) const { Vector3 v(projected.x * inv_x_factor - 1.0, -(projected.y * inv_x_factor - 1.0), projected.z); return unperspective.transform(v).z; } -void CameraDefinition::setLocation(const Vector3 &location) -{ +void CameraDefinition::setLocation(const Vector3 &location) { this->location = location; validate(); } -void CameraDefinition::setLocationCoords(double x, double y, double z) -{ +void CameraDefinition::setLocationCoords(double x, double y, double z) { location = Vector3(x, y, z); validate(); } -void CameraDefinition::setTarget(const Vector3 &target) -{ +void CameraDefinition::setTarget(const Vector3 &target) { Vector3 forward; forward = target.sub(location); - if (forward.getNorm() < 0.0000001) - { + if (forward.getNorm() < 0.0000001) { return; } @@ -130,77 +119,66 @@ void CameraDefinition::setTarget(const Vector3 &target) validate(); } -void CameraDefinition::setTargetCoords(double x, double y, double z) -{ +void CameraDefinition::setTargetCoords(double x, double y, double z) { setTarget(Vector3(x, y, z)); } -void CameraDefinition::setRoll(double angle) -{ +void CameraDefinition::setRoll(double angle) { roll = angle; validate(); } -void CameraDefinition::setZoomToTarget(double zoom) -{ +void CameraDefinition::setZoomToTarget(double zoom) { direction.r = zoom; location = target.add(Vector3(direction).scale(-1.0)); validate(); } -void CameraDefinition::setFov(double fov) -{ +void CameraDefinition::setFov(double fov) { perspective.yfov = fov; validate(); } -void CameraDefinition::strafeForward(double value) -{ +void CameraDefinition::strafeForward(double value) { location = location.add(forward.scale(value)); validate(); } -void CameraDefinition::strafeRight(double value) -{ +void CameraDefinition::strafeRight(double value) { location = location.add(right.scale(value)); validate(); } -void CameraDefinition::strafeUp(double value) -{ +void CameraDefinition::strafeUp(double value) { location = location.add(up.scale(value)); validate(); } -void CameraDefinition::rotateYaw(double value) -{ +void CameraDefinition::rotateYaw(double value) { direction.phi += value; validate(); } -void CameraDefinition::rotatePitch(double value) -{ +void CameraDefinition::rotatePitch(double value) { direction.theta += value; validate(); } -void CameraDefinition::rotateRoll(double value) -{ +void CameraDefinition::rotateRoll(double value) { roll += value; validate(); } -void CameraDefinition::setRenderSize(int width, int height) -{ +void CameraDefinition::setRenderSize(int width, int height) { this->width = (double)width; this->height = (double)height; perspective.xratio = this->width / this->height; @@ -208,11 +186,9 @@ void CameraDefinition::setRenderSize(int width, int height) validate(); } -Vector3 CameraDefinition::project(const Vector3 &point) const -{ +Vector3 CameraDefinition::project(const Vector3 &point) const { Vector3 tpoint = projector.transform(point); - if (tpoint.z < 1.0) - { + if (tpoint.z < 1.0) { tpoint.x = -tpoint.x; tpoint.y = -tpoint.y; } @@ -221,19 +197,16 @@ Vector3 CameraDefinition::project(const Vector3 &point) const return tpoint; } -Vector3 CameraDefinition::unproject(const Vector3 &point) const -{ +Vector3 CameraDefinition::unproject(const Vector3 &point) const { Vector3 tpoint(point.x / (0.5 * width) - 1.0, -(point.y / (0.5 * height) - 1.0), point.z); - if (tpoint.z < 1.0) - { + if (tpoint.z < 1.0) { tpoint.x = -tpoint.x; tpoint.y = -tpoint.y; } return unprojector.transform(tpoint); } -int CameraDefinition::isBoxInView(const Vector3 ¢er, double xsize, double ysize, double zsize) const -{ +int CameraDefinition::isBoxInView(const Vector3 ¢er, double xsize, double ysize, double zsize) const { BoundingBox box; box.pushPoint(center.add(Vector3(-xsize, -ysize, -zsize))); @@ -242,8 +215,7 @@ int CameraDefinition::isBoxInView(const Vector3 ¢er, double xsize, double ys return isUnprojectedBoxInView(box); } -int CameraDefinition::isUnprojectedBoxInView(const BoundingBox &box) const -{ +int CameraDefinition::isUnprojectedBoxInView(const BoundingBox &box) const { BoundingBox projected; projected.pushPoint(project(Vector3(box.xmin, box.ymin, box.zmin))); @@ -258,23 +230,19 @@ int CameraDefinition::isUnprojectedBoxInView(const BoundingBox &box) const return isProjectedBoxInView(projected); } -int CameraDefinition::isProjectedBoxInView(const BoundingBox &box) const -{ - if (box.xmin <= width && box.xmax >= 0.0 && box.ymin <= height && box.ymax >= 0.0 && box.zmax >= perspective.znear) - { +int CameraDefinition::isProjectedBoxInView(const BoundingBox &box) const { + if (box.xmin <= width && box.xmax >= 0.0 && box.ymin <= height && box.ymax >= 0.0 && + box.zmax >= perspective.znear) { double dx = box.xmax - box.xmin; double dy = box.ymax - box.ymin; return (int)ceil(dx) * (int)ceil(dy); - } - else - { + } else { return 0; } } -bool CameraDefinition::transitionToAnother(const CameraDefinition *wanted, double factor) -{ +bool CameraDefinition::transitionToAnother(const CameraDefinition *wanted, double factor) { double dx, dy, dz, dr, dphi, dtheta, droll; dx = wanted->location.x - location.x; @@ -285,12 +253,10 @@ bool CameraDefinition::transitionToAnother(const CameraDefinition *wanted, doubl dtheta = wanted->direction.theta - direction.theta; droll = wanted->roll - roll; - if (fabs(dx) < 0.000001 && fabs(dy) < 0.000001 && fabs(dz) < 0.000001 && fabs(dr) < 0.000001 && fabs(dphi) < 0.000001 && fabs(dtheta) < 0.000001 && fabs(droll) < 0.000001) - { + if (fabs(dx) < 0.000001 && fabs(dy) < 0.000001 && fabs(dz) < 0.000001 && fabs(dr) < 0.000001 && + fabs(dphi) < 0.000001 && fabs(dtheta) < 0.000001 && fabs(droll) < 0.000001) { return false; - } - else - { + } else { location.x += dx * factor; location.y += dy * factor; location.z += dz * factor; diff --git a/src/definition/CameraDefinition.h b/src/definition/CameraDefinition.h index 9e2c1d3..91631a3 100644 --- a/src/definition/CameraDefinition.h +++ b/src/definition/CameraDefinition.h @@ -11,36 +11,56 @@ namespace paysages { namespace definition { -typedef struct -{ +typedef struct { double yfov; double xratio; double znear; double zfar; } CameraPerspective; -class DEFINITIONSHARED_EXPORT CameraDefinition: public DefinitionNode -{ -public: +class DEFINITIONSHARED_EXPORT CameraDefinition : public DefinitionNode { + public: CameraDefinition(DefinitionNode *parent = NULL); - virtual void save(PackStream* pack) const override; - virtual void load(PackStream* pack) override; + virtual void save(PackStream *pack) const override; + virtual void load(PackStream *pack) override; - virtual void copy(DefinitionNode* destination) const override; + virtual void copy(DefinitionNode *destination) const override; virtual void validate() override; - inline const Vector3 &getLocation() const {return location;} - inline const Vector3 &getTarget() const {return target;} - inline const Vector3 &getUpVector() const {return up;} - inline double getRoll() const {return roll;} - inline Vector3 getDirection() const {return Vector3(direction);} - inline const Vector3 &getDirectionNormalized() const {return forward;} - inline const Matrix4 &getTransformationMatrix() const {return projector;} - inline const VectorSpherical &getDirectionSpherical() const {return direction;} - inline const CameraPerspective &getPerspective() const {return perspective;} - inline double getWidth() const {return width;} - inline double getHeight() const {return height;} + inline const Vector3 &getLocation() const { + return location; + } + inline const Vector3 &getTarget() const { + return target; + } + inline const Vector3 &getUpVector() const { + return up; + } + inline double getRoll() const { + return roll; + } + inline Vector3 getDirection() const { + return Vector3(direction); + } + inline const Vector3 &getDirectionNormalized() const { + return forward; + } + inline const Matrix4 &getTransformationMatrix() const { + return projector; + } + inline const VectorSpherical &getDirectionSpherical() const { + return direction; + } + inline const CameraPerspective &getPerspective() const { + return perspective; + } + inline double getWidth() const { + return width; + } + inline double getHeight() const { + return height; + } double getRealDepth(const Vector3 &projected) const; @@ -68,7 +88,7 @@ public: bool transitionToAnother(const CameraDefinition *wanted, double factor); -private: + private: /* Definition */ Vector3 location; VectorSpherical direction; @@ -90,7 +110,6 @@ private: double inv_x_factor; double inv_y_factor; }; - } } diff --git a/src/definition/CloudLayerDefinition.cpp b/src/definition/CloudLayerDefinition.cpp index e5a849c..09f0338 100644 --- a/src/definition/CloudLayerDefinition.cpp +++ b/src/definition/CloudLayerDefinition.cpp @@ -6,9 +6,7 @@ #include "PackStream.h" #include "FloatNode.h" -CloudLayerDefinition::CloudLayerDefinition(DefinitionNode* parent): - DefinitionNode(parent, "layer", "cloudlayer") -{ +CloudLayerDefinition::CloudLayerDefinition(DefinitionNode *parent) : DefinitionNode(parent, "layer", "cloudlayer") { type = CIRRUS; altitude = 0.5; scaling = 0.5; @@ -18,26 +16,22 @@ CloudLayerDefinition::CloudLayerDefinition(DefinitionNode* parent): zoffset = new FloatNode(this, "zoffset"); } -CloudLayerDefinition::~CloudLayerDefinition() -{ +CloudLayerDefinition::~CloudLayerDefinition() { } -CloudLayerDefinition* CloudLayerDefinition::newCopy(const CloudLayerDefinition& other, DefinitionNode* parent) -{ - CloudLayerDefinition* layer = new CloudLayerDefinition(parent); +CloudLayerDefinition *CloudLayerDefinition::newCopy(const CloudLayerDefinition &other, DefinitionNode *parent) { + CloudLayerDefinition *layer = new CloudLayerDefinition(parent); other.copy(layer); return layer; } -CloudLayerDefinition* CloudLayerDefinition::newCopy(DefinitionNode* parent) const -{ - CloudLayerDefinition* layer = new CloudLayerDefinition(parent); +CloudLayerDefinition *CloudLayerDefinition::newCopy(DefinitionNode *parent) const { + CloudLayerDefinition *layer = new CloudLayerDefinition(parent); copy(layer); return layer; } -void CloudLayerDefinition::save(PackStream* stream) const -{ +void CloudLayerDefinition::save(PackStream *stream) const { DefinitionNode::save(stream); int clouds_type = (int)type; @@ -50,8 +44,7 @@ void CloudLayerDefinition::save(PackStream* stream) const noise_state.save(stream); } -void CloudLayerDefinition::load(PackStream* stream) -{ +void CloudLayerDefinition::load(PackStream *stream) { DefinitionNode::load(stream); int clouds_type; @@ -67,11 +60,10 @@ void CloudLayerDefinition::load(PackStream* stream) validate(); } -void CloudLayerDefinition::copy(DefinitionNode* _destination) const -{ +void CloudLayerDefinition::copy(DefinitionNode *_destination) const { DefinitionNode::copy(_destination); - CloudLayerDefinition* destination = (CloudLayerDefinition*)_destination; + CloudLayerDefinition *destination = (CloudLayerDefinition *)_destination; destination->type = type; destination->altitude = altitude; @@ -81,12 +73,10 @@ void CloudLayerDefinition::copy(DefinitionNode* _destination) const noise_state.copy(&destination->noise_state); } -void CloudLayerDefinition::validate() -{ +void CloudLayerDefinition::validate() { DefinitionNode::validate(); - if (scaling < 0.1) - { + if (scaling < 0.1) { scaling = 0.1; } } diff --git a/src/definition/CloudLayerDefinition.h b/src/definition/CloudLayerDefinition.h index e525272..2afe919 100644 --- a/src/definition/CloudLayerDefinition.h +++ b/src/definition/CloudLayerDefinition.h @@ -10,28 +10,32 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT CloudLayerDefinition : public DefinitionNode -{ -public: - CloudLayerDefinition(DefinitionNode* parent); +class DEFINITIONSHARED_EXPORT CloudLayerDefinition : public DefinitionNode { + public: + CloudLayerDefinition(DefinitionNode *parent); virtual ~CloudLayerDefinition(); - inline const NoiseState &getNoiseState() const {return noise_state;} - inline FloatNode *propXOffset() const {return xoffset;} - inline FloatNode *propZOffset() const {return zoffset;} + inline const NoiseState &getNoiseState() const { + return noise_state; + } + inline FloatNode *propXOffset() const { + return xoffset; + } + inline FloatNode *propZOffset() const { + return zoffset; + } - static CloudLayerDefinition* newCopy(const CloudLayerDefinition& other, DefinitionNode* parent); - CloudLayerDefinition* newCopy(DefinitionNode* parent) const; + static CloudLayerDefinition *newCopy(const CloudLayerDefinition &other, DefinitionNode *parent); + CloudLayerDefinition *newCopy(DefinitionNode *parent) const; - virtual void save(PackStream* pack) const override; - virtual void load(PackStream* pack) override; + virtual void save(PackStream *pack) const override; + virtual void load(PackStream *pack) override; - virtual void copy(DefinitionNode* destination) const override; + virtual void copy(DefinitionNode *destination) const override; virtual void validate() override; -public: - typedef enum - { + public: + typedef enum { STRATUS, NIMBOSTRATUS, CUMULUS, @@ -44,18 +48,17 @@ public: CIRRUS } CloudsType; -public: + public: CloudsType type; NoiseState noise_state; double altitude; double scaling; double coverage; -private: + private: FloatNode *xoffset; FloatNode *zoffset; }; - } } diff --git a/src/definition/CloudsDefinition.cpp b/src/definition/CloudsDefinition.cpp index f17fc99..058d777 100644 --- a/src/definition/CloudsDefinition.cpp +++ b/src/definition/CloudsDefinition.cpp @@ -2,23 +2,18 @@ #include "CloudLayerDefinition.h" -static DefinitionNode* _layerConstructor(Layers* parent) -{ +static DefinitionNode *_layerConstructor(Layers *parent) { return new CloudLayerDefinition(parent); } -CloudsDefinition::CloudsDefinition(DefinitionNode* parent): - Layers(parent, "clouds", _layerConstructor) -{ +CloudsDefinition::CloudsDefinition(DefinitionNode *parent) : Layers(parent, "clouds", _layerConstructor) { } -void CloudsDefinition::applyPreset(CloudsPreset preset) -{ +void CloudsDefinition::applyPreset(CloudsPreset preset) { clear(); - if (preset == CLOUDS_PRESET_PARTLY_CLOUDY) - { - CloudLayerDefinition* layer = new CloudLayerDefinition(this); + if (preset == CLOUDS_PRESET_PARTLY_CLOUDY) { + CloudLayerDefinition *layer = new CloudLayerDefinition(this); layer->type = CloudLayerDefinition::STRATOCUMULUS; layer->setName("Strato-cumulus"); addLayer(layer); diff --git a/src/definition/CloudsDefinition.h b/src/definition/CloudsDefinition.h index f2305d1..f032c9d 100644 --- a/src/definition/CloudsDefinition.h +++ b/src/definition/CloudsDefinition.h @@ -8,20 +8,17 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT CloudsDefinition : public Layers -{ -public: - CloudsDefinition(DefinitionNode* parent); +class DEFINITIONSHARED_EXPORT CloudsDefinition : public Layers { + public: + CloudsDefinition(DefinitionNode *parent); - inline CloudLayerDefinition* getCloudLayer(int position) const {return (CloudLayerDefinition*)getLayer(position);} + inline CloudLayerDefinition *getCloudLayer(int position) const { + return (CloudLayerDefinition *)getLayer(position); + } - typedef enum - { - CLOUDS_PRESET_PARTLY_CLOUDY - } CloudsPreset; + typedef enum { CLOUDS_PRESET_PARTLY_CLOUDY } CloudsPreset; void applyPreset(CloudsPreset preset); }; - } } diff --git a/src/definition/DefinitionDiff.cpp b/src/definition/DefinitionDiff.cpp index 598f46a..7a787bd 100644 --- a/src/definition/DefinitionDiff.cpp +++ b/src/definition/DefinitionDiff.cpp @@ -2,7 +2,5 @@ #include "DefinitionNode.h" -DefinitionDiff::DefinitionDiff(const DefinitionNode *node): - type_name(node->getTypeName()), path(node->getPath()) -{ +DefinitionDiff::DefinitionDiff(const DefinitionNode *node) : type_name(node->getTypeName()), path(node->getPath()) { } diff --git a/src/definition/DefinitionDiff.h b/src/definition/DefinitionDiff.h index ee56371..01b20bb 100644 --- a/src/definition/DefinitionDiff.h +++ b/src/definition/DefinitionDiff.h @@ -11,19 +11,21 @@ namespace definition { * * Diffs are used to undo/redo changes. */ -class DEFINITIONSHARED_EXPORT DefinitionDiff -{ -public: +class DEFINITIONSHARED_EXPORT DefinitionDiff { + public: DefinitionDiff(const DefinitionNode *node); - inline const std::string &getTypeName() const {return type_name;} - inline const std::string &getPath() const {return path;} + inline const std::string &getTypeName() const { + return type_name; + } + inline const std::string &getPath() const { + return path; + } -private: + private: std::string type_name; std::string path; }; - } } diff --git a/src/definition/DefinitionNode.cpp b/src/definition/DefinitionNode.cpp index e994903..540dbd1 100644 --- a/src/definition/DefinitionNode.cpp +++ b/src/definition/DefinitionNode.cpp @@ -8,171 +8,123 @@ #include -DefinitionNode::DefinitionNode(DefinitionNode* parent, const std::string &name, const std::string &type_name): - parent(parent), type_name(type_name), name(name) -{ - if (parent) - { +DefinitionNode::DefinitionNode(DefinitionNode *parent, const std::string &name, const std::string &type_name) + : parent(parent), type_name(type_name), name(name) { + if (parent) { root = parent->root; parent->addChild(this); diffs = NULL; - } - else - { + } else { root = this; diffs = new DiffManager(this); } } -DefinitionNode::~DefinitionNode() -{ - if (parent) - { +DefinitionNode::~DefinitionNode() { + if (parent) { parent->removeChild(this); parent = NULL; } - if (diffs) - { + if (diffs) { delete diffs; diffs = NULL; } // Work on a copy, because the child destructor will modify the array by removing itself using removeChild - std::vector children_copy = children; - for (auto child:children_copy) - { - if (child->getParent() == this) - { + std::vector children_copy = children; + for (auto child : children_copy) { + if (child->getParent() == this) { delete child; } } } -void DefinitionNode::setName(const std::string &name) -{ +void DefinitionNode::setName(const std::string &name) { this->name = name; } -Scenery* DefinitionNode::getScenery() -{ - if (parent) - { +Scenery *DefinitionNode::getScenery() { + if (parent) { return parent->getScenery(); - } - else - { + } else { return NULL; } } -std::string DefinitionNode::toString(int indent) const -{ +std::string DefinitionNode::toString(int indent) const { std::string result; - for (int i = 0; i < indent; i++) - { + for (int i = 0; i < indent; i++) { result += " "; } result += name; - if (not children.empty()) - { - for (auto &child: children) - { + if (not children.empty()) { + for (auto &child : children) { result += "\n" + child->toString(indent + 1); } } return result; } -std::string DefinitionNode::getPath() const -{ - if (parent == root) - { +std::string DefinitionNode::getPath() const { + if (parent == root) { return parent->getPath() + name; - } - else if (parent) - { + } else if (parent) { return parent->getPath() + "/" + name; - } - else - { + } else { return "/"; } } -DefinitionNode *DefinitionNode::findByPath(const std::string &path) const -{ - if (path.empty()) - { +DefinitionNode *DefinitionNode::findByPath(const std::string &path) const { + if (path.empty()) { return NULL; - } - else if (path[0] == '/') - { - if (path.length() == 1) - { + } else if (path[0] == '/') { + if (path.length() == 1) { return root; - } - else if (root == this) - { + } else if (root == this) { return findByPath(path.substr(1)); - } - else - { + } else { return root->findByPath(path); } - } - else - { + } else { size_t seppos = path.find("/"); std::string child_name = (seppos == std::string::npos) ? path : path.substr(0, seppos); - DefinitionNode *child = ((DefinitionNode *)this)->findChildByName(child_name); // FIXME findChildByName should be const - if (child) - { - if (seppos == std::string::npos) - { + DefinitionNode *child = + ((DefinitionNode *)this)->findChildByName(child_name); // FIXME findChildByName should be const + if (child) { + if (seppos == std::string::npos) { return child; - } - else - { + } else { return child->findByPath(path.substr(seppos + 1)); } - } - else - { + } else { return NULL; } } } -bool DefinitionNode::applyDiff(const DefinitionDiff *diff, bool) -{ +bool DefinitionNode::applyDiff(const DefinitionDiff *diff, bool) { // Only do type check, subclasses will do the rest - if (diff->getTypeName() == type_name) - { + if (diff->getTypeName() == type_name) { return true; - } - else - { - Logs::error() << "Can't apply " << diff->getTypeName() << " diff to " << getName() << " " << type_name << " node" << std::endl; + } else { + Logs::error() << "Can't apply " << diff->getTypeName() << " diff to " << getName() << " " << type_name + << " node" << std::endl; return false; } } -void DefinitionNode::generateInitDiffs(std::vector *) const -{ +void DefinitionNode::generateInitDiffs(std::vector *) const { } -void DefinitionNode::addWatcher(DefinitionWatcher *watcher, bool init_diff) -{ - if (root && root->diffs) - { - if (init_diff) - { +void DefinitionNode::addWatcher(DefinitionWatcher *watcher, bool init_diff) { + if (root && root->diffs) { + if (init_diff) { std::vector diffs; generateInitDiffs(&diffs); - for (auto diff: diffs) - { + for (auto diff : diffs) { watcher->nodeChanged(this, diff); delete diff; } @@ -181,37 +133,29 @@ void DefinitionNode::addWatcher(DefinitionWatcher *watcher, bool init_diff) } } -int DefinitionNode::getWatcherCount() const -{ - if (root && root->diffs) - { +int DefinitionNode::getWatcherCount() const { + if (root && root->diffs) { return root->diffs->getWatcherCount(this); - } - else - { + } else { return 0; } } -void DefinitionNode::save(PackStream* stream) const -{ +void DefinitionNode::save(PackStream *stream) const { int children_count = (int)children.size(); stream->write(&children_count); - for (auto child: children) - { + for (auto child : children) { stream->write(child->name); int child_size = child->getStreamSize(); - if (child_size >= 0) - { + if (child_size >= 0) { stream->write(&child_size); child->save(stream); - } - else - { + } else { // Child size not known, write it to a temporary stream to know it - Logs::debug() << "Unknown size for child " << child->name << ", unefficient writing to temporary stream" << std::endl; + Logs::debug() << "Unknown size for child " << child->name << ", unefficient writing to temporary stream" + << std::endl; PackStream substream; child->save(&substream); stream->writeFromBuffer(substream, true); @@ -219,27 +163,22 @@ void DefinitionNode::save(PackStream* stream) const } } -void DefinitionNode::load(PackStream* stream) -{ +void DefinitionNode::load(PackStream *stream) { int children_count; stream->read(&children_count); - for (int i = 0; i < children_count; i++) - { + for (int i = 0; i < children_count; i++) { std::string child_name = stream->readString(); int child_size; stream->read(&child_size); DefinitionNode *child = findChildByName(child_name); - if (child) - { + if (child) { // TODO type check child->load(stream); - } - else - { + } else { // TODO Ask subclass if it can instanciate a child // Else skip length of unknown child stream->skipBytes(child_size); @@ -248,85 +187,65 @@ void DefinitionNode::load(PackStream* stream) } } -void DefinitionNode::copy(DefinitionNode* destination) const -{ - if (destination->getTypeName() == getTypeName()) - { +void DefinitionNode::copy(DefinitionNode *destination) const { + if (destination->getTypeName() == getTypeName()) { destination->setName(name); - for (auto &child: children) - { + for (auto &child : children) { DefinitionNode *dest_child = destination->findChildByName(child->name); - if (dest_child) - { + if (dest_child) { child->copy(dest_child); - } - else - { - Logs::warning() << "Can't copy to child " << child->name << " of " << destination->getTypeName() << std::endl; + } else { + Logs::warning() << "Can't copy to child " << child->name << " of " << destination->getTypeName() + << std::endl; } } - } - else - { + } else { Logs::error() << "Can't copy from " << getTypeName() << " to " << destination->getTypeName() << std::endl; } } -void DefinitionNode::validate() -{ - for (auto child: children) - { +void DefinitionNode::validate() { + for (auto child : children) { child->validate(); } } -void DefinitionNode::addChild(DefinitionNode* child) -{ - if (std::find(children.begin(), children.end(), child) == children.end()) - { +void DefinitionNode::addChild(DefinitionNode *child) { + if (std::find(children.begin(), children.end(), child) == children.end()) { children.push_back(child); child->parent = this; child->root = this->root; } } -void DefinitionNode::removeChild(DefinitionNode* child) -{ - std::vector::iterator it = std::find(children.begin(), children.end(), child); - if (it != children.end()) - { +void DefinitionNode::removeChild(DefinitionNode *child) { + std::vector::iterator it = std::find(children.begin(), children.end(), child); + if (it != children.end()) { child->parent = NULL; children.erase(it); - } - else - { - Logs::warning() << "Trying to remove not found child '" << child->name << "' from '" << name << "'" << std::endl; + } else { + Logs::warning() << "Trying to remove not found child '" << child->name << "' from '" << name << "'" + << std::endl; } } -DefinitionNode *DefinitionNode::findChildByName(const std::string name) -{ - for (auto child: children) - { - if (child->name == name) - { +DefinitionNode *DefinitionNode::findChildByName(const std::string name) { + for (auto child : children) { + if (child->name == name) { return child; } } return NULL; } -int DefinitionNode::getStreamSize() const -{ +int DefinitionNode::getStreamSize() const { return -1; } -void DefinitionNode::addDiff(const DefinitionDiff *diff) -{ +void DefinitionNode::addDiff(const DefinitionDiff *diff) { assert(diff->getTypeName() == type_name); - if (root && root->diffs) - { + if (root && root->diffs) { root->diffs->addDiff(this, diff); } } diff --git a/src/definition/DefinitionNode.h b/src/definition/DefinitionNode.h index 514631f..f1d6afb 100644 --- a/src/definition/DefinitionNode.h +++ b/src/definition/DefinitionNode.h @@ -9,29 +9,40 @@ namespace definition { /** * Base class for all nodes of the definition tree. */ -class DEFINITIONSHARED_EXPORT DefinitionNode -{ -public: - DefinitionNode(DefinitionNode* parent, const std::string &name, const std::string &type_name = ""); +class DEFINITIONSHARED_EXPORT DefinitionNode { + public: + DefinitionNode(DefinitionNode *parent, const std::string &name, const std::string &type_name = ""); virtual ~DefinitionNode(); - virtual void save(PackStream* stream) const; - virtual void load(PackStream* stream); + virtual void save(PackStream *stream) const; + virtual void load(PackStream *stream); - virtual void copy(DefinitionNode* destination) const; + virtual void copy(DefinitionNode *destination) const; virtual void validate(); - inline const std::string &getName() const {return name;} + inline const std::string &getName() const { + return name; + } virtual void setName(const std::string &name); - inline const std::string &getTypeName() const {return type_name;} + inline const std::string &getTypeName() const { + return type_name; + } - virtual Scenery* getScenery(); + virtual Scenery *getScenery(); - inline const DefinitionNode *getParent() const {return parent;} - inline const DefinitionNode *getRoot() const {return root;} - inline DiffManager *getDiffManager() const {return diffs;} - inline int getChildrenCount() const {return children.size();} + inline const DefinitionNode *getParent() const { + return parent; + } + inline const DefinitionNode *getRoot() const { + return root; + } + inline DiffManager *getDiffManager() const { + return diffs; + } + inline int getChildrenCount() const { + return children.size(); + } /** * Return a string representation of the tree (mainly for debugging purposes). @@ -59,7 +70,7 @@ public: * * Return true if the diff could be applied. */ - virtual bool applyDiff(const DefinitionDiff *diff, bool backward=false); + virtual bool applyDiff(const DefinitionDiff *diff, bool backward = false); /** * Fill a diff array to be applied to initialize a proper state for a watcher. @@ -75,16 +86,16 @@ public: * * If *init_diff* is set to true, a first diff (or several) will be be pushed immediately to initialize the state. */ - void addWatcher(DefinitionWatcher *watcher, bool init_diff=false); + void addWatcher(DefinitionWatcher *watcher, bool init_diff = false); /** * Get the current number of watchers. */ int getWatcherCount() const; -protected: - void addChild(DefinitionNode* child); - void removeChild(DefinitionNode* child); + protected: + void addChild(DefinitionNode *child); + void removeChild(DefinitionNode *child); virtual DefinitionNode *findChildByName(const std::string name); /** @@ -104,15 +115,14 @@ protected: */ void addDiff(const DefinitionDiff *diff); -private: + private: DefinitionNode *parent; DefinitionNode *root; DiffManager *diffs; std::string type_name; std::string name; - std::vector children; + std::vector children; }; - } } diff --git a/src/definition/DefinitionWatcher.cpp b/src/definition/DefinitionWatcher.cpp index 3e99c66..888ed13 100644 --- a/src/definition/DefinitionWatcher.cpp +++ b/src/definition/DefinitionWatcher.cpp @@ -1,7 +1,4 @@ #include "DefinitionWatcher.h" -DefinitionWatcher::DefinitionWatcher() -{ - +DefinitionWatcher::DefinitionWatcher() { } - diff --git a/src/definition/DefinitionWatcher.h b/src/definition/DefinitionWatcher.h index b209e69..84ee460 100644 --- a/src/definition/DefinitionWatcher.h +++ b/src/definition/DefinitionWatcher.h @@ -11,9 +11,8 @@ namespace definition { * * Watchers will be registered in DiffManager to receive DefinitionDiff objects. */ -class DEFINITIONSHARED_EXPORT DefinitionWatcher -{ -public: +class DEFINITIONSHARED_EXPORT DefinitionWatcher { + public: DefinitionWatcher(); /** @@ -21,7 +20,6 @@ public: */ virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff) = 0; }; - } } diff --git a/src/definition/DiffManager.cpp b/src/definition/DiffManager.cpp index af98faf..c84fb4e 100644 --- a/src/definition/DiffManager.cpp +++ b/src/definition/DiffManager.cpp @@ -4,38 +4,29 @@ #include "DefinitionDiff.h" #include "DefinitionWatcher.h" -DiffManager::DiffManager(DefinitionNode *tree): - tree(tree) -{ +DiffManager::DiffManager(DefinitionNode *tree) : tree(tree) { undone = 0; } -DiffManager::~DiffManager() -{ - for (auto diff: diffs) - { +DiffManager::~DiffManager() { + for (auto diff : diffs) { delete diff; } diffs.clear(); } -void DiffManager::addWatcher(const DefinitionNode *node, DefinitionWatcher *watcher) -{ - if (std::find(watchers[node].begin(), watchers[node].end(), watcher) == watchers[node].end()) - { +void DiffManager::addWatcher(const DefinitionNode *node, DefinitionWatcher *watcher) { + if (std::find(watchers[node].begin(), watchers[node].end(), watcher) == watchers[node].end()) { watchers[node].push_back(watcher); } } -int DiffManager::getWatcherCount(const DefinitionNode *node) -{ +int DiffManager::getWatcherCount(const DefinitionNode *node) { return watchers[node].size(); } -void DiffManager::addDiff(DefinitionNode *node, const DefinitionDiff *diff) -{ - while (undone > 0) - { +void DiffManager::addDiff(DefinitionNode *node, const DefinitionDiff *diff) { + while (undone > 0) { // truncate diffs ahead delete diffs.back(); diffs.pop_back(); @@ -47,16 +38,13 @@ void DiffManager::addDiff(DefinitionNode *node, const DefinitionDiff *diff) // TODO Delayed commit (with merge of consecutive diffs) node->applyDiff(diff); - for (auto watcher: watchers[node]) - { + for (auto watcher : watchers[node]) { watcher->nodeChanged(node, diff); } } -void DiffManager::undo() -{ - if (undone < (int)diffs.size()) - { +void DiffManager::undo() { + if (undone < (int)diffs.size()) { undone++; const DefinitionDiff *diff = diffs[diffs.size() - undone]; @@ -64,18 +52,15 @@ void DiffManager::undo() DefinitionNode *node = tree->findByPath(diff->getPath()); node->applyDiff(diff, true); - for (auto watcher: watchers[node]) - { + for (auto watcher : watchers[node]) { // FIXME Reverse diff watcher->nodeChanged(node, diff); } } } -void DiffManager::redo() -{ - if (undone > 0) - { +void DiffManager::redo() { + if (undone > 0) { const DefinitionDiff *diff = diffs[diffs.size() - undone]; undone--; @@ -83,10 +68,8 @@ void DiffManager::redo() DefinitionNode *node = tree->findByPath(diff->getPath()); node->applyDiff(diff); - for (auto watcher: watchers[node]) - { + for (auto watcher : watchers[node]) { watcher->nodeChanged(node, diff); } } } - diff --git a/src/definition/DiffManager.h b/src/definition/DiffManager.h index bf8c0ab..ba92514 100644 --- a/src/definition/DiffManager.h +++ b/src/definition/DiffManager.h @@ -14,9 +14,8 @@ namespace definition { * * Watchers can register themselves to received these diffs. */ -class DEFINITIONSHARED_EXPORT DiffManager -{ -public: +class DEFINITIONSHARED_EXPORT DiffManager { + public: DiffManager(DefinitionNode *tree); ~DiffManager(); @@ -47,13 +46,12 @@ public: */ void redo(); -private: + private: DefinitionNode *tree; int undone; std::vector diffs; std::map> watchers; }; - } } diff --git a/src/definition/FloatDiff.cpp b/src/definition/FloatDiff.cpp index 5bdaba9..a8dcb5e 100644 --- a/src/definition/FloatDiff.cpp +++ b/src/definition/FloatDiff.cpp @@ -1,6 +1,5 @@ #include "FloatDiff.h" -FloatDiff::FloatDiff(const DefinitionNode *node, double oldvalue, double newvalue): - DefinitionDiff(node), oldvalue(oldvalue), newvalue(newvalue) -{ +FloatDiff::FloatDiff(const DefinitionNode *node, double oldvalue, double newvalue) + : DefinitionDiff(node), oldvalue(oldvalue), newvalue(newvalue) { } diff --git a/src/definition/FloatDiff.h b/src/definition/FloatDiff.h index f05c3aa..315a73b 100644 --- a/src/definition/FloatDiff.h +++ b/src/definition/FloatDiff.h @@ -11,19 +11,21 @@ namespace definition { /** * Diff for a FloatNode. */ -class DEFINITIONSHARED_EXPORT FloatDiff: public DefinitionDiff -{ -public: +class DEFINITIONSHARED_EXPORT FloatDiff : public DefinitionDiff { + public: FloatDiff(const DefinitionNode *node, double oldvalue, double newvalue); - inline double getOldValue() const {return oldvalue;} - inline double getNewValue() const {return newvalue;} + inline double getOldValue() const { + return oldvalue; + } + inline double getNewValue() const { + return newvalue; + } -private: + private: double oldvalue; double newvalue; }; - } } diff --git a/src/definition/FloatNode.cpp b/src/definition/FloatNode.cpp index 80478f0..5e6f15d 100644 --- a/src/definition/FloatNode.cpp +++ b/src/definition/FloatNode.cpp @@ -6,13 +6,11 @@ #include #include -FloatNode::FloatNode(DefinitionNode* parent, const std::string &name, double value): - DefinitionNode(parent, name, "float"), value(value) -{ +FloatNode::FloatNode(DefinitionNode *parent, const std::string &name, double value) + : DefinitionNode(parent, name, "float"), value(value) { } -std::string FloatNode::toString(int indent) const -{ +std::string FloatNode::toString(int indent) const { std::ostringstream stream; stream << DefinitionNode::toString(indent) << " " << value; @@ -20,47 +18,36 @@ std::string FloatNode::toString(int indent) const return stream.str(); } -void FloatNode::save(PackStream *stream) const -{ +void FloatNode::save(PackStream *stream) const { stream->write(&value); } -void FloatNode::load(PackStream *stream) -{ +void FloatNode::load(PackStream *stream) { stream->read(&value); } -void FloatNode::copy(DefinitionNode *destination) const -{ - if (destination->getTypeName() == getTypeName()) - { +void FloatNode::copy(DefinitionNode *destination) const { + if (destination->getTypeName() == getTypeName()) { ((FloatNode *)destination)->value = value; - } - else - { + } else { Logs::error() << "Can't copy from " << getTypeName() << " to " << destination->getTypeName() << std::endl; } } -void FloatNode::setValue(double new_value) -{ +void FloatNode::setValue(double new_value) { addDiff(produceDiff(new_value)); } -const FloatDiff *FloatNode::produceDiff(double new_value) const -{ +const FloatDiff *FloatNode::produceDiff(double new_value) const { return new FloatDiff(this, value, new_value); } -void FloatNode::generateInitDiffs(std::vector *diffs) const -{ +void FloatNode::generateInitDiffs(std::vector *diffs) const { diffs->push_back(produceDiff(value)); } -bool FloatNode::applyDiff(const DefinitionDiff *diff, bool backward) -{ - if (!DefinitionNode::applyDiff(diff, backward)) - { +bool FloatNode::applyDiff(const DefinitionDiff *diff, bool backward) { + if (!DefinitionNode::applyDiff(diff, backward)) { return false; } @@ -70,19 +57,15 @@ bool FloatNode::applyDiff(const DefinitionDiff *diff, bool backward) double previous = backward ? float_diff->getNewValue() : float_diff->getOldValue(); double next = backward ? float_diff->getOldValue() : float_diff->getNewValue(); - if (value == previous) - { + if (value == previous) { value = next; return true; - } - else - { + } else { Logs::error() << "Can't apply float diff " << previous << " => " << next << " to " << getName() << std::endl; return false; } } -void FloatNode::addValue(double added) -{ +void FloatNode::addValue(double added) { setValue(value + added); } diff --git a/src/definition/FloatNode.h b/src/definition/FloatNode.h index 85f6e7c..f86fded 100644 --- a/src/definition/FloatNode.h +++ b/src/definition/FloatNode.h @@ -11,17 +11,18 @@ namespace definition { /** * Node with a single floating point numeric value, for the definition tree. */ -class DEFINITIONSHARED_EXPORT FloatNode: public DefinitionNode -{ -public: - FloatNode(DefinitionNode* parent, const std::string &name, double value = 0.0); +class DEFINITIONSHARED_EXPORT FloatNode : public DefinitionNode { + public: + FloatNode(DefinitionNode *parent, const std::string &name, double value = 0.0); - inline double getValue() const {return value;} + inline double getValue() const { + return value; + } virtual std::string toString(int indent) const override; - virtual void save(PackStream* stream) const override; - virtual void load(PackStream* stream) override; - virtual void copy(DefinitionNode* destination) const override; + virtual void save(PackStream *stream) const override; + virtual void load(PackStream *stream) override; + virtual void copy(DefinitionNode *destination) const override; /** * Change the float value stored. @@ -31,13 +32,13 @@ public: void setValue(double new_value); const FloatDiff *produceDiff(double new_value) const; void generateInitDiffs(std::vector *diffs) const; - virtual bool applyDiff(const DefinitionDiff *diff, bool backward=false) override; + virtual bool applyDiff(const DefinitionDiff *diff, bool backward = false) override; void addValue(double added); -private: + + private: double value; }; - } } diff --git a/src/definition/GodRaysDefinition.cpp b/src/definition/GodRaysDefinition.cpp index 94ec938..01fb2c6 100644 --- a/src/definition/GodRaysDefinition.cpp +++ b/src/definition/GodRaysDefinition.cpp @@ -2,11 +2,8 @@ #include "FloatNode.h" -GodRaysDefinition::GodRaysDefinition(DefinitionNode *parent): - DefinitionNode(parent, "godrays", "godrays") -{ +GodRaysDefinition::GodRaysDefinition(DefinitionNode *parent) : DefinitionNode(parent, "godrays", "godrays") { penetration = new FloatNode(this, "penetration", 0.01); resistance = new FloatNode(this, "resistance", 0.3); boost = new FloatNode(this, "boost", 8.0); } - diff --git a/src/definition/GodRaysDefinition.h b/src/definition/GodRaysDefinition.h index 52775ec..e9c09dc 100644 --- a/src/definition/GodRaysDefinition.h +++ b/src/definition/GodRaysDefinition.h @@ -8,21 +8,25 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT GodRaysDefinition: public DefinitionNode -{ -public: +class DEFINITIONSHARED_EXPORT GodRaysDefinition : public DefinitionNode { + public: GodRaysDefinition(DefinitionNode *parent); - inline FloatNode *propPenetration() const {return penetration;} - inline FloatNode *propResistance() const {return resistance;} - inline FloatNode *propBoost() const {return boost;} + inline FloatNode *propPenetration() const { + return penetration; + } + inline FloatNode *propResistance() const { + return resistance; + } + inline FloatNode *propBoost() const { + return boost; + } -private: + private: FloatNode *penetration; FloatNode *resistance; FloatNode *boost; }; - } } diff --git a/src/definition/IntDiff.cpp b/src/definition/IntDiff.cpp index 792acf8..d1ca66f 100644 --- a/src/definition/IntDiff.cpp +++ b/src/definition/IntDiff.cpp @@ -1,7 +1,5 @@ #include "IntDiff.h" -IntDiff::IntDiff(const DefinitionNode *node, int oldvalue, int newvalue): - DefinitionDiff(node), oldvalue(oldvalue), newvalue(newvalue) -{ +IntDiff::IntDiff(const DefinitionNode *node, int oldvalue, int newvalue) + : DefinitionDiff(node), oldvalue(oldvalue), newvalue(newvalue) { } - diff --git a/src/definition/IntDiff.h b/src/definition/IntDiff.h index c337124..ddf4313 100644 --- a/src/definition/IntDiff.h +++ b/src/definition/IntDiff.h @@ -11,19 +11,21 @@ namespace definition { /** * Diff for an IntNode. */ -class DEFINITIONSHARED_EXPORT IntDiff: public DefinitionDiff -{ -public: +class DEFINITIONSHARED_EXPORT IntDiff : public DefinitionDiff { + public: IntDiff(const DefinitionNode *node, int oldvalue, int newvalue); - inline int getOldValue() const {return oldvalue;} - inline int getNewValue() const {return newvalue;} + inline int getOldValue() const { + return oldvalue; + } + inline int getNewValue() const { + return newvalue; + } -private: + private: int oldvalue; int newvalue; }; - } } diff --git a/src/definition/IntNode.cpp b/src/definition/IntNode.cpp index cd16c49..a5704af 100644 --- a/src/definition/IntNode.cpp +++ b/src/definition/IntNode.cpp @@ -6,13 +6,11 @@ #include #include -IntNode::IntNode(DefinitionNode* parent, const std::string &name, int value): - DefinitionNode(parent, name, "int"), value(value) -{ +IntNode::IntNode(DefinitionNode *parent, const std::string &name, int value) + : DefinitionNode(parent, name, "int"), value(value) { } -std::string IntNode::toString(int indent) const -{ +std::string IntNode::toString(int indent) const { std::ostringstream stream; stream << DefinitionNode::toString(indent) << " " << value; @@ -20,47 +18,36 @@ std::string IntNode::toString(int indent) const return stream.str(); } -void IntNode::save(PackStream *stream) const -{ +void IntNode::save(PackStream *stream) const { stream->write(&value); } -void IntNode::load(PackStream *stream) -{ +void IntNode::load(PackStream *stream) { stream->read(&value); } -void IntNode::copy(DefinitionNode *destination) const -{ - if (destination->getTypeName() == getTypeName()) - { +void IntNode::copy(DefinitionNode *destination) const { + if (destination->getTypeName() == getTypeName()) { ((IntNode *)destination)->value = value; - } - else - { + } else { Logs::error() << "Can't copy from " << getTypeName() << " to " << destination->getTypeName() << std::endl; } } -void IntNode::setValue(int new_value) -{ +void IntNode::setValue(int new_value) { addDiff(produceDiff(new_value)); } -const IntDiff *IntNode::produceDiff(int new_value) const -{ +const IntDiff *IntNode::produceDiff(int new_value) const { return new IntDiff(this, value, new_value); } -void IntNode::generateInitDiffs(std::vector *diffs) const -{ +void IntNode::generateInitDiffs(std::vector *diffs) const { diffs->push_back(produceDiff(value)); } -bool IntNode::applyDiff(const DefinitionDiff *diff, bool backward) -{ - if (!DefinitionNode::applyDiff(diff, backward)) - { +bool IntNode::applyDiff(const DefinitionDiff *diff, bool backward) { + if (!DefinitionNode::applyDiff(diff, backward)) { return false; } @@ -70,13 +57,10 @@ bool IntNode::applyDiff(const DefinitionDiff *diff, bool backward) double previous = backward ? int_diff->getNewValue() : int_diff->getOldValue(); double next = backward ? int_diff->getOldValue() : int_diff->getNewValue(); - if (value == previous) - { + if (value == previous) { value = next; return true; - } - else - { + } else { Logs::error() << "Can't apply int diff " << previous << " => " << next << " to " << getName() << std::endl; return false; } diff --git a/src/definition/IntNode.h b/src/definition/IntNode.h index bf9ccf6..cd531ee 100644 --- a/src/definition/IntNode.h +++ b/src/definition/IntNode.h @@ -11,17 +11,18 @@ namespace definition { /** * Node with a single integer value, for the definition tree. */ -class DEFINITIONSHARED_EXPORT IntNode: public DefinitionNode -{ -public: - IntNode(DefinitionNode* parent, const std::string &name, int value = 0); +class DEFINITIONSHARED_EXPORT IntNode : public DefinitionNode { + public: + IntNode(DefinitionNode *parent, const std::string &name, int value = 0); - inline int getValue() const {return value;} + inline int getValue() const { + return value; + } virtual std::string toString(int indent) const override; - virtual void save(PackStream* stream) const override; - virtual void load(PackStream* stream) override; - virtual void copy(DefinitionNode* destination) const override; + virtual void save(PackStream *stream) const override; + virtual void load(PackStream *stream) override; + virtual void copy(DefinitionNode *destination) const override; /** * Change the int value stored. @@ -31,12 +32,11 @@ public: void setValue(int new_value); const IntDiff *produceDiff(int new_value) const; void generateInitDiffs(std::vector *diffs) const; - virtual bool applyDiff(const DefinitionDiff *diff, bool backward=false) override; + virtual bool applyDiff(const DefinitionDiff *diff, bool backward = false) override; -private: + private: int value; }; - } } diff --git a/src/definition/Layers.cpp b/src/definition/Layers.cpp index 500f276..d08a258 100644 --- a/src/definition/Layers.cpp +++ b/src/definition/Layers.cpp @@ -3,57 +3,48 @@ #include "PackStream.h" #include "Logs.h" -Layers::Layers(DefinitionNode* parent, const std::string &name, LayerConstructor layer_constructor): - DefinitionNode(parent, name, "layers" + name), layer_constructor(layer_constructor) -{ +Layers::Layers(DefinitionNode *parent, const std::string &name, LayerConstructor layer_constructor) + : DefinitionNode(parent, name, "layers" + name), layer_constructor(layer_constructor) { max_layer_count = 100; null_layer = layer_constructor(this); } -Layers::~Layers() -{ +Layers::~Layers() { clear(); delete null_layer; } -void Layers::save(PackStream *stream) const -{ +void Layers::save(PackStream *stream) const { int layer_count = (int)layers.size(); stream->write(&layer_count); - for (int i = 0; i < layer_count; i++) - { + for (int i = 0; i < layer_count; i++) { stream->write(layers[i]->getName()); layers[i]->save(stream); } } -void Layers::load(PackStream *stream) -{ +void Layers::load(PackStream *stream) { int layer_count; stream->read(&layer_count); - if (layer_count > max_layer_count) - { + if (layer_count > max_layer_count) { layer_count = max_layer_count; } clear(); - for (int i = 0; i < layer_count; i++) - { + for (int i = 0; i < layer_count; i++) { int position = addLayer(); - if (position >= 0) - { + if (position >= 0) { layers[position]->setName(stream->readString()); layers[position]->load(stream); } } } -void Layers::copy(DefinitionNode* destination_) const -{ +void Layers::copy(DefinitionNode *destination_) const { DefinitionNode::copy(destination_); - Layers* destination = (Layers*)destination_; + Layers *destination = (Layers *)destination_; destination->clear(); @@ -61,142 +52,113 @@ void Layers::copy(DefinitionNode* destination_) const null_layer->copy(destination->null_layer); - for (auto layer: layers) - { + for (auto layer : layers) { int position = destination->addLayer(); - DefinitionNode* new_layer = destination->getLayer(position); + DefinitionNode *new_layer = destination->getLayer(position); layer->copy(new_layer); } } -Layers* Layers::newCopy() const -{ - Layers* result = new Layers(NULL, getName(), layer_constructor); +Layers *Layers::newCopy() const { + Layers *result = new Layers(NULL, getName(), layer_constructor); copy(result); return result; } -void Layers::setMaxLayerCount(int max_layer_count) -{ +void Layers::setMaxLayerCount(int max_layer_count) { this->max_layer_count = max_layer_count; // TODO Delete overlimit layers ? } -int Layers::count() const -{ +int Layers::count() const { return layers.size(); } -DefinitionNode* Layers::getLayer(int position) const -{ - if (position >= 0 and position < (int)layers.size()) - { +DefinitionNode *Layers::getLayer(int position) const { + if (position >= 0 and position < (int)layers.size()) { return layers[position]; - } - else - { - Logs::warning() << "Asked for a undefined layer " << position << " on a total of " << (int)layers.size() << std::endl; + } else { + Logs::warning() << "Asked for a undefined layer " << position << " on a total of " << (int)layers.size() + << std::endl; return null_layer; } } -int Layers::findLayer(DefinitionNode* layer) const -{ +int Layers::findLayer(DefinitionNode *layer) const { int i = 0; - for (auto it:layers) - { - if (it == layer) - { + for (auto it : layers) { + if (it == layer) { return i; } i++; } - Logs::warning() << "Layer " << layer << " (" << layer->getName() << " not found, on a total of " << (int)layers.size() << std::endl; + Logs::warning() << "Layer " << layer << " (" << layer->getName() << " not found, on a total of " + << (int)layers.size() << std::endl; return -1; } -int Layers::addLayer(DefinitionNode* layer) -{ - if ((int)layers.size() < max_layer_count) - { +int Layers::addLayer(DefinitionNode *layer) { + if ((int)layers.size() < max_layer_count) { layers.push_back(layer); addChild(layer); return layers.size() - 1; - } - else - { + } else { Logs::warning() << "Add layer ignored because limit of " << max_layer_count << " reached" << std::endl; delete layer; return -1; } } -int Layers::addLayer() -{ +int Layers::addLayer() { return addLayer(layer_constructor(this)); } -void Layers::removeLayer(int position) -{ - if (position >= 0 and position < (int)layers.size()) - { - DefinitionNode* removed = layers[position]; +void Layers::removeLayer(int position) { + if (position >= 0 and position < (int)layers.size()) { + DefinitionNode *removed = layers[position]; removeChild(removed); layers.erase(layers.begin() + position); delete removed; - } - else - { - Logs::warning() << "Removing unknown layer " << position << " on " << (int)layers.size() << " from '" << getName() << "'" << std::endl; + } else { + Logs::warning() << "Removing unknown layer " << position << " on " << (int)layers.size() << " from '" + << getName() << "'" << std::endl; } } -void Layers::removeLayer(DefinitionNode* layer) -{ +void Layers::removeLayer(DefinitionNode *layer) { removeLayer(findLayer(layer)); } -void Layers::moveLayer(int old_position, int new_position) -{ - if (old_position >= 0 and old_position < (int)layers.size() and new_position >= 0 and new_position < (int)layers.size()) - { - DefinitionNode* layer = layers[old_position]; +void Layers::moveLayer(int old_position, int new_position) { + if (old_position >= 0 and old_position < (int)layers.size() and new_position >= 0 and + new_position < (int)layers.size()) { + DefinitionNode *layer = layers[old_position]; layers.erase(layers.begin() + old_position); layers.insert(layers.begin() + new_position, layer); } } -void Layers::moveLayer(DefinitionNode* layer, int new_position) -{ +void Layers::moveLayer(DefinitionNode *layer, int new_position) { moveLayer(findLayer(layer), new_position); } -void Layers::clear() -{ - while (layers.size() > 0) - { +void Layers::clear() { + while (layers.size() > 0) { removeLayer(0); } } -DefinitionNode *Layers::findChildByName(const std::string name) -{ +DefinitionNode *Layers::findChildByName(const std::string name) { DefinitionNode *result = DefinitionNode::findChildByName(name); - if (result) - { + if (result) { return result; - } - else - { + } else { int position = addLayer(); - if (position >= 0) - { + if (position >= 0) { result = getLayer(position); result->setName(name); return result; - } - else - { + } else { return NULL; } } diff --git a/src/definition/Layers.h b/src/definition/Layers.h index fa83762..4b454a4 100644 --- a/src/definition/Layers.h +++ b/src/definition/Layers.h @@ -8,27 +8,26 @@ namespace paysages { namespace definition { -typedef DefinitionNode* (*LayerConstructor)(Layers* parent); +typedef DefinitionNode *(*LayerConstructor)(Layers *parent); /** * @brief Layers of definitions, ideally all of the same type. */ -class DEFINITIONSHARED_EXPORT Layers:public DefinitionNode -{ -public: - Layers(DefinitionNode* parent, const std::string &name, LayerConstructor layer_constructor); +class DEFINITIONSHARED_EXPORT Layers : public DefinitionNode { + public: + Layers(DefinitionNode *parent, const std::string &name, LayerConstructor layer_constructor); virtual ~Layers(); virtual void save(PackStream *stream) const override; virtual void load(PackStream *stream) override; - virtual void copy(DefinitionNode* destination) const override; - Layers* newCopy() const; + virtual void copy(DefinitionNode *destination) const override; + Layers *newCopy() const; void setMaxLayerCount(int max_layer_count); int count() const; - DefinitionNode* getLayer(int position) const; - int findLayer(DefinitionNode* layer) const; + DefinitionNode *getLayer(int position) const; + int findLayer(DefinitionNode *layer) const; /** * @brief Add a new layer @@ -40,22 +39,20 @@ public: int addLayer(DefinitionNode *layer); int addLayer(); void removeLayer(int position); - void removeLayer(DefinitionNode* layer); + void removeLayer(DefinitionNode *layer); void moveLayer(int old_position, int new_position); - void moveLayer(DefinitionNode* layer, int new_position); + void moveLayer(DefinitionNode *layer, int new_position); void clear(); -protected: + protected: virtual DefinitionNode *findChildByName(const std::string name) override; -public: + public: LayerConstructor layer_constructor; int max_layer_count; - std::vector layers; - DefinitionNode* null_layer; - + std::vector layers; + DefinitionNode *null_layer; }; - } } diff --git a/src/definition/NoiseNode.cpp b/src/definition/NoiseNode.cpp index 5430393..c362e33 100644 --- a/src/definition/NoiseNode.cpp +++ b/src/definition/NoiseNode.cpp @@ -3,19 +3,15 @@ #include "NoiseGenerator.h" #include "Logs.h" -NoiseNode::NoiseNode(DefinitionNode *parent): - DefinitionNode(parent, "noise") -{ +NoiseNode::NoiseNode(DefinitionNode *parent) : DefinitionNode(parent, "noise") { noise = new NoiseGenerator(); } -NoiseNode::~NoiseNode() -{ +NoiseNode::~NoiseNode() { delete noise; } -void NoiseNode::setLevels(int levels, double min_value, double max_value) -{ +void NoiseNode::setLevels(int levels, double min_value, double max_value) { noise->clearLevels(); noise->addLevelsSimple(levels, 1.0, -1.0, 1.0, 0.5); noise->normalizeAmplitude(min_value, max_value, false); @@ -23,29 +19,22 @@ void NoiseNode::setLevels(int levels, double min_value, double max_value) noise->validate(); } -void NoiseNode::save(PackStream *stream) const -{ +void NoiseNode::save(PackStream *stream) const { noise->save(stream); } -void NoiseNode::load(PackStream *stream) -{ +void NoiseNode::load(PackStream *stream) { noise->load(stream); } -void NoiseNode::copy(DefinitionNode *destination) const -{ - if (destination->getTypeName() == getTypeName()) - { +void NoiseNode::copy(DefinitionNode *destination) const { + if (destination->getTypeName() == getTypeName()) { noise->copy(((NoiseNode *)destination)->noise); - } - else - { + } else { Logs::error() << "Can't copy from " << getTypeName() << " to " << destination->getTypeName() << std::endl; } } -void NoiseNode::validate() -{ +void NoiseNode::validate() { noise->validate(); } diff --git a/src/definition/NoiseNode.h b/src/definition/NoiseNode.h index f28340e..6168d47 100644 --- a/src/definition/NoiseNode.h +++ b/src/definition/NoiseNode.h @@ -11,30 +11,29 @@ namespace definition { /** * Definition node with noise parameters. */ -class DEFINITIONSHARED_EXPORT NoiseNode: public DefinitionNode -{ -public: +class DEFINITIONSHARED_EXPORT NoiseNode : public DefinitionNode { + public: NoiseNode(DefinitionNode *parent); virtual ~NoiseNode(); - inline const NoiseGenerator *getGenerator() {return noise;} + inline const NoiseGenerator *getGenerator() { + return noise; + } /** * Set the number of levels to use in the noise generator. */ - void setLevels(int levels, double min_value=-1.0, double max_value=1.0); + void setLevels(int levels, double min_value = -1.0, double max_value = 1.0); -protected: + protected: virtual void save(PackStream *stream) const override; virtual void load(PackStream *stream) override; virtual void copy(DefinitionNode *destination) const override; virtual void validate() override; -private: + private: NoiseGenerator *noise; - }; - } } diff --git a/src/definition/PaintedGrid.cpp b/src/definition/PaintedGrid.cpp index 2fece9e..a92be11 100644 --- a/src/definition/PaintedGrid.cpp +++ b/src/definition/PaintedGrid.cpp @@ -6,40 +6,33 @@ #include "PaintedGridData.h" #include "PaintedGridBrush.h" -PaintedGrid::PaintedGrid(DefinitionNode *parent): - DefinitionNode(parent, "grid", "grid") -{ +PaintedGrid::PaintedGrid(DefinitionNode *parent) : DefinitionNode(parent, "grid", "grid") { merged_data = new PaintedGridData; brush_data = new PaintedGridData; } -PaintedGrid::~PaintedGrid() -{ +PaintedGrid::~PaintedGrid() { delete merged_data; delete brush_data; } -void PaintedGrid::copy(DefinitionNode *_destination) const -{ - PaintedGrid* destination = (PaintedGrid *)_destination; +void PaintedGrid::copy(DefinitionNode *_destination) const { + PaintedGrid *destination = (PaintedGrid *)_destination; merged_data->copy(destination->merged_data); destination->brush_data->clear(); } -void PaintedGrid::save(PackStream *stream) const -{ +void PaintedGrid::save(PackStream *stream) const { merged_data->save(stream); } -void PaintedGrid::load(PackStream *stream) -{ +void PaintedGrid::load(PackStream *stream) { merged_data->load(stream); brush_data->clear(); } -bool PaintedGrid::getInterpolatedValue(double x, double y, double *result) const -{ +bool PaintedGrid::getInterpolatedValue(double x, double y, double *result) const { int ix, iy; int xlow; int ylow; @@ -48,27 +41,20 @@ bool PaintedGrid::getInterpolatedValue(double x, double y, double *result) const ylow = floor(y); int hit = 0; - for (ix = xlow - 1; ix <= xlow + 2 && !hit; ix++) - { - for (iy = ylow - 1; iy <= ylow + 2 && !hit; iy++) - { - if (getDataPointer(brush_data, x, y, NULL, false) || getDataPointer(merged_data, x, y, NULL, false)) - { + for (ix = xlow - 1; ix <= xlow + 2 && !hit; ix++) { + for (iy = ylow - 1; iy <= ylow + 2 && !hit; iy++) { + if (getDataPointer(brush_data, x, y, NULL, false) || getDataPointer(merged_data, x, y, NULL, false)) { hit = 1; } } } - if (hit && result) - { + if (hit && result) { double stencil[16]; double value; - for (ix = xlow - 1; ix <= xlow + 2; ix++) - { - for (iy = ylow - 1; iy <= ylow + 2; iy++) - { - if (!getGridValue(ix, iy, &value)) - { + for (ix = xlow - 1; ix <= xlow + 2; ix++) { + for (iy = ylow - 1; iy <= ylow + 2; iy++) { + if (!getGridValue(ix, iy, &value)) { value = getInitialValue(ix, iy); } stencil[(iy - (ylow - 1)) * 4 + ix - (xlow - 1)] = value; @@ -81,67 +67,51 @@ bool PaintedGrid::getInterpolatedValue(double x, double y, double *result) const return hit; } -bool PaintedGrid::getGridValue(int x, int y, double *result) const -{ - double* dpointer; +bool PaintedGrid::getGridValue(int x, int y, double *result) const { + double *dpointer; dpointer = getDataPointer(brush_data, x, y, NULL, false); - if (dpointer) - { + if (dpointer) { *result = *dpointer; return true; - } - else - { + } else { dpointer = getDataPointer(merged_data, x, y, NULL, false); - if (dpointer) - { + if (dpointer) { *result = *dpointer; return true; - } - else - { + } else { return false; } } } -double PaintedGrid::getFinalValue(double x, double y) const -{ +double PaintedGrid::getFinalValue(double x, double y) const { double result; - if (getInterpolatedValue(x, y, &result)) - { + if (getInterpolatedValue(x, y, &result)) { return result; - } - else - { + } else { return getInitialValue(x, y); } } -bool PaintedGrid::hasPainting() const -{ +bool PaintedGrid::hasPainting() const { return merged_data->hasData() || brush_data->hasData(); } -bool PaintedGrid::isPainted(int x, int y) const -{ +bool PaintedGrid::isPainted(int x, int y) const { return getDataPointer(brush_data, x, y, NULL, false) || getDataPointer(merged_data, x, y, NULL, false); } -unsigned long PaintedGrid::getMemoryStats() const -{ +unsigned long PaintedGrid::getMemoryStats() const { return merged_data->memsize + brush_data->memsize; } -void PaintedGrid::clearPainting() -{ +void PaintedGrid::clearPainting() { merged_data->clear(); brush_data->clear(); } -void PaintedGrid::applyBrush(const PaintedGridBrush &brush, double x, double y, double force, bool commit) -{ +void PaintedGrid::applyBrush(const PaintedGridBrush &brush, double x, double y, double force, bool commit) { int xstart, xend, ystart, yend; brush.getArea(x, y, &xstart, &ystart, &xend, ¥d); @@ -149,41 +119,34 @@ void PaintedGrid::applyBrush(const PaintedGridBrush &brush, double x, double y, int ix, iy; double dx, dy, influence; - for (ix = xstart; ix <= xend; ix++) - { + for (ix = xstart; ix <= xend; ix++) { dx = (double)ix; - for (iy = ystart; iy <= yend; iy++) - { + for (iy = ystart; iy <= yend; iy++) { dy = (double)iy; influence = brush.getInfluence(x - dx, y - dy); - if (influence > 0.0) - { - double* dpointer = getDataPointer(brush_data, ix, iy, merged_data, true); + if (influence > 0.0) { + double *dpointer = getDataPointer(brush_data, ix, iy, merged_data, true); *dpointer = brush.getValue(this, dx, dy, *dpointer, influence, force); } } } - if (commit) - { + if (commit) { endBrushStroke(); } } -void PaintedGrid::endBrushStroke() -{ +void PaintedGrid::endBrushStroke() { int i, j, k; - PaintedGridData* data = brush_data; + PaintedGridData *data = brush_data; - for (i = 0; i < data->rows_count; i++) - { - for (j = 0; j < data->rows[i].pixel_groups_count; j++) - { - for (k = 0; k < data->rows[i].pixel_groups[j].xend - data->rows[i].pixel_groups[j].xstart + 1; k++) - { - double* dpointer = getDataPointer(merged_data, data->rows[i].pixel_groups[j].xstart + k, data->rows[i].y, NULL, true); + for (i = 0; i < data->rows_count; i++) { + for (j = 0; j < data->rows[i].pixel_groups_count; j++) { + for (k = 0; k < data->rows[i].pixel_groups[j].xend - data->rows[i].pixel_groups[j].xstart + 1; k++) { + double *dpointer = + getDataPointer(merged_data, data->rows[i].pixel_groups[j].xstart + k, data->rows[i].y, NULL, true); *dpointer = data->rows[i].pixel_groups[j].height[k]; } } @@ -192,63 +155,51 @@ void PaintedGrid::endBrushStroke() brush_data->clear(); } -double PaintedGrid::getInitialValue(double, double) const -{ +double PaintedGrid::getInitialValue(double, double) const { return 0.0; } -double *PaintedGrid::getDataPointer(PaintedGridData *data, int x, int y, PaintedGridData *fallback, bool grow) const -{ +double *PaintedGrid::getDataPointer(PaintedGridData *data, int x, int y, PaintedGridData *fallback, bool grow) const { int i; /* Find row */ /* TODO Dichotomic search */ - PaintedGridData::HeightMapRow* row; + PaintedGridData::HeightMapRow *row; i = 0; - while (i < data->rows_count && data->rows[i].y < y) - { + while (i < data->rows_count && data->rows[i].y < y) { i++; } - if (i < data->rows_count && data->rows[i].y == y) - { + if (i < data->rows_count && data->rows[i].y == y) { row = data->rows + i; - } - else if (grow) - { - row = (PaintedGridData::HeightMapRow*)Memory::naiveArrayInsert((void**)&data->rows, sizeof(PaintedGridData::HeightMapRow), data->rows_count, i); + } else if (grow) { + row = (PaintedGridData::HeightMapRow *)Memory::naiveArrayInsert( + (void **)&data->rows, sizeof(PaintedGridData::HeightMapRow), data->rows_count, i); row->y = y; row->pixel_groups_count = 0; - row->pixel_groups = (PaintedGridData::HeightMapPixelGroup*)malloc(1); + row->pixel_groups = (PaintedGridData::HeightMapPixelGroup *)malloc(1); data->rows_count++; data->memsize += sizeof(PaintedGridData::HeightMapRow); - } - else - { + } else { return NULL; } #ifndef NDEBUG /* Check rows */ - for (i = 1; i < data->rows_count; i++) - { + for (i = 1; i < data->rows_count; i++) { assert(data->rows[i].y > data->rows[i - 1].y); } #endif /* Find pixel group */ - PaintedGridData::HeightMapPixelGroup* pixel_group = NULL; - for (i = 0; i < row->pixel_groups_count; i++) - { - if (x < row->pixel_groups[i].xstart - 1) - { + PaintedGridData::HeightMapPixelGroup *pixel_group = NULL; + for (i = 0; i < row->pixel_groups_count; i++) { + if (x < row->pixel_groups[i].xstart - 1) { break; - } - else if (x <= row->pixel_groups[i].xend + 1) - { - if (x == row->pixel_groups[i].xend + 1 && i < row->pixel_groups_count - 1 && x == row->pixel_groups[i + 1].xstart) - { + } else if (x <= row->pixel_groups[i].xend + 1) { + if (x == row->pixel_groups[i].xend + 1 && i < row->pixel_groups_count - 1 && + x == row->pixel_groups[i + 1].xstart) { /* Choose next group if it already includes the pixel */ i++; } @@ -258,53 +209,47 @@ double *PaintedGrid::getDataPointer(PaintedGridData *data, int x, int y, Painted } /* Alter pixel group */ - double* pixel; + double *pixel; int added = 1; - if (!pixel_group) - { - if (!grow) - { + if (!pixel_group) { + if (!grow) { return NULL; } /* Create the pixel group with one pixel */ - pixel_group = (PaintedGridData::HeightMapPixelGroup*)Memory::naiveArrayInsert((void**)&row->pixel_groups, sizeof(PaintedGridData::HeightMapPixelGroup), row->pixel_groups_count, i); + pixel_group = (PaintedGridData::HeightMapPixelGroup *)Memory::naiveArrayInsert( + (void **)&row->pixel_groups, sizeof(PaintedGridData::HeightMapPixelGroup), row->pixel_groups_count, i); pixel_group->xstart = x; pixel_group->xend = x; - pixel_group->height = (double*)malloc(sizeof(double)); + pixel_group->height = (double *)malloc(sizeof(double)); pixel = pixel_group->height; row->pixel_groups_count++; data->memsize += sizeof(PaintedGridData::HeightMapPixelGroup) + sizeof(double); - } - else if (x == pixel_group->xstart - 1) - { - if (!grow) - { + } else if (x == pixel_group->xstart - 1) { + if (!grow) { return NULL; } /* Extend the rowgroup at start */ pixel_group->xstart--; - pixel = (double*)Memory::naiveArrayInsert((void**)&pixel_group->height, sizeof(double), pixel_group->xend - pixel_group->xstart, 0); + pixel = (double *)Memory::naiveArrayInsert((void **)&pixel_group->height, sizeof(double), + pixel_group->xend - pixel_group->xstart, 0); data->memsize += sizeof(double); - } - else if (x == pixel_group->xend + 1) - { - if (!grow) - { + } else if (x == pixel_group->xend + 1) { + if (!grow) { return NULL; } /* Extend the rowgroup at end */ pixel_group->xend++; - pixel = (double*)Memory::naiveArrayInsert((void**)&pixel_group->height, sizeof(double), pixel_group->xend - pixel_group->xstart, pixel_group->xend - pixel_group->xstart); + pixel = (double *)Memory::naiveArrayInsert((void **)&pixel_group->height, sizeof(double), + pixel_group->xend - pixel_group->xstart, + pixel_group->xend - pixel_group->xstart); data->memsize += sizeof(double); - } - else - { + } else { assert(x >= pixel_group->xstart); assert(x <= pixel_group->xend); pixel = pixel_group->height + x - pixel_group->xstart; @@ -313,14 +258,11 @@ double *PaintedGrid::getDataPointer(PaintedGridData *data, int x, int y, Painted #ifndef NDEBUG /* Check pixel groups */ - for (i = 0; i < row->pixel_groups_count; i++) - { - if (i > 0) - { + for (i = 0; i < row->pixel_groups_count; i++) { + if (i > 0) { assert(row->pixel_groups[i].xstart > row->pixel_groups[i - 1].xend); } - if (i < row->pixel_groups_count - 1) - { + if (i < row->pixel_groups_count - 1) { assert(row->pixel_groups[i].xend < row->pixel_groups[i + 1].xstart); } assert(row->pixel_groups[i].xend >= row->pixel_groups[i].xstart); @@ -328,22 +270,15 @@ double *PaintedGrid::getDataPointer(PaintedGridData *data, int x, int y, Painted #endif /* Reset pixel if it had been added */ - if (added) - { - if (fallback) - { - double* dpointer = getDataPointer(fallback, x, y, NULL, false); - if (dpointer) - { + if (added) { + if (fallback) { + double *dpointer = getDataPointer(fallback, x, y, NULL, false); + if (dpointer) { *pixel = *dpointer; - } - else - { + } else { *pixel = getInitialValue(x, y); } - } - else - { + } else { *pixel = getInitialValue(x, y); } } diff --git a/src/definition/PaintedGrid.h b/src/definition/PaintedGrid.h index 9773a7a..63bca66 100644 --- a/src/definition/PaintedGrid.h +++ b/src/definition/PaintedGrid.h @@ -15,10 +15,9 @@ namespace definition { * * Grid cells are considered to be 1.0-sized. */ -class DEFINITIONSHARED_EXPORT PaintedGrid: public DefinitionNode -{ -public: - PaintedGrid(DefinitionNode *parent=0); +class DEFINITIONSHARED_EXPORT PaintedGrid : public DefinitionNode { + public: + PaintedGrid(DefinitionNode *parent = 0); virtual ~PaintedGrid(); virtual void copy(DefinitionNode *destination) const override; @@ -67,7 +66,7 @@ public: /** * Apply a brush stroke at a grid location (locating the brush center). */ - virtual void applyBrush(const PaintedGridBrush &brush, double x, double y, double force, bool commit=false); + virtual void applyBrush(const PaintedGridBrush &brush, double x, double y, double force, bool commit = false); /** * Commit previous brush strokes. @@ -81,14 +80,13 @@ public: */ virtual double getInitialValue(double x, double y) const; -private: + private: double *getDataPointer(PaintedGridData *data, int x, int y, PaintedGridData *fallback, bool grow) const; -private: + private: PaintedGridData *merged_data; PaintedGridData *brush_data; }; - } } diff --git a/src/definition/PaintedGridBrush.cpp b/src/definition/PaintedGridBrush.cpp index ffba79b..97e6cd5 100644 --- a/src/definition/PaintedGridBrush.cpp +++ b/src/definition/PaintedGridBrush.cpp @@ -4,13 +4,11 @@ #include "NoiseGenerator.h" #include "PaintedGrid.h" -PaintedGridBrush::PaintedGridBrush(double hard_radius, double smoothed_size, double total_radius): - hard_radius(hard_radius), smoothed_size(smoothed_size), total_radius(total_radius) -{ +PaintedGridBrush::PaintedGridBrush(double hard_radius, double smoothed_size, double total_radius) + : hard_radius(hard_radius), smoothed_size(smoothed_size), total_radius(total_radius) { } -void PaintedGridBrush::getArea(double x, double y, int *xstart, int *ystart, int *xend, int *yend) const -{ +void PaintedGridBrush::getArea(double x, double y, int *xstart, int *ystart, int *xend, int *yend) const { double s = smoothed_size + hard_radius; *xstart = (int)floor(x - s); @@ -19,39 +17,31 @@ void PaintedGridBrush::getArea(double x, double y, int *xstart, int *ystart, int *yend = (int)ceil(y + s); } -double PaintedGridBrush::getInfluence(double dx, double dy) const -{ +double PaintedGridBrush::getInfluence(double dx, double dy) const { double distance = sqrt(dx * dx + dy * dy); - if (distance > hard_radius) - { - if (distance <= hard_radius + smoothed_size) - { + if (distance > hard_radius) { + if (distance <= hard_radius + smoothed_size) { return 1.0 - (distance - hard_radius) / smoothed_size; - } - else - { + } else { return 0.0; } - } - else - { + } else { return 1.0; } } -double PaintedGridBrush::getValue(const PaintedGrid *, double, double, double basevalue, double, double) const -{ +double PaintedGridBrush::getValue(const PaintedGrid *, double, double, double basevalue, double, double) const { return basevalue; } -double PaintedGridBrushRaiseLower::getValue(const PaintedGrid *, double, double, double basevalue, double influence, double force) const -{ +double PaintedGridBrushRaiseLower::getValue(const PaintedGrid *, double, double, double basevalue, double influence, + double force) const { return basevalue + influence * force; } -double PaintedGridBrushSmooth::getValue(const PaintedGrid *grid, double x, double y, double basevalue, double influence, double force) const -{ +double PaintedGridBrushSmooth::getValue(const PaintedGrid *grid, double x, double y, double basevalue, double influence, + double force) const { double ideal, factor; ideal = grid->getFinalValue((x + total_radius * 0.5), y); ideal += grid->getFinalValue((x - total_radius * 0.5), y); @@ -59,26 +49,25 @@ double PaintedGridBrushSmooth::getValue(const PaintedGrid *grid, double x, doubl ideal += grid->getFinalValue(x, (y + total_radius * 0.5)); ideal /= 4.0; factor = influence * force; - if (factor > 1.0) - { + if (factor > 1.0) { factor = 0.0; } return basevalue + (ideal - basevalue) * factor; } -double PaintedGridBrushAddNoise::getValue(const PaintedGrid *, double x, double y, double basevalue, double influence, double force) const -{ +double PaintedGridBrushAddNoise::getValue(const PaintedGrid *, double x, double y, double basevalue, double influence, + double force) const { return basevalue + generator->get2DTotal(x / total_radius, y / total_radius) * influence * force * total_radius; } -double PaintedGridBrushReset::getValue(const PaintedGrid *grid, double x, double y, double basevalue, double influence, double force) const -{ +double PaintedGridBrushReset::getValue(const PaintedGrid *grid, double x, double y, double basevalue, double influence, + double force) const { double ideal = grid->getInitialValue(x, y); return basevalue + (ideal - basevalue) * influence * force; } -double PaintedGridBrushFlatten::getValue(const PaintedGrid *, double, double, double basevalue, double influence, double force) const -{ +double PaintedGridBrushFlatten::getValue(const PaintedGrid *, double, double, double basevalue, double influence, + double force) const { double ideal = target; return basevalue + (ideal - basevalue) * influence * force; } diff --git a/src/definition/PaintedGridBrush.h b/src/definition/PaintedGridBrush.h index 764d21d..02db785 100644 --- a/src/definition/PaintedGridBrush.h +++ b/src/definition/PaintedGridBrush.h @@ -9,9 +9,8 @@ namespace definition { /** * Base class for brushes that can be used to paint values on a PaintedGrid. */ -class DEFINITIONSHARED_EXPORT PaintedGridBrush -{ -public: +class DEFINITIONSHARED_EXPORT PaintedGridBrush { + public: PaintedGridBrush(double hard_radius, double smoothed_size, double total_radius); /** @@ -27,9 +26,10 @@ public: /** * Abstract method to reimplement to get the final value of a brush stroke at a given point. */ - virtual double getValue(const PaintedGrid *grid, double x, double y, double basevalue, double influence, double force) const; + virtual double getValue(const PaintedGrid *grid, double x, double y, double basevalue, double influence, + double force) const; -protected: + protected: double hard_radius; double smoothed_size; double total_radius; @@ -38,57 +38,64 @@ protected: /** * Brush able to raise or lower the grid value. */ -class DEFINITIONSHARED_EXPORT PaintedGridBrushRaiseLower: public PaintedGridBrush -{ -public: - PaintedGridBrushRaiseLower(const PaintedGridBrush &brush) : PaintedGridBrush(brush) {} - double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, double force) const override; +class DEFINITIONSHARED_EXPORT PaintedGridBrushRaiseLower : public PaintedGridBrush { + public: + PaintedGridBrushRaiseLower(const PaintedGridBrush &brush) : PaintedGridBrush(brush) { + } + double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, + double force) const override; }; /** * Brush able to smooth the value in an area. */ -class DEFINITIONSHARED_EXPORT PaintedGridBrushSmooth: public PaintedGridBrush -{ -public: - PaintedGridBrushSmooth(const PaintedGridBrush &brush) : PaintedGridBrush(brush) {} - double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, double force) const override; +class DEFINITIONSHARED_EXPORT PaintedGridBrushSmooth : public PaintedGridBrush { + public: + PaintedGridBrushSmooth(const PaintedGridBrush &brush) : PaintedGridBrush(brush) { + } + double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, + double force) const override; }; /** * Brush able to add random fractal noise. */ -class DEFINITIONSHARED_EXPORT PaintedGridBrushAddNoise: public PaintedGridBrush -{ -public: - PaintedGridBrushAddNoise(const PaintedGridBrush &brush, NoiseGenerator *generator) : PaintedGridBrush(brush), generator(generator) {} - double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, double force) const override; -private: +class DEFINITIONSHARED_EXPORT PaintedGridBrushAddNoise : public PaintedGridBrush { + public: + PaintedGridBrushAddNoise(const PaintedGridBrush &brush, NoiseGenerator *generator) + : PaintedGridBrush(brush), generator(generator) { + } + double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, + double force) const override; + + private: NoiseGenerator *generator; }; /** * Brush able to reset to initial value. */ -class DEFINITIONSHARED_EXPORT PaintedGridBrushReset: public PaintedGridBrush -{ -public: - PaintedGridBrushReset(const PaintedGridBrush &brush) : PaintedGridBrush(brush) {} - double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, double force) const override; +class DEFINITIONSHARED_EXPORT PaintedGridBrushReset : public PaintedGridBrush { + public: + PaintedGridBrushReset(const PaintedGridBrush &brush) : PaintedGridBrush(brush) { + } + double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, + double force) const override; }; /** * Brush able to flatten to a specific value. */ -class DEFINITIONSHARED_EXPORT PaintedGridBrushFlatten: public PaintedGridBrush -{ -public: - PaintedGridBrushFlatten(const PaintedGridBrush &brush, double target) : PaintedGridBrush(brush), target(target) {} - double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, double force) const override; -private: +class DEFINITIONSHARED_EXPORT PaintedGridBrushFlatten : public PaintedGridBrush { + public: + PaintedGridBrushFlatten(const PaintedGridBrush &brush, double target) : PaintedGridBrush(brush), target(target) { + } + double getValue(const PaintedGrid *grid, double x, double z, double basevalue, double influence, + double force) const override; + + private: double target; }; - } } diff --git a/src/definition/PaintedGridData.cpp b/src/definition/PaintedGridData.cpp index cd6a753..f04ec90 100644 --- a/src/definition/PaintedGridData.cpp +++ b/src/definition/PaintedGridData.cpp @@ -3,46 +3,40 @@ #include #include "PackStream.h" -PaintedGridData::PaintedGridData() -{ +PaintedGridData::PaintedGridData() { rows_count = 0; rows = (HeightMapRow *)malloc(sizeof(HeightMapRow)); memsize = 0; } -PaintedGridData::~PaintedGridData() -{ +PaintedGridData::~PaintedGridData() { clear(); free(rows); } -void PaintedGridData::copy(PaintedGridData *destination) const -{ +void PaintedGridData::copy(PaintedGridData *destination) const { int i, j, n; size_t size; destination->clear(); destination->rows_count = this->rows_count; - if (destination->rows_count > 0) - { + if (destination->rows_count > 0) { size = sizeof(HeightMapRow) * destination->rows_count; - destination->rows = (HeightMapRow*)realloc(destination->rows, size); + destination->rows = (HeightMapRow *)realloc(destination->rows, size); destination->memsize += size; - for (i = 0; i < destination->rows_count; i++) - { + for (i = 0; i < destination->rows_count; i++) { destination->rows[i].y = this->rows[i].y; destination->rows[i].pixel_groups_count = this->rows[i].pixel_groups_count; size = sizeof(HeightMapPixelGroup) * destination->rows[i].pixel_groups_count; - destination->rows[i].pixel_groups = (HeightMapPixelGroup*)malloc(size); + destination->rows[i].pixel_groups = (HeightMapPixelGroup *)malloc(size); destination->memsize += size; - for (j = 0; j < destination->rows[i].pixel_groups_count; j++) - { + for (j = 0; j < destination->rows[i].pixel_groups_count; j++) { destination->rows[i].pixel_groups[j].xstart = this->rows[i].pixel_groups[j].xstart; destination->rows[i].pixel_groups[j].xend = this->rows[i].pixel_groups[j].xend; n = destination->rows[i].pixel_groups[j].xend - destination->rows[i].pixel_groups[j].xstart + 1; size = sizeof(double) * n; - destination->rows[i].pixel_groups[j].height = (double*)malloc(size); + destination->rows[i].pixel_groups[j].height = (double *)malloc(size); destination->memsize += size; memcpy(destination->rows[i].pixel_groups[j].height, this->rows[i].pixel_groups[j].height, size); } @@ -50,56 +44,47 @@ void PaintedGridData::copy(PaintedGridData *destination) const } } -void PaintedGridData::save(PackStream *stream) const -{ +void PaintedGridData::save(PackStream *stream) const { int i, j, k; stream->write(&rows_count); - for (i = 0; i < rows_count; i++) - { + for (i = 0; i < rows_count; i++) { stream->write(&rows[i].y); stream->write(&rows[i].pixel_groups_count); - for (j = 0; j < rows[i].pixel_groups_count; j++) - { + for (j = 0; j < rows[i].pixel_groups_count; j++) { stream->write(&rows[i].pixel_groups[j].xstart); stream->write(&rows[i].pixel_groups[j].xend); - for (k = 0; k < rows[i].pixel_groups[j].xend - rows[i].pixel_groups[j].xstart; k++) - { + for (k = 0; k < rows[i].pixel_groups[j].xend - rows[i].pixel_groups[j].xstart; k++) { stream->write(&rows[i].pixel_groups[j].height[k]); } } } } -void PaintedGridData::load(PackStream *stream) -{ +void PaintedGridData::load(PackStream *stream) { int i, j, k, n; size_t size; clear(); stream->read(&rows_count); - if (rows_count > 0) - { + if (rows_count > 0) { size = sizeof(HeightMapRow) * rows_count; - rows = (HeightMapRow*)realloc(rows, size); + rows = (HeightMapRow *)realloc(rows, size); memsize += size; - for (i = 0; i < rows_count; i++) - { + for (i = 0; i < rows_count; i++) { stream->read(&rows[i].y); stream->read(&rows[i].pixel_groups_count); size = sizeof(HeightMapPixelGroup) * rows[i].pixel_groups_count; - rows[i].pixel_groups = (HeightMapPixelGroup*)malloc(size); + rows[i].pixel_groups = (HeightMapPixelGroup *)malloc(size); memsize += size; - for (j = 0; j < rows[i].pixel_groups_count; j++) - { + for (j = 0; j < rows[i].pixel_groups_count; j++) { stream->read(&rows[i].pixel_groups[j].xstart); stream->read(&rows[i].pixel_groups[j].xend); n = rows[i].pixel_groups[j].xend - rows[i].pixel_groups[j].xstart; size = sizeof(double) * n; - rows[i].pixel_groups[j].height = (double*)malloc(size); + rows[i].pixel_groups[j].height = (double *)malloc(size); memsize += size; - for (k = 0; k < n; k++) - { + for (k = 0; k < n; k++) { stream->read(&rows[i].pixel_groups[j].height[k]); } } @@ -107,13 +92,10 @@ void PaintedGridData::load(PackStream *stream) } } -void PaintedGridData::clear() -{ +void PaintedGridData::clear() { int i, j; - for (i = 0; i < rows_count; i++) - { - for (j = 0; j < rows[i].pixel_groups_count; j++) - { + for (i = 0; i < rows_count; i++) { + for (j = 0; j < rows[i].pixel_groups_count; j++) { free(rows[i].pixel_groups[j].height); } free(rows[i].pixel_groups); diff --git a/src/definition/PaintedGridData.h b/src/definition/PaintedGridData.h index ab00a36..1417822 100644 --- a/src/definition/PaintedGridData.h +++ b/src/definition/PaintedGridData.h @@ -9,11 +9,10 @@ namespace definition { /** * Internal storage class to hold data for a PaintedGrid. */ -class PaintedGridData -{ +class PaintedGridData { friend class PaintedGrid; -public: + public: PaintedGridData(); ~PaintedGridData(); @@ -26,28 +25,27 @@ public: */ void clear(); - inline bool hasData() const {return rows_count > 0;} + inline bool hasData() const { + return rows_count > 0; + } -private: - typedef struct - { + private: + typedef struct { int xstart; int xend; - double* height; + double *height; } HeightMapPixelGroup; - typedef struct - { + typedef struct { int y; int pixel_groups_count; - HeightMapPixelGroup* pixel_groups; + HeightMapPixelGroup *pixel_groups; } HeightMapRow; int memsize; int rows_count; - HeightMapRow* rows; + HeightMapRow *rows; }; - } } diff --git a/src/definition/Scenery.cpp b/src/definition/Scenery.cpp index 7637309..db08709 100644 --- a/src/definition/Scenery.cpp +++ b/src/definition/Scenery.cpp @@ -15,9 +15,7 @@ static const double APP_HEADER = 19866544632.125; static const int DATA_VERSION = 1; -Scenery::Scenery(): - DefinitionNode(NULL, "scenery", "scenery") -{ +Scenery::Scenery() : DefinitionNode(NULL, "scenery", "scenery") { atmosphere = new AtmosphereDefinition(this); camera = new CameraDefinition(this); clouds = new CloudsDefinition(this); @@ -26,21 +24,18 @@ Scenery::Scenery(): water = new WaterDefinition(this); } -void Scenery::validate() -{ +void Scenery::validate() { DefinitionNode::validate(); keepCameraAboveGround(camera); } -Scenery::FileOperationResult Scenery::saveGlobal(const std::string &filepath) const -{ +Scenery::FileOperationResult Scenery::saveGlobal(const std::string &filepath) const { PackStream stream; double app_header = (double)APP_HEADER; double version_header = (double)DATA_VERSION; - if (not stream.bindToFile(filepath, true)) - { + if (not stream.bindToFile(filepath, true)) { return FILE_OPERATION_IOERROR; } @@ -56,25 +51,21 @@ Scenery::FileOperationResult Scenery::saveGlobal(const std::string &filepath) co return FILE_OPERATION_OK; } -Scenery::FileOperationResult Scenery::loadGlobal(const std::string &filepath) -{ +Scenery::FileOperationResult Scenery::loadGlobal(const std::string &filepath) { PackStream stream; double app_header, version_header; - if (not stream.bindToFile(filepath, false)) - { + if (not stream.bindToFile(filepath, false)) { return FILE_OPERATION_IOERROR; } stream.read(&app_header); - if (app_header != APP_HEADER) - { + if (app_header != APP_HEADER) { return FILE_OPERATION_APP_MISMATCH; } stream.read(&version_header); - if ((int)version_header != DATA_VERSION) - { + if ((int)version_header != DATA_VERSION) { return FILE_OPERATION_VERSION_MISMATCH; } @@ -85,14 +76,12 @@ Scenery::FileOperationResult Scenery::loadGlobal(const std::string &filepath) version_header = -1; stream.read(&version_header); - if ((int)version_header != DATA_VERSION) - { + if ((int)version_header != DATA_VERSION) { return FILE_OPERATION_VERSION_MISMATCH; } stream.read(&app_header); - if (app_header != APP_HEADER) - { + if (app_header != APP_HEADER) { return FILE_OPERATION_APP_MISMATCH; } @@ -100,15 +89,12 @@ Scenery::FileOperationResult Scenery::loadGlobal(const std::string &filepath) return FILE_OPERATION_OK; } -Scenery* Scenery::getScenery() -{ +Scenery *Scenery::getScenery() { return this; } -void Scenery::autoPreset(int seed) -{ - if (!seed) - { +void Scenery::autoPreset(int seed) { + if (!seed) { seed = time(NULL); } srand(seed); @@ -127,74 +113,60 @@ void Scenery::autoPreset(int seed) Logs::debug() << "New scenery generated from seed " << seed << std::endl; } -void Scenery::setAtmosphere(AtmosphereDefinition* atmosphere) -{ +void Scenery::setAtmosphere(AtmosphereDefinition *atmosphere) { atmosphere->copy(this->atmosphere); } -void Scenery::getAtmosphere(AtmosphereDefinition* atmosphere) -{ +void Scenery::getAtmosphere(AtmosphereDefinition *atmosphere) { this->atmosphere->copy(atmosphere); } -void Scenery::setCamera(CameraDefinition* camera) -{ +void Scenery::setCamera(CameraDefinition *camera) { camera->copy(this->camera); keepCameraAboveGround(this->camera); } -void Scenery::getCamera(CameraDefinition* camera) -{ +void Scenery::getCamera(CameraDefinition *camera) { this->camera->copy(camera); } -void Scenery::setClouds(CloudsDefinition* clouds) -{ +void Scenery::setClouds(CloudsDefinition *clouds) { clouds->copy(this->clouds); } -void Scenery::getClouds(CloudsDefinition* clouds) -{ +void Scenery::getClouds(CloudsDefinition *clouds) { this->clouds->copy(clouds); } -void Scenery::setTerrain(TerrainDefinition* terrain) -{ +void Scenery::setTerrain(TerrainDefinition *terrain) { terrain->copy(this->terrain); } -void Scenery::getTerrain(TerrainDefinition* terrain) -{ +void Scenery::getTerrain(TerrainDefinition *terrain) { this->terrain->copy(terrain); } -void Scenery::setTextures(TexturesDefinition* textures) -{ +void Scenery::setTextures(TexturesDefinition *textures) { textures->copy(this->textures); } -void Scenery::getTextures(TexturesDefinition* textures) -{ +void Scenery::getTextures(TexturesDefinition *textures) { this->textures->copy(textures); } -void Scenery::setWater(WaterDefinition* water) -{ +void Scenery::setWater(WaterDefinition *water) { water->copy(this->water); } -void Scenery::getWater(WaterDefinition* water) -{ +void Scenery::getWater(WaterDefinition *water) { this->water->copy(water); } -void Scenery::keepCameraAboveGround(CameraDefinition* camera) -{ +void Scenery::keepCameraAboveGround(CameraDefinition *camera) { Vector3 camera_location = camera->getLocation(); double terrain_height = terrain->getInterpolatedHeight(camera_location.x, camera_location.z, true, true) + 1.0; double water_height = 0.5; - if (camera_location.y < water_height || camera_location.y < terrain_height) - { + if (camera_location.y < water_height || camera_location.y < terrain_height) { double diff = ((water_height > terrain_height) ? water_height : terrain_height) - camera_location.y; camera->setLocation(camera_location.add(Vector3(0.0, diff, 0.0))); } diff --git a/src/definition/Scenery.h b/src/definition/Scenery.h index acd8858..a48b363 100644 --- a/src/definition/Scenery.h +++ b/src/definition/Scenery.h @@ -13,9 +13,8 @@ namespace definition { * * This class contains the whole scenery definition. */ -class DEFINITIONSHARED_EXPORT Scenery: public DefinitionNode -{ -public: +class DEFINITIONSHARED_EXPORT Scenery : public DefinitionNode { + public: typedef enum { FILE_OPERATION_OK, FILE_OPERATION_IOERROR, @@ -23,9 +22,9 @@ public: FILE_OPERATION_VERSION_MISMATCH } FileOperationResult; - typedef void (*SceneryCustomDataCallback)(PackStream* stream, void* data); + typedef void (*SceneryCustomDataCallback)(PackStream *stream, void *data); -public: + public: Scenery(); virtual void validate() override; @@ -33,45 +32,56 @@ public: FileOperationResult saveGlobal(const std::string &filepath) const; FileOperationResult loadGlobal(const std::string &filepath); - virtual Scenery* getScenery() override; + virtual Scenery *getScenery() override; - void autoPreset(int seed=0); + void autoPreset(int seed = 0); - void setAtmosphere(AtmosphereDefinition* atmosphere); - inline AtmosphereDefinition* getAtmosphere() const {return atmosphere;} - void getAtmosphere(AtmosphereDefinition* atmosphere); + void setAtmosphere(AtmosphereDefinition *atmosphere); + inline AtmosphereDefinition *getAtmosphere() const { + return atmosphere; + } + void getAtmosphere(AtmosphereDefinition *atmosphere); - void setCamera(CameraDefinition* camera); - inline CameraDefinition* getCamera() const {return camera;} - void getCamera(CameraDefinition* camera); + void setCamera(CameraDefinition *camera); + inline CameraDefinition *getCamera() const { + return camera; + } + void getCamera(CameraDefinition *camera); - void setClouds(CloudsDefinition* clouds); - inline CloudsDefinition* getClouds() const {return clouds;} - void getClouds(CloudsDefinition* clouds); + void setClouds(CloudsDefinition *clouds); + inline CloudsDefinition *getClouds() const { + return clouds; + } + void getClouds(CloudsDefinition *clouds); - void setTerrain(TerrainDefinition* terrain); - inline TerrainDefinition* getTerrain() const {return terrain;} - void getTerrain(TerrainDefinition* terrain); + void setTerrain(TerrainDefinition *terrain); + inline TerrainDefinition *getTerrain() const { + return terrain; + } + void getTerrain(TerrainDefinition *terrain); - void setTextures(TexturesDefinition* textures); - inline TexturesDefinition* getTextures() const {return textures;} - void getTextures(TexturesDefinition* textures); + void setTextures(TexturesDefinition *textures); + inline TexturesDefinition *getTextures() const { + return textures; + } + void getTextures(TexturesDefinition *textures); - void setWater(WaterDefinition* water); - inline WaterDefinition* getWater() const {return water;} - void getWater(WaterDefinition* water); + void setWater(WaterDefinition *water); + inline WaterDefinition *getWater() const { + return water; + } + void getWater(WaterDefinition *water); - void keepCameraAboveGround(CameraDefinition* camera); + void keepCameraAboveGround(CameraDefinition *camera); -private: - AtmosphereDefinition* atmosphere; - CameraDefinition* camera; - CloudsDefinition* clouds; - TerrainDefinition* terrain; - TexturesDefinition* textures; - WaterDefinition* water; + private: + AtmosphereDefinition *atmosphere; + CameraDefinition *camera; + CloudsDefinition *clouds; + TerrainDefinition *terrain; + TexturesDefinition *textures; + WaterDefinition *water; }; - } } diff --git a/src/definition/SurfaceMaterial.cpp b/src/definition/SurfaceMaterial.cpp index b00d6d9..5cc7dc4 100644 --- a/src/definition/SurfaceMaterial.cpp +++ b/src/definition/SurfaceMaterial.cpp @@ -5,13 +5,10 @@ static SurfaceMaterial DEFAULT; -SurfaceMaterial::SurfaceMaterial(): - SurfaceMaterial(COLOR_BLACK) -{ +SurfaceMaterial::SurfaceMaterial() : SurfaceMaterial(COLOR_BLACK) { } -SurfaceMaterial::SurfaceMaterial(const Color &color) -{ +SurfaceMaterial::SurfaceMaterial(const Color &color) { base = new Color(color); hardness = 0.5; reflection = 0.0; @@ -19,26 +16,22 @@ SurfaceMaterial::SurfaceMaterial(const Color &color) receive_shadows = 1.0; } -SurfaceMaterial::~SurfaceMaterial() -{ +SurfaceMaterial::~SurfaceMaterial() { delete base; } -const SurfaceMaterial &SurfaceMaterial::getDefault() -{ +const SurfaceMaterial &SurfaceMaterial::getDefault() { return DEFAULT; } -void SurfaceMaterial::setColor(double r, double g, double b, double a) -{ +void SurfaceMaterial::setColor(double r, double g, double b, double a) { base->r = r; base->g = g; base->b = b; base->a = a; } -void SurfaceMaterial::save(PackStream* stream) const -{ +void SurfaceMaterial::save(PackStream *stream) const { base->save(stream); stream->write(&hardness); @@ -48,8 +41,7 @@ void SurfaceMaterial::save(PackStream* stream) const stream->write(&receive_shadows); } -void SurfaceMaterial::load(PackStream* stream) -{ +void SurfaceMaterial::load(PackStream *stream) { base->load(stream); stream->read(&hardness); @@ -59,8 +51,7 @@ void SurfaceMaterial::load(PackStream* stream) stream->read(&receive_shadows); } -void SurfaceMaterial::copy(SurfaceMaterial *destination) const -{ +void SurfaceMaterial::copy(SurfaceMaterial *destination) const { *destination->base = *base; destination->hardness = hardness; destination->reflection = reflection; @@ -69,6 +60,5 @@ void SurfaceMaterial::copy(SurfaceMaterial *destination) const destination->validate(); } -void SurfaceMaterial::validate() -{ +void SurfaceMaterial::validate() { } diff --git a/src/definition/SurfaceMaterial.h b/src/definition/SurfaceMaterial.h index aa6787e..8546b61 100644 --- a/src/definition/SurfaceMaterial.h +++ b/src/definition/SurfaceMaterial.h @@ -6,23 +6,22 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT SurfaceMaterial -{ -public: +class DEFINITIONSHARED_EXPORT SurfaceMaterial { + public: SurfaceMaterial(); - SurfaceMaterial(const Color& color); + SurfaceMaterial(const Color &color); ~SurfaceMaterial(); static const SurfaceMaterial &getDefault(); void setColor(double r, double g, double b, double a); - void save(PackStream* stream) const; - void load(PackStream* stream); + void save(PackStream *stream) const; + void load(PackStream *stream); void copy(SurfaceMaterial *destination) const; void validate(); -public: + public: Color *base; double hardness; @@ -31,7 +30,6 @@ public: double receive_shadows; }; - } } diff --git a/src/definition/TerrainDefinition.cpp b/src/definition/TerrainDefinition.cpp index c8888b5..d7be658 100644 --- a/src/definition/TerrainDefinition.cpp +++ b/src/definition/TerrainDefinition.cpp @@ -5,9 +5,7 @@ #include "PackStream.h" #include "FloatNode.h" -TerrainDefinition::TerrainDefinition(DefinitionNode* parent): - DefinitionNode(parent, "terrain", "terrain") -{ +TerrainDefinition::TerrainDefinition(DefinitionNode *parent) : DefinitionNode(parent, "terrain", "terrain") { height = 1.0; shadow_smoothing = 0.0; @@ -20,17 +18,14 @@ TerrainDefinition::TerrainDefinition(DefinitionNode* parent): _height_noise = new NoiseGenerator; } -TerrainDefinition::~TerrainDefinition() -{ +TerrainDefinition::~TerrainDefinition() { delete _height_noise; } -void TerrainDefinition::validate() -{ +void TerrainDefinition::validate() { _height_noise->validate(); - if (height < 1.0) - { + if (height < 1.0) { height = 1.0; } @@ -43,9 +38,8 @@ void TerrainDefinition::validate() has_painting = height_map->hasPainting(); } -void TerrainDefinition::copy(DefinitionNode* _destination) const -{ - TerrainDefinition* destination = (TerrainDefinition*)_destination; +void TerrainDefinition::copy(DefinitionNode *_destination) const { + TerrainDefinition *destination = (TerrainDefinition *)_destination; destination->height = height; destination->shadow_smoothing = shadow_smoothing; @@ -57,8 +51,7 @@ void TerrainDefinition::copy(DefinitionNode* _destination) const destination->validate(); } -void TerrainDefinition::save(PackStream* stream) const -{ +void TerrainDefinition::save(PackStream *stream) const { DefinitionNode::save(stream); stream->write(&height); @@ -66,8 +59,7 @@ void TerrainDefinition::save(PackStream* stream) const _height_noise->save(stream); } -void TerrainDefinition::load(PackStream* stream) -{ +void TerrainDefinition::load(PackStream *stream) { DefinitionNode::load(stream); stream->read(&height); @@ -77,44 +69,36 @@ void TerrainDefinition::load(PackStream* stream) validate(); } -double TerrainDefinition::getGridHeight(int x, int z, bool with_painting) -{ +double TerrainDefinition::getGridHeight(int x, int z, bool with_painting) { double h; - if (!with_painting || !has_painting || !height_map->getGridValue(x, z, &h)) - { + if (!with_painting || !has_painting || !height_map->getGridValue(x, z, &h)) { h = _height_noise->get2DTotal((double)x, (double)z); } return h; } -double TerrainDefinition::getInterpolatedHeight(double x, double z, bool scaled, bool with_painting, bool water_offset) -{ +double TerrainDefinition::getInterpolatedHeight(double x, double z, bool scaled, bool with_painting, + bool water_offset) { double h; - if (!with_painting || !has_painting || !height_map->getInterpolatedValue(x, z, &h)) - { + if (!with_painting || !has_painting || !height_map->getInterpolatedValue(x, z, &h)) { h = _height_noise->get2DTotal(x, z); } - if (scaled) - { + if (scaled) { return (water_offset ? (h - water_height->getValue()) : h) * height; - } - else - { + } else { return h; } } -double TerrainDefinition::getWaterOffset() const -{ +double TerrainDefinition::getWaterOffset() const { return -water_height->getValue() * height; } -HeightInfo TerrainDefinition::getHeightInfo() -{ +HeightInfo TerrainDefinition::getHeightInfo() { HeightInfo result; result.min_height = _min_height; @@ -124,16 +108,13 @@ HeightInfo TerrainDefinition::getHeightInfo() return result; } -unsigned long TerrainDefinition::getMemoryStats() -{ +unsigned long TerrainDefinition::getMemoryStats() { return height_map->getMemoryStats(); } -void TerrainDefinition::applyPreset(TerrainPreset preset) -{ +void TerrainDefinition::applyPreset(TerrainPreset preset) { int resolution = 8; - switch (preset) - { + switch (preset) { case TERRAIN_PRESET_STANDARD: _height_noise->randomizeOffsets(); _height_noise->clearLevels(); diff --git a/src/definition/TerrainDefinition.h b/src/definition/TerrainDefinition.h index 4a9a1d1..e787192 100644 --- a/src/definition/TerrainDefinition.h +++ b/src/definition/TerrainDefinition.h @@ -8,56 +8,52 @@ namespace paysages { namespace definition { -typedef struct -{ +typedef struct { double min_height; double max_height; double base_height; } HeightInfo; -class DEFINITIONSHARED_EXPORT TerrainDefinition : public DefinitionNode -{ -public: - TerrainDefinition(DefinitionNode* parent); +class DEFINITIONSHARED_EXPORT TerrainDefinition : public DefinitionNode { + public: + TerrainDefinition(DefinitionNode *parent); virtual ~TerrainDefinition(); - virtual void save(PackStream* stream) const override; - virtual void load(PackStream* stream) override; + virtual void save(PackStream *stream) const override; + virtual void load(PackStream *stream) override; - virtual void copy(DefinitionNode* destination) const override; + virtual void copy(DefinitionNode *destination) const override; virtual void validate() override; - inline FloatNode *propWaterHeight() const {return water_height;} + inline FloatNode *propWaterHeight() const { + return water_height; + } double getGridHeight(int x, int z, bool with_painting); - double getInterpolatedHeight(double x, double z, bool scaled, bool with_painting, bool water_offset=true); + double getInterpolatedHeight(double x, double z, bool scaled, bool with_painting, bool water_offset = true); double getWaterOffset() const; unsigned long getMemoryStats(); HeightInfo getHeightInfo(); -public: - typedef enum - { - TERRAIN_PRESET_STANDARD - } TerrainPreset; + public: + typedef enum { TERRAIN_PRESET_STANDARD } TerrainPreset; void applyPreset(TerrainPreset preset); -public: + public: double height; double shadow_smoothing; - TerrainHeightMap* height_map; + TerrainHeightMap *height_map; bool has_painting; double _detail; - NoiseGenerator* _height_noise; + NoiseGenerator *_height_noise; double _min_height; double _max_height; -private: + private: FloatNode *water_height; }; - } } diff --git a/src/definition/TerrainHeightMap.cpp b/src/definition/TerrainHeightMap.cpp index b15cba1..33f731e 100644 --- a/src/definition/TerrainHeightMap.cpp +++ b/src/definition/TerrainHeightMap.cpp @@ -3,64 +3,55 @@ #include "TerrainDefinition.h" #include "PaintedGridBrush.h" -TerrainHeightMap::TerrainHeightMap(TerrainDefinition* terrain): - PaintedGrid(terrain), terrain(terrain) -{ +TerrainHeightMap::TerrainHeightMap(TerrainDefinition *terrain) : PaintedGrid(terrain), terrain(terrain) { } -void TerrainHeightMap::copy(DefinitionNode* _destination) const -{ - TerrainHeightMap* destination = (TerrainHeightMap*)_destination; +void TerrainHeightMap::copy(DefinitionNode *_destination) const { + TerrainHeightMap *destination = (TerrainHeightMap *)_destination; destination->terrain = terrain; PaintedGrid::copy(destination); } -double TerrainHeightMap::getInitialValue(double x, double y) const -{ +double TerrainHeightMap::getInitialValue(double x, double y) const { return terrain->getInterpolatedHeight(x, y, false, false); } -void TerrainHeightMap::brushElevation(const PaintedGridBrush &brush, double x, double y, double value, bool commit) -{ +void TerrainHeightMap::brushElevation(const PaintedGridBrush &brush, double x, double y, double value, bool commit) { PaintedGridBrushRaiseLower sbrush(brush); applyBrush(sbrush, x, y, value / terrain->height, commit); } -void TerrainHeightMap::brushFlatten(const PaintedGridBrush &brush, double x, double y, double height, double force, bool commit) -{ +void TerrainHeightMap::brushFlatten(const PaintedGridBrush &brush, double x, double y, double height, double force, + bool commit) { PaintedGridBrushFlatten sbrush(brush, height); applyBrush(sbrush, x, y, force / terrain->height, commit); } -void TerrainHeightMap::brushSmooth(const PaintedGridBrush &brush, double x, double y, double value, bool commit) -{ +void TerrainHeightMap::brushSmooth(const PaintedGridBrush &brush, double x, double y, double value, bool commit) { PaintedGridBrushSmooth sbrush(brush); applyBrush(sbrush, x, y, value / terrain->height, commit); } -void TerrainHeightMap::brushAddNoise(const PaintedGridBrush &brush, double x, double y, NoiseGenerator* generator, double value, bool commit) -{ +void TerrainHeightMap::brushAddNoise(const PaintedGridBrush &brush, double x, double y, NoiseGenerator *generator, + double value, bool commit) { PaintedGridBrushAddNoise sbrush(brush, generator); applyBrush(sbrush, x, y, value / terrain->height, commit); } -void TerrainHeightMap::brushReset(const PaintedGridBrush &brush, double x, double y, double value, bool commit) -{ +void TerrainHeightMap::brushReset(const PaintedGridBrush &brush, double x, double y, double value, bool commit) { PaintedGridBrushReset sbrush(brush); applyBrush(sbrush, x, y, value / terrain->height, commit); } -void TerrainHeightMap::clearPainting() -{ +void TerrainHeightMap::clearPainting() { PaintedGrid::clearPainting(); terrain->validate(); } -void TerrainHeightMap::endBrushStroke() -{ +void TerrainHeightMap::endBrushStroke() { PaintedGrid::endBrushStroke(); terrain->validate(); diff --git a/src/definition/TerrainHeightMap.h b/src/definition/TerrainHeightMap.h index cf459b1..6cc4866 100644 --- a/src/definition/TerrainHeightMap.h +++ b/src/definition/TerrainHeightMap.h @@ -8,30 +8,32 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT TerrainHeightMap : public PaintedGrid -{ -public: +class DEFINITIONSHARED_EXPORT TerrainHeightMap : public PaintedGrid { + public: TerrainHeightMap(TerrainDefinition *terrain); virtual void copy(DefinitionNode *destination) const override; - inline TerrainDefinition* getTerrain() const {return terrain;} + inline TerrainDefinition *getTerrain() const { + return terrain; + } virtual double getInitialValue(double x, double y) const override; - void brushElevation(const PaintedGridBrush &brush, double x, double y, double value, bool commit=false); - void brushSmooth(const PaintedGridBrush &brush, double x, double y, double value, bool commit=false); - void brushAddNoise(const PaintedGridBrush &brush, double x, double y, NoiseGenerator* generator, double value, bool commit=false); - void brushReset(const PaintedGridBrush &brush, double x, double y, double value, bool commit=false); - void brushFlatten(const PaintedGridBrush &brush, double x, double y, double height, double force, bool commit=false); + void brushElevation(const PaintedGridBrush &brush, double x, double y, double value, bool commit = false); + void brushSmooth(const PaintedGridBrush &brush, double x, double y, double value, bool commit = false); + void brushAddNoise(const PaintedGridBrush &brush, double x, double y, NoiseGenerator *generator, double value, + bool commit = false); + void brushReset(const PaintedGridBrush &brush, double x, double y, double value, bool commit = false); + void brushFlatten(const PaintedGridBrush &brush, double x, double y, double height, double force, + bool commit = false); virtual void clearPainting() override; virtual void endBrushStroke() override; -private: - TerrainDefinition* terrain; + private: + TerrainDefinition *terrain; }; - } } diff --git a/src/definition/TextureLayerDefinition.cpp b/src/definition/TextureLayerDefinition.cpp index fce5217..61a5592 100644 --- a/src/definition/TextureLayerDefinition.cpp +++ b/src/definition/TextureLayerDefinition.cpp @@ -8,9 +8,8 @@ #include "TerrainDefinition.h" #include "Color.h" -TextureLayerDefinition::TextureLayerDefinition(DefinitionNode* parent): - DefinitionNode(parent, "texture", "texturelayer") -{ +TextureLayerDefinition::TextureLayerDefinition(DefinitionNode *parent) + : DefinitionNode(parent, "texture", "texturelayer") { terrain_zone = new Zone; _displacement_noise = new NoiseGenerator; _detail_noise = new NoiseGenerator; @@ -20,20 +19,17 @@ TextureLayerDefinition::TextureLayerDefinition(DefinitionNode* parent): displacement_scaling = 1.0; } -TextureLayerDefinition::~TextureLayerDefinition() -{ +TextureLayerDefinition::~TextureLayerDefinition() { delete terrain_zone; delete _displacement_noise; delete _detail_noise; delete material; } -void TextureLayerDefinition::validate() -{ +void TextureLayerDefinition::validate() { DefinitionNode::validate(); - if (displacement_scaling < 0.000001) - { + if (displacement_scaling < 0.000001) { displacement_scaling = 0.000001; } @@ -50,20 +46,18 @@ void TextureLayerDefinition::validate() material->validate(); /* Update zone height range */ - Scenery* scenery = getScenery(); - if (scenery) - { - TerrainDefinition* terrain = scenery->getTerrain(); + Scenery *scenery = getScenery(); + if (scenery) { + TerrainDefinition *terrain = scenery->getTerrain(); HeightInfo height_info = terrain->getHeightInfo(); terrain_zone->setRelativeHeight(height_info.min_height, height_info.base_height, height_info.max_height); } } -void TextureLayerDefinition::copy(DefinitionNode *_destination) const -{ +void TextureLayerDefinition::copy(DefinitionNode *_destination) const { DefinitionNode::copy(_destination); - TextureLayerDefinition* destination = (TextureLayerDefinition*)_destination; + TextureLayerDefinition *destination = (TextureLayerDefinition *)_destination; terrain_zone->copy(destination->terrain_zone); @@ -76,8 +70,7 @@ void TextureLayerDefinition::copy(DefinitionNode *_destination) const _detail_noise->copy(destination->_detail_noise); } -void TextureLayerDefinition::save(PackStream* stream) const -{ +void TextureLayerDefinition::save(PackStream *stream) const { DefinitionNode::save(stream); terrain_zone->save(stream); @@ -90,8 +83,7 @@ void TextureLayerDefinition::save(PackStream* stream) const _detail_noise->save(stream); } -void TextureLayerDefinition::load(PackStream* stream) -{ +void TextureLayerDefinition::load(PackStream *stream) { DefinitionNode::load(stream); terrain_zone->load(stream); @@ -104,64 +96,62 @@ void TextureLayerDefinition::load(PackStream* stream) _detail_noise->load(stream); } -void TextureLayerDefinition::applyPreset(TextureLayerPreset preset) -{ +void TextureLayerDefinition::applyPreset(TextureLayerPreset preset) { _displacement_noise->randomizeOffsets(); _detail_noise->randomizeOffsets(); terrain_zone->clear(); - switch (preset) - { - case TEXTURES_LAYER_PRESET_MUD: - displacement_height = 0.02; - displacement_scaling = 3.0; - displacement_offset = 0.0; - material->setColor(0.015, 0.014, 0.014, 1.0); - material->reflection = 0.003; - material->shininess = 4.0; - break; - case TEXTURES_LAYER_PRESET_ROCK: - terrain_zone->addHeightRangeQuick(1.0, 0.6, 0.7, 1.0, 1.0); - displacement_height = 0.3; - displacement_scaling = 2.0; - displacement_offset = 0.0; - material->setColor(0.6, 0.55, 0.57, 1.0); - material->reflection = 0.006; - material->shininess = 6.0; - break; - case TEXTURES_LAYER_PRESET_GRASS: - terrain_zone->addHeightRangeQuick(1.0, 0.45, 0.5, 0.8, 1.0); - terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.05, 0.4); - displacement_height = 0.0; - displacement_scaling = 1.0; - displacement_offset = 0.0; - material->setColor(0.12, 0.19, 0.035, 1.0); - material->reflection = 0.001; - material->shininess = 4.0; - break; - case TEXTURES_LAYER_PRESET_SAND: - terrain_zone->addHeightRangeQuick(1.0, 0.495, 0.505, 0.56, 0.63); - terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.1, 0.4); - displacement_height = 0.05; - displacement_scaling = 5.0; - displacement_offset = 0.0; - material->setColor(1.2, 1.1, 0.9, 1.0); - material->reflection = 0.008; - material->shininess = 1.0; - break; - case TEXTURES_LAYER_PRESET_SNOW: - terrain_zone->addHeightRangeQuick(1.0, 0.77, 0.85, 1.0, 1.0); - terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.2, 1.0); - displacement_height = 0.1; - displacement_scaling = 1.0; - displacement_offset = 0.0; - material->setColor(5.0, 5.0, 5.0, 1.0); - material->reflection = 0.02; - material->shininess = 0.6; - break; - default: - break; + switch (preset) { + case TEXTURES_LAYER_PRESET_MUD: + displacement_height = 0.02; + displacement_scaling = 3.0; + displacement_offset = 0.0; + material->setColor(0.015, 0.014, 0.014, 1.0); + material->reflection = 0.003; + material->shininess = 4.0; + break; + case TEXTURES_LAYER_PRESET_ROCK: + terrain_zone->addHeightRangeQuick(1.0, 0.6, 0.7, 1.0, 1.0); + displacement_height = 0.3; + displacement_scaling = 2.0; + displacement_offset = 0.0; + material->setColor(0.6, 0.55, 0.57, 1.0); + material->reflection = 0.006; + material->shininess = 6.0; + break; + case TEXTURES_LAYER_PRESET_GRASS: + terrain_zone->addHeightRangeQuick(1.0, 0.45, 0.5, 0.8, 1.0); + terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.05, 0.4); + displacement_height = 0.0; + displacement_scaling = 1.0; + displacement_offset = 0.0; + material->setColor(0.12, 0.19, 0.035, 1.0); + material->reflection = 0.001; + material->shininess = 4.0; + break; + case TEXTURES_LAYER_PRESET_SAND: + terrain_zone->addHeightRangeQuick(1.0, 0.495, 0.505, 0.56, 0.63); + terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.1, 0.4); + displacement_height = 0.05; + displacement_scaling = 5.0; + displacement_offset = 0.0; + material->setColor(1.2, 1.1, 0.9, 1.0); + material->reflection = 0.008; + material->shininess = 1.0; + break; + case TEXTURES_LAYER_PRESET_SNOW: + terrain_zone->addHeightRangeQuick(1.0, 0.77, 0.85, 1.0, 1.0); + terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.2, 1.0); + displacement_height = 0.1; + displacement_scaling = 1.0; + displacement_offset = 0.0; + material->setColor(5.0, 5.0, 5.0, 1.0); + material->reflection = 0.02; + material->shininess = 0.6; + break; + default: + break; } validate(); diff --git a/src/definition/TextureLayerDefinition.h b/src/definition/TextureLayerDefinition.h index e8696fc..5594f5f 100644 --- a/src/definition/TextureLayerDefinition.h +++ b/src/definition/TextureLayerDefinition.h @@ -8,17 +8,10 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT TextureLayerDefinition : public DefinitionNode -{ -public: - typedef enum - { - TEXTURES_MERGE_FADE, - TEXTURES_MERGE_DISSOLVE, - TEXTURES_MERGE_DISPLACEMENT_VALUE - } TextureMergeMode; - typedef enum - { +class DEFINITIONSHARED_EXPORT TextureLayerDefinition : public DefinitionNode { + public: + typedef enum { TEXTURES_MERGE_FADE, TEXTURES_MERGE_DISSOLVE, TEXTURES_MERGE_DISPLACEMENT_VALUE } TextureMergeMode; + typedef enum { TEXTURES_LAYER_PRESET_MUD, TEXTURES_LAYER_PRESET_ROCK, TEXTURES_LAYER_PRESET_GRASS, @@ -26,34 +19,33 @@ public: TEXTURES_LAYER_PRESET_SNOW } TextureLayerPreset; -public: - TextureLayerDefinition(DefinitionNode* parent); + public: + TextureLayerDefinition(DefinitionNode *parent); virtual ~TextureLayerDefinition(); - virtual void save(PackStream* stream) const override; - virtual void load(PackStream* stream) override; + virtual void save(PackStream *stream) const override; + virtual void load(PackStream *stream) override; - virtual void copy(DefinitionNode* destination) const override; + virtual void copy(DefinitionNode *destination) const override; virtual void validate() override; void applyPreset(TextureLayerPreset preset); -public: - Zone* terrain_zone; + public: + Zone *terrain_zone; double displacement_scaling; double displacement_height; double displacement_offset; /*double detail_scaling; double detail_height;*/ - SurfaceMaterial* material; + SurfaceMaterial *material; /*double cancel_displacement_factor; TexturesMergeMode merge_mode;*/ - NoiseGenerator* _displacement_noise; - NoiseGenerator* _detail_noise; + NoiseGenerator *_displacement_noise; + NoiseGenerator *_detail_noise; /*Curve* _local_slope_condition;*/ }; - } } diff --git a/src/definition/TexturesDefinition.cpp b/src/definition/TexturesDefinition.cpp index e253cec..5197c2a 100644 --- a/src/definition/TexturesDefinition.cpp +++ b/src/definition/TexturesDefinition.cpp @@ -2,27 +2,22 @@ #include "TextureLayerDefinition.h" -static DefinitionNode* _layer_constructor(Layers* parent) -{ +static DefinitionNode *_layer_constructor(Layers *parent) { return new TextureLayerDefinition(parent); } -TexturesDefinition::TexturesDefinition(DefinitionNode *parent): - Layers(parent, "textures", _layer_constructor) -{ +TexturesDefinition::TexturesDefinition(DefinitionNode *parent) : Layers(parent, "textures", _layer_constructor) { } -void TexturesDefinition::applyPreset(TexturesPreset preset) -{ - TextureLayerDefinition* layer; +void TexturesDefinition::applyPreset(TexturesPreset preset) { + TextureLayerDefinition *layer; clear(); layer = getTextureLayer(addLayer()); layer->applyPreset(TextureLayerDefinition::TEXTURES_LAYER_PRESET_MUD); layer->setName("Mud"); - if (preset == TEXTURES_PRESET_FULL) - { + if (preset == TEXTURES_PRESET_FULL) { layer = getTextureLayer(addLayer()); layer->applyPreset(TextureLayerDefinition::TEXTURES_LAYER_PRESET_ROCK); layer->setName("Ground"); @@ -38,9 +33,7 @@ void TexturesDefinition::applyPreset(TexturesPreset preset) layer = getTextureLayer(addLayer()); layer->applyPreset(TextureLayerDefinition::TEXTURES_LAYER_PRESET_SNOW); layer->setName("Snow"); - } - else if (preset == TEXTURES_PRESET_IRELAND) - { + } else if (preset == TEXTURES_PRESET_IRELAND) { layer = getTextureLayer(addLayer()); layer->applyPreset(TextureLayerDefinition::TEXTURES_LAYER_PRESET_ROCK); layer->setName("Ground"); @@ -48,9 +41,7 @@ void TexturesDefinition::applyPreset(TexturesPreset preset) layer = getTextureLayer(addLayer()); layer->applyPreset(TextureLayerDefinition::TEXTURES_LAYER_PRESET_GRASS); layer->setName("Grass"); - } - else if (preset == TEXTURES_PRESET_ALPS) - { + } else if (preset == TEXTURES_PRESET_ALPS) { layer = getTextureLayer(addLayer()); layer->applyPreset(TextureLayerDefinition::TEXTURES_LAYER_PRESET_ROCK); layer->setName("Ground"); @@ -58,19 +49,15 @@ void TexturesDefinition::applyPreset(TexturesPreset preset) layer = getTextureLayer(addLayer()); layer->applyPreset(TextureLayerDefinition::TEXTURES_LAYER_PRESET_SNOW); layer->setName("Snow"); - } - else if (preset == TEXTURES_PRESET_CANYON) - { + } else if (preset == TEXTURES_PRESET_CANYON) { /* TODO */ } } -double TexturesDefinition::getMaximalDisplacement() -{ +double TexturesDefinition::getMaximalDisplacement() { double result = 0.0; int n = count(); - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { result += getTextureLayer(i)->displacement_height; } return result; diff --git a/src/definition/TexturesDefinition.h b/src/definition/TexturesDefinition.h index a71b299..3b78f78 100644 --- a/src/definition/TexturesDefinition.h +++ b/src/definition/TexturesDefinition.h @@ -8,15 +8,15 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT TexturesDefinition : public Layers -{ -public: +class DEFINITIONSHARED_EXPORT TexturesDefinition : public Layers { + public: TexturesDefinition(DefinitionNode *parent); - inline TextureLayerDefinition* getTextureLayer(int position) const {return (TextureLayerDefinition*)getLayer(position);} + inline TextureLayerDefinition *getTextureLayer(int position) const { + return (TextureLayerDefinition *)getLayer(position); + } - typedef enum - { + typedef enum { TEXTURES_PRESET_FULL, TEXTURES_PRESET_IRELAND, TEXTURES_PRESET_ALPS, @@ -26,7 +26,6 @@ public: double getMaximalDisplacement(); }; - } } diff --git a/src/definition/TimeManager.cpp b/src/definition/TimeManager.cpp index af82410..c206636 100644 --- a/src/definition/TimeManager.cpp +++ b/src/definition/TimeManager.cpp @@ -7,21 +7,18 @@ #include "CloudLayerDefinition.h" #include "WaterDefinition.h" -TimeManager::TimeManager() -{ +TimeManager::TimeManager() { wind_x = 0.0; wind_z = 0.0; } -void TimeManager::moveForward(Scenery *scenery, double amount) -{ +void TimeManager::moveForward(Scenery *scenery, double amount) { // Move the sun scenery->getAtmosphere()->setDayTime(scenery->getAtmosphere()->propDayTime()->getValue() + amount); // Move the clouds int n = scenery->getClouds()->count(); - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { CloudLayerDefinition *cloud = scenery->getClouds()->getCloudLayer(i); cloud->propXOffset()->addValue(-wind_x * amount * 100.0); cloud->propZOffset()->addValue(-wind_z * amount * 100.0); @@ -35,8 +32,7 @@ void TimeManager::moveForward(Scenery *scenery, double amount) // TODO Alter noise offsets } -void TimeManager::setWind(double wind_x, double wind_z) -{ +void TimeManager::setWind(double wind_x, double wind_z) { this->wind_x = wind_x; this->wind_z = wind_z; } diff --git a/src/definition/TimeManager.h b/src/definition/TimeManager.h index 3024166..5237931 100644 --- a/src/definition/TimeManager.h +++ b/src/definition/TimeManager.h @@ -9,9 +9,8 @@ namespace definition { /** * Time manager, handling the inexorable passing of time. */ -class DEFINITIONSHARED_EXPORT TimeManager -{ -public: +class DEFINITIONSHARED_EXPORT TimeManager { + public: TimeManager(); /** @@ -26,11 +25,10 @@ public: */ void setWind(double wind_x, double wind_z); -private: + private: double wind_x; double wind_z; }; - } } diff --git a/src/definition/WaterDefinition.cpp b/src/definition/WaterDefinition.cpp index c4cb3c1..ccd275b 100644 --- a/src/definition/WaterDefinition.cpp +++ b/src/definition/WaterDefinition.cpp @@ -7,9 +7,7 @@ #include "IntNode.h" #include "FloatNode.h" -WaterDefinition::WaterDefinition(DefinitionNode* parent): - DefinitionNode(parent, "water", "water") -{ +WaterDefinition::WaterDefinition(DefinitionNode *parent) : DefinitionNode(parent, "water", "water") { model = new IntNode(this, "model", -1); reflection = new FloatNode(this, "reflection"); xoffset = new FloatNode(this, "xoffset"); @@ -32,16 +30,14 @@ WaterDefinition::WaterDefinition(DefinitionNode* parent): model->addWatcher(this, true); } -WaterDefinition::~WaterDefinition() -{ +WaterDefinition::~WaterDefinition() { delete material; delete depth_color; delete foam_material; delete noise_state; } -void WaterDefinition::save(PackStream* stream) const -{ +void WaterDefinition::save(PackStream *stream) const { DefinitionNode::save(stream); material->save(stream); @@ -61,8 +57,7 @@ void WaterDefinition::save(PackStream* stream) const noise_state->save(stream); } -void WaterDefinition::load(PackStream* stream) -{ +void WaterDefinition::load(PackStream *stream) { DefinitionNode::load(stream); material->load(stream); @@ -84,11 +79,10 @@ void WaterDefinition::load(PackStream* stream) validate(); } -void WaterDefinition::copy(DefinitionNode* _destination) const -{ +void WaterDefinition::copy(DefinitionNode *_destination) const { DefinitionNode::copy(_destination); - WaterDefinition* destination = (WaterDefinition*)_destination; + WaterDefinition *destination = (WaterDefinition *)_destination; *destination->material = *material; *destination->depth_color = *depth_color; destination->transparency_depth = transparency_depth; @@ -103,8 +97,7 @@ void WaterDefinition::copy(DefinitionNode* _destination) const noise_state->copy(destination->noise_state); } -void WaterDefinition::validate() -{ +void WaterDefinition::validate() { DefinitionNode::validate(); depth_color->a = 1.0; @@ -121,14 +114,11 @@ void WaterDefinition::validate() foam_material->validate(); } -void WaterDefinition::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) -{ - if (node == model) - { +void WaterDefinition::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) { + if (node == model) { noise_state->randomizeOffsets(); - switch (model->getValue()) - { + switch (model->getValue()) { case 1: transparency = 0.3; reflection->setValue(0.07); @@ -164,14 +154,10 @@ void WaterDefinition::nodeChanged(const DefinitionNode *node, const DefinitionDi } } -void WaterDefinition::applyPreset(WaterPreset preset) -{ - if (preset == WATER_PRESET_LAKE) - { +void WaterDefinition::applyPreset(WaterPreset preset) { + if (preset == WATER_PRESET_LAKE) { model->setValue(0); - } - else if (preset == WATER_PRESET_SEA) - { + } else if (preset == WATER_PRESET_SEA) { model->setValue(1); } } diff --git a/src/definition/WaterDefinition.h b/src/definition/WaterDefinition.h index 77e8eb8..e191045 100644 --- a/src/definition/WaterDefinition.h +++ b/src/definition/WaterDefinition.h @@ -9,36 +9,39 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT WaterDefinition: public DefinitionNode, public DefinitionWatcher -{ -public: - WaterDefinition(DefinitionNode* parent); +class DEFINITIONSHARED_EXPORT WaterDefinition : public DefinitionNode, public DefinitionWatcher { + public: + WaterDefinition(DefinitionNode *parent); virtual ~WaterDefinition(); - virtual void save(PackStream* stream) const override; - virtual void load(PackStream* stream) override; + virtual void save(PackStream *stream) const override; + virtual void load(PackStream *stream) override; - virtual void copy(DefinitionNode* destination) const override; + virtual void copy(DefinitionNode *destination) const override; virtual void validate() override; - inline IntNode *propModel() const {return model;} - inline FloatNode *propReflection() const {return reflection;} - inline FloatNode *propXOffset() const {return xoffset;} - inline FloatNode *propZOffset() const {return zoffset;} + inline IntNode *propModel() const { + return model; + } + inline FloatNode *propReflection() const { + return reflection; + } + inline FloatNode *propXOffset() const { + return xoffset; + } + inline FloatNode *propZOffset() const { + return zoffset; + } virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff); - typedef enum - { - WATER_PRESET_LAKE, - WATER_PRESET_SEA - } WaterPreset; + typedef enum { WATER_PRESET_LAKE, WATER_PRESET_SEA } WaterPreset; void applyPreset(WaterPreset preset); -public: + public: double transparency; - SurfaceMaterial* material; - Color* depth_color; + SurfaceMaterial *material; + Color *depth_color; double transparency_depth; double lighting_depth; @@ -48,17 +51,16 @@ public: double detail_height; double foam_coverage; - SurfaceMaterial* foam_material; + SurfaceMaterial *foam_material; - NoiseState* noise_state; + NoiseState *noise_state; -private: + private: IntNode *model; FloatNode *reflection; FloatNode *xoffset; FloatNode *zoffset; }; - } } diff --git a/src/definition/Zone.cpp b/src/definition/Zone.cpp index 33a326d..b9aaab7 100644 --- a/src/definition/Zone.cpp +++ b/src/definition/Zone.cpp @@ -5,9 +5,7 @@ #include "PackStream.h" #include "Vector3.h" -Zone::Zone(DefinitionNode *parent): - DefinitionNode(parent, "zone", "zone") -{ +Zone::Zone(DefinitionNode *parent) : DefinitionNode(parent, "zone", "zone") { value_by_height = new Curve; absolute_height = 1; value_by_height->setDefault(1.0); @@ -15,14 +13,12 @@ Zone::Zone(DefinitionNode *parent): value_by_slope->setDefault(1.0); } -Zone::~Zone() -{ +Zone::~Zone() { delete value_by_height; delete value_by_slope; } -void Zone::save(PackStream* stream) const -{ +void Zone::save(PackStream *stream) const { stream->write(&absolute_height); stream->write(&relative_height_min); stream->write(&relative_height_middle); @@ -32,8 +28,7 @@ void Zone::save(PackStream* stream) const value_by_slope->save(stream); } -void Zone::load(PackStream* stream) -{ +void Zone::load(PackStream *stream) { stream->read(&absolute_height); stream->read(&relative_height_min); stream->read(&relative_height_middle); @@ -43,9 +38,8 @@ void Zone::load(PackStream* stream) value_by_slope->load(stream); } -void Zone::copy(DefinitionNode* _destination) const -{ - Zone* destination = (Zone*)_destination; +void Zone::copy(DefinitionNode *_destination) const { + Zone *destination = (Zone *)_destination; destination->absolute_height = absolute_height; destination->relative_height_min = relative_height_min; @@ -56,29 +50,23 @@ void Zone::copy(DefinitionNode* _destination) const value_by_slope->copy(destination->value_by_slope); } -void Zone::clear() -{ +void Zone::clear() { value_by_height->clear(); value_by_slope->clear(); } -void Zone::setAbsoluteHeight() -{ +void Zone::setAbsoluteHeight() { absolute_height = 1; } -void Zone::setRelativeHeight(double min, double middle, double max) -{ - if (max < min) - { +void Zone::setRelativeHeight(double min, double middle, double max) { + if (max < min) { max = min; } - if (middle < min) - { + if (middle < min) { middle = min; } - if (middle > max) - { + if (middle > max) { middle = max; } @@ -88,81 +76,61 @@ void Zone::setRelativeHeight(double min, double middle, double max) relative_height_max = max; } -void Zone::getHeightCurve(Curve* curve) const -{ +void Zone::getHeightCurve(Curve *curve) const { value_by_height->copy(curve); } -void Zone::setHeightCurve(Curve* curve) -{ +void Zone::setHeightCurve(Curve *curve) { curve->copy(value_by_height); } -void Zone::addHeightRangeQuick(double value, double hardmin, double softmin, double softmax, double hardmax) -{ +void Zone::addHeightRangeQuick(double value, double hardmin, double softmin, double softmax, double hardmax) { value_by_height->addPoint(hardmin, 0.0); value_by_height->addPoint(softmin, value); value_by_height->addPoint(softmax, value); value_by_height->addPoint(hardmax, 0.0); } -void Zone::getSlopeCurve(Curve* curve) const -{ +void Zone::getSlopeCurve(Curve *curve) const { value_by_slope->copy(curve); } -void Zone::setSlopeCurve(Curve* curve) -{ +void Zone::setSlopeCurve(Curve *curve) { curve->copy(value_by_slope); } -void Zone::addSlopeRangeQuick(double value, double hardmin, double softmin, double softmax, double hardmax) -{ +void Zone::addSlopeRangeQuick(double value, double hardmin, double softmin, double softmax, double hardmax) { value_by_slope->addPoint(hardmin, 0.0); value_by_slope->addPoint(softmin, value); value_by_slope->addPoint(softmax, value); value_by_slope->addPoint(hardmax, 0.0); } -double Zone::getValue(const Vector3 &location, const Vector3 &normal) const -{ +double Zone::getValue(const Vector3 &location, const Vector3 &normal) const { double final_height; double value_height, value_steepness; - if (absolute_height) - { + if (absolute_height) { final_height = location.y; - } - else - { - if (location.y >= relative_height_max) - { + } else { + if (location.y >= relative_height_max) { final_height = 1.0; - } - else if (location.y <= relative_height_min) - { + } else if (location.y <= relative_height_min) { final_height = 0.0; - } - else if (location.y <= relative_height_middle) - { + } else if (location.y <= relative_height_middle) { final_height = 0.5 * (location.y - relative_height_min) / (relative_height_middle - relative_height_min); - } - else - { - final_height = 0.5 + 0.5 * (location.y - relative_height_middle) / (relative_height_max - relative_height_middle); + } else { + final_height = + 0.5 + 0.5 * (location.y - relative_height_middle) / (relative_height_max - relative_height_middle); } } value_height = value_by_height->getValue(final_height); value_steepness = value_by_slope->getValue(1.0 - normal.y); - if (value_steepness < value_height) - { + if (value_steepness < value_height) { return value_steepness; - } - else - { + } else { return value_height; } } - diff --git a/src/definition/Zone.h b/src/definition/Zone.h index 0a5b4d3..b7a3823 100644 --- a/src/definition/Zone.h +++ b/src/definition/Zone.h @@ -8,42 +8,40 @@ namespace paysages { namespace definition { -class DEFINITIONSHARED_EXPORT Zone : public DefinitionNode -{ -public: +class DEFINITIONSHARED_EXPORT Zone : public DefinitionNode { + public: Zone(DefinitionNode *parent = 0); virtual ~Zone(); - virtual void save(PackStream* stream) const override; - virtual void load(PackStream* stream) override; + virtual void save(PackStream *stream) const override; + virtual void load(PackStream *stream) override; - virtual void copy(DefinitionNode* destination) const override; + virtual void copy(DefinitionNode *destination) const override; void clear(); void setAbsoluteHeight(); void setRelativeHeight(double min, double middle, double max); - void getHeightCurve(Curve* curve) const; - void setHeightCurve(Curve* curve); + void getHeightCurve(Curve *curve) const; + void setHeightCurve(Curve *curve); void addHeightRangeQuick(double value, double hardmin, double softmin, double softmax, double hardmax); - void getSlopeCurve(Curve* curve) const; - void setSlopeCurve(Curve* curve); + void getSlopeCurve(Curve *curve) const; + void setSlopeCurve(Curve *curve); void addSlopeRangeQuick(double value, double hardmin, double softmin, double softmax, double hardmax); double getValue(const Vector3 &location, const Vector3 &normal) const; -private: + private: int absolute_height; double relative_height_min; double relative_height_middle; double relative_height_max; - Curve* value_by_height; - Curve* value_by_slope; + Curve *value_by_height; + Curve *value_by_slope; }; - } } diff --git a/src/definition/definition_global.h b/src/definition/definition_global.h index 82da9d0..1496366 100644 --- a/src/definition/definition_global.h +++ b/src/definition/definition_global.h @@ -4,47 +4,47 @@ #include #if defined(DEFINITION_LIBRARY) -# define DEFINITIONSHARED_EXPORT Q_DECL_EXPORT +#define DEFINITIONSHARED_EXPORT Q_DECL_EXPORT #else -# define DEFINITIONSHARED_EXPORT Q_DECL_IMPORT +#define DEFINITIONSHARED_EXPORT Q_DECL_IMPORT #endif #include "basics_global.h" namespace paysages { namespace definition { - class DefinitionNode; - class DefinitionDiff; - class FloatNode; - class FloatDiff; - class IntNode; - class IntDiff; - class NoiseNode; - class DiffManager; - class DefinitionWatcher; - class Scenery; - class CameraDefinition; - class SurfaceMaterial; - class Zone; - class WaterDefinition; - class Layers; - class CloudsDefinition; - class CloudLayerDefinition; - class AtmosphereDefinition; - class GodRaysDefinition; - class TexturesDefinition; - class TextureLayerDefinition; - class TerrainDefinition; - class TerrainHeightMap; - class PaintedGrid; - class PaintedGridData; - class PaintedGridBrush; - class PaintedGridBrushRaiseLower; - class PaintedGridBrushSmooth; - class PaintedGridBrushAddNoise; - class PaintedGridBrushReset; - class PaintedGridBrushFlatten; - class TimeManager; +class DefinitionNode; +class DefinitionDiff; +class FloatNode; +class FloatDiff; +class IntNode; +class IntDiff; +class NoiseNode; +class DiffManager; +class DefinitionWatcher; +class Scenery; +class CameraDefinition; +class SurfaceMaterial; +class Zone; +class WaterDefinition; +class Layers; +class CloudsDefinition; +class CloudLayerDefinition; +class AtmosphereDefinition; +class GodRaysDefinition; +class TexturesDefinition; +class TextureLayerDefinition; +class TerrainDefinition; +class TerrainHeightMap; +class PaintedGrid; +class PaintedGridData; +class PaintedGridBrush; +class PaintedGridBrushRaiseLower; +class PaintedGridBrushSmooth; +class PaintedGridBrushAddNoise; +class PaintedGridBrushReset; +class PaintedGridBrushFlatten; +class TimeManager; } } using namespace paysages::definition; diff --git a/src/experiments/bruneton/Main.cpp b/src/experiments/bruneton/Main.cpp index f9909f5..b11a229 100644 --- a/src/experiments/bruneton/Main.cpp +++ b/src/experiments/bruneton/Main.cpp @@ -54,22 +54,20 @@ using namespace std; // TOOLS // ---------------------------------------------------------------------------- -void loadTIFF(const char *name, unsigned char *tex) -{ +void loadTIFF(const char *name, unsigned char *tex) { tstrip_t strip = 0; tsize_t off = 0; tsize_t n = 0; - TIFF* tf = TIFFOpen(name, "r"); - while ((n = TIFFReadEncodedStrip(tf, strip, tex + off, (tsize_t) -1)) > 0) { - strip += 1; + TIFF *tf = TIFFOpen(name, "r"); + while ((n = TIFFReadEncodedStrip(tf, strip, tex + off, (tsize_t)-1)) > 0) { + strip += 1; off += n; }; TIFFClose(tf); } -string* loadFile(const string &fileName) -{ - string* result = new string(); +string *loadFile(const string &fileName) { + string *result = new string(); ifstream file(fileName.c_str()); if (!file) { std::cerr << "Cannot open file " << fileName << endl; @@ -84,8 +82,7 @@ string* loadFile(const string &fileName) return result; } -void printShaderLog(int shaderId) -{ +void printShaderLog(int shaderId) { int logLength; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { @@ -96,8 +93,7 @@ void printShaderLog(int shaderId) } } -unsigned int loadProgram(const vector &files) -{ +unsigned int loadProgram(const vector &files) { unsigned int programId = glCreateProgram(); unsigned int vertexShaderId = glCreateShader(GL_VERTEX_SHADER); unsigned int fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER); @@ -105,12 +101,12 @@ unsigned int loadProgram(const vector &files) glAttachShader(programId, fragmentShaderId); int n = files.size(); - string **strs = new string*[n]; - const char** lines = new const char*[n + 1]; + string **strs = new string *[n]; + const char **lines = new const char *[n + 1]; cout << "loading program " << files[n - 1] << "..." << endl; bool geo = false; for (int i = 0; i < n; ++i) { - string* s = loadFile(files[i]); + string *s = loadFile(files[i]); strs[i] = s; lines[i + 1] = s->c_str(); if (strstr(lines[i + 1], "_GEOMETRY_") != NULL) { @@ -151,8 +147,7 @@ unsigned int loadProgram(const vector &files) return programId; } -void drawQuad() -{ +void drawQuad() { glBegin(GL_TRIANGLE_STRIP); glVertex2f(-1.0, -1.0); glVertex2f(+1.0, -1.0); @@ -174,14 +169,14 @@ const int deltaSRUnit = 5; const int deltaSMUnit = 6; const int deltaJUnit = 7; -unsigned int reflectanceTexture;//unit 0, ground reflectance texture -unsigned int transmittanceTexture;//unit 1, T table -unsigned int irradianceTexture;//unit 2, E table -unsigned int inscatterTexture;//unit 3, S table -unsigned int deltaETexture;//unit 4, deltaE table -unsigned int deltaSRTexture;//unit 5, deltaS table (Rayleigh part) -unsigned int deltaSMTexture;//unit 6, deltaS table (Mie part) -unsigned int deltaJTexture;//unit 7, deltaJ table +unsigned int reflectanceTexture; // unit 0, ground reflectance texture +unsigned int transmittanceTexture; // unit 1, T table +unsigned int irradianceTexture; // unit 2, E table +unsigned int inscatterTexture; // unit 3, S table +unsigned int deltaETexture; // unit 4, deltaE table +unsigned int deltaSRTexture; // unit 5, deltaS table (Rayleigh part) +unsigned int deltaSMTexture; // unit 6, deltaS table (Mie part) +unsigned int deltaJTexture; // unit 7, deltaJ table unsigned int transmittanceProg; unsigned int irradiance1Prog; @@ -197,8 +192,7 @@ unsigned int fbo; unsigned int drawProg; -void setLayer(unsigned int prog, int layer) -{ +void setLayer(unsigned int prog, int layer) { double r = layer / (RES_R - 1.0); r = r * r; r = sqrt(Rg * Rg + r * (Rt * Rt - Rg * Rg)) + (layer == 0 ? 0.01 : (layer == RES_R - 1 ? -0.001 : 0.0)); @@ -211,9 +205,8 @@ void setLayer(unsigned int prog, int layer) glUniform1i(glGetUniformLocation(prog, "layer"), layer); } -void loadData() -{ - //return; +void loadData() { + // return; cout << "loading Earth texture..." << endl; glActiveTexture(GL_TEXTURE0 + reflectanceUnit); glGenTextures(1, &reflectanceTexture); @@ -230,8 +223,7 @@ void loadData() delete[] tex; } -void precompute() -{ +void precompute() { glActiveTexture(GL_TEXTURE0 + transmittanceUnit); glGenTextures(1, &transmittanceTexture); glBindTexture(GL_TEXTURE_2D, transmittanceTexture); @@ -397,7 +389,7 @@ void precompute() // Rayleigh and Mie separated in deltaSR + deltaSM glFramebufferTextureEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, deltaSRTexture, 0); glFramebufferTextureEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, deltaSMTexture, 0); - unsigned int bufs[2] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT }; + unsigned int bufs[2] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT}; glDrawBuffers(2, bufs); glViewport(0, 0, RES_MU_S * RES_NU, RES_MU); glUseProgram(inscatter1Prog); @@ -506,8 +498,7 @@ void precompute() glUseProgram(drawProg); } -void recompute() -{ +void recompute() { glDeleteTextures(1, &transmittanceTexture); glDeleteTextures(1, &irradianceTexture); glDeleteTextures(1, &inscatterTexture); @@ -549,39 +540,34 @@ mat4d view; double exposure = 0.4; -void updateView() -{ - double co = cos(lon); - double so = sin(lon); - double ca = cos(lat); - double sa = sin(lat); - vec3d po = vec3d(co*ca, so*ca, sa) * Rg; - vec3d px = vec3d(-so, co, 0); - vec3d py = vec3d(-co*sa, -so*sa, ca); - vec3d pz = vec3d(co*ca, so*ca, sa); +void updateView() { + double co = cos(lon); + double so = sin(lon); + double ca = cos(lat); + double sa = sin(lat); + vec3d po = vec3d(co * ca, so * ca, sa) * Rg; + vec3d px = vec3d(-so, co, 0); + vec3d py = vec3d(-co * sa, -so * sa, ca); + vec3d pz = vec3d(co * ca, so * ca, sa); double ct = cos(theta); double st = sin(theta); double cp = cos(phi); double sp = sin(phi); vec3d cx = px * cp + py * sp; - vec3d cy = -px * sp*ct + py * cp*ct + pz * st; - vec3d cz = px * sp*st - py * cp*st + pz * ct; + vec3d cy = -px * sp * ct + py * cp * ct + pz * st; + vec3d cz = px * sp * st - py * cp * st + pz * ct; position = po + cz * d; if (position.length() < Rg + 0.01) { - position.normalize(Rg + 0.01); + position.normalize(Rg + 0.01); } - view = mat4d(cx.x, cx.y, cx.z, 0, - cy.x, cy.y, cy.z, 0, - cz.x, cz.y, cz.z, 0, - 0, 0, 0, 1); + view = mat4d(cx.x, cx.y, cx.z, 0, cy.x, cy.y, cy.z, 0, cz.x, cz.y, cz.z, 0, 0, 0, 0, 1); view = view * mat4d::translate(-position); } -void redisplayFunc() -{ +void redisplayFunc() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); float h = position.length() - Rg; @@ -592,10 +578,9 @@ void redisplayFunc() mat4d iview = view.inverse(); vec3d c = iview * vec3d(0.0, 0.0, 0.0); - mat4f iviewf = mat4f(iview[0][0], iview[0][1], iview[0][2], iview[0][3], - iview[1][0], iview[1][1], iview[1][2], iview[1][3], - iview[2][0], iview[2][1], iview[2][2], iview[2][3], - iview[3][0], iview[3][1], iview[3][2], iview[3][3]); + mat4f iviewf = + mat4f(iview[0][0], iview[0][1], iview[0][2], iview[0][3], iview[1][0], iview[1][1], iview[1][2], iview[1][3], + iview[2][0], iview[2][1], iview[2][2], iview[2][3], iview[3][0], iview[3][1], iview[3][2], iview[3][3]); glUniform3f(glGetUniformLocation(drawProg, "c"), c.x, c.y, c.z); glUniform3f(glGetUniformLocation(drawProg, "s"), s.x, s.y, s.z); @@ -611,92 +596,86 @@ void redisplayFunc() // USER INTERFACE // ---------------------------------------------------------------------------- -void reshapeFunc(int x, int y) -{ +void reshapeFunc(int x, int y) { width = x; height = y; glViewport(0, 0, x, y); glutPostRedisplay(); } -void mouseClickFunc(int button, int state, int x, int y) -{ +void mouseClickFunc(int button, int state, int x, int y) { oldx = x; oldy = y; int modifiers = glutGetModifiers(); bool ctrl = (modifiers & GLUT_ACTIVE_CTRL) != 0; bool shift = (modifiers & GLUT_ACTIVE_SHIFT) != 0; if (ctrl) { - move = 0; + move = 0; } else if (shift) { move = 1; } else { - move = 2; + move = 2; } } -void mouseMotionFunc(int x, int y) -{ +void mouseMotionFunc(int x, int y) { if (move == 0) { - phi += (oldx - x) / 500.0; - theta += (oldy - y) / 500.0; + phi += (oldx - x) / 500.0; + theta += (oldy - y) / 500.0; theta = max(0.0, min(M_PI, theta)); updateView(); oldx = x; oldy = y; } else if (move == 1) { - double factor = position.length() - Rg; - factor = factor / Rg; - lon += (oldx - x) / 400.0 * factor; - lat -= (oldy - y) / 400.0 * factor; + double factor = position.length() - Rg; + factor = factor / Rg; + lon += (oldx - x) / 400.0 * factor; + lat -= (oldy - y) / 400.0 * factor; lat = max(-M_PI / 2.0, min(M_PI / 2.0, lat)); updateView(); oldx = x; oldy = y; } else if (move == 2) { - float vangle = asin(s.z); - float hangle = atan2(s.y, s.x); - vangle += (oldy - y) / 180.0 * M_PI / 4; - hangle += (oldx - x) / 180.0 * M_PI / 4; - s.x = cos(vangle) * cos(hangle); - s.y = cos(vangle) * sin(hangle); - s.z = sin(vangle); + float vangle = asin(s.z); + float hangle = atan2(s.y, s.x); + vangle += (oldy - y) / 180.0 * M_PI / 4; + hangle += (oldx - x) / 180.0 * M_PI / 4; + s.x = cos(vangle) * cos(hangle); + s.y = cos(vangle) * sin(hangle); + s.z = sin(vangle); oldx = x; oldy = y; } } -void specialKeyFunc(int c, int x, int y) -{ +void specialKeyFunc(int c, int x, int y) { switch (c) { case GLUT_KEY_PAGE_UP: - d = d * 1.05; + d = d * 1.05; updateView(); break; case GLUT_KEY_PAGE_DOWN: - d = d / 1.05; + d = d / 1.05; updateView(); break; case GLUT_KEY_F5: - recompute(); + recompute(); glViewport(0, 0, width, height); break; } } -void keyboardFunc(unsigned char c, int x, int y) -{ +void keyboardFunc(unsigned char c, int x, int y) { if (c == 27) { ::exit(0); } else if (c == '+') { - exposure *= 1.1; - } else if (c == '-') { - exposure /= 1.1; - } + exposure *= 1.1; + } else if (c == '-') { + exposure /= 1.1; + } } -void idleFunc() -{ +void idleFunc() { glutPostRedisplay(); } @@ -705,11 +684,10 @@ void idleFunc() #include "Color.h" #include "Logs.h" #include "PackStream.h" -void dumpTextures() -{ +void dumpTextures() { PackStream stream; int x, y, z, w; - float* texdata; + float *texdata; /* Dump irradiance */ Texture2D irradiance(SKY_W, SKY_H); @@ -719,11 +697,9 @@ void dumpTextures() glBindTexture(GL_TEXTURE_2D, irradianceTexture); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_FLOAT, texdata); - for (x = 0; x < SKY_W; x++) - { - for (y = 0; y < SKY_H; y++) - { - float* pixel = texdata + (y * SKY_W + x) * 3; + for (x = 0; x < SKY_W; x++) { + for (y = 0; y < SKY_H; y++) { + float *pixel = texdata + (y * SKY_W + x) * 3; irradiance.setPixel(x, y, Color(pixel[0], pixel[1], pixel[2], 1.0)); } } @@ -742,11 +718,9 @@ void dumpTextures() glBindTexture(GL_TEXTURE_2D, transmittanceTexture); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_FLOAT, texdata); - for (x = 0; x < TRANSMITTANCE_W; x++) - { - for (y = 0; y < TRANSMITTANCE_H; y++) - { - float* pixel = texdata + (y * TRANSMITTANCE_W + x) * 3; + for (x = 0; x < TRANSMITTANCE_W; x++) { + for (y = 0; y < TRANSMITTANCE_H; y++) { + float *pixel = texdata + (y * TRANSMITTANCE_W + x) * 3; transmittance.setPixel(x, y, Color(pixel[0], pixel[1], pixel[2], 1.0)); } } @@ -759,22 +733,19 @@ void dumpTextures() /* Dump inscatter */ Texture4D inscatter(RES_MU, RES_MU_S, RES_NU, RES_R); - //Texture3D inscatter(RES_MU_S * RES_NU, RES_MU, RES_R); + // Texture3D inscatter(RES_MU_S * RES_NU, RES_MU, RES_R); texdata = new float[RES_MU * RES_MU_S * RES_NU * RES_R * 4 * sizeof(float)]; glBindTexture(GL_TEXTURE_3D, inscatterTexture); glGetTexImage(GL_TEXTURE_3D, 0, GL_RGBA, GL_FLOAT, texdata); - for (x = 0; x < RES_MU; x++) - { - for (y = 0; y < RES_MU_S; y++) - { - for (z = 0; z < RES_NU; z++) - { - for (w = 0; w < RES_R; w++) - { - float* pixel = texdata + (w * (RES_MU * RES_MU_S * RES_NU) + z * (RES_MU_S) + y + x * (RES_MU_S * RES_NU)) * 4; + for (x = 0; x < RES_MU; x++) { + for (y = 0; y < RES_MU_S; y++) { + for (z = 0; z < RES_NU; z++) { + for (w = 0; w < RES_R; w++) { + float *pixel = + texdata + (w * (RES_MU * RES_MU_S * RES_NU) + z * (RES_MU_S) + y + x * (RES_MU_S * RES_NU)) * 4; inscatter.setPixel(x, y, z, w, Color(pixel[0], pixel[1], pixel[2], pixel[3])); } } @@ -789,15 +760,13 @@ void dumpTextures() /* Check errors */ int error_code; - while ((error_code = glGetError()) != GL_NO_ERROR) - { - logWarning("[OpenGL] ERROR : %s", (const char*)gluErrorString(error_code)); + while ((error_code = glGetError()) != GL_NO_ERROR) { + logWarning("[OpenGL] ERROR : %s", (const char *)gluErrorString(error_code)); } } -int main(int argc, char* argv[]) -{ - glutInit(&argc, argv); +int main(int argc, char *argv[]) { + glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(1024, 768); glutCreateWindow("Precomputed Atmospheric Scattering"); diff --git a/src/experiments/bruneton/mat4.h b/src/experiments/bruneton/mat4.h index 0e3e89f..b5476ce 100644 --- a/src/experiments/bruneton/mat4.h +++ b/src/experiments/bruneton/mat4.h @@ -40,15 +40,14 @@ /** * A 4x4 matrix. */ -template class mat4 -{ -protected: +template class mat4 { + protected: union { type m[4][4]; type _m[16]; }; -public: + public: /** * Creates a new, uninitialized matrix. */ @@ -58,52 +57,50 @@ public: * Creates a new matrix with the given components. The first index is the * row index, the second one is the column index. */ - mat4(type m00, type m01, type m02, type m03, - type m10, type m11, type m12, type m13, - type m20, type m21, type m22, type m23, - type m30, type m31, type m32, type m33); + mat4(type m00, type m01, type m02, type m03, type m10, type m11, type m12, type m13, type m20, type m21, type m22, + type m23, type m30, type m31, type m32, type m33); /** * Returns the coefficients of this matrix. */ - const type* coefficients() const; + const type *coefficients() const; /** * Returns the row of this matrix whose index is given. */ - const type* operator[](int iRow) const; + const type *operator[](int iRow) const; /** * Returns true is this matrix is equal to the given matrix. */ - bool operator==(const mat4& m2) const; + bool operator==(const mat4 &m2) const; /** * Returns true is this matrix is different from the given matrix. */ - bool operator!=(const mat4& m2) const; + bool operator!=(const mat4 &m2) const; /** * Returns the sum of this matrix and of the given matrix. */ - mat4 operator+(const mat4& m2) const; + mat4 operator+(const mat4 &m2) const; /** * Returns the difference of this matrix and of the given matrix. */ - mat4 operator-(const mat4& m2) const; + mat4 operator-(const mat4 &m2) const; /** * Returns the product of this matrix and of the given matrix. */ - mat4 operator*(const mat4& m2) const; + mat4 operator*(const mat4 &m2) const; /** * Returns the product of this matrix and of the given vector. The given * vector w coordinate is set to 1, and the 4 vector result is converted * to a 3 vector by dividing its xyz components by its w component. */ - vec3 operator*(const vec3& v) const; + vec3 operator*(const vec3 &v) const; /** * Returns the product of this matrix and of the given scalar. @@ -134,7 +131,7 @@ public: * Returns the translation matrix corresponding to the given translation * vector. */ - static mat4 translate(const vec3& v); + static mat4 translate(const vec3 &v); /** * Returns the perspective projection matrix corresponding to the given @@ -158,17 +155,12 @@ typedef mat4 mat4f; */ typedef mat4 mat4d; -template -inline mat4::mat4() -{ +template inline mat4::mat4() { } template -inline mat4::mat4(type m00, type m01, type m02, type m03, - type m10, type m11, type m12, type m13, - type m20, type m21, type m22, type m23, - type m30, type m31, type m32, type m33) -{ +inline mat4::mat4(type m00, type m01, type m02, type m03, type m10, type m11, type m12, type m13, type m20, + type m21, type m22, type m23, type m30, type m31, type m32, type m33) { m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; @@ -187,24 +179,17 @@ inline mat4::mat4(type m00, type m01, type m02, type m03, m[3][3] = m33; } -template -inline const type* mat4::coefficients() const -{ +template inline const type *mat4::coefficients() const { return _m; } -template -inline const type* mat4::operator[](int iRow) const -{ - //assert(iRow < 4); +template inline const type *mat4::operator[](int iRow) const { + // assert(iRow < 4); return m[iRow]; } -template -inline bool mat4::operator==(const mat4& m2) const -{ - if ( - m[0][0] != m2.m[0][0] || m[0][1] != m2.m[0][1] || m[0][2] != m2.m[0][2] || m[0][3] != m2.m[0][3] || +template inline bool mat4::operator==(const mat4 &m2) const { + if (m[0][0] != m2.m[0][0] || m[0][1] != m2.m[0][1] || m[0][2] != m2.m[0][2] || m[0][3] != m2.m[0][3] || m[1][0] != m2.m[1][0] || m[1][1] != m2.m[1][1] || m[1][2] != m2.m[1][2] || m[1][3] != m2.m[1][3] || m[2][0] != m2.m[2][0] || m[2][1] != m2.m[2][1] || m[2][2] != m2.m[2][2] || m[2][3] != m2.m[2][3] || m[3][0] != m2.m[3][0] || m[3][1] != m2.m[3][1] || m[3][2] != m2.m[3][2] || m[3][3] != m2.m[3][3]) @@ -213,11 +198,8 @@ inline bool mat4::operator==(const mat4& m2) const return true; } -template -inline bool mat4::operator!=(const mat4& m2) const -{ - if ( - m[0][0] != m2.m[0][0] || m[0][1] != m2.m[0][1] || m[0][2] != m2.m[0][2] || m[0][3] != m2.m[0][3] || +template inline bool mat4::operator!=(const mat4 &m2) const { + if (m[0][0] != m2.m[0][0] || m[0][1] != m2.m[0][1] || m[0][2] != m2.m[0][2] || m[0][3] != m2.m[0][3] || m[1][0] != m2.m[1][0] || m[1][1] != m2.m[1][1] || m[1][2] != m2.m[1][2] || m[1][3] != m2.m[1][3] || m[2][0] != m2.m[2][0] || m[2][1] != m2.m[2][1] || m[2][2] != m2.m[2][2] || m[2][3] != m2.m[2][3] || m[3][0] != m2.m[3][0] || m[3][1] != m2.m[3][1] || m[3][2] != m2.m[3][2] || m[3][3] != m2.m[3][3]) @@ -226,9 +208,7 @@ inline bool mat4::operator!=(const mat4& m2) const return false; } -template -inline mat4 mat4::operator+(const mat4& m2) const -{ +template inline mat4 mat4::operator+(const mat4 &m2) const { mat4 r; r.m[0][0] = m[0][0] + m2.m[0][0]; @@ -254,9 +234,7 @@ inline mat4 mat4::operator+(const mat4& m2) const return r; } -template -inline mat4 mat4::operator-(const mat4& m2) const -{ +template inline mat4 mat4::operator-(const mat4 &m2) const { mat4 r; r.m[0][0] = m[0][0] - m2.m[0][0]; r.m[0][1] = m[0][1] - m2.m[0][1]; @@ -281,9 +259,7 @@ inline mat4 mat4::operator-(const mat4& m2) const return r; } -template -inline mat4 mat4::operator*(const mat4& m2) const -{ +template inline mat4 mat4::operator*(const mat4 &m2) const { mat4 r; r.m[0][0] = m[0][0] * m2.m[0][0] + m[0][1] * m2.m[1][0] + m[0][2] * m2.m[2][0] + m[0][3] * m2.m[3][0]; r.m[0][1] = m[0][0] * m2.m[0][1] + m[0][1] * m2.m[1][1] + m[0][2] * m2.m[2][1] + m[0][3] * m2.m[3][1]; @@ -308,9 +284,7 @@ inline mat4 mat4::operator*(const mat4& m2) const return r; } -template -inline vec3 mat4::operator*(const vec3& v) const -{ +template inline vec3 mat4::operator*(const vec3 &v) const { vec3 r; float fInvW = 1.0 / (m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3]); @@ -322,9 +296,7 @@ inline vec3 mat4::operator*(const vec3& v) const return r; } -template -inline mat4 mat4::operator*(type f) const -{ +template inline mat4 mat4::operator*(type f) const { mat4 r; r.m[0][0] = m[0][0] * f; @@ -350,80 +322,50 @@ inline mat4 mat4::operator*(type f) const return r; } -template -inline mat4 mat4::transpose(void) const -{ - return mat4(m[0][0], m[1][0], m[2][0], m[3][0], - m[0][1], m[1][1], m[2][1], m[3][1], - m[0][2], m[1][2], m[2][2], m[3][2], - m[0][3], m[1][3], m[2][3], m[3][3]); +template inline mat4 mat4::transpose(void) const { + return mat4(m[0][0], m[1][0], m[2][0], m[3][0], m[0][1], m[1][1], m[2][1], m[3][1], m[0][2], m[1][2], m[2][2], + m[3][2], m[0][3], m[1][3], m[2][3], m[3][3]); } template -inline static float -MINOR(const mat4& m, int r0, int r1, int r2, int c0, int c1, int c2) -{ - return m[r0][c0] *(m[r1][c1] * m[r2][c2] - m[r2][c1] * m[r1][c2]) - - m[r0][c1] *(m[r1][c0] * m[r2][c2] - m[r2][c0] * m[r1][c2]) + - m[r0][c2] *(m[r1][c0] * m[r2][c1] - m[r2][c0] * m[r1][c1]); +inline static float MINOR(const mat4 &m, int r0, int r1, int r2, int c0, int c1, int c2) { + return m[r0][c0] * (m[r1][c1] * m[r2][c2] - m[r2][c1] * m[r1][c2]) - + m[r0][c1] * (m[r1][c0] * m[r2][c2] - m[r2][c0] * m[r1][c2]) + + m[r0][c2] * (m[r1][c0] * m[r2][c1] - m[r2][c0] * m[r1][c1]); } -template -mat4 mat4::adjoint() const -{ - return mat4(MINOR(*this, 1, 2, 3, 1, 2, 3), - -MINOR(*this, 0, 2, 3, 1, 2, 3), - MINOR(*this, 0, 1, 3, 1, 2, 3), +template mat4 mat4::adjoint() const { + return mat4(MINOR(*this, 1, 2, 3, 1, 2, 3), -MINOR(*this, 0, 2, 3, 1, 2, 3), MINOR(*this, 0, 1, 3, 1, 2, 3), -MINOR(*this, 0, 1, 2, 1, 2, 3), - -MINOR(*this, 1, 2, 3, 0, 2, 3), - MINOR(*this, 0, 2, 3, 0, 2, 3), - -MINOR(*this, 0, 1, 3, 0, 2, 3), + -MINOR(*this, 1, 2, 3, 0, 2, 3), MINOR(*this, 0, 2, 3, 0, 2, 3), -MINOR(*this, 0, 1, 3, 0, 2, 3), MINOR(*this, 0, 1, 2, 0, 2, 3), - MINOR(*this, 1, 2, 3, 0, 1, 3), - -MINOR(*this, 0, 2, 3, 0, 1, 3), - MINOR(*this, 0, 1, 3, 0, 1, 3), + MINOR(*this, 1, 2, 3, 0, 1, 3), -MINOR(*this, 0, 2, 3, 0, 1, 3), MINOR(*this, 0, 1, 3, 0, 1, 3), -MINOR(*this, 0, 1, 2, 0, 1, 3), - -MINOR(*this, 1, 2, 3, 0, 1, 2), - MINOR(*this, 0, 2, 3, 0, 1, 2), - -MINOR(*this, 0, 1, 3, 0, 1, 2), + -MINOR(*this, 1, 2, 3, 0, 1, 2), MINOR(*this, 0, 2, 3, 0, 1, 2), -MINOR(*this, 0, 1, 3, 0, 1, 2), MINOR(*this, 0, 1, 2, 0, 1, 2)); } -template -mat4 mat4::inverse() const -{ +template mat4 mat4::inverse() const { return adjoint() * (1.0f / determinant()); } -template -float mat4::determinant() const -{ - return m[0][0] * MINOR(*this, 1, 2, 3, 1, 2, 3) - - m[0][1] * MINOR(*this, 1, 2, 3, 0, 2, 3) + - m[0][2] * MINOR(*this, 1, 2, 3, 0, 1, 3) - - m[0][3] * MINOR(*this, 1, 2, 3, 0, 1, 2); +template float mat4::determinant() const { + return m[0][0] * MINOR(*this, 1, 2, 3, 1, 2, 3) - m[0][1] * MINOR(*this, 1, 2, 3, 0, 2, 3) + + m[0][2] * MINOR(*this, 1, 2, 3, 0, 1, 3) - m[0][3] * MINOR(*this, 1, 2, 3, 0, 1, 2); +} + +template inline mat4 mat4::translate(const vec3 &v) { + return mat4(1, 0, 0, v.x, 0, 1, 0, v.y, 0, 0, 1, v.z, 0, 0, 0, 1); } template -inline mat4 mat4::translate(const vec3 &v) -{ - return mat4(1, 0, 0, v.x, - 0, 1, 0, v.y, - 0, 0, 1, v.z, - 0, 0, 0, 1); -} - -template -inline mat4 mat4::perspectiveProjection(type fovy, type aspect, type zNear, type zFar) -{ - type f = (type) 1 / tan(fovy * M_PI / 180.0 / 2); - return mat4(f / aspect, 0, 0, 0, - 0, f, 0, 0, - 0, 0, (zFar + zNear) / (zNear - zFar), (2*zFar*zNear) / (zNear - zFar), - 0, 0, -1, 0); +inline mat4 mat4::perspectiveProjection(type fovy, type aspect, type zNear, type zFar) { + type f = (type)1 / tan(fovy * M_PI / 180.0 / 2); + return mat4(f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (zFar + zNear) / (zNear - zFar), + (2 * zFar * zNear) / (zNear - zFar), 0, 0, -1, 0); } #endif /*MAT4_H_*/ diff --git a/src/experiments/bruneton/vec3.h b/src/experiments/bruneton/vec3.h index 01d4f48..2235820 100644 --- a/src/experiments/bruneton/vec3.h +++ b/src/experiments/bruneton/vec3.h @@ -36,9 +36,8 @@ /** * A 3D vector. */ -template class vec3 -{ -public: +template class vec3 { + public: type x, y, z; /** @@ -59,7 +58,7 @@ public: /** * Creates a new vector as a copy of the given vector. */ - vec3(const vec3& v); + vec3(const vec3 &v); /** * Returns the coordinate of this vector whose index is given. @@ -69,38 +68,38 @@ public: /** * Returns the coordinate of this vector whose index is given. */ - type& operator[](const int i); + type &operator[](const int i); /** * Assigns the given vector to this vector. */ - void operator=(const vec3& v); + void operator=(const vec3 &v); /** * Returns true if this vector is equal to the given vector. */ - bool operator==(const vec3& v) const; + bool operator==(const vec3 &v) const; /** * Returns true if this vector is different from the given vector. */ - bool operator!=(const vec3& v) const; + bool operator!=(const vec3 &v) const; /** * Returns the sum of this vector and of the given vector. */ - vec3 operator+(const vec3& v) const; + vec3 operator+(const vec3 &v) const; /** * Returns the difference of this vector and of the given vector. */ - vec3 operator-(const vec3& v) const; + vec3 operator-(const vec3 &v) const; /** * Returns the product of this vector and of the given vector. The * product is done component by component. */ - vec3 operator*(const vec3& v) const; + vec3 operator*(const vec3 &v) const; /** * Returns the product of this vector and of the given scalar. @@ -111,7 +110,7 @@ public: * Returns the division of this vector and of the given vector. The * division is done component by component. */ - vec3 operator/(const vec3& v) const; + vec3 operator/(const vec3 &v) const; /** * Returns the division of this vector and of the given scalar. @@ -126,22 +125,22 @@ public: /** * Adds the given vector to this vector. */ - vec3& operator+=(const vec3& v); + vec3 &operator+=(const vec3 &v); /** * Substracts the given vector from this vector. */ - vec3& operator-=(const vec3& v); + vec3 &operator-=(const vec3 &v); /** * Multiplies this vector by the given scalar. */ - vec3& operator*=(const type& scalar); + vec3 &operator*=(const type &scalar); /** * Divides this vector by the given scalar. */ - vec3& operator/=(const type& scalar); + vec3 &operator/=(const type &scalar); /** * Returns the length of this vector. @@ -156,7 +155,7 @@ public: /** * Returns the dot product of this vector and of the given vector. */ - type dotproduct(const vec3& v) const; + type dotproduct(const vec3 &v) const; /** * Normalizes this vector and returns its initial length. @@ -171,7 +170,7 @@ public: /** * Returns he cross product of this vector and of the given vector. */ - vec3 crossProduct(const vec3& v) const; + vec3 crossProduct(const vec3 &v) const; /** * The null vector (0,0,0). @@ -209,134 +208,94 @@ typedef vec3 vec3d; */ typedef vec3 vec3i; -template -inline vec3::vec3() -{ +template inline vec3::vec3() { } -template -inline vec3::vec3(type xi, type yi, type zi) : x(xi), y(yi), z(zi) -{ +template inline vec3::vec3(type xi, type yi, type zi) : x(xi), y(yi), z(zi) { } -template -inline vec3::vec3(const type v[3]) : x(v[0]), y(v[1]), z(v[2]) -{ +template inline vec3::vec3(const type v[3]) : x(v[0]), y(v[1]), z(v[2]) { } -template -inline vec3::vec3(const vec3& v) : x(v.x), y(v.y), z(v.z) -{ +template inline vec3::vec3(const vec3 &v) : x(v.x), y(v.y), z(v.z) { } -template -inline type vec3::operator[](const int i) const -{ - //assert(i<3); +template inline type vec3::operator[](const int i) const { + // assert(i<3); return *(&x + i); } -template -inline type& vec3::operator[](const int i) -{ - //assert(i<3); +template inline type &vec3::operator[](const int i) { + // assert(i<3); return *(&x + i); } -template -inline void vec3::operator=(const vec3& v) -{ +template inline void vec3::operator=(const vec3 &v) { x = v.x; y = v.y; z = v.z; } -template -inline bool vec3::operator==(const vec3& v) const -{ +template inline bool vec3::operator==(const vec3 &v) const { return (x == v.x && y == v.y && z == v.z); } -template -inline bool vec3::operator!=(const vec3& v) const -{ +template inline bool vec3::operator!=(const vec3 &v) const { return (x != v.x || y != v.y || z != v.z); } -template -inline vec3 vec3::operator+(const vec3& v) const -{ +template inline vec3 vec3::operator+(const vec3 &v) const { return vec3(x + v.x, y + v.y, z + v.z); } -template -inline vec3 vec3::operator-(const vec3& v) const -{ +template inline vec3 vec3::operator-(const vec3 &v) const { return vec3(x - v.x, y - v.y, z - v.z); } -template -inline vec3 vec3::operator*(const vec3& v) const -{ +template inline vec3 vec3::operator*(const vec3 &v) const { return vec3(x * v.x, y * v.y, z * v.z); } -template -inline vec3 vec3::operator*(const type scalar) const -{ +template inline vec3 vec3::operator*(const type scalar) const { return vec3(x * scalar, y * scalar, z * scalar); } -template -inline vec3 vec3::operator/(const vec3& v) const -{ +template inline vec3 vec3::operator/(const vec3 &v) const { return vec3(x / v.x, y / v.y, z / v.z); } -template -inline vec3 vec3::operator/(const type scalar) const -{ +template inline vec3 vec3::operator/(const type scalar) const { assert(scalar != 0); type inv = 1 / scalar; return vec3(x * inv, y * inv, z * inv); } -template -inline vec3 vec3::operator-() const -{ +template inline vec3 vec3::operator-() const { return vec3(-x, -y, -z); } -template -inline vec3& vec3::operator+=(const vec3& v) -{ +template inline vec3 &vec3::operator+=(const vec3 &v) { x += v.x; y += v.y; z += v.z; return *this; } -template -inline vec3& vec3::operator-=(const vec3& v) -{ +template inline vec3 &vec3::operator-=(const vec3 &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } -template -inline vec3& vec3::operator*=(const type& scalar) -{ +template inline vec3 &vec3::operator*=(const type &scalar) { x *= scalar; y *= scalar; z *= scalar; return *this; } -template -inline vec3& vec3::operator/=(const type& scalar) -{ +template inline vec3 &vec3::operator/=(const type &scalar) { assert(scalar != 0); type inv = 1 / scalar; x *= inv; @@ -345,27 +304,19 @@ inline vec3& vec3::operator/=(const type& scalar) return *this; } -template -inline type vec3::length() const -{ - return sqrt(x*x + y*y + z*z); +template inline type vec3::length() const { + return sqrt(x * x + y * y + z * z); } -template -inline type vec3::squaredlength() const -{ - return (x*x + y*y + z*z); +template inline type vec3::squaredlength() const { + return (x * x + y * y + z * z); } -template -inline type vec3::dotproduct(const vec3& v) const -{ - return (x*v.x + y*v.y + z*v.z); +template inline type vec3::dotproduct(const vec3 &v) const { + return (x * v.x + y * v.y + z * v.z); } -template -inline type vec3::normalize() -{ +template inline type vec3::normalize() { type length = sqrt(x * x + y * y + z * z); type invLength = 1.0 / length; x *= invLength; @@ -374,9 +325,7 @@ inline type vec3::normalize() return length; } -template -inline type vec3::normalize(type l) -{ +template inline type vec3::normalize(type l) { type length = sqrt(x * x + y * y + z * z); type invLength = l / length; x *= invLength; @@ -385,22 +334,16 @@ inline type vec3::normalize(type l) return length; } -template -inline vec3 vec3::crossProduct(const vec3& v) const -{ - return vec3(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x); +template inline vec3 vec3::crossProduct(const vec3 &v) const { + return vec3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); } -template -const vec3 vec3::ZERO(0, 0, 0); +template const vec3 vec3::ZERO(0, 0, 0); -template -const vec3 vec3::UNIT_X(1, 0, 0); +template const vec3 vec3::UNIT_X(1, 0, 0); -template -const vec3 vec3::UNIT_Y(0, 1, 0); +template const vec3 vec3::UNIT_Y(0, 1, 0); -template -const vec3 vec3::UNIT_Z(0, 0, 1); +template const vec3 vec3::UNIT_Z(0, 0, 1); #endif /*VEC3_H_*/ diff --git a/src/interface/commandline/main.cpp b/src/interface/commandline/main.cpp index e87b2ad..9d3cba3 100644 --- a/src/interface/commandline/main.cpp +++ b/src/interface/commandline/main.cpp @@ -10,8 +10,7 @@ void startRender(SoftwareCanvasRenderer *renderer, const char *outputpath); void runTestSuite(); -static void displayHelp() -{ +static void displayHelp() { printf("Usage : paysages-cli [options]\n"); printf("Options :\n"); printf(" -h Show this help\n"); @@ -31,10 +30,9 @@ static void displayHelp() printf(" -cz z Camera Z step (double)\n"); } -int main(int argc, char** argv) -{ - SoftwareCanvasRenderer* renderer; - char* conf_file_path = NULL; +int main(int argc, char **argv) { + SoftwareCanvasRenderer *renderer; + char *conf_file_path = NULL; RenderConfig conf_render_params(480, 270, 1, 3); int conf_first_picture = 0; int conf_nb_pictures = 1; @@ -51,113 +49,67 @@ int main(int argc, char** argv) argc--; argv++; - while (argc--) - { - if (strcmp(*argv, "-h") == 0 || strcmp(*argv, "--help") == 0) - { + while (argc--) { + if (strcmp(*argv, "-h") == 0 || strcmp(*argv, "--help") == 0) { displayHelp(); return 0; - } - else if (strcmp(*argv, "-ts") == 0 || strcmp(*argv, "--testsuite") == 0) - { + } else if (strcmp(*argv, "-ts") == 0 || strcmp(*argv, "--testsuite") == 0) { runTestSuite(); return 0; - } - else if (strcmp(*argv, "-f") == 0 || strcmp(*argv, "--file") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-f") == 0 || strcmp(*argv, "--file") == 0) { + if (argc--) { conf_file_path = *(++argv); } - } - else if (strcmp(*argv, "-s") == 0 || strcmp(*argv, "--start") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-s") == 0 || strcmp(*argv, "--start") == 0) { + if (argc--) { conf_first_picture = atoi(*(++argv)); } - } - else if (strcmp(*argv, "-n") == 0 || strcmp(*argv, "--count") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-n") == 0 || strcmp(*argv, "--count") == 0) { + if (argc--) { conf_nb_pictures = atoi(*(++argv)); } - } - else if (strcmp(*argv, "-rw") == 0 || strcmp(*argv, "--width") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-rw") == 0 || strcmp(*argv, "--width") == 0) { + if (argc--) { conf_render_params.width = atoi(*(++argv)); } - } - else if (strcmp(*argv, "-rh") == 0 || strcmp(*argv, "--height") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-rh") == 0 || strcmp(*argv, "--height") == 0) { + if (argc--) { conf_render_params.height = atoi(*(++argv)); } - } - else if (strcmp(*argv, "-rq") == 0 || strcmp(*argv, "--quality") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-rq") == 0 || strcmp(*argv, "--quality") == 0) { + if (argc--) { conf_render_params.quality = atoi(*(++argv)); } - } - else if (strcmp(*argv, "-ra") == 0 || strcmp(*argv, "--antialias") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-ra") == 0 || strcmp(*argv, "--antialias") == 0) { + if (argc--) { conf_render_params.antialias = atoi(*(++argv)); } - } - else if (strcmp(*argv, "-wx") == 0 || strcmp(*argv, "--windx") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-wx") == 0 || strcmp(*argv, "--windx") == 0) { + if (argc--) { conf_wind_x = atof(*(++argv)); } - } - else if (strcmp(*argv, "-wz") == 0 || strcmp(*argv, "--windz") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-wz") == 0 || strcmp(*argv, "--windz") == 0) { + if (argc--) { conf_wind_z = atof(*(++argv)); } - } - else if (strcmp(*argv, "-di") == 0 || strcmp(*argv, "--daystart") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-di") == 0 || strcmp(*argv, "--daystart") == 0) { + if (argc--) { conf_daytime_start = atof(*(++argv)); } - } - else if (strcmp(*argv, "-ds") == 0 || strcmp(*argv, "--daystep") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-ds") == 0 || strcmp(*argv, "--daystep") == 0) { + if (argc--) { conf_daytime_step = atof(*(++argv)); } - } - else if (strcmp(*argv, "-cx") == 0 || strcmp(*argv, "--camerastepx") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-cx") == 0 || strcmp(*argv, "--camerastepx") == 0) { + if (argc--) { conf_camera_step_x = atof(*(++argv)); } - } - else if (strcmp(*argv, "-cy") == 0 || strcmp(*argv, "--camerastepy") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-cy") == 0 || strcmp(*argv, "--camerastepy") == 0) { + if (argc--) { conf_camera_step_y = atof(*(++argv)); } - } - else if (strcmp(*argv, "-cz") == 0 || strcmp(*argv, "--camerastepz") == 0) - { - if (argc--) - { + } else if (strcmp(*argv, "-cz") == 0 || strcmp(*argv, "--camerastepz") == 0) { + if (argc--) { conf_camera_step_z = atof(*(++argv)); } } @@ -166,35 +118,29 @@ int main(int argc, char** argv) } printf("Initializing ...\n"); - Scenery* scenery = new Scenery(); + Scenery *scenery = new Scenery(); - if (conf_file_path) - { + if (conf_file_path) { scenery->loadGlobal(conf_file_path); - } - else - { + } else { scenery->autoPreset(); } TimeManager time; time.setWind(conf_wind_x, conf_wind_z); - if (conf_daytime_start >= 0.0) - { + if (conf_daytime_start >= 0.0) { scenery->getAtmosphere()->setDayTime(conf_daytime_start); } - for (outputcount = 0; outputcount < conf_first_picture + conf_nb_pictures; outputcount++) - { - CameraDefinition* camera = scenery->getCamera(); + for (outputcount = 0; outputcount < conf_first_picture + conf_nb_pictures; outputcount++) { + CameraDefinition *camera = scenery->getCamera(); Vector3 step = {conf_camera_step_x, conf_camera_step_y, conf_camera_step_z}; camera->setLocation(camera->getLocation().add(step)); renderer = new SoftwareCanvasRenderer(scenery); renderer->setConfig(conf_render_params); - if (outputcount >= conf_first_picture) - { + if (outputcount >= conf_first_picture) { sprintf(outputpath, "pic%05d.png", outputcount); startRender(renderer, outputpath); } diff --git a/src/interface/commandline/render.cpp b/src/interface/commandline/render.cpp index 9a3bbee..ac54517 100644 --- a/src/interface/commandline/render.cpp +++ b/src/interface/commandline/render.cpp @@ -1,33 +1,28 @@ #include "Thread.h" #include "SoftwareCanvasRenderer.h" -class RenderThread: public Thread -{ -public: - RenderThread(SoftwareCanvasRenderer *renderer, const char *outputpath): - renderer(renderer), outputpath(outputpath) - { +class RenderThread : public Thread { + public: + RenderThread(SoftwareCanvasRenderer *renderer, const char *outputpath) + : renderer(renderer), outputpath(outputpath) { } - virtual void run() override - { + virtual void run() override { renderer->render(); } -private: + private: SoftwareCanvasRenderer *renderer; const char *outputpath; }; -void startRender(SoftwareCanvasRenderer *renderer, const char *outputpath) -{ +void startRender(SoftwareCanvasRenderer *renderer, const char *outputpath) { RenderThread thread(renderer, outputpath); printf("\rRendering %s ... \n", outputpath); thread.start(); - while (thread.isWorking()) - { + while (thread.isWorking()) { Thread::timeSleepMs(200); printf("\rProgress : %0.1f%% ", renderer->getProgress() * 100.0); @@ -39,4 +34,3 @@ void startRender(SoftwareCanvasRenderer *renderer, const char *outputpath) remove(outputpath); renderer->saveToDisk(outputpath); } - diff --git a/src/interface/commandline/tests.cpp b/src/interface/commandline/tests.cpp index eff1c13..beb8a06 100644 --- a/src/interface/commandline/tests.cpp +++ b/src/interface/commandline/tests.cpp @@ -22,13 +22,11 @@ void startRender(SoftwareCanvasRenderer *renderer, const char *outputpath); -static void startTestRender(SoftwareCanvasRenderer *renderer, const std::string &name, int iteration=-1) -{ +static void startTestRender(SoftwareCanvasRenderer *renderer, const std::string &name, int iteration = -1) { std::ostringstream stream; stream << "pic_test_" << name; - if (iteration >= 0) - { + if (iteration >= 0) { stream << "_"; stream.width(4); stream.fill('0'); @@ -39,8 +37,7 @@ static void startTestRender(SoftwareCanvasRenderer *renderer, const std::string startRender(renderer, stream.str().data()); } -static void testGroundShadowQuality() -{ +static void testGroundShadowQuality() { Scenery scenery; srand(5); scenery.getTerrain()->applyPreset(TerrainDefinition::TERRAIN_PRESET_STANDARD); @@ -70,31 +67,27 @@ static void testGroundShadowQuality() SoftwareCanvasRenderer renderer(&scenery); renderer.setSize(400, 300); renderer.setQuality(0.2); - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { // TODO keep same rasterization across renders renderer.getTerrainRenderer()->setQuality((double)i / 5.0); startTestRender(&renderer, "ground_shadow_quality", i); } } -static void testRasterizationQuality() -{ +static void testRasterizationQuality() { Scenery scenery; scenery.autoPreset(12); SoftwareCanvasRenderer renderer(&scenery); renderer.setSize(800, 600); renderer.enablePostprocess(false); - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { renderer.setQuality((double)i / 5.0); startTestRender(&renderer, "rasterization_quality", i); } } -static void testCloudQuality() -{ +static void testCloudQuality() { Scenery scenery; scenery.autoPreset(3); scenery.getCamera()->setLocation(Vector3(5.0, 5.0, 5.0)); @@ -106,38 +99,31 @@ static void testCloudQuality() renderer.setSize(600, 800); SkyRasterizer *rasterizer = new SkyRasterizer(&renderer, renderer.getProgressHelper(), 0); renderer.setSoloRasterizer(rasterizer); - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { renderer.setQuality((double)i / 5.0); rasterizer->setQuality(0.2); startTestRender(&renderer, "cloud_quality", i); } } -static void testGodRays() -{ - class TestLightFilter: public LightFilter - { - virtual bool applyLightFilter(LightComponent &light, const Vector3 &at) override - { - if (Vector3(0.0, 100.0, 0.0).sub(at).normalize().y > 0.97) - { +static void testGodRays() { + class TestLightFilter : public LightFilter { + virtual bool applyLightFilter(LightComponent &light, const Vector3 &at) override { + if (Vector3(0.0, 100.0, 0.0).sub(at).normalize().y > 0.97) { light.color = COLOR_BLACK; return false; - } - else - { + } else { return true; } } }; - class TestRenderer: public SoftwareCanvasRenderer - { - public: - TestRenderer(Scenery *scenery): SoftwareCanvasRenderer(scenery) {} - private: - virtual void prepare() override - { + class TestRenderer : public SoftwareCanvasRenderer { + public: + TestRenderer(Scenery *scenery) : SoftwareCanvasRenderer(scenery) { + } + + private: + virtual void prepare() override { SoftwareRenderer::prepare(); getLightingManager()->clearSources(); @@ -165,8 +151,7 @@ static void testGodRays() renderer.getLightingManager()->registerFilter(&filter); // quality - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { renderer.setQuality((double)i / 5.0); rasterizer->setQuality(0.2); startTestRender(&renderer, "god_rays_quality", i); @@ -174,31 +159,27 @@ static void testGodRays() renderer.setQuality(0.5); // penetration - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { scenery.getAtmosphere()->childGodRays()->propPenetration()->setValue(0.01 + 0.02 * (double)i); startTestRender(&renderer, "god_rays_penetration", i); } // resistance scenery.getAtmosphere()->childGodRays()->propPenetration()->setValue(0.01); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { scenery.getAtmosphere()->childGodRays()->propResistance()->setValue(0.1 + 0.1 * (double)i); startTestRender(&renderer, "god_rays_resistance", i); } // boost scenery.getAtmosphere()->childGodRays()->propResistance()->setValue(0.3); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { scenery.getAtmosphere()->childGodRays()->propBoost()->setValue(2.0 + 4.0 * (double)i); startTestRender(&renderer, "god_rays_boost", i); } } -static void testNearFrustum() -{ +static void testNearFrustum() { Scenery scenery; scenery.autoPreset(3); scenery.getCamera()->setLocation(Vector3(0.0, 0.0, 0.0)); @@ -213,8 +194,7 @@ static void testNearFrustum() startTestRender(&renderer, "near_frustum_bad"); } -static void testCloudsNearGround() -{ +static void testCloudsNearGround() { Scenery scenery; scenery.autoPreset(8); scenery.getAtmosphere()->setDayTime(6, 20); @@ -230,8 +210,7 @@ static void testCloudsNearGround() startTestRender(&renderer, "clouds_near_ground", 2); } -static void testSunNearHorizon() -{ +static void testSunNearHorizon() { Scenery scenery; scenery.autoPreset(28); scenery.getCamera()->setLocation(VECTOR_ZERO); @@ -244,15 +223,13 @@ static void testSunNearHorizon() renderer.setSize(400, 300); renderer.setQuality(0.3); - for (int i = 0; i <= 20; i++) - { + for (int i = 0; i <= 20; i++) { scenery.getAtmosphere()->propDayTime()->setValue(0.24 + 0.001 * (double)i); startTestRender(&renderer, "sun_near_horizon", i); } } -void runTestSuite() -{ +void runTestSuite() { testGroundShadowQuality(); testRasterizationQuality(); testCloudQuality(); diff --git a/src/interface/modeler/extension/extension_plugin.cpp b/src/interface/modeler/extension/extension_plugin.cpp index ded9382..b056ea7 100644 --- a/src/interface/modeler/extension/extension_plugin.cpp +++ b/src/interface/modeler/extension/extension_plugin.cpp @@ -3,10 +3,7 @@ #include -void ExtensionPlugin::registerTypes(const char *uri) -{ +void ExtensionPlugin::registerTypes(const char *uri) { // @uri Paysages qmlRegisterType(uri, 1, 0, "Paysages"); } - - diff --git a/src/interface/modeler/extension/extension_plugin.h b/src/interface/modeler/extension/extension_plugin.h index 9471ff3..0e950e6 100644 --- a/src/interface/modeler/extension/extension_plugin.h +++ b/src/interface/modeler/extension/extension_plugin.h @@ -3,14 +3,12 @@ #include -class ExtensionPlugin : public QQmlExtensionPlugin -{ +class ExtensionPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") -public: + public: void registerTypes(const char *uri); }; #endif // EXTENSION_PLUGIN_H - diff --git a/src/interface/modeler/extension/paysages.cpp b/src/interface/modeler/extension/paysages.cpp index ad88921..3311ce3 100644 --- a/src/interface/modeler/extension/paysages.cpp +++ b/src/interface/modeler/extension/paysages.cpp @@ -1,8 +1,6 @@ #include "paysages.h" -Paysages::Paysages(QQuickItem *parent): - QQuickItem(parent) -{ +Paysages::Paysages(QQuickItem *parent) : QQuickItem(parent) { // By default, QQuickItem does not draw anything. If you subclass // QQuickItem to create a visual item, you will need to uncomment the // following line and re-implement updatePaintNode() @@ -10,7 +8,5 @@ Paysages::Paysages(QQuickItem *parent): // setFlag(ItemHasContents, true); } -Paysages::~Paysages() -{ +Paysages::~Paysages() { } - diff --git a/src/interface/modeler/extension/paysages.h b/src/interface/modeler/extension/paysages.h index 0f55ef5..8993c50 100644 --- a/src/interface/modeler/extension/paysages.h +++ b/src/interface/modeler/extension/paysages.h @@ -3,15 +3,13 @@ #include -class Paysages : public QQuickItem -{ +class Paysages : public QQuickItem { Q_OBJECT Q_DISABLE_COPY(Paysages) -public: + public: Paysages(QQuickItem *parent = 0); ~Paysages(); }; #endif // PAYSAGES_H - diff --git a/src/interface/modeler/quickapp/AtmosphereModeler.cpp b/src/interface/modeler/quickapp/AtmosphereModeler.cpp index 7985ef1..e17d94e 100644 --- a/src/interface/modeler/quickapp/AtmosphereModeler.cpp +++ b/src/interface/modeler/quickapp/AtmosphereModeler.cpp @@ -5,15 +5,16 @@ #include "AtmosphereDefinition.h" #include "FloatPropertyBind.h" -AtmosphereModeler::AtmosphereModeler(MainModelerWindow *main) -{ - prop_daytime = new FloatPropertyBind(main, "atmosphere_daytime", "value", main->getScenery()->getAtmosphere()->propDayTime()); - prop_humidity = new FloatPropertyBind(main, "atmosphere_humidity", "value", main->getScenery()->getAtmosphere()->propHumidity()); - prop_sun_radius = new FloatPropertyBind(main, "atmosphere_sun_radius", "value", main->getScenery()->getAtmosphere()->propSunRadius()); +AtmosphereModeler::AtmosphereModeler(MainModelerWindow *main) { + prop_daytime = + new FloatPropertyBind(main, "atmosphere_daytime", "value", main->getScenery()->getAtmosphere()->propDayTime()); + prop_humidity = new FloatPropertyBind(main, "atmosphere_humidity", "value", + main->getScenery()->getAtmosphere()->propHumidity()); + prop_sun_radius = new FloatPropertyBind(main, "atmosphere_sun_radius", "value", + main->getScenery()->getAtmosphere()->propSunRadius()); } -AtmosphereModeler::~AtmosphereModeler() -{ +AtmosphereModeler::~AtmosphereModeler() { delete prop_daytime; delete prop_humidity; delete prop_sun_radius; diff --git a/src/interface/modeler/quickapp/AtmosphereModeler.h b/src/interface/modeler/quickapp/AtmosphereModeler.h index 5b1e31d..8615e1b 100644 --- a/src/interface/modeler/quickapp/AtmosphereModeler.h +++ b/src/interface/modeler/quickapp/AtmosphereModeler.h @@ -6,18 +6,16 @@ namespace paysages { namespace modeler { -class AtmosphereModeler -{ -public: +class AtmosphereModeler { + public: AtmosphereModeler(MainModelerWindow *main); ~AtmosphereModeler(); -private: + private: FloatPropertyBind *prop_daytime; FloatPropertyBind *prop_humidity; FloatPropertyBind *prop_sun_radius; }; - } } diff --git a/src/interface/modeler/quickapp/FloatPropertyBind.cpp b/src/interface/modeler/quickapp/FloatPropertyBind.cpp index 7c40386..d8a58b5 100644 --- a/src/interface/modeler/quickapp/FloatPropertyBind.cpp +++ b/src/interface/modeler/quickapp/FloatPropertyBind.cpp @@ -6,34 +6,27 @@ #include -FloatPropertyBind::FloatPropertyBind(MainModelerWindow *window, const QString &object_name, const QString &property_name, FloatNode *node): - QObject(window), node(node), property(property_name) -{ +FloatPropertyBind::FloatPropertyBind(MainModelerWindow *window, const QString &object_name, + const QString &property_name, FloatNode *node) + : QObject(window), node(node), property(property_name) { item = window->findQmlObject(object_name); - if (item) - { + if (item) { node->addWatcher(this, true); connect(item, SIGNAL(changed(double)), this, SLOT(propertyChanged(double))); - } - else - { + } else { item = NULL; Logs::error() << "Can't find object :" << object_name.toStdString() << std::endl; } } -void FloatPropertyBind::nodeChanged(const DefinitionNode *, const DefinitionDiff *) -{ - if (item) - { +void FloatPropertyBind::nodeChanged(const DefinitionNode *, const DefinitionDiff *) { + if (item) { item->setProperty(property.toLocal8Bit(), node->getValue()); } } -void FloatPropertyBind::propertyChanged(double value) -{ - if (fabs(value - node->getValue()) > 0.00000001) - { +void FloatPropertyBind::propertyChanged(double value) { + if (fabs(value - node->getValue()) > 0.00000001) { node->setValue(value); } } diff --git a/src/interface/modeler/quickapp/FloatPropertyBind.h b/src/interface/modeler/quickapp/FloatPropertyBind.h index 10c5420..84f5bac 100644 --- a/src/interface/modeler/quickapp/FloatPropertyBind.h +++ b/src/interface/modeler/quickapp/FloatPropertyBind.h @@ -14,23 +14,22 @@ namespace modeler { * * The FloatNode must exist through this object lifetime. */ -class FloatPropertyBind : public QObject, public DefinitionWatcher -{ +class FloatPropertyBind : public QObject, public DefinitionWatcher { Q_OBJECT -public: - FloatPropertyBind(MainModelerWindow *window, const QString &object_name, const QString &property_name, FloatNode *node); + public: + FloatPropertyBind(MainModelerWindow *window, const QString &object_name, const QString &property_name, + FloatNode *node); virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff) override; -private slots: + private slots: void propertyChanged(double value); -private: + private: FloatNode *node; QString property; QObject *item; }; - } } diff --git a/src/interface/modeler/quickapp/IntPropertyBind.cpp b/src/interface/modeler/quickapp/IntPropertyBind.cpp index 61a11e7..8931a63 100644 --- a/src/interface/modeler/quickapp/IntPropertyBind.cpp +++ b/src/interface/modeler/quickapp/IntPropertyBind.cpp @@ -4,34 +4,27 @@ #include "IntNode.h" #include "Logs.h" -IntPropertyBind::IntPropertyBind(MainModelerWindow *window, const QString &object_name, const QString &property_name, IntNode *node): - QObject(window), node(node), property(property_name) -{ +IntPropertyBind::IntPropertyBind(MainModelerWindow *window, const QString &object_name, const QString &property_name, + IntNode *node) + : QObject(window), node(node), property(property_name) { item = window->findQmlObject(object_name); - if (item) - { + if (item) { node->addWatcher(this, true); connect(item, SIGNAL(changed(int)), this, SLOT(propertyChanged(int))); - } - else - { + } else { item = NULL; Logs::error() << "Can't find object :" << object_name.toStdString() << std::endl; } } -void IntPropertyBind::nodeChanged(const DefinitionNode *, const DefinitionDiff *) -{ - if (item) - { +void IntPropertyBind::nodeChanged(const DefinitionNode *, const DefinitionDiff *) { + if (item) { item->setProperty(property.toLocal8Bit(), node->getValue()); } } -void IntPropertyBind::propertyChanged(int value) -{ - if (value != node->getValue()) - { +void IntPropertyBind::propertyChanged(int value) { + if (value != node->getValue()) { node->setValue(value); } } diff --git a/src/interface/modeler/quickapp/IntPropertyBind.h b/src/interface/modeler/quickapp/IntPropertyBind.h index f8bbfdf..7824aba 100644 --- a/src/interface/modeler/quickapp/IntPropertyBind.h +++ b/src/interface/modeler/quickapp/IntPropertyBind.h @@ -14,23 +14,21 @@ namespace modeler { * * The IntNode must exist through this object lifetime. */ -class IntPropertyBind : public QObject, public DefinitionWatcher -{ +class IntPropertyBind : public QObject, public DefinitionWatcher { Q_OBJECT -public: + public: IntPropertyBind(MainModelerWindow *window, const QString &object_name, const QString &property_name, IntNode *node); virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff) override; -private slots: + private slots: void propertyChanged(int value); -private: + private: IntNode *node; QString property; QObject *item; }; - } } #endif // INTPROPERTYBIND_H diff --git a/src/interface/modeler/quickapp/MainModelerWindow.cpp b/src/interface/modeler/quickapp/MainModelerWindow.cpp index 87f472b..1d70530 100644 --- a/src/interface/modeler/quickapp/MainModelerWindow.cpp +++ b/src/interface/modeler/quickapp/MainModelerWindow.cpp @@ -15,8 +15,7 @@ #include #include -MainModelerWindow::MainModelerWindow() -{ +MainModelerWindow::MainModelerWindow() { scenery = new Scenery(); scenery->autoPreset(); @@ -57,171 +56,118 @@ MainModelerWindow::MainModelerWindow() } } -MainModelerWindow::~MainModelerWindow() -{ +MainModelerWindow::~MainModelerWindow() { delete atmosphere; delete water; delete cameras; - //delete render_preview_provider; // don't delete it, addImageProvider took ownership + // delete render_preview_provider; // don't delete it, addImageProvider took ownership delete render_process; delete renderer; delete scenery; } -QObject *MainModelerWindow::findQmlObject(const QString &objectName) -{ - if (objectName == "ui" || objectName == "root") - { +QObject *MainModelerWindow::findQmlObject(const QString &objectName) { + if (objectName == "ui" || objectName == "root") { return rootObject(); - } - else - { + } else { return rootObject()->findChild(objectName); } } -void MainModelerWindow::setQmlProperty(const QString &objectName, const QString &propertyName, const QVariant &value) -{ +void MainModelerWindow::setQmlProperty(const QString &objectName, const QString &propertyName, const QVariant &value) { QObject *item = findQmlObject(objectName); - if (item) - { + if (item) { item->setProperty(propertyName.toLocal8Bit(), value); - } - else - { + } else { Logs::error() << "QML object not found :" << objectName.toStdString() << std::endl; } } -void MainModelerWindow::connectQmlSignal(const QString &objectName, const char *signal, const QObject *receiver, const char *method) -{ +void MainModelerWindow::connectQmlSignal(const QString &objectName, const char *signal, const QObject *receiver, + const char *method) { QObject *item = findQmlObject(objectName); - if (item) - { + if (item) { connect(item, signal, receiver, method); - } - else - { + } else { Logs::error() << "QML object not found :" << objectName.toStdString() << std::endl; } } -QString MainModelerWindow::getState() const -{ +QString MainModelerWindow::getState() const { return rootObject()->property("state").toString(); } -void MainModelerWindow::setState(const QString &stateName) -{ +void MainModelerWindow::setState(const QString &stateName) { rootObject()->setProperty("state", stateName); } -void MainModelerWindow::newFile() -{ +void MainModelerWindow::newFile() { getScenery()->autoPreset(); renderer->reset(); } -void MainModelerWindow::saveFile() -{ +void MainModelerWindow::saveFile() { getScenery()->saveGlobal("saved.p3d"); } -void MainModelerWindow::loadFile() -{ +void MainModelerWindow::loadFile() { Scenery loaded; - if (loaded.loadGlobal("saved.p3d") == Scenery::FILE_OPERATION_OK) - { + if (loaded.loadGlobal("saved.p3d") == Scenery::FILE_OPERATION_OK) { loaded.copy(scenery); renderer->reset(); } } -void MainModelerWindow::exit() -{ +void MainModelerWindow::exit() { close(); } -void MainModelerWindow::keyReleaseEvent(QKeyEvent *event) -{ - if (event->modifiers() & Qt::ControlModifier && event->key() == Qt::Key_Q) - { +void MainModelerWindow::keyReleaseEvent(QKeyEvent *event) { + if (event->modifiers() & Qt::ControlModifier && event->key() == Qt::Key_Q) { exit(); - } - else if (getState() == "Render Dialog") - { - if (event->key() == Qt::Key_Escape) - { + } else if (getState() == "Render Dialog") { + if (event->key() == Qt::Key_Escape) { render_process->stopRender(); } - } - else - { - if (event->key() == Qt::Key_F5) - { + } else { + if (event->key() == Qt::Key_F5) { // Start render in a thread - if ((event->modifiers() & Qt::ControlModifier) and (event->modifiers() & Qt::ShiftModifier)) - { + if ((event->modifiers() & Qt::ControlModifier) and (event->modifiers() & Qt::ShiftModifier)) { render_process->startFinalRender(); - } - else if (event->modifiers() & Qt::ControlModifier) - { + } else if (event->modifiers() & Qt::ControlModifier) { render_process->startMediumRender(); - } - else - { + } else { render_process->startQuickRender(); } - } - else if (event->key() == Qt::Key_F6) - { + } else if (event->key() == Qt::Key_F6) { render_process->showPreviousRender(); - } - else if (event->key() == Qt::Key_F12) - { - Logs::warning() << "Current scenery dump:" << std::endl << scenery->toString() << std::endl; - } - else if (event->key() == Qt::Key_N) - { - if (event->modifiers() & Qt::ControlModifier) - { + } else if (event->key() == Qt::Key_F12) { + Logs::warning() << "Current scenery dump:" << std::endl + << scenery->toString() << std::endl; + } else if (event->key() == Qt::Key_N) { + if (event->modifiers() & Qt::ControlModifier) { newFile(); } - } - else if (event->key() == Qt::Key_S) - { - if (event->modifiers() & Qt::ControlModifier) - { + } else if (event->key() == Qt::Key_S) { + if (event->modifiers() & Qt::ControlModifier) { saveFile(); } - } - else if (event->key() == Qt::Key_L or event->key() == Qt::Key_O) - { - if (event->modifiers() & Qt::ControlModifier) - { + } else if (event->key() == Qt::Key_L or event->key() == Qt::Key_O) { + if (event->modifiers() & Qt::ControlModifier) { loadFile(); } - } - else if (event->key() == Qt::Key_Z) - { - if (event->modifiers() & Qt::ControlModifier) - { - if (event->modifiers() & Qt::ShiftModifier) - { + } else if (event->key() == Qt::Key_Z) { + if (event->modifiers() & Qt::ControlModifier) { + if (event->modifiers() & Qt::ShiftModifier) { getScenery()->getDiffManager()->redo(); - } - else - { + } else { getScenery()->getDiffManager()->undo(); } } - } - else if (event->key() == Qt::Key_Y) - { - if (event->modifiers() & Qt::ControlModifier) - { + } else if (event->key() == Qt::Key_Y) { + if (event->modifiers() & Qt::ControlModifier) { getScenery()->getDiffManager()->undo(); } } diff --git a/src/interface/modeler/quickapp/MainModelerWindow.h b/src/interface/modeler/quickapp/MainModelerWindow.h index c882828..73297ce 100644 --- a/src/interface/modeler/quickapp/MainModelerWindow.h +++ b/src/interface/modeler/quickapp/MainModelerWindow.h @@ -8,10 +8,9 @@ namespace paysages { namespace modeler { -class MainModelerWindow: public QQuickView -{ +class MainModelerWindow : public QQuickView { Q_OBJECT -public: + public: MainModelerWindow(); virtual ~MainModelerWindow(); @@ -22,20 +21,26 @@ public: QString getState() const; void setState(const QString &stateName); - inline Scenery *getScenery() const {return scenery;} - inline OpenGLRenderer *getRenderer() const {return renderer;} - inline ModelerCameras *getCamera() const {return cameras;} + inline Scenery *getScenery() const { + return scenery; + } + inline OpenGLRenderer *getRenderer() const { + return renderer; + } + inline ModelerCameras *getCamera() const { + return cameras; + } -public slots: + public slots: void newFile(); void saveFile(); void loadFile(); void exit(); -protected: + protected: virtual void keyReleaseEvent(QKeyEvent *event) override; -private: + private: Scenery *scenery; OpenGLRenderer *renderer; @@ -47,7 +52,6 @@ private: RenderPreviewProvider *render_preview_provider; RenderProcess *render_process; }; - } } diff --git a/src/interface/modeler/quickapp/ModelerCameras.cpp b/src/interface/modeler/quickapp/ModelerCameras.cpp index 641546b..1b292d0 100644 --- a/src/interface/modeler/quickapp/ModelerCameras.cpp +++ b/src/interface/modeler/quickapp/ModelerCameras.cpp @@ -8,9 +8,7 @@ #include "FloatNode.h" #include "AtmosphereRenderer.h" -ModelerCameras::ModelerCameras(MainModelerWindow *parent): - QObject(parent), parent(parent) -{ +ModelerCameras::ModelerCameras(MainModelerWindow *parent) : QObject(parent), parent(parent) { render = new CameraDefinition(); topdown = new CameraDefinition(); current = new CameraDefinition(); @@ -30,39 +28,34 @@ ModelerCameras::ModelerCameras(MainModelerWindow *parent): startTimer(50); } -ModelerCameras::~ModelerCameras() -{ +ModelerCameras::~ModelerCameras() { delete current; delete render; delete topdown; delete tool; } -void ModelerCameras::processZoom(double value) -{ +void ModelerCameras::processZoom(double value) { active->strafeForward(value); validate(); } -void ModelerCameras::processScroll(double xvalue, double yvalue) -{ +void ModelerCameras::processScroll(double xvalue, double yvalue) { active->strafeRight(xvalue); active->strafeUp(yvalue); validate(); } -void ModelerCameras::processPanning(double xvalue, double yvalue) -{ +void ModelerCameras::processPanning(double xvalue, double yvalue) { active->rotateYaw(xvalue); active->rotatePitch(yvalue); validate(); } -void ModelerCameras::startSunTool() -{ +void ModelerCameras::startSunTool() { tool_mode = TOOL_SUN; previous = active; @@ -72,51 +65,41 @@ void ModelerCameras::startSunTool() parent->getScenery()->getAtmosphere()->propDayTime()->addWatcher(this, true); } -void ModelerCameras::endTool() -{ +void ModelerCameras::endTool() { active = previous; tool_mode = TOOL_NONE; validate(); } -void ModelerCameras::timerEvent(QTimerEvent *) -{ +void ModelerCameras::timerEvent(QTimerEvent *) { current->transitionToAnother(active, 0.5); parent->getScenery()->keepCameraAboveGround(current); parent->getRenderer()->setCamera(current); } -void ModelerCameras::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) -{ - if (node->getPath() == "/atmosphere/daytime" && tool_mode == TOOL_SUN) - { +void ModelerCameras::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) { + if (node->getPath() == "/atmosphere/daytime" && tool_mode == TOOL_SUN) { Vector3 direction = parent->getRenderer()->getAtmosphereRenderer()->getSunDirection(); tool->setTarget(tool->getLocation().add(direction)); } } -void ModelerCameras::validate() -{ +void ModelerCameras::validate() { parent->getScenery()->keepCameraAboveGround(active); parent->getScenery()->keepCameraAboveGround(current); parent->getRenderer()->setCamera(current); - if (active == render) - { + if (active == render) { parent->getScenery()->setCamera(active); } } -void ModelerCameras::changeActiveCamera(const QString &name) -{ - if (name == "Render camera") - { +void ModelerCameras::changeActiveCamera(const QString &name) { + if (name == "Render camera") { active = render; - } - else if (name == "Top-down camera") - { + } else if (name == "Top-down camera") { render->copy(topdown); topdown->strafeForward(-10.0); @@ -131,14 +114,10 @@ void ModelerCameras::changeActiveCamera(const QString &name) previous = active; } -void ModelerCameras::toolChanged(const QString &tool) -{ - if (tool.isEmpty()) - { +void ModelerCameras::toolChanged(const QString &tool) { + if (tool.isEmpty()) { endTool(); - } - else if (tool == "sun") - { + } else if (tool == "sun") { startSunTool(); } } diff --git a/src/interface/modeler/quickapp/ModelerCameras.h b/src/interface/modeler/quickapp/ModelerCameras.h index ead8eb5..47f20cb 100644 --- a/src/interface/modeler/quickapp/ModelerCameras.h +++ b/src/interface/modeler/quickapp/ModelerCameras.h @@ -12,11 +12,10 @@ namespace modeler { /** * Storage for modeler cameras. */ -class ModelerCameras: public QObject, public DefinitionWatcher -{ +class ModelerCameras : public QObject, public DefinitionWatcher { Q_OBJECT -public: + public: ModelerCameras(MainModelerWindow *parent); ~ModelerCameras(); @@ -45,7 +44,7 @@ public: */ void endTool(); -protected: + protected: void timerEvent(QTimerEvent *event); virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff) override; @@ -55,11 +54,11 @@ protected: */ void validate(); -public slots: + public slots: void changeActiveCamera(const QString &name); void toolChanged(const QString &tool); -private: + private: MainModelerWindow *parent; CameraDefinition *active; CameraDefinition *current; @@ -68,14 +67,9 @@ private: CameraDefinition *tool; CameraDefinition *previous; - typedef enum - { - TOOL_NONE, - TOOL_SUN - } CameraToolMode; + typedef enum { TOOL_NONE, TOOL_SUN } CameraToolMode; CameraToolMode tool_mode; }; - } } diff --git a/src/interface/modeler/quickapp/OpenGLView.cpp b/src/interface/modeler/quickapp/OpenGLView.cpp index fa38e4d..66cc116 100644 --- a/src/interface/modeler/quickapp/OpenGLView.cpp +++ b/src/interface/modeler/quickapp/OpenGLView.cpp @@ -6,9 +6,7 @@ #include "OpenGLRenderer.h" #include "ModelerCameras.h" -OpenGLView::OpenGLView(QQuickItem *parent) : - QQuickItem(parent) -{ +OpenGLView::OpenGLView(QQuickItem *parent) : QQuickItem(parent) { initialized = false; window = NULL; renderer = NULL; @@ -19,19 +17,16 @@ OpenGLView::OpenGLView(QQuickItem *parent) : mouse_button = Qt::NoButton; - connect(this, SIGNAL(windowChanged(QQuickWindow*)), this, SLOT(handleWindowChanged(QQuickWindow*))); + connect(this, SIGNAL(windowChanged(QQuickWindow *)), this, SLOT(handleWindowChanged(QQuickWindow *))); connect(this, SIGNAL(widthChanged()), this, SLOT(handleResize())); connect(this, SIGNAL(heightChanged()), this, SLOT(handleResize())); startTimer(50); } -void OpenGLView::handleWindowChanged(QQuickWindow *win) -{ - if (win) - { +void OpenGLView::handleWindowChanged(QQuickWindow *win) { + if (win) { window = qobject_cast(win); - if (window) - { + if (window) { renderer = window->getRenderer(); connect(win, SIGNAL(beforeRendering()), this, SLOT(paint()), Qt::DirectConnection); @@ -43,22 +38,18 @@ void OpenGLView::handleWindowChanged(QQuickWindow *win) } } -void OpenGLView::paint() -{ - if (delayed > 1) - { +void OpenGLView::paint() { + if (delayed > 1) { return; } - if (not initialized or not renderer) - { + if (not initialized or not renderer) { renderer->initialize(); initialized = true; resized = true; } - if (resized) - { + if (resized) { renderer->resize(width(), height()); resized = false; } @@ -66,21 +57,17 @@ void OpenGLView::paint() renderer->prepareOpenGLState(); renderer->paint(); - if (window) - { + if (window) { window->resetOpenGLState(); } } -void OpenGLView::handleResize() -{ +void OpenGLView::handleResize() { resized = true; } -void OpenGLView::wheelEvent(QWheelEvent *event) -{ - if (not acceptInputs()) - { +void OpenGLView::wheelEvent(QWheelEvent *event) { + if (not acceptInputs()) { return; } @@ -88,10 +75,8 @@ void OpenGLView::wheelEvent(QWheelEvent *event) window->getCamera()->processZoom(0.01 * factor * (double)event->angleDelta().y()); } -void OpenGLView::mousePressEvent(QMouseEvent *event) -{ - if (not acceptInputs()) - { +void OpenGLView::mousePressEvent(QMouseEvent *event) { + if (not acceptInputs()) { return; } @@ -99,31 +84,24 @@ void OpenGLView::mousePressEvent(QMouseEvent *event) mouse_pos = event->windowPos(); } -void OpenGLView::mouseReleaseEvent(QMouseEvent *) -{ - if (not acceptInputs()) - { +void OpenGLView::mouseReleaseEvent(QMouseEvent *) { + if (not acceptInputs()) { return; } mouse_button = Qt::NoButton; } -void OpenGLView::mouseMoveEvent(QMouseEvent *event) -{ - if (not acceptInputs()) - { +void OpenGLView::mouseMoveEvent(QMouseEvent *event) { + if (not acceptInputs()) { return; } double factor = getSpeedFactor(event); QPointF diff = event->windowPos() - mouse_pos; - if (mouse_button == Qt::LeftButton) - { + if (mouse_button == Qt::LeftButton) { window->getCamera()->processPanning(0.002 * factor * diff.x(), 0.001 * factor * diff.y()); - } - else if (mouse_button == Qt::RightButton) - { + } else if (mouse_button == Qt::RightButton) { window->getCamera()->processScroll(-0.02 * factor * diff.x(), 0.02 * factor * diff.y()); } mouse_pos = event->windowPos(); @@ -131,49 +109,35 @@ void OpenGLView::mouseMoveEvent(QMouseEvent *event) renderer->setMouseLocation(event->pos().x(), height() - event->pos().y()); } -void OpenGLView::hoverMoveEvent(QHoverEvent *event) -{ +void OpenGLView::hoverMoveEvent(QHoverEvent *event) { renderer->setMouseLocation(event->pos().x(), height() - event->pos().y()); } -void OpenGLView::timerEvent(QTimerEvent *) -{ - if (delayed > 1) - { +void OpenGLView::timerEvent(QTimerEvent *) { + if (delayed > 1) { delayed--; - } - else if (delayed == 1) - { - if (renderer->isDisplayed()) - { + } else if (delayed == 1) { + if (renderer->isDisplayed()) { delayed = 0; window->setState("Init"); } } - if (window) - { + if (window) { window->update(); } } -bool OpenGLView::acceptInputs() const -{ +bool OpenGLView::acceptInputs() const { return window->getState() != "Render Dialog"; } -double OpenGLView::getSpeedFactor(QInputEvent *event) -{ - if (event->modifiers() & Qt::ControlModifier) - { +double OpenGLView::getSpeedFactor(QInputEvent *event) { + if (event->modifiers() & Qt::ControlModifier) { return 0.2; - } - else if (event->modifiers() & Qt::ShiftModifier) - { + } else if (event->modifiers() & Qt::ShiftModifier) { return 3.0; - } - else - { + } else { return 1.0; } } diff --git a/src/interface/modeler/quickapp/OpenGLView.h b/src/interface/modeler/quickapp/OpenGLView.h index 8c8197b..51a2dc8 100644 --- a/src/interface/modeler/quickapp/OpenGLView.h +++ b/src/interface/modeler/quickapp/OpenGLView.h @@ -8,18 +8,17 @@ namespace paysages { namespace modeler { -class OpenGLView : public QQuickItem -{ +class OpenGLView : public QQuickItem { Q_OBJECT -public: + public: explicit OpenGLView(QQuickItem *parent = 0); -public slots: + public slots: void handleWindowChanged(QQuickWindow *win); void paint(); void handleResize(); -protected: + protected: virtual void wheelEvent(QWheelEvent *event) override; virtual void mousePressEvent(QMouseEvent *event) override; virtual void mouseReleaseEvent(QMouseEvent *event) override; @@ -27,11 +26,11 @@ protected: virtual void hoverMoveEvent(QHoverEvent *event) override; virtual void timerEvent(QTimerEvent *event) override; -private: + private: bool acceptInputs() const; double getSpeedFactor(QInputEvent *event); -private: + private: int delayed; bool initialized; bool resized; @@ -41,7 +40,6 @@ private: Qt::MouseButton mouse_button; QPointF mouse_pos; }; - } } diff --git a/src/interface/modeler/quickapp/PropertyBind.cpp b/src/interface/modeler/quickapp/PropertyBind.cpp index 6853613..4dc8e02 100644 --- a/src/interface/modeler/quickapp/PropertyBind.cpp +++ b/src/interface/modeler/quickapp/PropertyBind.cpp @@ -1,7 +1,4 @@ #include "PropertyBind.h" -PropertyBind::PropertyBind(QObject *parent) : QObject(parent) -{ - +PropertyBind::PropertyBind(QObject *parent) : QObject(parent) { } - diff --git a/src/interface/modeler/quickapp/PropertyBind.h b/src/interface/modeler/quickapp/PropertyBind.h index e06a560..8ca02ac 100644 --- a/src/interface/modeler/quickapp/PropertyBind.h +++ b/src/interface/modeler/quickapp/PropertyBind.h @@ -3,15 +3,14 @@ #include -class PropertyBind : public QObject -{ +class PropertyBind : public QObject { Q_OBJECT -public: + public: explicit PropertyBind(QObject *parent = 0); signals: -public slots: + public slots: }; #endif // PROPERTYBIND_H diff --git a/src/interface/modeler/quickapp/RenderPreviewProvider.cpp b/src/interface/modeler/quickapp/RenderPreviewProvider.cpp index f562466..e4ce0c5 100644 --- a/src/interface/modeler/quickapp/RenderPreviewProvider.cpp +++ b/src/interface/modeler/quickapp/RenderPreviewProvider.cpp @@ -4,89 +4,71 @@ #include "CanvasPreview.h" #include "Color.h" -static inline QColor colorToQColor(Color color) -{ +static inline QColor colorToQColor(Color color) { color.normalize(); return QColor(color.r * 255.0, color.g * 255.0, color.b * 255.0, color.a * 255.0); } -RenderPreviewProvider::RenderPreviewProvider() : - QQuickImageProvider(QQuickImageProvider::Image) -{ +RenderPreviewProvider::RenderPreviewProvider() : QQuickImageProvider(QQuickImageProvider::Image) { canvas = NULL; pixbuf = new QImage(1, 1, QImage::Format_ARGB32); hide(); } -RenderPreviewProvider::~RenderPreviewProvider() -{ +RenderPreviewProvider::~RenderPreviewProvider() { delete pixbuf; } -QImage RenderPreviewProvider::requestImage(const QString &, QSize *size, const QSize &) -{ - if (canvas) - { +QImage RenderPreviewProvider::requestImage(const QString &, QSize *size, const QSize &) { + if (canvas) { canvas->getPreview()->updateLive(this); } - if (size) - { + if (size) { *size = pixbuf->size(); } return *pixbuf; } -void RenderPreviewProvider::setCanvas(const Canvas *canvas) -{ - if (not this->canvas) - { +void RenderPreviewProvider::setCanvas(const Canvas *canvas) { + if (not this->canvas) { this->canvas = canvas; pixbuf->fill(Qt::black); canvas->getPreview()->initLive(this); } } -void RenderPreviewProvider::releaseCanvas() -{ - if (canvas) - { +void RenderPreviewProvider::releaseCanvas() { + if (canvas) { canvas->getPreview()->updateLive(this); canvas = NULL; } } -void RenderPreviewProvider::hide() -{ +void RenderPreviewProvider::hide() { pixbuf->fill(Qt::black); } -void RenderPreviewProvider::setToneMapping(const ColorProfile &profile) -{ - if (canvas) - { +void RenderPreviewProvider::setToneMapping(const ColorProfile &profile) { + if (canvas) { canvas->getPreview()->setToneMapping(profile); canvas->getPreview()->updateLive(this); } } -void RenderPreviewProvider::canvasResized(int width, int height) -{ - if (QSize(width, height) != pixbuf->size()) - { +void RenderPreviewProvider::canvasResized(int width, int height) { + if (QSize(width, height) != pixbuf->size()) { delete pixbuf; pixbuf = new QImage(width, height, QImage::Format_ARGB32); } pixbuf->fill(Qt::black); } -void RenderPreviewProvider::canvasCleared(const Color &col) -{ +void RenderPreviewProvider::canvasCleared(const Color &col) { pixbuf->fill(colorToQColor(col)); } -void RenderPreviewProvider::canvasPainted(int x, int y, const Color &col) -{ +void RenderPreviewProvider::canvasPainted(int x, int y, const Color &col) { pixbuf->setPixel(x, pixbuf->height() - 1 - y, colorToQColor(col).rgb()); } diff --git a/src/interface/modeler/quickapp/RenderPreviewProvider.h b/src/interface/modeler/quickapp/RenderPreviewProvider.h index 4164c73..462e5e0 100644 --- a/src/interface/modeler/quickapp/RenderPreviewProvider.h +++ b/src/interface/modeler/quickapp/RenderPreviewProvider.h @@ -12,9 +12,8 @@ namespace modeler { /** * Provider for a Qml Image content, filled from a canvas rendering. */ -class RenderPreviewProvider : public QQuickImageProvider, public CanvasLiveClient -{ -public: +class RenderPreviewProvider : public QQuickImageProvider, public CanvasLiveClient { + public: RenderPreviewProvider(); virtual ~RenderPreviewProvider(); @@ -40,18 +39,17 @@ public: */ void setToneMapping(const ColorProfile &profile); -protected: + protected: virtual QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override; virtual void canvasResized(int width, int height) override; virtual void canvasCleared(const Color &col) override; virtual void canvasPainted(int x, int y, const Color &col) override; -private: - QImage* pixbuf; + private: + QImage *pixbuf; const Canvas *canvas; }; - } } diff --git a/src/interface/modeler/quickapp/RenderProcess.cpp b/src/interface/modeler/quickapp/RenderProcess.cpp index 064b691..21f477e 100644 --- a/src/interface/modeler/quickapp/RenderProcess.cpp +++ b/src/interface/modeler/quickapp/RenderProcess.cpp @@ -13,23 +13,20 @@ #include "CanvasPreview.h" #include "OpenGLRenderer.h" -class RenderThread: public Thread -{ -public: - RenderThread(SoftwareCanvasRenderer *renderer): renderer(renderer) - { +class RenderThread : public Thread { + public: + RenderThread(SoftwareCanvasRenderer *renderer) : renderer(renderer) { } - virtual void run() override - { + virtual void run() override { renderer->render(); } -private: + + private: SoftwareCanvasRenderer *renderer; }; -RenderProcess::RenderProcess(MainModelerWindow *window, RenderPreviewProvider *destination): - window(window), destination(destination) -{ +RenderProcess::RenderProcess(MainModelerWindow *window, RenderPreviewProvider *destination) + : window(window), destination(destination) { has_render = false; rendering = false; renderer = NULL; @@ -69,31 +66,25 @@ RenderProcess::RenderProcess(MainModelerWindow *window, RenderPreviewProvider *d startTimer(100); } -RenderProcess::~RenderProcess() -{ - if (rendering) - { +RenderProcess::~RenderProcess() { + if (rendering) { renderer->interrupt(); } rendering = false; - if (render_thread) - { + if (render_thread) { render_thread->join(); delete render_thread; } - if (renderer) - { + if (renderer) { delete renderer; } } -void RenderProcess::startRender(Scenery *scenery, const RenderConfig &config) -{ - if (rendering) - { +void RenderProcess::startRender(Scenery *scenery, const RenderConfig &config) { + if (rendering) { return; } @@ -104,8 +95,7 @@ void RenderProcess::startRender(Scenery *scenery, const RenderConfig &config) has_render = true; rendering = true; - if (renderer) - { + if (renderer) { delete renderer; } @@ -133,25 +123,20 @@ void RenderProcess::startRender(Scenery *scenery, const RenderConfig &config) window->setState("Render Dialog"); } -void RenderProcess::startQuickRender() -{ +void RenderProcess::startQuickRender() { startRender(window->getScenery(), RenderConfig(480, 270, 1, 3)); } -void RenderProcess::startMediumRender() -{ +void RenderProcess::startMediumRender() { startRender(window->getScenery(), RenderConfig(800, 450, 1, 5)); } -void RenderProcess::startFinalRender() -{ +void RenderProcess::startFinalRender() { startRender(window->getScenery(), RenderConfig(1920, 1080, 4, 8)); } -void RenderProcess::showPreviousRender() -{ - if (not rendering and has_render) - { +void RenderProcess::showPreviousRender() { + if (not rendering and has_render) { destination->setCanvas(renderer->getCanvas()); destination->releaseCanvas(); @@ -159,40 +144,29 @@ void RenderProcess::showPreviousRender() } } -void RenderProcess::stopRender() -{ - if (rendering) - { +void RenderProcess::stopRender() { + if (rendering) { renderer->interrupt(); - } - else - { + } else { destination->hide(); window->setState(window->rootObject()->property("previous_state").toString()); } } -void RenderProcess::savePicture(QString path) -{ +void RenderProcess::savePicture(QString path) { renderer->saveToDisk(path.replace("file://", "").toStdString()); } -const QSize RenderProcess::getPreviewSize() -{ - if (renderer) - { +const QSize RenderProcess::getPreviewSize() { + if (renderer) { return QSize(renderer->getCanvas()->getPreview()->getWidth(), renderer->getCanvas()->getPreview()->getHeight()); - } - else - { + } else { return QSize(10, 10); } } -void RenderProcess::timerEvent(QTimerEvent *) -{ - if (rendering and renderer->isFinished()) - { +void RenderProcess::timerEvent(QTimerEvent *) { + if (rendering and renderer->isFinished()) { destination->releaseCanvas(); rendering = false; @@ -204,15 +178,12 @@ void RenderProcess::timerEvent(QTimerEvent *) window->getRenderer()->resume(); } - if (renderer) - { + if (renderer) { QTime t = QTime(0, 0, 0).addMSecs(renderer->getProgressHelper()->getDuration()); QString info = QString("Elapsed time: ") + t.toString("hh:mm:ss"); - if (rendering) - { + if (rendering) { unsigned long remaining = renderer->getProgressHelper()->estimateRemainingTime(); - if (remaining > 0) - { + if (remaining > 0) { t = QTime(0, 0, 0).addMSecs(999 + remaining); info += " - Remaining: ~" + t.toString("hh:mm:ss"); } diff --git a/src/interface/modeler/quickapp/RenderProcess.h b/src/interface/modeler/quickapp/RenderProcess.h index b7d5349..7fc62bf 100644 --- a/src/interface/modeler/quickapp/RenderProcess.h +++ b/src/interface/modeler/quickapp/RenderProcess.h @@ -8,11 +8,10 @@ namespace paysages { namespace modeler { -class RenderProcess: public QObject -{ +class RenderProcess : public QObject { Q_OBJECT -public: + public: RenderProcess(MainModelerWindow *window, RenderPreviewProvider *destination); virtual ~RenderProcess(); @@ -26,9 +25,11 @@ public: */ const QSize getPreviewSize(); - inline bool isRendering() const {return rendering;} + inline bool isRendering() const { + return rendering; + } -public slots: + public slots: /** * Start a quick render. */ @@ -59,10 +60,10 @@ public slots: */ void savePicture(QString path); -protected: + protected: virtual void timerEvent(QTimerEvent *event) override; -private: + private: MainModelerWindow *window; RenderPreviewProvider *destination; bool has_render; @@ -70,7 +71,6 @@ private: SoftwareCanvasRenderer *renderer; Thread *render_thread; }; - } } diff --git a/src/interface/modeler/quickapp/WaterModeler.cpp b/src/interface/modeler/quickapp/WaterModeler.cpp index d44af33..db703c8 100644 --- a/src/interface/modeler/quickapp/WaterModeler.cpp +++ b/src/interface/modeler/quickapp/WaterModeler.cpp @@ -9,28 +9,24 @@ #include "OpenGLRenderer.h" #include "OpenGLWater.h" -WaterModeler::WaterModeler(MainModelerWindow *ui): - ui(ui) -{ +WaterModeler::WaterModeler(MainModelerWindow *ui) : ui(ui) { QObject *toggle_water = ui->findQmlObject("camera_toggle_water"); - if (toggle_water) - { + if (toggle_water) { connect(toggle_water, SIGNAL(toggled(bool)), this, SLOT(enableRendering(bool))); } prop_model = new IntPropertyBind(ui, "water_model", "value", ui->getScenery()->getWater()->propModel()); prop_height = new FloatPropertyBind(ui, "water_height", "value", ui->getScenery()->getTerrain()->propWaterHeight()); - prop_reflexion = new FloatPropertyBind(ui, "water_reflection", "value", ui->getScenery()->getWater()->propReflection()); + prop_reflexion = + new FloatPropertyBind(ui, "water_reflection", "value", ui->getScenery()->getWater()->propReflection()); } -WaterModeler::~WaterModeler() -{ +WaterModeler::~WaterModeler() { delete prop_model; delete prop_height; delete prop_reflexion; } -void WaterModeler::enableRendering(bool enable) -{ +void WaterModeler::enableRendering(bool enable) { ui->getRenderer()->getWater()->setEnabled(enable); } diff --git a/src/interface/modeler/quickapp/WaterModeler.h b/src/interface/modeler/quickapp/WaterModeler.h index 1ecd487..95b38bb 100644 --- a/src/interface/modeler/quickapp/WaterModeler.h +++ b/src/interface/modeler/quickapp/WaterModeler.h @@ -8,23 +8,21 @@ namespace paysages { namespace modeler { -class WaterModeler: public QObject -{ +class WaterModeler : public QObject { Q_OBJECT -public: + public: WaterModeler(MainModelerWindow *ui); ~WaterModeler(); -public slots: + public slots: void enableRendering(bool enable); -private: + private: MainModelerWindow *ui; IntPropertyBind *prop_model; FloatPropertyBind *prop_height; FloatPropertyBind *prop_reflexion; }; - } } diff --git a/src/interface/modeler/quickapp/main.cpp b/src/interface/modeler/quickapp/main.cpp index 3d9237a..9fec99e 100644 --- a/src/interface/modeler/quickapp/main.cpp +++ b/src/interface/modeler/quickapp/main.cpp @@ -2,8 +2,7 @@ #include "MainModelerWindow.h" -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); MainModelerWindow view; diff --git a/src/interface/modeler/quickapp/modeler_global.h b/src/interface/modeler/quickapp/modeler_global.h index 77b8895..c007929 100644 --- a/src/interface/modeler/quickapp/modeler_global.h +++ b/src/interface/modeler/quickapp/modeler_global.h @@ -7,19 +7,19 @@ namespace paysages { namespace modeler { - class MainModelerWindow; - class OpenGLView; +class MainModelerWindow; +class OpenGLView; - class AtmosphereModeler; - class WaterModeler; +class AtmosphereModeler; +class WaterModeler; - class RenderPreviewProvider; - class RenderProcess; +class RenderPreviewProvider; +class RenderProcess; - class ModelerCameras; +class ModelerCameras; - class FloatPropertyBind; - class IntPropertyBind; +class FloatPropertyBind; +class IntPropertyBind; } } diff --git a/src/render/opengl/ExplorerChunkTerrain.cpp b/src/render/opengl/ExplorerChunkTerrain.cpp index b4a1fdd..0e9f86a 100644 --- a/src/render/opengl/ExplorerChunkTerrain.cpp +++ b/src/render/opengl/ExplorerChunkTerrain.cpp @@ -11,9 +11,8 @@ #include "Scenery.h" #include "TerrainDefinition.h" -ExplorerChunkTerrain::ExplorerChunkTerrain(OpenGLRenderer* renderer, double x, double z, double size, int nbchunks): - _renderer(renderer) -{ +ExplorerChunkTerrain::ExplorerChunkTerrain(OpenGLRenderer *renderer, double x, double z, double size, int nbchunks) + : _renderer(renderer) { priority = 0.0; _reset_topology = false; _reset_texture = false; @@ -30,7 +29,7 @@ ExplorerChunkTerrain::ExplorerChunkTerrain(OpenGLRenderer* renderer, double x, d _startx = x; _startz = z; _size = size; - _overall_step = size * (double) nbchunks; + _overall_step = size * (double)nbchunks; distance_to_camera = 0.0; underwater = false; @@ -43,70 +42,60 @@ ExplorerChunkTerrain::ExplorerChunkTerrain(OpenGLRenderer* renderer, double x, d tessellated->setAutoGridIndices(tessellation_count); _tessellation_max_size = tessellation_count - 1; _tessellation_current_size = 0; - _tessellation_step = _size / (double) _tessellation_max_size; + _tessellation_step = _size / (double)_tessellation_max_size; maintain(); } -ExplorerChunkTerrain::~ExplorerChunkTerrain() -{ +ExplorerChunkTerrain::~ExplorerChunkTerrain() { _lock_data.lock(); delete _texture; delete tessellated; _lock_data.unlock(); } -bool ExplorerChunkTerrain::maintain() -{ +bool ExplorerChunkTerrain::maintain() { bool subchanged; _lock_data.lock(); - if (_reset_topology) - { + if (_reset_topology) { _reset_topology = false; _tessellation_current_size = 0; lowest = 10000.0; highest = -10000.0; underwater = false; } - if (_reset_texture) - { + if (_reset_texture) { _reset_texture = false; _texture_current_size = 0; underwater = false; } _lock_data.unlock(); - if (underwater) - { + if (underwater) { return false; } // Improve heightmap resolution - if (_tessellation_current_size < _tessellation_max_size) - { - while (_tessellation_current_size < _tessellation_max_size) - { + if (_tessellation_current_size < _tessellation_max_size) { + while (_tessellation_current_size < _tessellation_max_size) { int new_tessellation_size = _tessellation_current_size ? _tessellation_current_size * 4 : 4; - int old_tessellation_inc = _tessellation_current_size ? _tessellation_max_size / _tessellation_current_size : 1; + int old_tessellation_inc = + _tessellation_current_size ? _tessellation_max_size / _tessellation_current_size : 1; int new_tessellation_inc = _tessellation_max_size / new_tessellation_size; float internal_step = 1.0f / (float)_tessellation_max_size; - for (int j = 0; j <= _tessellation_max_size; j += new_tessellation_inc) - { - for (int i = 0; i <= _tessellation_max_size; i += new_tessellation_inc) - { - if (_tessellation_current_size == 0 || i % old_tessellation_inc != 0 || j % old_tessellation_inc != 0) - { + for (int j = 0; j <= _tessellation_max_size; j += new_tessellation_inc) { + for (int i = 0; i <= _tessellation_max_size; i += new_tessellation_inc) { + if (_tessellation_current_size == 0 || i % old_tessellation_inc != 0 || + j % old_tessellation_inc != 0) { double x = _startx + _tessellation_step * (float)i; double z = _startz + _tessellation_step * (float)j; double height = _renderer->getTerrainRenderer()->getHeight(x, z, true, false); - if (height >= highest) - { + if (height >= highest) { highest = height; } - if (height <= lowest) - { + if (height <= lowest) { lowest = height; } @@ -122,8 +111,7 @@ bool ExplorerChunkTerrain::maintain() tessellated->setGridVertex(tessellation_count, i, j, v); } } - if (interrupt or _reset_topology) - { + if (interrupt or _reset_topology) { return false; } } @@ -135,37 +123,31 @@ bool ExplorerChunkTerrain::maintain() tessellated->setAutoGridIndices(tessellation_count, new_tessellation_inc); _lock_data.unlock(); - if (_tessellation_current_size >= 4) - { + if (_tessellation_current_size >= 4) { break; } } subchanged = true; - } - else - { + } else { subchanged = false; } // Improve texture resolution - if (_texture_current_size < _texture_wanted_size) - { + if (_texture_current_size < _texture_wanted_size) { int new_texture_size = _texture_current_size ? _texture_current_size * 2 : 1; - QImage* new_image = new QImage(_texture->scaled(new_texture_size + 1, new_texture_size + 1, Qt::IgnoreAspectRatio, Qt::FastTransformation)); - for (int j = 0; j <= new_texture_size; j++) - { - for (int i = 0; i <= new_texture_size; i++) - { - if (_texture_current_size <= 1 || i % 2 != 0 || j % 2 != 0) - { - Color color = getTextureColor((double)i / (double)new_texture_size, (double)j / (double)new_texture_size); + QImage *new_image = new QImage(_texture->scaled(new_texture_size + 1, new_texture_size + 1, + Qt::IgnoreAspectRatio, Qt::FastTransformation)); + for (int j = 0; j <= new_texture_size; j++) { + for (int i = 0; i <= new_texture_size; i++) { + if (_texture_current_size <= 1 || i % 2 != 0 || j % 2 != 0) { + Color color = + getTextureColor((double)i / (double)new_texture_size, (double)j / (double)new_texture_size); color.normalize(); new_image->setPixel(i, j, color.to32BitRGBA()); } } - if (interrupt or _reset_texture) - { + if (interrupt or _reset_texture) { return false; } } @@ -178,19 +160,15 @@ bool ExplorerChunkTerrain::maintain() _lock_data.unlock(); return true; - } - else - { + } else { return subchanged; } } -void ExplorerChunkTerrain::updatePriority(CameraDefinition* camera) -{ +void ExplorerChunkTerrain::updatePriority(CameraDefinition *camera) { // Under water check underwater = highest < -_renderer->getScenery()->getTerrain()->getWaterOffset(); - if (underwater) - { + if (underwater) { priority = -10000.0; return; } @@ -199,23 +177,19 @@ void ExplorerChunkTerrain::updatePriority(CameraDefinition* camera) // Handle position _lock_data.lock(); - if (camera_location.x > _startx + _overall_step * 0.5) - { + if (camera_location.x > _startx + _overall_step * 0.5) { _startx += _overall_step; askReset(); } - if (camera_location.z > _startz + _overall_step * 0.5) - { + if (camera_location.z > _startz + _overall_step * 0.5) { _startz += _overall_step; askReset(); } - if (camera_location.x < _startx - _overall_step * 0.5) - { + if (camera_location.x < _startx - _overall_step * 0.5) { _startx -= _overall_step; askReset(); } - if (camera_location.z < _startz - _overall_step * 0.5) - { + if (camera_location.z < _startz - _overall_step * 0.5) { _startz -= _overall_step; askReset(); } @@ -223,57 +197,41 @@ void ExplorerChunkTerrain::updatePriority(CameraDefinition* camera) _lock_data.unlock(); // Update wanted LOD - if (distance_to_camera < 60.0) - { + if (distance_to_camera < 60.0) { _texture_wanted_size = _texture_max_size; - } - else if (distance_to_camera < 140.0) - { + } else if (distance_to_camera < 140.0) { _texture_wanted_size = _texture_max_size / 4; - } - else if (distance_to_camera < 300.0) - { + } else if (distance_to_camera < 300.0) { _texture_wanted_size = _texture_max_size / 8; - } - else - { + } else { _texture_wanted_size = 8; } // Update priority - if (_reset_topology || _reset_texture || (_texture_max_size > 1 && _texture_current_size <= 1)) - { + if (_reset_topology || _reset_texture || (_texture_max_size > 1 && _texture_current_size <= 1)) { priority = 1000.0; - } - else if (_texture_current_size == _texture_wanted_size) - { + } else if (_texture_current_size == _texture_wanted_size) { priority = -1000.0; - } - else - { + } else { priority = _texture_wanted_size / _texture_current_size; } - } -void ExplorerChunkTerrain::render(QOpenGLShaderProgram* program, OpenGLFunctions* functions) -{ - if (underwater) - { +void ExplorerChunkTerrain::render(QOpenGLShaderProgram *program, OpenGLFunctions *functions) { + if (underwater) { return; } // Put texture in place _lock_data.lock(); - if (_texture_changed) - { + if (_texture_changed) { _texture_changed = false; // TODO Only do the scale if not power-of-two textures are unsupported by GPU - QImage tex = _texture->scaled(_texture_current_size, _texture_current_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + QImage tex = _texture->scaled(_texture_current_size, _texture_current_size, Qt::IgnoreAspectRatio, + Qt::SmoothTransformation); - if (texture_id == 0) - { + if (texture_id == 0) { GLuint texid; functions->glGenTextures(1, &texid); texture_id = texid; @@ -284,19 +242,18 @@ void ExplorerChunkTerrain::render(QOpenGLShaderProgram* program, OpenGLFunctions functions->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); functions->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); functions->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - functions->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.width(), tex.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, tex.bits()); + functions->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.width(), tex.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, + tex.bits()); } _lock_data.unlock(); // Render tessellated mesh - if (!_reset_topology) - { + if (!_reset_topology) { _lock_data.lock(); int tessellation_size = _tessellation_current_size; _lock_data.unlock(); - if (tessellation_size <= 1) - { + if (tessellation_size <= 1) { return; } @@ -310,30 +267,25 @@ void ExplorerChunkTerrain::render(QOpenGLShaderProgram* program, OpenGLFunctions } } -void ExplorerChunkTerrain::askReset(bool topology, bool texture) -{ +void ExplorerChunkTerrain::askReset(bool topology, bool texture) { _reset_topology = _reset_topology or topology; _reset_texture = _reset_texture or texture; } -void ExplorerChunkTerrain::askInterrupt() -{ +void ExplorerChunkTerrain::askInterrupt() { interrupt = true; } -void ExplorerChunkTerrain::askResume() -{ +void ExplorerChunkTerrain::askResume() { interrupt = false; } -Color ExplorerChunkTerrain::getTextureColor(double x, double y) -{ +Color ExplorerChunkTerrain::getTextureColor(double x, double y) { Vector3 location = {_startx + x * _size, 0.0, _startz + y * _size}; return _renderer->getTerrainRenderer()->getFinalColor(location, 0.01); } -Vector3 ExplorerChunkTerrain::getCenter() -{ +Vector3 ExplorerChunkTerrain::getCenter() { Vector3 result; result.x = _startx + _size / 2.0; diff --git a/src/render/opengl/ExplorerChunkTerrain.h b/src/render/opengl/ExplorerChunkTerrain.h index 60dcdf3..69213d5 100644 --- a/src/render/opengl/ExplorerChunkTerrain.h +++ b/src/render/opengl/ExplorerChunkTerrain.h @@ -10,22 +10,20 @@ class QOpenGLShaderProgram; namespace paysages { namespace opengl { -class OPENGLSHARED_EXPORT ExplorerChunkTerrain -{ -public: - typedef struct - { +class OPENGLSHARED_EXPORT ExplorerChunkTerrain { + public: + typedef struct { float location[3]; float uv[2]; } TerrainVertex; -public: - ExplorerChunkTerrain(OpenGLRenderer* renderer, double x, double z, double size, int nbchunks); + public: + ExplorerChunkTerrain(OpenGLRenderer *renderer, double x, double z, double size, int nbchunks); ~ExplorerChunkTerrain(); bool maintain(); - void updatePriority(CameraDefinition* camera); - void render(QOpenGLShaderProgram* program, OpenGLFunctions* functions); + void updatePriority(CameraDefinition *camera); + void render(QOpenGLShaderProgram *program, OpenGLFunctions *functions); void askReset(bool topology = true, bool texture = true); void askInterrupt(); @@ -35,7 +33,7 @@ public: double priority; -private: + private: Vector3 getCenter(); double _startx; @@ -51,13 +49,13 @@ private: QMutex _lock_data; - OpenGLRenderer* _renderer; + OpenGLRenderer *_renderer; bool _reset_topology; bool _reset_texture; bool interrupt; - QImage* _texture; + QImage *_texture; unsigned int texture_id; bool _texture_changed; int _texture_current_size; @@ -70,7 +68,6 @@ private: double highest; double distance_to_camera; }; - } } diff --git a/src/render/opengl/OpenGLPart.cpp b/src/render/opengl/OpenGLPart.cpp index dd86727..cfefc62 100644 --- a/src/render/opengl/OpenGLPart.cpp +++ b/src/render/opengl/OpenGLPart.cpp @@ -9,45 +9,34 @@ #include "AtmosphereRenderer.h" #include "Scenery.h" -OpenGLPart::OpenGLPart(OpenGLRenderer* renderer): - renderer(renderer) -{ +OpenGLPart::OpenGLPart(OpenGLRenderer *renderer) : renderer(renderer) { } -OpenGLPart::~OpenGLPart() -{ - QMapIterator i(shaders); - while (i.hasNext()) - { +OpenGLPart::~OpenGLPart() { + QMapIterator i(shaders); + while (i.hasNext()) { i.next(); delete i.value(); } } -void OpenGLPart::interrupt() -{ +void OpenGLPart::interrupt() { } -OpenGLShaderProgram* OpenGLPart::createShader(QString name) -{ - OpenGLShaderProgram* program = new OpenGLShaderProgram(name.toStdString(), renderer); +OpenGLShaderProgram *OpenGLPart::createShader(QString name) { + OpenGLShaderProgram *program = new OpenGLShaderProgram(name.toStdString(), renderer); - if (!shaders.contains(name)) - { + if (!shaders.contains(name)) { shaders[name] = program; return program; - } - else - { + } else { return 0; } } -void OpenGLPart::updateScenery(bool onlyCommon) -{ +void OpenGLPart::updateScenery(bool onlyCommon) { // Let subclass do its own collecting - if (not onlyCommon) - { + if (not onlyCommon) { update(); } } diff --git a/src/render/opengl/OpenGLPart.h b/src/render/opengl/OpenGLPart.h index 8cd5034..fedef49 100644 --- a/src/render/opengl/OpenGLPart.h +++ b/src/render/opengl/OpenGLPart.h @@ -11,10 +11,9 @@ namespace opengl { // Class that can be inherited by scenery parts, to use OpenGL features -class OPENGLSHARED_EXPORT OpenGLPart -{ -public: - OpenGLPart(OpenGLRenderer* renderer); +class OPENGLSHARED_EXPORT OpenGLPart { + public: + OpenGLPart(OpenGLRenderer *renderer); virtual ~OpenGLPart(); // Initialize the part rendering (create shaders, prepare static textures...) @@ -29,17 +28,17 @@ public: // Interrupt the rendering virtual void interrupt(); - void updateScenery(bool onlyCommon=false); + void updateScenery(bool onlyCommon = false); -protected: + protected: // Create a shader program - OpenGLShaderProgram* createShader(QString name); + OpenGLShaderProgram *createShader(QString name); // Access to the main scenery renderer - OpenGLRenderer* renderer; + OpenGLRenderer *renderer; -private: - QMap shaders; + private: + QMap shaders; }; } } diff --git a/src/render/opengl/OpenGLRenderer.cpp b/src/render/opengl/OpenGLRenderer.cpp index d960f28..25e15d7 100644 --- a/src/render/opengl/OpenGLRenderer.cpp +++ b/src/render/opengl/OpenGLRenderer.cpp @@ -14,9 +14,7 @@ #include "Logs.h" #include "Vector3.h" -OpenGLRenderer::OpenGLRenderer(Scenery* scenery): - SoftwareRenderer(scenery) -{ +OpenGLRenderer::OpenGLRenderer(Scenery *scenery) : SoftwareRenderer(scenery) { ready = false; paused = false; displayed = false; @@ -43,8 +41,7 @@ OpenGLRenderer::OpenGLRenderer(Scenery* scenery): terrain = new OpenGLTerrain(this); } -OpenGLRenderer::~OpenGLRenderer() -{ +OpenGLRenderer::~OpenGLRenderer() { terrain->interrupt(); water->interrupt(); skybox->interrupt(); @@ -61,12 +58,10 @@ OpenGLRenderer::~OpenGLRenderer() delete shared_state; } -void OpenGLRenderer::initialize() -{ +void OpenGLRenderer::initialize() { ready = functions->initializeOpenGLFunctions(); - if (ready) - { + if (ready) { prepareOpenGLState(); prepare(); @@ -85,17 +80,13 @@ void OpenGLRenderer::initialize() terrain->updateScenery(); cameraChangeEvent(render_camera); - } - else - { + } else { Logs::error() << "Failed to initialize OpenGL bindings" << std::endl; } } -void OpenGLRenderer::prepareOpenGLState() -{ - if (ready) - { +void OpenGLRenderer::prepareOpenGLState() { + if (ready) { functions->glDisable(GL_LIGHTING); functions->glFrontFace(GL_CCW); @@ -122,18 +113,15 @@ void OpenGLRenderer::prepareOpenGLState() } } -void OpenGLRenderer::setCamera(CameraDefinition *camera) -{ +void OpenGLRenderer::setCamera(CameraDefinition *camera) { camera->copy(render_camera); getScenery()->keepCameraAboveGround(render_camera); render_camera->setRenderSize(vp_width, vp_height); cameraChangeEvent(render_camera); } -void OpenGLRenderer::resize(int width, int height) -{ - if (ready) - { +void OpenGLRenderer::resize(int width, int height) { + if (ready) { vp_width = width; vp_height = height; @@ -144,24 +132,20 @@ void OpenGLRenderer::resize(int width, int height) } } -void OpenGLRenderer::paint() -{ - if (ready and not paused) - { +void OpenGLRenderer::paint() { + if (ready and not paused) { functions->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); skybox->render(); terrain->render(); water->render(); - if (mouse_tracking) - { + if (mouse_tracking) { updateMouseProjection(); } int error_code; - while ((error_code = functions->glGetError()) != GL_NO_ERROR) - { + while ((error_code = functions->glGetError()) != GL_NO_ERROR) { Logs::warning() << "[OpenGL] ERROR : " << error_code << std::endl; } @@ -169,10 +153,8 @@ void OpenGLRenderer::paint() } } -void OpenGLRenderer::reset() -{ - if (ready) - { +void OpenGLRenderer::reset() { + if (ready) { skybox->updateScenery(); water->updateScenery(); terrain->updateScenery(); @@ -181,31 +163,26 @@ void OpenGLRenderer::reset() } } -void OpenGLRenderer::pause() -{ +void OpenGLRenderer::pause() { paused = true; terrain->pause(); } -void OpenGLRenderer::resume() -{ +void OpenGLRenderer::resume() { paused = false; terrain->resume(); } -void OpenGLRenderer::setMouseLocation(int x, int y) -{ +void OpenGLRenderer::setMouseLocation(int x, int y) { mouse_x = x; mouse_y = y; } -const Vector3 &OpenGLRenderer::getMouseProjection() -{ +const Vector3 &OpenGLRenderer::getMouseProjection() { return *mouse_projected; } -void OpenGLRenderer::cameraChangeEvent(CameraDefinition *camera) -{ +void OpenGLRenderer::cameraChangeEvent(CameraDefinition *camera) { // Get camera info Vector3 location = camera->getLocation(); Vector3 target = camera->getTarget(); @@ -215,39 +192,36 @@ void OpenGLRenderer::cameraChangeEvent(CameraDefinition *camera) // Compute matrix QMatrix4x4 transform; transform.setToIdentity(); - transform.lookAt(QVector3D(location.x, location.y, location.z), - QVector3D(target.x, target.y, target.z), - QVector3D(up.x, up.y, up.z)); + transform.lookAt(QVector3D(location.x, location.y, location.z), QVector3D(target.x, target.y, target.z), + QVector3D(up.x, up.y, up.z)); QMatrix4x4 projection; projection.setToIdentity(); projection.perspective(perspective.yfov * 180.0 / M_PI, perspective.xratio, perspective.znear, perspective.zfar); - *view_matrix = projection * transform; + *view_matrix = projection *transform; // Set in shaders shared_state->set("cameraLocation", location); shared_state->set("viewMatrix", *view_matrix); } -double OpenGLRenderer::getPrecision(const Vector3 &) -{ +double OpenGLRenderer::getPrecision(const Vector3 &) { return 0.0000001; } -Color OpenGLRenderer::applyMediumTraversal(const Vector3&, const Color &color) -{ +Color OpenGLRenderer::applyMediumTraversal(const Vector3 &, const Color &color) { return color; } -void OpenGLRenderer::updateMouseProjection() -{ +void OpenGLRenderer::updateMouseProjection() { GLfloat z; functions->glReadPixels(mouse_x, mouse_y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); QVector4D located(mouse_x / render_camera->getWidth(), mouse_y / render_camera->getHeight(), z, 1.0); QVector4D unprojected = view_matrix->inverted() * 2.0 * (located - QVector4D(0.5, 0.5, 0.5, 0.5)); - *mouse_projected = Vector3(unprojected.x() / unprojected.w(), unprojected.y() / unprojected.w(), unprojected.z() / unprojected.w()); + *mouse_projected = Vector3(unprojected.x() / unprojected.w(), unprojected.y() / unprojected.w(), + unprojected.z() / unprojected.w()); shared_state->set("mouseProjection", *mouse_projected); } diff --git a/src/render/opengl/OpenGLRenderer.h b/src/render/opengl/OpenGLRenderer.h index ceee92b..0796303 100644 --- a/src/render/opengl/OpenGLRenderer.h +++ b/src/render/opengl/OpenGLRenderer.h @@ -13,16 +13,23 @@ namespace opengl { /*! * \brief Scenery renderer in an OpenGL context. */ -class OPENGLSHARED_EXPORT OpenGLRenderer: public SoftwareRenderer -{ -public: - OpenGLRenderer(Scenery* scenery); +class OPENGLSHARED_EXPORT OpenGLRenderer : public SoftwareRenderer { + public: + OpenGLRenderer(Scenery *scenery); virtual ~OpenGLRenderer(); - inline OpenGLSkybox *getSkybox() const {return skybox;} - inline OpenGLWater *getWater() const {return water;} - inline OpenGLTerrain *getTerrain() const {return terrain;} - inline bool isDisplayed() const {return displayed;} + inline OpenGLSkybox *getSkybox() const { + return skybox; + } + inline OpenGLWater *getWater() const { + return water; + } + inline OpenGLTerrain *getTerrain() const { + return terrain; + } + inline bool isDisplayed() const { + return displayed; + } void initialize(); void prepareOpenGLState(); @@ -59,21 +66,25 @@ public: * Change the camera location. */ void setCamera(CameraDefinition *camera); - void cameraChangeEvent(CameraDefinition* camera); + void cameraChangeEvent(CameraDefinition *camera); - inline OpenGLFunctions* getOpenGlFunctions() const {return functions;} - inline OpenGLSharedState* getSharedState() const {return shared_state;} + inline OpenGLFunctions *getOpenGlFunctions() const { + return functions; + } + inline OpenGLSharedState *getSharedState() const { + return shared_state; + } virtual double getPrecision(const Vector3 &location) override; virtual Color applyMediumTraversal(const Vector3 &location, const Color &color) override; -private: + private: /** * Update the mouse_projected member. */ void updateMouseProjection(); -private: + private: bool ready; bool paused; bool displayed; @@ -87,14 +98,13 @@ private: QMatrix4x4 *view_matrix; - OpenGLFunctions* functions; - OpenGLSharedState* shared_state; + OpenGLFunctions *functions; + OpenGLSharedState *shared_state; - OpenGLSkybox* skybox; - OpenGLWater* water; - OpenGLTerrain* terrain; + OpenGLSkybox *skybox; + OpenGLWater *water; + OpenGLTerrain *terrain; }; - } } diff --git a/src/render/opengl/OpenGLShaderProgram.cpp b/src/render/opengl/OpenGLShaderProgram.cpp index 014a885..817b97f 100644 --- a/src/render/opengl/OpenGLShaderProgram.cpp +++ b/src/render/opengl/OpenGLShaderProgram.cpp @@ -11,64 +11,50 @@ #include "Color.h" #include "Logs.h" -OpenGLShaderProgram::OpenGLShaderProgram(const std::string &name, OpenGLRenderer* renderer): - renderer(renderer), name(name) -{ +OpenGLShaderProgram::OpenGLShaderProgram(const std::string &name, OpenGLRenderer *renderer) + : renderer(renderer), name(name) { program = new QOpenGLShaderProgram(); functions = renderer->getOpenGlFunctions(); compiled = false; } -OpenGLShaderProgram::~OpenGLShaderProgram() -{ +OpenGLShaderProgram::~OpenGLShaderProgram() { delete program; } -void OpenGLShaderProgram::addVertexSource(QString path) -{ +void OpenGLShaderProgram::addVertexSource(QString path) { QFile file(QString(":/shaders/%1.vert").arg(path)); - if (file.open(QIODevice::ReadOnly | QIODevice::Text)) - { + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { source_vertex += QString(file.readAll()).toStdString(); - } - else - { + } else { Logs::error() << "Can't open vertex file " << file.fileName().toStdString() << std::endl; } } -void OpenGLShaderProgram::addFragmentSource(QString path) -{ +void OpenGLShaderProgram::addFragmentSource(QString path) { QFile file(QString(":/shaders/%1.frag").arg(path)); - if (file.open(QIODevice::ReadOnly | QIODevice::Text)) - { + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { source_fragment += QString(file.readAll()).toStdString(); - } - else - { + } else { Logs::error() << "Can't open fragment file " << file.fileName().toStdString() << std::endl; } } -void OpenGLShaderProgram::compile() -{ +void OpenGLShaderProgram::compile() { program->addShaderFromSourceCode(QOpenGLShader::Vertex, QString::fromStdString(source_vertex)); program->addShaderFromSourceCode(QOpenGLShader::Fragment, QString::fromStdString(source_fragment)); - if (not program->link()) - { - Logs::warning() << "Error while compiling shader " << name << std::endl << program->log().toStdString() << std::endl; - } - else if (program->log().length() > 0) - { - Logs::debug() << "Shader " << name << " compilation output:" << std::endl << program->log().toStdString() << std::endl; + if (not program->link()) { + Logs::warning() << "Error while compiling shader " << name << std::endl + << program->log().toStdString() << std::endl; + } else if (program->log().length() > 0) { + Logs::debug() << "Shader " << name << " compilation output:" << std::endl + << program->log().toStdString() << std::endl; } } -void OpenGLShaderProgram::bind() -{ - if (not compiled) - { +void OpenGLShaderProgram::bind() { + if (not compiled) { compile(); compiled = true; } @@ -79,13 +65,11 @@ void OpenGLShaderProgram::bind() renderer->getSharedState()->apply(this, texture_unit); } -void OpenGLShaderProgram::release() -{ +void OpenGLShaderProgram::release() { program->release(); } -void OpenGLShaderProgram::drawTriangles(float* vertices, int triangle_count) -{ +void OpenGLShaderProgram::drawTriangles(float *vertices, int triangle_count) { bind(); GLuint vertex = program->attributeLocation("vertex"); @@ -99,8 +83,7 @@ void OpenGLShaderProgram::drawTriangles(float* vertices, int triangle_count) release(); } -void OpenGLShaderProgram::drawTriangleStrip(float* vertices, int vertex_count) -{ +void OpenGLShaderProgram::drawTriangleStrip(float *vertices, int vertex_count) { bind(); GLuint vertex = program->attributeLocation("vertex"); diff --git a/src/render/opengl/OpenGLShaderProgram.h b/src/render/opengl/OpenGLShaderProgram.h index 4ae814a..c833e5d 100644 --- a/src/render/opengl/OpenGLShaderProgram.h +++ b/src/render/opengl/OpenGLShaderProgram.h @@ -10,42 +10,44 @@ class QOpenGLShaderProgram; namespace paysages { namespace opengl { -class OPENGLSHARED_EXPORT OpenGLShaderProgram -{ -public: - OpenGLShaderProgram(const std::string &name, OpenGLRenderer* renderer); +class OPENGLSHARED_EXPORT OpenGLShaderProgram { + public: + OpenGLShaderProgram(const std::string &name, OpenGLRenderer *renderer); ~OpenGLShaderProgram(); void addVertexSource(QString path); void addFragmentSource(QString path); - void drawTriangles(float* vertices, int triangle_count); - void drawTriangleStrip(float* vertices, int vertex_count); + void drawTriangles(float *vertices, int triangle_count); + void drawTriangleStrip(float *vertices, int vertex_count); void bind(); void release(); - inline QOpenGLShaderProgram* getProgram() const {return program;} - inline OpenGLRenderer* getRenderer() const {return renderer;} + inline QOpenGLShaderProgram *getProgram() const { + return program; + } + inline OpenGLRenderer *getRenderer() const { + return renderer; + } -protected: + protected: friend class OpenGLVariable; -private: + private: void compile(); bool compiled; - OpenGLRenderer* renderer; + OpenGLRenderer *renderer; std::string name; - QOpenGLShaderProgram* program; - OpenGLFunctions* functions; + QOpenGLShaderProgram *program; + OpenGLFunctions *functions; std::string source_vertex; std::string source_fragment; }; - } } diff --git a/src/render/opengl/OpenGLSharedState.cpp b/src/render/opengl/OpenGLSharedState.cpp index b59951d..f374277 100644 --- a/src/render/opengl/OpenGLSharedState.cpp +++ b/src/render/opengl/OpenGLSharedState.cpp @@ -1,22 +1,17 @@ #include "OpenGLSharedState.h" -OpenGLSharedState::OpenGLSharedState() -{ +OpenGLSharedState::OpenGLSharedState() { } -void OpenGLSharedState::apply(OpenGLShaderProgram *program, int &texture_unit) -{ - for (const auto &pair : variables) - { +void OpenGLSharedState::apply(OpenGLShaderProgram *program, int &texture_unit) { + for (const auto &pair : variables) { pair.second->apply(program, texture_unit); } } -OpenGLVariable *OpenGLSharedState::get(const std::string &name) -{ - OpenGLVariable*& var = variables[name]; - if (var == 0) - { +OpenGLVariable *OpenGLSharedState::get(const std::string &name) { + OpenGLVariable *&var = variables[name]; + if (var == 0) { var = new OpenGLVariable(name); } return var; diff --git a/src/render/opengl/OpenGLSharedState.h b/src/render/opengl/OpenGLSharedState.h index 4cdd8e6..8e206c7 100644 --- a/src/render/opengl/OpenGLSharedState.h +++ b/src/render/opengl/OpenGLSharedState.h @@ -12,15 +12,14 @@ namespace opengl { /*! * \brief OpenGL variables that can be shared between shaders. */ -class OPENGLSHARED_EXPORT OpenGLSharedState -{ -public: +class OPENGLSHARED_EXPORT OpenGLSharedState { + public: OpenGLSharedState(); /*! * \brief Apply the stored variables to the bound program. */ - void apply(OpenGLShaderProgram* program, int &texture_unit); + void apply(OpenGLShaderProgram *program, int &texture_unit); /*! * \brief Get or create a variable in the state. @@ -28,20 +27,37 @@ public: OpenGLVariable *get(const std::string &name); // Shortcuts - inline void set(const std::string &name, const Texture2D *texture, bool repeat=false, bool color=true) {get(name)->set(texture, repeat, color);} - inline void set(const std::string &name, const Texture3D *texture, bool repeat=false, bool color=true) {get(name)->set(texture, repeat, color);} - inline void set(const std::string &name, const Texture4D *texture, bool repeat=false, bool color=true) {get(name)->set(texture, repeat, color);} - inline void set(const std::string &name, float value) {get(name)->set(value);} - inline void set(const std::string &name, const Vector3 &vector) {get(name)->set(vector);} - inline void set(const std::string &name, const QVector3D &vector) {get(name)->set(vector);} - inline void set(const std::string &name, const Matrix4 &matrix) {get(name)->set(matrix);} - inline void set(const std::string &name, const QMatrix4x4 &matrix) {get(name)->set(matrix);} - inline void set(const std::string &name, const Color &color) {get(name)->set(color);} + inline void set(const std::string &name, const Texture2D *texture, bool repeat = false, bool color = true) { + get(name)->set(texture, repeat, color); + } + inline void set(const std::string &name, const Texture3D *texture, bool repeat = false, bool color = true) { + get(name)->set(texture, repeat, color); + } + inline void set(const std::string &name, const Texture4D *texture, bool repeat = false, bool color = true) { + get(name)->set(texture, repeat, color); + } + inline void set(const std::string &name, float value) { + get(name)->set(value); + } + inline void set(const std::string &name, const Vector3 &vector) { + get(name)->set(vector); + } + inline void set(const std::string &name, const QVector3D &vector) { + get(name)->set(vector); + } + inline void set(const std::string &name, const Matrix4 &matrix) { + get(name)->set(matrix); + } + inline void set(const std::string &name, const QMatrix4x4 &matrix) { + get(name)->set(matrix); + } + inline void set(const std::string &name, const Color &color) { + get(name)->set(color); + } -private: - std::map variables; + private: + std::map variables; }; - } } diff --git a/src/render/opengl/OpenGLSkybox.cpp b/src/render/opengl/OpenGLSkybox.cpp index 5c45a7e..a59722b 100644 --- a/src/render/opengl/OpenGLSkybox.cpp +++ b/src/render/opengl/OpenGLSkybox.cpp @@ -10,19 +10,15 @@ #include "AtmosphereModelBruneton.h" #include "FloatNode.h" -OpenGLSkybox::OpenGLSkybox(OpenGLRenderer* renderer): - OpenGLPart(renderer) -{ +OpenGLSkybox::OpenGLSkybox(OpenGLRenderer *renderer) : OpenGLPart(renderer) { vertices = new float[14 * 3]; } -OpenGLSkybox::~OpenGLSkybox() -{ +OpenGLSkybox::~OpenGLSkybox() { delete[] vertices; } -void OpenGLSkybox::initialize() -{ +void OpenGLSkybox::initialize() { program = createShader("skybox"); program->addVertexSource("skybox"); program->addFragmentSource("atmosphere"); @@ -57,22 +53,19 @@ void OpenGLSkybox::initialize() renderer->getScenery()->getAtmosphere()->propSunRadius()->addWatcher(this, true); } -void OpenGLSkybox::update() -{ - SoftwareBrunetonAtmosphereRenderer* bruneton = (SoftwareBrunetonAtmosphereRenderer*)renderer->getAtmosphereRenderer(); +void OpenGLSkybox::update() { + SoftwareBrunetonAtmosphereRenderer *bruneton = + (SoftwareBrunetonAtmosphereRenderer *)renderer->getAtmosphereRenderer(); renderer->getSharedState()->set("transmittanceTexture", bruneton->getModel()->getTextureTransmittance()); renderer->getSharedState()->set("inscatterTexture", bruneton->getModel()->getTextureInscatter()); } -void OpenGLSkybox::render() -{ +void OpenGLSkybox::render() { program->drawTriangleStrip(vertices, 14); } -void OpenGLSkybox::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) -{ - if (node->getPath() == "/atmosphere/daytime") - { +void OpenGLSkybox::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) { + if (node->getPath() == "/atmosphere/daytime") { Vector3 sun_direction = renderer->getAtmosphereRenderer()->getSunDirection(false); renderer->getSharedState()->set("sunDirection", sun_direction); @@ -80,19 +73,16 @@ void OpenGLSkybox::nodeChanged(const DefinitionNode *node, const DefinitionDiff renderer->getSharedState()->set("sunColor", sun_color); renderer->getSharedState()->set("dayTime", renderer->getScenery()->getAtmosphere()->propDayTime()->getValue()); - } - else if (node->getPath() == "/atmosphere/humidity") - { - renderer->getSharedState()->set("atmosphereHumidity", renderer->getScenery()->getAtmosphere()->propHumidity()->getValue()); - } - else if (node->getPath() == "/atmosphere/sun_radius") - { - renderer->getSharedState()->set("sunRadius", renderer->getScenery()->getAtmosphere()->propSunRadius()->getValue()); + } else if (node->getPath() == "/atmosphere/humidity") { + renderer->getSharedState()->set("atmosphereHumidity", + renderer->getScenery()->getAtmosphere()->propHumidity()->getValue()); + } else if (node->getPath() == "/atmosphere/sun_radius") { + renderer->getSharedState()->set("sunRadius", + renderer->getScenery()->getAtmosphere()->propSunRadius()->getValue()); } } -void OpenGLSkybox::setVertex(int i, float x, float y, float z) -{ +void OpenGLSkybox::setVertex(int i, float x, float y, float z) { vertices[i * 3] = x; vertices[i * 3 + 1] = y; vertices[i * 3 + 2] = z; diff --git a/src/render/opengl/OpenGLSkybox.h b/src/render/opengl/OpenGLSkybox.h index 7b36cc8..794ee89 100644 --- a/src/render/opengl/OpenGLSkybox.h +++ b/src/render/opengl/OpenGLSkybox.h @@ -9,10 +9,9 @@ namespace paysages { namespace opengl { -class OPENGLSHARED_EXPORT OpenGLSkybox: public OpenGLPart, public DefinitionWatcher -{ -public: - OpenGLSkybox(OpenGLRenderer* renderer); +class OPENGLSHARED_EXPORT OpenGLSkybox : public OpenGLPart, public DefinitionWatcher { + public: + OpenGLSkybox(OpenGLRenderer *renderer); virtual ~OpenGLSkybox(); virtual void initialize() override; @@ -20,13 +19,13 @@ public: virtual void render() override; virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff) override; -private: + + private: void setVertex(int i, float x, float y, float z); - OpenGLShaderProgram* program; - float* vertices; + OpenGLShaderProgram *program; + float *vertices; }; - } } diff --git a/src/render/opengl/OpenGLTerrain.cpp b/src/render/opengl/OpenGLTerrain.cpp index 8df2fd8..b0cf055 100644 --- a/src/render/opengl/OpenGLTerrain.cpp +++ b/src/render/opengl/OpenGLTerrain.cpp @@ -13,20 +13,14 @@ #include "FloatNode.h" #include "FloatDiff.h" -class ChunkMaintenanceThreads:public ParallelPool -{ -public: - ChunkMaintenanceThreads(OpenGLTerrain* terrain): - terrain(terrain) - { +class ChunkMaintenanceThreads : public ParallelPool { + public: + ChunkMaintenanceThreads(OpenGLTerrain *terrain) : terrain(terrain) { } - virtual void work() override - { - while (running) - { - if (not terrain->isPaused()) - { + virtual void work() override { + while (running) { + if (not terrain->isPaused()) { terrain->performChunksMaintenance(); } @@ -34,29 +28,24 @@ public: } } -private: - OpenGLTerrain* terrain; + private: + OpenGLTerrain *terrain; }; -OpenGLTerrain::OpenGLTerrain(OpenGLRenderer *renderer): - OpenGLPart(renderer) -{ +OpenGLTerrain::OpenGLTerrain(OpenGLRenderer *renderer) : OpenGLPart(renderer) { work = new ChunkMaintenanceThreads(this); paused = false; } -OpenGLTerrain::~OpenGLTerrain() -{ +OpenGLTerrain::~OpenGLTerrain() { delete work; - for (int i = 0; i < _chunks.count(); i++) - { + for (int i = 0; i < _chunks.count(); i++) { delete _chunks[i]; } } -void OpenGLTerrain::initialize() -{ +void OpenGLTerrain::initialize() { // Prepare shader programs program = createShader("terrain"); program->addVertexSource("terrain"); @@ -69,13 +58,12 @@ void OpenGLTerrain::initialize() // Add terrain chunks int chunks = 12; double size = 800.0; - double chunksize = size / (double) chunks; + double chunksize = size / (double)chunks; double start = -size / 2.0; - for (int i = 0; i < chunks; i++) - { - for (int j = 0; j < chunks; j++) - { - ExplorerChunkTerrain* chunk = new ExplorerChunkTerrain(renderer, start + chunksize * (double) i, start + chunksize * (double) j, chunksize, chunks); + for (int i = 0; i < chunks; i++) { + for (int j = 0; j < chunks; j++) { + ExplorerChunkTerrain *chunk = new ExplorerChunkTerrain(renderer, start + chunksize * (double)i, + start + chunksize * (double)j, chunksize, chunks); _chunks.append(chunk); _updateQueue.append(chunk); } @@ -89,75 +77,59 @@ void OpenGLTerrain::initialize() renderer->getScenery()->getAtmosphere()->propDayTime()->addWatcher(this); } -void OpenGLTerrain::update() -{ - for (auto &chunk: _chunks) - { +void OpenGLTerrain::update() { + for (auto &chunk : _chunks) { chunk->askReset(true, true); } } -void OpenGLTerrain::render() -{ +void OpenGLTerrain::render() { program->bind(); - for (int i = 0; i < _chunks.count(); i++) - { + for (int i = 0; i < _chunks.count(); i++) { _chunks[i]->render(program->getProgram(), renderer->getOpenGlFunctions()); } program->release(); } -void OpenGLTerrain::interrupt() -{ - for (auto &chunk: _chunks) - { +void OpenGLTerrain::interrupt() { + for (auto &chunk : _chunks) { chunk->askInterrupt(); } } -void OpenGLTerrain::pause() -{ +void OpenGLTerrain::pause() { paused = true; interrupt(); } -void OpenGLTerrain::resume() -{ - for (auto &chunk: _chunks) - { +void OpenGLTerrain::resume() { + for (auto &chunk : _chunks) { chunk->askResume(); } paused = false; } -void OpenGLTerrain::resetTextures() -{ - for (auto &chunk: _chunks) - { +void OpenGLTerrain::resetTextures() { + for (auto &chunk : _chunks) { chunk->askReset(false, true); } } -static bool _cmpChunks(const ExplorerChunkTerrain* c1, const ExplorerChunkTerrain* c2) -{ +static bool _cmpChunks(const ExplorerChunkTerrain *c1, const ExplorerChunkTerrain *c2) { return c1->priority > c2->priority; } -void OpenGLTerrain::performChunksMaintenance() -{ - CameraDefinition* camera = renderer->getScenery()->getCamera(); - ExplorerChunkTerrain* chunk; +void OpenGLTerrain::performChunksMaintenance() { + CameraDefinition *camera = renderer->getScenery()->getCamera(); + ExplorerChunkTerrain *chunk; _lock_chunks.lock(); - if (_updateQueue.count() > 0) - { + if (_updateQueue.count() > 0) { chunk = _updateQueue.takeFirst(); _lock_chunks.unlock(); - } - else - { + } else { _lock_chunks.unlock(); return; } @@ -166,23 +138,17 @@ void OpenGLTerrain::performChunksMaintenance() _lock_chunks.lock(); _updateQueue.append(chunk); - for (int i = 0; i < _chunks.count(); i++) - { + for (int i = 0; i < _chunks.count(); i++) { _chunks[i]->updatePriority(camera); } qSort(_updateQueue.begin(), _updateQueue.end(), _cmpChunks); _lock_chunks.unlock(); } - -void OpenGLTerrain::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) -{ - if (node->getPath() == "/terrain/water_height") - { +void OpenGLTerrain::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) { + if (node->getPath() == "/terrain/water_height") { resetTextures(); - } - else if (node->getPath() == "/atmosphere/daytime") - { + } else if (node->getPath() == "/atmosphere/daytime") { resetTextures(); } } diff --git a/src/render/opengl/OpenGLTerrain.h b/src/render/opengl/OpenGLTerrain.h index b34fa56..b2850be 100644 --- a/src/render/opengl/OpenGLTerrain.h +++ b/src/render/opengl/OpenGLTerrain.h @@ -13,10 +13,9 @@ namespace paysages { namespace opengl { -class OPENGLSHARED_EXPORT OpenGLTerrain: public OpenGLPart, public DefinitionWatcher -{ -public: - OpenGLTerrain(OpenGLRenderer* renderer); +class OPENGLSHARED_EXPORT OpenGLTerrain : public OpenGLPart, public DefinitionWatcher { + public: + OpenGLTerrain(OpenGLRenderer *renderer); virtual ~OpenGLTerrain(); virtual void initialize() override; @@ -26,7 +25,9 @@ public: void pause(); void resume(); - inline bool isPaused() const { return paused; } + inline bool isPaused() const { + return paused; + } /** * Reset the color textures, without changing the tessellation. @@ -36,18 +37,17 @@ public: void performChunksMaintenance(); virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff) override; -private: - OpenGLShaderProgram* program; - ParallelPool* work; + private: + OpenGLShaderProgram *program; + + ParallelPool *work; bool paused; - QVector _chunks; - QList _updateQueue; + QVector _chunks; + QList _updateQueue; QMutex _lock_chunks; - }; - } } diff --git a/src/render/opengl/OpenGLVariable.cpp b/src/render/opengl/OpenGLVariable.cpp index dcde1b5..e1df6d6 100644 --- a/src/render/opengl/OpenGLVariable.cpp +++ b/src/render/opengl/OpenGLVariable.cpp @@ -12,27 +12,22 @@ #include "Texture3D.h" #include "Texture4D.h" -OpenGLVariable::OpenGLVariable(const std::string &name): - name(name) -{ +OpenGLVariable::OpenGLVariable(const std::string &name) : name(name) { type = TYPE_NONE; texture_toupload = false; texture_id = 0; } -void OpenGLVariable::apply(OpenGLShaderProgram *program, int &texture_unit) -{ - QOpenGLShaderProgram* pr = program->getProgram(); - OpenGLFunctions* functions = program->getRenderer()->getOpenGlFunctions(); +void OpenGLVariable::apply(OpenGLShaderProgram *program, int &texture_unit) { + QOpenGLShaderProgram *pr = program->getProgram(); + OpenGLFunctions *functions = program->getRenderer()->getOpenGlFunctions(); - if (texture_toupload) - { + if (texture_toupload) { uploadTexture(program->getRenderer()); texture_toupload = false; } - switch (type) - { + switch (type) { case TYPE_FLOAT: pr->setUniformValue(name.c_str(), value_float); break; @@ -63,8 +58,7 @@ void OpenGLVariable::apply(OpenGLShaderProgram *program, int &texture_unit) } } -void OpenGLVariable::set(const Texture2D *texture, bool repeat, bool color) -{ +void OpenGLVariable::set(const Texture2D *texture, bool repeat, bool color) { assert(type == TYPE_NONE or type == TYPE_TEXTURE_2D); type = TYPE_TEXTURE_2D; @@ -74,8 +68,7 @@ void OpenGLVariable::set(const Texture2D *texture, bool repeat, bool color) texture_color = color; } -void OpenGLVariable::set(const Texture3D *texture, bool repeat, bool color) -{ +void OpenGLVariable::set(const Texture3D *texture, bool repeat, bool color) { assert(type == TYPE_NONE or type == TYPE_TEXTURE_3D); type = TYPE_TEXTURE_3D; @@ -85,8 +78,7 @@ void OpenGLVariable::set(const Texture3D *texture, bool repeat, bool color) texture_color = color; } -void OpenGLVariable::set(const Texture4D *texture, bool repeat, bool color) -{ +void OpenGLVariable::set(const Texture4D *texture, bool repeat, bool color) { assert(type == TYPE_NONE or type == TYPE_TEXTURE_4D); type = TYPE_TEXTURE_4D; @@ -96,56 +88,48 @@ void OpenGLVariable::set(const Texture4D *texture, bool repeat, bool color) texture_color = color; } -void OpenGLVariable::set(float value) -{ +void OpenGLVariable::set(float value) { assert(type == TYPE_NONE or type == TYPE_FLOAT); type = TYPE_FLOAT; value_float = value; } -void OpenGLVariable::set(const Vector3 &vector) -{ +void OpenGLVariable::set(const Vector3 &vector) { set(QVector3D(vector.x, vector.y, vector.z)); } -void OpenGLVariable::set(const QVector3D &vector) -{ +void OpenGLVariable::set(const QVector3D &vector) { assert(type == TYPE_NONE or type == TYPE_VECTOR3); type = TYPE_VECTOR3; value_vector3 = vector; } -void OpenGLVariable::set(const Matrix4 &matrix) -{ +void OpenGLVariable::set(const Matrix4 &matrix) { set(matrix.toQMatrix()); } -void OpenGLVariable::set(const QMatrix4x4 &matrix) -{ +void OpenGLVariable::set(const QMatrix4x4 &matrix) { assert(type == TYPE_NONE or type == TYPE_MATRIX4); type = TYPE_MATRIX4; value_matrix4 = matrix; } -void OpenGLVariable::set(const Color &color) -{ +void OpenGLVariable::set(const Color &color) { assert(type == TYPE_NONE or type == TYPE_COLOR); type = TYPE_COLOR; value_color = QColor::fromRgbF(color.r, color.g, color.b); } -void OpenGLVariable::uploadTexture(OpenGLRenderer* renderer) -{ - OpenGLFunctions* functions = renderer->getOpenGlFunctions(); +void OpenGLVariable::uploadTexture(OpenGLRenderer *renderer) { + OpenGLFunctions *functions = renderer->getOpenGlFunctions(); assert(type == TYPE_TEXTURE_2D or type == TYPE_TEXTURE_3D or type == TYPE_TEXTURE_4D); - if (texture_id == 0) - { + if (texture_id == 0) { GLuint texid; functions->glGenTextures(1, &texid); texture_id = texid; @@ -158,23 +142,19 @@ void OpenGLVariable::uploadTexture(OpenGLRenderer* renderer) functions->glTexParameteri(textype, GL_TEXTURE_MAG_FILTER, GL_LINEAR); functions->glTexParameteri(textype, GL_TEXTURE_WRAP_S, texture_repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE); functions->glTexParameteri(textype, GL_TEXTURE_WRAP_T, texture_repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE); - if (textype == GL_TEXTURE_3D) - { + if (textype == GL_TEXTURE_3D) { functions->glTexParameteri(textype, GL_TEXTURE_WRAP_R, texture_repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE); } int dest_format = texture_color ? GL_RGBA : GL_RED; - if (type == TYPE_TEXTURE_2D) - { + if (type == TYPE_TEXTURE_2D) { int sx, sy; value_tex2d->getSize(&sx, &sy); - float* pixels = new float[sx * sy * 4]; - for (int x = 0; x < sx; x++) - { - for (int y = 0; y < sy; y++) - { - float* pixel = pixels + (y * sx + x) * 4; + float *pixels = new float[sx * sy * 4]; + for (int x = 0; x < sx; x++) { + for (int y = 0; y < sy; y++) { + float *pixel = pixels + (y * sx + x) * 4; Color col = value_tex2d->getPixel(x, y); pixel[0] = (float)col.r; pixel[1] = (float)col.g; @@ -185,19 +165,14 @@ void OpenGLVariable::uploadTexture(OpenGLRenderer* renderer) functions->glTexImage2D(GL_TEXTURE_2D, 0, dest_format, sx, sy, 0, GL_RGBA, GL_FLOAT, pixels); delete[] pixels; - } - else if (type == TYPE_TEXTURE_3D) - { + } else if (type == TYPE_TEXTURE_3D) { int sx, sy, sz; value_tex3d->getSize(&sx, &sy, &sz); - float* pixels = new float[sx * sy * sz * 4]; - for (int x = 0; x < sx; x++) - { - for (int y = 0; y < sy; y++) - { - for (int z = 0; z < sz; z++) - { - float* pixel = pixels + (z * (sx * sy) + y * sx + x) * 4; + float *pixels = new float[sx * sy * sz * 4]; + for (int x = 0; x < sx; x++) { + for (int y = 0; y < sy; y++) { + for (int z = 0; z < sz; z++) { + float *pixel = pixels + (z * (sx * sy) + y * sx + x) * 4; Color col = value_tex3d->getPixel(x, y, z); pixel[0] = (float)col.r; pixel[1] = (float)col.g; @@ -209,21 +184,15 @@ void OpenGLVariable::uploadTexture(OpenGLRenderer* renderer) functions->glTexImage3D(GL_TEXTURE_3D, 0, dest_format, sx, sy, sz, 0, GL_RGBA, GL_FLOAT, pixels); delete[] pixels; - } - else - { + } else { int sx, sy, sz, sw; value_tex4d->getSize(&sx, &sy, &sz, &sw); - float* pixels = new float[sx * sy * sz * sw * 4]; - for (int x = 0; x < sx; x++) - { - for (int y = 0; y < sy; y++) - { - for (int z = 0; z < sz; z++) - { - for (int w = 0; w < sw; w++) - { - float* pixel = pixels + (w * (sx * sy * sz) + z * (sx * sy) + y * sx + x) * 4; + float *pixels = new float[sx * sy * sz * sw * 4]; + for (int x = 0; x < sx; x++) { + for (int y = 0; y < sy; y++) { + for (int z = 0; z < sz; z++) { + for (int w = 0; w < sw; w++) { + float *pixel = pixels + (w * (sx * sy * sz) + z * (sx * sy) + y * sx + x) * 4; Color col = value_tex4d->getPixel(x, y, z, w); pixel[0] = (float)col.r; pixel[1] = (float)col.g; diff --git a/src/render/opengl/OpenGLVariable.h b/src/render/opengl/OpenGLVariable.h index 418c4f0..5da2869 100644 --- a/src/render/opengl/OpenGLVariable.h +++ b/src/render/opengl/OpenGLVariable.h @@ -13,9 +13,8 @@ namespace opengl { /*! * \brief OpenGL variable that can be bound to a uniform for shaders. */ -class OpenGLVariable -{ -public: +class OpenGLVariable { + public: typedef enum { TYPE_NONE, TYPE_TEXTURE_2D, @@ -27,14 +26,14 @@ public: TYPE_COLOR } OpenGLVariableType; -public: + public: OpenGLVariable(const std::string &name); void apply(OpenGLShaderProgram *program, int &texture_unit); - void set(const Texture2D *texture, bool repeat=false, bool color=true); - void set(const Texture3D *texture, bool repeat=false, bool color=true); - void set(const Texture4D *texture, bool repeat=false, bool color=true); + void set(const Texture2D *texture, bool repeat = false, bool color = true); + void set(const Texture3D *texture, bool repeat = false, bool color = true); + void set(const Texture4D *texture, bool repeat = false, bool color = true); void set(float value); void set(const Vector3 &vector); void set(const QVector3D &vector); @@ -42,10 +41,10 @@ public: void set(const QMatrix4x4 &matrix); void set(const Color &color); -protected: - void uploadTexture(OpenGLRenderer* renderer); + protected: + void uploadTexture(OpenGLRenderer *renderer); -private: + private: std::string name; OpenGLVariableType type; @@ -53,16 +52,15 @@ private: QColor value_color; QVector3D value_vector3; QMatrix4x4 value_matrix4; - const Texture2D* value_tex2d; - const Texture3D* value_tex3d; - const Texture4D* value_tex4d; + const Texture2D *value_tex2d; + const Texture3D *value_tex3d; + const Texture4D *value_tex4d; bool texture_toupload; bool texture_repeat; bool texture_color; unsigned int texture_id; }; - } } diff --git a/src/render/opengl/OpenGLWater.cpp b/src/render/opengl/OpenGLWater.cpp index 75068c9..257c432 100644 --- a/src/render/opengl/OpenGLWater.cpp +++ b/src/render/opengl/OpenGLWater.cpp @@ -12,20 +12,16 @@ #include "FloatDiff.h" #include "IntNode.h" -OpenGLWater::OpenGLWater(OpenGLRenderer *renderer): - OpenGLPart(renderer) -{ +OpenGLWater::OpenGLWater(OpenGLRenderer *renderer) : OpenGLPart(renderer) { vertices = new float[4 * 3]; enabled = true; } -OpenGLWater::~OpenGLWater() -{ +OpenGLWater::~OpenGLWater() { delete[] vertices; } -void OpenGLWater::initialize() -{ +void OpenGLWater::initialize() { program = createShader("water"); program->addVertexSource("water"); program->addFragmentSource("atmosphere"); @@ -46,8 +42,7 @@ void OpenGLWater::initialize() renderer->getScenery()->getWater()->propModel()->addWatcher(this, false); } -void OpenGLWater::update() -{ +void OpenGLWater::update() { WaterDefinition *water = renderer->getScenery()->getWater(); renderer->getSharedState()->set("waterMaterialColor", *water->material->base); renderer->getSharedState()->set("waterMaterialReflection", water->material->reflection); @@ -57,38 +52,29 @@ void OpenGLWater::update() renderer->getSharedState()->set("simplexSampler", NoiseFunctionSimplex::getNormalTexture(), true, true); } -void OpenGLWater::render() -{ - if (enabled) - { +void OpenGLWater::render() { + if (enabled) { program->drawTriangleStrip(vertices, 4); } } -void OpenGLWater::setVertex(int i, float x, float y, float z) -{ +void OpenGLWater::setVertex(int i, float x, float y, float z) { vertices[i * 3] = x; vertices[i * 3 + 1] = y; vertices[i * 3 + 2] = z; } -void OpenGLWater::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) -{ - if (node->getPath() == "/terrain/water_height") - { +void OpenGLWater::nodeChanged(const DefinitionNode *node, const DefinitionDiff *) { + if (node->getPath() == "/terrain/water_height") { renderer->getSharedState()->set("waterOffset", renderer->getScenery()->getTerrain()->getWaterOffset()); - } - else if (node->getPath() == "/water/reflection") - { - renderer->getSharedState()->set("waterReflection", renderer->getScenery()->getWater()->propReflection()->getValue()); - } - else if (node->getPath() == "/water/model") - { + } else if (node->getPath() == "/water/reflection") { + renderer->getSharedState()->set("waterReflection", + renderer->getScenery()->getWater()->propReflection()->getValue()); + } else if (node->getPath() == "/water/model") { update(); } } -void OpenGLWater::setEnabled(bool enabled) -{ +void OpenGLWater::setEnabled(bool enabled) { this->enabled = enabled; } diff --git a/src/render/opengl/OpenGLWater.h b/src/render/opengl/OpenGLWater.h index 0edaf13..ed968ad 100644 --- a/src/render/opengl/OpenGLWater.h +++ b/src/render/opengl/OpenGLWater.h @@ -9,10 +9,9 @@ namespace paysages { namespace opengl { -class OPENGLSHARED_EXPORT OpenGLWater: public OpenGLPart, public DefinitionWatcher -{ -public: - OpenGLWater(OpenGLRenderer* renderer); +class OPENGLSHARED_EXPORT OpenGLWater : public OpenGLPart, public DefinitionWatcher { + public: + OpenGLWater(OpenGLRenderer *renderer); virtual ~OpenGLWater(); virtual void initialize() override; @@ -25,14 +24,14 @@ public: * Enable or disable the water surface rendering. */ void setEnabled(bool enabled); -private: + + private: void setVertex(int i, float x, float y, float z); bool enabled; - OpenGLShaderProgram* program; - float* vertices; + OpenGLShaderProgram *program; + float *vertices; }; - } } diff --git a/src/render/opengl/VertexArray.h b/src/render/opengl/VertexArray.h index 2d47307..5c3a91d 100644 --- a/src/render/opengl/VertexArray.h +++ b/src/render/opengl/VertexArray.h @@ -13,11 +13,9 @@ namespace opengl { /*! * Wrapper for OpenGL vertex arrays. */ -template class VertexArray -{ -public: - VertexArray() - { +template class VertexArray { + public: + VertexArray() { ready = false; changed = false; vertex_count = 1; @@ -26,19 +24,25 @@ public: indices = new unsigned short[1]; } - ~VertexArray() - { + ~VertexArray() { delete[] vertices; delete[] indices; } - inline int getVertexCount() {return vertex_count;} - inline int getIndexCount() {return index_count;} - inline bool isReady() {return ready;} - inline bool isChanged() {return changed;} + inline int getVertexCount() { + return vertex_count; + } + inline int getIndexCount() { + return index_count; + } + inline bool isReady() { + return ready; + } + inline bool isChanged() { + return changed; + } - void setVertexCount(int count) - { + void setVertexCount(int count) { assert(count > 0 and count <= 16384); delete[] vertices; @@ -47,15 +51,13 @@ public: vertex_count = count; } - void setGridSize(int edge_vertex_count) - { + void setGridSize(int edge_vertex_count) { assert(edge_vertex_count >= 2); setVertexCount(edge_vertex_count * edge_vertex_count); } - void setVertex(int position, const Vertex &vertex) - { + void setVertex(int position, const Vertex &vertex) { assert(position >= 0 and position < vertex_count); vertices[position] = vertex; @@ -63,13 +65,11 @@ public: changed = true; } - void setGridVertex(int edge_vertex_count, int x, int y, const Vertex &vertex) - { + void setGridVertex(int edge_vertex_count, int x, int y, const Vertex &vertex) { setVertex(y * edge_vertex_count + x, vertex); } - void setAutoGridIndices(int edge_vertex_count, int stride=1) - { + void setAutoGridIndices(int edge_vertex_count, int stride = 1) { assert(stride >= 1); delete[] indices; @@ -79,10 +79,8 @@ public: indices = new unsigned short[index_count]; int idx = 0; - for (int y = 0; y < cell_count; y += stride) - { - for (int x = 0; x < cell_count; x += stride) - { + for (int y = 0; y < cell_count; y += stride) { + for (int x = 0; x < cell_count; x += stride) { int base = y * edge_vertex_count + x; indices[idx++] = base; indices[idx++] = base + edge_vertex_count * stride; @@ -94,42 +92,37 @@ public: } } - Vertex getVertex(int position) - { + Vertex getVertex(int position) { assert(position >= 0 and position < vertex_count); return vertices[position]; } - Vertex getVertexByIndex(unsigned short index) - { + Vertex getVertexByIndex(unsigned short index) { assert(index >= 0 and index < index_count); return getVertex(indices[index]); } - Vertex getGridVertex(int edge_vertex_count, int x, int y) - { + Vertex getGridVertex(int edge_vertex_count, int x, int y) { return getVertex(y * edge_vertex_count + x); } - unsigned short getIndex(int position) - { + unsigned short getIndex(int position) { assert(position >= 0 and position < index_count); return indices[position]; } - void render(QOpenGLShaderProgram* program, OpenGLFunctions* functions) - { + void render(QOpenGLShaderProgram *program, OpenGLFunctions *functions) { size_t ptr = (size_t)vertices; GLuint vertex = program->attributeLocation("vertex"); - program->setAttributeArray(vertex, GL_FLOAT, (void*)(ptr + offsetof(Vertex, location)), 3, sizeof(Vertex)); + program->setAttributeArray(vertex, GL_FLOAT, (void *)(ptr + offsetof(Vertex, location)), 3, sizeof(Vertex)); program->enableAttributeArray(vertex); GLuint uv = program->attributeLocation("uv"); - program->setAttributeArray(uv, GL_FLOAT, (void*)(ptr + offsetof(Vertex, uv)), 2, sizeof(Vertex)); + program->setAttributeArray(uv, GL_FLOAT, (void *)(ptr + offsetof(Vertex, uv)), 2, sizeof(Vertex)); program->enableAttributeArray(uv); functions->glDrawRangeElements(GL_TRIANGLES, 0, vertex_count - 1, index_count, GL_UNSIGNED_SHORT, indices); @@ -138,17 +131,16 @@ public: program->disableAttributeArray(uv); } -private: + private: bool ready; bool changed; int vertex_count; - Vertex* vertices; + Vertex *vertices; int index_count; - unsigned short* indices; + unsigned short *indices; }; - } } diff --git a/src/render/opengl/opengl_global.h b/src/render/opengl/opengl_global.h index 1150545..cd956ea 100644 --- a/src/render/opengl/opengl_global.h +++ b/src/render/opengl/opengl_global.h @@ -4,25 +4,25 @@ #include #if defined(OPENGL_LIBRARY) -# define OPENGLSHARED_EXPORT Q_DECL_EXPORT +#define OPENGLSHARED_EXPORT Q_DECL_EXPORT #else -# define OPENGLSHARED_EXPORT Q_DECL_IMPORT +#define OPENGLSHARED_EXPORT Q_DECL_IMPORT #endif #include "software_global.h" namespace paysages { namespace opengl { - class WidgetExplorer; - class OpenGLRenderer; - class OpenGLShaderProgram; - class OpenGLSharedState; - class OpenGLVariable; - class OpenGLSkybox; - class OpenGLWater; - class OpenGLTerrain; - class ExplorerChunkTerrain; - template class VertexArray; +class WidgetExplorer; +class OpenGLRenderer; +class OpenGLShaderProgram; +class OpenGLSharedState; +class OpenGLVariable; +class OpenGLSkybox; +class OpenGLWater; +class OpenGLTerrain; +class ExplorerChunkTerrain; +template class VertexArray; } } using namespace paysages::opengl; diff --git a/src/render/software/AtmosphereModelBruneton.cpp b/src/render/software/AtmosphereModelBruneton.cpp index c387ff1..459239f 100644 --- a/src/render/software/AtmosphereModelBruneton.cpp +++ b/src/render/software/AtmosphereModelBruneton.cpp @@ -70,9 +70,9 @@ static const double AVERAGE_GROUND_REFLECTANCE = 0.1; #define INSCATTER_SPHERICAL_INTEGRAL_SAMPLES 8 #endif -Texture2D* _transmittanceTexture = NULL; -Texture2D* _irradianceTexture = NULL; -Texture4D* _inscatterTexture = NULL; +Texture2D *_transmittanceTexture = NULL; +Texture2D *_irradianceTexture = NULL; +Texture4D *_inscatterTexture = NULL; /* Rayleigh */ static const double HR = 8.0; @@ -97,56 +97,63 @@ static const double mieG = 0.65;*/ /*********************** Shader helpers ***********************/ -#define step(_a_,_b_) ((_b_) < (_a_) ? 0.0 : 1.0) +#define step(_a_, _b_) ((_b_) < (_a_) ? 0.0 : 1.0) #define sign(_a_) ((_a_) < 0.0 ? -1.0 : ((_a_) > 0.0 ? 1.0 : 0.0)) -#define mix(_x_,_y_,_a_) ((_x_) * (1.0 - (_a_)) + (_y_) * (_a_)) -static inline double min(double a, double b) -{ +#define mix(_x_, _y_, _a_) ((_x_) * (1.0 - (_a_)) + (_y_) * (_a_)) +static inline double min(double a, double b) { return a < b ? a : b; } -static inline double max(double a, double b) -{ +static inline double max(double a, double b) { return a > b ? a : b; } -static inline Color vec4mix(Color v1, Color v2, double a) -{ +static inline Color vec4mix(Color v1, Color v2, double a) { v1.r = mix(v1.r, v2.r, a); v1.g = mix(v1.g, v2.g, a); v1.b = mix(v1.b, v2.b, a); v1.a = mix(v1.a, v2.a, a); return v1; } -static inline double clamp(double x, double minVal, double maxVal) -{ - if (x < minVal) - { +static inline double clamp(double x, double minVal, double maxVal) { + if (x < minVal) { x = minVal; } return (x > maxVal) ? maxVal : x; } -static inline double smoothstep(double edge0, double edge1, double x) -{ +static inline double smoothstep(double edge0, double edge1, double x) { double t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0); return t * t * (3.0 - 2.0 * t); } -static inline void _fixVec4Min(Color* vec, double minVal) -{ - if (vec->r < minVal) { vec->r = minVal; } - if (vec->g < minVal) { vec->g = minVal; } - if (vec->b < minVal) { vec->b = minVal; } - if (vec->a < minVal) { vec->a = minVal; } +static inline void _fixVec4Min(Color *vec, double minVal) { + if (vec->r < minVal) { + vec->r = minVal; + } + if (vec->g < minVal) { + vec->g = minVal; + } + if (vec->b < minVal) { + vec->b = minVal; + } + if (vec->a < minVal) { + vec->a = minVal; + } } -static inline Color vec4max(Color vec, double minVal) -{ - if (vec.r < minVal) { vec.r = minVal; } - if (vec.g < minVal) { vec.g = minVal; } - if (vec.b < minVal) { vec.b = minVal; } - if (vec.a < minVal) { vec.a = minVal; } +static inline Color vec4max(Color vec, double minVal) { + if (vec.r < minVal) { + vec.r = minVal; + } + if (vec.g < minVal) { + vec.g = minVal; + } + if (vec.b < minVal) { + vec.b = minVal; + } + if (vec.a < minVal) { + vec.a = minVal; + } return vec; } -static inline Vector3 vec3(double x, double y, double z) -{ +static inline Vector3 vec3(double x, double y, double z) { Vector3 result; result.x = x; result.y = y; @@ -154,8 +161,7 @@ static inline Vector3 vec3(double x, double y, double z) return result; } -static inline Color vec4(double r, double g, double b, double a) -{ +static inline Color vec4(double r, double g, double b, double a) { Color result; result.r = r; result.g = g; @@ -166,17 +172,20 @@ static inline Color vec4(double r, double g, double b, double a) /*********************** Texture manipulation ***********************/ -static Color _texture4D(Texture4D* tex, double r, double mu, double muS, double nu) -{ - if (r < Rg + 0.00000001) r = Rg + 0.00000001; +static Color _texture4D(Texture4D *tex, double r, double mu, double muS, double nu) { + if (r < Rg + 0.00000001) + r = Rg + 0.00000001; double H = sqrt(Rt * Rt - Rg * Rg); double rho = sqrt(r * r - Rg * Rg); double rmu = r * mu; double delta = rmu * rmu - r * r + Rg * Rg; - Color cst = (rmu < 0.0 && delta > 0.0) ? vec4(1.0, 0.0, 0.0, 0.5 - 0.5 / (double)(RES_MU)) : vec4(-1.0, H * H, H, 0.5 + 0.5 / (double)(RES_MU)); + Color cst = (rmu < 0.0 && delta > 0.0) ? vec4(1.0, 0.0, 0.0, 0.5 - 0.5 / (double)(RES_MU)) + : vec4(-1.0, H * H, H, 0.5 + 0.5 / (double)(RES_MU)); double uR = 0.5 / (double)(RES_R) + rho / H * (1.0 - 1.0 / (double)(RES_R)); double uMu = cst.a + (rmu * cst.r + sqrt(delta + cst.g)) / (rho + cst.b) * (0.5 - 1.0 / (double)(RES_MU)); - double uMuS = 0.5 / (double)(RES_MU_S) + (atan(max(muS, -0.1975) * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5 * (1.0 - 1.0 / (double)(RES_MU_S)); + double uMuS = + 0.5 / (double)(RES_MU_S) + + (atan(max(muS, -0.1975) * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5 * (1.0 - 1.0 / (double)(RES_MU_S)); return tex->getLinear(uMu, uMuS, nu, uR); } @@ -184,20 +193,18 @@ static Color _texture4D(Texture4D* tex, double r, double mu, double muS, double /*********************** Physics functions ***********************/ /* Rayleigh phase function */ -static double _phaseFunctionR(double mu) -{ +static double _phaseFunctionR(double mu) { return (3.0 / (16.0 * M_PI)) * (1.0 + mu * mu); } /* Mie phase function */ -static double _phaseFunctionM(double mu) -{ - return 1.5 * 1.0 / (4.0 * M_PI) * (1.0 - mieG * mieG) * pow(1.0 + (mieG * mieG) - 2.0 * mieG * mu, -3.0 / 2.0) * (1.0 + mu * mu) / (2.0 + mieG * mieG); +static double _phaseFunctionM(double mu) { + return 1.5 * 1.0 / (4.0 * M_PI) * (1.0 - mieG * mieG) * pow(1.0 + (mieG * mieG) - 2.0 * mieG * mu, -3.0 / 2.0) * + (1.0 + mu * mu) / (2.0 + mieG * mieG); } /* approximated single Mie scattering (cf. approximate Cm in paragraph "Angular precision") */ -static Color _getMie(Color rayMie) -{ +static Color _getMie(Color rayMie) { Color result; result.r = rayMie.r * rayMie.a / max(rayMie.r, 1e-4) * (betaR.r / betaR.r); @@ -211,8 +218,7 @@ static Color _getMie(Color rayMie) /* optical depth for ray (r,mu) of length d, using analytic formula (mu=cos(view zenith angle)), intersections with ground ignored H=height scale of exponential density function */ -static double _opticalDepth(double H, double r, double mu, double d) -{ +static double _opticalDepth(double H, double r, double mu, double d) { double a = sqrt((0.5 / H) * r); double ax = a * (mu); double ay = a * (mu + d / r); @@ -226,9 +232,9 @@ static double _opticalDepth(double H, double r, double mu, double d) return sqrt((6.2831 * H) * r) * exp((Rg - r) / H) * (x + yx - yy); } -static inline void _getTransmittanceUV(double r, double mu, double* u, double* v) -{ - if (r < Rg + 0.00000001) r = Rg + 0.00000001; +static inline void _getTransmittanceUV(double r, double mu, double *u, double *v) { + if (r < Rg + 0.00000001) + r = Rg + 0.00000001; double dr = (r - Rg) / (Rt - Rg); *v = sqrt(dr); *u = atan((mu + 0.15) / (1.0 + 0.15) * tan(1.5)) / 1.5; @@ -236,8 +242,7 @@ static inline void _getTransmittanceUV(double r, double mu, double* u, double* v /* transmittance(=transparency) of atmosphere for infinite ray (r,mu) (mu=cos(view zenith angle)), intersections with ground ignored */ -static Color _transmittance(double r, double mu) -{ +static Color _transmittance(double r, double mu) { double u, v; _getTransmittanceUV(r, mu, &u, &v); return _transmittanceTexture->getLinear(u, v); @@ -246,18 +251,14 @@ static Color _transmittance(double r, double mu) /* transmittance(=transparency) of atmosphere between x and x0 * assume segment x,x0 not intersecting ground * d = distance between x and x0, mu=cos(zenith angle of [x,x0) ray at x) */ -static Color _transmittance3(double r, double mu, double d) -{ +static Color _transmittance3(double r, double mu, double d) { Color result, t1, t2; double r1 = sqrt(r * r + d * d + 2.0 * r * mu * d); double mu1 = (r * mu + d) / r1; - if (mu > 0.0) - { + if (mu > 0.0) { t1 = _transmittance(r, mu); t2 = _transmittance(r1, mu1); - } - else - { + } else { t1 = _transmittance(r1, -mu1); t2 = _transmittance(r, -mu); } @@ -268,20 +269,17 @@ static Color _transmittance3(double r, double mu, double d) return result; } -static void _getIrradianceRMuS(double x, double y, double* r, double* muS) -{ - *r = Rg + y * (Rt - Rg); - *muS = -0.2 + x * (1.0 + 0.2); +static void _getIrradianceRMuS(double x, double y, double *r, double *muS) { + *r = Rg + y *(Rt - Rg); + *muS = -0.2 + x *(1.0 + 0.2); } /* nearest intersection of ray r,mu with ground or top atmosphere boundary * mu=cos(ray zenith angle at ray origin) */ -static double _limit(double r, double mu) -{ +static double _limit(double r, double mu) { double dout = -r * mu + sqrt(r * r * (mu * mu - 1.0) + RL * RL); double delta2 = r * r * (mu * mu - 1.0) + Rg * Rg; - if (delta2 >= 0.0) - { + if (delta2 >= 0.0) { double din = -r * mu - sqrt(delta2); if (din >= 0.0) { dout = min(dout, din); @@ -293,8 +291,7 @@ static double _limit(double r, double mu) /* transmittance(=transparency) of atmosphere for ray (r,mu) of length d (mu=cos(view zenith angle)), intersections with ground ignored uses analytic formula instead of transmittance texture */ -static Vector3 _analyticTransmittance(double r, double mu, double d) -{ +static Vector3 _analyticTransmittance(double r, double mu, double d) { Vector3 result; result.x = exp(-betaR.r * _opticalDepth(HR, r, mu, d) - betaMEx.x * _opticalDepth(HM, r, mu, d)); @@ -306,28 +303,24 @@ static Vector3 _analyticTransmittance(double r, double mu, double d) /* transmittance(=transparency) of atmosphere for infinite ray (r,mu) (mu=cos(view zenith angle)), or zero if ray intersects ground */ -static Color _transmittanceWithShadow(double r, double mu) -{ +static Color _transmittanceWithShadow(double r, double mu) { return mu < -sqrt(1.0 - (Rg / r) * (Rg / r)) ? COLOR_BLACK : _transmittance(r, mu); } -static void _texCoordToMuMuSNu(double x, double y, double z, double r, Color dhdH, double* mu, double* muS, double* nu) -{ +static void _texCoordToMuMuSNu(double x, double y, double z, double r, Color dhdH, double *mu, double *muS, + double *nu) { double d; x /= (double)RES_MU; y /= (double)RES_MU_S; z /= (double)RES_NU; - if (x < 0.5) - { + if (x < 0.5) { d = 1.0 - x / 0.5; d = min(max(dhdH.b, d * dhdH.a), dhdH.a * 0.999); *mu = (Rg * Rg - r * r - d * d) / (2.0 * r * d); *mu = min(*mu, -sqrt(1.0 - (Rg / r) * (Rg / r)) - 0.001); - } - else - { + } else { d = (x - 0.5) / 0.5; d = min(max(dhdH.r, d * dhdH.g), dhdH.g * 0.999); *mu = (Rt * Rt - r * r - d * d) / (2.0 * r * d); @@ -336,14 +329,12 @@ static void _texCoordToMuMuSNu(double x, double y, double z, double r, Color dhd *nu = -1.0 + z / 2.0; } -static void _getIrradianceUV(double r, double muS, double* uMuS, double* uR) -{ +static void _getIrradianceUV(double r, double muS, double *uMuS, double *uR) { *uR = (r - Rg) / (Rt - Rg); *uMuS = (muS + 0.2) / (1.0 + 0.2); } -static Color _irradiance(Texture2D* sampler, double r, double muS) -{ +static Color _irradiance(Texture2D *sampler, double r, double muS) { double u, v; _getIrradianceUV(r, muS, &u, &v); return sampler->getLinear(u, v); @@ -351,14 +342,12 @@ static Color _irradiance(Texture2D* sampler, double r, double muS) /*********************** transmittance.glsl ***********************/ -static void _getTransmittanceRMu(double x, double y, double* r, double* muS) -{ +static void _getTransmittanceRMu(double x, double y, double *r, double *muS) { *r = Rg + (y * y) * (Rt - Rg); *muS = -0.15 + tan(1.5 * x) / tan(1.5) * (1.0 + 0.15); } -static double _opticalDepthTransmittance(double H, double r, double mu) -{ +static double _opticalDepthTransmittance(double H, double r, double mu) { double result = 0.0; double dx = _limit(r, mu) / (double)TRANSMITTANCE_INTEGRAL_SAMPLES; double yi = exp(-(r - Rg) / H); @@ -372,14 +361,11 @@ static double _opticalDepthTransmittance(double H, double r, double mu) return mu < -sqrt(1.0 - (Rg / r) * (Rg / r)) ? 1e9 : result; } -static void _precomputeTransmittanceTexture() -{ +static void _precomputeTransmittanceTexture() { int x, y; - for (x = 0; x < TRANSMITTANCE_W; x++) - { - for (y = 0; y < TRANSMITTANCE_H; y++) - { + for (x = 0; x < TRANSMITTANCE_W; x++) { + for (y = 0; y < TRANSMITTANCE_H; y++) { double r, muS; _getTransmittanceRMu((double)(x + 0.5) / TRANSMITTANCE_W, (double)(y + 0.5) / TRANSMITTANCE_H, &r, &muS); double depth1 = _opticalDepthTransmittance(HR, r, muS); @@ -396,15 +382,12 @@ static void _precomputeTransmittanceTexture() /*********************** irradiance1.glsl ***********************/ -static void _precomputeIrrDeltaETexture(Texture2D* destination) -{ +static void _precomputeIrrDeltaETexture(Texture2D *destination) { int x, y; /* Irradiance program */ - for (x = 0; x < SKY_W; x++) - { - for (y = 0; y < SKY_H; y++) - { + for (x = 0; x < SKY_W; x++) { + for (y = 0; y < SKY_H; y++) { double r, muS; Color trans, irr; _getIrradianceRMuS((double)x / SKY_W, (double)y / SKY_H, &r, &muS); @@ -420,8 +403,7 @@ static void _precomputeIrrDeltaETexture(Texture2D* destination) } } -static void _getLayerParams(int layer, double* _r, Color* _dhdH) -{ +static void _getLayerParams(int layer, double *_r, Color *_dhdH) { double r = layer / (RES_R - 1.0); r = r * r; r = sqrt(Rg * Rg + r * (Rt * Rt - Rg * Rg)) + (layer == 0 ? 0.01 : (layer == RES_R - 1 ? -0.001 : 0.0)); @@ -439,13 +421,11 @@ static void _getLayerParams(int layer, double* _r, Color* _dhdH) /*********************** inscatter1.glsl ***********************/ -static void _integrand1(double r, double mu, double muS, double nu, double t, Color* ray, Color* mie) -{ +static void _integrand1(double r, double mu, double muS, double nu, double t, Color *ray, Color *mie) { double ri = sqrt(r * r + t * t + 2.0 * r * mu * t); double muSi = (nu * t + muS * r) / ri; ri = max(Rg, ri); - if (muSi >= -sqrt(1.0 - Rg * Rg / (ri * ri))) - { + if (muSi >= -sqrt(1.0 - Rg * Rg / (ri * ri))) { Color t1, t2; t1 = _transmittance3(r, mu, t); t2 = _transmittance(ri, muSi); @@ -457,16 +437,13 @@ static void _integrand1(double r, double mu, double muS, double nu, double t, Co mie->r = fM * t1.r * t2.r; mie->g = fM * t1.g * t2.g; mie->b = fM * t1.b * t2.b; - } - else - { + } else { ray->r = ray->g = ray->b = 0.0; mie->r = mie->g = mie->b = 0.0; } } -static void _inscatter1(double r, double mu, double muS, double nu, Color* ray, Color* mie) -{ +static void _inscatter1(double r, double mu, double muS, double nu, Color *ray, Color *mie) { ray->r = ray->g = ray->b = 0.0; mie->r = mie->g = mie->b = 0.0; double dx = _limit(r, mu) / (double)(INSCATTER_INTEGRAL_SAMPLES); @@ -474,9 +451,8 @@ static void _inscatter1(double r, double mu, double muS, double nu, Color* ray, Color miei; _integrand1(r, mu, muS, nu, 0.0, &rayi, &miei); int i; - for (i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) - { - double xj = (double)(i) * dx; + for (i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { + double xj = (double)(i)*dx; Color rayj; Color miej; _integrand1(r, mu, muS, nu, xj, &rayj, &miej); @@ -497,27 +473,22 @@ static void _inscatter1(double r, double mu, double muS, double nu, Color* ray, mie->b *= betaMSca.z; } -typedef struct -{ - Texture4D* ray; - Texture4D* mie; +typedef struct { + Texture4D *ray; + Texture4D *mie; } Inscatter1Params; -static int _inscatter1Worker(ParallelWork*, int layer, void* data) -{ - Inscatter1Params* params = (Inscatter1Params*)data; +static int _inscatter1Worker(ParallelWork *, int layer, void *data) { + Inscatter1Params *params = (Inscatter1Params *)data; double r; Color dhdH; _getLayerParams(layer, &r, &dhdH); int x, y, z; - for (x = 0; x < RES_MU; x++) - { - for (y = 0; y < RES_MU_S; y++) - { - for (z = 0; z < RES_NU; z++) - { + for (x = 0; x < RES_MU; x++) { + for (y = 0; y < RES_MU_S; y++) { + for (z = 0; z < RES_NU; z++) { Color ray = COLOR_BLACK; Color mie = COLOR_BLACK; double mu, muS, nu; @@ -535,8 +506,8 @@ static int _inscatter1Worker(ParallelWork*, int layer, void* data) /*********************** inscatterS.glsl ***********************/ -static Color _inscatterS(double r, double mu, double muS, double nu, int first, Texture2D* deltaE, Texture4D* deltaSR, Texture4D* deltaSM) -{ +static Color _inscatterS(double r, double mu, double muS, double nu, int first, Texture2D *deltaE, Texture4D *deltaSR, + Texture4D *deltaSM) { Color raymie = COLOR_BLACK; double dphi = M_PI / (double)(INSCATTER_SPHERICAL_INTEGRAL_SAMPLES); @@ -556,16 +527,14 @@ static Color _inscatterS(double r, double mu, double muS, double nu, int first, /* integral over 4.PI around x with two nested loops over w directions (theta,phi) -- Eq (7) */ int itheta; - for (itheta = 0; itheta < INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++itheta) - { + for (itheta = 0; itheta < INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++itheta) { double theta = ((double)(itheta) + 0.5) * dtheta; double ctheta = cos(theta); double greflectance = 0.0; double dground = 0.0; Color gtransp = {0.0, 0.0, 0.0, 0.0}; - if (ctheta < cthetamin) - { + if (ctheta < cthetamin) { /* if ground visible in direction w * compute transparency gtransp between x and ground */ greflectance = AVERAGE_GROUND_REFLECTANCE / M_PI; @@ -574,8 +543,7 @@ static Color _inscatterS(double r, double mu, double muS, double nu, int first, } int iphi; - for (iphi = 0; iphi < 2 * INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++iphi) - { + for (iphi = 0; iphi < 2 * INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++iphi) { double phi = ((double)(iphi) + 0.5) * dphi; double dw = dtheta * dphi * sin(theta); Vector3 w = vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), ctheta); @@ -600,8 +568,7 @@ static Color _inscatterS(double r, double mu, double muS, double nu, int first, raymie1.b = greflectance * girradiance.b * gtransp.b; /* second term = inscattered light, =deltaS */ - if (first) - { + if (first) { /* first iteration is special because Rayleigh and Mie were stored separately, * without the phase functions factors; they must be reintroduced here */ double pr1 = _phaseFunctionR(nu1); @@ -611,9 +578,7 @@ static Color _inscatterS(double r, double mu, double muS, double nu, int first, raymie1.r += ray1.r * pr1 + mie1.r * pm1; raymie1.g += ray1.g * pr1 + mie1.g * pm1; raymie1.b += ray1.b * pr1 + mie1.b * pm1; - } - else - { + } else { Color col = _texture4D(deltaSR, r, w.z, muS, nu1); raymie1.r += col.r; raymie1.g += col.g; @@ -633,30 +598,25 @@ static Color _inscatterS(double r, double mu, double muS, double nu, int first, return raymie; } -typedef struct -{ - Texture4D* result; - Texture2D* deltaE; - Texture4D* deltaSR; - Texture4D* deltaSM; +typedef struct { + Texture4D *result; + Texture2D *deltaE; + Texture4D *deltaSR; + Texture4D *deltaSM; int first; } jParams; -static int _jWorker(ParallelWork*, int layer, void* data) -{ - jParams* params = (jParams*)data; +static int _jWorker(ParallelWork *, int layer, void *data) { + jParams *params = (jParams *)data; double r; Color dhdH; _getLayerParams(layer, &r, &dhdH); int x, y, z; - for (x = 0; x < RES_MU; x++) - { - for (y = 0; y < RES_MU_S; y++) - { - for (z = 0; z < RES_NU; z++) - { + for (x = 0; x < RES_MU; x++) { + for (y = 0; y < RES_MU_S; y++) { + for (z = 0; z < RES_NU; z++) { Color raymie; double mu, muS, nu; _texCoordToMuMuSNu((double)x, (double)y, (double)z, r, dhdH, &mu, &muS, &nu); @@ -670,15 +630,12 @@ static int _jWorker(ParallelWork*, int layer, void* data) /*********************** irradianceN.glsl ***********************/ -void _irradianceNProg(Texture2D* destination, Texture4D* deltaSR, Texture4D* deltaSM, int first) -{ +void _irradianceNProg(Texture2D *destination, Texture4D *deltaSR, Texture4D *deltaSM, int first) { int x, y; double dphi = M_PI / (double)(IRRADIANCE_INTEGRAL_SAMPLES); double dtheta = M_PI / (double)(IRRADIANCE_INTEGRAL_SAMPLES); - for (x = 0; x < SKY_W; x++) - { - for (y = 0; y < SKY_H; y++) - { + for (x = 0; x < SKY_W; x++) { + for (y = 0; y < SKY_H; y++) { double r, muS; int iphi; _getIrradianceRMuS((double)x / SKY_W, (double)y / SKY_H, &r, &muS); @@ -686,18 +643,15 @@ void _irradianceNProg(Texture2D* destination, Texture4D* deltaSR, Texture4D* del Color result = COLOR_BLACK; /* integral over 2.PI around x with two nested loops over w directions (theta,phi) -- Eq (15) */ - for (iphi = 0; iphi < 2 * IRRADIANCE_INTEGRAL_SAMPLES; ++iphi) - { + for (iphi = 0; iphi < 2 * IRRADIANCE_INTEGRAL_SAMPLES; ++iphi) { double phi = ((double)(iphi) + 0.5) * dphi; int itheta; - for (itheta = 0; itheta < IRRADIANCE_INTEGRAL_SAMPLES / 2; ++itheta) - { + for (itheta = 0; itheta < IRRADIANCE_INTEGRAL_SAMPLES / 2; ++itheta) { double theta = ((double)(itheta) + 0.5) * dtheta; double dw = dtheta * dphi * sin(theta); Vector3 w = vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); double nu = s.dotProduct(w); - if (first) - { + if (first) { /* first iteration is special because Rayleigh and Mie were stored separately, without the phase functions factors; they must be reintroduced here */ double pr1 = _phaseFunctionR(nu); @@ -707,9 +661,7 @@ void _irradianceNProg(Texture2D* destination, Texture4D* deltaSR, Texture4D* del result.r += (ray1.r * pr1 + mie1.r * pm1) * w.z * dw; result.g += (ray1.g * pr1 + mie1.g * pm1) * w.z * dw; result.b += (ray1.b * pr1 + mie1.b * pm1) * w.z * dw; - } - else - { + } else { Color col = _texture4D(deltaSR, r, w.z, muS, nu); result.r += col.r * w.z * dw; result.g += col.g * w.z * dw; @@ -725,14 +677,12 @@ void _irradianceNProg(Texture2D* destination, Texture4D* deltaSR, Texture4D* del /*********************** inscatterN.glsl ***********************/ -typedef struct -{ - Texture4D* destination; - Texture4D* deltaJ; +typedef struct { + Texture4D *destination; + Texture4D *deltaJ; } InscatterNParams; -static Color _integrand2(Texture4D* deltaJ, double r, double mu, double muS, double nu, double t) -{ +static Color _integrand2(Texture4D *deltaJ, double r, double mu, double muS, double nu, double t) { double ri = sqrt(r * r + t * t + 2.0 * r * mu * t); double mui = (r * mu + t) / ri; double muSi = (nu * t + muS * r) / ri; @@ -746,15 +696,13 @@ static Color _integrand2(Texture4D* deltaJ, double r, double mu, double muS, dou return c1; } -static Color _inscatterN(Texture4D* deltaJ, double r, double mu, double muS, double nu) -{ +static Color _inscatterN(Texture4D *deltaJ, double r, double mu, double muS, double nu) { Color raymie = COLOR_BLACK; double dx = _limit(r, mu) / (double)(INSCATTER_INTEGRAL_SAMPLES); Color raymiei = _integrand2(deltaJ, r, mu, muS, nu, 0.0); int i; - for (i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) - { - double xj = (double)(i) * dx; + for (i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { + double xj = (double)(i)*dx; Color raymiej = _integrand2(deltaJ, r, mu, muS, nu, xj); raymie.r += (raymiei.r + raymiej.r) / 2.0 * dx; raymie.g += (raymiei.g + raymiej.g) / 2.0 * dx; @@ -764,21 +712,17 @@ static Color _inscatterN(Texture4D* deltaJ, double r, double mu, double muS, dou return raymie; } -static int _inscatterNWorker(ParallelWork*, int layer, void* data) -{ - InscatterNParams* params = (InscatterNParams*)data; +static int _inscatterNWorker(ParallelWork *, int layer, void *data) { + InscatterNParams *params = (InscatterNParams *)data; double r; Color dhdH; _getLayerParams(layer, &r, &dhdH); int x, y, z; - for (x = 0; x < RES_MU; x++) - { - for (y = 0; y < RES_MU_S; y++) - { - for (z = 0; z < RES_NU; z++) - { + for (x = 0; x < RES_MU; x++) { + for (y = 0; y < RES_MU_S; y++) { + for (z = 0; z < RES_NU; z++) { double mu, muS, nu; _texCoordToMuMuSNu((double)x, (double)y, (double)z, r, dhdH, &mu, &muS, &nu); params->destination->setPixel(x, y, z, layer, _inscatterN(params->deltaJ, r, mu, muS, nu)); @@ -790,27 +734,22 @@ static int _inscatterNWorker(ParallelWork*, int layer, void* data) /*********************** copyInscatterN.glsl ***********************/ -typedef struct -{ - Texture4D* source; - Texture4D* destination; +typedef struct { + Texture4D *source; + Texture4D *destination; } CopyInscatterNParams; -static int _copyInscatterNWorker(ParallelWork*, int layer, void* data) -{ - CopyInscatterNParams* params = (CopyInscatterNParams*)data; +static int _copyInscatterNWorker(ParallelWork *, int layer, void *data) { + CopyInscatterNParams *params = (CopyInscatterNParams *)data; double r; Color dhdH; _getLayerParams(layer, &r, &dhdH); int x, y, z; - for (x = 0; x < RES_MU; x++) - { - for (y = 0; y < RES_MU_S; y++) - { - for (z = 0; z < RES_NU; z++) - { + for (x = 0; x < RES_MU; x++) { + for (y = 0; y < RES_MU_S; y++) { + for (z = 0; z < RES_NU; z++) { double mu, muS, nu; _texCoordToMuMuSNu((double)x, (double)y, (double)z, r, dhdH, &mu, &muS, &nu); Color col1 = params->source->getPixel(x, y, z, layer); @@ -827,8 +766,7 @@ static int _copyInscatterNWorker(ParallelWork*, int layer, void* data) /*********************** Final getters ***********************/ -static inline Color _applyInscatter(Color inscatter, Color attmod, Color samp) -{ +static inline Color _applyInscatter(Color inscatter, Color attmod, Color samp) { inscatter.r = inscatter.r - attmod.r * samp.r; inscatter.g = inscatter.g - attmod.g * samp.g; inscatter.b = inscatter.b - attmod.b * samp.b; @@ -837,15 +775,14 @@ static inline Color _applyInscatter(Color inscatter, Color attmod, Color samp) } /* inscattered light along ray x+tv, when sun in direction s (=S[L]-T(x,x0)S[L]|x0) */ -static Color _getInscatterColor(Vector3* _x, double* _t, Vector3 v, Vector3 s, double* _r, double* _mu, Vector3* attenuation) -{ +static Color _getInscatterColor(Vector3 *_x, double *_t, Vector3 v, Vector3 s, double *_r, double *_mu, + Vector3 *attenuation) { Color result; double r = _x->getNorm(); double mu = _x->dotProduct(v) / r; double d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); attenuation->x = attenuation->y = attenuation->z = 0.0; - if (d > 0.0) - { + if (d > 0.0) { /* if x in space and ray intersects atmosphere move x to nearest intersection of ray with top atmosphere boundary */ _x->x += d * v.x; @@ -857,16 +794,14 @@ static Color _getInscatterColor(Vector3* _x, double* _t, Vector3 v, Vector3 s, d } double t = *_t; Vector3 x = *_x; - if (r <= Rt) - { + if (r <= Rt) { /* if ray intersects atmosphere */ double nu = v.dotProduct(s); double muS = x.dotProduct(s) / r; double phaseR = _phaseFunctionR(nu); double phaseM = _phaseFunctionM(nu); Color inscatter = vec4max(_texture4D(_inscatterTexture, r, mu, muS, nu), 0.0); - if (t > 0.0) - { + if (t > 0.0) { Vector3 x0 = x.add(v.scale(t)); double r0 = x0.getNorm(); double rMu0 = x0.dotProduct(v); @@ -874,17 +809,16 @@ static Color _getInscatterColor(Vector3* _x, double* _t, Vector3 v, Vector3 s, d double muS0 = x0.dotProduct(s) / r0; /* avoids imprecision problems in transmittance computations based on textures */ *attenuation = _analyticTransmittance(r, mu, t); - if (r0 > Rg + 0.001) - { + if (r0 > Rg + 0.001) { /* computes S[L]-T(x,x0)S[L]|x0 */ Color attmod = {attenuation->x, attenuation->y, attenuation->z, attenuation->x}; Color samp = _texture4D(_inscatterTexture, r0, mu0, muS0, nu); inscatter = _applyInscatter(inscatter, attmod, samp); - /* avoids imprecision problems near horizon by interpolating between two points above and below horizon */ + /* avoids imprecision problems near horizon by interpolating between two points above and below horizon + */ const double EPS = 0.02; double muHoriz = -sqrt(1.0 - (Rg / r) * (Rg / r)); - if (fabs(mu - muHoriz) < EPS) - { + if (fabs(mu - muHoriz) < EPS) { double a = ((mu - muHoriz) + EPS) / (2.0 * EPS); mu = muHoriz - EPS; @@ -913,9 +847,7 @@ static Color _getInscatterColor(Vector3* _x, double* _t, Vector3 v, Vector3 s, d result.b = inscatter.b * phaseR + mie.b * phaseM; result.a = 1.0; _fixVec4Min(&result, 0.0); - } - else - { + } else { /* x in space and ray looking in space */ result = COLOR_BLACK; } @@ -930,8 +862,7 @@ static Color _getInscatterColor(Vector3* _x, double* _t, Vector3 v, Vector3 s, d } /* direct sun light for ray x+tv, when sun in direction s (=L0) */ -static Color _sunColor(Vector3 v, Vector3 s, double r, double mu, double radius) -{ +static Color _sunColor(Vector3 v, Vector3 s, double r, double mu, double radius) { Color transmittance = r <= Rt ? _transmittanceWithShadow(r, mu) : COLOR_WHITE; /* T(x,xo) */ double d = _limit(r, mu); radius *= (1.0 + 25.0 * d / Rt); /* Inflating due to lens effect near horizon */ @@ -945,103 +876,86 @@ static Color _sunColor(Vector3 v, Vector3 s, double r, double mu, double radius) /*********************** Cache/debug methods ***********************/ -static int _tryLoadCache2D(Texture2D* tex, const char* tag, int order) -{ +static int _tryLoadCache2D(Texture2D *tex, const char *tag, int order) { int xsize, ysize; tex->getSize(&xsize, &ysize); CacheFile cache("atmo-br", "cache", tag, xsize, ysize, 0, 0, order); - if (cache.isReadable()) - { + if (cache.isReadable()) { PackStream stream; stream.bindToFile(cache.getPath()); tex->load(&stream); return 1; - } - else - { + } else { return 0; } } -static void _saveCache2D(Texture2D* tex, const char* tag, int order) -{ +static void _saveCache2D(Texture2D *tex, const char *tag, int order) { int xsize, ysize; tex->getSize(&xsize, &ysize); CacheFile cache("atmo-br", "cache", tag, xsize, ysize, 0, 0, order); - if (cache.isWritable()) - { + if (cache.isWritable()) { PackStream stream; stream.bindToFile(cache.getPath()); tex->save(&stream); } } -static void _saveDebug2D(Texture2D* tex, const char* tag, int order) -{ +static void _saveDebug2D(Texture2D *tex, const char *tag, int order) { int xsize, ysize; tex->getSize(&xsize, &ysize); CacheFile cache("atmo-br", "png", tag, xsize, ysize, 0, 0, order); - if (cache.isWritable()) - { + if (cache.isWritable()) { tex->saveToFile(cache.getPath()); } } -static int _tryLoadCache4D(Texture4D* tex, const char* tag, int order) -{ +static int _tryLoadCache4D(Texture4D *tex, const char *tag, int order) { int xsize, ysize, zsize, wsize; tex->getSize(&xsize, &ysize, &zsize, &wsize); CacheFile cache("atmo-br", "cache", tag, xsize, ysize, zsize, wsize, order); - if (cache.isReadable()) - { + if (cache.isReadable()) { PackStream stream; stream.bindToFile(cache.getPath()); tex->load(&stream); return 1; - } - else - { + } else { return 0; } } -static void _saveCache4D(Texture4D* tex, const char* tag, int order) -{ +static void _saveCache4D(Texture4D *tex, const char *tag, int order) { int xsize, ysize, zsize, wsize; tex->getSize(&xsize, &ysize, &zsize, &wsize); CacheFile cache("atmo-br", "cache", tag, xsize, ysize, zsize, wsize, order); - if (cache.isWritable()) - { + if (cache.isWritable()) { PackStream stream; stream.bindToFile(cache.getPath()); tex->save(&stream); } } -static void _saveDebug4D(Texture4D* tex, const char* tag, int order) -{ +static void _saveDebug4D(Texture4D *tex, const char *tag, int order) { int xsize, ysize, zsize, wsize; tex->getSize(&xsize, &ysize, &zsize, &wsize); CacheFile cache("atmo-br", "png", tag, xsize, ysize, zsize, wsize, order); - if (cache.isWritable()) - { + if (cache.isWritable()) { tex->saveToFile(cache.getPath()); } } /*********************** Public methods ***********************/ -int brunetonInit() -{ +int brunetonInit() { int x, y, z, w, order; - ParallelWork* work; + ParallelWork *work; assert(_inscatterTexture == NULL); @@ -1051,17 +965,15 @@ int brunetonInit() _inscatterTexture = new Texture4D(RES_MU, RES_MU_S, RES_NU, RES_R); /* try loading from cache */ - if (_tryLoadCache2D(_transmittanceTexture, "transmittance", 0) - && _tryLoadCache2D(_irradianceTexture, "irradiance", 0) - && _tryLoadCache4D(_inscatterTexture, "inscatter", 0)) - { + if (_tryLoadCache2D(_transmittanceTexture, "transmittance", 0) && + _tryLoadCache2D(_irradianceTexture, "irradiance", 0) && _tryLoadCache4D(_inscatterTexture, "inscatter", 0)) { return 1; } - Texture2D* _deltaETexture = new Texture2D(SKY_W, SKY_H); - Texture4D* _deltaSMTexture = new Texture4D(RES_MU, RES_MU_S, RES_NU, RES_R); - Texture4D* _deltaSRTexture = new Texture4D(RES_MU, RES_MU_S, RES_NU, RES_R); - Texture4D* _deltaJTexture = new Texture4D(RES_MU, RES_MU_S, RES_NU, RES_R); + Texture2D *_deltaETexture = new Texture2D(SKY_W, SKY_H); + Texture4D *_deltaSMTexture = new Texture4D(RES_MU, RES_MU_S, RES_NU, RES_R); + Texture4D *_deltaSRTexture = new Texture4D(RES_MU, RES_MU_S, RES_NU, RES_R); + Texture4D *_deltaJTexture = new Texture4D(RES_MU, RES_MU_S, RES_NU, RES_R); /* computes transmittance texture T (line 1 in algorithm 4.1) */ _precomputeTransmittanceTexture(); @@ -1085,14 +997,10 @@ int brunetonInit() _irradianceTexture->fill(COLOR_BLACK); /* copies deltaS into inscatter texture S (line 5 in algorithm 4.1) */ - for (x = 0; x < RES_MU; x++) - { - for (y = 0; y < RES_MU_S; y++) - { - for (z = 0; z < RES_NU; z++) - { - for (w = 0; w < RES_R; w++) - { + for (x = 0; x < RES_MU; x++) { + for (y = 0; y < RES_MU_S; y++) { + for (z = 0; z < RES_NU; z++) { + for (w = 0; w < RES_R; w++) { Color result = _deltaSRTexture->getPixel(x, y, z, w); Color mie = _deltaSMTexture->getPixel(x, y, z, w); result.a = mie.r; @@ -1104,8 +1012,7 @@ int brunetonInit() _saveDebug4D(_inscatterTexture, "inscatter", 0); /* loop for each scattering order (line 6 in algorithm 4.1) */ - for (order = 2; order <= 4; ++order) - { + for (order = 2; order <= 4; ++order) { /* computes deltaJ (line 7 in algorithm 4.1) */ jParams jparams = {_deltaJTexture, _deltaETexture, _deltaSRTexture, _deltaSMTexture, order == 2}; work = new ParallelWork(_jWorker, RES_R, &jparams); @@ -1149,21 +1056,17 @@ int brunetonInit() static int _inited; -AtmosphereModelBruneton::AtmosphereModelBruneton(SoftwareRenderer *parent): - parent(parent) -{ - if (not _inited) - { +AtmosphereModelBruneton::AtmosphereModelBruneton(SoftwareRenderer *parent) : parent(parent) { + if (not _inited) { _inited = brunetonInit(); } } -AtmosphereModelBruneton::~AtmosphereModelBruneton() -{ +AtmosphereModelBruneton::~AtmosphereModelBruneton() { } -AtmosphereResult AtmosphereModelBruneton::getSkyColor(Vector3 eye, const Vector3 &direction, const Vector3 &sun_position, const Color &base) -{ +AtmosphereResult AtmosphereModelBruneton::getSkyColor(Vector3 eye, const Vector3 &direction, + const Vector3 &sun_position, const Color &base) { Vector3 x = {0.0, Rg + eye.y * WORLD_SCALING, 0.0}; Vector3 v = direction.normalize(); Vector3 s = sun_position.sub(x).normalize(); @@ -1174,7 +1077,8 @@ AtmosphereResult AtmosphereModelBruneton::getSkyColor(Vector3 eye, const Vector3 AtmosphereResult result; Vector3 attenuation; - Color sunColor = _sunColor(v, s, r, mu, parent->getScenery()->getAtmosphere()->propSunRadius()->getValue()); /* L0 */ + Color sunColor = + _sunColor(v, s, r, mu, parent->getScenery()->getAtmosphere()->propSunRadius()->getValue()); /* L0 */ /*result.base.r = base.r + sunColor.r; result.base.g = base.g + sunColor.g; @@ -1189,15 +1093,13 @@ AtmosphereResult AtmosphereModelBruneton::getSkyColor(Vector3 eye, const Vector3 return result; } -AtmosphereResult AtmosphereModelBruneton::applyAerialPerspective(Vector3 location, const Color &base) -{ +AtmosphereResult AtmosphereModelBruneton::applyAerialPerspective(Vector3 location, const Color &base) { Vector3 eye = parent->getCameraLocation(location); Vector3 sun_position = parent->getAtmosphereRenderer()->getSunDirection().scale(SUN_DISTANCE); Vector3 direction = location.sub(eye).scale(WORLD_SCALING); double t = direction.getNorm(); - if (t < 0.000001) - { + if (t < 0.000001) { direction = parent->getCameraDirection(location).scale(0.001 * WORLD_SCALING); t = direction.getNorm(); } @@ -1206,8 +1108,7 @@ AtmosphereResult AtmosphereModelBruneton::applyAerialPerspective(Vector3 locatio Vector3 v = direction.normalize(); Vector3 s = sun_position.sub(x).normalize(); - if (v.y == 0.0) - { + if (v.y == 0.0) { v.y = -0.000001; } @@ -1229,8 +1130,7 @@ AtmosphereResult AtmosphereModelBruneton::applyAerialPerspective(Vector3 locatio return result; } -bool AtmosphereModelBruneton::getLightsAt(std::vector &result, const Vector3 &location) const -{ +bool AtmosphereModelBruneton::getLightsAt(std::vector &result, const Vector3 &location) const { LightComponent sun, irradiance; double muS; @@ -1243,12 +1143,9 @@ bool AtmosphereModelBruneton::getLightsAt(std::vector &result, c Vector3 s = sun_position.sub(x).normalize(); muS = up.dotProduct(s); - if (altitude > RL) - { + if (altitude > RL) { sun.color = parent->getScenery()->getAtmosphere()->sun_color; - } - else - { + } else { sun.color = _transmittanceWithShadow(r0, muS); } sun.direction = s.scale(-1.0); @@ -1267,17 +1164,14 @@ bool AtmosphereModelBruneton::getLightsAt(std::vector &result, c return true; } -Texture2D *AtmosphereModelBruneton::getTextureTransmittance() const -{ +Texture2D *AtmosphereModelBruneton::getTextureTransmittance() const { return _transmittanceTexture; } -Texture2D *AtmosphereModelBruneton::getTextureIrradiance() const -{ +Texture2D *AtmosphereModelBruneton::getTextureIrradiance() const { return _irradianceTexture; } -Texture4D *AtmosphereModelBruneton::getTextureInscatter() const -{ +Texture4D *AtmosphereModelBruneton::getTextureInscatter() const { return _inscatterTexture; } diff --git a/src/render/software/AtmosphereModelBruneton.h b/src/render/software/AtmosphereModelBruneton.h index d826172..889fecc 100644 --- a/src/render/software/AtmosphereModelBruneton.h +++ b/src/render/software/AtmosphereModelBruneton.h @@ -8,9 +8,8 @@ namespace paysages { namespace software { -class SOFTWARESHARED_EXPORT AtmosphereModelBruneton: public LightSource -{ -public: +class SOFTWARESHARED_EXPORT AtmosphereModelBruneton : public LightSource { + public: AtmosphereModelBruneton(SoftwareRenderer *parent); virtual ~AtmosphereModelBruneton(); @@ -19,14 +18,13 @@ public: virtual bool getLightsAt(std::vector &result, const Vector3 &location) const override; /* Functions to get access to internal textures (for opengl shaders) */ - Texture2D* getTextureTransmittance() const; - Texture2D* getTextureIrradiance() const; - Texture4D* getTextureInscatter() const; + Texture2D *getTextureTransmittance() const; + Texture2D *getTextureIrradiance() const; + Texture4D *getTextureInscatter() const; -private: - SoftwareRenderer* parent; + private: + SoftwareRenderer *parent; }; - } } diff --git a/src/render/software/AtmosphereRenderer.cpp b/src/render/software/AtmosphereRenderer.cpp index ac2e446..f84ef4c 100644 --- a/src/render/software/AtmosphereRenderer.cpp +++ b/src/render/software/AtmosphereRenderer.cpp @@ -19,16 +19,13 @@ #define SUN_RADIUS 6.955e5 #define SUN_RADIUS_SCALED (SUN_RADIUS / WORLD_SCALING) -static inline double _getDayFactor(double daytime) -{ +static inline double _getDayFactor(double daytime) { daytime = 1.0 - fabs(0.5 - daytime) / 0.5; return daytime < 0.45 ? 0.0 : sqrt((daytime - 0.45) / 0.55); } -static inline void _applyWeatherEffects(AtmosphereDefinition* definition, AtmosphereResult* result) -{ - if (definition->model == AtmosphereDefinition::ATMOSPHERE_MODEL_DISABLED) - { +static inline void _applyWeatherEffects(AtmosphereDefinition *definition, AtmosphereResult *result) { + if (definition->model == AtmosphereDefinition::ATMOSPHERE_MODEL_DISABLED) { result->updateFinal(); return; } @@ -38,8 +35,7 @@ static inline void _applyWeatherEffects(AtmosphereDefinition* definition, Atmosp double max_distance = 100.0 - 90.0 * humidity; double distancefactor, dayfactor; - if (distance > max_distance) - { + if (distance > max_distance) { distance = max_distance; } distancefactor = (distance > max_distance ? max_distance : distance) / max_distance; @@ -47,21 +43,17 @@ static inline void _applyWeatherEffects(AtmosphereDefinition* definition, Atmosp dayfactor = _getDayFactor(definition->propDayTime()->getValue()); /* Fog masking */ - if (humidity > 0.3) - { + if (humidity > 0.3) { result->mask.r = result->mask.g = result->mask.b = (10.0 - 8.0 * humidity) * dayfactor; result->mask.a = distancefactor * (humidity - 0.3) / 0.7; } /* Scattering tweaking */ - if (humidity < 0.15) - { + if (humidity < 0.15) { /* Limit scattering on ultra clear day */ double force = (0.15 - humidity) / 0.15; result->inscattering.limitPower(100.0 - 90.0 * pow(force, 0.1)); - } - else - { + } else { /* Scattering boost */ double force = 1.2 * (humidity < 0.5 ? sqrt((humidity - 0.15) / 0.35) : 1.0 - (humidity - 0.5) / 0.5); result->inscattering.r *= 1.0 + force * distancefactor * (humidity - 0.15) / 0.85; @@ -77,64 +69,53 @@ static inline void _applyWeatherEffects(AtmosphereDefinition* definition, Atmosp result->updateFinal(); } - -BaseAtmosphereRenderer::BaseAtmosphereRenderer(SoftwareRenderer* renderer): - parent(renderer) -{ +BaseAtmosphereRenderer::BaseAtmosphereRenderer(SoftwareRenderer *renderer) : parent(renderer) { } -AtmosphereResult BaseAtmosphereRenderer::applyAerialPerspective(const Vector3 &, const Color &base) -{ +AtmosphereResult BaseAtmosphereRenderer::applyAerialPerspective(const Vector3 &, const Color &base) { AtmosphereResult result; result.base = result.final = base; result.inscattering = result.attenuation = COLOR_BLACK; return result; } -AtmosphereResult BaseAtmosphereRenderer::getSkyColor(const Vector3 &) -{ +AtmosphereResult BaseAtmosphereRenderer::getSkyColor(const Vector3 &) { AtmosphereResult result; result.base = result.final = COLOR_WHITE; result.inscattering = result.attenuation = COLOR_BLACK; return result; } -Vector3 BaseAtmosphereRenderer::getSunDirection(bool) const -{ - AtmosphereDefinition* atmosphere = getDefinition(); +Vector3 BaseAtmosphereRenderer::getSunDirection(bool) const { + AtmosphereDefinition *atmosphere = getDefinition(); double sun_angle = (atmosphere->propDayTime()->getValue() + 0.75) * M_PI * 2.0; return Vector3(cos(sun_angle), sin(sun_angle), 0.0); } -bool BaseAtmosphereRenderer::getLightsAt(std::vector &, const Vector3 &) const -{ +bool BaseAtmosphereRenderer::getLightsAt(std::vector &, const Vector3 &) const { return false; } -AtmosphereDefinition* BaseAtmosphereRenderer::getDefinition() const -{ +AtmosphereDefinition *BaseAtmosphereRenderer::getDefinition() const { return parent->getScenery()->getAtmosphere(); } -SoftwareBrunetonAtmosphereRenderer::SoftwareBrunetonAtmosphereRenderer(SoftwareRenderer* renderer): - BaseAtmosphereRenderer(renderer) -{ +SoftwareBrunetonAtmosphereRenderer::SoftwareBrunetonAtmosphereRenderer(SoftwareRenderer *renderer) + : BaseAtmosphereRenderer(renderer) { model = new AtmosphereModelBruneton(parent); } -SoftwareBrunetonAtmosphereRenderer::~SoftwareBrunetonAtmosphereRenderer() -{ +SoftwareBrunetonAtmosphereRenderer::~SoftwareBrunetonAtmosphereRenderer() { delete model; } -AtmosphereResult SoftwareBrunetonAtmosphereRenderer::applyAerialPerspective(const Vector3 &location, const Color &base) -{ - AtmosphereDefinition* definition = getDefinition(); +AtmosphereResult SoftwareBrunetonAtmosphereRenderer::applyAerialPerspective(const Vector3 &location, + const Color &base) { + AtmosphereDefinition *definition = getDefinition(); AtmosphereResult result; // Get base perspective - switch (definition->model) - { + switch (definition->model) { case AtmosphereDefinition::ATMOSPHERE_MODEL_BRUNETON: result = model->applyAerialPerspective(location, base); break; @@ -151,9 +132,8 @@ AtmosphereResult SoftwareBrunetonAtmosphereRenderer::applyAerialPerspective(cons return result; } -AtmosphereResult SoftwareBrunetonAtmosphereRenderer::getSkyColor(const Vector3 &direction) -{ - AtmosphereDefinition* definition; +AtmosphereResult SoftwareBrunetonAtmosphereRenderer::getSkyColor(const Vector3 &direction) { + AtmosphereDefinition *definition; Vector3 sun_direction, sun_position, camera_location; Color base; @@ -177,7 +157,8 @@ AtmosphereResult SoftwareBrunetonAtmosphereRenderer::getSkyColor(const Vector3 & int hits = euclidRayIntersectSphere(camera_location, direction, sun_position, sun_radius, &hit1, &hit2); if (hits > 1) { - double dist = v3Norm(v3Sub(hit2, hit1)) / sun_radius; // distance between intersection points (relative to radius) + double dist = v3Norm(v3Sub(hit2, hit1)) / sun_radius; // distance between intersection points (relative to + radius) Color sun_color = definition->sun_color; sun_color.r *= 100.0; @@ -197,8 +178,7 @@ AtmosphereResult SoftwareBrunetonAtmosphereRenderer::getSkyColor(const Vector3 & // Get scattering AtmosphereResult result; Vector3 location = camera_location.add(direction_norm.scale(6421.0)); - switch (definition->model) - { + switch (definition->model) { case AtmosphereDefinition::ATMOSPHERE_MODEL_BRUNETON: result = model->getSkyColor(camera_location, direction_norm, sun_position, base); break; @@ -215,8 +195,8 @@ AtmosphereResult SoftwareBrunetonAtmosphereRenderer::getSkyColor(const Vector3 & return result; } -bool SoftwareBrunetonAtmosphereRenderer::getLightsAt(std::vector &result, const Vector3 &location) const -{ +bool SoftwareBrunetonAtmosphereRenderer::getLightsAt(std::vector &result, + const Vector3 &location) const { bool changed = false; changed |= model->getLightsAt(result, location); changed |= parent->getNightSky()->getLightsAt(result, location); diff --git a/src/render/software/AtmosphereRenderer.h b/src/render/software/AtmosphereRenderer.h index f29fa58..66b68da 100644 --- a/src/render/software/AtmosphereRenderer.h +++ b/src/render/software/AtmosphereRenderer.h @@ -8,27 +8,26 @@ namespace paysages { namespace software { -class BaseAtmosphereRenderer: public LightSource -{ -public: - BaseAtmosphereRenderer(SoftwareRenderer* parent); - virtual ~BaseAtmosphereRenderer() {} +class BaseAtmosphereRenderer : public LightSource { + public: + BaseAtmosphereRenderer(SoftwareRenderer *parent); + virtual ~BaseAtmosphereRenderer() { + } virtual AtmosphereResult applyAerialPerspective(const Vector3 &location, const Color &base); virtual AtmosphereResult getSkyColor(const Vector3 &direction); - virtual Vector3 getSunDirection(bool cache=true) const; + virtual Vector3 getSunDirection(bool cache = true) const; virtual bool getLightsAt(std::vector &result, const Vector3 &location) const override; -protected: - virtual AtmosphereDefinition* getDefinition() const; - SoftwareRenderer* parent; + protected: + virtual AtmosphereDefinition *getDefinition() const; + SoftwareRenderer *parent; }; -class SoftwareBrunetonAtmosphereRenderer: public BaseAtmosphereRenderer -{ -public: - SoftwareBrunetonAtmosphereRenderer(SoftwareRenderer* parent); +class SoftwareBrunetonAtmosphereRenderer : public BaseAtmosphereRenderer { + public: + SoftwareBrunetonAtmosphereRenderer(SoftwareRenderer *parent); virtual ~SoftwareBrunetonAtmosphereRenderer(); virtual AtmosphereResult applyAerialPerspective(const Vector3 &location, const Color &base) override; @@ -36,12 +35,13 @@ public: virtual bool getLightsAt(std::vector &result, const Vector3 &location) const override; - inline const AtmosphereModelBruneton* getModel() const {return model;} + inline const AtmosphereModelBruneton *getModel() const { + return model; + } -private: - AtmosphereModelBruneton* model; + private: + AtmosphereModelBruneton *model; }; - } } diff --git a/src/render/software/AtmosphereResult.cpp b/src/render/software/AtmosphereResult.cpp index a6c6be2..d1607d6 100644 --- a/src/render/software/AtmosphereResult.cpp +++ b/src/render/software/AtmosphereResult.cpp @@ -1,7 +1,6 @@ #include "AtmosphereResult.h" -AtmosphereResult::AtmosphereResult() -{ +AtmosphereResult::AtmosphereResult() { base = COLOR_BLACK; inscattering = COLOR_BLACK; attenuation = COLOR_WHITE; @@ -10,8 +9,7 @@ AtmosphereResult::AtmosphereResult() final = COLOR_BLACK; } -void AtmosphereResult::updateFinal() -{ +void AtmosphereResult::updateFinal() { final.r = base.r * attenuation.r + inscattering.r; final.g = base.g * attenuation.g + inscattering.g; final.b = base.b * attenuation.b + inscattering.b; diff --git a/src/render/software/AtmosphereResult.h b/src/render/software/AtmosphereResult.h index c798496..03dac00 100644 --- a/src/render/software/AtmosphereResult.h +++ b/src/render/software/AtmosphereResult.h @@ -8,9 +8,8 @@ namespace paysages { namespace software { -class SOFTWARESHARED_EXPORT AtmosphereResult -{ -public: +class SOFTWARESHARED_EXPORT AtmosphereResult { + public: AtmosphereResult(); void updateFinal(); @@ -21,7 +20,6 @@ public: Color mask; Color final; }; - } } diff --git a/src/render/software/BaseCloudLayerRenderer.cpp b/src/render/software/BaseCloudLayerRenderer.cpp index c553313..8499370 100644 --- a/src/render/software/BaseCloudLayerRenderer.cpp +++ b/src/render/software/BaseCloudLayerRenderer.cpp @@ -3,80 +3,57 @@ #include "clouds/BaseCloudsModel.h" #include "Vector3.h" -BaseCloudLayerRenderer::BaseCloudLayerRenderer(SoftwareRenderer* parent): - parent(parent) -{ +BaseCloudLayerRenderer::BaseCloudLayerRenderer(SoftwareRenderer *parent) : parent(parent) { setQuality(0.5); } -BaseCloudLayerRenderer::~BaseCloudLayerRenderer() -{ - +BaseCloudLayerRenderer::~BaseCloudLayerRenderer() { } -Color BaseCloudLayerRenderer::getColor(BaseCloudsModel *, const Vector3 &, const Vector3 &) -{ +Color BaseCloudLayerRenderer::getColor(BaseCloudsModel *, const Vector3 &, const Vector3 &) { return COLOR_TRANSPARENT; } -bool BaseCloudLayerRenderer::alterLight(BaseCloudsModel *, LightComponent *, const Vector3 &, const Vector3 &) -{ +bool BaseCloudLayerRenderer::alterLight(BaseCloudsModel *, LightComponent *, const Vector3 &, const Vector3 &) { return false; } -void BaseCloudLayerRenderer::setQuality(double quality) -{ +void BaseCloudLayerRenderer::setQuality(double quality) { this->quality = quality; } -bool BaseCloudLayerRenderer::optimizeSearchLimits(BaseCloudsModel *model, Vector3 *start, Vector3 *end) -{ +bool BaseCloudLayerRenderer::optimizeSearchLimits(BaseCloudsModel *model, Vector3 *start, Vector3 *end) { Vector3 diff; double min_altitude, max_altitude; model->getAltitudeRange(&min_altitude, &max_altitude); - if (start->y > max_altitude) - { - if (end->y >= max_altitude) - { + if (start->y > max_altitude) { + if (end->y >= max_altitude) { return false; - } - else - { + } else { diff = end->sub(*start); *start = start->add(diff.scale((max_altitude - start->y) / diff.y)); - if (end->y < min_altitude) - { + if (end->y < min_altitude) { *end = end->add(diff.scale((min_altitude - end->y) / diff.y)); } } - } - else if (start->y < min_altitude) - { - if (end->y <= min_altitude) - { + } else if (start->y < min_altitude) { + if (end->y <= min_altitude) { return false; - } - else - { + } else { diff = end->sub(*start); *start = start->add(diff.scale((min_altitude - start->y) / diff.y)); - if (end->y >= max_altitude) - { + if (end->y >= max_altitude) { *end = end->add(diff.scale((max_altitude - end->y) / diff.y)); } } - } - else /* start is inside layer */ + } else /* start is inside layer */ { diff = end->sub(*start); - if (end->y > max_altitude) - { + if (end->y > max_altitude) { *end = start->add(diff.scale((max_altitude - start->y) / diff.y)); - } - else if (end->y < min_altitude) - { + } else if (end->y < min_altitude) { *end = start->add(diff.scale((min_altitude - start->y) / diff.y)); } } diff --git a/src/render/software/BaseCloudLayerRenderer.h b/src/render/software/BaseCloudLayerRenderer.h index dc2e451..227c535 100644 --- a/src/render/software/BaseCloudLayerRenderer.h +++ b/src/render/software/BaseCloudLayerRenderer.h @@ -6,24 +6,22 @@ namespace paysages { namespace software { -class BaseCloudLayerRenderer -{ -public: - BaseCloudLayerRenderer(SoftwareRenderer* parent); +class BaseCloudLayerRenderer { + public: + BaseCloudLayerRenderer(SoftwareRenderer *parent); virtual ~BaseCloudLayerRenderer(); virtual bool optimizeSearchLimits(BaseCloudsModel *model, Vector3 *start, Vector3 *end); virtual Color getColor(BaseCloudsModel *model, const Vector3 &eye, const Vector3 &location); - virtual bool alterLight(BaseCloudsModel *model, LightComponent* light, const Vector3 &eye, const Vector3 &location); + virtual bool alterLight(BaseCloudsModel *model, LightComponent *light, const Vector3 &eye, const Vector3 &location); virtual void setQuality(double quality); -protected: - SoftwareRenderer* parent; + protected: + SoftwareRenderer *parent; double quality; }; - } } diff --git a/src/render/software/Canvas.cpp b/src/render/software/Canvas.cpp index 58726b0..929081d 100644 --- a/src/render/software/Canvas.cpp +++ b/src/render/software/Canvas.cpp @@ -8,8 +8,7 @@ #define CUTTER_SIZE 800 -Canvas::Canvas() -{ +Canvas::Canvas() { horizontal_portion_count = 1; vertical_portion_count = 1; width = 1; @@ -19,25 +18,21 @@ Canvas::Canvas() preview = new CanvasPreview; } -Canvas::~Canvas() -{ - for (auto portion: portions) - { +Canvas::~Canvas() { + for (auto portion : portions) { delete portion; } delete preview; } -void Canvas::setSize(int width, int height) -{ +void Canvas::setSize(int width, int height) { horizontal_portion_count = 1 + (width - 1) / CUTTER_SIZE; vertical_portion_count = 1 + (height - 1) / CUTTER_SIZE; int portion_width = width / horizontal_portion_count; int portion_height = height / vertical_portion_count; - for (auto portion: portions) - { + for (auto portion : portions) { delete portion; } portions.clear(); @@ -46,21 +41,17 @@ void Canvas::setSize(int width, int height) int done_height = 0; int index = 0; - for (int y = 0; y < vertical_portion_count; y++) - { + for (int y = 0; y < vertical_portion_count; y++) { done_width = 0; - for (int x = 0; x < horizontal_portion_count; x++) - { + for (int x = 0; x < horizontal_portion_count; x++) { CanvasPortion *portion = new CanvasPortion(index++, preview); portion->setSize((x == horizontal_portion_count - 1) ? width - done_width : portion_width, - (y == vertical_portion_count - 1) ? height - done_height : portion_height, - done_width, + (y == vertical_portion_count - 1) ? height - done_height : portion_height, done_width, done_height); done_width += portion->getWidth(); - if (x == horizontal_portion_count - 1) - { + if (x == horizontal_portion_count - 1) { done_height += portion->getHeight(); } @@ -74,24 +65,21 @@ void Canvas::setSize(int width, int height) this->height = height; // Smaller preview - while (width > 1000 or height > 700) - { + while (width > 1000 or height > 700) { width = width / 2; height = height / 2; } preview->setSize(this->width, this->height, width, height); } -CanvasPortion *Canvas::at(int x, int y) const -{ +CanvasPortion *Canvas::at(int x, int y) const { assert(x >= 0 && x < horizontal_portion_count); assert(y >= 0 && y < vertical_portion_count); return portions[y * horizontal_portion_count + x]; } -CanvasPortion *Canvas::atPixel(int x, int y) const -{ +CanvasPortion *Canvas::atPixel(int x, int y) const { assert(x >= 0 && x < width); assert(y >= 0 && y < height); @@ -101,20 +89,17 @@ CanvasPortion *Canvas::atPixel(int x, int y) const int px = x / pwidth; int py = y / pheight; - if (px >= horizontal_portion_count) - { + if (px >= horizontal_portion_count) { px = horizontal_portion_count - 1; } - if (py >= vertical_portion_count) - { + if (py >= vertical_portion_count) { py = vertical_portion_count - 1; } return at(px, py); } -bool Canvas::saveToDisk(const std::string &filepath, const ColorProfile &profile, int antialias) const -{ +bool Canvas::saveToDisk(const std::string &filepath, const ColorProfile &profile, int antialias) const { assert(antialias >= 1); CanvasPictureWriter writer(this); diff --git a/src/render/software/Canvas.h b/src/render/software/Canvas.h index c326bca..b352527 100644 --- a/src/render/software/Canvas.h +++ b/src/render/software/Canvas.h @@ -12,23 +12,32 @@ namespace software { * Software rendering is done in portions of Canvas (in CanvasPortion class). * This splitting in portions allows to keep memory consumption low. */ -class SOFTWARESHARED_EXPORT Canvas -{ -public: +class SOFTWARESHARED_EXPORT Canvas { + public: Canvas(); ~Canvas(); void setSize(int width, int height); - inline int getHorizontalPortionCount() const {return horizontal_portion_count;} - inline int getVerticalPortionCount() const {return vertical_portion_count;} + inline int getHorizontalPortionCount() const { + return horizontal_portion_count; + } + inline int getVerticalPortionCount() const { + return vertical_portion_count; + } CanvasPortion *at(int x, int y) const; CanvasPortion *atPixel(int x, int y) const; - inline int getWidth() const {return width;} - inline int getHeight() const {return height;} - inline CanvasPreview *getPreview() const {return preview;} + inline int getWidth() const { + return width; + } + inline int getHeight() const { + return height; + } + inline CanvasPreview *getPreview() const { + return preview; + } /** * Save the canvas to a picture file on disk. @@ -37,8 +46,8 @@ public: */ bool saveToDisk(const std::string &filepath, const ColorProfile &profile, int antialias) const; -private: - std::vector portions; + private: + std::vector portions; int horizontal_portion_count; int vertical_portion_count; int width; @@ -46,7 +55,6 @@ private: CanvasPreview *preview; }; - } } diff --git a/src/render/software/CanvasFragment.cpp b/src/render/software/CanvasFragment.cpp index 2725cc3..cbb8404 100644 --- a/src/render/software/CanvasFragment.cpp +++ b/src/render/software/CanvasFragment.cpp @@ -1,12 +1,11 @@ #include "CanvasFragment.h" -CanvasFragment::CanvasFragment(bool front_facing, const Vector3 &pixel, const Vector3 &location, int client, bool opaque): - opaque(opaque), front_facing(front_facing), pixel(pixel), location(location), client(client) -{ +CanvasFragment::CanvasFragment(bool front_facing, const Vector3 &pixel, const Vector3 &location, int client, + bool opaque) + : opaque(opaque), front_facing(front_facing), pixel(pixel), location(location), client(client) { color = COLOR_WHITE; } -void CanvasFragment::setColor(const Color &col) -{ +void CanvasFragment::setColor(const Color &col) { color = col; } diff --git a/src/render/software/CanvasFragment.h b/src/render/software/CanvasFragment.h index 4a09af2..f209a83 100644 --- a/src/render/software/CanvasFragment.h +++ b/src/render/software/CanvasFragment.h @@ -12,23 +12,37 @@ namespace software { /** * @brief Representation of world coordinates projected in a canvas pixel. */ -class SOFTWARESHARED_EXPORT CanvasFragment -{ -public: +class SOFTWARESHARED_EXPORT CanvasFragment { + public: CanvasFragment() = default; - CanvasFragment(bool front_facing, const Vector3 &pixel, const Vector3 &location, int client=0, bool opaque=true); + CanvasFragment(bool front_facing, const Vector3 &pixel, const Vector3 &location, int client = 0, + bool opaque = true); void setColor(const Color &col); - inline bool getOpaque() const {return opaque;} - inline bool isFrontFacing() const {return front_facing;} - inline double getZ() const {return pixel.z;} - inline const Vector3 &getLocation() const {return location;} - inline const Vector3 &getPixel() const {return pixel;} - inline int getClient() const {return client;} - inline const Color &getColor() const {return color;} + inline bool getOpaque() const { + return opaque; + } + inline bool isFrontFacing() const { + return front_facing; + } + inline double getZ() const { + return pixel.z; + } + inline const Vector3 &getLocation() const { + return location; + } + inline const Vector3 &getPixel() const { + return pixel; + } + inline int getClient() const { + return client; + } + inline const Color &getColor() const { + return color; + } -private: + private: bool opaque; bool front_facing; Vector3 pixel; @@ -36,7 +50,6 @@ private: int client; Color color; }; - } } diff --git a/src/render/software/CanvasLiveClient.cpp b/src/render/software/CanvasLiveClient.cpp index 3586fdd..0b5e542 100644 --- a/src/render/software/CanvasLiveClient.cpp +++ b/src/render/software/CanvasLiveClient.cpp @@ -1,17 +1,13 @@ #include "CanvasLiveClient.h" -CanvasLiveClient::CanvasLiveClient() -{ +CanvasLiveClient::CanvasLiveClient() { } -void CanvasLiveClient::canvasResized(int, int) -{ +void CanvasLiveClient::canvasResized(int, int) { } -void CanvasLiveClient::canvasCleared(const Color &) -{ +void CanvasLiveClient::canvasCleared(const Color &) { } -void CanvasLiveClient::canvasPainted(int, int, const Color &) -{ +void CanvasLiveClient::canvasPainted(int, int, const Color &) { } diff --git a/src/render/software/CanvasLiveClient.h b/src/render/software/CanvasLiveClient.h index 133e7cb..053e861 100644 --- a/src/render/software/CanvasLiveClient.h +++ b/src/render/software/CanvasLiveClient.h @@ -9,16 +9,14 @@ namespace software { /** * @brief Abstract class to receive live modifications from canvas preview. */ -class SOFTWARESHARED_EXPORT CanvasLiveClient -{ -public: +class SOFTWARESHARED_EXPORT CanvasLiveClient { + public: CanvasLiveClient(); virtual void canvasResized(int width, int height); virtual void canvasCleared(const Color &col); virtual void canvasPainted(int x, int y, const Color &col); }; - } } diff --git a/src/render/software/CanvasPictureWriter.cpp b/src/render/software/CanvasPictureWriter.cpp index be68387..01a91f3 100644 --- a/src/render/software/CanvasPictureWriter.cpp +++ b/src/render/software/CanvasPictureWriter.cpp @@ -7,9 +7,7 @@ #include "ColorProfile.h" #include "PackStream.h" -CanvasPictureWriter::CanvasPictureWriter(const Canvas *canvas): - canvas(canvas) -{ +CanvasPictureWriter::CanvasPictureWriter(const Canvas *canvas) : canvas(canvas) { profile = new ColorProfile(); antialias = 1; width = canvas->getWidth(); @@ -20,14 +18,12 @@ CanvasPictureWriter::CanvasPictureWriter(const Canvas *canvas): cache_width = 0; } -CanvasPictureWriter::~CanvasPictureWriter() -{ +CanvasPictureWriter::~CanvasPictureWriter() { delete profile; delete[] cache; } -void CanvasPictureWriter::setAntialias(int antialias) -{ +void CanvasPictureWriter::setAntialias(int antialias) { assert(antialias >= 1); assert(canvas->getWidth() % antialias == 0); assert(canvas->getHeight() % antialias == 0); @@ -37,41 +33,33 @@ void CanvasPictureWriter::setAntialias(int antialias) this->height = canvas->getHeight() / antialias; } -void CanvasPictureWriter::setColorProfile(const ColorProfile &profile) -{ +void CanvasPictureWriter::setColorProfile(const ColorProfile &profile) { profile.copy(this->profile); } -bool CanvasPictureWriter::saveCanvas(const std::string &filepath) -{ +bool CanvasPictureWriter::saveCanvas(const std::string &filepath) { return save(filepath, width, height); } -unsigned int CanvasPictureWriter::getPixel(int x, int y) -{ +unsigned int CanvasPictureWriter::getPixel(int x, int y) { Color comp; - if (antialias > 1) - { + if (antialias > 1) { int basex = x * antialias; int basey = y * antialias; double factor = 1.0 / (antialias * antialias); comp = COLOR_BLACK; - for (int iy = 0; iy < antialias; iy++) - { - for (int ix = 0; ix < antialias; ix++) - { + for (int iy = 0; iy < antialias; iy++) { + for (int ix = 0; ix < antialias; ix++) { Color col = getRawPixel(basex + ix, basey + iy); comp.r += col.r * factor; comp.g += col.g * factor; comp.b += col.b * factor; } } - } - else - { + } else { comp = getRawPixel(x, y); } @@ -80,10 +68,8 @@ unsigned int CanvasPictureWriter::getPixel(int x, int y) return comp.to32BitBGRA(); } -Color CanvasPictureWriter::getRawPixel(int x, int y) -{ - if (not (y >= cache_y && y < cache_y + antialias)) - { +Color CanvasPictureWriter::getRawPixel(int x, int y) { + if (not(y >= cache_y && y < cache_y + antialias)) { // Load rows into cache delete[] cache; cache_y = y; @@ -93,26 +79,21 @@ Color CanvasPictureWriter::getRawPixel(int x, int y) CanvasPortion *portion = NULL; PackStream *stream = new PackStream; - Color* itcolor = cache; + Color *itcolor = cache; bool has_pixels = false; - for (int cy = cache_y; cy < cache_y + antialias; cy++) - { - for (int cx = 0; cx < cache_width; cx++) - { + for (int cy = cache_y; cy < cache_y + antialias; cy++) { + for (int cx = 0; cx < cache_width; cx++) { CanvasPortion *nportion = canvas->atPixel(cx, cy); - if (nportion != portion) - { + if (nportion != portion) { portion = nportion; delete stream; stream = new PackStream; - has_pixels = portion->getReadStream(*stream, cx - portion->getXOffset(), cy - portion->getYOffset()); + has_pixels = + portion->getReadStream(*stream, cx - portion->getXOffset(), cy - portion->getYOffset()); } - if (has_pixels) - { + if (has_pixels) { itcolor->load(stream); - } - else - { + } else { *itcolor = COLOR_BLACK; } itcolor++; diff --git a/src/render/software/CanvasPictureWriter.h b/src/render/software/CanvasPictureWriter.h index c0394cf..d6c9ee6 100644 --- a/src/render/software/CanvasPictureWriter.h +++ b/src/render/software/CanvasPictureWriter.h @@ -11,9 +11,8 @@ namespace software { /** * Picture writer to create the final image from canvas portions. */ -class SOFTWARESHARED_EXPORT CanvasPictureWriter: public PictureWriter -{ -public: +class SOFTWARESHARED_EXPORT CanvasPictureWriter : public PictureWriter { + public: CanvasPictureWriter(const Canvas *canvas); virtual ~CanvasPictureWriter(); @@ -34,13 +33,13 @@ public: */ bool saveCanvas(const std::string &filepath); -protected: + protected: virtual unsigned int getPixel(int x, int y) override; -private: + private: Color getRawPixel(int x, int y); -private: + private: const Canvas *canvas; int antialias; int width; @@ -51,7 +50,6 @@ private: int cache_width; Color *cache; }; - } } diff --git a/src/render/software/CanvasPixel.cpp b/src/render/software/CanvasPixel.cpp index 859ad37..cbd3129 100644 --- a/src/render/software/CanvasPixel.cpp +++ b/src/render/software/CanvasPixel.cpp @@ -2,94 +2,69 @@ #include -CanvasPixel::CanvasPixel() -{ +CanvasPixel::CanvasPixel() { count = 0; composite = COLOR_BLACK; } -const CanvasFragment *CanvasPixel::getFrontFragment() const -{ - if (count == 0) - { +const CanvasFragment *CanvasPixel::getFrontFragment() const { + if (count == 0) { return NULL; - } - else - { + } else { return fragments + (count - 1); } } -void CanvasPixel::reset() -{ +void CanvasPixel::reset() { count = 0; composite = COLOR_BLACK; } -void CanvasPixel::pushFragment(const CanvasFragment &fragment) -{ - if (count == 0) - { +void CanvasPixel::pushFragment(const CanvasFragment &fragment) { + if (count == 0) { fragments[0] = fragment; count = 1; - } - else - { - if (fragments[0].getOpaque() and fragment.getZ() <= fragments[0].getZ()) - { + } else { + if (fragments[0].getOpaque() and fragment.getZ() <= fragments[0].getZ()) { // behind opaque fragment, don't bother return; } // find expected position int i = 0; - while (i < count and fragment.getZ() >= fragments[i].getZ()) - { + while (i < count and fragment.getZ() >= fragments[i].getZ()) { i++; } - if (i > 0 and fragments[i - 1].getZ() == fragment.getZ() and fragments[i - 1].getClient() == fragment.getClient()) - { + if (i > 0 and fragments[i - 1].getZ() == fragment.getZ() and + fragments[i - 1].getClient() == fragment.getClient()) { // Pixel already pushed by same client, don't do anything return; } - if (fragment.getOpaque()) - { + if (fragment.getOpaque()) { // Discard fragments masked by the incoming opaque one - if (i < count) - { + if (i < count) { memmove(fragments + 1, fragments + i, sizeof(CanvasFragment) * (count - i)); count -= i; - } - else - { + } else { count = 1; } fragments[0] = fragment; - } - else - { + } else { // Transparent pixel - if (i < count) - { + if (i < count) { // Need to make room for the incoming fragment - if (count < MAX_FRAGMENTS_PER_PIXEL) - { + if (count < MAX_FRAGMENTS_PER_PIXEL) { memmove(fragments + i + 1, fragments + i, sizeof(CanvasFragment) * (count - i)); fragments[i] = fragment; count++; } - } - else - { - if (count == MAX_FRAGMENTS_PER_PIXEL) - { + } else { + if (count == MAX_FRAGMENTS_PER_PIXEL) { // Replace nearest fragment fragments[count - 1] = fragment; - } - else - { + } else { // Append fragments[count] = fragment; count++; @@ -101,17 +76,14 @@ void CanvasPixel::pushFragment(const CanvasFragment &fragment) updateComposite(); } -void CanvasPixel::updateComposite() -{ +void CanvasPixel::updateComposite() { Color result(0.0, 0.0, 0.0, 1.0); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { result.mask(fragments[i].getColor()); } composite = result; } -void CanvasPixel::setComposite(const Color &color) -{ +void CanvasPixel::setComposite(const Color &color) { composite = color; } diff --git a/src/render/software/CanvasPixel.h b/src/render/software/CanvasPixel.h index f21b6a9..c6b72c6 100644 --- a/src/render/software/CanvasPixel.h +++ b/src/render/software/CanvasPixel.h @@ -15,14 +15,19 @@ namespace software { * * A pixel stores superimposed fragments (CanvasFragment), sorted by their distance to camera. */ -class SOFTWARESHARED_EXPORT CanvasPixel -{ -public: +class SOFTWARESHARED_EXPORT CanvasPixel { + public: CanvasPixel(); - inline int getFragmentCount() const {return count;} - inline const Color &getComposite() const {return composite;} - inline const CanvasFragment &getFragment(int position) const {return fragments[position];} + inline int getFragmentCount() const { + return count; + } + inline const Color &getComposite() const { + return composite; + } + inline const CanvasFragment &getFragment(int position) const { + return fragments[position]; + } const CanvasFragment *getFrontFragment() const; void reset(); @@ -30,12 +35,11 @@ public: void updateComposite(); void setComposite(const Color &color); -private: + private: int count; CanvasFragment fragments[MAX_FRAGMENTS_PER_PIXEL]; Color composite; }; - } } diff --git a/src/render/software/CanvasPixelShader.cpp b/src/render/software/CanvasPixelShader.cpp index 92cd1fc..ee65c60 100644 --- a/src/render/software/CanvasPixelShader.cpp +++ b/src/render/software/CanvasPixelShader.cpp @@ -8,14 +8,14 @@ #include "Rasterizer.h" #include "RenderProgress.h" - -CanvasPixelShader::CanvasPixelShader(const SoftwareCanvasRenderer &renderer, CanvasPortion *portion, RenderProgress *progress, int chunk_size, int sub_chunk_size, int chunks_x, int chunks_y): - renderer(renderer), portion(portion), progress(progress), chunk_size(chunk_size), sub_chunk_size(sub_chunk_size), chunks_x(chunks_x), chunks_y(chunks_y) -{ +CanvasPixelShader::CanvasPixelShader(const SoftwareCanvasRenderer &renderer, CanvasPortion *portion, + RenderProgress *progress, int chunk_size, int sub_chunk_size, int chunks_x, + int chunks_y) + : renderer(renderer), portion(portion), progress(progress), chunk_size(chunk_size), sub_chunk_size(sub_chunk_size), + chunks_x(chunks_x), chunks_y(chunks_y) { } -void CanvasPixelShader::processParallelUnit(int unit) -{ +void CanvasPixelShader::processParallelUnit(int unit) { // Locate the chunk we work on int prev_sub_chunk_size = sub_chunk_size * 2; int chunk_x = unit / chunks_y; @@ -29,25 +29,20 @@ void CanvasPixelShader::processParallelUnit(int unit) limit_y = (limit_y > chunk_size) ? chunk_size : limit_y; // Iterate on sub-chunks - for (int x = 0; x < limit_x; x += sub_chunk_size) - { + for (int x = 0; x < limit_x; x += sub_chunk_size) { int done = 0; - for (int y = 0; y < limit_y; y += sub_chunk_size) - { - if (interrupted) - { + for (int y = 0; y < limit_y; y += sub_chunk_size) { + if (interrupted) { return; } - if (sub_chunk_size == chunk_size or x % prev_sub_chunk_size != 0 or y % prev_sub_chunk_size != 0) - { + if (sub_chunk_size == chunk_size or x % prev_sub_chunk_size != 0 or y % prev_sub_chunk_size != 0) { // Resolve the pixel color const CanvasPixel &pixel = portion->at(base_x + x, base_y + y); int n = pixel.getFragmentCount(); Color composite = COLOR_BLACK; const CanvasFragment *previous = NULL; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { const CanvasFragment &fragment = pixel.getFragment(i); const Rasterizer &rasterizer = renderer.getRasterizer(fragment.getClient()); composite.mask(rasterizer.shadeFragment(fragment, previous)); @@ -55,10 +50,8 @@ void CanvasPixelShader::processParallelUnit(int unit) } // Fill the square area - for (int fx = 0; fx + x < limit_x and fx < sub_chunk_size; fx++) - { - for (int fy = 0; fy + y < limit_y and fy < sub_chunk_size; fy++) - { + for (int fx = 0; fx + x < limit_x and fx < sub_chunk_size; fx++) { + for (int fy = 0; fy + y < limit_y and fy < sub_chunk_size; fy++) { portion->setColor(base_x + x + fx, base_y + y + fy, composite); } } diff --git a/src/render/software/CanvasPixelShader.h b/src/render/software/CanvasPixelShader.h index 4fd10e0..1717f6b 100644 --- a/src/render/software/CanvasPixelShader.h +++ b/src/render/software/CanvasPixelShader.h @@ -15,14 +15,14 @@ namespace software { * * This worker will be set to work on a given chunk of a canvas portion. */ -class CanvasPixelShader: public ParallelWorker -{ -public: - CanvasPixelShader(const SoftwareCanvasRenderer &renderer, CanvasPortion *portion, RenderProgress *progress, int chunk_size, int sub_chunk_size, int chunks_x, int chunks_y); +class CanvasPixelShader : public ParallelWorker { + public: + CanvasPixelShader(const SoftwareCanvasRenderer &renderer, CanvasPortion *portion, RenderProgress *progress, + int chunk_size, int sub_chunk_size, int chunks_x, int chunks_y); virtual void processParallelUnit(int unit) override; -private: + private: const SoftwareCanvasRenderer &renderer; CanvasPortion *portion; RenderProgress *progress; @@ -31,7 +31,6 @@ private: int chunks_x; int chunks_y; }; - } } diff --git a/src/render/software/CanvasPortion.cpp b/src/render/software/CanvasPortion.cpp index dbf2950..932424d 100644 --- a/src/render/software/CanvasPortion.cpp +++ b/src/render/software/CanvasPortion.cpp @@ -7,15 +7,14 @@ #include "PackStream.h" #include "FileSystem.h" -#define CHECK_COORDINATES() assert(x >= 0); \ - assert(x < width); \ - assert(y >= 0); \ - assert(y < height); \ +#define CHECK_COORDINATES() \ + assert(x >= 0); \ + assert(x < width); \ + assert(y >= 0); \ + assert(y < height); \ assert(pixels != NULL) -CanvasPortion::CanvasPortion(int index, CanvasPreview* preview): - index(index), preview(preview) -{ +CanvasPortion::CanvasPortion(int index, CanvasPreview *preview) : index(index), preview(preview) { width = 1; height = 1; xoffset = 0; @@ -23,60 +22,48 @@ CanvasPortion::CanvasPortion(int index, CanvasPreview* preview): pixels = NULL; } -CanvasPortion::~CanvasPortion() -{ - if (pixels) - { +CanvasPortion::~CanvasPortion() { + if (pixels) { delete[] pixels; } } -int CanvasPortion::getFragmentCount(int x, int y) const -{ +int CanvasPortion::getFragmentCount(int x, int y) const { CHECK_COORDINATES(); return pixels[y * width + x].getFragmentCount(); } -const CanvasFragment *CanvasPortion::getFrontFragment(int x, int y) const -{ +const CanvasFragment *CanvasPortion::getFrontFragment(int x, int y) const { CHECK_COORDINATES(); return pixels[y * width + x].getFrontFragment(); } -void CanvasPortion::clear() -{ +void CanvasPortion::clear() { int n = width * height; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { pixels[i].reset(); } } -void CanvasPortion::setSize(int width, int height, int xoffset, int yoffset) -{ +void CanvasPortion::setSize(int width, int height, int xoffset, int yoffset) { this->width = width; this->height = height; this->xoffset = xoffset; this->yoffset = yoffset; } -void CanvasPortion::preparePixels() -{ - if (pixels) - { +void CanvasPortion::preparePixels() { + if (pixels) { delete[] pixels; } pixels = new CanvasPixel[width * height]; } -void CanvasPortion::discardPixels(bool save) -{ - if (pixels) - { - if (save) - { +void CanvasPortion::discardPixels(bool save) { + if (pixels) { + if (save) { saveToDisk(); } delete[] pixels; @@ -84,53 +71,42 @@ void CanvasPortion::discardPixels(bool save) } } -void CanvasPortion::saveToDisk() -{ - if (pixels) - { +void CanvasPortion::saveToDisk() { + if (pixels) { filepath = FileSystem::getTempFile("paysages_portion_" + std::to_string(index) + ".dat"); PackStream stream; stream.bindToFile(filepath, true); stream.write(&width); stream.write(&height); - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { pixels[y * width + x].getComposite().save(&stream); } } } } -bool CanvasPortion::getReadStream(PackStream &stream, int x, int y) -{ - if (FileSystem::isFile(filepath)) - { - if (not stream.bindToFile(filepath)) - { +bool CanvasPortion::getReadStream(PackStream &stream, int x, int y) { + if (FileSystem::isFile(filepath)) { + if (not stream.bindToFile(filepath)) { return false; } int unused_i; stream.skip(unused_i, 2); - if (x > 0 or y > 0) - { + if (x > 0 or y > 0) { double unused_d; stream.skip(unused_d, (y * width + x) * 4); } return true; - } - else - { + } else { return false; } } -void CanvasPortion::pushFragment(int x, int y, const CanvasFragment &fragment) -{ +void CanvasPortion::pushFragment(int x, int y, const CanvasFragment &fragment) { CHECK_COORDINATES(); CanvasPixel &pixel = pixels[y * width + x]; @@ -138,21 +114,18 @@ void CanvasPortion::pushFragment(int x, int y, const CanvasFragment &fragment) pixel.pushFragment(fragment); - if (preview) - { + if (preview) { preview->pushPixel(xoffset + x, yoffset + y, old_color, pixel.getComposite()); } } -const CanvasPixel &CanvasPortion::at(int x, int y) -{ +const CanvasPixel &CanvasPortion::at(int x, int y) { CHECK_COORDINATES(); return pixels[y * width + x]; } -void CanvasPortion::setColor(int x, int y, const Color &color) -{ +void CanvasPortion::setColor(int x, int y, const Color &color) { CHECK_COORDINATES(); CanvasPixel &pixel = pixels[y * width + x]; @@ -160,8 +133,7 @@ void CanvasPortion::setColor(int x, int y, const Color &color) pixel.setComposite(color); - if (preview) - { + if (preview) { preview->pushPixel(xoffset + x, yoffset + y, old_color, pixel.getComposite()); } } diff --git a/src/render/software/CanvasPortion.h b/src/render/software/CanvasPortion.h index 1131e16..4e52bda 100644 --- a/src/render/software/CanvasPortion.h +++ b/src/render/software/CanvasPortion.h @@ -13,21 +13,28 @@ namespace software { * * Pixels are not allocated until preparePixels is called. */ -class SOFTWARESHARED_EXPORT CanvasPortion -{ -public: - CanvasPortion(int index=0, CanvasPreview *preview=NULL); +class SOFTWARESHARED_EXPORT CanvasPortion { + public: + CanvasPortion(int index = 0, CanvasPreview *preview = NULL); virtual ~CanvasPortion(); - inline int getWidth() const {return width;} - inline int getHeight() const {return height;} - inline int getXOffset() const {return xoffset;} - inline int getYOffset() const {return yoffset;} + inline int getWidth() const { + return width; + } + inline int getHeight() const { + return height; + } + inline int getXOffset() const { + return xoffset; + } + inline int getYOffset() const { + return yoffset; + } int getFragmentCount(int x, int y) const; const CanvasFragment *getFrontFragment(int x, int y) const; void clear(); - void setSize(int width, int height, int xoffset=0, int yoffset=0); + void setSize(int width, int height, int xoffset = 0, int yoffset = 0); /** * Prepare (allocate in memory) the pixels area. @@ -39,7 +46,7 @@ public: * * If save is true, the portion will be saved to disk before. */ - void discardPixels(bool save=true); + void discardPixels(bool save = true); /** * Save the portion to a picture file on disk. @@ -51,7 +58,7 @@ public: * * Returns true if the stream was successfully located, false if it was not possible. */ - bool getReadStream(PackStream &stream, int x=0, int y=0); + bool getReadStream(PackStream &stream, int x = 0, int y = 0); /** * Add a fragment to the pixel located at (x, y). @@ -74,7 +81,7 @@ public: */ void setColor(int x, int y, const Color &color); -private: + private: int index; int width; int height; @@ -84,7 +91,6 @@ private: CanvasPreview *preview; std::string filepath; }; - } } diff --git a/src/render/software/CanvasPreview.cpp b/src/render/software/CanvasPreview.cpp index 6e49eec..955ef8f 100644 --- a/src/render/software/CanvasPreview.cpp +++ b/src/render/software/CanvasPreview.cpp @@ -7,14 +7,13 @@ #include -#define CHECK_COORDINATES(_x_, _y_) \ - assert(_x_ >= 0); \ - assert(_y_ >= 0); \ - assert(_x_ < this->width); \ - assert(_y_ < this->height) \ +#define CHECK_COORDINATES(_x_, _y_) \ + assert(_x_ >= 0); \ + assert(_y_ >= 0); \ + assert(_x_ < this->width); \ + assert(_y_ < this->height) -CanvasPreview::CanvasPreview() -{ +CanvasPreview::CanvasPreview() { width = 1; height = 1; pixels = new Color[1]; @@ -33,25 +32,22 @@ CanvasPreview::CanvasPreview() profile = new ColorProfile(); } -CanvasPreview::~CanvasPreview() -{ - delete [] pixels; +CanvasPreview::~CanvasPreview() { + delete[] pixels; delete lock; delete profile; } -const Color &CanvasPreview::getFinalPixel(int x, int y) const -{ +const Color &CanvasPreview::getFinalPixel(int x, int y) const { CHECK_COORDINATES(x, y); return pixels[y * width + x]; } -void CanvasPreview::setSize(int real_width, int real_height, int preview_width, int preview_height) -{ +void CanvasPreview::setSize(int real_width, int real_height, int preview_width, int preview_height) { lock->acquire(); - delete [] pixels; + delete[] pixels; pixels = new Color[preview_width * preview_height]; width = preview_width; @@ -72,43 +68,36 @@ void CanvasPreview::setSize(int real_width, int real_height, int preview_width, reset(); } -void CanvasPreview::setToneMapping(const ColorProfile &profile) -{ +void CanvasPreview::setToneMapping(const ColorProfile &profile) { profile.copy(this->profile); setAllDirty(); } -void CanvasPreview::reset() -{ +void CanvasPreview::reset() { lock->acquire(); int n = width * height; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { pixels[i] = COLOR_BLACK; } lock->release(); } -void CanvasPreview::initLive(CanvasLiveClient *client) -{ +void CanvasPreview::initLive(CanvasLiveClient *client) { client->canvasResized(width, height); client->canvasCleared(COLOR_BLACK); setAllDirty(); } -void CanvasPreview::updateLive(CanvasLiveClient *client) -{ +void CanvasPreview::updateLive(CanvasLiveClient *client) { int x, y; lock->acquire(); - for (y = dirty_down; y <= dirty_up; y++) - { - for (x = dirty_left; x <= dirty_right; x++) - { + for (y = dirty_down; y <= dirty_up; y++) { + for (x = dirty_left; x <= dirty_right; x++) { client->canvasPainted(x, y, profile->apply(pixels[y * width + x])); } } @@ -121,20 +110,16 @@ void CanvasPreview::updateLive(CanvasLiveClient *client) lock->release(); } -void CanvasPreview::pushPixel(int real_x, int real_y, const Color &old_color, const Color &new_color) -{ +void CanvasPreview::pushPixel(int real_x, int real_y, const Color &old_color, const Color &new_color) { int x, y; - if (scaled) - { + if (scaled) { x = int(real_x * factor_x); y = int(real_y * factor_y); x = (x >= width) ? width - 1 : x; y = (y >= height) ? height - 1 : y; - } - else - { + } else { x = real_x; y = real_y; } @@ -143,34 +128,29 @@ void CanvasPreview::pushPixel(int real_x, int real_y, const Color &old_color, co lock->acquire(); - Color* pixel = pixels + (y * width + x); + Color *pixel = pixels + (y * width + x); pixel->r = pixel->r - old_color.r * factor + new_color.r * factor; pixel->g = pixel->g - old_color.g * factor + new_color.g * factor; pixel->b = pixel->b - old_color.b * factor + new_color.b * factor; // Set pixel dirty - if (x < dirty_left) - { + if (x < dirty_left) { dirty_left = x; } - if (x > dirty_right) - { + if (x > dirty_right) { dirty_right = x; } - if (y < dirty_down) - { + if (y < dirty_down) { dirty_down = y; } - if (y > dirty_up) - { + if (y > dirty_up) { dirty_up = y; } lock->release(); } -void CanvasPreview::setAllDirty() -{ +void CanvasPreview::setAllDirty() { lock->acquire(); dirty_left = 0; diff --git a/src/render/software/CanvasPreview.h b/src/render/software/CanvasPreview.h index 20f4a35..f55776d 100644 --- a/src/render/software/CanvasPreview.h +++ b/src/render/software/CanvasPreview.h @@ -9,15 +9,20 @@ namespace software { /** * @brief Smaller preview of a Canvas rendering, that can be watched live. */ -class SOFTWARESHARED_EXPORT CanvasPreview -{ -public: +class SOFTWARESHARED_EXPORT CanvasPreview { + public: CanvasPreview(); ~CanvasPreview(); - inline int getWidth() const {return width;} - inline int getHeight() const {return height;} - inline const ColorProfile *getToneMapping() const {return profile;} + inline int getWidth() const { + return width; + } + inline int getHeight() const { + return height; + } + inline const ColorProfile *getToneMapping() const { + return profile; + } const Color &getFinalPixel(int x, int y) const; @@ -30,10 +35,10 @@ public: void pushPixel(int real_x, int real_y, const Color &old_color, const Color &new_color); -protected: + protected: void setAllDirty(); -private: + private: Mutex *lock; Color *pixels; @@ -52,7 +57,6 @@ private: double factor_x; double factor_y; }; - } } diff --git a/src/render/software/CloudBasicLayerRenderer.cpp b/src/render/software/CloudBasicLayerRenderer.cpp index 23cc733..b728b1d 100644 --- a/src/render/software/CloudBasicLayerRenderer.cpp +++ b/src/render/software/CloudBasicLayerRenderer.cpp @@ -14,20 +14,16 @@ #include -struct CloudSegment -{ +struct CloudSegment { Vector3 start; Vector3 end; double length; }; -CloudBasicLayerRenderer::CloudBasicLayerRenderer(SoftwareRenderer* parent): - BaseCloudLayerRenderer(parent) -{ +CloudBasicLayerRenderer::CloudBasicLayerRenderer(SoftwareRenderer *parent) : BaseCloudLayerRenderer(parent) { } -static inline double _getDistanceToBorder(BaseCloudsModel* model, const Vector3 &position) -{ +static inline double _getDistanceToBorder(BaseCloudsModel *model, const Vector3 &position) { return model->getDensity(position); } @@ -47,8 +43,9 @@ static inline double _getDistanceToBorder(BaseCloudsModel* model, const Vector3 * @param out_segments Allocated space to fill found segments * @return Number of segments found */ -int CloudBasicLayerRenderer::findSegments(BaseCloudsModel *model, const Vector3 &start, const Vector3 &direction, int max_segments, double max_inside_length, double max_total_length, double* inside_length, double* total_length, CloudSegment* out_segments) -{ +int CloudBasicLayerRenderer::findSegments(BaseCloudsModel *model, const Vector3 &start, const Vector3 &direction, + int max_segments, double max_inside_length, double max_total_length, + double *inside_length, double *total_length, CloudSegment *out_segments) { double ymin, ymax; int inside, segment_count; double current_total_length, current_inside_length; @@ -58,8 +55,7 @@ int CloudBasicLayerRenderer::findSegments(BaseCloudsModel *model, const Vector3 Vector3 walker, step, segment_start, offset; double render_precision; - if (max_segments <= 0) - { + if (max_segments <= 0) { return 0; } @@ -67,12 +63,9 @@ int CloudBasicLayerRenderer::findSegments(BaseCloudsModel *model, const Vector3 model->getDetailRange(&min_step, &max_step); render_precision = max_step - quality * (max_step - min_step); - if (render_precision > max_total_length / 10.0) - { + if (render_precision > max_total_length / 10.0) { render_precision = max_total_length / 10.0; - } - else if (render_precision < max_total_length / 2000.0) - { + } else if (render_precision < max_total_length / 2000.0) { render_precision = max_total_length / 2000.0; } @@ -86,24 +79,19 @@ int CloudBasicLayerRenderer::findSegments(BaseCloudsModel *model, const Vector3 inside = 0; step = direction.scale(render_precision); - do - { + do { walker = walker.add(step); step_length = step.getNorm(); noise_distance = _getDistanceToBorder(model, walker.add(offset)) * render_precision; current_total_length += step_length; - if (noise_distance > 0.0) - { - if (inside) - { + if (noise_distance > 0.0) { + if (inside) { // inside the cloud segment_length += step_length; current_inside_length += step_length; step = direction.scale((noise_distance < render_precision) ? render_precision : noise_distance); - } - else - { + } else { // entering the cloud inside = 1; segment_length = 0.0; @@ -111,11 +99,8 @@ int CloudBasicLayerRenderer::findSegments(BaseCloudsModel *model, const Vector3 current_inside_length += segment_length; step = direction.scale(render_precision); } - } - else - { - if (inside) - { + } else { + if (inside) { // exiting the cloud segment_length += step_length; current_inside_length += step_length; @@ -124,29 +109,26 @@ int CloudBasicLayerRenderer::findSegments(BaseCloudsModel *model, const Vector3 out_segments->end = walker; out_segments->length = segment_length; out_segments++; - if (++segment_count >= max_segments) - { + if (++segment_count >= max_segments) { break; } inside = 0; step = direction.scale(render_precision); - } - else - { + } else { // searching for a cloud step = direction.scale((noise_distance > -render_precision) ? render_precision : -noise_distance); } } - } while (inside || (walker.y >= ymin - 0.001 && walker.y <= ymax + 0.001 && current_total_length < max_total_length && current_inside_length < max_inside_length)); + } while (inside || (walker.y >= ymin - 0.001 && walker.y <= ymax + 0.001 && + current_total_length < max_total_length && current_inside_length < max_inside_length)); *total_length = current_total_length; *inside_length = current_inside_length; return segment_count; } -Color CloudBasicLayerRenderer::getColor(BaseCloudsModel *model, const Vector3 &eye, const Vector3 &location) -{ +Color CloudBasicLayerRenderer::getColor(BaseCloudsModel *model, const Vector3 &eye, const Vector3 &location) { int i, segment_count; double max_length, total_length, inside_length; Vector3 start, end, direction; @@ -155,8 +137,7 @@ Color CloudBasicLayerRenderer::getColor(BaseCloudsModel *model, const Vector3 &e start = eye; end = location; - if (!optimizeSearchLimits(model, &start, &end)) - { + if (!optimizeSearchLimits(model, &start, &end)) { return COLOR_TRANSPARENT; } @@ -169,16 +150,17 @@ Color CloudBasicLayerRenderer::getColor(BaseCloudsModel *model, const Vector3 &e model->getAltitudeRange(&ymin, &ymax); double transparency_depth = (ymax - ymin) * 0.5; - segment_count = findSegments(model, start, direction, 20, transparency_depth, max_length, &inside_length, &total_length, segments); - for (i = segment_count - 1; i >= 0; i--) - { + segment_count = findSegments(model, start, direction, 20, transparency_depth, max_length, &inside_length, + &total_length, segments); + for (i = segment_count - 1; i >= 0; i--) { SurfaceMaterial material(COLOR_WHITE); material.hardness = 0.25; material.reflection = 0.0; material.shininess = 0.0; material.validate(); - col = parent->applyLightingToSurface(segments[i].start, parent->getAtmosphereRenderer()->getSunDirection(), material); + col = parent->applyLightingToSurface(segments[i].start, parent->getAtmosphereRenderer()->getSunDirection(), + material); // Boost highly lighted area double boost = 1.0 + (col.getPower() * col.getPower()); @@ -191,18 +173,14 @@ Color CloudBasicLayerRenderer::getColor(BaseCloudsModel *model, const Vector3 &e } // Opacify when hitting inside_length limit - if (inside_length >= transparency_depth) - { + if (inside_length >= transparency_depth) { result.a = 1.0; - } - else if (inside_length >= transparency_depth * 0.8) - { + } else if (inside_length >= transparency_depth * 0.8) { result.a += (1.0 - result.a) * ((inside_length - transparency_depth * 0.8) / (transparency_depth * 0.2)); } // Apply aerial perspective - if (result.a > 0.00001) - { + if (result.a > 0.00001) { assert(segment_count > 0); double a = result.a; @@ -214,8 +192,8 @@ Color CloudBasicLayerRenderer::getColor(BaseCloudsModel *model, const Vector3 &e return result; } -bool CloudBasicLayerRenderer::alterLight(BaseCloudsModel *model, LightComponent* light, const Vector3 &, const Vector3 &location) -{ +bool CloudBasicLayerRenderer::alterLight(BaseCloudsModel *model, LightComponent *light, const Vector3 &, + const Vector3 &location) { Vector3 start, end, direction; double inside_depth, total_depth, factor; CloudSegment segments[20]; @@ -223,29 +201,23 @@ bool CloudBasicLayerRenderer::alterLight(BaseCloudsModel *model, LightComponent* start = location; direction = light->direction.scale(-1.0); end = location.add(direction.scale(10000.0)); - if (not optimizeSearchLimits(model, &start, &end)) - { + if (not optimizeSearchLimits(model, &start, &end)) { return false; } double ymin, ymax; model->getAltitudeRange(&ymin, &ymax); double light_traversal = (ymax - ymin) * 1.2; - findSegments(model, start, direction, 20, light_traversal, end.sub(start).getNorm(), &inside_depth, &total_depth, segments); + findSegments(model, start, direction, 20, light_traversal, end.sub(start).getNorm(), &inside_depth, &total_depth, + segments); - if (light_traversal < 0.0001) - { + if (light_traversal < 0.0001) { factor = 0.0; - } - else - { + } else { factor = inside_depth / light_traversal; - if (factor > 1.0) - { + if (factor > 1.0) { factor = 1.0; - } - else if (factor > 0.00001) - { + } else if (factor > 0.00001) { factor = sqrt(factor); } } diff --git a/src/render/software/CloudBasicLayerRenderer.h b/src/render/software/CloudBasicLayerRenderer.h index ebeaaf0..1279026 100644 --- a/src/render/software/CloudBasicLayerRenderer.h +++ b/src/render/software/CloudBasicLayerRenderer.h @@ -16,18 +16,19 @@ namespace software { * This renderer simply iters through the cloud layer, collecting cloud segments. * It does not account for local density variations. */ -class SOFTWARESHARED_EXPORT CloudBasicLayerRenderer: public BaseCloudLayerRenderer -{ -public: - CloudBasicLayerRenderer(SoftwareRenderer* parent); +class SOFTWARESHARED_EXPORT CloudBasicLayerRenderer : public BaseCloudLayerRenderer { + public: + CloudBasicLayerRenderer(SoftwareRenderer *parent); virtual Color getColor(BaseCloudsModel *model, const Vector3 &eye, const Vector3 &location) override; - virtual bool alterLight(BaseCloudsModel *model, LightComponent* light, const Vector3 &eye, const Vector3 &location) override; + virtual bool alterLight(BaseCloudsModel *model, LightComponent *light, const Vector3 &eye, + const Vector3 &location) override; -private: - int findSegments(BaseCloudsModel* model, const Vector3 &start, const Vector3 &direction, int max_segments, double max_inside_length, double max_total_length, double* inside_length, double* total_length, CloudSegment* out_segments); + private: + int findSegments(BaseCloudsModel *model, const Vector3 &start, const Vector3 &direction, int max_segments, + double max_inside_length, double max_total_length, double *inside_length, double *total_length, + CloudSegment *out_segments); }; - } } diff --git a/src/render/software/CloudsRenderer.cpp b/src/render/software/CloudsRenderer.cpp index d2a700f..1d8fdb8 100644 --- a/src/render/software/CloudsRenderer.cpp +++ b/src/render/software/CloudsRenderer.cpp @@ -14,71 +14,58 @@ #include "clouds/CloudModelCumuloNimbus.h" #include "clouds/CloudModelStratoCumulus.h" -CloudsRenderer::CloudsRenderer(SoftwareRenderer* parent): - parent(parent) -{ +CloudsRenderer::CloudsRenderer(SoftwareRenderer *parent) : parent(parent) { quality = 0.5; enabled = true; fake_renderer = new BaseCloudLayerRenderer(parent); - CloudLayerDefinition* fake_layer = new CloudLayerDefinition(NULL); + CloudLayerDefinition *fake_layer = new CloudLayerDefinition(NULL); fake_model = new BaseCloudsModel(fake_layer); } -CloudsRenderer::~CloudsRenderer() -{ - for (auto renderer : layer_renderers) - { +CloudsRenderer::~CloudsRenderer() { + for (auto renderer : layer_renderers) { delete renderer; } delete fake_renderer; - for (auto model : layer_models) - { + for (auto model : layer_models) { delete model; } delete fake_model->getLayer(); delete fake_model; } -void CloudsRenderer::setQuality(double factor) -{ +void CloudsRenderer::setQuality(double factor) { this->quality = factor; - for (auto &renderer: layer_renderers) - { + for (auto &renderer : layer_renderers) { renderer->setQuality(factor); } } -void CloudsRenderer::setEnabled(bool enabled) -{ +void CloudsRenderer::setEnabled(bool enabled) { this->enabled = enabled; } -void CloudsRenderer::update() -{ - for (auto renderer : layer_renderers) - { +void CloudsRenderer::update() { + for (auto renderer : layer_renderers) { delete renderer; } layer_renderers.clear(); - for (auto model : layer_models) - { + for (auto model : layer_models) { delete model; } layer_models.clear(); - CloudsDefinition* clouds = parent->getScenery()->getClouds(); + CloudsDefinition *clouds = parent->getScenery()->getClouds(); int n = clouds->count(); - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { layer_renderers.push_back(new CloudBasicLayerRenderer(parent)); - CloudLayerDefinition* layer = clouds->getCloudLayer(i); - BaseCloudsModel* model; - switch (layer->type) - { + CloudLayerDefinition *layer = clouds->getCloudLayer(i); + BaseCloudsModel *model; + switch (layer->type) { case CloudLayerDefinition::STRATOCUMULUS: model = new CloudModelStratoCumulus(layer); break; @@ -108,66 +95,50 @@ void CloudsRenderer::update() setQuality(quality); } -BaseCloudLayerRenderer* CloudsRenderer::getLayerRenderer(unsigned int layer) -{ - if (layer < layer_renderers.size()) - { +BaseCloudLayerRenderer *CloudsRenderer::getLayerRenderer(unsigned int layer) { + if (layer < layer_renderers.size()) { return layer_renderers[layer]; - } - else - { + } else { qWarning("Asked for unknown layer renderer %d", layer); return fake_renderer; } } -BaseCloudsModel* CloudsRenderer::getLayerModel(unsigned int layer) -{ - if (layer < layer_models.size()) - { +BaseCloudsModel *CloudsRenderer::getLayerModel(unsigned int layer) { + if (layer < layer_models.size()) { return layer_models[layer]; - } - else - { + } else { qWarning("Asked for unknown layer model %d", layer); return fake_model; } } -void CloudsRenderer::setLayerModel(unsigned int layer, BaseCloudsModel *model, bool delete_old) -{ - if (layer < layer_models.size()) - { - if (delete_old) - { +void CloudsRenderer::setLayerModel(unsigned int layer, BaseCloudsModel *model, bool delete_old) { + if (layer < layer_models.size()) { + if (delete_old) { delete layer_models[layer]; } layer_models[layer] = model; - } - else - { + } else { qWarning("Asked to set an unknown layer model %d", layer); delete model; } } -Color CloudsRenderer::getColor(const Vector3 &eye, const Vector3 &location, const Color &base) -{ - CloudsDefinition* definition = parent->getScenery()->getClouds(); +Color CloudsRenderer::getColor(const Vector3 &eye, const Vector3 &location, const Color &base) { + CloudsDefinition *definition = parent->getScenery()->getClouds(); int n = definition->count(); - if (not enabled or n < 1) - { + if (not enabled or n < 1) { return base; } /* TODO Iter layers in sorted order */ Color cumul = base; - for (int i = 0; i < n; i++) - { - BaseCloudLayerRenderer* layer_renderer = getLayerRenderer(i); - BaseCloudsModel* layer_model = getLayerModel(i); + for (int i = 0; i < n; i++) { + BaseCloudLayerRenderer *layer_renderer = getLayerRenderer(i); + BaseCloudsModel *layer_model = getLayerModel(i); Color layer_color = layer_renderer->getColor(layer_model, eye, location); @@ -177,21 +148,18 @@ Color CloudsRenderer::getColor(const Vector3 &eye, const Vector3 &location, cons return cumul; } -bool CloudsRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) -{ - CloudsDefinition* definition = parent->getScenery()->getClouds(); +bool CloudsRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) { + CloudsDefinition *definition = parent->getScenery()->getClouds(); int n = definition->count(); - if (not enabled or n < 1) - { + if (not enabled or n < 1) { return true; } /* TODO Iter layers in sorted order */ - for (int i = 0; i < n; i++) - { - BaseCloudLayerRenderer* layer_renderer = getLayerRenderer(i); - BaseCloudsModel* layer_model = getLayerModel(i); + for (int i = 0; i < n; i++) { + BaseCloudLayerRenderer *layer_renderer = getLayerRenderer(i); + BaseCloudsModel *layer_model = getLayerModel(i); layer_renderer->alterLight(layer_model, &light, parent->render_camera->getLocation(), at); } @@ -199,19 +167,16 @@ bool CloudsRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) return true; } -double CloudsRenderer::getHighestAltitude() -{ - CloudsDefinition* definition = parent->getScenery()->getClouds(); +double CloudsRenderer::getHighestAltitude() { + CloudsDefinition *definition = parent->getScenery()->getClouds(); double highest = 0.0; int n = definition->count(); double low, high; - for (int i = 0; i < n; i++) - { - BaseCloudsModel* layer_model = getLayerModel(i); + for (int i = 0; i < n; i++) { + BaseCloudsModel *layer_model = getLayerModel(i); layer_model->getAltitudeRange(&low, &high); - if (high > highest) - { + if (high > highest) { highest = high; } } diff --git a/src/render/software/CloudsRenderer.h b/src/render/software/CloudsRenderer.h index acb28c1..a97e49b 100644 --- a/src/render/software/CloudsRenderer.h +++ b/src/render/software/CloudsRenderer.h @@ -11,10 +11,9 @@ namespace software { /*! * \brief Software renderer of a group of cloud layers. */ -class SOFTWARESHARED_EXPORT CloudsRenderer: public LightFilter -{ -public: - CloudsRenderer(SoftwareRenderer* parent); +class SOFTWARESHARED_EXPORT CloudsRenderer : public LightFilter { + public: + CloudsRenderer(SoftwareRenderer *parent); virtual ~CloudsRenderer(); /** @@ -39,14 +38,14 @@ public: * * The returned renderer is managed by this object and should not be deleted. */ - virtual BaseCloudLayerRenderer* getLayerRenderer(unsigned int layer); + virtual BaseCloudLayerRenderer *getLayerRenderer(unsigned int layer); /*! * \brief Get the cloud model for a given layer. * * The returned model is managed by this object and should not be deleted. */ - virtual BaseCloudsModel* getLayerModel(unsigned int layer); + virtual BaseCloudsModel *getLayerModel(unsigned int layer); /*! * \brief Override de default density model for a given layer. @@ -54,7 +53,7 @@ public: * This must be called after each update(). * Ownership of the model is taken. */ - virtual void setLayerModel(unsigned int layer, BaseCloudsModel* model, bool delete_old=true); + virtual void setLayerModel(unsigned int layer, BaseCloudsModel *model, bool delete_old = true); /*! * \brief Get the composited color, as applied on a base color and location. @@ -72,19 +71,19 @@ public: * Get the highest altitude of all layers. */ double getHighestAltitude(); -private: + + private: double quality; bool enabled; - SoftwareRenderer* parent; + SoftwareRenderer *parent; - std::vector layer_renderers; - BaseCloudLayerRenderer* fake_renderer; + std::vector layer_renderers; + BaseCloudLayerRenderer *fake_renderer; - std::vector layer_models; - BaseCloudsModel* fake_model; + std::vector layer_models; + BaseCloudsModel *fake_model; }; - } } diff --git a/src/render/software/FluidMediumInterface.h b/src/render/software/FluidMediumInterface.h index f706080..b494d7f 100644 --- a/src/render/software/FluidMediumInterface.h +++ b/src/render/software/FluidMediumInterface.h @@ -9,16 +9,14 @@ namespace software { /*! * \brief Interface to a fluid medium compatible class. */ -class SOFTWARESHARED_EXPORT FluidMediumInterface -{ -public: +class SOFTWARESHARED_EXPORT FluidMediumInterface { + public: /*! * Return true if the object may change the fluid medium on the given segment. * When returning true, the object may alter 'segment' to limit its influence. */ - virtual bool checkInfluence(SpaceSegment& segment) const = 0; + virtual bool checkInfluence(SpaceSegment &segment) const = 0; }; - } } diff --git a/src/render/software/FluidMediumManager.cpp b/src/render/software/FluidMediumManager.cpp index 242e0f7..d2fea02 100644 --- a/src/render/software/FluidMediumManager.cpp +++ b/src/render/software/FluidMediumManager.cpp @@ -4,31 +4,25 @@ #include "FluidMediumInterface.h" #include "Color.h" -FluidMediumManager::FluidMediumManager(SoftwareRenderer* renderer): - renderer(renderer) -{ +FluidMediumManager::FluidMediumManager(SoftwareRenderer *renderer) : renderer(renderer) { } -FluidMediumManager::~FluidMediumManager() -{ +FluidMediumManager::~FluidMediumManager() { } -void FluidMediumManager::clearMedia() -{ +void FluidMediumManager::clearMedia() { media.clear(); } -void FluidMediumManager::registerMedium(FluidMediumInterface *medium) -{ +void FluidMediumManager::registerMedium(FluidMediumInterface *medium) { media.push_back(medium); } -Color FluidMediumManager::applyTraversal(const Vector3 &eye, const Vector3 &location, const Color &color) const -{ +Color FluidMediumManager::applyTraversal(const Vector3 &eye, const Vector3 &location, const Color &color) const { // Collect potential segments SpaceSegment ray(eye, location); int max_segments = media.size(); - FluidMediumSegment* segments; + FluidMediumSegment *segments; segments = new FluidMediumSegment[max_segments]; getTraversedMedia(segments, ray, max_segments); @@ -36,14 +30,12 @@ Color FluidMediumManager::applyTraversal(const Vector3 &eye, const Vector3 &loca return color; } -int FluidMediumManager::getTraversedMedia(FluidMediumSegment segments[], const SpaceSegment &ray, int max_segments) const -{ +int FluidMediumManager::getTraversedMedia(FluidMediumSegment segments[], const SpaceSegment &ray, + int max_segments) const { int added = 0; - for (auto &medium : media) - { + for (auto &medium : media) { SpaceSegment ray_inter(ray); - if (added < max_segments and medium->checkInfluence(ray_inter)) - { + if (added < max_segments and medium->checkInfluence(ray_inter)) { // The medium intersect with the ray segments[added++] = {medium, ray_inter}; } diff --git a/src/render/software/FluidMediumManager.h b/src/render/software/FluidMediumManager.h index 99d2194..1f9917c 100644 --- a/src/render/software/FluidMediumManager.h +++ b/src/render/software/FluidMediumManager.h @@ -9,7 +9,7 @@ namespace paysages { namespace software { typedef struct { - FluidMediumInterface* medium; + FluidMediumInterface *medium; SpaceSegment segment; } FluidMediumSegment; @@ -20,9 +20,8 @@ typedef struct { * medium density and properties. * It is mainly used to compute the alteration made by such media on light. */ -class SOFTWARESHARED_EXPORT FluidMediumManager -{ -public: +class SOFTWARESHARED_EXPORT FluidMediumManager { + public: FluidMediumManager(SoftwareRenderer *renderer); virtual ~FluidMediumManager(); @@ -50,11 +49,10 @@ public: */ virtual int getTraversedMedia(FluidMediumSegment segments[], const SpaceSegment &ray, int max_segments) const; -private: + private: SoftwareRenderer *renderer; - std::vector media; + std::vector media; }; - } } diff --git a/src/render/software/GodRaysResult.cpp b/src/render/software/GodRaysResult.cpp index 5a629ae..ce30313 100644 --- a/src/render/software/GodRaysResult.cpp +++ b/src/render/software/GodRaysResult.cpp @@ -1,38 +1,26 @@ #include "GodRaysResult.h" -GodRaysResult::GodRaysResult(double inside_length, double full_length): - inside_length(inside_length), full_length(full_length) -{ +GodRaysResult::GodRaysResult(double inside_length, double full_length) + : inside_length(inside_length), full_length(full_length) { } -Color GodRaysResult::apply(const Color &raw, const Color &atmosphered, const GodRaysParams ¶ms) -{ - if (inside_length == 0.0) - { +Color GodRaysResult::apply(const Color &raw, const Color &atmosphered, const GodRaysParams ¶ms) { + if (inside_length == 0.0) { return raw; - } - else if (inside_length < full_length) - { + } else if (inside_length < full_length) { double diff = full_length - inside_length; double factor = 1.0 - params.penetration * diff; double minimum = params.resistance; double complement = 1.0 - minimum; - if (factor < minimum) - { + if (factor < minimum) { factor = minimum; - } - else - { + } else { factor = pow((factor - minimum) / complement, params.boost) * complement + minimum; } - return Color(raw.r + (atmosphered.r - raw.r) * factor, - raw.g + (atmosphered.g - raw.g) * factor, - raw.b + (atmosphered.b - raw.b) * factor, - atmosphered.a); - } - else - { + return Color(raw.r + (atmosphered.r - raw.r) * factor, raw.g + (atmosphered.g - raw.g) * factor, + raw.b + (atmosphered.b - raw.b) * factor, atmosphered.a); + } else { return atmosphered; } } diff --git a/src/render/software/GodRaysResult.h b/src/render/software/GodRaysResult.h index 15102f4..dec3950 100644 --- a/src/render/software/GodRaysResult.h +++ b/src/render/software/GodRaysResult.h @@ -11,16 +11,15 @@ namespace software { /** * Result of god rays computation. */ -class SOFTWARESHARED_EXPORT GodRaysResult -{ -public: +class SOFTWARESHARED_EXPORT GodRaysResult { + public: typedef struct { double penetration; double resistance; double boost; } GodRaysParams; -public: + public: GodRaysResult() = default; GodRaysResult(double inside_length, double full_length); @@ -29,11 +28,10 @@ public: */ Color apply(const Color &raw, const Color &atmosphered, const GodRaysParams ¶ms); -private: + private: double inside_length; double full_length; }; - } } diff --git a/src/render/software/GodRaysSampler.cpp b/src/render/software/GodRaysSampler.cpp index 4233cd6..dffd769 100644 --- a/src/render/software/GodRaysSampler.cpp +++ b/src/render/software/GodRaysSampler.cpp @@ -15,8 +15,7 @@ #include "Interpolation.h" #include -GodRaysSampler::GodRaysSampler() -{ +GodRaysSampler::GodRaysSampler() { enabled = true; bounds = new SpaceSegment(); definition = new GodRaysDefinition(NULL); @@ -30,25 +29,23 @@ GodRaysSampler::GodRaysSampler() setQuality(0.5); } -GodRaysSampler::~GodRaysSampler() -{ +GodRaysSampler::~GodRaysSampler() { delete definition; delete bounds; delete camera_location; delete[] data; } -void GodRaysSampler::prepare(SoftwareRenderer *renderer) -{ +void GodRaysSampler::prepare(SoftwareRenderer *renderer) { setCameraLocation(renderer->getCameraLocation(VECTOR_ZERO)); setLighting(renderer->getLightingManager()); - setAltitudes(renderer->getScenery()->getTerrain()->getHeightInfo().min_height, renderer->getCloudsRenderer()->getHighestAltitude()); + setAltitudes(renderer->getScenery()->getTerrain()->getHeightInfo().min_height, + renderer->getCloudsRenderer()->getHighestAltitude()); renderer->getScenery()->getAtmosphere()->childGodRays()->copy(definition); reset(); } -void GodRaysSampler::reset() -{ +void GodRaysSampler::reset() { *bounds = SpaceSegment(Vector3(camera_location->x - max_length, low_altitude, camera_location->z - max_length), Vector3(camera_location->x + max_length, high_altitude, camera_location->z + max_length)); samples_x = round(bounds->getXDiff() / sampling_step) + 1; @@ -58,70 +55,57 @@ void GodRaysSampler::reset() long n = samples_x * samples_y * samples_z; delete[] data; data = new double[n]; - for (long i = 0; i < n; i++) - { + for (long i = 0; i < n; i++) { data[i] = -1.0; } } -void GodRaysSampler::setEnabled(bool enabled) -{ +void GodRaysSampler::setEnabled(bool enabled) { this->enabled = enabled; } -void GodRaysSampler::setLighting(LightingManager *manager) -{ +void GodRaysSampler::setLighting(LightingManager *manager) { this->lighting = manager; } -void GodRaysSampler::setQuality(double factor) -{ +void GodRaysSampler::setQuality(double factor) { setQuality(5.0 / (factor * 8.0 + 1.0), 100.0, 5.0 / (factor * 80.0 + 1.0)); reset(); } -void GodRaysSampler::setQuality(double sampling_step, double max_length, double walk_step) -{ +void GodRaysSampler::setQuality(double sampling_step, double max_length, double walk_step) { this->sampling_step = sampling_step; this->max_length = max_length; this->walk_step = walk_step; } -void GodRaysSampler::setCameraLocation(const Vector3 &location) -{ +void GodRaysSampler::setCameraLocation(const Vector3 &location) { *camera_location = location; } -void GodRaysSampler::setAltitudes(double low, double high) -{ +void GodRaysSampler::setAltitudes(double low, double high) { low_altitude = low; high_altitude = high; } -void GodRaysSampler::getSamples(int *x, int *y, int *z) const -{ +void GodRaysSampler::getSamples(int *x, int *y, int *z) const { *x = samples_x; *y = samples_y; *z = samples_z; } -Color GodRaysSampler::getRawLight(const Vector3 &location, bool filtered) const -{ - if (lighting) - { +Color GodRaysSampler::getRawLight(const Vector3 &location, bool filtered) const { + if (lighting) { LightStatus status(lighting, location, *camera_location, filtered); - status.setSafetyOffset(0.0); // Not a hard surface, safety offset not needed + status.setSafetyOffset(0.0); // Not a hard surface, safety offset not needed lighting->fillStatus(status, location); return status.getSum(); - } - else - { + } else { return COLOR_TRANSPARENT; } } -double GodRaysSampler::getCachedLight(const Vector3 &location) -{ +double GodRaysSampler::getCachedLight(const Vector3 &location) { double x = location.x - bounds->getStart().x; double y = location.y - bounds->getStart().y; double z = location.z - bounds->getStart().z; @@ -131,30 +115,20 @@ double GodRaysSampler::getCachedLight(const Vector3 &location) int iz = (int)floor(z / sampling_step); // Check cache limits - if (ix < 0 || ix >= samples_x - 1 || iy < 0 || iy >= samples_y - 1 || iz < 0 || iz >= samples_z - 1) - { + if (ix < 0 || ix >= samples_x - 1 || iy < 0 || iy >= samples_y - 1 || iz < 0 || iz >= samples_z - 1) { return 1.0; } // Hit cache - double p[8] = { - getCache(ix, iy, iz), - getCache(ix + 1, iy, iz), - getCache(ix + 1, iy + 1, iz), - getCache(ix, iy + 1, iz), - getCache(ix, iy, iz + 1), - getCache(ix + 1, iy, iz + 1), - getCache(ix + 1, iy + 1, iz + 1), - getCache(ix, iy + 1, iz + 1) - }; - return Interpolation::trilinear(p, - (x - sampling_step * double(ix)) / sampling_step, + double p[8] = {getCache(ix, iy, iz), getCache(ix + 1, iy, iz), getCache(ix + 1, iy + 1, iz), + getCache(ix, iy + 1, iz), getCache(ix, iy, iz + 1), getCache(ix + 1, iy, iz + 1), + getCache(ix + 1, iy + 1, iz + 1), getCache(ix, iy + 1, iz + 1)}; + return Interpolation::trilinear(p, (x - sampling_step * double(ix)) / sampling_step, (y - sampling_step * double(iy)) / sampling_step, (z - sampling_step * double(iz)) / sampling_step); } -GodRaysResult GodRaysSampler::getResult(const SpaceSegment &segment) -{ +GodRaysResult GodRaysSampler::getResult(const SpaceSegment &segment) { Vector3 step = segment.getEnd().sub(segment.getStart()); double max_length = step.getNorm(); step = step.normalize().scale(walk_step); @@ -162,13 +136,11 @@ GodRaysResult GodRaysSampler::getResult(const SpaceSegment &segment) double travelled = 0.0; double inside = 0.0; - if (max_length > this->max_length) - { + if (max_length > this->max_length) { max_length = this->max_length; } - while (travelled < max_length) - { + while (travelled < max_length) { double light = getCachedLight(walker); inside += light * walk_step; @@ -180,10 +152,8 @@ GodRaysResult GodRaysSampler::getResult(const SpaceSegment &segment) return GodRaysResult(inside, travelled); } -Color GodRaysSampler::apply(const Color &raw, const Color &atmosphered, const Vector3 &location) -{ - if (enabled) - { +Color GodRaysSampler::apply(const Color &raw, const Color &atmosphered, const Vector3 &location) { + if (enabled) { GodRaysResult result = getResult(SpaceSegment(*camera_location, location)); GodRaysResult::GodRaysParams params; @@ -192,28 +162,21 @@ Color GodRaysSampler::apply(const Color &raw, const Color &atmosphered, const Ve params.boost = definition->propBoost()->getValue(); return result.apply(raw, atmosphered, params); - } - else - { + } else { return atmosphered; } } -inline double GodRaysSampler::getCache(int x, int y, int z) -{ +inline double GodRaysSampler::getCache(int x, int y, int z) { double *cache = data + z * samples_x * samples_y + y * samples_x + x; - if (*cache < 0.0) - { - Vector3 location = Vector3(bounds->getStart().x + sampling_step * (double)x, - bounds->getStart().y + sampling_step * (double)y, - bounds->getStart().z + sampling_step * (double)z); + if (*cache < 0.0) { + Vector3 location = + Vector3(bounds->getStart().x + sampling_step * (double)x, bounds->getStart().y + sampling_step * (double)y, + bounds->getStart().z + sampling_step * (double)z); double unfiltered_power = getRawLight(location, false).getPower(); - if (unfiltered_power == 0.0) - { + if (unfiltered_power == 0.0) { *cache = 1.0; - } - else - { + } else { *cache = getRawLight(location, true).getPower() / unfiltered_power; } } diff --git a/src/render/software/GodRaysSampler.h b/src/render/software/GodRaysSampler.h index 27efc67..a1e1c1e 100644 --- a/src/render/software/GodRaysSampler.h +++ b/src/render/software/GodRaysSampler.h @@ -9,16 +9,23 @@ namespace software { /** * 3D sampler for "god rays". */ -class SOFTWARESHARED_EXPORT GodRaysSampler -{ -public: +class SOFTWARESHARED_EXPORT GodRaysSampler { + public: GodRaysSampler(); ~GodRaysSampler(); - inline const SpaceSegment &getBounds() const {return *bounds;} - inline double getSamplingStep() const {return sampling_step;} - inline double getMaxLength() const {return max_length;} - inline double getWalkStep() const {return walk_step;} + inline const SpaceSegment &getBounds() const { + return *bounds; + } + inline double getSamplingStep() const { + return sampling_step; + } + inline double getMaxLength() const { + return max_length; + } + inline double getWalkStep() const { + return walk_step; + } /** * Prepare the sampler from a renderer. @@ -92,10 +99,10 @@ public: */ Color apply(const Color &raw, const Color &atmosphered, const Vector3 &location); -private: + private: double getCache(int x, int y, int z); -private: + private: bool enabled; SpaceSegment *bounds; @@ -117,7 +124,6 @@ private: double *data; }; - } } diff --git a/src/render/software/LightComponent.cpp b/src/render/software/LightComponent.cpp index ac00e66..557ea3f 100644 --- a/src/render/software/LightComponent.cpp +++ b/src/render/software/LightComponent.cpp @@ -1,6 +1,5 @@ #include "LightComponent.h" -LightComponent::LightComponent(const Color &color, const Vector3 &direction, double reflection, bool altered): - color(color), direction(direction), reflection(reflection), altered(altered) -{ +LightComponent::LightComponent(const Color &color, const Vector3 &direction, double reflection, bool altered) + : color(color), direction(direction), reflection(reflection), altered(altered) { } diff --git a/src/render/software/LightComponent.h b/src/render/software/LightComponent.h index 4a0140b..26cc120 100644 --- a/src/render/software/LightComponent.h +++ b/src/render/software/LightComponent.h @@ -14,18 +14,16 @@ namespace software { * * A light component represents the amount of light received at a point from a given direction. */ -class SOFTWARESHARED_EXPORT LightComponent -{ -public: +class SOFTWARESHARED_EXPORT LightComponent { + public: LightComponent() = default; LightComponent(const Color &color, const Vector3 &direction, double reflection = 0.0, bool altered = true); - Color color; // Light power - Vector3 direction; // Direction the light is travelling - double reflection; /* Reflected factor of the light (for specular lighting) */ - bool altered; /* Should the light be filtered or masked (by atmosphere, water, ground, clouds...) */ + Color color; // Light power + Vector3 direction; // Direction the light is travelling + double reflection; /* Reflected factor of the light (for specular lighting) */ + bool altered; /* Should the light be filtered or masked (by atmosphere, water, ground, clouds...) */ }; - } } diff --git a/src/render/software/LightFilter.cpp b/src/render/software/LightFilter.cpp index 7128c75..1f78294 100644 --- a/src/render/software/LightFilter.cpp +++ b/src/render/software/LightFilter.cpp @@ -1,6 +1,5 @@ #include "LightFilter.h" -bool LightFilter::applyLightFilter(LightComponent &, const Vector3 &) -{ +bool LightFilter::applyLightFilter(LightComponent &, const Vector3 &) { return false; } diff --git a/src/render/software/LightFilter.h b/src/render/software/LightFilter.h index eb9b90b..480cd2c 100644 --- a/src/render/software/LightFilter.h +++ b/src/render/software/LightFilter.h @@ -9,9 +9,8 @@ namespace software { /** * @brief Interface for rendering parts that can alter light. */ -class SOFTWARESHARED_EXPORT LightFilter -{ -public: +class SOFTWARESHARED_EXPORT LightFilter { + public: /** * @brief Apply filtering on a light component. * @@ -20,7 +19,6 @@ public: */ virtual bool applyLightFilter(LightComponent &light, const Vector3 &at) = 0; }; - } } diff --git a/src/render/software/LightSource.h b/src/render/software/LightSource.h index 9cf8751..8d472ad 100644 --- a/src/render/software/LightSource.h +++ b/src/render/software/LightSource.h @@ -9,9 +9,8 @@ namespace software { /** * Source of dynamic lights. */ -class SOFTWARESHARED_EXPORT LightSource -{ -public: +class SOFTWARESHARED_EXPORT LightSource { + public: LightSource() = default; /** @@ -21,7 +20,6 @@ public: */ virtual bool getLightsAt(std::vector &result, const Vector3 &location) const = 0; }; - } } diff --git a/src/render/software/LightStatus.cpp b/src/render/software/LightStatus.cpp index e06baa5..0aa3f9f 100644 --- a/src/render/software/LightStatus.cpp +++ b/src/render/software/LightStatus.cpp @@ -5,8 +5,7 @@ #include "Color.h" #include "SurfaceMaterial.h" -LightStatus::LightStatus(LightingManager *manager, const Vector3 &location, const Vector3 &eye, bool filtered) -{ +LightStatus::LightStatus(LightingManager *manager, const Vector3 &location, const Vector3 &eye, bool filtered) { this->safety_offset = -0.0000001; this->max_power = 0.0; this->manager = manager; @@ -15,38 +14,29 @@ LightStatus::LightStatus(LightingManager *manager, const Vector3 &location, cons this->filtered = filtered; } -void LightStatus::pushComponent(LightComponent component) -{ - if (filtered) - { +void LightStatus::pushComponent(LightComponent component) { + if (filtered) { double power = component.color.getPower(); - if (component.altered && (power < max_power * 0.05 || power < 0.001)) - { + if (component.altered && (power < max_power * 0.05 || power < 0.001)) { // Exclude filtered lights that are owerpowered by a previous one return; } - if (manager->alterLight(component, location.add(component.direction.scale(safety_offset)))) - { - if (power > max_power) - { + if (manager->alterLight(component, location.add(component.direction.scale(safety_offset)))) { + if (power > max_power) { max_power = power; } components.push_back(component); } - } - else - { + } else { components.push_back(component); } } -Color LightStatus::apply(const Vector3 &normal, const SurfaceMaterial &material) -{ +Color LightStatus::apply(const Vector3 &normal, const SurfaceMaterial &material) { Color final(0.0, 0.0, 0.0, 0.0); - for (auto component: components) - { + for (auto component : components) { final = final.add(manager->applyFinalComponent(component, eye, location, normal, material)); } @@ -54,19 +44,16 @@ Color LightStatus::apply(const Vector3 &normal, const SurfaceMaterial &material) return final; } -Color LightStatus::getSum() const -{ +Color LightStatus::getSum() const { Color final = COLOR_BLACK; - for (auto component: components) - { + for (auto component : components) { final = final.add(component.color); } return final; } -void LightStatus::setSafetyOffset(double safety_offset) -{ +void LightStatus::setSafetyOffset(double safety_offset) { this->safety_offset = -safety_offset; } diff --git a/src/render/software/LightStatus.h b/src/render/software/LightStatus.h index 6de1251..166b0ce 100644 --- a/src/render/software/LightStatus.h +++ b/src/render/software/LightStatus.h @@ -13,12 +13,13 @@ namespace software { * * The light status is the combination of all LightComponent received at a given location. */ -class SOFTWARESHARED_EXPORT LightStatus -{ -public: - LightStatus(LightingManager *manager, const Vector3 &location, const Vector3 &eye, bool filtered=true); +class SOFTWARESHARED_EXPORT LightStatus { + public: + LightStatus(LightingManager *manager, const Vector3 &location, const Vector3 &eye, bool filtered = true); - inline Vector3 getLocation() const {return location;} + inline Vector3 getLocation() const { + return location; + } void pushComponent(LightComponent component); @@ -38,16 +39,15 @@ public: */ void setSafetyOffset(double safety_offset); -private: + private: double safety_offset; double max_power; - LightingManager* manager; + LightingManager *manager; Vector3 location; Vector3 eye; bool filtered; std::vector components; }; - } } diff --git a/src/render/software/LightingManager.cpp b/src/render/software/LightingManager.cpp index 5b087a2..b9744d1 100644 --- a/src/render/software/LightingManager.cpp +++ b/src/render/software/LightingManager.cpp @@ -7,112 +7,89 @@ #include "Color.h" #include "SurfaceMaterial.h" -LightingManager::LightingManager() -{ +LightingManager::LightingManager() { specularity = true; filtering = true; } -int LightingManager::getStaticLightsCount() const -{ +int LightingManager::getStaticLightsCount() const { return static_lights.size(); } -int LightingManager::getSourcesCount() const -{ +int LightingManager::getSourcesCount() const { return sources.size(); } -int LightingManager::getFiltersCount() const -{ +int LightingManager::getFiltersCount() const { return filters.size(); } -void LightingManager::clearStaticLights() -{ +void LightingManager::clearStaticLights() { static_lights.clear(); } -void LightingManager::addStaticLight(const LightComponent &light) -{ +void LightingManager::addStaticLight(const LightComponent &light) { static_lights.push_back(light); } -void LightingManager::clearSources() -{ +void LightingManager::clearSources() { sources.clear(); } -void LightingManager::registerSource(LightSource *source) -{ - if (std::find(sources.begin(), sources.end(), source) == sources.end()) - { +void LightingManager::registerSource(LightSource *source) { + if (std::find(sources.begin(), sources.end(), source) == sources.end()) { sources.push_back(source); } } -void LightingManager::unregisterSource(LightSource *source) -{ - if (std::find(sources.begin(), sources.end(), source) != sources.end()) - { +void LightingManager::unregisterSource(LightSource *source) { + if (std::find(sources.begin(), sources.end(), source) != sources.end()) { sources.erase(std::find(sources.begin(), sources.end(), source)); } } -void LightingManager::clearFilters() -{ +void LightingManager::clearFilters() { filters.clear(); } -void LightingManager::registerFilter(LightFilter* filter) -{ - if (std::find(filters.begin(), filters.end(), filter) == filters.end()) - { +void LightingManager::registerFilter(LightFilter *filter) { + if (std::find(filters.begin(), filters.end(), filter) == filters.end()) { filters.push_back(filter); } } -void LightingManager::unregisterFilter(LightFilter *filter) -{ - if (std::find(filters.begin(), filters.end(), filter) != filters.end()) - { +void LightingManager::unregisterFilter(LightFilter *filter) { + if (std::find(filters.begin(), filters.end(), filter) != filters.end()) { filters.erase(std::find(filters.begin(), filters.end(), filter)); } } -bool LightingManager::alterLight(LightComponent &component, const Vector3 &location) -{ - if (filtering and component.altered) - { - for (auto filter:filters) - { - if (not filter->applyLightFilter(component, location)) - { +bool LightingManager::alterLight(LightComponent &component, const Vector3 &location) { + if (filtering and component.altered) { + for (auto filter : filters) { + if (not filter->applyLightFilter(component, location)) { return false; } } } - if (not specularity) - { + if (not specularity) { component.reflection = 0.0; } return component.color.getPower() > 0.0001; } -void LightingManager::setSpecularity(bool enabled) -{ +void LightingManager::setSpecularity(bool enabled) { specularity = enabled; } -void LightingManager::setFiltering(bool enabled) -{ +void LightingManager::setFiltering(bool enabled) { filtering = enabled; } -Color LightingManager::applyFinalComponent(const LightComponent &component, const Vector3 &eye, const Vector3 &location, const Vector3 &normal, const SurfaceMaterial &material) -{ +Color LightingManager::applyFinalComponent(const LightComponent &component, const Vector3 &eye, const Vector3 &location, + const Vector3 &normal, const SurfaceMaterial &material) { Color result, light_color; double normal_norm; Vector3 direction_inv; @@ -121,8 +98,7 @@ Color LightingManager::applyFinalComponent(const LightComponent &component, cons direction_inv = component.direction.normalize().scale(-1.0); normal_norm = normal.getNorm(); - if (normal_norm > 1.0) - { + if (normal_norm > 1.0) { normal_norm = 1.0; } @@ -131,35 +107,28 @@ Color LightingManager::applyFinalComponent(const LightComponent &component, cons /* diffused light */ double diffuse = direction_inv.dotProduct(normal.normalize()); double sign = (diffuse < 0.0) ? -1.0 : 1.0; - if (material.hardness <= 0.5) - { + if (material.hardness <= 0.5) { double hardness = material.hardness * 2.0; diffuse = (1.0 - hardness) * (diffuse * diffuse) * sign + hardness * diffuse; - } - else if (diffuse != 0.0) - { + } else if (diffuse != 0.0) { double hardness = (material.hardness - 0.5) * 2.0; diffuse = (1.0 - hardness) * diffuse + hardness * sign * sqrt(fabs(diffuse)); } diffuse = (diffuse + (1.0 - normal_norm)) / (1.0 + (1.0 - normal_norm)); - if (diffuse > 0.0) - { + if (diffuse > 0.0) { result.r += diffuse * material.base->r * light_color.r; result.g += diffuse * material.base->g * light_color.g; result.b += diffuse * material.base->b * light_color.b; } /* specular reflection */ - if (material.shininess > 0.0 && material.reflection > 0.0 && component.reflection > 0.0) - { + if (material.shininess > 0.0 && material.reflection > 0.0 && component.reflection > 0.0) { Vector3 view = location.sub(eye).normalize(); Vector3 reflect = direction_inv.sub(normal.scale(2.0 * direction_inv.dotProduct(normal))); double specular = reflect.dotProduct(view); - if (specular > 0.0) - { + if (specular > 0.0) { specular = pow(specular, material.shininess) * material.reflection * component.reflection * normal_norm; - if (specular > 0.0) - { + if (specular > 0.0) { result.r += specular * light_color.r; result.g += specular * light_color.g; result.b += specular * light_color.b; @@ -190,27 +159,22 @@ Color LightingManager::applyFinalComponent(const LightComponent &component, cons return result; } -void LightingManager::fillStatus(LightStatus &status, const Vector3 &location) const -{ - for (auto &light: static_lights) - { +void LightingManager::fillStatus(LightStatus &status, const Vector3 &location) const { + for (auto &light : static_lights) { status.pushComponent(light); } - for (auto source: sources) - { + for (auto source : sources) { std::vector lights; - if (source->getLightsAt(lights, location)) - { - for (auto &light: lights) - { + if (source->getLightsAt(lights, location)) { + for (auto &light : lights) { status.pushComponent(light); } } } } -Color LightingManager::apply(const Vector3 &eye, const Vector3 &location, const Vector3 &normal, const SurfaceMaterial &material) -{ +Color LightingManager::apply(const Vector3 &eye, const Vector3 &location, const Vector3 &normal, + const SurfaceMaterial &material) { LightStatus status(this, location, eye); fillStatus(status, location); return status.apply(normal, material); diff --git a/src/render/software/LightingManager.h b/src/render/software/LightingManager.h index 49cf1ae..83e569b 100644 --- a/src/render/software/LightingManager.h +++ b/src/render/software/LightingManager.h @@ -16,9 +16,8 @@ namespace software { * There are both static and dynamic lights. * A dynamic light depends on the location at which the lighting occurs. */ -class SOFTWARESHARED_EXPORT LightingManager -{ -public: +class SOFTWARESHARED_EXPORT LightingManager { + public: LightingManager(); int getStaticLightsCount() const; @@ -85,7 +84,8 @@ public: /** * Apply a final component on a surface material. */ - Color applyFinalComponent(const LightComponent &component, const Vector3 &eye, const Vector3 &location, const Vector3 &normal, const SurfaceMaterial &material); + Color applyFinalComponent(const LightComponent &component, const Vector3 &eye, const Vector3 &location, + const Vector3 &normal, const SurfaceMaterial &material); /** * Compute the light status at a given location. @@ -97,14 +97,13 @@ public: */ Color apply(const Vector3 &eye, const Vector3 &location, const Vector3 &normal, const SurfaceMaterial &material); -private: + private: bool specularity; bool filtering; std::vector static_lights; std::vector filters; std::vector sources; }; - } } diff --git a/src/render/software/NightSky.cpp b/src/render/software/NightSky.cpp index d70923e..810e2a8 100644 --- a/src/render/software/NightSky.cpp +++ b/src/render/software/NightSky.cpp @@ -17,45 +17,36 @@ #define MOON_RADIUS 1737.4 #define MOON_RADIUS_SCALED (MOON_RADIUS / WORLD_SCALING) -NightSky::NightSky(SoftwareRenderer* renderer): - renderer(renderer) -{ +NightSky::NightSky(SoftwareRenderer *renderer) : renderer(renderer) { } -NightSky::~NightSky() -{ +NightSky::~NightSky() { } -void NightSky::update() -{ +void NightSky::update() { } -const Color NightSky::getColor(double altitude, const Vector3 &direction) -{ - AtmosphereDefinition* atmosphere = renderer->getScenery()->getAtmosphere(); +const Color NightSky::getColor(double altitude, const Vector3 &direction) { + AtmosphereDefinition *atmosphere = renderer->getScenery()->getAtmosphere(); Color result(0.01, 0.012, 0.03); Vector3 location(0.0, altitude, 0.0); // Get stars Vector3 sun_direction = renderer->getAtmosphereRenderer()->getSunDirection(); - if (sun_direction.y < 0.1) - { + if (sun_direction.y < 0.1) { double factor = (sun_direction.y < 0.0) ? 1.0 : 1.0 - (sun_direction.y * 10.0); - for (const auto &star: atmosphere->stars) - { - if (star.location.dotProduct(direction) >= 0) - { + for (const auto &star : atmosphere->stars) { + if (star.location.dotProduct(direction) >= 0) { double radius = star.radius; Vector3 hit1, hit2; int hits = Geometry::rayIntersectSphere(location, direction, star.location, radius, &hit1, &hit2); - if (hits > 1) - { - double dist = hit2.sub(hit1).getNorm() / radius; // distance between intersection points (relative to radius) + if (hits > 1) { + double dist = + hit2.sub(hit1).getNorm() / radius; // distance between intersection points (relative to radius) Color color = star.col; - if (dist <= 0.5) - { + if (dist <= 0.5) { color.a *= (1.0 - dist / 0.5) * factor; } result.mask(color); @@ -68,38 +59,34 @@ const Color NightSky::getColor(double altitude, const Vector3 &direction) VectorSpherical moon_location_s = {MOON_DISTANCE_SCALED, atmosphere->moon_theta, -atmosphere->moon_phi}; Vector3 moon_position(moon_location_s); Vector3 moon_direction = moon_position.normalize(); - if (moon_direction.dotProduct(direction) >= 0) - { + if (moon_direction.dotProduct(direction) >= 0) { double moon_radius = MOON_RADIUS_SCALED * 5.0 * atmosphere->moon_radius; Vector3 hit1, hit2; int hits = Geometry::rayIntersectSphere(location, direction, moon_position, moon_radius, &hit1, &hit2); - if (hits > 1) - { - double dist = hit2.sub(hit1).getNorm() / moon_radius; // distance between intersection points (relative to radius) + if (hits > 1) { + double dist = + hit2.sub(hit1).getNorm() / moon_radius; // distance between intersection points (relative to radius) Vector3 nearest = (hit1.sub(location).getNorm() > hit2.sub(location).getNorm()) ? hit2 : hit1; SurfaceMaterial moon_material(Color(3.0, 3.0, 3.0)); moon_material.validate(); - Color moon_color = renderer->applyLightingToSurface(nearest, nearest.sub(moon_position).normalize(), moon_material); - if (dist <= 0.05) - { + Color moon_color = + renderer->applyLightingToSurface(nearest, nearest.sub(moon_position).normalize(), moon_material); + if (dist <= 0.05) { moon_color.a *= 1.0 - dist / 0.05; } result.mask(moon_color); } } - return result; - } -bool NightSky::getLightsAt(std::vector &result, const Vector3 &) const -{ +bool NightSky::getLightsAt(std::vector &result, const Vector3 &) const { LightComponent moon, sky; - AtmosphereDefinition* atmosphere = renderer->getScenery()->getAtmosphere(); + AtmosphereDefinition *atmosphere = renderer->getScenery()->getAtmosphere(); VectorSpherical moon_location_s = {MOON_DISTANCE_SCALED, atmosphere->moon_theta, -atmosphere->moon_phi}; moon.color = Color(0.03, 0.03, 0.03); // TODO take moon phase into account diff --git a/src/render/software/NightSky.h b/src/render/software/NightSky.h index c305f21..b7e1d7a 100644 --- a/src/render/software/NightSky.h +++ b/src/render/software/NightSky.h @@ -11,10 +11,9 @@ namespace software { /*! * \brief Night sky renderer. */ -class SOFTWARESHARED_EXPORT NightSky: public LightSource -{ -public: - NightSky(SoftwareRenderer* renderer); +class SOFTWARESHARED_EXPORT NightSky : public LightSource { + public: + NightSky(SoftwareRenderer *renderer); virtual ~NightSky(); /*! @@ -30,10 +29,9 @@ public: virtual bool getLightsAt(std::vector &result, const Vector3 &location) const override; -private: - SoftwareRenderer* renderer; + private: + SoftwareRenderer *renderer; }; - } } diff --git a/src/render/software/Rasterizer.cpp b/src/render/software/Rasterizer.cpp index 6e4fc2c..0c5dbeb 100644 --- a/src/render/software/Rasterizer.cpp +++ b/src/render/software/Rasterizer.cpp @@ -7,8 +7,7 @@ #include "Vector3.h" #include "RenderProgress.h" -struct paysages::software::ScanPoint -{ +struct paysages::software::ScanPoint { int x; int y; struct { @@ -25,17 +24,15 @@ struct paysages::software::ScanPoint bool front_facing; }; -struct paysages::software::RenderScanlines -{ - ScanPoint* up; - ScanPoint* down; +struct paysages::software::RenderScanlines { + ScanPoint *up; + ScanPoint *down; int left; int right; }; -Rasterizer::Rasterizer(SoftwareRenderer* renderer, RenderProgress *progress, int client_id, const Color &color): - renderer(renderer), progress(progress), client_id(client_id) -{ +Rasterizer::Rasterizer(SoftwareRenderer *renderer, RenderProgress *progress, int client_id, const Color &color) + : renderer(renderer), progress(progress), client_id(client_id) { this->color = new Color(color); interrupted = false; @@ -46,42 +43,36 @@ Rasterizer::Rasterizer(SoftwareRenderer* renderer, RenderProgress *progress, int setQuality(0.5); } -Rasterizer::~Rasterizer() -{ +Rasterizer::~Rasterizer() { delete color; } -void Rasterizer::interrupt() -{ +void Rasterizer::interrupt() { interrupted = true; } -void Rasterizer::setQuality(double) -{ +void Rasterizer::setQuality(double) { } -void Rasterizer::setColor(const Color &color) -{ +void Rasterizer::setColor(const Color &color) { *this->color = color; } -void Rasterizer::setBackFaceCulling(bool cull) -{ +void Rasterizer::setBackFaceCulling(bool cull) { this->backface_culling = cull; } -void Rasterizer::setAutoCutLimit(double limit) -{ +void Rasterizer::setAutoCutLimit(double limit) { this->auto_cut_limit = limit; } -void Rasterizer::resetTriangleCount() -{ +void Rasterizer::resetTriangleCount() { triangle_count = 0; } -bool Rasterizer::pushProjectedTriangle(CanvasPortion *canvas, const Vector3 &pixel1, const Vector3 &pixel2, const Vector3 &pixel3, const Vector3 &location1, const Vector3 &location2, const Vector3 &location3) -{ +bool Rasterizer::pushProjectedTriangle(CanvasPortion *canvas, const Vector3 &pixel1, const Vector3 &pixel2, + const Vector3 &pixel3, const Vector3 &location1, const Vector3 &location2, + const Vector3 &location3) { ScanPoint point1, point2, point3; double limit_width = (double)(canvas->getWidth() - 1); double limit_height = (double)(canvas->getHeight() - 1); @@ -92,23 +83,25 @@ bool Rasterizer::pushProjectedTriangle(CanvasPortion *canvas, const Vector3 &pix Vector3 dpixel3 = pixel3.sub(canvas_offset); double limit_near = renderer->render_camera->getPerspective().znear; - if ((dpixel1.z < limit_near && dpixel2.z < limit_near && dpixel3.z < limit_near) || (dpixel1.x < 0.0 && dpixel2.x < 0.0 && dpixel3.x < 0.0) || (dpixel1.y < 0.0 && dpixel2.y < 0.0 && dpixel3.y < 0.0) || (dpixel1.x > limit_width && dpixel2.x > limit_width && dpixel3.x > limit_width) || (dpixel1.y > limit_height && dpixel2.y > limit_height && dpixel3.y > limit_height)) - { + if ((dpixel1.z < limit_near && dpixel2.z < limit_near && dpixel3.z < limit_near) || + (dpixel1.x < 0.0 && dpixel2.x < 0.0 && dpixel3.x < 0.0) || + (dpixel1.y < 0.0 && dpixel2.y < 0.0 && dpixel3.y < 0.0) || + (dpixel1.x > limit_width && dpixel2.x > limit_width && dpixel3.x > limit_width) || + (dpixel1.y > limit_height && dpixel2.y > limit_height && dpixel3.y > limit_height)) { // Fully outside screen return false; - } - else if (dpixel1.z < limit_near || dpixel2.z < limit_near || dpixel3.z < limit_near) - { + } else if (dpixel1.z < limit_near || dpixel2.z < limit_near || dpixel3.z < limit_near) { // Intersects the near frustum plane, needs cutting // ... except if the triangle is already small - return location1.sub(location2).getNorm() > auto_cut_limit && location2.sub(location3).getNorm() > auto_cut_limit && location3.sub(location1).getNorm() > auto_cut_limit; + return location1.sub(location2).getNorm() > auto_cut_limit && + location2.sub(location3).getNorm() > auto_cut_limit && + location3.sub(location1).getNorm() > auto_cut_limit; } // Check the poylgon's facing (front-face or back-face) Vector3 normal = dpixel2.sub(dpixel1).crossProduct(dpixel3.sub(dpixel1)); bool front_facing = (normal.z >= 0.0); - if (backface_culling and not front_facing) - { + if (backface_culling and not front_facing) { return false; } @@ -165,16 +158,14 @@ bool Rasterizer::pushProjectedTriangle(CanvasPortion *canvas, const Vector3 &pix return false; } -void Rasterizer::pushTriangle(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3) -{ +void Rasterizer::pushTriangle(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3) { Vector3 p1, p2, p3; p1 = getRenderer()->projectPoint(v1); p2 = getRenderer()->projectPoint(v2); p3 = getRenderer()->projectPoint(v3); - if (pushProjectedTriangle(canvas, p1, p2, p3, v1, v2, v3)) - { + if (pushProjectedTriangle(canvas, p1, p2, p3, v1, v2, v3)) { // Cutting needed Vector3 vm1 = v1.midPointTo(v2); Vector3 vm2 = v2.midPointTo(v3); @@ -186,8 +177,8 @@ void Rasterizer::pushTriangle(CanvasPortion *canvas, const Vector3 &v1, const Ve } } -void Rasterizer::pushDisplacedTriangle(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, const Vector3 &ov1, const Vector3 &ov2, const Vector3 &ov3) -{ +void Rasterizer::pushDisplacedTriangle(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, + const Vector3 &ov1, const Vector3 &ov2, const Vector3 &ov3) { Vector3 p1, p2, p3; // TODO v1, v2 and v3 are lost, but may be useful (avoid need to unproject) @@ -195,8 +186,7 @@ void Rasterizer::pushDisplacedTriangle(CanvasPortion *canvas, const Vector3 &v1, p2 = getRenderer()->projectPoint(v2); p3 = getRenderer()->projectPoint(v3); - if (pushProjectedTriangle(canvas, p1, p2, p3, ov1, ov2, ov3)) - { + if (pushProjectedTriangle(canvas, p1, p2, p3, ov1, ov2, ov3)) { // Cutting needed Vector3 vm1 = v1.midPointTo(v2); Vector3 vm2 = v2.midPointTo(v3); @@ -211,20 +201,20 @@ void Rasterizer::pushDisplacedTriangle(CanvasPortion *canvas, const Vector3 &v1, } } -void Rasterizer::pushQuad(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, const Vector3 &v4) -{ +void Rasterizer::pushQuad(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, + const Vector3 &v4) { pushTriangle(canvas, v2, v3, v1); pushTriangle(canvas, v4, v1, v3); } -void Rasterizer::pushDisplacedQuad(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, const Vector3 &v4, const Vector3 &ov1, const Vector3 &ov2, const Vector3 &ov3, const Vector3 &ov4) -{ +void Rasterizer::pushDisplacedQuad(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, + const Vector3 &v4, const Vector3 &ov1, const Vector3 &ov2, const Vector3 &ov3, + const Vector3 &ov4) { pushDisplacedTriangle(canvas, v2, v3, v1, ov2, ov3, ov1); pushDisplacedTriangle(canvas, v4, v1, v3, ov4, ov1, ov3); } -void Rasterizer::scanGetDiff(ScanPoint* v1, ScanPoint* v2, ScanPoint* result) -{ +void Rasterizer::scanGetDiff(ScanPoint *v1, ScanPoint *v2, ScanPoint *result) { result->pixel.x = v2->pixel.x - v1->pixel.x; result->pixel.y = v2->pixel.y - v1->pixel.y; result->pixel.z = v2->pixel.z - v1->pixel.z; @@ -234,8 +224,8 @@ void Rasterizer::scanGetDiff(ScanPoint* v1, ScanPoint* v2, ScanPoint* result) result->client = v1->client; } -void Rasterizer::scanInterpolate(CameraDefinition* camera, ScanPoint* v1, ScanPoint* diff, double value, ScanPoint* result) -{ +void Rasterizer::scanInterpolate(CameraDefinition *camera, ScanPoint *v1, ScanPoint *diff, double value, + ScanPoint *result) { Vector3 vec1(v1->pixel.x, v1->pixel.y, v1->pixel.z); Vector3 vecdiff(diff->pixel.x, diff->pixel.y, diff->pixel.z); double v1depth = 1.0 / camera->getRealDepth(vec1); @@ -245,112 +235,88 @@ void Rasterizer::scanInterpolate(CameraDefinition* camera, ScanPoint* v1, ScanPo result->pixel.x = v1->pixel.x + diff->pixel.x * value; result->pixel.y = v1->pixel.y + diff->pixel.y * value; result->pixel.z = v1->pixel.z + diff->pixel.z * value; - result->location.x = ((1.0 - value) * (v1->location.x * v1depth) + value * (v1->location.x + diff->location.x) * v2depth) * factor; - result->location.y = ((1.0 - value) * (v1->location.y * v1depth) + value * (v1->location.y + diff->location.y) * v2depth) * factor; - result->location.z = ((1.0 - value) * (v1->location.z * v1depth) + value * (v1->location.z + diff->location.z) * v2depth) * factor; + result->location.x = + ((1.0 - value) * (v1->location.x * v1depth) + value * (v1->location.x + diff->location.x) * v2depth) * factor; + result->location.y = + ((1.0 - value) * (v1->location.y * v1depth) + value * (v1->location.y + diff->location.y) * v2depth) * factor; + result->location.z = + ((1.0 - value) * (v1->location.z * v1depth) + value * (v1->location.z + diff->location.z) * v2depth) * factor; result->client = v1->client; result->front_facing = v1->front_facing; } -void Rasterizer::pushScanPoint(CanvasPortion* canvas, RenderScanlines* scanlines, ScanPoint* point) -{ +void Rasterizer::pushScanPoint(CanvasPortion *canvas, RenderScanlines *scanlines, ScanPoint *point) { point->x = (int)floor(point->pixel.x); point->y = (int)floor(point->pixel.y); - if (point->x < 0 || point->x >= canvas->getWidth()) - { + if (point->x < 0 || point->x >= canvas->getWidth()) { // Point outside scanline range return; - } - else if (scanlines->right < 0) - { + } else if (scanlines->right < 0) { // First point pushed scanlines->left = point->x; scanlines->right = point->x; scanlines->up[point->x] = *point; scanlines->down[point->x] = *point; - } - else if (point->x > scanlines->right) - { + } else if (point->x > scanlines->right) { // Grow scanlines to right - for (int x = scanlines->right + 1; x < point->x; x++) - { + for (int x = scanlines->right + 1; x < point->x; x++) { scanlines->up[x].y = -1; scanlines->down[x].y = canvas->getHeight(); } scanlines->right = point->x; scanlines->up[point->x] = *point; scanlines->down[point->x] = *point; - } - else if (point->x < scanlines->left) - { + } else if (point->x < scanlines->left) { // Grow scanlines to left - for (int x = point->x + 1; x < scanlines->left; x++) - { + for (int x = point->x + 1; x < scanlines->left; x++) { scanlines->up[x].y = -1; scanlines->down[x].y = canvas->getHeight(); } scanlines->left = point->x; scanlines->up[point->x] = *point; scanlines->down[point->x] = *point; - } - else - { + } else { // Expand existing scanline - if (point->y > scanlines->up[point->x].y) - { + if (point->y > scanlines->up[point->x].y) { scanlines->up[point->x] = *point; } - if (point->y < scanlines->down[point->x].y) - { + if (point->y < scanlines->down[point->x].y) { scanlines->down[point->x] = *point; } } } -void Rasterizer::pushScanLineEdge(CanvasPortion *canvas, RenderScanlines *scanlines, ScanPoint *point1, ScanPoint *point2) -{ +void Rasterizer::pushScanLineEdge(CanvasPortion *canvas, RenderScanlines *scanlines, ScanPoint *point1, + ScanPoint *point2) { double dx, fx; ScanPoint diff, point; int startx = lround(point1->pixel.x); int endx = lround(point2->pixel.x); int curx; - if (endx < startx) - { + if (endx < startx) { pushScanLineEdge(canvas, scanlines, point2, point1); - } - else if (endx < 0 || startx >= canvas->getWidth()) - { + } else if (endx < 0 || startx >= canvas->getWidth()) { return; - } - else if (startx == endx) - { + } else if (startx == endx) { pushScanPoint(canvas, scanlines, point1); pushScanPoint(canvas, scanlines, point2); - } - else - { - if (startx < 0) - { + } else { + if (startx < 0) { startx = 0; } - if (endx >= canvas->getWidth()) - { + if (endx >= canvas->getWidth()) { endx = canvas->getWidth() - 1; } dx = point2->pixel.x - point1->pixel.x; scanGetDiff(point1, point2, &diff); - for (curx = startx; curx <= endx; curx++) - { + for (curx = startx; curx <= endx; curx++) { fx = (double)curx + 0.5; - if (fx < point1->pixel.x) - { + if (fx < point1->pixel.x) { fx = point1->pixel.x; - } - else if (fx > point2->pixel.x) - { + } else if (fx > point2->pixel.x) { fx = point2->pixel.x; } fx = fx - point1->pixel.x; @@ -363,34 +329,28 @@ void Rasterizer::pushScanLineEdge(CanvasPortion *canvas, RenderScanlines *scanli } } -void Rasterizer::renderScanLines(CanvasPortion *canvas, RenderScanlines* scanlines) -{ +void Rasterizer::renderScanLines(CanvasPortion *canvas, RenderScanlines *scanlines) { int x, starty, endy, cury; ScanPoint diff; double dy, fy; ScanPoint up, down, current; - if (scanlines->right > 0) - { - for (x = scanlines->left; x <= scanlines->right; x++) - { + if (scanlines->right > 0) { + for (x = scanlines->left; x <= scanlines->right; x++) { up = scanlines->up[x]; down = scanlines->down[x]; starty = down.y; endy = up.y; - if (endy < 0 || starty >= canvas->getHeight()) - { + if (endy < 0 || starty >= canvas->getHeight()) { continue; } - if (starty < 0) - { + if (starty < 0) { starty = 0; } - if (endy >= canvas->getHeight()) - { + if (endy >= canvas->getHeight()) { endy = canvas->getHeight() - 1; } @@ -398,22 +358,15 @@ void Rasterizer::renderScanLines(CanvasPortion *canvas, RenderScanlines* scanlin scanGetDiff(&down, &up, &diff); current.x = x; - for (cury = starty; cury <= endy; cury++) - { - if (dy == 0) - { + for (cury = starty; cury <= endy; cury++) { + if (dy == 0) { // Down and up are the same current = down; - } - else - { + } else { fy = (double)cury + 0.5; - if (fy < down.pixel.y) - { + if (fy < down.pixel.y) { fy = down.pixel.y; - } - else if (fy > up.pixel.y) - { + } else if (fy > up.pixel.y) { fy = up.pixel.y; } fy = fy - down.pixel.y; @@ -422,14 +375,14 @@ void Rasterizer::renderScanLines(CanvasPortion *canvas, RenderScanlines* scanlin scanInterpolate(renderer->render_camera, &down, &diff, fy / dy, ¤t); } - Vector3 pixel(current.pixel.x + canvas->getXOffset(), current.pixel.y + canvas->getYOffset(), current.pixel.z); + Vector3 pixel(current.pixel.x + canvas->getXOffset(), current.pixel.y + canvas->getYOffset(), + current.pixel.z); Vector3 location(current.location.x, current.location.y, current.location.z); CanvasFragment fragment(current.front_facing, pixel, location, current.client, color->a == 1.0); Color frag_color = *color; frag_color.a = 1.0; - if (cury == starty || cury == endy) - { + if (cury == starty || cury == endy) { frag_color.mask(Color(0.0, 0.0, 0.0, 0.3)); } frag_color.a = color->a; diff --git a/src/render/software/Rasterizer.h b/src/render/software/Rasterizer.h index beb1ac3..6556689 100644 --- a/src/render/software/Rasterizer.h +++ b/src/render/software/Rasterizer.h @@ -16,14 +16,17 @@ typedef struct RenderScanlines RenderScanlines; /** * @brief Base abstract class for scenery pieces that can be rasterized to polygons. */ -class SOFTWARESHARED_EXPORT Rasterizer -{ -public: +class SOFTWARESHARED_EXPORT Rasterizer { + public: Rasterizer(SoftwareRenderer *renderer, RenderProgress *progress, int client_id, const Color &color); virtual ~Rasterizer(); - inline SoftwareRenderer *getRenderer() const {return renderer;} - inline int getTriangleCount() const {return triangle_count;} + inline SoftwareRenderer *getRenderer() const { + return renderer; + } + inline int getTriangleCount() const { + return triangle_count; + } /** * Set the rasterization quality factor. @@ -64,21 +67,26 @@ public: void resetTriangleCount(); void pushTriangle(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3); - void pushDisplacedTriangle(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, const Vector3 &ov1, const Vector3 &ov2, const Vector3 &ov3); + void pushDisplacedTriangle(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, + const Vector3 &ov1, const Vector3 &ov2, const Vector3 &ov3); void pushQuad(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, const Vector3 &v4); - void pushDisplacedQuad(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, const Vector3 &v4, const Vector3 &ov1, const Vector3 &ov2, const Vector3 &ov3, const Vector3 &ov4); + void pushDisplacedQuad(CanvasPortion *canvas, const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, + const Vector3 &v4, const Vector3 &ov1, const Vector3 &ov2, const Vector3 &ov3, + const Vector3 &ov4); -protected: - bool pushProjectedTriangle(CanvasPortion *canvas, const Vector3 &pixel1, const Vector3 &pixel2, const Vector3 &pixel3, const Vector3 &location1, const Vector3 &location2, const Vector3 &location3); + protected: + bool pushProjectedTriangle(CanvasPortion *canvas, const Vector3 &pixel1, const Vector3 &pixel2, + const Vector3 &pixel3, const Vector3 &location1, const Vector3 &location2, + const Vector3 &location3); - Color* color; + Color *color; SoftwareRenderer *renderer; RenderProgress *progress; int client_id; bool interrupted; -private: + private: void scanGetDiff(ScanPoint *v1, ScanPoint *v2, ScanPoint *result); void scanInterpolate(CameraDefinition *camera, ScanPoint *v1, ScanPoint *diff, double value, ScanPoint *result); void pushScanPoint(CanvasPortion *canvas, RenderScanlines *scanlines, ScanPoint *point); @@ -89,7 +97,6 @@ private: double auto_cut_limit; bool backface_culling; }; - } } diff --git a/src/render/software/RayCastingManager.cpp b/src/render/software/RayCastingManager.cpp index b9239c9..563039b 100644 --- a/src/render/software/RayCastingManager.cpp +++ b/src/render/software/RayCastingManager.cpp @@ -1,5 +1,4 @@ #include "RayCastingManager.h" -RayCastingManager::RayCastingManager() -{ +RayCastingManager::RayCastingManager() { } diff --git a/src/render/software/RayCastingManager.h b/src/render/software/RayCastingManager.h index 6bedf6b..ae9afa6 100644 --- a/src/render/software/RayCastingManager.h +++ b/src/render/software/RayCastingManager.h @@ -6,14 +6,13 @@ namespace paysages { namespace software { -typedef RayCastingResult (*FuncGeneralCastRay)(SoftwareRenderer* renderer, const Vector3 &start, const Vector3 &direction); +typedef RayCastingResult (*FuncGeneralCastRay)(SoftwareRenderer *renderer, const Vector3 &start, + const Vector3 &direction); -class SOFTWARESHARED_EXPORT RayCastingManager -{ -public: +class SOFTWARESHARED_EXPORT RayCastingManager { + public: RayCastingManager(); }; - } } diff --git a/src/render/software/RayCastingResult.cpp b/src/render/software/RayCastingResult.cpp index 26e680f..de667d3 100644 --- a/src/render/software/RayCastingResult.cpp +++ b/src/render/software/RayCastingResult.cpp @@ -1,6 +1,5 @@ #include "RayCastingResult.h" -RayCastingResult::RayCastingResult() -{ +RayCastingResult::RayCastingResult() { hit = false; } diff --git a/src/render/software/RayCastingResult.h b/src/render/software/RayCastingResult.h index 5c81631..9008c05 100644 --- a/src/render/software/RayCastingResult.h +++ b/src/render/software/RayCastingResult.h @@ -9,16 +9,14 @@ namespace paysages { namespace software { -class SOFTWARESHARED_EXPORT RayCastingResult -{ -public: +class SOFTWARESHARED_EXPORT RayCastingResult { + public: RayCastingResult(); bool hit; Color hit_color; Vector3 hit_location; }; - } } diff --git a/src/render/software/RenderConfig.cpp b/src/render/software/RenderConfig.cpp index c4f67ca..4dcc34b 100644 --- a/src/render/software/RenderConfig.cpp +++ b/src/render/software/RenderConfig.cpp @@ -1,30 +1,23 @@ #include "RenderConfig.h" -RenderConfig::RenderConfig(int width, int height, int antialias, int quality): - width(width), height(height), antialias(antialias), quality(quality) -{ - if (this->width <= 0) - { +RenderConfig::RenderConfig(int width, int height, int antialias, int quality) + : width(width), height(height), antialias(antialias), quality(quality) { + if (this->width <= 0) { this->width = 400; } - if (this->height <= 0) - { + if (this->height <= 0) { this->height = this->width * 4 / 3; } - if (this->antialias < 1) - { + if (this->antialias < 1) { this->antialias = 1; } - if (this->antialias > 4) - { + if (this->antialias > 4) { this->antialias = 4; } - if (this->quality < 1) - { + if (this->quality < 1) { this->quality = 1; } - if (this->quality > 10) - { + if (this->quality > 10) { this->quality = 10; } } diff --git a/src/render/software/RenderConfig.h b/src/render/software/RenderConfig.h index 558b5b3..6dbe5a1 100644 --- a/src/render/software/RenderConfig.h +++ b/src/render/software/RenderConfig.h @@ -6,17 +6,15 @@ namespace paysages { namespace software { -class SOFTWARESHARED_EXPORT RenderConfig -{ -public: - RenderConfig(int width=0, int height=0, int antialias=1, int quality=5); +class SOFTWARESHARED_EXPORT RenderConfig { + public: + RenderConfig(int width = 0, int height = 0, int antialias = 1, int quality = 5); int width; int height; int antialias; int quality; }; - } } diff --git a/src/render/software/RenderProgress.cpp b/src/render/software/RenderProgress.cpp index 5c5a62d..3ba5df2 100644 --- a/src/render/software/RenderProgress.cpp +++ b/src/render/software/RenderProgress.cpp @@ -4,8 +4,7 @@ #include "Time.h" #include "Logs.h" -RenderProgress::RenderProgress(int count) -{ +RenderProgress::RenderProgress(int count) { lock = new Mutex(); global = 0.0; step = 1.0 / (double)count; @@ -14,18 +13,15 @@ RenderProgress::RenderProgress(int count) reset(); } -paysages::software::RenderProgress::~RenderProgress() -{ +paysages::software::RenderProgress::~RenderProgress() { delete lock; } -void RenderProgress::reset() -{ +void RenderProgress::reset() { lock->acquire(); global = 0.0; - while (not subs.empty()) - { + while (not subs.empty()) { subs.pop(); } @@ -38,8 +34,7 @@ void RenderProgress::reset() lock->release(); } -void RenderProgress::add(int value) -{ +void RenderProgress::add(int value) { lock->acquire(); global += step * (double)value; @@ -47,8 +42,7 @@ void RenderProgress::add(int value) lock->release(); } -void RenderProgress::enterSub(int count) -{ +void RenderProgress::enterSub(int count) { struct RenderSub sub; sub.start = global; sub.end = global + step; @@ -63,8 +57,7 @@ void RenderProgress::enterSub(int count) lock->release(); } -void RenderProgress::exitSub() -{ +void RenderProgress::exitSub() { lock->acquire(); struct RenderSub sub = subs.top(); @@ -77,46 +70,35 @@ void RenderProgress::exitSub() lock->release(); } -void RenderProgress::end() -{ - if (subs.size() > 0) - { +void RenderProgress::end() { + if (subs.size() > 0) { Logs::error() << subs.size() << " progress subs remaining at the end of render" << std::endl; } end_time = Time::getRelativeTimeMs(); } -unsigned long RenderProgress::getDuration() const -{ - if (end_time) - { +unsigned long RenderProgress::getDuration() const { + if (end_time) { return end_time - start_time; - } - else - { + } else { return Time::getRelativeTimeMs() - start_time; } } -unsigned long RenderProgress::estimateRemainingTime() -{ +unsigned long RenderProgress::estimateRemainingTime() { unsigned long spent = getDuration(); double speed = (global - prev_est_done) / (double)(spent - prev_est_spent); prev_est_speed = prev_est_speed ? (prev_est_speed * 0.8 + speed * 0.2) : speed; - if (spent - prev_est_spent > 5000) - { + if (spent - prev_est_spent > 5000) { prev_est_spent = spent; prev_est_done = global; } - if (prev_est_speed > 0.0000000001) - { + if (prev_est_speed > 0.0000000001) { return (unsigned long)((1.0 - global) / prev_est_speed); - } - else - { + } else { return 0; } } diff --git a/src/render/software/RenderProgress.h b/src/render/software/RenderProgress.h index 385717a..d9da550 100644 --- a/src/render/software/RenderProgress.h +++ b/src/render/software/RenderProgress.h @@ -18,16 +18,17 @@ struct RenderSub { /** * Utility to keep track of render progress. */ -class SOFTWARESHARED_EXPORT RenderProgress -{ -public: - RenderProgress(int count=1); +class SOFTWARESHARED_EXPORT RenderProgress { + public: + RenderProgress(int count = 1); ~RenderProgress(); - inline double get() const {return global;} + inline double get() const { + return global; + } void reset(); - void add(int value=1); + void add(int value = 1); void enterSub(int count); void exitSub(); void end(); @@ -44,7 +45,7 @@ public: */ unsigned long estimateRemainingTime(); -private: + private: Mutex *lock; double global; @@ -59,7 +60,6 @@ private: std::stack subs; }; - } } diff --git a/src/render/software/SkyRasterizer.cpp b/src/render/software/SkyRasterizer.cpp index cc70a67..ca3f9aa 100644 --- a/src/render/software/SkyRasterizer.cpp +++ b/src/render/software/SkyRasterizer.cpp @@ -13,18 +13,15 @@ #define SPHERE_SIZE 20000.0 -SkyRasterizer::SkyRasterizer(SoftwareRenderer* renderer, RenderProgress *progress, int client_id): - Rasterizer(renderer, progress, client_id, Color(0.9, 0.9, 1.0)) -{ +SkyRasterizer::SkyRasterizer(SoftwareRenderer *renderer, RenderProgress *progress, int client_id) + : Rasterizer(renderer, progress, client_id, Color(0.9, 0.9, 1.0)) { } -int SkyRasterizer::prepareRasterization() -{ +int SkyRasterizer::prepareRasterization() { return res_i * res_j; } -void SkyRasterizer::rasterizeToCanvas(CanvasPortion* canvas) -{ +void SkyRasterizer::rasterizeToCanvas(CanvasPortion *canvas) { int i, j; double step_i, step_j; double current_i, current_j; @@ -36,17 +33,14 @@ void SkyRasterizer::rasterizeToCanvas(CanvasPortion* canvas) camera_location = renderer->getCameraLocation(VECTOR_ZERO); - for (j = 0; j < res_j; j++) - { - if (interrupted) - { + for (j = 0; j < res_j; j++) { + if (interrupted) { return; } current_j = (double)(j - res_j / 2) * step_j; - for (i = 0; i < res_i; i++) - { + for (i = 0; i < res_i; i++) { current_i = (double)i * step_i; direction.x = SPHERE_SIZE * cos(current_i) * cos(current_j); @@ -76,8 +70,7 @@ void SkyRasterizer::rasterizeToCanvas(CanvasPortion* canvas) } } -Color SkyRasterizer::shadeFragment(const CanvasFragment &fragment, const CanvasFragment *) const -{ +Color SkyRasterizer::shadeFragment(const CanvasFragment &fragment, const CanvasFragment *) const { Vector3 location = fragment.getLocation(); Vector3 camera_location, direction; Color result; @@ -87,18 +80,17 @@ Color SkyRasterizer::shadeFragment(const CanvasFragment &fragment, const CanvasF // TODO Don't compute sky color if it's fully covered by clouds result = renderer->getAtmosphereRenderer()->getSkyColor(direction.normalize()).final; - result = renderer->getCloudsRenderer()->getColor(camera_location, camera_location.add(direction.scale(10.0)), result); + result = + renderer->getCloudsRenderer()->getColor(camera_location, camera_location.add(direction.scale(10.0)), result); return result; } -void SkyRasterizer::setQuality(int res_i, int res_j) -{ +void SkyRasterizer::setQuality(int res_i, int res_j) { this->res_i = res_i; this->res_j = res_j; } -void SkyRasterizer::setQuality(double factor) -{ +void SkyRasterizer::setQuality(double factor) { setQuality(20.0 * (1.0 + factor * 10.0), 10.0 * (1.0 + factor * 10.0)); } diff --git a/src/render/software/SkyRasterizer.h b/src/render/software/SkyRasterizer.h index 10a648f..f674de5 100644 --- a/src/render/software/SkyRasterizer.h +++ b/src/render/software/SkyRasterizer.h @@ -8,23 +8,21 @@ namespace paysages { namespace software { -class SOFTWARESHARED_EXPORT SkyRasterizer: public Rasterizer -{ -public: - SkyRasterizer(SoftwareRenderer* renderer, RenderProgress *progress, int client_id); +class SOFTWARESHARED_EXPORT SkyRasterizer : public Rasterizer { + public: + SkyRasterizer(SoftwareRenderer *renderer, RenderProgress *progress, int client_id); virtual int prepareRasterization() override; - virtual void rasterizeToCanvas(CanvasPortion* canvas) override; + virtual void rasterizeToCanvas(CanvasPortion *canvas) override; virtual Color shadeFragment(const CanvasFragment &fragment, const CanvasFragment *previous) const override; void setQuality(int res_i, int res_j); virtual void setQuality(double factor) override; -private: + private: int res_i; int res_j; }; - } } diff --git a/src/render/software/SoftwareCanvasRenderer.cpp b/src/render/software/SoftwareCanvasRenderer.cpp index d690e33..cbe41fe 100644 --- a/src/render/software/SoftwareCanvasRenderer.cpp +++ b/src/render/software/SoftwareCanvasRenderer.cpp @@ -15,9 +15,7 @@ #include "CanvasPreview.h" #include "RenderProgress.h" -SoftwareCanvasRenderer::SoftwareCanvasRenderer(Scenery *scenery): - SoftwareRenderer(scenery) -{ +SoftwareCanvasRenderer::SoftwareCanvasRenderer(Scenery *scenery) : SoftwareRenderer(scenery) { started = false; finished = false; interrupted = false; @@ -34,67 +32,54 @@ SoftwareCanvasRenderer::SoftwareCanvasRenderer(Scenery *scenery): current_work = NULL; } -SoftwareCanvasRenderer::~SoftwareCanvasRenderer() -{ +SoftwareCanvasRenderer::~SoftwareCanvasRenderer() { delete canvas; delete progress; - for (auto &rasterizer: rasterizers) - { + for (auto &rasterizer : rasterizers) { delete rasterizer; } } -void SoftwareCanvasRenderer::setQuality(double factor) -{ +void SoftwareCanvasRenderer::setQuality(double factor) { SoftwareRenderer::setQuality(factor); - for (auto &rasterizer:rasterizers) - { + for (auto &rasterizer : rasterizers) { rasterizer->setQuality(factor); } } -void SoftwareCanvasRenderer::setSoloRasterizer(Rasterizer *rasterizer) -{ - for (auto &rast: rasterizers) - { +void SoftwareCanvasRenderer::setSoloRasterizer(Rasterizer *rasterizer) { + for (auto &rast : rasterizers) { delete rast; } rasterizers.clear(); rasterizers.push_back(rasterizer); } -double SoftwareCanvasRenderer::getProgress() const -{ +double SoftwareCanvasRenderer::getProgress() const { return progress->get(); } -void SoftwareCanvasRenderer::setConfig(const RenderConfig &config) -{ - if (not started) - { +void SoftwareCanvasRenderer::setConfig(const RenderConfig &config) { + if (not started) { setSize(config.width, config.height, config.antialias); setQuality((double)(config.quality - 1) / 9.0); } } -void SoftwareCanvasRenderer::enablePostprocess(bool enabled) -{ +void SoftwareCanvasRenderer::enablePostprocess(bool enabled) { this->postprocess_enabled = enabled; } -void SoftwareCanvasRenderer::setSize(int width, int height, int samples) -{ - if (not started) - { +void SoftwareCanvasRenderer::setSize(int width, int height, int samples) { + if (not started) { canvas->setSize(width * samples, height * samples); this->samples = samples; } } -void SoftwareCanvasRenderer::render() -{ +void SoftwareCanvasRenderer::render() { started = true; progress->reset(); @@ -107,22 +92,18 @@ void SoftwareCanvasRenderer::render() int ny = canvas->getVerticalPortionCount(); int n = nx * ny; progress->enterSub(n); - for (int y = 0; y < ny; y++) - { - for (int x = 0; x < nx; x++) - { + for (int y = 0; y < ny; y++) { + for (int x = 0; x < nx; x++) { CanvasPortion *portion = canvas->at(x, y); progress->enterSub(2); - if (not interrupted) - { + if (not interrupted) { portion->preparePixels(); rasterize(portion); } - if (not interrupted and postprocess_enabled) - { + if (not interrupted and postprocess_enabled) { applyPixelShader(portion); } @@ -136,48 +117,39 @@ void SoftwareCanvasRenderer::render() finished = true; } -void SoftwareCanvasRenderer::interrupt() -{ +void SoftwareCanvasRenderer::interrupt() { interrupted = true; - if (current_work) - { + if (current_work) { current_work->interrupt(); } - for (auto &rasterizer:rasterizers) - { + for (auto &rasterizer : rasterizers) { rasterizer->interrupt(); } } -const Rasterizer &SoftwareCanvasRenderer::getRasterizer(int client_id) const -{ +const Rasterizer &SoftwareCanvasRenderer::getRasterizer(int client_id) const { return *(rasterizers[client_id]); } -bool SoftwareCanvasRenderer::saveToDisk(const std::string &filepath) const -{ +bool SoftwareCanvasRenderer::saveToDisk(const std::string &filepath) const { return getCanvas()->saveToDisk(filepath, *getCanvas()->getPreview()->getToneMapping(), samples); } -void SoftwareCanvasRenderer::rasterize(CanvasPortion *portion) -{ +void SoftwareCanvasRenderer::rasterize(CanvasPortion *portion) { int count = 0; - for (auto &rasterizer:rasterizers) - { + for (auto &rasterizer : rasterizers) { count += rasterizer->prepareRasterization(); } progress->enterSub(count); - for (auto &rasterizer:rasterizers) - { + for (auto &rasterizer : rasterizers) { rasterizer->rasterizeToCanvas(portion); } progress->exitSub(); } -void SoftwareCanvasRenderer::applyPixelShader(CanvasPortion *portion) -{ +void SoftwareCanvasRenderer::applyPixelShader(CanvasPortion *portion) { // Subdivide in chunks int chunk_size = 64; int chunks_x = (portion->getWidth() - 1) / chunk_size + 1; @@ -186,10 +158,8 @@ void SoftwareCanvasRenderer::applyPixelShader(CanvasPortion *portion) // Render chunks in parallel progress->enterSub(portion->getWidth() * portion->getHeight()); - for (int sub_chunk_size = chunk_size; sub_chunk_size >= 1; sub_chunk_size /= 2) - { - if (interrupted) - { + for (int sub_chunk_size = chunk_size; sub_chunk_size >= 1; sub_chunk_size /= 2) { + if (interrupted) { break; } diff --git a/src/render/software/SoftwareCanvasRenderer.h b/src/render/software/SoftwareCanvasRenderer.h index 6eea200..73737a9 100644 --- a/src/render/software/SoftwareCanvasRenderer.h +++ b/src/render/software/SoftwareCanvasRenderer.h @@ -16,19 +16,30 @@ namespace software { * * It tries to keep a canvas portion rasterized ahead of the post processing. */ -class SOFTWARESHARED_EXPORT SoftwareCanvasRenderer: public SoftwareRenderer -{ -public: +class SOFTWARESHARED_EXPORT SoftwareCanvasRenderer : public SoftwareRenderer { + public: SoftwareCanvasRenderer(Scenery *scenery); virtual ~SoftwareCanvasRenderer(); - inline const Canvas *getCanvas() const {return canvas;} - inline RenderProgress *getProgressHelper() const {return progress;} - inline bool isFinished() const {return finished;} + inline const Canvas *getCanvas() const { + return canvas; + } + inline RenderProgress *getProgressHelper() const { + return progress; + } + inline bool isFinished() const { + return finished; + } - inline Rasterizer *getSkyRasterizer() const {return rasterizers[0];} - inline Rasterizer *getWaterRasterizer() const {return rasterizers[1];} - inline Rasterizer *getTerrainRasterizer() const {return rasterizers[2];} + inline Rasterizer *getSkyRasterizer() const { + return rasterizers[0]; + } + inline Rasterizer *getWaterRasterizer() const { + return rasterizers[1]; + } + inline Rasterizer *getTerrainRasterizer() const { + return rasterizers[2]; + } virtual void setQuality(double factor) override; @@ -59,7 +70,7 @@ public: * * Set 'samples' to something bigger than 1 to allow for the multi-sampling of pixels. */ - void setSize(int width, int height, int samples=1); + void setSize(int width, int height, int samples = 1); /** * @brief Start the two-pass render process. @@ -83,7 +94,7 @@ public: */ bool saveToDisk(const std::string &filepath) const; -protected: + protected: /** * @brief Rasterize the scenery into a canvas portion. */ @@ -94,12 +105,12 @@ protected: */ void applyPixelShader(CanvasPortion *portion); -private: + private: RenderProgress *progress; Canvas *canvas; int samples; - std::vector rasterizers; + std::vector rasterizers; bool started; bool finished; bool interrupted; @@ -108,7 +119,6 @@ private: ParallelWork *current_work; }; - } } diff --git a/src/render/software/SoftwareRenderer.cpp b/src/render/software/SoftwareRenderer.cpp index 3daeed5..64de073 100644 --- a/src/render/software/SoftwareRenderer.cpp +++ b/src/render/software/SoftwareRenderer.cpp @@ -23,9 +23,7 @@ #include "Thread.h" #include "RayCastingResult.h" -SoftwareRenderer::SoftwareRenderer(Scenery* scenery): - scenery(scenery) -{ +SoftwareRenderer::SoftwareRenderer(Scenery *scenery) : scenery(scenery) { render_camera = new CameraDefinition; scenery->getCamera()->copy(render_camera); @@ -50,8 +48,7 @@ SoftwareRenderer::SoftwareRenderer(Scenery* scenery): setQuality(0.5); } -SoftwareRenderer::~SoftwareRenderer() -{ +SoftwareRenderer::~SoftwareRenderer() { delete render_camera; delete fluid_medium; @@ -67,8 +64,7 @@ SoftwareRenderer::~SoftwareRenderer() delete water_renderer; } -void SoftwareRenderer::prepare() -{ +void SoftwareRenderer::prepare() { scenery->validate(); scenery->getCamera()->copy(render_camera); @@ -76,12 +72,9 @@ void SoftwareRenderer::prepare() // TODO Don't recreate the renderer each time, only when it changes lighting->unregisterSource(atmosphere_renderer); delete atmosphere_renderer; - if (getScenery()->getAtmosphere()->model == AtmosphereDefinition::ATMOSPHERE_MODEL_BRUNETON) - { + if (getScenery()->getAtmosphere()->model == AtmosphereDefinition::ATMOSPHERE_MODEL_BRUNETON) { atmosphere_renderer = new SoftwareBrunetonAtmosphereRenderer(this); - } - else - { + } else { atmosphere_renderer = new BaseAtmosphereRenderer(this); } lighting->registerSource(atmosphere_renderer); @@ -96,11 +89,10 @@ void SoftwareRenderer::prepare() // Prepare global tools godrays->prepare(this); fluid_medium->clearMedia(); - //fluid_medium->registerMedium(water_renderer); + // fluid_medium->registerMedium(water_renderer); } -void SoftwareRenderer::setQuality(double quality) -{ +void SoftwareRenderer::setQuality(double quality) { terrain_renderer->setQuality(quality); clouds_renderer->setQuality(quality); godrays->setQuality(quality); @@ -109,26 +101,23 @@ void SoftwareRenderer::setQuality(double quality) render_quality = (int)(quality * 9.0) + 1; } -Color SoftwareRenderer::applyLightingToSurface(const Vector3 &location, const Vector3 &normal, const SurfaceMaterial &material) -{ +Color SoftwareRenderer::applyLightingToSurface(const Vector3 &location, const Vector3 &normal, + const SurfaceMaterial &material) { return lighting->apply(getCameraLocation(location), location, normal, material); } -Color SoftwareRenderer::applyMediumTraversal(const Vector3 &location, const Color &color) -{ +Color SoftwareRenderer::applyMediumTraversal(const Vector3 &location, const Color &color) { Color result = atmosphere_renderer->applyAerialPerspective(location, color).final; result = clouds_renderer->getColor(getCameraLocation(location), location, result); return result; } -RayCastingResult SoftwareRenderer::rayWalking(const Vector3 &location, const Vector3 &direction, int, int, int, int) -{ +RayCastingResult SoftwareRenderer::rayWalking(const Vector3 &location, const Vector3 &direction, int, int, int, int) { RayCastingResult result; Color sky_color; result = terrain_renderer->castRay(location, direction); - if (!result.hit) - { + if (!result.hit) { sky_color = atmosphere_renderer->getSkyColor(direction).final; result.hit = 1; @@ -139,33 +128,28 @@ RayCastingResult SoftwareRenderer::rayWalking(const Vector3 &location, const Vec return result; } -Vector3 SoftwareRenderer::getCameraLocation(const Vector3 &) -{ +Vector3 SoftwareRenderer::getCameraLocation(const Vector3 &) { return render_camera->getLocation(); } -Vector3 SoftwareRenderer::getCameraDirection(const Vector3 &) -{ +Vector3 SoftwareRenderer::getCameraDirection(const Vector3 &) { return render_camera->getDirectionNormalized(); } -double SoftwareRenderer::getPrecision(const Vector3 &location) -{ +double SoftwareRenderer::getPrecision(const Vector3 &location) { Vector3 projected; projected = render_camera->project(location); projected.x += 1.0; - //projected.y += 1.0; + // projected.y += 1.0; return render_camera->unproject(projected).sub(location).getNorm(); // / (double)render_quality; } -Vector3 SoftwareRenderer::projectPoint(const Vector3 &point) -{ +Vector3 SoftwareRenderer::projectPoint(const Vector3 &point) { return render_camera->project(point); } -Vector3 SoftwareRenderer::unprojectPoint(const Vector3 &point) -{ +Vector3 SoftwareRenderer::unprojectPoint(const Vector3 &point) { return render_camera->unproject(point); } diff --git a/src/render/software/SoftwareRenderer.h b/src/render/software/SoftwareRenderer.h index 9786f26..163838f 100644 --- a/src/render/software/SoftwareRenderer.h +++ b/src/render/software/SoftwareRenderer.h @@ -9,16 +9,15 @@ namespace software { /*! * \brief This class renders a defined scenery in sotware mode (using only standard CPU computations). */ -class SOFTWARESHARED_EXPORT SoftwareRenderer -{ +class SOFTWARESHARED_EXPORT SoftwareRenderer { -public: - SoftwareRenderer(Scenery* scenery); + public: + SoftwareRenderer(Scenery *scenery); virtual ~SoftwareRenderer(); /* Render base configuration */ int render_quality; - CameraDefinition* render_camera; + CameraDefinition *render_camera; virtual Vector3 getCameraLocation(const Vector3 &target); virtual Vector3 getCameraDirection(const Vector3 &target); @@ -43,39 +42,60 @@ public: */ virtual void setQuality(double quality); - inline Scenery* getScenery() const {return scenery;} + inline Scenery *getScenery() const { + return scenery; + } - inline BaseAtmosphereRenderer* getAtmosphereRenderer() const {return atmosphere_renderer;} - inline CloudsRenderer* getCloudsRenderer() const {return clouds_renderer;} - inline TerrainRenderer* getTerrainRenderer() const {return terrain_renderer;} - inline TexturesRenderer* getTexturesRenderer() const {return textures_renderer;} - inline WaterRenderer* getWaterRenderer() const {return water_renderer;} + inline BaseAtmosphereRenderer *getAtmosphereRenderer() const { + return atmosphere_renderer; + } + inline CloudsRenderer *getCloudsRenderer() const { + return clouds_renderer; + } + inline TerrainRenderer *getTerrainRenderer() const { + return terrain_renderer; + } + inline TexturesRenderer *getTexturesRenderer() const { + return textures_renderer; + } + inline WaterRenderer *getWaterRenderer() const { + return water_renderer; + } - inline NightSky* getNightSky() const {return nightsky_renderer;} + inline NightSky *getNightSky() const { + return nightsky_renderer; + } - inline FluidMediumManager* getFluidMediumManager() const {return fluid_medium;} - inline LightingManager* getLightingManager() const {return lighting;} - inline GodRaysSampler* getGodRaysSampler() const {return godrays;} + inline FluidMediumManager *getFluidMediumManager() const { + return fluid_medium; + } + inline LightingManager *getLightingManager() const { + return lighting; + } + inline GodRaysSampler *getGodRaysSampler() const { + return godrays; + } - virtual Color applyLightingToSurface(const Vector3 &location, const Vector3 &normal, const SurfaceMaterial &material); + virtual Color applyLightingToSurface(const Vector3 &location, const Vector3 &normal, + const SurfaceMaterial &material); virtual Color applyMediumTraversal(const Vector3 &location, const Color &color); - virtual RayCastingResult rayWalking(const Vector3 &location, const Vector3 &direction, int terrain, int water, int sky, int clouds); + virtual RayCastingResult rayWalking(const Vector3 &location, const Vector3 &direction, int terrain, int water, + int sky, int clouds); -private: - Scenery* scenery; + private: + Scenery *scenery; - FluidMediumManager* fluid_medium; - LightingManager* lighting; - GodRaysSampler* godrays; + FluidMediumManager *fluid_medium; + LightingManager *lighting; + GodRaysSampler *godrays; - BaseAtmosphereRenderer* atmosphere_renderer; - CloudsRenderer* clouds_renderer; - TerrainRenderer* terrain_renderer; - TexturesRenderer* textures_renderer; - WaterRenderer* water_renderer; - NightSky* nightsky_renderer; + BaseAtmosphereRenderer *atmosphere_renderer; + CloudsRenderer *clouds_renderer; + TerrainRenderer *terrain_renderer; + TexturesRenderer *textures_renderer; + WaterRenderer *water_renderer; + NightSky *nightsky_renderer; }; - } } diff --git a/src/render/software/TerrainRasterizer.cpp b/src/render/software/TerrainRasterizer.cpp index 676d9ba..80eca27 100644 --- a/src/render/software/TerrainRasterizer.cpp +++ b/src/render/software/TerrainRasterizer.cpp @@ -11,32 +11,25 @@ #include "CanvasFragment.h" #include "RenderProgress.h" -TerrainRasterizer::TerrainRasterizer(SoftwareRenderer* renderer, RenderProgress *progress, int client_id): - Rasterizer(renderer, progress, client_id, Color(1.0, 0.9, 0.9)) -{ +TerrainRasterizer::TerrainRasterizer(SoftwareRenderer *renderer, RenderProgress *progress, int client_id) + : Rasterizer(renderer, progress, client_id, Color(1.0, 0.9, 0.9)) { } -void TerrainRasterizer::setQuality(double base_chunk_size, double detail_factor, int max_chunk_detail) -{ +void TerrainRasterizer::setQuality(double base_chunk_size, double detail_factor, int max_chunk_detail) { this->base_chunk_size = base_chunk_size; this->detail_factor = detail_factor; this->max_chunk_detail = max_chunk_detail; } -void TerrainRasterizer::setQuality(double factor) -{ - setQuality(5.0 - 4.5 * factor * factor, - 1.0 / (25.0 - 20.0 * factor), - 1 + 49 * factor * factor); +void TerrainRasterizer::setQuality(double factor) { + setQuality(5.0 - 4.5 * factor * factor, 1.0 / (25.0 - 20.0 * factor), 1 + 49 * factor * factor); } -static inline Vector3 _getPoint(SoftwareRenderer* renderer, double x, double z) -{ +static inline Vector3 _getPoint(SoftwareRenderer *renderer, double x, double z) { return Vector3(x, renderer->getTerrainRenderer()->getHeight(x, z, true), z); } -void TerrainRasterizer::tessellateChunk(CanvasPortion* canvas, TerrainChunkInfo* chunk, int detail) -{ +void TerrainRasterizer::tessellateChunk(CanvasPortion *canvas, TerrainChunkInfo *chunk, int detail) { double water_height = renderer->getWaterRenderer()->getHeightInfo().min_height; double startx = chunk->point_nw.x; @@ -44,18 +37,15 @@ void TerrainRasterizer::tessellateChunk(CanvasPortion* canvas, TerrainChunkInfo* double size = (chunk->point_ne.x - chunk->point_nw.x) / (double)detail; int i, j; - for (i = 0; i < detail; i++) - { - for (j = 0; j < detail; j++) - { + for (i = 0; i < detail; i++) { + for (j = 0; j < detail; j++) { renderQuad(canvas, startx + (double)i * size, startz + (double)j * size, size, water_height); } progress->add(detail); } } -void TerrainRasterizer::renderQuad(CanvasPortion *canvas, double x, double z, double size, double water_height) -{ +void TerrainRasterizer::renderQuad(CanvasPortion *canvas, double x, double z, double size, double water_height) { Vector3 ov1, ov2, ov3, ov4; Vector3 dv1, dv2, dv3, dv4; @@ -77,32 +67,28 @@ void TerrainRasterizer::renderQuad(CanvasPortion *canvas, double x, double z, do ov4.z = z; dv4 = renderer->getTerrainRenderer()->getResult(x + size, z, true, true).location; - if (dv1.y > water_height || dv2.y > water_height || dv3.y > water_height || dv4.y > water_height) - { + if (dv1.y > water_height || dv2.y > water_height || dv3.y > water_height || dv4.y > water_height) { pushDisplacedQuad(canvas, dv1, dv2, dv3, dv4, ov1, ov2, ov3, ov4); } } -void TerrainRasterizer::getChunk(TerrainRasterizer::TerrainChunkInfo* chunk, double x, double z, double size, bool displaced) -{ +void TerrainRasterizer::getChunk(TerrainRasterizer::TerrainChunkInfo *chunk, double x, double z, double size, + bool displaced) { chunk->point_nw = renderer->getTerrainRenderer()->getResult(x, z, true, displaced).location; chunk->point_sw = renderer->getTerrainRenderer()->getResult(x, z + size, true, displaced).location; chunk->point_se = renderer->getTerrainRenderer()->getResult(x + size, z + size, true, displaced).location; chunk->point_ne = renderer->getTerrainRenderer()->getResult(x + size, z, true, displaced).location; double displacement_power; - if (displaced) - { + if (displaced) { displacement_power = 0.0; - } - else - { - displacement_power = renderer->getTexturesRenderer()->getMaximalDisplacement(renderer->getScenery()->getTextures()); + } else { + displacement_power = + renderer->getTexturesRenderer()->getMaximalDisplacement(renderer->getScenery()->getTextures()); } BoundingBox box; - if (displacement_power > 0.0) - { + if (displacement_power > 0.0) { box.pushPoint(chunk->point_nw.add(Vector3(-displacement_power, displacement_power, -displacement_power))); box.pushPoint(chunk->point_nw.add(Vector3(-displacement_power, -displacement_power, -displacement_power))); box.pushPoint(chunk->point_sw.add(Vector3(-displacement_power, displacement_power, displacement_power))); @@ -111,9 +97,7 @@ void TerrainRasterizer::getChunk(TerrainRasterizer::TerrainChunkInfo* chunk, dou box.pushPoint(chunk->point_se.add(Vector3(displacement_power, -displacement_power, displacement_power))); box.pushPoint(chunk->point_ne.add(Vector3(displacement_power, displacement_power, -displacement_power))); box.pushPoint(chunk->point_ne.add(Vector3(displacement_power, -displacement_power, -displacement_power))); - } - else - { + } else { box.pushPoint(chunk->point_nw); box.pushPoint(chunk->point_sw); box.pushPoint(chunk->point_se); @@ -121,23 +105,18 @@ void TerrainRasterizer::getChunk(TerrainRasterizer::TerrainChunkInfo* chunk, dou } int coverage = renderer->render_camera->isUnprojectedBoxInView(box); - if (coverage > 0) - { + if (coverage > 0) { chunk->detail_hint = (int)ceil(sqrt((double)coverage) * detail_factor); - if (chunk->detail_hint > max_chunk_detail) - { + if (chunk->detail_hint > max_chunk_detail) { chunk->detail_hint = max_chunk_detail; } - } - else - { + } else { /* Not in view */ chunk->detail_hint = -1; } } -int TerrainRasterizer::performTessellation(CanvasPortion* canvas, bool displaced) -{ +int TerrainRasterizer::performTessellation(CanvasPortion *canvas, bool displaced) { TerrainChunkInfo chunk; int chunk_factor, chunk_count, i, result; Vector3 cam = renderer->getCameraLocation(VECTOR_ZERO); @@ -154,69 +133,54 @@ int TerrainRasterizer::performTessellation(CanvasPortion* canvas, bool displaced double cx = cam.x - fmod(cam.x, base_chunk_size); double cz = cam.z - fmod(cam.x, base_chunk_size); - while (radius_int < 20000.0) - { - for (i = 0; i < chunk_count - 1; i++) - { + while (radius_int < 20000.0) { + for (i = 0; i < chunk_count - 1; i++) { getChunk(&chunk, cx - radius_ext + chunk_size * i, cz - radius_ext, chunk_size, displaced); - if (chunk.detail_hint > 0) - { + if (chunk.detail_hint > 0) { result += chunk.detail_hint * chunk.detail_hint; - if (canvas) - { + if (canvas) { processChunk(canvas, &chunk); } } - if (interrupted) - { + if (interrupted) { return result; } getChunk(&chunk, cx + radius_int, cz - radius_ext + chunk_size * i, chunk_size, displaced); - if (chunk.detail_hint > 0) - { + if (chunk.detail_hint > 0) { result += chunk.detail_hint * chunk.detail_hint; - if (canvas) - { + if (canvas) { processChunk(canvas, &chunk); } } - if (interrupted) - { + if (interrupted) { return result; } getChunk(&chunk, cx + radius_int - chunk_size * i, cz + radius_int, chunk_size, displaced); - if (chunk.detail_hint > 0) - { + if (chunk.detail_hint > 0) { result += chunk.detail_hint * chunk.detail_hint; - if (canvas) - { + if (canvas) { processChunk(canvas, &chunk); } } - if (interrupted) - { + if (interrupted) { return result; } getChunk(&chunk, cx - radius_ext, cz + radius_int - chunk_size * i, chunk_size, displaced); - if (chunk.detail_hint > 0) - { + if (chunk.detail_hint > 0) { result += chunk.detail_hint * chunk.detail_hint; - if (canvas) - { + if (canvas) { processChunk(canvas, &chunk); } } - if (interrupted) - { + if (interrupted) { return result; } } - if (radius_int > 20.0 && chunk_count % 64 == 0 && (double)chunk_factor < radius_int / 20.0) - { + if (radius_int > 20.0 && chunk_count % 64 == 0 && (double)chunk_factor < radius_int / 20.0) { chunk_count /= 2; chunk_factor *= 2; } @@ -229,24 +193,20 @@ int TerrainRasterizer::performTessellation(CanvasPortion* canvas, bool displaced return result; } -void TerrainRasterizer::processChunk(CanvasPortion* canvas, TerrainChunkInfo* chunk) -{ +void TerrainRasterizer::processChunk(CanvasPortion *canvas, TerrainChunkInfo *chunk) { tessellateChunk(canvas, chunk, chunk->detail_hint); } -int TerrainRasterizer::prepareRasterization() -{ +int TerrainRasterizer::prepareRasterization() { // TODO Chunks could be saved and reused in rasterizeToCanvas return performTessellation(NULL, false); } -void TerrainRasterizer::rasterizeToCanvas(CanvasPortion *canvas) -{ +void TerrainRasterizer::rasterizeToCanvas(CanvasPortion *canvas) { performTessellation(canvas, false); } -Color TerrainRasterizer::shadeFragment(const CanvasFragment &fragment, const CanvasFragment *) const -{ +Color TerrainRasterizer::shadeFragment(const CanvasFragment &fragment, const CanvasFragment *) const { Vector3 point = fragment.getLocation(); double precision = renderer->getPrecision(_getPoint(renderer, point.x, point.z)); return renderer->getTerrainRenderer()->getFinalColor(point, precision); diff --git a/src/render/software/TerrainRasterizer.h b/src/render/software/TerrainRasterizer.h index be7180b..cf99ae0 100644 --- a/src/render/software/TerrainRasterizer.h +++ b/src/render/software/TerrainRasterizer.h @@ -9,11 +9,9 @@ namespace paysages { namespace software { -class SOFTWARESHARED_EXPORT TerrainRasterizer: public Rasterizer -{ -public: - typedef struct - { +class SOFTWARESHARED_EXPORT TerrainRasterizer : public Rasterizer { + public: + typedef struct { Vector3 point_nw; Vector3 point_sw; Vector3 point_se; @@ -21,8 +19,8 @@ public: int detail_hint; } TerrainChunkInfo; -public: - TerrainRasterizer(SoftwareRenderer* renderer, RenderProgress *progress, int client_id); + public: + TerrainRasterizer(SoftwareRenderer *renderer, RenderProgress *progress, int client_id); /** * Set the rasterization quality. @@ -35,14 +33,14 @@ public: virtual void setQuality(double factor) override; virtual int prepareRasterization() override; - virtual void rasterizeToCanvas(CanvasPortion* canvas) override; + virtual void rasterizeToCanvas(CanvasPortion *canvas) override; virtual Color shadeFragment(const CanvasFragment &fragment, const CanvasFragment *previous) const override; -private: + private: /** * Method called for each chunk tessellated by performTessellation. */ - void processChunk(CanvasPortion* canvas, TerrainChunkInfo* chunk); + void processChunk(CanvasPortion *canvas, TerrainChunkInfo *chunk); /** * Tessellate the terrain, calling processChunk for each chunk. @@ -53,24 +51,23 @@ private: * * *canvas* may be NULL to only simulate the tessellation. */ - int performTessellation(CanvasPortion* canvas, bool displaced); + int performTessellation(CanvasPortion *canvas, bool displaced); /** * Tessellate a terrain chunk, pushing the quads in the render area. */ - void tessellateChunk(CanvasPortion* canvas, TerrainChunkInfo* chunk, int detail); + void tessellateChunk(CanvasPortion *canvas, TerrainChunkInfo *chunk, int detail); - void renderQuad(CanvasPortion* canvas, double x, double z, double size, double water_height); + void renderQuad(CanvasPortion *canvas, double x, double z, double size, double water_height); - void getChunk(TerrainRasterizer::TerrainChunkInfo* chunk, double x, double z, double size, bool displaced); + void getChunk(TerrainRasterizer::TerrainChunkInfo *chunk, double x, double z, double size, bool displaced); -private: + private: // Quality control double base_chunk_size; double detail_factor; int max_chunk_detail; }; - } } diff --git a/src/render/software/TerrainRayWalker.cpp b/src/render/software/TerrainRayWalker.cpp index 8a0cab5..e85146f 100644 --- a/src/render/software/TerrainRayWalker.cpp +++ b/src/render/software/TerrainRayWalker.cpp @@ -8,14 +8,12 @@ #include "TexturesRenderer.h" #include "Matrix4.h" -TerrainRayWalker::TerrainRayWalker(SoftwareRenderer* renderer): - renderer(renderer) -{ +TerrainRayWalker::TerrainRayWalker(SoftwareRenderer *renderer) : renderer(renderer) { setQuality(0.5); } -void TerrainRayWalker::setQuality(double displacement_safety, double minimal_step, double maximal_step, double step_factor, double max_distance, double escape_step) -{ +void TerrainRayWalker::setQuality(double displacement_safety, double minimal_step, double maximal_step, + double step_factor, double max_distance, double escape_step) { this->displacement_safety = displacement_safety; this->minimal_step = minimal_step; this->maximal_step = maximal_step; @@ -24,45 +22,35 @@ void TerrainRayWalker::setQuality(double displacement_safety, double minimal_ste this->escape_step = escape_step; } -void TerrainRayWalker::setQuality(double factor) -{ - setQuality(0.2 + 0.8 * factor, - 1.0 / (factor * factor * 30.0 + 1.0), - 50.0 / (factor * 10.0 + 1.0), - 1.0 / (factor * 10.0 + 1.0), - 10.0 + factor * 200.0, - factor * factor * 100.0); +void TerrainRayWalker::setQuality(double factor) { + setQuality(0.2 + 0.8 * factor, 1.0 / (factor * factor * 30.0 + 1.0), 50.0 / (factor * 10.0 + 1.0), + 1.0 / (factor * 10.0 + 1.0), 10.0 + factor * 200.0, factor * factor * 100.0); } -void TerrainRayWalker::update() -{ - TerrainDefinition* terrain = renderer->getScenery()->getTerrain(); +void TerrainRayWalker::update() { + TerrainDefinition *terrain = renderer->getScenery()->getTerrain(); HeightInfo info = terrain->getHeightInfo(); - TexturesDefinition* textures = renderer->getScenery()->getTextures(); + TexturesDefinition *textures = renderer->getScenery()->getTextures(); displacement_base = textures->getMaximalDisplacement(); ymin = info.min_height - displacement_base; ymax = info.max_height + displacement_base; } -static inline Vector3 _getShiftAxis(const Vector3 &direction) -{ - if (fabs(direction.y) > 0.99) - { +static inline Vector3 _getShiftAxis(const Vector3 &direction) { + if (fabs(direction.y) > 0.99) { // When the ray is vertical, we choose an arbitrary shift axis return VECTOR_NORTH; - } - else - { + } else { return VECTOR_UP.crossProduct(direction); } } -bool TerrainRayWalker::startWalking(const Vector3 &start, Vector3 direction, double escape_angle, TerrainHitResult &result) -{ - TerrainRenderer* terrain_renderer = renderer->getTerrainRenderer(); - TexturesRenderer* textures_renderer = renderer->getTexturesRenderer(); +bool TerrainRayWalker::startWalking(const Vector3 &start, Vector3 direction, double escape_angle, + TerrainHitResult &result) { + TerrainRenderer *terrain_renderer = renderer->getTerrainRenderer(); + TexturesRenderer *textures_renderer = renderer->getTexturesRenderer(); TerrainRenderer::TerrainResult terrain_result; Vector3 cursor, displaced; double diff; @@ -75,15 +63,13 @@ bool TerrainRayWalker::startWalking(const Vector3 &start, Vector3 direction, dou double walked_length = 0.0; result.escape_angle = 0.0; - if (escape_angle != 0.0) - { + if (escape_angle != 0.0) { // Prepare escape shift_step = escape_angle / escape_step; shift_matrix = Matrix4::newRotateAxis(-shift_step, _getShiftAxis(direction)); } - do - { + do { // Perform a step cursor = previous_cursor.add(direction.scale(step_length)); @@ -92,21 +78,18 @@ bool TerrainRayWalker::startWalking(const Vector3 &start, Vector3 direction, dou diff = cursor.y - terrain_result.location.y; // If we are very under the terrain, consider a hit - if (diff < -displacement_base * displacement_safety) - { + if (diff < -displacement_base * displacement_safety) { hit = true; } // If we are close enough to the terrain, apply displacement - else if (diff < displacement_base * displacement_safety) - { + else if (diff < displacement_base * displacement_safety) { displaced = textures_renderer->displaceTerrain(terrain_result); diff = cursor.y - displaced.y; hit = diff < 0.0; } - if (hit) - { + if (hit) { // TODO Refine the hit with dichotomy at high quality /*if (renderer->render_quality > 7) { @@ -114,11 +97,9 @@ bool TerrainRayWalker::startWalking(const Vector3 &start, Vector3 direction, dou }*/ // Shift ray to escape terrain - if (escape_angle != 0.0) - { + if (escape_angle != 0.0) { result.escape_angle += shift_step; - if (result.escape_angle > escape_angle) - { + if (result.escape_angle > escape_angle) { // Too much shifted to escape, make it a hit result.escape_angle = 0.0; return true; @@ -129,20 +110,15 @@ bool TerrainRayWalker::startWalking(const Vector3 &start, Vector3 direction, dou } result.hit_location = cursor; - } - else - { + } else { // Prepare next step previous_cursor = cursor; walked_length += step_length; step_length = diff * step_factor; - if (step_length < minimal_step) - { + if (step_length < minimal_step) { step_length = minimal_step; - } - else if (step_length > maximal_step) - { + } else if (step_length > maximal_step) { step_length = maximal_step; } } diff --git a/src/render/software/TerrainRayWalker.h b/src/render/software/TerrainRayWalker.h index 0572e51..f0bd1a3 100644 --- a/src/render/software/TerrainRayWalker.h +++ b/src/render/software/TerrainRayWalker.h @@ -15,16 +15,15 @@ namespace software { * a ray and the terrain (e.g. for raytracing), or a soft intersection * (e.g. for shadows). */ -class SOFTWARESHARED_EXPORT TerrainRayWalker -{ -public: +class SOFTWARESHARED_EXPORT TerrainRayWalker { + public: typedef struct { Vector3 hit_location; // Location of the hit double escape_angle; // Angle used to shift the ray to escape the terrain (0.0 if no escape was possible) } TerrainHitResult; -public: - TerrainRayWalker(SoftwareRenderer* renderer); + public: + TerrainRayWalker(SoftwareRenderer *renderer); /** * Set the walker quality. @@ -36,7 +35,8 @@ public: * @param max_distance Maximal distance allowed to travel before considering an escape * @param escape_step Angle step when allowing an escape angle */ - void setQuality(double displacement_safety, double minimal_step, double maximal_step, double step_factor, double max_distance, double escape_step); + void setQuality(double displacement_safety, double minimal_step, double maximal_step, double step_factor, + double max_distance, double escape_step); void setQuality(double factor); /*! @@ -55,8 +55,8 @@ public: */ bool startWalking(const Vector3 &start, Vector3 direction, double escape_angle, TerrainHitResult &result); -private: - SoftwareRenderer* renderer; + private: + SoftwareRenderer *renderer; double ymin; double ymax; double displacement_base; @@ -69,7 +69,6 @@ private: double max_distance; double escape_step; }; - } } diff --git a/src/render/software/TerrainRenderer.cpp b/src/render/software/TerrainRenderer.cpp index 033a5c0..54dfed8 100644 --- a/src/render/software/TerrainRenderer.cpp +++ b/src/render/software/TerrainRenderer.cpp @@ -8,46 +8,38 @@ #include "TerrainRayWalker.h" #include "RayCastingResult.h" -TerrainRenderer::TerrainRenderer(SoftwareRenderer* parent): - parent(parent) -{ +TerrainRenderer::TerrainRenderer(SoftwareRenderer *parent) : parent(parent) { walker_ray = new TerrainRayWalker(parent); walker_shadows = new TerrainRayWalker(parent); quad_normals = false; } -TerrainRenderer::~TerrainRenderer() -{ +TerrainRenderer::~TerrainRenderer() { delete walker_ray; delete walker_shadows; } -void TerrainRenderer::update() -{ +void TerrainRenderer::update() { walker_ray->update(); walker_shadows->update(); } -void TerrainRenderer::setQuality(bool quad_normals, double ray_precision, double shadow_precision) -{ +void TerrainRenderer::setQuality(bool quad_normals, double ray_precision, double shadow_precision) { this->quad_normals = quad_normals; walker_ray->setQuality(ray_precision); walker_shadows->setQuality(shadow_precision); } -void TerrainRenderer::setQuality(double factor) -{ +void TerrainRenderer::setQuality(double factor) { setQuality(factor > 0.6, factor, factor * factor); } -double TerrainRenderer::getHeight(double x, double z, bool with_painting, bool water_offset) -{ +double TerrainRenderer::getHeight(double x, double z, bool with_painting, bool water_offset) { return parent->getScenery()->getTerrain()->getInterpolatedHeight(x, z, true, with_painting, water_offset); } -static inline Vector3 _getNormal4(Vector3 center, Vector3 north, Vector3 east, Vector3 south, Vector3 west) -{ +static inline Vector3 _getNormal4(Vector3 center, Vector3 north, Vector3 east, Vector3 south, Vector3 west) { Vector3 dnorth, deast, dsouth, dwest, normal; dnorth = north.sub(center); @@ -63,13 +55,11 @@ static inline Vector3 _getNormal4(Vector3 center, Vector3 north, Vector3 east, V return normal.normalize(); } -static inline Vector3 _getNormal2(Vector3 center, Vector3 east, Vector3 south) -{ +static inline Vector3 _getNormal2(Vector3 center, Vector3 east, Vector3 south) { return south.sub(center).crossProduct(east.sub(center)).normalize(); } -TerrainRenderer::TerrainResult TerrainRenderer::getResult(double x, double z, bool with_painting, bool with_textures) -{ +TerrainRenderer::TerrainResult TerrainRenderer::getResult(double x, double z, bool with_painting, bool with_textures) { TerrainResult result; double detail = 0.001; /* TODO */ @@ -88,8 +78,7 @@ TerrainRenderer::TerrainResult TerrainRenderer::getResult(double x, double z, bo south.z = z + detail; south.y = getHeight(south.x, south.z, with_painting); - if (parent->render_quality > 6) - { + if (parent->render_quality > 6) { west.x = x - detail; west.z = z; west.y = getHeight(west.x, west.z, with_painting); @@ -99,9 +88,7 @@ TerrainRenderer::TerrainResult TerrainRenderer::getResult(double x, double z, bo north.y = getHeight(north.x, north.z, with_painting); result.normal = _getNormal4(center, north, east, south, west); - } - else - { + } else { result.normal = _getNormal2(center, east, south); } @@ -109,14 +96,12 @@ TerrainRenderer::TerrainResult TerrainRenderer::getResult(double x, double z, bo result.location = center; /* Texture displacement */ - if (with_textures) - { + if (with_textures) { center = parent->getTexturesRenderer()->displaceTerrain(result); result.location = center; /* Recompute normal */ - if (parent->render_quality > 6) - { + if (parent->render_quality > 6) { /* Use 5 points on displaced terrain */ east = parent->getTexturesRenderer()->displaceTerrain(getResult(east.x, east.z, with_painting, 0)); south = parent->getTexturesRenderer()->displaceTerrain(getResult(south.x, south.z, with_painting, 0)); @@ -124,17 +109,13 @@ TerrainRenderer::TerrainResult TerrainRenderer::getResult(double x, double z, bo north = parent->getTexturesRenderer()->displaceTerrain(getResult(north.x, north.z, with_painting, 0)); result.normal = _getNormal4(center, north, east, south, west); - } - else if (parent->render_quality > 2) - { + } else if (parent->render_quality > 2) { /* Use 3 points on displaced terrain */ east = parent->getTexturesRenderer()->displaceTerrain(getResult(east.x, east.z, with_painting, 0)); south = parent->getTexturesRenderer()->displaceTerrain(getResult(south.x, south.z, with_painting, 0)); result.normal = _getNormal2(center, east, south); - } - else - { + } else { /* TODO Use texture noise directly, as if terrain was a plane */ } } @@ -142,50 +123,40 @@ TerrainRenderer::TerrainResult TerrainRenderer::getResult(double x, double z, bo return result; } -Color TerrainRenderer::getFinalColor(const Vector3 &location, double) -{ +Color TerrainRenderer::getFinalColor(const Vector3 &location, double) { /* TODO Restore precision control */ TexturesRenderer::TexturesResult textures = parent->getTexturesRenderer()->applyToTerrain(location.x, location.z); return parent->applyMediumTraversal(textures.final_location, textures.final_color); } -RayCastingResult TerrainRenderer::castRay(const Vector3 &start, const Vector3 &direction) -{ +RayCastingResult TerrainRenderer::castRay(const Vector3 &start, const Vector3 &direction) { RayCastingResult result; TerrainRayWalker::TerrainHitResult walk_result; - if (walker_ray->startWalking(start, direction.normalize(), 0.0, walk_result)) - { + if (walker_ray->startWalking(start, direction.normalize(), 0.0, walk_result)) { result.hit = true; result.hit_location = walk_result.hit_location; result.hit_color = getFinalColor(walk_result.hit_location, parent->getPrecision(walk_result.hit_location)); - } - else - { + } else { result.hit = false; } return result; } -bool TerrainRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) -{ - TerrainDefinition* definition = parent->getScenery()->getTerrain(); +bool TerrainRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) { + TerrainDefinition *definition = parent->getScenery()->getTerrain(); TerrainRayWalker::TerrainHitResult walk_result; // If location is above terrain, don't bother - if (at.y > definition->getHeightInfo().max_height) - { + if (at.y > definition->getHeightInfo().max_height) { return true; } // Handle sun below horizon Vector3 direction_to_light = light.direction.scale(-1.0); - if (direction_to_light.y < -0.05) - { + if (direction_to_light.y < -0.05) { light.color = COLOR_BLACK; return false; - } - else if (direction_to_light.y < 0.0000) - { + } else if (direction_to_light.y < 0.0000) { light.color.r *= (0.05 + direction_to_light.y) / 0.05; light.color.g *= (0.05 + direction_to_light.y) / 0.05; light.color.b *= (0.05 + direction_to_light.y) / 0.05; @@ -194,16 +165,12 @@ bool TerrainRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) // Walk to find an intersection double escape_angle = definition->shadow_smoothing; // TODO max length should depend on the sun light angle and altitude range - if (walker_shadows->startWalking(at, direction_to_light, escape_angle, walk_result)) - { - if (walk_result.escape_angle == 0.0) - { + if (walker_shadows->startWalking(at, direction_to_light, escape_angle, walk_result)) { + if (walk_result.escape_angle == 0.0) { // Hit, with no escape, cancelling the light light.color = COLOR_BLACK; return false; - } - else - { + } else { // Hit, with an escape double light_factor = 1.0 - (walk_result.escape_angle / escape_angle); @@ -213,9 +180,7 @@ bool TerrainRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) return true; } - } - else - { + } else { // No hit, leave light alone return true; } diff --git a/src/render/software/TerrainRenderer.h b/src/render/software/TerrainRenderer.h index ec462ba..094eead 100644 --- a/src/render/software/TerrainRenderer.h +++ b/src/render/software/TerrainRenderer.h @@ -11,17 +11,15 @@ namespace paysages { namespace software { -class SOFTWARESHARED_EXPORT TerrainRenderer: public LightFilter -{ -public: - typedef struct - { +class SOFTWARESHARED_EXPORT TerrainRenderer : public LightFilter { + public: + typedef struct { Vector3 location; Vector3 normal; } TerrainResult; -public: - TerrainRenderer(SoftwareRenderer* parent); + public: + TerrainRenderer(SoftwareRenderer *parent); virtual ~TerrainRenderer(); virtual void update(); @@ -29,19 +27,18 @@ public: void setQuality(double factor); virtual RayCastingResult castRay(const Vector3 &start, const Vector3 &direction); - virtual double getHeight(double x, double z, bool with_painting, bool water_offset=true); + virtual double getHeight(double x, double z, bool with_painting, bool water_offset = true); virtual TerrainResult getResult(double x, double z, bool with_painting, bool with_textures); virtual Color getFinalColor(const Vector3 &location, double precision); virtual bool applyLightFilter(LightComponent &light, const Vector3 &at) override; -private: + private: SoftwareRenderer *parent; TerrainRayWalker *walker_ray; TerrainRayWalker *walker_shadows; bool quad_normals; }; - } } diff --git a/src/render/software/TexturesRenderer.cpp b/src/render/software/TexturesRenderer.cpp index 57868ab..015f732 100644 --- a/src/render/software/TexturesRenderer.cpp +++ b/src/render/software/TexturesRenderer.cpp @@ -7,32 +7,27 @@ #include "Zone.h" #include "NoiseGenerator.h" -TexturesRenderer::TexturesRenderer(SoftwareRenderer *parent): - parent(parent) -{ +TexturesRenderer::TexturesRenderer(SoftwareRenderer *parent) : parent(parent) { } -TexturesRenderer::~TexturesRenderer() -{ +TexturesRenderer::~TexturesRenderer() { } -void TexturesRenderer::update() -{ +void TexturesRenderer::update() { } /* * Get the base presence factor of a layer, not accounting for other layers. */ -double TexturesRenderer::getLayerBasePresence(TextureLayerDefinition *layer, const TerrainRenderer::TerrainResult &terrain) -{ +double TexturesRenderer::getLayerBasePresence(TextureLayerDefinition *layer, + const TerrainRenderer::TerrainResult &terrain) { return layer->terrain_zone->getValue(terrain.location, terrain.normal); } /* * Get triplanar noise value, depending on the normal direction. */ -double TexturesRenderer::getTriplanarNoise(NoiseGenerator *noise, const Vector3 &location, const Vector3 &normal) -{ +double TexturesRenderer::getTriplanarNoise(NoiseGenerator *noise, const Vector3 &location, const Vector3 &normal) { double noiseXY = noise->get2DTotal(location.x, location.y); double noiseXZ = noise->get2DTotal(location.x, location.z); double noiseYZ = noise->get2DTotal(location.y, location.z); @@ -48,25 +43,21 @@ double TexturesRenderer::getTriplanarNoise(NoiseGenerator *noise, const Vector3 return noiseXY * mXY + noiseXZ * mXZ + noiseYZ * mYZ; } -double TexturesRenderer::getMaximalDisplacement(TexturesDefinition *textures) -{ +double TexturesRenderer::getMaximalDisplacement(TexturesDefinition *textures) { int i, n; double disp = 0.0; n = textures->count(); - for (i = 0; i < n; i++) - { - TextureLayerDefinition* layer = textures->getTextureLayer(i); + for (i = 0; i < n; i++) { + TextureLayerDefinition *layer = textures->getTextureLayer(i); - if (layer->displacement_height > 0.0) - { + if (layer->displacement_height > 0.0) { disp += layer->displacement_height; } } return disp; } -static inline Vector3 _getNormal4(Vector3 center, Vector3 north, Vector3 east, Vector3 south, Vector3 west) -{ +static inline Vector3 _getNormal4(Vector3 center, Vector3 north, Vector3 east, Vector3 south, Vector3 west) { Vector3 dnorth, deast, dsouth, dwest, normal; dnorth = north.sub(center); @@ -82,26 +73,22 @@ static inline Vector3 _getNormal4(Vector3 center, Vector3 north, Vector3 east, V return normal.normalize(); } -static inline Vector3 _getNormal2(Vector3 center, Vector3 east, Vector3 south) -{ +static inline Vector3 _getNormal2(Vector3 center, Vector3 east, Vector3 south) { return south.sub(center).crossProduct(east.sub(center)).normalize(); } -static Vector3 _getDetailNormal(SoftwareRenderer* renderer, Vector3 base_location, Vector3 base_normal, TextureLayerDefinition* layer) -{ - TexturesRenderer* textures = renderer->getTexturesRenderer(); +static Vector3 _getDetailNormal(SoftwareRenderer *renderer, Vector3 base_location, Vector3 base_normal, + TextureLayerDefinition *layer) { + TexturesRenderer *textures = renderer->getTexturesRenderer(); Vector3 result; double offset = 0.01; /* Find guiding vectors in the appoximated local plane */ Vector3 dx, dy; Vector3 pivot; - if (base_normal.y > 0.95) - { + if (base_normal.y > 0.95) { pivot = VECTOR_NORTH; - } - else - { + } else { pivot = VECTOR_UP; } dx = base_normal.crossProduct(pivot).normalize(); @@ -110,7 +97,8 @@ static Vector3 _getDetailNormal(SoftwareRenderer* renderer, Vector3 base_locatio /* Apply detail noise locally */ Vector3 center, north, east, south, west; - center = base_location.add(base_normal.scale(textures->getTriplanarNoise(layer->_detail_noise, base_location, base_normal))); + center = base_location.add( + base_normal.scale(textures->getTriplanarNoise(layer->_detail_noise, base_location, base_normal))); east = base_location.add(dx.scale(offset)); east = east.add(base_normal.scale(textures->getTriplanarNoise(layer->_detail_noise, east, base_normal))); @@ -118,8 +106,7 @@ static Vector3 _getDetailNormal(SoftwareRenderer* renderer, Vector3 base_locatio south = base_location.add(dy.scale(offset)); south = south.add(base_normal.scale(textures->getTriplanarNoise(layer->_detail_noise, south, base_normal))); - if (renderer->render_quality > 6) - { + if (renderer->render_quality > 6) { west = base_location.add(dx.scale(-offset)); west = west.add(base_normal.scale(textures->getTriplanarNoise(layer->_detail_noise, west, base_normal))); @@ -127,50 +114,45 @@ static Vector3 _getDetailNormal(SoftwareRenderer* renderer, Vector3 base_locatio north = north.add(base_normal.scale(textures->getTriplanarNoise(layer->_detail_noise, north, base_normal))); result = _getNormal4(center, north, east, south, west); - } - else - { + } else { result = _getNormal2(center, east, south); } - if (result.dotProduct(base_normal) < 0.0) - { + if (result.dotProduct(base_normal) < 0.0) { result = result.scale(-1.0); } return result; } -Vector3 TexturesRenderer::displaceTerrain(const TerrainRenderer::TerrainResult &terrain) -{ - TexturesDefinition* textures = parent->getScenery()->getTextures(); +Vector3 TexturesRenderer::displaceTerrain(const TerrainRenderer::TerrainResult &terrain) { + TexturesDefinition *textures = parent->getScenery()->getTextures(); double offset = 0.0; int i, n; n = textures->count(); - for (i = 0; i < n; i++) - { - TextureLayerDefinition* layer = textures->getTextureLayer(i); + for (i = 0; i < n; i++) { + TextureLayerDefinition *layer = textures->getTextureLayer(i); - if (layer->displacement_height > 0.0) - { + if (layer->displacement_height > 0.0) { double presence = getLayerBasePresence(layer, terrain); - Vector3 location = {terrain.location.x / layer->displacement_scaling, terrain.location.y / layer->displacement_scaling, terrain.location.z / layer->displacement_scaling}; - offset += getTriplanarNoise(layer->_displacement_noise, location, terrain.normal) * presence * layer->displacement_height; + Vector3 location = {terrain.location.x / layer->displacement_scaling, + terrain.location.y / layer->displacement_scaling, + terrain.location.z / layer->displacement_scaling}; + offset += getTriplanarNoise(layer->_displacement_noise, location, terrain.normal) * presence * + layer->displacement_height; } } return terrain.location.add(terrain.normal.normalize().scale(offset)); } -double TexturesRenderer::getBasePresence(int layer, const TerrainRenderer::TerrainResult &terrain) -{ - TextureLayerDefinition* layerdef = parent->getScenery()->getTextures()->getTextureLayer(layer); +double TexturesRenderer::getBasePresence(int layer, const TerrainRenderer::TerrainResult &terrain) { + TextureLayerDefinition *layerdef = parent->getScenery()->getTextures()->getTextureLayer(layer); return getLayerBasePresence(layerdef, terrain); } -TexturesRenderer::TexturesResult TexturesRenderer::applyToTerrain(double x, double z) -{ - TexturesDefinition* textures = parent->getScenery()->getTextures(); +TexturesRenderer::TexturesResult TexturesRenderer::applyToTerrain(double x, double z) { + TexturesDefinition *textures = parent->getScenery()->getTextures(); TexturesResult result; // Displacement @@ -181,14 +163,12 @@ TexturesRenderer::TexturesResult TexturesRenderer::applyToTerrain(double x, doub // Find presence of each layer int n = textures->count(); int start = 0; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { TexturesLayerResult &layer = result.layers[i]; layer.definition = textures->getTextureLayer(i); layer.presence = getBasePresence(i, terrain); - if (layer.presence > 0.9999) - { + if (layer.presence > 0.9999) { start = i; } } @@ -200,20 +180,16 @@ TexturesRenderer::TexturesResult TexturesRenderer::applyToTerrain(double x, doub result.final_color = COLOR_GREEN; // Compute and merge colors of visible layers - for (int i = start; i < n; i++) - { + for (int i = start; i < n; i++) { TexturesLayerResult &layer = result.layers[i]; - if (layer.presence > 0.0) - { + if (layer.presence > 0.0) { Vector3 normal = _getDetailNormal(parent, terrain.location, terrain.normal, layer.definition); Vector3 location(x, terrain.location.y, z); layer.color = parent->applyLightingToSurface(location, normal, *layer.definition->material); layer.color.a = layer.presence; result.final_color.mask(layer.color); - } - else - { + } else { layer.color = COLOR_TRANSPARENT; } } diff --git a/src/render/software/TexturesRenderer.h b/src/render/software/TexturesRenderer.h index 2986b7b..70ac873 100644 --- a/src/render/software/TexturesRenderer.h +++ b/src/render/software/TexturesRenderer.h @@ -10,18 +10,15 @@ namespace paysages { namespace software { -class SOFTWARESHARED_EXPORT TexturesRenderer -{ -public: - typedef struct - { - TextureLayerDefinition* definition; +class SOFTWARESHARED_EXPORT TexturesRenderer { + public: + typedef struct { + TextureLayerDefinition *definition; double presence; Color color; } TexturesLayerResult; - typedef struct - { + typedef struct { Vector3 base_location; Vector3 base_normal; int layer_count; @@ -30,7 +27,7 @@ public: Color final_color; } TexturesResult; -public: + public: TexturesRenderer(SoftwareRenderer *parent); virtual ~TexturesRenderer(); @@ -44,10 +41,9 @@ public: virtual double getBasePresence(int layer, const TerrainRenderer::TerrainResult &terrain); virtual TexturesResult applyToTerrain(double x, double z); -private: + private: SoftwareRenderer *parent; }; - } } diff --git a/src/render/software/WaterRasterizer.cpp b/src/render/software/WaterRasterizer.cpp index 26c451c..a1817a9 100644 --- a/src/render/software/WaterRasterizer.cpp +++ b/src/render/software/WaterRasterizer.cpp @@ -5,13 +5,11 @@ #include "CanvasFragment.h" #include "RenderProgress.h" -WaterRasterizer::WaterRasterizer(SoftwareRenderer* renderer, RenderProgress *progress, int client_id): - Rasterizer(renderer, progress, client_id, Color(0.9, 0.95, 1.0)) -{ +WaterRasterizer::WaterRasterizer(SoftwareRenderer *renderer, RenderProgress *progress, int client_id) + : Rasterizer(renderer, progress, client_id, Color(0.9, 0.95, 1.0)) { } -static inline Vector3 _getFirstPassVertex(SoftwareRenderer* renderer, double x, double z) -{ +static inline Vector3 _getFirstPassVertex(SoftwareRenderer *renderer, double x, double z) { Vector3 result; result.x = x; @@ -21,8 +19,7 @@ static inline Vector3 _getFirstPassVertex(SoftwareRenderer* renderer, double x, return result; } -void WaterRasterizer::rasterizeQuad(CanvasPortion* canvas, double x, double z, double size) -{ +void WaterRasterizer::rasterizeQuad(CanvasPortion *canvas, double x, double z, double size) { Vector3 v1, v2, v3, v4; v1 = _getFirstPassVertex(renderer, x, z); @@ -33,33 +30,27 @@ void WaterRasterizer::rasterizeQuad(CanvasPortion* canvas, double x, double z, d pushQuad(canvas, v1, v2, v3, v4); } -int WaterRasterizer::prepareRasterization() -{ +int WaterRasterizer::prepareRasterization() { return performTessellation(NULL); } -void WaterRasterizer::rasterizeToCanvas(CanvasPortion *canvas) -{ +void WaterRasterizer::rasterizeToCanvas(CanvasPortion *canvas) { performTessellation(canvas); } -Color WaterRasterizer::shadeFragment(const CanvasFragment &fragment, const CanvasFragment *) const -{ +Color WaterRasterizer::shadeFragment(const CanvasFragment &fragment, const CanvasFragment *) const { Vector3 location = fragment.getLocation(); return renderer->getWaterRenderer()->getResult(location.x, location.z).final; } -void WaterRasterizer::setQuality(double factor) -{ +void WaterRasterizer::setQuality(double factor) { base_chunk_size = 10.0 / (1.0 + factor * 7.0); - if (factor > 0.6) - { + if (factor > 0.6) { base_chunk_size *= 0.5; } } -int WaterRasterizer::performTessellation(CanvasPortion *canvas) -{ +int WaterRasterizer::performTessellation(CanvasPortion *canvas) { int chunk_factor, chunk_count, i, result; Vector3 cam = renderer->getCameraLocation(VECTOR_ZERO); double radius_int, radius_ext, chunk_size; @@ -74,31 +65,25 @@ int WaterRasterizer::performTessellation(CanvasPortion *canvas) double cx = cam.x - fmod(cam.x, base_chunk_size); double cz = cam.z - fmod(cam.x, base_chunk_size); - while (radius_int < 20000.0) - { - if (interrupted) - { + while (radius_int < 20000.0) { + if (interrupted) { return result; } - for (i = 0; i < chunk_count - 1; i++) - { + for (i = 0; i < chunk_count - 1; i++) { result++; - if (canvas) - { + if (canvas) { rasterizeQuad(canvas, cx - radius_ext + chunk_size * i, cz - radius_ext, chunk_size); rasterizeQuad(canvas, cx + radius_int, cz - radius_ext + chunk_size * i, chunk_size); rasterizeQuad(canvas, cx + radius_int - chunk_size * i, cz + radius_int, chunk_size); rasterizeQuad(canvas, cx - radius_ext, cz + radius_int - chunk_size * i, chunk_size); } } - if (canvas) - { + if (canvas) { progress->add(chunk_count - 1); } - if (radius_int > 20.0 && chunk_count % 64 == 0 && (double)chunk_factor < radius_int / 20.0) - { + if (radius_int > 20.0 && chunk_count % 64 == 0 && (double)chunk_factor < radius_int / 20.0) { chunk_count /= 2; chunk_factor *= 2; } diff --git a/src/render/software/WaterRasterizer.h b/src/render/software/WaterRasterizer.h index f90af89..acbf3bf 100644 --- a/src/render/software/WaterRasterizer.h +++ b/src/render/software/WaterRasterizer.h @@ -8,27 +8,25 @@ namespace paysages { namespace software { -class WaterRasterizer: public Rasterizer -{ -public: - WaterRasterizer(SoftwareRenderer* renderer, RenderProgress *progress, int client_id); +class WaterRasterizer : public Rasterizer { + public: + WaterRasterizer(SoftwareRenderer *renderer, RenderProgress *progress, int client_id); - void rasterizeQuad(CanvasPortion* canvas, double x, double z, double size); + void rasterizeQuad(CanvasPortion *canvas, double x, double z, double size); virtual int prepareRasterization() override; - virtual void rasterizeToCanvas(CanvasPortion* canvas) override; + virtual void rasterizeToCanvas(CanvasPortion *canvas) override; virtual Color shadeFragment(const CanvasFragment &fragment, const CanvasFragment *previous) const override; virtual void setQuality(double factor) override; -private: - int performTessellation(CanvasPortion* canvas); + private: + int performTessellation(CanvasPortion *canvas); -private: + private: // Quality control double base_chunk_size; }; - } } diff --git a/src/render/software/WaterRenderer.cpp b/src/render/software/WaterRenderer.cpp index 5a111f0..f5b0eee 100644 --- a/src/render/software/WaterRenderer.cpp +++ b/src/render/software/WaterRenderer.cpp @@ -11,32 +11,26 @@ #include "FloatNode.h" #include "RayCastingResult.h" -WaterRenderer::WaterRenderer(SoftwareRenderer* parent): - parent(parent) -{ +WaterRenderer::WaterRenderer(SoftwareRenderer *parent) : parent(parent) { noise = new NoiseFunctionSimplex(); } -WaterRenderer::~WaterRenderer() -{ +WaterRenderer::~WaterRenderer() { delete noise; } -void WaterRenderer::update() -{ - WaterDefinition* definition = parent->getScenery()->getWater(); +void WaterRenderer::update() { + WaterDefinition *definition = parent->getScenery()->getWater(); noise->setState(*definition->noise_state); noise->setScaling(definition->scaling * 0.3, definition->waves_height * 0.05); noise->setStep(0.3); } -static inline double _getHeight(WaterDefinition* definition, FractalNoise* noise, double x, double z) -{ +static inline double _getHeight(WaterDefinition *definition, FractalNoise *noise, double x, double z) { return noise->get2d(0.00001, x + definition->propXOffset()->getValue(), z + definition->propZOffset()->getValue()); } -static inline Vector3 _getNormal(WaterDefinition* definition, FractalNoise* noise, Vector3 base, double detail) -{ +static inline Vector3 _getNormal(WaterDefinition *definition, FractalNoise *noise, Vector3 base, double detail) { Vector3 back, right; double x, z; @@ -56,33 +50,28 @@ static inline Vector3 _getNormal(WaterDefinition* definition, FractalNoise* nois return back.crossProduct(right).normalize(); } -static inline Vector3 _reflectRay(Vector3 incoming, Vector3 normal) -{ +static inline Vector3 _reflectRay(Vector3 incoming, Vector3 normal) { double c; c = normal.dotProduct(incoming.scale(-1.0)); return incoming.add(normal.scale(2.0 * c)); } -static inline Vector3 _refractRay(Vector3 incoming, Vector3 normal) -{ +static inline Vector3 _refractRay(Vector3 incoming, Vector3 normal) { double c1, c2, f; f = 1.0 / 1.33; c1 = normal.dotProduct(incoming.scale(-1.0)); c2 = sqrt(1.0 - pow(f, 2.0) * (1.0 - pow(c1, 2.0))); - if (c1 >= 0.0) - { + if (c1 >= 0.0) { return incoming.scale(f).add(normal.scale(f * c1 - c2)); - } - else - { + } else { return incoming.scale(f).add(normal.scale(c2 - f * c1)); } } -static inline Color _getFoamMask(SoftwareRenderer* renderer, WaterDefinition* definition, FractalNoise* noise, Vector3 location, Vector3 normal, double detail) -{ +static inline Color _getFoamMask(SoftwareRenderer *renderer, WaterDefinition *definition, FractalNoise *noise, + Vector3 location, Vector3 normal, double detail) { Color result; double foam_factor, normal_diff, location_offset; @@ -91,38 +80,32 @@ static inline Color _getFoamMask(SoftwareRenderer* renderer, WaterDefinition* de foam_factor = 0.0; location.x += location_offset; normal_diff = 1.0 - normal.dotProduct(_getNormal(definition, noise, location, detail)); - if (normal_diff > foam_factor) - { + if (normal_diff > foam_factor) { foam_factor = normal_diff; } location.x -= location_offset * 2.0; normal_diff = 1.0 - normal.dotProduct(_getNormal(definition, noise, location, detail)); - if (normal_diff > foam_factor) - { + if (normal_diff > foam_factor) { foam_factor = normal_diff; } location.x += location_offset; location.z -= location_offset; normal_diff = 1.0 - normal.dotProduct(_getNormal(definition, noise, location, detail)); - if (normal_diff > foam_factor) - { + if (normal_diff > foam_factor) { foam_factor = normal_diff; } location.z += location_offset * 2.0; normal_diff = 1.0 - normal.dotProduct(_getNormal(definition, noise, location, detail)); - if (normal_diff > foam_factor) - { + if (normal_diff > foam_factor) { foam_factor = normal_diff; } foam_factor *= 10.0; - if (foam_factor > 1.0) - { + if (foam_factor > 1.0) { foam_factor = 1.0; } - if (foam_factor <= 1.0 - definition->foam_coverage) - { + if (foam_factor <= 1.0 - definition->foam_coverage) { return COLOR_TRANSPARENT; } foam_factor = (foam_factor - (1.0 - definition->foam_coverage)) * definition->foam_coverage; @@ -134,26 +117,22 @@ static inline Color _getFoamMask(SoftwareRenderer* renderer, WaterDefinition* de result.b *= 2.0; /* TODO This should be configurable */ - if (foam_factor > 0.2) - { + if (foam_factor > 0.2) { result.a = 0.8; - } - else - { + } else { result.a = 0.8 * (foam_factor / 0.2); } return result; } -HeightInfo WaterRenderer::getHeightInfo() -{ +HeightInfo WaterRenderer::getHeightInfo() { HeightInfo info; double noise_minvalue, noise_maxvalue; info.base_height = 0.0; // TODO - //noise->getRange(&noise_minvalue, &noise_maxvalue); + // noise->getRange(&noise_minvalue, &noise_maxvalue); noise_minvalue = noise_maxvalue = 0.0; info.min_height = info.base_height + noise_minvalue; info.max_height = info.base_height + noise_maxvalue; @@ -161,14 +140,12 @@ HeightInfo WaterRenderer::getHeightInfo() return info; } -double WaterRenderer::getHeight(double x, double z) -{ +double WaterRenderer::getHeight(double x, double z) { return _getHeight(parent->getScenery()->getWater(), noise, x, z); } -WaterRenderer::WaterResult WaterRenderer::getResult(double x, double z) -{ - WaterDefinition* definition = parent->getScenery()->getWater(); +WaterRenderer::WaterResult WaterRenderer::getResult(double x, double z) { + WaterDefinition *definition = parent->getScenery()->getWater(); WaterResult result; RayCastingResult refracted; Vector3 location, normal, look_direction; @@ -182,8 +159,7 @@ WaterRenderer::WaterResult WaterRenderer::getResult(double x, double z) result.location = location; detail = parent->getPrecision(location) * 0.1; - if (detail < 0.00001) - { + if (detail < 0.00001) { detail = 0.00001; } @@ -191,32 +167,23 @@ WaterRenderer::WaterResult WaterRenderer::getResult(double x, double z) look_direction = location.sub(parent->getCameraLocation(location)).normalize(); /* Reflection */ - if (reflection == 0.0) - { + if (reflection == 0.0) { result.reflected = COLOR_BLACK; - } - else - { + } else { result.reflected = parent->rayWalking(location, _reflectRay(look_direction, normal), 1, 0, 1, 1).hit_color; } /* Transparency/refraction */ - if (definition->transparency == 0.0) - { + if (definition->transparency == 0.0) { result.refracted = COLOR_BLACK; - } - else - { + } else { Color depth_color = *definition->depth_color; refracted = parent->rayWalking(location, _refractRay(look_direction, normal), 1, 0, 1, 1); depth = location.sub(refracted.hit_location).getNorm(); depth_color.limitPower(refracted.hit_color.getPower()); - if (depth > definition->transparency_depth) - { + if (depth > definition->transparency_depth) { result.refracted = depth_color; - } - else - { + } else { depth /= definition->transparency_depth; result.refracted.r = refracted.hit_color.r * (1.0 - depth) + depth_color.r * depth; result.refracted.g = refracted.hit_color.g * (1.0 - depth) + depth_color.g * depth; @@ -245,18 +212,14 @@ WaterRenderer::WaterResult WaterRenderer::getResult(double x, double z) return result; } -bool WaterRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) -{ - WaterDefinition* definition = parent->getScenery()->getWater(); +bool WaterRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) { + WaterDefinition *definition = parent->getScenery()->getWater(); double factor; - if (at.y < 0.0) - { - if (light.direction.y <= -0.00001) - { + if (at.y < 0.0) { + if (light.direction.y <= -0.00001) { factor = -at.y / (-light.direction.y * definition->lighting_depth); - if (factor > 1.0) - { + if (factor > 1.0) { factor = 1.0; } factor = 1.0 - factor; @@ -267,15 +230,11 @@ bool WaterRenderer::applyLightFilter(LightComponent &light, const Vector3 &at) light.reflection *= factor; return factor > 0.0; - } - else - { + } else { light.color = COLOR_BLACK; return false; } - } - else - { + } else { return true; } } diff --git a/src/render/software/WaterRenderer.h b/src/render/software/WaterRenderer.h index 4dd2f2c..14c444c 100644 --- a/src/render/software/WaterRenderer.h +++ b/src/render/software/WaterRenderer.h @@ -12,11 +12,9 @@ namespace paysages { namespace software { -class SOFTWARESHARED_EXPORT WaterRenderer:public LightFilter -{ -public: - typedef struct - { +class SOFTWARESHARED_EXPORT WaterRenderer : public LightFilter { + public: + typedef struct { Vector3 location; Color base; Color reflected; @@ -25,8 +23,8 @@ public: Color final; } WaterResult; -public: - WaterRenderer(SoftwareRenderer* parent); + public: + WaterRenderer(SoftwareRenderer *parent); virtual ~WaterRenderer(); virtual void update(); @@ -36,11 +34,10 @@ public: virtual WaterResult getResult(double x, double z); virtual bool applyLightFilter(LightComponent &light, const Vector3 &at) override; -private: - SoftwareRenderer* parent; - FractalNoise* noise; + private: + SoftwareRenderer *parent; + FractalNoise *noise; }; - } } diff --git a/src/render/software/clouds/BaseCloudsModel.cpp b/src/render/software/clouds/BaseCloudsModel.cpp index f1c6162..10993fd 100644 --- a/src/render/software/clouds/BaseCloudsModel.cpp +++ b/src/render/software/clouds/BaseCloudsModel.cpp @@ -2,27 +2,21 @@ #include "CloudLayerDefinition.h" -BaseCloudsModel::BaseCloudsModel(CloudLayerDefinition *layer): - layer(layer) -{ +BaseCloudsModel::BaseCloudsModel(CloudLayerDefinition *layer) : layer(layer) { } -BaseCloudsModel::~BaseCloudsModel() -{ +BaseCloudsModel::~BaseCloudsModel() { } -void BaseCloudsModel::update() -{ +void BaseCloudsModel::update() { } -void BaseCloudsModel::getAltitudeRange(double *min_altitude, double *max_altitude) const -{ +void BaseCloudsModel::getAltitudeRange(double *min_altitude, double *max_altitude) const { *min_altitude = layer->altitude; *max_altitude = layer->altitude * layer->scaling; } -void BaseCloudsModel::getDetailRange(double *min_step, double *max_step) const -{ +void BaseCloudsModel::getDetailRange(double *min_step, double *max_step) const { double min_altitude, max_altitude, thickness; getAltitudeRange(&min_altitude, &max_altitude); thickness = max_altitude - min_altitude; @@ -30,23 +24,18 @@ void BaseCloudsModel::getDetailRange(double *min_step, double *max_step) const *max_step = thickness * 0.2; } -double BaseCloudsModel::getProbability(const Vector3 &, double) const -{ +double BaseCloudsModel::getProbability(const Vector3 &, double) const { return 1.0; } -double BaseCloudsModel::getDensity(const Vector3 &) const -{ +double BaseCloudsModel::getDensity(const Vector3 &) const { return 0.0; } -Color BaseCloudsModel::filterLight(const Color &light, double, double) const -{ +Color BaseCloudsModel::filterLight(const Color &light, double, double) const { return light; } -Color BaseCloudsModel::applyLightExit(const Color &light, const Vector3 &, const Vector3 &) const -{ +Color BaseCloudsModel::applyLightExit(const Color &light, const Vector3 &, const Vector3 &) const { return light; } - diff --git a/src/render/software/clouds/BaseCloudsModel.h b/src/render/software/clouds/BaseCloudsModel.h index 09fa815..5f45fe2 100644 --- a/src/render/software/clouds/BaseCloudsModel.h +++ b/src/render/software/clouds/BaseCloudsModel.h @@ -11,9 +11,8 @@ namespace software { /*! * \brief Abstract class for all cloud models (cirrus, cumulus...). */ -class SOFTWARESHARED_EXPORT BaseCloudsModel -{ -public: +class SOFTWARESHARED_EXPORT BaseCloudsModel { + public: BaseCloudsModel(CloudLayerDefinition *layer); virtual ~BaseCloudsModel(); @@ -24,14 +23,16 @@ public: virtual double getProbability(const Vector3 &location, double radius) const; virtual double getDensity(const Vector3 &location) const; virtual Color filterLight(const Color &light, double length, double density) const; - virtual Color applyLightExit(const Color &light, const Vector3 &light_direction, const Vector3 &direction_to_eye) const; + virtual Color applyLightExit(const Color &light, const Vector3 &light_direction, + const Vector3 &direction_to_eye) const; - inline CloudLayerDefinition* getLayer() const {return layer;} + inline CloudLayerDefinition *getLayer() const { + return layer; + } -protected: + protected: CloudLayerDefinition *layer; }; - } } diff --git a/src/render/software/clouds/CloudModelAltoCumulus.cpp b/src/render/software/clouds/CloudModelAltoCumulus.cpp index 2e6b27f..692e586 100644 --- a/src/render/software/clouds/CloudModelAltoCumulus.cpp +++ b/src/render/software/clouds/CloudModelAltoCumulus.cpp @@ -4,19 +4,15 @@ #include "Vector3.h" #include "CloudLayerDefinition.h" -CloudModelAltoCumulus::CloudModelAltoCumulus(CloudLayerDefinition* layer): - BaseCloudsModel(layer) -{ +CloudModelAltoCumulus::CloudModelAltoCumulus(CloudLayerDefinition *layer) : BaseCloudsModel(layer) { noise = new NoiseGenerator(); } -CloudModelAltoCumulus::~CloudModelAltoCumulus() -{ +CloudModelAltoCumulus::~CloudModelAltoCumulus() { delete noise; } -void CloudModelAltoCumulus::update() -{ +void CloudModelAltoCumulus::update() { noise->clearLevels(); noise->addLevelSimple(4.0, -1.0, 1.0); noise->addLevelSimple(1.0 / 2.0, -0.6, 0.6); @@ -31,31 +27,27 @@ void CloudModelAltoCumulus::update() noise->setState(layer->getNoiseState()); } -void CloudModelAltoCumulus::getAltitudeRange(double *min_altitude, double *max_altitude) const -{ +void CloudModelAltoCumulus::getAltitudeRange(double *min_altitude, double *max_altitude) const { *min_altitude = 15.0 + 10.0 * layer->altitude; *max_altitude = *min_altitude + 18.0 * layer->scaling; } -double CloudModelAltoCumulus::getDensity(const Vector3 &location) const -{ +double CloudModelAltoCumulus::getDensity(const Vector3 &location) const { double val; double min_altitude, max_altitude; double noise_scaling = 18.0 * layer->scaling; getAltitudeRange(&min_altitude, &max_altitude); - if (location.y < min_altitude || location.y > max_altitude) - { + if (location.y < min_altitude || location.y > max_altitude) { return 0.0; - } - else - { + } else { double x = 0.6 * location.x / noise_scaling; double y = (location.y - min_altitude) / noise_scaling; double z = 0.6 * location.z / noise_scaling; - //double coverage = layer->coverage * layer->_coverage_by_altitude->getValue((position.y - layer->altitude) / layer->scaling); + // double coverage = layer->coverage * layer->_coverage_by_altitude->getValue((position.y - layer->altitude) / + // layer->scaling); double coverage = layer->coverage; val = 0.5 * noise->get3DTotal(x, y, z); diff --git a/src/render/software/clouds/CloudModelAltoCumulus.h b/src/render/software/clouds/CloudModelAltoCumulus.h index f14890a..4884ede 100644 --- a/src/render/software/clouds/CloudModelAltoCumulus.h +++ b/src/render/software/clouds/CloudModelAltoCumulus.h @@ -8,10 +8,9 @@ namespace paysages { namespace software { -class CloudModelAltoCumulus : public BaseCloudsModel -{ -public: - CloudModelAltoCumulus(CloudLayerDefinition* layer); +class CloudModelAltoCumulus : public BaseCloudsModel { + public: + CloudModelAltoCumulus(CloudLayerDefinition *layer); virtual ~CloudModelAltoCumulus(); virtual void update() override; @@ -19,10 +18,9 @@ public: virtual void getAltitudeRange(double *min_altitude, double *max_altitude) const override; virtual double getDensity(const Vector3 &location) const override; -private: - NoiseGenerator* noise; + private: + NoiseGenerator *noise; }; - } } diff --git a/src/render/software/clouds/CloudModelCirrus.cpp b/src/render/software/clouds/CloudModelCirrus.cpp index b6c8078..8040b7b 100644 --- a/src/render/software/clouds/CloudModelCirrus.cpp +++ b/src/render/software/clouds/CloudModelCirrus.cpp @@ -4,19 +4,15 @@ #include "Vector3.h" #include "CloudLayerDefinition.h" -CloudModelCirrus::CloudModelCirrus(CloudLayerDefinition* layer): - BaseCloudsModel(layer) -{ +CloudModelCirrus::CloudModelCirrus(CloudLayerDefinition *layer) : BaseCloudsModel(layer) { noise = new NoiseGenerator(); } -CloudModelCirrus::~CloudModelCirrus() -{ +CloudModelCirrus::~CloudModelCirrus() { delete noise; } -void CloudModelCirrus::update() -{ +void CloudModelCirrus::update() { noise->clearLevels(); noise->addLevelSimple(1.0, -1.0, 1.0); noise->addLevelSimple(1.0 / 6.0, -0.6, 0.6); @@ -29,31 +25,27 @@ void CloudModelCirrus::update() noise->setState(layer->getNoiseState()); } -void CloudModelCirrus::getAltitudeRange(double *min_altitude, double *max_altitude) const -{ +void CloudModelCirrus::getAltitudeRange(double *min_altitude, double *max_altitude) const { *min_altitude = 45.0 + 20.0 * layer->altitude; *max_altitude = *min_altitude + 20.0 * layer->scaling; } -double CloudModelCirrus::getDensity(const Vector3 &location) const -{ +double CloudModelCirrus::getDensity(const Vector3 &location) const { double val; double min_altitude, max_altitude; double noise_scaling = 30.0 * layer->scaling; getAltitudeRange(&min_altitude, &max_altitude); - if (location.y < min_altitude || location.y > max_altitude) - { + if (location.y < min_altitude || location.y > max_altitude) { return 0.0; - } - else - { + } else { double x = 0.03 * location.x / noise_scaling; double y = (location.y - min_altitude) / noise_scaling; double z = 0.03 * location.z / noise_scaling; - //double coverage = layer->coverage * layer->_coverage_by_altitude->getValue((position.y - layer->altitude) / layer->scaling); + // double coverage = layer->coverage * layer->_coverage_by_altitude->getValue((position.y - layer->altitude) / + // layer->scaling); double coverage = layer->coverage; val = 0.6 * noise->get3DTotal(x, y, z); diff --git a/src/render/software/clouds/CloudModelCirrus.h b/src/render/software/clouds/CloudModelCirrus.h index 5cdfcc4..6572d24 100644 --- a/src/render/software/clouds/CloudModelCirrus.h +++ b/src/render/software/clouds/CloudModelCirrus.h @@ -8,10 +8,9 @@ namespace paysages { namespace software { -class CloudModelCirrus : public BaseCloudsModel -{ -public: - CloudModelCirrus(CloudLayerDefinition* layer); +class CloudModelCirrus : public BaseCloudsModel { + public: + CloudModelCirrus(CloudLayerDefinition *layer); virtual ~CloudModelCirrus(); virtual void update() override; @@ -19,10 +18,9 @@ public: virtual void getAltitudeRange(double *min_altitude, double *max_altitude) const override; virtual double getDensity(const Vector3 &location) const override; -private: - NoiseGenerator* noise; + private: + NoiseGenerator *noise; }; - } } diff --git a/src/render/software/clouds/CloudModelCumuloNimbus.cpp b/src/render/software/clouds/CloudModelCumuloNimbus.cpp index 0a43489..af77379 100644 --- a/src/render/software/clouds/CloudModelCumuloNimbus.cpp +++ b/src/render/software/clouds/CloudModelCumuloNimbus.cpp @@ -4,19 +4,15 @@ #include "Vector3.h" #include "CloudLayerDefinition.h" -CloudModelCumuloNimbus::CloudModelCumuloNimbus(CloudLayerDefinition* layer): - BaseCloudsModel(layer) -{ +CloudModelCumuloNimbus::CloudModelCumuloNimbus(CloudLayerDefinition *layer) : BaseCloudsModel(layer) { noise = new NoiseGenerator(); } -CloudModelCumuloNimbus::~CloudModelCumuloNimbus() -{ +CloudModelCumuloNimbus::~CloudModelCumuloNimbus() { delete noise; } -void CloudModelCumuloNimbus::update() -{ +void CloudModelCumuloNimbus::update() { noise->clearLevels(); noise->addLevelSimple(8.0, -1.0, 1.0); noise->addLevelSimple(7.0 / 2.0, -0.6, 0.6); @@ -36,31 +32,27 @@ void CloudModelCumuloNimbus::update() noise->setState(layer->getNoiseState()); } -void CloudModelCumuloNimbus::getAltitudeRange(double *min_altitude, double *max_altitude) const -{ +void CloudModelCumuloNimbus::getAltitudeRange(double *min_altitude, double *max_altitude) const { *min_altitude = 5.0 + 10.0 * layer->altitude; *max_altitude = *min_altitude + 50.0 + 50.0 * layer->scaling; } -double CloudModelCumuloNimbus::getDensity(const Vector3 &location) const -{ +double CloudModelCumuloNimbus::getDensity(const Vector3 &location) const { double val; double min_altitude, max_altitude; double noise_scaling = 60.0 * layer->scaling; getAltitudeRange(&min_altitude, &max_altitude); - if (location.y < min_altitude || location.y > max_altitude) - { + if (location.y < min_altitude || location.y > max_altitude) { return 0.0; - } - else - { + } else { double x = 1.5 * location.x / noise_scaling; double y = (location.y - min_altitude) / noise_scaling; double z = 1.5 * location.z / noise_scaling; - //double coverage = layer->coverage * layer->_coverage_by_altitude->getValue((position.y - layer->altitude) / layer->scaling); + // double coverage = layer->coverage * layer->_coverage_by_altitude->getValue((position.y - layer->altitude) / + // layer->scaling); double coverage = layer->coverage; val = 0.5 * noise->get3DTotal(x, y, z); diff --git a/src/render/software/clouds/CloudModelCumuloNimbus.h b/src/render/software/clouds/CloudModelCumuloNimbus.h index 72d4f31..d2dd7f0 100644 --- a/src/render/software/clouds/CloudModelCumuloNimbus.h +++ b/src/render/software/clouds/CloudModelCumuloNimbus.h @@ -8,10 +8,9 @@ namespace paysages { namespace software { -class CloudModelCumuloNimbus : public BaseCloudsModel -{ -public: - CloudModelCumuloNimbus(CloudLayerDefinition* layer); +class CloudModelCumuloNimbus : public BaseCloudsModel { + public: + CloudModelCumuloNimbus(CloudLayerDefinition *layer); virtual ~CloudModelCumuloNimbus(); virtual void update() override; @@ -19,10 +18,9 @@ public: virtual void getAltitudeRange(double *min_altitude, double *max_altitude) const override; virtual double getDensity(const Vector3 &location) const override; -private: - NoiseGenerator* noise; + private: + NoiseGenerator *noise; }; - } } diff --git a/src/render/software/clouds/CloudModelStratoCumulus.cpp b/src/render/software/clouds/CloudModelStratoCumulus.cpp index d50a568..6664294 100644 --- a/src/render/software/clouds/CloudModelStratoCumulus.cpp +++ b/src/render/software/clouds/CloudModelStratoCumulus.cpp @@ -4,19 +4,15 @@ #include "Vector3.h" #include "CloudLayerDefinition.h" -CloudModelStratoCumulus::CloudModelStratoCumulus(CloudLayerDefinition* layer): - BaseCloudsModel(layer) -{ +CloudModelStratoCumulus::CloudModelStratoCumulus(CloudLayerDefinition *layer) : BaseCloudsModel(layer) { noise = new NoiseGenerator(); } -CloudModelStratoCumulus::~CloudModelStratoCumulus() -{ +CloudModelStratoCumulus::~CloudModelStratoCumulus() { delete noise; } -void CloudModelStratoCumulus::update() -{ +void CloudModelStratoCumulus::update() { noise->clearLevels(); noise->addLevelSimple(1.0, -1.0, 1.0); noise->addLevelSimple(1.0 / 2.0, -0.6, 0.6); @@ -36,31 +32,27 @@ void CloudModelStratoCumulus::update() noise->setState(layer->getNoiseState()); } -void CloudModelStratoCumulus::getAltitudeRange(double *min_altitude, double *max_altitude) const -{ +void CloudModelStratoCumulus::getAltitudeRange(double *min_altitude, double *max_altitude) const { *min_altitude = 10.0 + 10.0 * layer->altitude; *max_altitude = *min_altitude + 11.0 * layer->scaling; } -double CloudModelStratoCumulus::getDensity(const Vector3 &location) const -{ +double CloudModelStratoCumulus::getDensity(const Vector3 &location) const { double val; double min_altitude, max_altitude; double noise_scaling = 25.0 * layer->scaling; getAltitudeRange(&min_altitude, &max_altitude); - if (location.y < min_altitude || location.y > max_altitude) - { + if (location.y < min_altitude || location.y > max_altitude) { return 0.0; - } - else - { + } else { double x = 0.3 * location.x / noise_scaling; double y = (location.y - min_altitude) / noise_scaling; double z = 0.3 * location.z / noise_scaling; - //double coverage = layer->coverage * layer->_coverage_by_altitude->getValue((position.y - layer->altitude) / layer->scaling); + // double coverage = layer->coverage * layer->_coverage_by_altitude->getValue((position.y - layer->altitude) / + // layer->scaling); double coverage = layer->coverage; val = 0.5 * noise->get3DTotal(x, y, z); diff --git a/src/render/software/clouds/CloudModelStratoCumulus.h b/src/render/software/clouds/CloudModelStratoCumulus.h index 9bb039b..482d144 100644 --- a/src/render/software/clouds/CloudModelStratoCumulus.h +++ b/src/render/software/clouds/CloudModelStratoCumulus.h @@ -8,10 +8,9 @@ namespace paysages { namespace software { -class CloudModelStratoCumulus : public BaseCloudsModel -{ -public: - CloudModelStratoCumulus(CloudLayerDefinition* layer); +class CloudModelStratoCumulus : public BaseCloudsModel { + public: + CloudModelStratoCumulus(CloudLayerDefinition *layer); virtual ~CloudModelStratoCumulus(); virtual void update() override; @@ -19,10 +18,9 @@ public: virtual void getAltitudeRange(double *min_altitude, double *max_altitude) const override; virtual double getDensity(const Vector3 &location) const override; -private: - NoiseGenerator* noise; + private: + NoiseGenerator *noise; }; - } } diff --git a/src/render/software/software_global.h b/src/render/software/software_global.h index 25e9e68..b220dd4 100644 --- a/src/render/software/software_global.h +++ b/src/render/software/software_global.h @@ -4,65 +4,65 @@ #include #if defined(SOFTWARE_LIBRARY) -# define SOFTWARESHARED_EXPORT Q_DECL_EXPORT +#define SOFTWARESHARED_EXPORT Q_DECL_EXPORT #else -# define SOFTWARESHARED_EXPORT Q_DECL_IMPORT +#define SOFTWARESHARED_EXPORT Q_DECL_IMPORT #endif #include "definition_global.h" namespace paysages { namespace software { - class SoftwareRenderer; - class SoftwareCanvasRenderer; - class RenderConfig; - class RenderProgress; +class SoftwareRenderer; +class SoftwareCanvasRenderer; +class RenderConfig; +class RenderProgress; - class FluidMediumManager; - class FluidMediumInterface; - class FluidMediumCollector; +class FluidMediumManager; +class FluidMediumInterface; +class FluidMediumCollector; - class BaseAtmosphereRenderer; - class SoftwareBrunetonAtmosphereRenderer; - class AtmosphereResult; - class AtmosphereModelBruneton; +class BaseAtmosphereRenderer; +class SoftwareBrunetonAtmosphereRenderer; +class AtmosphereResult; +class AtmosphereModelBruneton; - class CloudsRenderer; - class BaseCloudLayerRenderer; - class BaseCloudsModel; +class CloudsRenderer; +class BaseCloudLayerRenderer; +class BaseCloudsModel; - class TerrainRenderer; - class TexturesRenderer; - class WaterRenderer; +class TerrainRenderer; +class TexturesRenderer; +class WaterRenderer; - class Rasterizer; - class SkyRasterizer; - class TerrainRasterizer; +class Rasterizer; +class SkyRasterizer; +class TerrainRasterizer; - class LightingManager; - class LightStatus; - class LightFilter; - class LightComponent; - class LightSource; +class LightingManager; +class LightStatus; +class LightFilter; +class LightComponent; +class LightSource; - class RayCastingManager; - class RayCastingResult; +class RayCastingManager; +class RayCastingResult; - class NightSky; +class NightSky; - class TerrainRayWalker; +class TerrainRayWalker; - class GodRaysSampler; - class GodRaysResult; +class GodRaysSampler; +class GodRaysResult; - class Canvas; - class CanvasPortion; - class CanvasPixel; - class CanvasFragment; - class CanvasLiveClient; - class CanvasPreview; - class CanvasPixelShader; - class CanvasPictureWriter; +class Canvas; +class CanvasPortion; +class CanvasPixel; +class CanvasFragment; +class CanvasLiveClient; +class CanvasPreview; +class CanvasPixelShader; +class CanvasPictureWriter; } } diff --git a/src/system/CacheFile.cpp b/src/system/CacheFile.cpp index aef984f..5762411 100644 --- a/src/system/CacheFile.cpp +++ b/src/system/CacheFile.cpp @@ -3,65 +3,56 @@ #include #include "DataFile.h" -CacheFile::CacheFile(const std::string &module, const std::string &ext, const std::string &tag1, int tag2, int tag3, int tag4, int tag5, int tag6) -{ - filepath = QString("cache/%1-%2-%3-%4-%5-%6-%7.%8").arg(QString::fromStdString(module)).arg(QString::fromStdString(tag1)).arg(tag2).arg(tag3).arg(tag4).arg(tag5).arg(tag6).arg(QString::fromStdString(ext)).toStdString(); +CacheFile::CacheFile(const std::string &module, const std::string &ext, const std::string &tag1, int tag2, int tag3, + int tag4, int tag5, int tag6) { + filepath = QString("cache/%1-%2-%3-%4-%5-%6-%7.%8") + .arg(QString::fromStdString(module)) + .arg(QString::fromStdString(tag1)) + .arg(tag2) + .arg(tag3) + .arg(tag4) + .arg(tag5) + .arg(tag6) + .arg(QString::fromStdString(ext)) + .toStdString(); } -bool CacheFile::isReadable() -{ - FILE* f = fopen(filepath.c_str(), "rb"); - if (f) - { +bool CacheFile::isReadable() { + FILE *f = fopen(filepath.c_str(), "rb"); + if (f) { fclose(f); return true; - } - else - { + } else { std::string datapath = DataFile::findFile(filepath); - if (datapath.empty()) - { + if (datapath.empty()) { return false; - } - else - { - FILE* f = fopen(datapath.c_str(), "rb"); - if (f) - { + } else { + FILE *f = fopen(datapath.c_str(), "rb"); + if (f) { fclose(f); return true; - } - else - { + } else { return false; } } } } -bool CacheFile::isWritable() -{ - FILE* f = fopen("cache/.test", "wb"); - if (f) - { +bool CacheFile::isWritable() { + FILE *f = fopen("cache/.test", "wb"); + if (f) { fclose(f); return true; - } - else - { + } else { return false; } } -std::string CacheFile::getPath() -{ +std::string CacheFile::getPath() { std::string datapath = DataFile::findFile(filepath); - if (datapath.empty()) - { + if (datapath.empty()) { return filepath; - } - else - { + } else { return datapath; } } diff --git a/src/system/CacheFile.h b/src/system/CacheFile.h index 4e5e9c1..b64d4b9 100644 --- a/src/system/CacheFile.h +++ b/src/system/CacheFile.h @@ -6,19 +6,18 @@ namespace paysages { namespace system { -class SYSTEMSHARED_EXPORT CacheFile -{ -public: - CacheFile(const std::string &module, const std::string &ext, const std::string &tag1, int tag2, int tag3, int tag4, int tag5, int tag6); +class SYSTEMSHARED_EXPORT CacheFile { + public: + CacheFile(const std::string &module, const std::string &ext, const std::string &tag1, int tag2, int tag3, int tag4, + int tag5, int tag6); bool isReadable(); bool isWritable(); std::string getPath(); -private: + private: std::string filepath; }; - } } diff --git a/src/system/DataFile.cpp b/src/system/DataFile.cpp index 36bf698..a73acf4 100644 --- a/src/system/DataFile.cpp +++ b/src/system/DataFile.cpp @@ -3,52 +3,41 @@ #include "Logs.h" #include -std::string DataFile::findFile(const std::string &relpath) -{ - if (dataDir.empty()) - { +std::string DataFile::findFile(const std::string &relpath) { + if (dataDir.empty()) { dataDir = initDataDir(); } QDir dir(QString::fromStdString(dataDir)); - if (dir.exists(QString::fromStdString(relpath))) - { + if (dir.exists(QString::fromStdString(relpath))) { return dir.absoluteFilePath(QString::fromStdString(relpath)).toStdString(); - } - else - { + } else { return ""; } } -std::string DataFile::findDir(const std::string &relpath) -{ +std::string DataFile::findDir(const std::string &relpath) { return findFile(relpath); } -bool DataFile::tryDataDir(const QDir &dir) -{ +bool DataFile::tryDataDir(const QDir &dir) { Logs::debug() << "[System] Try data dir " << dir.absolutePath().toStdString() << std::endl; return dir.exists("data/.paysages_data"); } -std::string DataFile::locateDataDir() -{ +std::string DataFile::locateDataDir() { QDir dir = QDir::current(); int i = 0; // TODO /usr/share/paysages3d/ - while (i++ < 100 and not dir.isRoot()) - { - if (tryDataDir(dir)) - { + while (i++ < 100 and not dir.isRoot()) { + if (tryDataDir(dir)) { return dir.absolutePath().toStdString(); } QDir dir2(dir.absoluteFilePath("paysages3d")); - if (tryDataDir(dir2)) - { + if (tryDataDir(dir2)) { return dir2.absolutePath().toStdString(); } @@ -58,16 +47,12 @@ std::string DataFile::locateDataDir() return ""; } -std::string DataFile::initDataDir() -{ +std::string DataFile::initDataDir() { std::string parent = locateDataDir(); - if (parent.empty()) - { + if (parent.empty()) { Logs::warning() << "[System] Data files not found" << std::endl; return parent; - } - else - { + } else { std::string result = QDir(QString::fromStdString(parent)).absoluteFilePath("data").toStdString(); Logs::debug() << "[System] Data files found : " << result << std::endl; return result; diff --git a/src/system/DataFile.h b/src/system/DataFile.h index f66e4e4..3048f4e 100644 --- a/src/system/DataFile.h +++ b/src/system/DataFile.h @@ -11,9 +11,8 @@ namespace system { /** * Locator of data files. */ -class SYSTEMSHARED_EXPORT DataFile -{ -public: +class SYSTEMSHARED_EXPORT DataFile { + public: /** * Find a data file. * @@ -28,13 +27,12 @@ public: */ static std::string findDir(const std::string &relpath); -private: + private: static bool tryDataDir(const QDir &dir); static std::string locateDataDir(); static std::string initDataDir(); static std::string dataDir; }; - } } diff --git a/src/system/FileSystem.cpp b/src/system/FileSystem.cpp index ae43dc2..11d31ec 100644 --- a/src/system/FileSystem.cpp +++ b/src/system/FileSystem.cpp @@ -3,12 +3,10 @@ #include #include -std::string FileSystem::getTempFile(const std::string &filename) -{ +std::string FileSystem::getTempFile(const std::string &filename) { return QDir::temp().filePath(QString::fromStdString(filename)).toStdString(); } -bool FileSystem::isFile(const std::string &filepath) -{ +bool FileSystem::isFile(const std::string &filepath) { return QFileInfo(QString::fromStdString(filepath)).exists(); } diff --git a/src/system/FileSystem.h b/src/system/FileSystem.h index f59e596..5e8963a 100644 --- a/src/system/FileSystem.h +++ b/src/system/FileSystem.h @@ -6,9 +6,8 @@ namespace paysages { namespace system { -class SYSTEMSHARED_EXPORT FileSystem -{ -public: +class SYSTEMSHARED_EXPORT FileSystem { + public: /** * Get an absolute path to a temporary file. * @@ -21,7 +20,6 @@ public: */ static bool isFile(const std::string &filepath); }; - } } diff --git a/src/system/Logs.cpp b/src/system/Logs.cpp index 1240230..ebab594 100644 --- a/src/system/Logs.cpp +++ b/src/system/Logs.cpp @@ -5,81 +5,62 @@ #include #include -template > -class basic_nullbuf: public std::basic_streambuf { - typename traits::int_type overflow(typename traits::int_type c) - { +template > class basic_nullbuf : public std::basic_streambuf { + typename traits::int_type overflow(typename traits::int_type c) { return traits::not_eof(c); // indicate success } }; -template > -class basic_onullstream: public std::basic_ostream { - public: - basic_onullstream(): - std::basic_ios(&m_sbuf), - std::basic_ostream(&m_sbuf) - { - this->init(&m_sbuf); - } +template > +class basic_onullstream : public std::basic_ostream { + public: + basic_onullstream() : std::basic_ios(&m_sbuf), std::basic_ostream(&m_sbuf) { + this->init(&m_sbuf); + } - private: - basic_nullbuf m_sbuf; + private: + basic_nullbuf m_sbuf; }; typedef basic_onullstream onullstream; static onullstream NULL_STREAM; static bool enabled = true; -std::ostream &Logs::debug() -{ +std::ostream &Logs::debug() { #ifdef NDEBUG return NULL_STREAM; #else - if (enabled) - { + if (enabled) { std::cout << "DEBUG - "; return std::cout; - } - else - { + } else { return NULL_STREAM; } #endif } -std::ostream &Logs::warning() -{ - if (enabled) - { +std::ostream &Logs::warning() { + if (enabled) { std::cerr << "WARN - "; return std::cerr; - } - else - { + } else { return NULL_STREAM; } } -std::ostream &Logs::error() -{ - if (enabled) - { +std::ostream &Logs::error() { + if (enabled) { std::cerr << "ERROR - "; return std::cerr; - } - else - { + } else { return NULL_STREAM; } } -void Logs::debugTimestamp(const std::string &message) -{ +void Logs::debugTimestamp(const std::string &message) { debug() << Time::getRelativeTimeMs() << " - " << message << std::endl; } -void Logs::disable() -{ +void Logs::disable() { enabled = false; } diff --git a/src/system/Logs.h b/src/system/Logs.h index bae7355..97c876c 100644 --- a/src/system/Logs.h +++ b/src/system/Logs.h @@ -11,9 +11,8 @@ namespace system { /** * Logger streams */ -class Logs -{ -public: +class Logs { + public: static std::ostream &debug(); static std::ostream &warning(); static std::ostream &error(); @@ -24,7 +23,6 @@ public: // Disable all logs from now on static void disable(); }; - } } diff --git a/src/system/Memory.cpp b/src/system/Memory.cpp index 7c48f12..7ad83bb 100644 --- a/src/system/Memory.cpp +++ b/src/system/Memory.cpp @@ -3,17 +3,16 @@ #include #include -void* Memory::naiveArrayInsert(void** array, unsigned long item_size, int item_count, int location) -{ - char** barray = (char**)array; +void *Memory::naiveArrayInsert(void **array, unsigned long item_size, int item_count, int location) { + char **barray = (char **)array; assert(location >= 0); assert(location <= item_count); - *barray = (char*)realloc(*barray, item_size * (item_count + 1)); - if (location < item_count) - { - memmove(*barray + item_size * (location + 1), *barray + item_size * location, item_size * (item_count - location)); + *barray = (char *)realloc(*barray, item_size * (item_count + 1)); + if (location < item_count) { + memmove(*barray + item_size * (location + 1), *barray + item_size * location, + item_size * (item_count - location)); } return *barray + item_size * location; diff --git a/src/system/Memory.h b/src/system/Memory.h index 3257c79..904bfcb 100644 --- a/src/system/Memory.h +++ b/src/system/Memory.h @@ -6,12 +6,10 @@ namespace paysages { namespace system { -class SYSTEMSHARED_EXPORT Memory -{ -public: - static void* naiveArrayInsert(void** array, unsigned long item_size, int item_count, int location); +class SYSTEMSHARED_EXPORT Memory { + public: + static void *naiveArrayInsert(void **array, unsigned long item_size, int item_count, int location); }; - } } diff --git a/src/system/Mutex.cpp b/src/system/Mutex.cpp index 0bd1914..53aa811 100644 --- a/src/system/Mutex.cpp +++ b/src/system/Mutex.cpp @@ -1,5 +1,4 @@ #include "Mutex.h" -Mutex::Mutex() -{ +Mutex::Mutex() { } diff --git a/src/system/Mutex.h b/src/system/Mutex.h index bb2c886..2429b12 100644 --- a/src/system/Mutex.h +++ b/src/system/Mutex.h @@ -4,26 +4,26 @@ #include "system_global.h" #include -namespace paysages -{ -namespace system -{ +namespace paysages { +namespace system { /*! * \brief System mutex */ -class SYSTEMSHARED_EXPORT Mutex: private QMutex -{ -public: +class SYSTEMSHARED_EXPORT Mutex : private QMutex { + public: /*! * \brief Create a new mutex */ Mutex(); - inline void acquire() {QMutex::lock();} - inline void release() {QMutex::unlock();} + inline void acquire() { + QMutex::lock(); + } + inline void release() { + QMutex::unlock(); + } }; - } } diff --git a/src/system/PackStream.cpp b/src/system/PackStream.cpp index f3c827a..0e90ef4 100644 --- a/src/system/PackStream.cpp +++ b/src/system/PackStream.cpp @@ -5,109 +5,84 @@ #include #include -PackStream::PackStream() -{ +PackStream::PackStream() { file = NULL; buffer = new QByteArray(); stream = new QDataStream(buffer, QIODevice::WriteOnly); stream->setVersion(QDataStream::Qt_5_2); } -PackStream::~PackStream() -{ +PackStream::~PackStream() { delete buffer; delete stream; - if (file) - { + if (file) { delete file; } } -PackStream::PackStream(const PackStream *other) -{ +PackStream::PackStream(const PackStream *other) { file = NULL; buffer = new QByteArray(); - if (other->file) - { - Logs::error() << "Try to read from a substream bound to a file: " << other->file->fileName().toStdString() << std::endl; + if (other->file) { + Logs::error() << "Try to read from a substream bound to a file: " << other->file->fileName().toStdString() + << std::endl; stream = new QDataStream(buffer, QIODevice::ReadOnly); - } - else - { + } else { stream = new QDataStream(other->buffer, QIODevice::ReadOnly); } stream->setVersion(QDataStream::Qt_5_2); } -bool PackStream::bindToFile(const std::string &filepath, bool write) -{ - if (not file) - { +bool PackStream::bindToFile(const std::string &filepath, bool write) { + if (not file) { file = new QFile(QString::fromStdString(filepath)); - if (not file->open(write ? QIODevice::WriteOnly : QIODevice::ReadOnly)) - { + if (not file->open(write ? QIODevice::WriteOnly : QIODevice::ReadOnly)) { return false; } QDataStream *new_stream = new QDataStream(file); - if (new_stream) - { + if (new_stream) { delete stream; stream = new_stream; stream->setVersion(QDataStream::Qt_5_2); return true; - } - else - { + } else { return false; } - } - else - { + } else { return false; } } -void PackStream::write(const int *value) -{ - if (value) - { +void PackStream::write(const int *value) { + if (value) { *stream << *value; } } -void PackStream::write(const double *value) -{ - if (value) - { +void PackStream::write(const double *value) { + if (value) { *stream << *value; } } -void PackStream::write(const char *value, int max_length) -{ - if (value) - { +void PackStream::write(const char *value, int max_length) { + if (value) { int length = qstrlen(value); *stream << QString::fromUtf8(value, length > max_length ? max_length : length); } } -void PackStream::write(const std::string &value) -{ +void PackStream::write(const std::string &value) { *stream << QString::fromStdString(value); } -void PackStream::writeFromBuffer(const PackStream &other, bool prepend_size) -{ - if (other.file) - { - Logs::error() << "Try to write from a substream bound to a file: " << other.file->fileName().toStdString() << std::endl; - } - else - { - if (prepend_size) - { +void PackStream::writeFromBuffer(const PackStream &other, bool prepend_size) { + if (other.file) { + Logs::error() << "Try to write from a substream bound to a file: " << other.file->fileName().toStdString() + << std::endl; + } else { + if (prepend_size) { int buffer_size = (int)other.buffer->size(); write(&buffer_size); } @@ -115,30 +90,24 @@ void PackStream::writeFromBuffer(const PackStream &other, bool prepend_size) } } -void PackStream::read(int* value) -{ - if (value and not stream->atEnd()) - { +void PackStream::read(int *value) { + if (value and not stream->atEnd()) { int output; *stream >> output; *value = output; } } -void PackStream::read(double* value) -{ - if (value and not stream->atEnd()) - { +void PackStream::read(double *value) { + if (value and not stream->atEnd()) { double output; *stream >> output; *value = output; } } -void PackStream::read(char* value, int max_length) -{ - if (value and not stream->atEnd()) - { +void PackStream::read(char *value, int max_length) { + if (value and not stream->atEnd()) { QString output; *stream >> output; QByteArray array = output.toUtf8(); @@ -146,31 +115,24 @@ void PackStream::read(char* value, int max_length) } } -std::string PackStream::readString() -{ - if (not stream->atEnd()) - { +std::string PackStream::readString() { + if (not stream->atEnd()) { QString output; *stream >> output; return output.toStdString(); - } - else - { + } else { return ""; } } -void PackStream::skip(const int &value, int count) -{ +void PackStream::skip(const int &value, int count) { stream->skipRawData(sizeof(value) * count); } -void PackStream::skip(const double &value, int count) -{ +void PackStream::skip(const double &value, int count) { stream->skipRawData(sizeof(value) * count); } -void paysages::system::PackStream::skipBytes(int bytes) -{ +void paysages::system::PackStream::skipBytes(int bytes) { stream->skipRawData(bytes); } diff --git a/src/system/PackStream.h b/src/system/PackStream.h index 8d6194b..45e2bf7 100644 --- a/src/system/PackStream.h +++ b/src/system/PackStream.h @@ -6,17 +6,14 @@ class QFile; class QDataStream; -namespace paysages -{ -namespace system -{ +namespace paysages { +namespace system { /*! * \brief Data (de)serialization in files or streams. */ -class SYSTEMSHARED_EXPORT PackStream -{ -public: +class SYSTEMSHARED_EXPORT PackStream { + public: PackStream(); ~PackStream(); @@ -27,7 +24,7 @@ public: */ PackStream(const PackStream *other); - bool bindToFile(const std::string &filepath, bool write=false); + bool bindToFile(const std::string &filepath, bool write = false); void write(const int *value); void write(const double *value); @@ -48,16 +45,15 @@ public: void read(char *value, int max_length); std::string readString(); - void skip(const int &value, int count=1); - void skip(const double &value, int count=1); + void skip(const int &value, int count = 1); + void skip(const double &value, int count = 1); void skipBytes(int bytes); -private: + private: QFile *file; QByteArray *buffer; QDataStream *stream; }; - } } diff --git a/src/system/ParallelPool.cpp b/src/system/ParallelPool.cpp index 941868e..b4e5039 100644 --- a/src/system/ParallelPool.cpp +++ b/src/system/ParallelPool.cpp @@ -3,53 +3,43 @@ #include "System.h" #include "Thread.h" -static void* _threadFunction(void* data) -{ - ParallelPool* pool = (ParallelPool*)data; +static void *_threadFunction(void *data) { + ParallelPool *pool = (ParallelPool *)data; pool->work(); return NULL; } -ParallelPool::ParallelPool() -{ +ParallelPool::ParallelPool() { running = false; } -ParallelPool::~ParallelPool() -{ - if (running) - { +ParallelPool::~ParallelPool() { + if (running) { interrupt(); } - for (auto thread : threads) - { + for (auto thread : threads) { thread->join(); delete thread; } threads.clear(); } -void ParallelPool::start(int thread_count) -{ - if (running) - { +void ParallelPool::start(int thread_count) { + if (running) { qCritical("Starting an already started parallel pool !"); return; } running = true; - if (thread_count < 0) - { + if (thread_count < 0) { thread_count = System::getCoreCount(); } - for (int i = 0; i < thread_count; i++) - { - Thread* thread = new Thread(_threadFunction); + for (int i = 0; i < thread_count; i++) { + Thread *thread = new Thread(_threadFunction); thread->start(this); threads.push_back(thread); } } -void ParallelPool::interrupt() -{ +void ParallelPool::interrupt() { running = false; } diff --git a/src/system/ParallelPool.h b/src/system/ParallelPool.h index d36832e..78ad253 100644 --- a/src/system/ParallelPool.h +++ b/src/system/ParallelPool.h @@ -9,16 +9,15 @@ namespace system { /*! * Pool to handle a group of threads doing the same task. */ -class SYSTEMSHARED_EXPORT ParallelPool -{ -public: +class SYSTEMSHARED_EXPORT ParallelPool { + public: ParallelPool(); virtual ~ParallelPool(); /*! * Start the effective work. */ - void start(int thread_count=-1); + void start(int thread_count = -1); /*! * Method called from each thread to do actual work. @@ -30,13 +29,12 @@ public: */ virtual void interrupt(); -protected: + protected: bool running; -private: - std::vector threads; + private: + std::vector threads; }; - } } diff --git a/src/system/ParallelWork.cpp b/src/system/ParallelWork.cpp index fd6338a..bdd7483 100644 --- a/src/system/ParallelWork.cpp +++ b/src/system/ParallelWork.cpp @@ -10,61 +10,50 @@ /** * Compatibility class for code that uses ParallelUnitFunction. */ -class ParallelWorkerCompat:public ParallelWorker -{ -public: - ParallelWorkerCompat(ParallelWork *work, ParallelWork::ParallelUnitFunction func, void* data): - ParallelWorker(), work(work), func(func), data(data) - { +class ParallelWorkerCompat : public ParallelWorker { + public: + ParallelWorkerCompat(ParallelWork *work, ParallelWork::ParallelUnitFunction func, void *data) + : ParallelWorker(), work(work), func(func), data(data) { } - virtual void processParallelUnit(int unit) - { + virtual void processParallelUnit(int unit) { func(work, unit, data); } -private: - ParallelWork* work; + private: + ParallelWork *work; ParallelWork::ParallelUnitFunction func; - void* data; + void *data; }; /** * Thread sub-class to perform units of work */ -class ParallelWork::ParallelThread:public Thread -{ -public: - ParallelThread(ParallelWork *work): - Thread(), work(work), sem(0) - { +class ParallelWork::ParallelThread : public Thread { + public: + ParallelThread(ParallelWork *work) : Thread(), work(work), sem(0) { interrupted = false; unit = -1; } - void feedUnit(int unit) - { + void feedUnit(int unit) { this->unit = unit; sem.release(); } - void interrupt() - { + void interrupt() { interrupted = true; sem.release(); } -protected: - virtual void run() override - { - while (unit >= 0 or not interrupted) - { + protected: + virtual void run() override { + while (unit >= 0 or not interrupted) { // Wait for a unit (or interrupt) sem.acquire(); // Process the unit - if (unit >= 0) - { + if (unit >= 0) { work->worker->processParallelUnit(unit); unit = -1; work->returnThread(this); @@ -72,50 +61,43 @@ protected: } } -private: - ParallelWork* work; + private: + ParallelWork *work; Semaphore sem; int unit; bool interrupted; }; -ParallelWork::ParallelWork(ParallelWorker *worker, int units) -{ +ParallelWork::ParallelWork(ParallelWorker *worker, int units) { this->units = units; this->running = 0; this->worker = worker; this->worker_compat = false; } -ParallelWork::ParallelWork(ParallelUnitFunction func, int units, void* data) -{ +ParallelWork::ParallelWork(ParallelUnitFunction func, int units, void *data) { this->units = units; this->running = 0; this->worker = new ParallelWorkerCompat(this, func, data); this->worker_compat = true; } -ParallelWork::~ParallelWork() -{ +ParallelWork::~ParallelWork() { assert(not running); - if (worker_compat) - { + if (worker_compat) { delete worker; } } -int ParallelWork::perform(int thread_count) -{ +int ParallelWork::perform(int thread_count) { int i, done; assert(not running); // Get thread count - if (thread_count <= 0) - { + if (thread_count <= 0) { thread_count = System::getCoreCount(); } - if (thread_count > PARALLEL_MAX_THREADS) - { + if (thread_count > PARALLEL_MAX_THREADS) { thread_count = PARALLEL_MAX_THREADS; } this->thread_count = thread_count; @@ -124,26 +106,23 @@ int ParallelWork::perform(int thread_count) // Init threads semaphore = new Semaphore(thread_count); mutex = new Mutex(); - threads = new ParallelThread*[thread_count]; - available = new ParallelThread*[thread_count]; + threads = new ParallelThread *[thread_count]; + available = new ParallelThread *[thread_count]; available_offset = 0; available_length = thread_count; - for (i = 0; i < thread_count; i++) - { + for (i = 0; i < thread_count; i++) { threads[i] = available[i] = new ParallelThread(this); threads[i]->start(); } // Perform all units - for (done = 0; done < units; done++) - { + for (done = 0; done < units; done++) { // Take first available thread semaphore->acquire(); mutex->acquire(); ParallelThread *thread = available[available_offset]; available_offset++; - if (available_offset >= thread_count) - { + if (available_offset >= thread_count) { available_offset = 0; } available_length--; @@ -154,12 +133,10 @@ int ParallelWork::perform(int thread_count) } // Wait for all threads to end, then cleanup - for (i = 0; i < thread_count; i++) - { + for (i = 0; i < thread_count; i++) { threads[i]->interrupt(); } - for (i = 0; i < thread_count; i++) - { + for (i = 0; i < thread_count; i++) { threads[i]->join(); delete threads[i]; } @@ -172,13 +149,11 @@ int ParallelWork::perform(int thread_count) return done; } -void ParallelWork::interrupt() -{ +void ParallelWork::interrupt() { worker->interrupt(); } -void ParallelWork::returnThread(ParallelWork::ParallelThread *thread) -{ +void ParallelWork::returnThread(ParallelWork::ParallelThread *thread) { mutex->acquire(); available[(available_offset + available_length) % thread_count] = thread; available_length++; diff --git a/src/system/ParallelWork.h b/src/system/ParallelWork.h index f1b6133..9c858a6 100644 --- a/src/system/ParallelWork.h +++ b/src/system/ParallelWork.h @@ -8,10 +8,9 @@ namespace paysages { namespace system { -class SYSTEMSHARED_EXPORT ParallelWork -{ -public: - typedef int (*ParallelUnitFunction)(ParallelWork* work, int unit, void* data); +class SYSTEMSHARED_EXPORT ParallelWork { + public: + typedef int (*ParallelUnitFunction)(ParallelWork *work, int unit, void *data); /** * Obscure thread class. @@ -19,7 +18,7 @@ public: class ParallelThread; friend class ParallelThread; -public: + public: /** * Create a parallel work handler. * @@ -32,7 +31,7 @@ public: * * This is a compatibility constructor for older code, use the constructor with ParallelWorker instead. */ - ParallelWork(ParallelUnitFunction func, int units, void* data); + ParallelWork(ParallelUnitFunction func, int units, void *data); /** * Delete a parallel work handler. @@ -46,7 +45,7 @@ public: * * @param threads Number of threads to spaws, -1 for an optimal number. */ - int perform(int thread_count=-1); + int perform(int thread_count = -1); /** * Tell the threads to interrupt what they are doing. @@ -55,24 +54,23 @@ public: */ void interrupt(); -private: + private: void returnThread(ParallelThread *thread); -private: + private: int units; int running; ParallelWorker *worker; bool worker_compat; int thread_count; - Mutex* mutex; - Semaphore* semaphore; - ParallelThread** threads; - ParallelThread** available; + Mutex *mutex; + Semaphore *semaphore; + ParallelThread **threads; + ParallelThread **available; int available_offset; int available_length; }; - } } diff --git a/src/system/ParallelWorker.cpp b/src/system/ParallelWorker.cpp index d08dc7b..60170ed 100644 --- a/src/system/ParallelWorker.cpp +++ b/src/system/ParallelWorker.cpp @@ -1,15 +1,12 @@ #include "ParallelWorker.h" -ParallelWorker::ParallelWorker() -{ +ParallelWorker::ParallelWorker() { interrupted = false; } -ParallelWorker::~ParallelWorker() -{ +ParallelWorker::~ParallelWorker() { } -void ParallelWorker::interrupt() -{ +void ParallelWorker::interrupt() { interrupted = true; } diff --git a/src/system/ParallelWorker.h b/src/system/ParallelWorker.h index 1d6d8b4..5f2bfe0 100644 --- a/src/system/ParallelWorker.h +++ b/src/system/ParallelWorker.h @@ -9,9 +9,8 @@ namespace system { /** * @brief Worker that can be used by the ParallelWork object to perform tasks in several threads. */ -class SYSTEMSHARED_EXPORT ParallelWorker -{ -public: +class SYSTEMSHARED_EXPORT ParallelWorker { + public: ParallelWorker(); virtual ~ParallelWorker(); @@ -27,10 +26,9 @@ public: */ virtual void interrupt(); -protected: + protected: bool interrupted; }; - } } diff --git a/src/system/PictureWriter.cpp b/src/system/PictureWriter.cpp index 5f5c229..ec06e78 100644 --- a/src/system/PictureWriter.cpp +++ b/src/system/PictureWriter.cpp @@ -2,14 +2,11 @@ #include -bool PictureWriter::save(const std::string &filepath, int width, int height) -{ +bool PictureWriter::save(const std::string &filepath, int width, int height) { QImage result(width, height, QImage::Format_ARGB32); - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { result.setPixel(x, height - 1 - y, getPixel(x, y)); } } diff --git a/src/system/PictureWriter.h b/src/system/PictureWriter.h index b4affa4..372b9f7 100644 --- a/src/system/PictureWriter.h +++ b/src/system/PictureWriter.h @@ -6,21 +6,19 @@ namespace paysages { namespace system { -class SYSTEMSHARED_EXPORT PictureWriter -{ -public: +class SYSTEMSHARED_EXPORT PictureWriter { + public: /** * @brief Start saving the picture in a file. */ bool save(const std::string &filepath, int width, int height); -protected: + protected: /** * @brief Get the (x, y) pixel, in BGRA format */ virtual unsigned int getPixel(int x, int y) = 0; }; - } } diff --git a/src/system/RandomGenerator.h b/src/system/RandomGenerator.h index 54007c6..ffe9b01 100644 --- a/src/system/RandomGenerator.h +++ b/src/system/RandomGenerator.h @@ -8,17 +8,14 @@ namespace paysages { namespace system { -class SYSTEMSHARED_EXPORT RandomGenerator -{ -public: +class SYSTEMSHARED_EXPORT RandomGenerator { + public: RandomGenerator(); - static inline double random() - { + static inline double random() { return ((double)rand()) / (double)RAND_MAX; } }; - } } diff --git a/src/system/Semaphore.cpp b/src/system/Semaphore.cpp index 65ca0c7..342933f 100644 --- a/src/system/Semaphore.cpp +++ b/src/system/Semaphore.cpp @@ -1,6 +1,4 @@ #include "Semaphore.h" -Semaphore::Semaphore(int resources): - QSemaphore(resources) -{ +Semaphore::Semaphore(int resources) : QSemaphore(resources) { } diff --git a/src/system/Semaphore.h b/src/system/Semaphore.h index 659cee2..41771b2 100644 --- a/src/system/Semaphore.h +++ b/src/system/Semaphore.h @@ -5,20 +5,20 @@ #include -namespace paysages -{ -namespace system -{ +namespace paysages { +namespace system { -class Semaphore: private QSemaphore -{ -public: +class Semaphore : private QSemaphore { + public: Semaphore(int resources); - inline void acquire() {QSemaphore::acquire();} - inline void release() {QSemaphore::release();} + inline void acquire() { + QSemaphore::acquire(); + } + inline void release() { + QSemaphore::release(); + } }; - } } diff --git a/src/system/System.cpp b/src/system/System.cpp index 1872bef..3eb559e 100644 --- a/src/system/System.cpp +++ b/src/system/System.cpp @@ -4,14 +4,11 @@ static int core_count = -1; -int System::getCoreCount() -{ - if (core_count < 0) - { +int System::getCoreCount() { + if (core_count < 0) { #ifdef NDEBUG core_count = QThread::idealThreadCount(); - if (core_count <= 0) - { + if (core_count <= 0) { qWarning("Can't find number of CPU cores, using only 1"); core_count = 1; } diff --git a/src/system/System.h b/src/system/System.h index 490ce0c..9c5d4d6 100644 --- a/src/system/System.h +++ b/src/system/System.h @@ -3,20 +3,16 @@ #include "system_global.h" -namespace paysages -{ -namespace system -{ +namespace paysages { +namespace system { /*! * \brief Access to system info */ -class SYSTEMSHARED_EXPORT System -{ -public: +class SYSTEMSHARED_EXPORT System { + public: static int getCoreCount(); }; - } } diff --git a/src/system/Thread.cpp b/src/system/Thread.cpp index fa549ea..ab9a7aa 100644 --- a/src/system/Thread.cpp +++ b/src/system/Thread.cpp @@ -1,23 +1,18 @@ #include "Thread.h" -Thread::Thread(ThreadFunction function): - data(0), result(0), function(function) -{ +Thread::Thread(ThreadFunction function) : data(0), result(0), function(function) { } -void Thread::start(void* data) -{ +void Thread::start(void *data) { this->data = data; QThread::start(); } -void* Thread::join() -{ +void *Thread::join() { QThread::wait(); return result; } -void Thread::run() -{ +void Thread::run() { result = function(data); } diff --git a/src/system/Thread.h b/src/system/Thread.h index 3adbdb0..61f9b9a 100644 --- a/src/system/Thread.h +++ b/src/system/Thread.h @@ -4,19 +4,16 @@ #include "system_global.h" #include -namespace paysages -{ -namespace system -{ +namespace paysages { +namespace system { -typedef void* (*ThreadFunction)(void* data); +typedef void *(*ThreadFunction)(void *data); /** * System thread */ -class SYSTEMSHARED_EXPORT Thread: private QThread -{ -public: +class SYSTEMSHARED_EXPORT Thread : private QThread { + public: /** * Create a new thread. * @@ -25,40 +22,43 @@ public: * Either the *function* argument should be provided (with the function to call from the * thread), or the *run* method overridden. */ - Thread(ThreadFunction function=0); + Thread(ThreadFunction function = 0); /** * Start the thread, with custom data. */ - void start(void* data=0); + void start(void *data = 0); /** * Wait for the thread to end, and collect its result. * * Returns the value returned by the threaded function. */ - void* join(); + void *join(); /** * Return true if the thread is currently running. */ - inline bool isWorking() const {return not isFinished();} + inline bool isWorking() const { + return not isFinished(); + } - static inline void timeSleepMs(unsigned long ms){ QThread::msleep(ms); } + static inline void timeSleepMs(unsigned long ms) { + QThread::msleep(ms); + } -protected: + protected: /** * Function to reimplement if no ThreadFunction has been passed to the constructor. */ virtual void run(); - void* data; - void* result; + void *data; + void *result; -private: + private: ThreadFunction function; }; - } } diff --git a/src/system/Time.cpp b/src/system/Time.cpp index d4315e5..3ff0aa0 100644 --- a/src/system/Time.cpp +++ b/src/system/Time.cpp @@ -4,8 +4,6 @@ static QTime EPOCH = QTime::currentTime(); -unsigned long Time::getRelativeTimeMs() -{ +unsigned long Time::getRelativeTimeMs() { return EPOCH.msecsTo(QTime::currentTime()); } - diff --git a/src/system/Time.h b/src/system/Time.h index 42c06c5..a385b71 100644 --- a/src/system/Time.h +++ b/src/system/Time.h @@ -6,15 +6,13 @@ namespace paysages { namespace system { -class SYSTEMSHARED_EXPORT Time -{ -public: +class SYSTEMSHARED_EXPORT Time { + public: /** * Get a timestamp in milliseconds. */ static unsigned long getRelativeTimeMs(); }; - } } diff --git a/src/system/system_global.h b/src/system/system_global.h index de9142b..5e79530 100644 --- a/src/system/system_global.h +++ b/src/system/system_global.h @@ -7,23 +7,23 @@ #include #if defined(SYSTEM_LIBRARY) -# define SYSTEMSHARED_EXPORT Q_DECL_EXPORT +#define SYSTEMSHARED_EXPORT Q_DECL_EXPORT #else -# define SYSTEMSHARED_EXPORT Q_DECL_IMPORT +#define SYSTEMSHARED_EXPORT Q_DECL_IMPORT #endif namespace paysages { namespace system { - class Logs; - class PackStream; - class ParallelWork; - class ParallelPool; - class ParallelWorker; - class Thread; - class Mutex; - class Semaphore; - class PictureWriter; - class Time; +class Logs; +class PackStream; +class ParallelWork; +class ParallelPool; +class ParallelWorker; +class Thread; +class Mutex; +class Semaphore; +class PictureWriter; +class Time; } } using namespace paysages::system; diff --git a/src/tests/AtmosphereDefinition_Test.cpp b/src/tests/AtmosphereDefinition_Test.cpp index a8f921a..5d57f4e 100644 --- a/src/tests/AtmosphereDefinition_Test.cpp +++ b/src/tests/AtmosphereDefinition_Test.cpp @@ -2,8 +2,8 @@ #include "AtmosphereDefinition.h" -static void check_daytime(const AtmosphereDefinition &atmo, int expected_hour, int expected_minute=0, int expected_second=0) -{ +static void check_daytime(const AtmosphereDefinition &atmo, int expected_hour, int expected_minute = 0, + int expected_second = 0) { int hour, minute, second; atmo.getHMS(&hour, &minute, &second); EXPECT_EQ(expected_hour, hour); @@ -11,8 +11,7 @@ static void check_daytime(const AtmosphereDefinition &atmo, int expected_hour, i EXPECT_EQ(expected_second, second); } -TEST(AtmosphereDefinition, setDayTime) -{ +TEST(AtmosphereDefinition, setDayTime) { AtmosphereDefinition atmo(NULL); atmo.setDayTime(0.0); diff --git a/src/tests/BaseTestCase.h b/src/tests/BaseTestCase.h index 093c60f..4011c18 100644 --- a/src/tests/BaseTestCase.h +++ b/src/tests/BaseTestCase.h @@ -4,29 +4,37 @@ #include "gtest/gtest.h" #undef EXPECT_DOUBLE_EQ -#define EXPECT_DOUBLE_EQ(_expected_, _value_) \ - EXPECT_NEAR(_expected_, _value_, 0.0000000001) +#define EXPECT_DOUBLE_EQ(_expected_, _value_) EXPECT_NEAR(_expected_, _value_, 0.0000000001) #undef ASSERT_DOUBLE_EQ -#define ASSERT_DOUBLE_EQ(_expected_, _value_) \ - ASSERT_NEAR(_expected_, _value_, 0.0000000001) +#define ASSERT_DOUBLE_EQ(_expected_, _value_) ASSERT_NEAR(_expected_, _value_, 0.0000000001) -#define EXPECT_DOUBLE_IN_RANGE(_value_, _min_, _max_) \ - EXPECT_GT(_value_, _min_); EXPECT_LT(_value_, _max_) -#define ASSERT_DOUBLE_IN_RANGE(_value_, _min_, _max_) \ - ASSERT_GT(_value_, _min_); ASSERT_LT(_value_, _max_) +#define EXPECT_DOUBLE_IN_RANGE(_value_, _min_, _max_) \ + EXPECT_GT(_value_, _min_); \ + EXPECT_LT(_value_, _max_) +#define ASSERT_DOUBLE_IN_RANGE(_value_, _min_, _max_) \ + ASSERT_GT(_value_, _min_); \ + ASSERT_LT(_value_, _max_) -#define EXPECT_COLOR_RGBA(_col_, _r_, _g_, _b_, _a_) \ - EXPECT_DOUBLE_EQ(_col_.r, _r_); EXPECT_DOUBLE_EQ(_col_.g, _g_); EXPECT_DOUBLE_EQ(_col_.b, _b_); EXPECT_DOUBLE_EQ(_col_.a, _a_) -#define ASSERT_COLOR_RGBA(_col_, _r_, _g_, _b_, _a_) \ - EXPECT_DOUBLE_EQ(_col_.r, _r_); EXPECT_DOUBLE_EQ(_col_.g, _g_); EXPECT_DOUBLE_EQ(_col_.b, _b_); EXPECT_DOUBLE_EQ(_col_.a, _a_) +#define EXPECT_COLOR_RGBA(_col_, _r_, _g_, _b_, _a_) \ + EXPECT_DOUBLE_EQ(_col_.r, _r_); \ + EXPECT_DOUBLE_EQ(_col_.g, _g_); \ + EXPECT_DOUBLE_EQ(_col_.b, _b_); \ + EXPECT_DOUBLE_EQ(_col_.a, _a_) +#define ASSERT_COLOR_RGBA(_col_, _r_, _g_, _b_, _a_) \ + EXPECT_DOUBLE_EQ(_col_.r, _r_); \ + EXPECT_DOUBLE_EQ(_col_.g, _g_); \ + EXPECT_DOUBLE_EQ(_col_.b, _b_); \ + EXPECT_DOUBLE_EQ(_col_.a, _a_) -#define EXPECT_VECTOR3_COORDS(_vec_, _x_, _y_, _z_) \ - EXPECT_DOUBLE_EQ(_vec_.x, _x_); EXPECT_DOUBLE_EQ(_vec_.y, _y_); EXPECT_DOUBLE_EQ(_vec_.z, _z_) -#define ASSERT_VECTOR3_COORDS(_vec_, _x_, _y_, _z_) \ - ASSERT_DOUBLE_EQ(_vec_.x, _x_); ASSERT_DOUBLE_EQ(_vec_.y, _y_); ASSERT_DOUBLE_EQ(_vec_.z, _z_) +#define EXPECT_VECTOR3_COORDS(_vec_, _x_, _y_, _z_) \ + EXPECT_DOUBLE_EQ(_vec_.x, _x_); \ + EXPECT_DOUBLE_EQ(_vec_.y, _y_); \ + EXPECT_DOUBLE_EQ(_vec_.z, _z_) +#define ASSERT_VECTOR3_COORDS(_vec_, _x_, _y_, _z_) \ + ASSERT_DOUBLE_EQ(_vec_.x, _x_); \ + ASSERT_DOUBLE_EQ(_vec_.y, _y_); \ + ASSERT_DOUBLE_EQ(_vec_.z, _z_) -class BaseTestCase: public ::testing::Test -{ -}; +class BaseTestCase : public ::testing::Test {}; #endif // BASETESTCASE_H diff --git a/src/tests/Camera_Test.cpp b/src/tests/Camera_Test.cpp index 3f93aed..43fab26 100644 --- a/src/tests/Camera_Test.cpp +++ b/src/tests/Camera_Test.cpp @@ -2,8 +2,7 @@ #include "CameraDefinition.h" -TEST(Camera, Definition) -{ +TEST(Camera, Definition) { CameraDefinition cam; cam.setLocationCoords(0.0, 1.0, 1.0); @@ -13,8 +12,7 @@ TEST(Camera, Definition) EXPECT_VECTOR3_COORDS(cam.getTarget(), 0.0, 0.0, 0.0); } -TEST(Camera, Projection) -{ +TEST(Camera, Projection) { CameraDefinition cam; cam.setLocationCoords(0.0, 1.0, 1.0); @@ -29,8 +27,7 @@ TEST(Camera, Projection) EXPECT_VECTOR3_COORDS(point, -25.1, 8.3, 1.3); } -TEST(Camera, Depth) -{ +TEST(Camera, Depth) { CameraDefinition cam; cam.setLocationCoords(0.0, 0.0, 0.0); diff --git a/src/tests/CanvasPixel_Test.cpp b/src/tests/CanvasPixel_Test.cpp index db2e265..733b785 100644 --- a/src/tests/CanvasPixel_Test.cpp +++ b/src/tests/CanvasPixel_Test.cpp @@ -2,16 +2,14 @@ #include "CanvasPixel.h" -TEST(CanvasPixel, MaxFragments) -{ +TEST(CanvasPixel, MaxFragments) { CanvasPixel pixel; // One opaque fragment pixel.pushFragment(CanvasFragment(true, Vector3(0.0, 0.0, 0.0), Vector3(), 0, true)); // Overflow max fragment count with transparent fragments - for (int i = 0; i < MAX_FRAGMENTS_PER_PIXEL * 2; i++) - { + for (int i = 0; i < MAX_FRAGMENTS_PER_PIXEL * 2; i++) { pixel.pushFragment(CanvasFragment(true, Vector3(0.0, 0.0, (double)i), Vector3(), 0, false)); } @@ -22,8 +20,7 @@ TEST(CanvasPixel, MaxFragments) EXPECT_EQ(pixel.getFragment(MAX_FRAGMENTS_PER_PIXEL - 1).getOpaque(), false); } -TEST(CanvasPixel, SameTransparent) -{ +TEST(CanvasPixel, SameTransparent) { CanvasPixel pixel; pixel.pushFragment(CanvasFragment(true, Vector3(0.0, 0.0, 1.4), Vector3(), 0, false)); @@ -39,8 +36,7 @@ TEST(CanvasPixel, SameTransparent) EXPECT_EQ(pixel.getFragment(1).getClient(), 1); } -TEST(CanvasPixel, SameOpaque) -{ +TEST(CanvasPixel, SameOpaque) { CanvasPixel pixel; pixel.pushFragment(CanvasFragment(true, Vector3(0.0, 0.0, 1.4), Vector3(), 0, true)); diff --git a/src/tests/CanvasPortion_Test.cpp b/src/tests/CanvasPortion_Test.cpp index d188693..22687d6 100644 --- a/src/tests/CanvasPortion_Test.cpp +++ b/src/tests/CanvasPortion_Test.cpp @@ -3,8 +3,7 @@ #include "CanvasPortion.h" #include "CanvasFragment.h" -TEST(CanvasPortion, setSize) -{ +TEST(CanvasPortion, setSize) { CanvasPortion portion; portion.setSize(150, 30); @@ -13,8 +12,7 @@ TEST(CanvasPortion, setSize) EXPECT_EQ(30, portion.getHeight()); } -TEST(CanvasPortion, pushFragment) -{ +TEST(CanvasPortion, pushFragment) { CanvasPortion portion; CanvasFragment pushed; const CanvasFragment *got; @@ -36,8 +34,7 @@ TEST(CanvasPortion, pushFragment) ASSERT_TRUE(got); } -TEST(CanvasPortion, pushFragment_opaque) -{ +TEST(CanvasPortion, pushFragment_opaque) { CanvasPortion portion; CanvasFragment pushed; @@ -63,8 +60,7 @@ TEST(CanvasPortion, pushFragment_opaque) EXPECT_DOUBLE_EQ(4.0, portion.getFrontFragment(2, 2)->getZ()); } -TEST(CanvasPortion, pushFragment_transparent) -{ +TEST(CanvasPortion, pushFragment_transparent) { CanvasPortion portion; CanvasFragment pushed; @@ -90,8 +86,7 @@ TEST(CanvasPortion, pushFragment_transparent) EXPECT_DOUBLE_EQ(4.0, portion.getFrontFragment(2, 2)->getZ()); } -TEST(CanvasPortion, clear) -{ +TEST(CanvasPortion, clear) { CanvasPortion portion; CanvasFragment fragment; diff --git a/src/tests/CanvasPreview_Test.cpp b/src/tests/CanvasPreview_Test.cpp index e754267..415c292 100644 --- a/src/tests/CanvasPreview_Test.cpp +++ b/src/tests/CanvasPreview_Test.cpp @@ -3,8 +3,7 @@ #include "CanvasPreview.h" #include "Color.h" -TEST(CanvasPreview, setSize) -{ +TEST(CanvasPreview, setSize) { CanvasPreview preview; preview.setSize(800, 600, 400, 300); @@ -13,8 +12,7 @@ TEST(CanvasPreview, setSize) EXPECT_EQ(300, preview.getHeight()); } -TEST(CanvasPreview, pushPixel_accumulate) -{ +TEST(CanvasPreview, pushPixel_accumulate) { CanvasPreview preview; Color col; preview.setSize(800, 600, 400, 300); @@ -41,8 +39,7 @@ TEST(CanvasPreview, pushPixel_accumulate) EXPECT_COLOR_RGBA(col, 0.25, 0.25, 0.0, 1.0); } -TEST(CanvasPreview, pushPixel_border) -{ +TEST(CanvasPreview, pushPixel_border) { CanvasPreview preview; preview.setSize(759, 237, 9, 14); diff --git a/src/tests/Canvas_Test.cpp b/src/tests/Canvas_Test.cpp index 4070c91..4f59945 100644 --- a/src/tests/Canvas_Test.cpp +++ b/src/tests/Canvas_Test.cpp @@ -4,19 +4,17 @@ #include "CanvasPortion.h" #include "CanvasPreview.h" -static void checkPortion(Canvas &canvas, int x, int y, int width, int height) -{ +static void checkPortion(Canvas &canvas, int x, int y, int width, int height) { ASSERT_LT(x, canvas.getHorizontalPortionCount()); ASSERT_LT(y, canvas.getVerticalPortionCount()); - CanvasPortion* portion = canvas.at(x, y); + CanvasPortion *portion = canvas.at(x, y); EXPECT_EQ(width, portion->getWidth()); EXPECT_EQ(height, portion->getHeight()); } -TEST(Canvas, SizingAndCutting) -{ +TEST(Canvas, SizingAndCutting) { Canvas canvas; canvas.setSize(200, 100); diff --git a/src/tests/CappedCylinder_Test.cpp b/src/tests/CappedCylinder_Test.cpp index cfa60cd..1a04463 100644 --- a/src/tests/CappedCylinder_Test.cpp +++ b/src/tests/CappedCylinder_Test.cpp @@ -2,37 +2,43 @@ #include "CappedCylinder.h" -TEST(CappedCylinder, checkRayIntersection) -{ +TEST(CappedCylinder, checkRayIntersection) { CappedCylinder cylinder(VECTOR_DOWN, VECTOR_UP, 1.0, 2.0); int intersect_count; Vector3 p1, p2; - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(1.5, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(1.5, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); EXPECT_EQ(0, intersect_count); - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(1.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(1.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); EXPECT_EQ(1, intersect_count); EXPECT_VECTOR3_COORDS(p1, 1.0, 0.0, 0.0); - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(0.5, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(0.5, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); EXPECT_EQ(2, intersect_count); EXPECT_VECTOR3_COORDS(p1, 0.5, 0.0, -cos(asin(0.5))); EXPECT_VECTOR3_COORDS(p2, 0.5, 0.0, cos(asin(0.5))); - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(0.5, -2.1, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(0.5, -2.1, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); EXPECT_EQ(0, intersect_count); - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(0.5, 2.1, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(0.5, 2.1, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); EXPECT_EQ(0, intersect_count); // diagonal cases (through a cap) - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(-2.0, -1.0, 0.0), Vector3(1.0, 1.0, 0.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(-2.0, -1.0, 0.0), Vector3(1.0, 1.0, 0.0)), &p1, &p2); EXPECT_EQ(1, intersect_count); EXPECT_VECTOR3_COORDS(p1, -1.0, 0.0, 0.0); - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(-2.0, 3.0, 0.0), Vector3(1.0, -1.0, 0.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(-2.0, 3.0, 0.0), Vector3(1.0, -1.0, 0.0)), &p1, &p2); EXPECT_EQ(1, intersect_count); EXPECT_VECTOR3_COORDS(p1, 1.0, 0.0, 0.0); } diff --git a/src/tests/ColorHSL_Test.cpp b/src/tests/ColorHSL_Test.cpp index 7eaa5be..85d0933 100644 --- a/src/tests/ColorHSL_Test.cpp +++ b/src/tests/ColorHSL_Test.cpp @@ -3,21 +3,18 @@ #include "Color.h" #include "ColorHSL.h" -TEST(ColorHSL, colorFromHSL) -{ +TEST(ColorHSL, colorFromHSL) { std::vector colors; colors.push_back(Color()); colors.push_back(Color(1.0, 0.0, 0.0, 1.0)); colors.push_back(Color(0.7, 0.5, 0.3, 1.0)); - //colors.push_back(Color(2.0, 0.0, 0.0, 1.0)); // FIXME not working yet + // colors.push_back(Color(2.0, 0.0, 0.0, 1.0)); // FIXME not working yet colors.push_back(Color(3.0, 3.0, 3.0, 1.0)); - for (auto &color: colors) - { + for (auto &color : colors) { ColorHSL hsl = colorToHSL(color); Color rgb = colorFromHSL(hsl); EXPECT_COLOR_RGBA(rgb, color.r, color.g, color.b, color.a); } } - diff --git a/src/tests/DefinitionNode_Test.cpp b/src/tests/DefinitionNode_Test.cpp index 174c2db..f970d24 100644 --- a/src/tests/DefinitionNode_Test.cpp +++ b/src/tests/DefinitionNode_Test.cpp @@ -5,8 +5,7 @@ #include "PackStream.h" #include "DefinitionWatcher.h" -TEST(DefinitionNode, toString) -{ +TEST(DefinitionNode, toString) { DefinitionNode root(NULL, "root"); DefinitionNode branch(&root, "branch"); DefinitionNode leaf1(&branch, "leaf1"); @@ -16,8 +15,7 @@ TEST(DefinitionNode, toString) EXPECT_EQ("branch\n leaf1\n leaf2", branch.toString()); } -TEST(DefinitionNode, getPath) -{ +TEST(DefinitionNode, getPath) { DefinitionNode root(NULL, "root"); DefinitionNode branch(&root, "branch"); DefinitionNode leaf(&branch, "leaf"); @@ -27,15 +25,12 @@ TEST(DefinitionNode, getPath) EXPECT_EQ("/branch/leaf", leaf.getPath()); } -class FakeWatcher: public DefinitionWatcher -{ - virtual void nodeChanged(const DefinitionNode *, const DefinitionDiff *) override - { +class FakeWatcher : public DefinitionWatcher { + virtual void nodeChanged(const DefinitionNode *, const DefinitionDiff *) override { } }; -TEST(DefinitionNode, addWatcher) -{ +TEST(DefinitionNode, addWatcher) { DefinitionNode root(NULL, "root"); FakeWatcher watcher; @@ -46,8 +41,7 @@ TEST(DefinitionNode, addWatcher) EXPECT_EQ(1, root.getWatcherCount()); } -TEST(DefinitionNode, findByPath) -{ +TEST(DefinitionNode, findByPath) { DefinitionNode root(NULL, "root"); DefinitionNode branch(&root, "branch"); DefinitionNode leaf(&branch, "leaf"); @@ -64,11 +58,10 @@ TEST(DefinitionNode, findByPath) EXPECT_EQ(&leaf, branch.findByPath("leaf")); } -TEST(DefinitionNode, attachDetach) -{ - DefinitionNode* root = new DefinitionNode(NULL, "root"); - DefinitionNode* child1 = new DefinitionNode(root, "child1"); - DefinitionNode* child2 = new DefinitionNode(root, "child2"); +TEST(DefinitionNode, attachDetach) { + DefinitionNode *root = new DefinitionNode(NULL, "root"); + DefinitionNode *child1 = new DefinitionNode(root, "child1"); + DefinitionNode *child2 = new DefinitionNode(root, "child2"); EXPECT_EQ(root, child1->getParent()); EXPECT_EQ(root, child2->getParent()); @@ -85,16 +78,15 @@ TEST(DefinitionNode, attachDetach) delete root; } -TEST(DefinitionNode, saveLoadCopy) -{ +TEST(DefinitionNode, saveLoadCopy) { PackStream *stream; int check_in = 42, check_out = 0; - DefinitionNode* before = new DefinitionNode(NULL, "root"); - DefinitionNode* before1 = new DefinitionNode(before, "before1"); + DefinitionNode *before = new DefinitionNode(NULL, "root"); + DefinitionNode *before1 = new DefinitionNode(before, "before1"); new FloatNode(before1, "before11", 2.1); new FloatNode(before1, "before12", -4.3); - DefinitionNode* before2 = new DefinitionNode(before, "before2"); + DefinitionNode *before2 = new DefinitionNode(before, "before2"); new DefinitionNode(before2, "before21"); new FloatNode(before2, "before22"); new FloatNode(before, "before3", 6.7); @@ -106,12 +98,12 @@ TEST(DefinitionNode, saveLoadCopy) delete stream; // Same definition tree, but with missing nodes, and added ones - DefinitionNode* after = new DefinitionNode(NULL, "root"); - DefinitionNode* after1 = new DefinitionNode(after, "before1"); - FloatNode* after12 = new FloatNode(after1, "before12"); - FloatNode* after13 = new FloatNode(after1, "before13"); - FloatNode* after3 = new FloatNode(after, "before3"); - FloatNode* after4 = new FloatNode(after, "before4"); + DefinitionNode *after = new DefinitionNode(NULL, "root"); + DefinitionNode *after1 = new DefinitionNode(after, "before1"); + FloatNode *after12 = new FloatNode(after1, "before12"); + FloatNode *after13 = new FloatNode(after1, "before13"); + FloatNode *after3 = new FloatNode(after, "before3"); + FloatNode *after4 = new FloatNode(after, "before4"); stream = new PackStream(); stream->bindToFile("/tmp/test_paysages_pack"); diff --git a/src/tests/DiffManager_Test.cpp b/src/tests/DiffManager_Test.cpp index 332aed3..4fd135a 100644 --- a/src/tests/DiffManager_Test.cpp +++ b/src/tests/DiffManager_Test.cpp @@ -6,8 +6,7 @@ #include "FloatDiff.h" #include "FloatNode.h" -TEST(DiffManager, undoRedo) -{ +TEST(DiffManager, undoRedo) { DefinitionNode root(NULL, "root"); DiffManager *diffs = root.getDiffManager(); @@ -33,8 +32,7 @@ TEST(DiffManager, undoRedo) EXPECT_DOUBLE_EQ(-2.1, leaf.getValue()); } -TEST(DiffManager, undoTooMuch) -{ +TEST(DiffManager, undoTooMuch) { DefinitionNode root(NULL, "root"); DiffManager *diffs = root.getDiffManager(); @@ -54,8 +52,7 @@ TEST(DiffManager, undoTooMuch) EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); } -TEST(DiffManager, redoTooMuch) -{ +TEST(DiffManager, redoTooMuch) { DefinitionNode root(NULL, "root"); DiffManager *diffs = root.getDiffManager(); @@ -78,8 +75,7 @@ TEST(DiffManager, redoTooMuch) EXPECT_DOUBLE_EQ(1.1, leaf.getValue()); } -TEST(DiffManager, undoBranch) -{ +TEST(DiffManager, undoBranch) { DefinitionNode root(NULL, "root"); DiffManager *diffs = root.getDiffManager(); @@ -114,17 +110,15 @@ TEST(DiffManager, undoBranch) EXPECT_DOUBLE_EQ(4.4, leaf.getValue()); } -class TestWatcher: public DefinitionWatcher -{ -public: - TestWatcher(DefinitionNode* expected_node, double expected_old_value, double expected_new_value): - DefinitionWatcher(), expected_node(expected_node), expected_old_value(expected_old_value), expected_new_value(expected_new_value) - { +class TestWatcher : public DefinitionWatcher { + public: + TestWatcher(DefinitionNode *expected_node, double expected_old_value, double expected_new_value) + : DefinitionWatcher(), expected_node(expected_node), expected_old_value(expected_old_value), + expected_new_value(expected_new_value) { calls = 0; } - virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff) override - { + virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff) override { EXPECT_EQ(expected_node, node); ASSERT_EQ("float", diff->getTypeName()); const FloatDiff *float_diff = (const FloatDiff *)diff; @@ -134,13 +128,12 @@ public: } int calls; - DefinitionNode* expected_node; + DefinitionNode *expected_node; double expected_old_value; double expected_new_value; }; -TEST(DiffManager, addWatcher) -{ +TEST(DiffManager, addWatcher) { FloatNode node(NULL, "node"); TestWatcher watcher(&node, 1.3, -4.0); @@ -154,8 +147,7 @@ TEST(DiffManager, addWatcher) EXPECT_EQ(1, watcher.calls); } -TEST(DiffManager, addWatcherWithInitDiffs) -{ +TEST(DiffManager, addWatcherWithInitDiffs) { FloatNode node(NULL, "node", 1.3); TestWatcher watcher(&node, 1.3, 1.3); diff --git a/src/tests/Disk_Test.cpp b/src/tests/Disk_Test.cpp index 062d4e2..1b8d4ea 100644 --- a/src/tests/Disk_Test.cpp +++ b/src/tests/Disk_Test.cpp @@ -3,8 +3,7 @@ #include "InfiniteRay.h" #include "Disk.h" -TEST(Disk, checkRayIntersection) -{ +TEST(Disk, checkRayIntersection) { Disk disk(VECTOR_UP, VECTOR_UP, 0.8); int result; diff --git a/src/tests/Euclid_Test.cpp b/src/tests/Euclid_Test.cpp index 52a4cc8..5f5ed5f 100644 --- a/src/tests/Euclid_Test.cpp +++ b/src/tests/Euclid_Test.cpp @@ -6,7 +6,8 @@ /*static inline int _Vector3_cmp(Vector3 v1, Vector3 v2) { - return fabs(v1.x - v2.z) >= 0.00000000001 && fabs(v1.y - v2.y) >= 0.00000000001 && fabs(v1.z - v2.z) >= 0.00000000001; + return fabs(v1.x - v2.z) >= 0.00000000001 && fabs(v1.y - v2.y) >= 0.00000000001 && fabs(v1.z - v2.z) >= +0.00000000001; } static inline void _Vector3_str(Vector3 v, char* buffer, int length) @@ -15,8 +16,7 @@ static inline void _Vector3_str(Vector3 v, char* buffer, int length) } DEFINE_COMPARE_ASSERT(Vector3, _Vector3_cmp, _Vector3_str);*/ -TEST(Euclid, get2DAngle) -{ +TEST(Euclid, get2DAngle) { EXPECT_DOUBLE_EQ(Geometry::get2DAngle(0.0, 0.0), 0.0); EXPECT_DOUBLE_EQ(Geometry::get2DAngle(0.1, 0.0), 0.0); @@ -59,8 +59,7 @@ TEST(Euclid, get2DAngle) EXPECT_EQ(v3Scale(v1, -0.5), v3); }*/ -TEST(Euclid, VectorSpherical) -{ +TEST(Euclid, VectorSpherical) { Vector3 v1; VectorSpherical v2; diff --git a/src/tests/FloatNode_Test.cpp b/src/tests/FloatNode_Test.cpp index c3013ab..67d6301 100644 --- a/src/tests/FloatNode_Test.cpp +++ b/src/tests/FloatNode_Test.cpp @@ -4,16 +4,14 @@ #include "FloatDiff.h" #include "PackStream.h" -TEST(FloatNode, toString) -{ +TEST(FloatNode, toString) { FloatNode test(NULL, "test", 2.1); EXPECT_EQ("test 2.1", test.toString(0)); EXPECT_EQ(" test 2.1", test.toString(2)); } -TEST(FloatNode, saveLoadAndSkip) -{ +TEST(FloatNode, saveLoadAndSkip) { DefinitionNode root1(NULL, "root"); FloatNode testa1(&root1, "testa", 1.5); FloatNode testb1(&root1, "testb", 4.3); @@ -30,8 +28,7 @@ TEST(FloatNode, saveLoadAndSkip) EXPECT_DOUBLE_EQ(4.3, testb2.getValue()); } -TEST(FloatNode, copy) -{ +TEST(FloatNode, copy) { FloatNode base(NULL, "test", 2.1); FloatNode other(NULL, "test", 4.3); DefinitionNode badother(NULL, "test"); @@ -47,8 +44,7 @@ TEST(FloatNode, copy) // can't check anything, just useful in valgrind } -TEST(FloatNode, produceDiff) -{ +TEST(FloatNode, produceDiff) { FloatNode node(NULL, "test", 8.3); const FloatDiff *diff = node.produceDiff(-4.1); @@ -64,8 +60,7 @@ TEST(FloatNode, produceDiff) delete diff; } -TEST(FloatNode, applyDiff) -{ +TEST(FloatNode, applyDiff) { FloatNode node(NULL, "test", 1.2); FloatDiff diff(&node, 1.2, 2.4); DefinitionNode onode(NULL, "test", "badtype"); diff --git a/src/tests/FluidMediumManager_Test.cpp b/src/tests/FluidMediumManager_Test.cpp index a2e7694..71bb711 100644 --- a/src/tests/FluidMediumManager_Test.cpp +++ b/src/tests/FluidMediumManager_Test.cpp @@ -6,17 +6,14 @@ #include "FluidMediumManager.h" #include "FluidMediumInterface.h" -class FluidMediumManager_Test:public BaseTestCase -{ -protected: - virtual void setUp() - { +class FluidMediumManager_Test : public BaseTestCase { + protected: + virtual void setUp() { scenery = new Scenery(); renderer = new SoftwareRenderer(scenery); } - virtual void tearDown() - { + virtual void tearDown() { delete renderer; delete scenery; } @@ -25,26 +22,22 @@ protected: SoftwareRenderer *renderer; }; - -TEST_F(FluidMediumManager_Test, getTraversedMedia) -{ +TEST_F(FluidMediumManager_Test, getTraversedMedia) { FluidMediumManager manager(renderer); int traversed; FluidMediumSegment segments[10]; - class FakeMedium:public FluidMediumInterface - { - public: - void setCut(double ymin, double ymax) - { + class FakeMedium : public FluidMediumInterface { + public: + void setCut(double ymin, double ymax) { this->ymin = ymin; this->ymax = ymax; } - virtual bool checkInfluence(SpaceSegment& segment) const override - { + virtual bool checkInfluence(SpaceSegment &segment) const override { return segment.intersectYInterval(this->ymin, this->ymax); } - private: + + private: double ymin = -2.0; double ymax = -1.0; }; @@ -64,7 +57,7 @@ TEST_F(FluidMediumManager_Test, getTraversedMedia) m1.setCut(1.0, 2.0); traversed = manager.getTraversedMedia(segments, ray, 10); ASSERT_EQ(1, traversed); - EXPECT_EQ((FluidMediumInterface*)&m1, segments[0].medium); + EXPECT_EQ((FluidMediumInterface *)&m1, segments[0].medium); EXPECT_VECTOR3_COORDS(segments[0].segment.getStart(), 0.8, 1.0, -0.4); EXPECT_VECTOR3_COORDS(segments[0].segment.getEnd(), 1.6, 2.0, -0.8); @@ -74,10 +67,10 @@ TEST_F(FluidMediumManager_Test, getTraversedMedia) manager.registerMedium(&m2); traversed = manager.getTraversedMedia(segments, ray, 10); ASSERT_EQ(2, traversed); - EXPECT_EQ((FluidMediumInterface*)&m1, segments[0].medium); + EXPECT_EQ((FluidMediumInterface *)&m1, segments[0].medium); EXPECT_VECTOR3_COORDS(segments[0].segment.getStart(), 0.8, 1.0, -0.4); EXPECT_VECTOR3_COORDS(segments[0].segment.getEnd(), 1.6, 2.0, -0.8); - EXPECT_EQ((FluidMediumInterface*)&m2, segments[1].medium); + EXPECT_EQ((FluidMediumInterface *)&m2, segments[1].medium); EXPECT_VECTOR3_COORDS(segments[1].segment.getStart(), 3.2, 4.0, -1.6); EXPECT_VECTOR3_COORDS(segments[1].segment.getEnd(), 8.0, 10.0, -4.0); @@ -87,21 +80,21 @@ TEST_F(FluidMediumManager_Test, getTraversedMedia) manager.registerMedium(&m3); traversed = manager.getTraversedMedia(segments, ray, 10); ASSERT_EQ(3, traversed); - EXPECT_EQ((FluidMediumInterface*)&m1, segments[0].medium); + EXPECT_EQ((FluidMediumInterface *)&m1, segments[0].medium); EXPECT_VECTOR3_COORDS(segments[0].segment.getStart(), 0.8, 1.0, -0.4); EXPECT_VECTOR3_COORDS(segments[0].segment.getEnd(), 1.6, 2.0, -0.8); - EXPECT_EQ((FluidMediumInterface*)&m2, segments[1].medium); + EXPECT_EQ((FluidMediumInterface *)&m2, segments[1].medium); EXPECT_VECTOR3_COORDS(segments[1].segment.getStart(), 3.2, 4.0, -1.6); EXPECT_VECTOR3_COORDS(segments[1].segment.getEnd(), 8.0, 10.0, -4.0); - EXPECT_EQ((FluidMediumInterface*)&m3, segments[2].medium); + EXPECT_EQ((FluidMediumInterface *)&m3, segments[2].medium); EXPECT_VECTOR3_COORDS(segments[2].segment.getStart(), 2.4, 3.0, -1.2); EXPECT_VECTOR3_COORDS(segments[2].segment.getEnd(), 3.6, 4.5, -1.8); // Testing the segment count limit traversed = manager.getTraversedMedia(segments, ray, 2); ASSERT_EQ(2, traversed); - EXPECT_EQ((FluidMediumInterface*)&m1, segments[0].medium); - EXPECT_EQ((FluidMediumInterface*)&m2, segments[1].medium); + EXPECT_EQ((FluidMediumInterface *)&m1, segments[0].medium); + EXPECT_EQ((FluidMediumInterface *)&m2, segments[1].medium); // Testing after clear manager.clearMedia(); diff --git a/src/tests/FractalNoise_Test.cpp b/src/tests/FractalNoise_Test.cpp index 6e4af79..7983e64 100644 --- a/src/tests/FractalNoise_Test.cpp +++ b/src/tests/FractalNoise_Test.cpp @@ -2,11 +2,9 @@ #include "FractalNoise.h" -class TestFractalNoise:public FractalNoise -{ -public: - TestFractalNoise(double value=0.0):FractalNoise(), value(value) - { +class TestFractalNoise : public FractalNoise { + public: + TestFractalNoise(double value = 0.0) : FractalNoise(), value(value) { NoiseState state; state.resetOffsets(); setState(state); @@ -14,20 +12,19 @@ public: calls = 0; } - virtual double getBase3d(double x, double y, double z) const override - { - ((TestFractalNoise*)this)->calls++; + virtual double getBase3d(double x, double y, double z) const override { + ((TestFractalNoise *)this)->calls++; return value + x + y + z; } -public: + public: int calls; -private: + + private: double value; }; -TEST(FractalNoise, AutoBase2d) -{ +TEST(FractalNoise, AutoBase2d) { TestFractalNoise noise(0.2); double result = noise.getBase2d(0.4, 0.1); @@ -36,8 +33,7 @@ TEST(FractalNoise, AutoBase2d) EXPECT_DOUBLE_EQ(0.7, result); } -TEST(FractalNoise, AutoBase1d) -{ +TEST(FractalNoise, AutoBase1d) { TestFractalNoise noise(0.2); double result = noise.getBase1d(0.4); @@ -46,8 +42,7 @@ TEST(FractalNoise, AutoBase1d) EXPECT_DOUBLE_EQ(0.6, result); } -TEST(FractalNoise, NoStep) -{ +TEST(FractalNoise, NoStep) { TestFractalNoise noise(0.1); double result = noise.get1d(1.1, 1.0); @@ -56,8 +51,7 @@ TEST(FractalNoise, NoStep) EXPECT_DOUBLE_EQ(0.0, result); } -TEST(FractalNoise, SingleStep) -{ +TEST(FractalNoise, SingleStep) { TestFractalNoise noise(0.1); double result = noise.get1d(0.7, 1.0); @@ -66,8 +60,7 @@ TEST(FractalNoise, SingleStep) EXPECT_DOUBLE_EQ(1.1, result); } -TEST(FractalNoise, Sum2Steps) -{ +TEST(FractalNoise, Sum2Steps) { TestFractalNoise noise(0.1); double result = noise.get1d(0.3, 1.0); @@ -76,8 +69,7 @@ TEST(FractalNoise, Sum2Steps) EXPECT_DOUBLE_EQ(1.1 + 1.05, result); } -TEST(FractalNoise, Sum3Steps) -{ +TEST(FractalNoise, Sum3Steps) { TestFractalNoise noise(0.1); double result = noise.get1d(0.2, 1.0); @@ -86,8 +78,7 @@ TEST(FractalNoise, Sum3Steps) EXPECT_DOUBLE_EQ(1.1 + 1.05 + 1.025, result); } -TEST(FractalNoise, InitialScaling) -{ +TEST(FractalNoise, InitialScaling) { TestFractalNoise noise(0.8); noise.setScaling(0.5); @@ -97,8 +88,7 @@ TEST(FractalNoise, InitialScaling) EXPECT_DOUBLE_EQ(1.4 + 1.2, result); } -TEST(FractalNoise, InitialHeight) -{ +TEST(FractalNoise, InitialHeight) { TestFractalNoise noise(0.8); noise.setScaling(1.0, 0.5); @@ -108,8 +98,7 @@ TEST(FractalNoise, InitialHeight) EXPECT_DOUBLE_EQ(0.9 + 0.7, result); } -TEST(FractalNoise, InitialScalingAndHeight) -{ +TEST(FractalNoise, InitialScalingAndHeight) { TestFractalNoise noise(0.8); noise.setScaling(0.5, 0.5); @@ -119,8 +108,7 @@ TEST(FractalNoise, InitialScalingAndHeight) EXPECT_DOUBLE_EQ(0.7 + 0.6, result); } -TEST(FractalNoise, StepScaling) -{ +TEST(FractalNoise, StepScaling) { TestFractalNoise noise(0.1); noise.setStep(0.8); @@ -130,8 +118,7 @@ TEST(FractalNoise, StepScaling) EXPECT_DOUBLE_EQ(1.1 + 1.08 + 1.064, result); } -TEST(FractalNoise, StepHeight) -{ +TEST(FractalNoise, StepHeight) { TestFractalNoise noise(0.1); noise.setStep(0.5, 0.8); @@ -141,8 +128,7 @@ TEST(FractalNoise, StepHeight) EXPECT_DOUBLE_EQ(1.1 + 0.84, result); } -TEST(FractalNoise, StepScalingAndHeight) -{ +TEST(FractalNoise, StepScalingAndHeight) { TestFractalNoise noise(0.8); noise.setStep(0.5, 0.5); @@ -152,8 +138,7 @@ TEST(FractalNoise, StepScalingAndHeight) EXPECT_DOUBLE_EQ(1.8 + 0.7 + 0.3, result); } -TEST(FractalNoise, StateOffset) -{ +TEST(FractalNoise, StateOffset) { TestFractalNoise noise(0.8); NoiseState state; state.resetOffsets(0.2); @@ -165,8 +150,7 @@ TEST(FractalNoise, StateOffset) EXPECT_DOUBLE_EQ(2.0 + 1.5, result); } -TEST(FractalNoise, StateOffsetIter) -{ +TEST(FractalNoise, StateOffsetIter) { TestFractalNoise noise(0.8); NoiseState state; state.setLevel(0, 0.1, 0.1, 0.1); @@ -179,8 +163,7 @@ TEST(FractalNoise, StateOffsetIter) EXPECT_DOUBLE_EQ(1.9 + 1.7, result); } -TEST(FractalNoise, StateOffsetLoop) -{ +TEST(FractalNoise, StateOffsetLoop) { TestFractalNoise noise(0.8); NoiseState state; state.setLevelCount(2); @@ -194,8 +177,7 @@ TEST(FractalNoise, StateOffsetLoop) EXPECT_DOUBLE_EQ(1.9 + 1.7 + 1.225, result); } -TEST(FractalNoise, Noise2d) -{ +TEST(FractalNoise, Noise2d) { TestFractalNoise noise(0.8); NoiseState state; state.setLevelCount(2); @@ -209,8 +191,7 @@ TEST(FractalNoise, Noise2d) EXPECT_DOUBLE_EQ(2.6 + 2.55, result); } -TEST(FractalNoise, Noise3d) -{ +TEST(FractalNoise, Noise3d) { TestFractalNoise noise(0.8); NoiseState state; state.setLevelCount(2); diff --git a/src/tests/GodRaysSampler_Test.cpp b/src/tests/GodRaysSampler_Test.cpp index 9f1e797..7e156e6 100644 --- a/src/tests/GodRaysSampler_Test.cpp +++ b/src/tests/GodRaysSampler_Test.cpp @@ -9,8 +9,7 @@ #include "LightComponent.h" #include "Color.h" -TEST(GodRaysSampler, getBounds) -{ +TEST(GodRaysSampler, getBounds) { GodRaysSampler sampler; sampler.setAltitudes(-5.0, 300.0); @@ -24,8 +23,7 @@ TEST(GodRaysSampler, getBounds) EXPECT_VECTOR3_COORDS(bounds.getEnd(), 600.0, 300.0, 8500.0); } -TEST(GodRaysSampler, getSamples) -{ +TEST(GodRaysSampler, getSamples) { GodRaysSampler sampler; sampler.setAltitudes(-50.0, 100.0); @@ -40,8 +38,7 @@ TEST(GodRaysSampler, getSamples) EXPECT_EQ(21, z); } -TEST(GodRaysSampler, setQuality) -{ +TEST(GodRaysSampler, setQuality) { GodRaysSampler sampler; sampler.setQuality(0.0); @@ -60,10 +57,8 @@ TEST(GodRaysSampler, setQuality) EXPECT_DOUBLE_EQ(0.06172839506, sampler.getWalkStep()); } -class GodRayLightSource: public LightSource -{ - virtual bool getLightsAt(std::vector &result, const Vector3 &location) const override - { +class GodRayLightSource : public LightSource { + virtual bool getLightsAt(std::vector &result, const Vector3 &location) const override { LightComponent light; light.altered = true; light.color = Color(fabs(location.x), fabs(location.y), fabs(location.z)); @@ -72,19 +67,13 @@ class GodRayLightSource: public LightSource } }; -TEST(GodRaysSampler, getRawLight) -{ - class TestLightFilter: public LightFilter - { - virtual bool applyLightFilter(LightComponent &light, const Vector3 &at) override - { - if (at.x > 0.5) - { +TEST(GodRaysSampler, getRawLight) { + class TestLightFilter : public LightFilter { + virtual bool applyLightFilter(LightComponent &light, const Vector3 &at) override { + if (at.x > 0.5) { light.color.r = 0.1; return true; - } - else - { + } else { return true; } } @@ -106,12 +95,9 @@ TEST(GodRaysSampler, getRawLight) EXPECT_COLOR_RGBA(sampler.getRawLight(Vector3(1.0, 2.0, -6.0), true), 0.1, 2.0, 6.0, 1.0); } -TEST(GodRaysSampler, getCachedLight) -{ - class TestLightFilter: public LightFilter - { - virtual bool applyLightFilter(LightComponent &, const Vector3 &at) override - { +TEST(GodRaysSampler, getCachedLight) { + class TestLightFilter : public LightFilter { + virtual bool applyLightFilter(LightComponent &, const Vector3 &at) override { return at.x <= 10.0 or at.x >= 50.0; } }; diff --git a/src/tests/InfiniteCylinder_Test.cpp b/src/tests/InfiniteCylinder_Test.cpp index 6ce8254..1d836d9 100644 --- a/src/tests/InfiniteCylinder_Test.cpp +++ b/src/tests/InfiniteCylinder_Test.cpp @@ -4,38 +4,39 @@ #include "InfiniteCylinder.h" #include -TEST(InfiniteCylinder, checkRayIntersection) -{ +TEST(InfiniteCylinder, checkRayIntersection) { InfiniteRay ray(VECTOR_ZERO, VECTOR_UP); InfiniteCylinder cylinder(ray, 1.0); int intersect_count; Vector3 p1, p2; - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(1.5, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(1.5, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); EXPECT_EQ(0, intersect_count); - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(1.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(1.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); EXPECT_EQ(1, intersect_count); EXPECT_VECTOR3_COORDS(p1, 1.0, 0.0, 0.0); - intersect_count = cylinder.checkRayIntersection(InfiniteRay(Vector3(0.5, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); + intersect_count = + cylinder.checkRayIntersection(InfiniteRay(Vector3(0.5, 0.0, 0.0), Vector3(0.0, 0.0, 1.0)), &p1, &p2); EXPECT_EQ(2, intersect_count); EXPECT_VECTOR3_COORDS(p1, 0.5, 0.0, -cos(asin(0.5))); EXPECT_VECTOR3_COORDS(p2, 0.5, 0.0, cos(asin(0.5))); } -TEST(InfiniteCylinder, checkRayIntersection2) -{ +TEST(InfiniteCylinder, checkRayIntersection2) { InfiniteRay ray(Vector3(-1.4, 1.5, 1.0), Vector3(1.0, 0.0, 0.0)); InfiniteCylinder cylinder(ray, 0.5); int intersect_count; Vector3 p1, p2; - intersect_count = cylinder.checkRayIntersection(InfiniteRay::fromPoints(Vector3(0.0, 1.5, 0.0), Vector3(0.0, 1.5, 2.0)), &p1, &p2); + intersect_count = cylinder.checkRayIntersection( + InfiniteRay::fromPoints(Vector3(0.0, 1.5, 0.0), Vector3(0.0, 1.5, 2.0)), &p1, &p2); EXPECT_EQ(2, intersect_count); EXPECT_VECTOR3_COORDS(p1, 0.0, 1.5, 0.5); EXPECT_VECTOR3_COORDS(p2, 0.0, 1.5, 1.5); } - diff --git a/src/tests/InfinitePlane_Test.cpp b/src/tests/InfinitePlane_Test.cpp index 8a92517..ec9170d 100644 --- a/src/tests/InfinitePlane_Test.cpp +++ b/src/tests/InfinitePlane_Test.cpp @@ -3,8 +3,7 @@ #include "InfiniteRay.h" #include "InfinitePlane.h" -TEST(InfinitePlane, checkRayIntersection) -{ +TEST(InfinitePlane, checkRayIntersection) { InfinitePlane plane(VECTOR_UP, VECTOR_UP); int result; @@ -21,8 +20,7 @@ TEST(InfinitePlane, checkRayIntersection) ASSERT_EQ(-1, result); } -TEST(InfinitePlane, checkRayIntersection_oblique) -{ +TEST(InfinitePlane, checkRayIntersection_oblique) { InfinitePlane plane(Vector3(14.0, -5.0, 3.5), Vector3(1.0, 0.0, 0.0)); InfiniteRay ray(Vector3(2.0, 2.0, 2.0), Vector3(1.0, 1.0, 1.0).normalize()); int result; diff --git a/src/tests/IntNode_Test.cpp b/src/tests/IntNode_Test.cpp index b6cae16..bb59666 100644 --- a/src/tests/IntNode_Test.cpp +++ b/src/tests/IntNode_Test.cpp @@ -4,16 +4,14 @@ #include "IntDiff.h" #include "PackStream.h" -TEST(IntNode, toString) -{ +TEST(IntNode, toString) { IntNode test(NULL, "test", 2); EXPECT_EQ("test 2", test.toString(0)); EXPECT_EQ(" test 2", test.toString(2)); } -TEST(IntNode, saveLoadAndSkip) -{ +TEST(IntNode, saveLoadAndSkip) { DefinitionNode root1(NULL, "root"); IntNode testa1(&root1, "testa", 1); IntNode testb1(&root1, "testb", 4); @@ -30,8 +28,7 @@ TEST(IntNode, saveLoadAndSkip) EXPECT_DOUBLE_EQ(4, testb2.getValue()); } -TEST(IntNode, copy) -{ +TEST(IntNode, copy) { IntNode base(NULL, "test", 2); IntNode other(NULL, "test", 4); DefinitionNode badother(NULL, "test"); @@ -47,8 +44,7 @@ TEST(IntNode, copy) // can't check anything, just useful in valgrind } -TEST(IntNode, produceDiff) -{ +TEST(IntNode, produceDiff) { IntNode node(NULL, "test", 8); const IntDiff *diff = node.produceDiff(-4); @@ -64,8 +60,7 @@ TEST(IntNode, produceDiff) delete diff; } -TEST(IntNode, applyDiff) -{ +TEST(IntNode, applyDiff) { IntNode node(NULL, "test", 1); IntDiff diff(&node, 1, 2); DefinitionNode onode(NULL, "test", "badtype"); @@ -110,4 +105,3 @@ TEST(IntNode, applyDiff) EXPECT_TRUE(result); EXPECT_DOUBLE_EQ(2, node.getValue()); } - diff --git a/src/tests/Interpolation_Test.cpp b/src/tests/Interpolation_Test.cpp index 000a771..782dc62 100644 --- a/src/tests/Interpolation_Test.cpp +++ b/src/tests/Interpolation_Test.cpp @@ -1,8 +1,7 @@ #include "BaseTestCase.h" #include "Interpolation.h" -TEST(Interpolation, trilinear) -{ +TEST(Interpolation, trilinear) { double p[8] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}; EXPECT_DOUBLE_EQ(0.0, Interpolation::trilinear(p, 0.0, 0.0, 0.0)); @@ -24,4 +23,3 @@ TEST(Interpolation, trilinear) EXPECT_DOUBLE_EQ(3.5, Interpolation::trilinear(p, 0.5, 0.5, 0.5)); } - diff --git a/src/tests/Layers_Test.cpp b/src/tests/Layers_Test.cpp index 4e9d605..b9d2961 100644 --- a/src/tests/Layers_Test.cpp +++ b/src/tests/Layers_Test.cpp @@ -3,31 +3,26 @@ #include "Layers.h" #include "PackStream.h" -DefinitionNode* _construc1(Layers*) -{ +DefinitionNode *_construc1(Layers *) { return new DefinitionNode(NULL, "test"); } -DefinitionNode* _construc2(Layers* parent) -{ - DefinitionNode* result = new DefinitionNode(parent, "test"); +DefinitionNode *_construc2(Layers *parent) { + DefinitionNode *result = new DefinitionNode(parent, "test"); return result; } -TEST(Layers, Constructor) -{ +TEST(Layers, Constructor) { Layers layers1(NULL, "test", _construc1); EXPECT_EQ(0, layers1.count()); } -TEST(Layers, NullLayer) -{ +TEST(Layers, NullLayer) { Layers layers1(NULL, "test", _construc1); - for (int i = -2; i < 5; i++) - { - DefinitionNode* layer = layers1.getLayer(0); - EXPECT_NE((DefinitionNode*)NULL, layer); + for (int i = -2; i < 5; i++) { + DefinitionNode *layer = layers1.getLayer(0); + EXPECT_NE((DefinitionNode *)NULL, layer); EXPECT_EQ(NULL, layer->getParent()); EXPECT_EQ(layer, layer->getRoot()); @@ -38,8 +33,7 @@ TEST(Layers, NullLayer) EXPECT_EQ(0, layers1.count()); } -TEST(Layers, copy) -{ +TEST(Layers, copy) { Layers layers1(NULL, "test", _construc2); layers1.addLayer(); EXPECT_EQ(1, layers1.count()); @@ -56,8 +50,7 @@ TEST(Layers, copy) EXPECT_NE(layers1.getLayer(0), layers2.getLayer(0)); } -TEST(Layers, maxLayerCount) -{ +TEST(Layers, maxLayerCount) { Layers layers1(NULL, "test", _construc1); layers1.setMaxLayerCount(2); @@ -78,8 +71,7 @@ TEST(Layers, maxLayerCount) EXPECT_EQ(2, layers1.count()); } -TEST(Layers, saveLoad) -{ +TEST(Layers, saveLoad) { PackStream *stream; Layers layers1(NULL, "test", _construc1); diff --git a/src/tests/LightingManager_Test.cpp b/src/tests/LightingManager_Test.cpp index 784c033..97a111d 100644 --- a/src/tests/LightingManager_Test.cpp +++ b/src/tests/LightingManager_Test.cpp @@ -4,16 +4,13 @@ #include "LightSource.h" #include "LightFilter.h" -class FakeLightSource: public LightSource -{ - virtual bool getLightsAt(std::vector &, const Vector3 &) const override - { +class FakeLightSource : public LightSource { + virtual bool getLightsAt(std::vector &, const Vector3 &) const override { return false; } }; -TEST(LightingManager, registerSource) -{ +TEST(LightingManager, registerSource) { LightingManager manager; FakeLightSource source; @@ -32,16 +29,13 @@ TEST(LightingManager, registerSource) EXPECT_EQ(0, manager.getSourcesCount()); } -class FakeLightFilter: public LightFilter -{ - virtual bool applyLightFilter(LightComponent &, const Vector3 &) override - { +class FakeLightFilter : public LightFilter { + virtual bool applyLightFilter(LightComponent &, const Vector3 &) override { return false; } }; -TEST(LightingManager, registerFilter) -{ +TEST(LightingManager, registerFilter) { LightingManager manager; FakeLightFilter filter; @@ -59,4 +53,3 @@ TEST(LightingManager, registerFilter) EXPECT_EQ(0, manager.getFiltersCount()); } - diff --git a/src/tests/NoiseGenerator_Test.cpp b/src/tests/NoiseGenerator_Test.cpp index ca26efc..1df25ac 100644 --- a/src/tests/NoiseGenerator_Test.cpp +++ b/src/tests/NoiseGenerator_Test.cpp @@ -2,9 +2,8 @@ #include "NoiseGenerator.h" -TEST(NoiseGenerator, getRange) -{ - NoiseGenerator* noise; +TEST(NoiseGenerator, getRange) { + NoiseGenerator *noise; double minvalue, maxvalue; noise = new NoiseGenerator(); @@ -21,10 +20,9 @@ TEST(NoiseGenerator, getRange) delete noise; } -TEST(NoiseGenerator, normalizeAmplitude) -{ +TEST(NoiseGenerator, normalizeAmplitude) { int x; - NoiseGenerator* noise; + NoiseGenerator *noise; noise = new NoiseGenerator(); @@ -32,8 +30,7 @@ TEST(NoiseGenerator, normalizeAmplitude) noise->addLevelsSimple(10, 1.0, -4.0, 4.0, 0.5); noise->validate(); noise->normalizeAmplitude(-1.0, 1.0, 0); - for (x = 0; x < 1000; x++) - { + for (x = 0; x < 1000; x++) { double value = noise->get1DTotal(0.01 * (double)x); ASSERT_DOUBLE_IN_RANGE(value, -1.0, 1.0); } @@ -43,8 +40,7 @@ TEST(NoiseGenerator, normalizeAmplitude) noise->addLevelsSimple(10, 1.0, -5.0, 5.0, 0.5); noise->validate(); noise->normalizeAmplitude(0.0, 1.0, 0); - for (x = 0; x < 1000; x++) - { + for (x = 0; x < 1000; x++) { double value = noise->get1DTotal(0.01 * (double)x); ASSERT_DOUBLE_IN_RANGE(value, 0.0, 1.0); } @@ -54,8 +50,7 @@ TEST(NoiseGenerator, normalizeAmplitude) noise->addLevelsSimple(10, 1.0, 0.0, 10.0, 0.0); noise->validate(); noise->normalizeAmplitude(0.0, 1.0, 0); - for (x = 0; x < 1000; x++) - { + for (x = 0; x < 1000; x++) { double value = noise->get1DTotal(0.01 * (double)x); ASSERT_DOUBLE_IN_RANGE(value, 0.0, 1.0); } @@ -65,8 +60,7 @@ TEST(NoiseGenerator, normalizeAmplitude) noise->addLevelsSimple(3, 1.0, -2.0, 8.0, 0.3); noise->validate(); noise->normalizeAmplitude(-2.0, 4.0, 0.0); - for (x = 0; x < 1000; x++) - { + for (x = 0; x < 1000; x++) { double value = noise->get1DTotal(0.01 * (double)x); ASSERT_DOUBLE_IN_RANGE(value, -2.0, 4.0); } diff --git a/src/tests/PackStream_Test.cpp b/src/tests/PackStream_Test.cpp index 92b5c4e..29261cb 100644 --- a/src/tests/PackStream_Test.cpp +++ b/src/tests/PackStream_Test.cpp @@ -2,20 +2,18 @@ #include "PackStream.h" -TEST(PackStream, All) -{ - PackStream* stream; +TEST(PackStream, All) { + PackStream *stream; int i; int data_i; double data_d; - const char* data_s; + const char *data_s; char buffer[100]; /* Writing to pack */ stream = new PackStream(); stream->bindToFile("/tmp/test_paysages_pack", true); - for (i = 0; i < 5; i++) - { + for (i = 0; i < 5; i++) { data_i = i; stream->write(&data_i); @@ -32,8 +30,7 @@ TEST(PackStream, All) /* Reading from pack */ stream = new PackStream(); stream->bindToFile("/tmp/test_paysages_pack"); - for (i = 0; i < 5; i++) - { + for (i = 0; i < 5; i++) { stream->read(&data_i); ASSERT_EQ(i, data_i); @@ -50,11 +47,10 @@ TEST(PackStream, All) delete stream; } -TEST(PackStream, Skip) -{ - PackStream* stream; - int i1=1, i2=2, i3=3; - double d1=1.1, d2=2.2; +TEST(PackStream, Skip) { + PackStream *stream; + int i1 = 1, i2 = 2, i3 = 3; + double d1 = 1.1, d2 = 2.2; stream = new PackStream(); stream->bindToFile("/tmp/test_paysages_pack", true); diff --git a/src/tests/Rasterizer_Test.cpp b/src/tests/Rasterizer_Test.cpp index 8e7f0c9..80fda81 100644 --- a/src/tests/Rasterizer_Test.cpp +++ b/src/tests/Rasterizer_Test.cpp @@ -8,27 +8,21 @@ #include "Color.h" #include "CanvasPortion.h" -class FakeRasterizer: public Rasterizer -{ -public: - FakeRasterizer(SoftwareRenderer *renderer): Rasterizer(renderer, NULL, 0, COLOR_WHITE) - { +class FakeRasterizer : public Rasterizer { + public: + FakeRasterizer(SoftwareRenderer *renderer) : Rasterizer(renderer, NULL, 0, COLOR_WHITE) { } - virtual Color shadeFragment(const CanvasFragment &, const CanvasFragment *) const override - { + virtual Color shadeFragment(const CanvasFragment &, const CanvasFragment *) const override { return COLOR_RED; } - virtual int prepareRasterization() override - { + virtual int prepareRasterization() override { return 0; } - virtual void rasterizeToCanvas(CanvasPortion *) override - { + virtual void rasterizeToCanvas(CanvasPortion *) override { } }; -TEST(Rasterizer, autoSplitNearFrustum) -{ +TEST(Rasterizer, autoSplitNearFrustum) { Scenery scenery; scenery.getCamera()->setLocation(Vector3(0.0, 5.0, 0.0)); scenery.getCamera()->setTarget(Vector3(0.0, 5.0, 1.0)); diff --git a/src/tests/RenderProgress_Test.cpp b/src/tests/RenderProgress_Test.cpp index f929f97..fb02ddd 100644 --- a/src/tests/RenderProgress_Test.cpp +++ b/src/tests/RenderProgress_Test.cpp @@ -2,8 +2,7 @@ #include "RenderProgress.h" -TEST(RenderProgress, RecursiveSections) -{ +TEST(RenderProgress, RecursiveSections) { RenderProgress progress(2); EXPECT_DOUBLE_EQ(0.0, progress.get()); diff --git a/src/tests/Scenery_Test.cpp b/src/tests/Scenery_Test.cpp index d7f4491..e7ad5a8 100644 --- a/src/tests/Scenery_Test.cpp +++ b/src/tests/Scenery_Test.cpp @@ -6,8 +6,7 @@ #include "AtmosphereDefinition.h" #include "FloatNode.h" -TEST(Scenery, saveGlobal) -{ +TEST(Scenery, saveGlobal) { Scenery scenery1; scenery1.autoPreset(); scenery1.getTerrain()->propWaterHeight()->setValue(0.2); diff --git a/src/tests/SpaceSegment_Test.cpp b/src/tests/SpaceSegment_Test.cpp index c7c219f..4916795 100644 --- a/src/tests/SpaceSegment_Test.cpp +++ b/src/tests/SpaceSegment_Test.cpp @@ -3,20 +3,18 @@ #include "SpaceSegment.h" #include "SpaceGridIterator.h" -class CollectGridIterator: public SpaceGridIterator -{ -public: +class CollectGridIterator : public SpaceGridIterator { + public: std::vector locations; -protected: - virtual bool onCell(int x, int y, int z) override - { + + protected: + virtual bool onCell(int x, int y, int z) override { locations.push_back(Vector3(x, y, z)); return true; } }; -TEST(SpaceSegment, iterateOnGrid) -{ +TEST(SpaceSegment, iterateOnGrid) { CollectGridIterator it; SpaceSegment segment(Vector3(0.5, 1.5, 0.0), Vector3(2.5, 0.5, 0.0)); segment.iterateOnGrid(it); @@ -28,8 +26,7 @@ TEST(SpaceSegment, iterateOnGrid) EXPECT_VECTOR3_COORDS(it.locations[3], 2.0, 0.0, 0.0); } -TEST(SpaceSegment, iterateOnGrid_Corner) -{ +TEST(SpaceSegment, iterateOnGrid_Corner) { CollectGridIterator it; SpaceSegment segment(Vector3(0.5, 0.5, 0.5), Vector3(2.5, 2.5, 2.5)); segment.iterateOnGrid(it); @@ -40,8 +37,7 @@ TEST(SpaceSegment, iterateOnGrid_Corner) EXPECT_VECTOR3_COORDS(it.locations[6], 2.0, 2.0, 2.0); } -TEST(SpaceSegment, iterateOnGrid_OneCell) -{ +TEST(SpaceSegment, iterateOnGrid_OneCell) { CollectGridIterator it; SpaceSegment segment(Vector3(8.1, 8.2, 8.9), Vector3(8.9, 8.3, 8.6)); segment.iterateOnGrid(it); @@ -50,8 +46,7 @@ TEST(SpaceSegment, iterateOnGrid_OneCell) EXPECT_VECTOR3_COORDS(it.locations[0], 8.0, 8.0, 8.0); } -TEST(SpaceSegment, iterateOnGrid_Negative) -{ +TEST(SpaceSegment, iterateOnGrid_Negative) { CollectGridIterator it; SpaceSegment segment(Vector3(-8.1, -8.2, -8.9), Vector3(-8.9, -8.3, -8.6)); segment.iterateOnGrid(it); diff --git a/src/tests/Sphere_Test.cpp b/src/tests/Sphere_Test.cpp index afdef99..47a15ea 100644 --- a/src/tests/Sphere_Test.cpp +++ b/src/tests/Sphere_Test.cpp @@ -3,8 +3,7 @@ #include "InfiniteRay.h" #include "Sphere.h" -TEST(Sphere, checkRayIntersection) -{ +TEST(Sphere, checkRayIntersection) { Sphere sphere(Vector3(2.0, 1.0, 1.0), 0.5); int intersect_count; diff --git a/src/tests/TerrainPainting_Test.cpp b/src/tests/TerrainPainting_Test.cpp index c3a6af5..925d9f9 100644 --- a/src/tests/TerrainPainting_Test.cpp +++ b/src/tests/TerrainPainting_Test.cpp @@ -10,23 +10,20 @@ /* Noise sin period is defined at 20.0 */ #define X_FACTOR (M_PI / 10.0) -static double _noise1dMock(double x) -{ +static double _noise1dMock(double x) { return sin(x * X_FACTOR) * 0.5 + 0.5; } -static double _noise2dMock(double x, double) -{ +static double _noise2dMock(double x, double) { return sin(x * X_FACTOR) * 0.5 + 0.5; } -static double _noise3dMock(double x, double, double) -{ +static double _noise3dMock(double x, double, double) { return sin(x * X_FACTOR) * 0.5 + 0.5; } class TerrainPainting_Test : public BaseTestCase { -protected: + protected: virtual void SetUp() { terrain = new TerrainDefinition(NULL); terrain->height = 3.0; @@ -39,17 +36,15 @@ protected: terrain->_height_noise->setCustomFunction(_noise1dMock, _noise2dMock, _noise3dMock); } - virtual void TearDown() - { + virtual void TearDown() { delete terrain; } - TerrainDefinition* terrain; + TerrainDefinition *terrain; NoiseState noise_state; }; -TEST_F(TerrainPainting_Test, grid) -{ +TEST_F(TerrainPainting_Test, grid) { /* Test base grid */ EXPECT_DOUBLE_EQ(0.0, terrain->getGridHeight(0, 0, 0)); EXPECT_DOUBLE_EQ(0.0, terrain->getGridHeight(0, 1, 0)); @@ -75,8 +70,9 @@ TEST_F(TerrainPainting_Test, grid) EXPECT_DOUBLE_EQ(terrain->getInterpolatedHeight(1.0, 0.0, 1, 0), 3.0 * sin(1.0 * X_FACTOR)); } -static void _checkBrushResultSides(TerrainDefinition* terrain, PaintedGridBrush*, double center, double midhard, double hard, double midsoft, double soft, double exter, double neg_midhard, double neg_hard, double neg_midsoft, double neg_soft, double neg_exter) -{ +static void _checkBrushResultSides(TerrainDefinition *terrain, PaintedGridBrush *, double center, double midhard, + double hard, double midsoft, double soft, double exter, double neg_midhard, + double neg_hard, double neg_midsoft, double neg_soft, double neg_exter) { EXPECT_DOUBLE_EQ(terrain->getGridHeight(0, 0, 1), center); EXPECT_DOUBLE_EQ(terrain->getGridHeight(1, 0, 1), midhard); @@ -92,20 +88,18 @@ static void _checkBrushResultSides(TerrainDefinition* terrain, PaintedGridBrush* EXPECT_DOUBLE_EQ(terrain->getGridHeight(-5, 0, 1), neg_exter); } -static void _checkBrushResult(TerrainDefinition* terrain, PaintedGridBrush* brush, double center, double midhard, double hard, double midsoft, double soft, double exter, int mirror) -{ - if (mirror) - { - _checkBrushResultSides(terrain, brush, center, midhard, hard, midsoft, soft, exter, -midhard, -hard, -midsoft, -soft, -exter); - } - else - { - _checkBrushResultSides(terrain, brush, center, midhard, hard, midsoft, soft, exter, midhard, hard, midsoft, soft, exter); +static void _checkBrushResult(TerrainDefinition *terrain, PaintedGridBrush *brush, double center, double midhard, + double hard, double midsoft, double soft, double exter, int mirror) { + if (mirror) { + _checkBrushResultSides(terrain, brush, center, midhard, hard, midsoft, soft, exter, -midhard, -hard, -midsoft, + -soft, -exter); + } else { + _checkBrushResultSides(terrain, brush, center, midhard, hard, midsoft, soft, exter, midhard, hard, midsoft, + soft, exter); } } -TEST_F(TerrainPainting_Test, brush_flatten) -{ +TEST_F(TerrainPainting_Test, brush_flatten) { /* Set up */ PaintedGridBrush brush(2.0, 2.0, 4.0); terrain->height = 1.0; @@ -134,8 +128,7 @@ TEST_F(TerrainPainting_Test, brush_flatten) _checkBrushResult(terrain, &brush, 0.05, 0.05, 0.05, 0.025, 0.0, 0.0, 0); } -TEST_F(TerrainPainting_Test, brush_reset) -{ +TEST_F(TerrainPainting_Test, brush_reset) { /* Set up */ PaintedGridBrush brush(2.0, 2.0, 4.0); PaintedGridBrush brush_full(4.0, 0.0, 4.0); diff --git a/src/tests/Vector3_Test.cpp b/src/tests/Vector3_Test.cpp index c6be931..fbd071a 100644 --- a/src/tests/Vector3_Test.cpp +++ b/src/tests/Vector3_Test.cpp @@ -1,16 +1,14 @@ #include "BaseTestCase.h" #include "Vector3.h" -TEST(Vector3, midPointTo) -{ +TEST(Vector3, midPointTo) { Vector3 v1(1.0, 2.0, 8.0); Vector3 v2(4.0, 2.5, -1.0); Vector3 vm = v1.midPointTo(v2); EXPECT_VECTOR3_COORDS(vm, 2.5, 2.25, 3.5); } -TEST(Vector3, randomInSphere) -{ +TEST(Vector3, randomInSphere) { Vector3 v; v = Vector3::randomInSphere(); diff --git a/src/tests/VertexArray_Test.cpp b/src/tests/VertexArray_Test.cpp index 1b29e6d..ba061d4 100644 --- a/src/tests/VertexArray_Test.cpp +++ b/src/tests/VertexArray_Test.cpp @@ -2,24 +2,18 @@ #include "VertexArray.h" -class TestVertex -{ -public: +class TestVertex { + public: float uv[2]; int loc[3]; - bool operator==(const TestVertex &other) const - { - return other.uv[0] == uv[0] - and other.uv[1] == uv[1] - and other.loc[0] == loc[0] - and other.loc[1] == loc[1] - and other.loc[2] == loc[2]; + bool operator==(const TestVertex &other) const { + return other.uv[0] == uv[0] and other.uv[1] == uv[1] and other.loc[0] == loc[0] and other.loc[1] == loc[1] and + other.loc[2] == loc[2]; } }; -TEST(VertexArray, grid) -{ +TEST(VertexArray, grid) { VertexArray array; array.setGridSize(3); @@ -36,8 +30,7 @@ TEST(VertexArray, grid) EXPECT_EQ(v1, vgot); } -TEST(VertexArray, gridIndices) -{ +TEST(VertexArray, gridIndices) { VertexArray array; array.setGridSize(3); @@ -66,8 +59,7 @@ TEST(VertexArray, gridIndices) EXPECT_EQ(4, array.getIndex(14)); } -TEST(VertexArray, gridIndicesStride) -{ +TEST(VertexArray, gridIndicesStride) { VertexArray array; array.setGridSize(5); diff --git a/src/tests/Zone_Test.cpp b/src/tests/Zone_Test.cpp index 4315c10..52e6be0 100644 --- a/src/tests/Zone_Test.cpp +++ b/src/tests/Zone_Test.cpp @@ -4,21 +4,19 @@ #include "Vector3.h" class Zone_Test : public BaseTestCase { -protected: + protected: virtual void SetUp() { zone = new Zone; } - virtual void TearDown() - { + virtual void TearDown() { delete zone; } - Zone* zone; + Zone *zone; }; -TEST_F(Zone_Test, absolute_height) -{ +TEST_F(Zone_Test, absolute_height) { zone->addHeightRangeQuick(1.0, -1.0, 2.0, 5.0, 6.0); EXPECT_DOUBLE_EQ(zone->getValue(Vector3(0.0, -10.0, 0.0), VECTOR_UP), 0.0); @@ -39,8 +37,7 @@ TEST_F(Zone_Test, absolute_height) EXPECT_DOUBLE_EQ(zone->getValue(Vector3(0.0, 150.0, 0.0), VECTOR_UP), 0.0); } -TEST_F(Zone_Test, relative_height) -{ +TEST_F(Zone_Test, relative_height) { zone->addHeightRangeQuick(1.0, 0.2, 0.3, 0.6, 0.9); zone->setRelativeHeight(-2.0, 2.0, 8.0); diff --git a/src/tests/main.cpp b/src/tests/main.cpp index d4e6e7f..3b332bb 100644 --- a/src/tests/main.cpp +++ b/src/tests/main.cpp @@ -3,12 +3,10 @@ #include #include "Logs.h" -void noMessageOutput(QtMsgType, const QMessageLogContext&, const QString&) -{ +void noMessageOutput(QtMsgType, const QMessageLogContext &, const QString &) { } -int main(int argc, char **argv) -{ +int main(int argc, char **argv) { int result; qInstallMessageHandler(noMessageOutput); @@ -19,4 +17,3 @@ int main(int argc, char **argv) return result; } -