From 0a0c03847ad7428bec5394df0f663a206ad37041 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 8 Apr 2024 18:24:38 +0300 Subject: [PATCH] [h4] Added Mendelbrot shader --- src/main.cpp | 6 +++--- src/shading.cpp | 29 +++++++++++++++++++++++++++++ src/shading.h | 14 ++++++++++++++ 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 5ec299f..594fb70 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -47,10 +47,10 @@ Sphere sphere(Vector(-10, 60, 0), 30); void setupScene() { - camera.pos.set(0, 60, -120); + camera.pos.set(101.82, 80, -7436.4); + camera.pitch = -90.0; camera.beginFrame(); - nodes.push_back(Node{ new Plane(15), new Checker(Color(0, 0, 0.8), Color(0.2, 0.3, 0.6))}); - nodes.push_back(Node{ &sphere, new Checker(Color(0.8, 0, 0), Color(0.6, 0.4, 0.1), 9)}); + nodes.push_back(Node{ new Plane(15), new Mendelbrot()}); lightPos.set(+30, +100, -70); lightColor.setColor(1, 1, 1); lightIntensity = 10000.0; diff --git a/src/shading.cpp b/src/shading.cpp index c4c17ff..41543b1 100644 --- a/src/shading.cpp +++ b/src/shading.cpp @@ -24,6 +24,7 @@ #include "shading.h" #include "main.h" +#include Vector lightPos; Color lightColor; @@ -57,3 +58,31 @@ Color Checker::computeColor(Ray ray, const IntersectionInfo& info) Color ambient = toUse * AMBIENT_LIGHT; return direct + ambient; } + +double nfmod(double a, double b) { + return fmod(fmod(a, b) + b, b); +} +double limit(double val, double low, double high) { + return nfmod(val - low, high - low) + low; +} + +Color linearInterpolation(double alpha, const Color& a, const Color& b) { + return a*(1.0-alpha) + b*alpha; +} + +Color Mendelbrot::computeColor(Ray ray, const IntersectionInfo& info) { + double u = limit(info.u / scaling, -2.00, 0.47); + double v = limit(info.v / scaling, -1.12, 1.12); + + double x = 0.0, y = 0.0; + for (int i = 0; i < ITERATIONS; i++) { + if (sqr(x) + sqr(y) > 4) { + return linearInterpolation((double)i / (double)ITERATIONS, color1, color2); + } + + double temp = sqr(x) - sqr(y) + u; + y = 2 * x * y + v; + x = temp; + } + return color2; +} diff --git a/src/shading.h b/src/shading.h index b896b6b..857834c 100644 --- a/src/shading.h +++ b/src/shading.h @@ -54,3 +54,17 @@ public: float scaling = 20.0f): col1(col1), col2(col2), scaling(scaling) {} virtual Color computeColor(Ray ray, const IntersectionInfo& info) override; }; + +class Mendelbrot : public Shader { + const int ITERATIONS = 100; + +public: + Color color1, color2; + double scaling; + + Mendelbrot(Color color1 = Color(0.0, 0.0, 0.1), Color color2 = Color(1.0, 0.4, 0.0), double scaling = 10000.0) + : color1(color1), color2(color2), scaling(scaling) + {} + + virtual Color computeColor(Ray ray, const IntersectionInfo& info) override; +}; -- 2.42.0