FracGen.cpp 11.1 KB
Newer Older
Jehferson Mello's avatar
Jehferson Mello committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include "FracGen.hpp"

#include <iostream>
#include <cfloat>
#include <functional>
#include <atomic>
#include <vector>

#include <tbb/parallel_for.h>
#include <tbb/blocked_range2d.h>

//static Vec3f boxMaxes;
//static Vec3f boxMins;


using  estimatorFunction = std::function<float(Vec3f)>;


/******************************************************************************
 *
 * Tweakable parameters
 *
 ******************************************************************************/

static constexpr const size_t maxRaySteps     = 7500;
static constexpr const float collisionMinDist = 0.00055f;
static constexpr const float  cameraZ         = -3.8f;

// coulouring parameters

31 32 33
static constexpr const float hueFactor   = -10.0f;
static constexpr const int   hueOffset   = 195;
static constexpr const float valueFactor = 62;
Jehferson Mello's avatar
Jehferson Mello committed
34 35
static constexpr const float valueRange  = 1.0f;
static constexpr const float valueClamp  = 0.9f;
36
static constexpr const float satValue    = 0.7f;
Jehferson Mello's avatar
Jehferson Mello committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
static constexpr const float bgValue     = 0.05f;
static constexpr const float bgAlpha     = 1.0f;

// Mandelbox constants
static constexpr const float fixedRadiusSq  = 2.2f;
static constexpr const float minRadiusSq    = 0.8f;
static constexpr const float foldingLimit   = 1.45;
static constexpr const float boxScale       = -3.5f;
static constexpr const size_t boxIterations = 30;


/******************************************************************************
 *
 * Distance estimator functions and helpers
 *
 ******************************************************************************/



void sphereFold(Vec3f& z, float& dz)
{
    float r2 = z.sqMod();
    if ( r2 < minRadiusSq)
    {
        // linear inner scaling
        float temp = (fixedRadiusSq/minRadiusSq);
        z *= temp;
        dz *= temp;
    }
    else if(r2<fixedRadiusSq)
    {
        // this is the actual sphere inversion
        float temp =(fixedRadiusSq/r2);
        z *= temp;
        dz*= temp;
    }
}

void boxFold(Vec3f& z)
{
    z = z.clamp(-foldingLimit, foldingLimit)* 2.0f - z;
}

float boxDist(const Vec3f& p)
{
    /**
     * Distance estimator for a mandelbox
     *
     * Distance estimator adapted from
     * https://http://blog.hvidtfeldts.net/index.php/2011/11/distance-estimated-3d-fractals-vi-the-mandelbox/
     */
    const Vec3f& offset = p;
    float dr = boxScale;
    Vec3f z{p};
    for (size_t n = 0; n < boxIterations; n++)
    {
        boxFold(z);       // Reflect
        sphereFold(z,dr);    // Sphere Inversion

        z = z * boxScale + offset;  // Scale & Translate
        dr = dr * std::abs(boxScale) + 1.0f;


    }
    float r = z.mod();
    return r/std::abs(dr);
}


float bulbDist(const Vec3f& p)
{

    /**
     * Distance estimator for a mandelbulb
     *
     * Distance estimator adapted from
     * https://www.iquilezles.org/www/articles/mandelbulb/mandelbulb.htm
     * https://www.shadertoy.com/view/ltfSWn
     */

    Vec3f w = p;
    float m = w.sqMod();

    //vec4 trap = vec4(abs(w),m);
    float dz = 3.0f;


    for( int i=0; i<4; i++ )
    {
#if 1
        float m2 = m*m;
        float m4 = m2*m2;
        dz = 8.0f*sqrt(m4*m2*m)*dz + 1.0f;

        float x = w.X(); float x2 = x*x; float x4 = x2*x2;
        float y = w.Y(); float y2 = y*y; float y4 = y2*y2;
        float z = w.Z(); float z2 = z*z; float z4 = z2*z2;

        float k3 = x2 + z2;
        float k2 = 1/sqrt( k3*k3*k3*k3*k3*k3*k3 );
        float k1 = x4 + y4 + z4 - 6.0f*y2*z2 - 6.0f*x2*y2 + 2.0f*z2*x2;
        float k4 = x2 - y2 + z2;

        w.setX(p.X() +  64.0f*x*y*z*(x2-z2)*k4*(x4-6.0f*x2*z2+z4)*k1*k2);
        w.setY(p.Y() + -16.0f*y2*k3*k4*k4 + k1*k1);
        w.setZ(p.Z() +  -8.0f*y*k4*(x4*x4 - 28.0f*x4*x2*z2 + 70.0f*x4*z4 - 28.0f*x2*z2*z4 + z4*z4)*k1*k2);
#else
        dz = 8.0*pow(sqrt(m),7.0)*dz + 1.0;
        //dz = 8.0*pow(m,3.5)*dz + 1.0;

        float r = w.mod();
        float b = 8.0*acos( w.Y()/r);
        float a = 8.0*atan2( w.X(), w.Z() );
        w = p + Vec3f( sin(b)*sin(a), cos(b), sin(b)*cos(a) ) * pow(r,8.0);
#endif

       // trap = min( trap, vec4(abs(w),m) );

        m = w.sqMod();
        if( m > 256.0f )
            break;
    }

    return 0.25f*log(m)*sqrt(m)/dz;
}

float sphereDist(Vec3f p)
{
    float radius = 2.f;
    return p.mod() - radius;
}

/******************************************************************************
 *
 * Coulouring functions and helpers
 *
 ******************************************************************************/

RGBA HSVtoRGB(int H, float S, float V)
{

    /**
     * adapted from
     * https://gist.github.com/kuathadianto/200148f53616cbd226d993b400214a7f
     */

    RGBA output;
    float C = S * V;
    float X = C * (1 - std::abs(std::fmod(H / 60.0, 2) - 1));
    float m = V - C;
    float Rs, Gs, Bs;

    if(H >= 0 && H < 60)
    {
        Rs = C;
        Gs = X;
        Bs = 0;
    }
    else if(H >= 60 && H < 120)
    {
        Rs = X;
        Gs = C;
        Bs = 0;
    }
    else if(H >= 120 && H < 180)
    {
        Rs = 0;
        Gs = C;
        Bs = X;
    }
    else if(H >= 180 && H < 240)
    {
        Rs = 0;
        Gs = X;
        Bs = C;
    }
    else if(H >= 240 && H < 300)
    {
        Rs = X;
        Gs = 0;
        Bs = C;
    }
    else {
        Rs = C;
        Gs = 0;
        Bs = X;
    }

    output.setR(Rs + m);
    output.setG(Gs + m);
    output.setB(Bs + m);
    output.setA( 1.0f );

    return output;
}

RGBA getColour(const Vec4f& steps)
{
    RGBA colour;

    Vec3f position(steps.X(),steps.Y(),steps.Z());

239
    static const RGBA background(bgValue,bgValue,bgValue,bgAlpha);
Jehferson Mello's avatar
Jehferson Mello committed
240

241
    if(steps.W() >= maxRaySteps)
Jehferson Mello's avatar
Jehferson Mello committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    {
        return background;
    }

//        This is a good place to float check your bounds if you need to

//        boxMins.setX(std::min(boxMins.X(),position.X()));
//        boxMins.setY(std::min(boxMins.Y(),position.Y()));
//        boxMins.setZ(std::min(boxMins.Z(),position.Z()));

//        boxMaxes.setX(std::max(boxMaxes.X(),position.X()));
//        boxMaxes.setY(std::max(boxMaxes.Y(),position.Y()));
//        boxMaxes.setZ(std::max(boxMaxes.Z(),position.Z()));

    float saturation = satValue;
    int hue = std::abs((static_cast<int>(position.Z() * hueFactor) + hueOffset) % 360);
    float value = valueRange*(1.0f - std::min(steps.W()*valueFactor/maxRaySteps, valueClamp));

    colour = HSVtoRGB(hue, saturation, value);

//    Simplest colouring, based only on steps (roughly distance from camera)
263
    //colour = RGBA(value,value,value,1.0f);
Jehferson Mello's avatar
Jehferson Mello committed
264 265 266 267 268 269 270 271 272 273

    return colour;
}

/******************************************************************************
 *
 * Ray marching functions and helpers
 *
 ******************************************************************************/

274
Vec4f trace(const Camera& cam, const Screen& s, size_t x, size_t y, const estimatorFunction& f)
Jehferson Mello's avatar
Jehferson Mello committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
{
    /**
     * This function taken from
     * http://blog.hvidtfeldts.net/index.php/2011/06/distance-estimated-3d-fractals-part-i/
     */

    float totalDistance = 0.0f;
    unsigned int steps;

    Vec3f pixelPosition = s.topLeft + Vec3f{s.pixelWidth*x, s.pixelHeight * y, 0.f};

    Vec3f rayDir = pixelPosition -  static_cast<Vec3f>(cam.pos);
    rayDir.normalise();

    Vec3f p;
    for (steps=0; steps < maxRaySteps; steps++)
    {
        p = cam.pos + (rayDir * totalDistance);
        float distance = f(p);
        totalDistance += distance;
        if (distance < collisionMinDist) break;
    }
    //return both the steps and the actual position in space for colouring purposes
    return Vec4f{p,static_cast<float>(steps)};
}

void traceRegion(colourVec& data,
                 const Camera& cam, const Screen& scr,
                 const estimatorFunction& f,
                 const tbb::blocked_range2d<size_t,size_t>& range)
{
    for(size_t h = range.rows().begin(); h < range.rows().end(); h++)
    {
        for(size_t w = range.cols().begin(); w < range.cols().end(); w++ )
        {
            data[(h*scr.width)+w] = getColour(trace(cam, scr, w, h, f));
        }
    }
}

/******************************************************************************
 *
 * Thread spawning section
 *
 ******************************************************************************/

bool FracGen::Generate(int width, int height)
{

    bool finishedGeneration = false;
    int heightStep = bench ? height : 10;

    estimatorFunction bulb(bulbDist);
    estimatorFunction box(boxDist);
    estimatorFunction sphere(sphereDist);

    /*
     * calculate the rectangle which represents the screen (camera z near) in object space
     * No need to have an actual general camera so I'm just assuming the camera
     * always sits on the Z axis and always has (0,1,0) as it's up vector

     * This allows me to cheat a lot and not have to actually go into the
     * linear algebra side and write something like gluUnproject
     */
    Screen s;

    Vec3f screenPlaneOrigin{cam->pos.X(),cam->pos.Y(),cam->pos.Z() + cam->near};
    float screenPlaneHeight = 2*(cam->near*sin(cam->fovY/2));
    screenPlaneHeight = screenPlaneHeight < 0 ? -screenPlaneHeight : screenPlaneHeight;
    float screenPlaneWidth = screenPlaneHeight * cam->AR;
    // if 0,0 is top left, pixel height needs to be a negative
    s.width  = width;
    s.height = height;
    s.pixelHeight = (-1.f) * screenPlaneHeight / s.height;
    s.pixelWidth = screenPlaneWidth / s.width;
    s.topLeft = Vec3f {screenPlaneOrigin.X() - (screenPlaneWidth/2),
                       screenPlaneOrigin.Y() + (screenPlaneHeight/2),
                       screenPlaneOrigin.Z()                          };


    auto tbbTrace = [this, s, f = box](const tbb::blocked_range2d<size_t,size_t>& range)
            {traceRegion(*(this->outBuffer), *(this->cam), s, f, range); };


    // Minor optimization in TBB: Since we can define the range here, we don't need to check bounds in
    // traceRegion. This is very similar to how SYCL and OpenCL do things
361
    tbb::blocked_range2d<size_t,size_t> range(lastHeight, std::min(lastHeight+heightStep, static_cast<size_t>(height)), 0, width);
Jehferson Mello's avatar
Jehferson Mello committed
362 363
    tbb::parallel_for(range, tbbTrace);

364
    lastHeight+= heightStep;
Jehferson Mello's avatar
Jehferson Mello committed
365 366 367 368 369 370
    /*
     * TBB doesn't seem to like the way of doing things where I know how
     * many tasks there are and am collecting the return from them.
     * At least not in the initial tutorials and beginner documentation
     */

371
    if (lastHeight >=static_cast<size_t>(height) )
Jehferson Mello's avatar
Jehferson Mello committed
372
    {
373
        lastHeight = 0;
Jehferson Mello's avatar
Jehferson Mello committed
374 375 376 377 378 379 380 381 382
        finishedGeneration = true;
    }

    return finishedGeneration;
}

FracGen::FracGen(bool benching, size_t width, size_t height)
    : bench{benching}
    , cam{new Camera}
383
    , lastHeight{0}
Jehferson Mello's avatar
Jehferson Mello committed
384 385 386 387 388 389
{

    outBuffer = std::make_shared< colourVec >(width*height);
    cam->AR = static_cast<double>(width)/static_cast<double>(height);
    // Position here is more or less ignored. It's used for initial screen calculation but the
    // rays are launched from a different distance, specified in the .cl file
390 391 392 393
    cam->pos = Vec3f{0, 0, cameraZ};
    cam->target = Vec3f{0,0,0};
    cam->up = Vec3f{0,1,0};
    cam->near = 0.1f;
Jehferson Mello's avatar
Jehferson Mello committed
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
    cam->fovY = 45;

    static bool once = false;
    if(!bench || !once)
    {
      std::cout << "Running on TBB "<< TBB_VERSION_MAJOR <<"."<< TBB_VERSION_MINOR << std::endl;
      once = true;
    }
}

FracGen::~FracGen()
{}