Search code examples
javascript3draytracing

Why do streaks appear in my ray marching rendering?


I'm trying to implement the ray marching algorithm. There is a sphere, and the camera is looking at it.

Everything works, but there are streaks in the result, and I have no idea why. Jsfiddle: link

Image:

enter image description here

Code:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// position and radius of the sphere
var cx = 100;
var cy = 100;
var cz = 100;
var cr = 50;

// direction of the marching 
var dx = 0;
var dy = 0;
var dz = 1;

// maximum steps, and distance
var MaximumRaySteps = 50;
var MinimumDistance = .005;

// calculating the distance from the surface of the sphere
var DistanceEstimator = function(x, y, z) {
    var a=x-cx;
    var b=y-cy;
    var c=z-cz;

    var dist = Math.sqrt(a*a + b*b + c*c);

    return dist-cr;
};

// calculate shading on a pixel (1=white, 0=black)
var trace = function(x, y) {
    var totalDistance = 0.0;
    var steps;
    for (steps=0; steps < MaximumRaySteps; steps++) {
        var distance = DistanceEstimator(x, y, totalDistance);
        totalDistance += distance;
        if (distance < MinimumDistance) {
            break;
        }
    }
    return 1.0-steps/MaximumRaySteps;
};

// iterate over the pixels
(function() {
    for(var y=0; y<200; y++) {
        for(var x=0; x<200; x++) {
            ctx.fillStyle = '#'+(Math.floor(trace(x,y)*0xFF)*0x010101).toString(16);
            ctx.fillRect(x,y,1,1);

        }
    }
})();

Solution

  • This removes your streaks, which helps clear up what's happening:

    (function() {
        for(var y=0; y<200; y++) {
            for(var x=0; x<200; x++) {
                ctx.fillStyle = '#000000';
                ctx.fillStyle = '#'+(Math.floor(trace(x,y)*0xFF)*0x010101).toString(16);
                ctx.fillRect(x,y,1,1);
            }
        }
    })();
    

    Your color calculation is producing #0. When you try to assign that value to ctx.fillStyle, the assignment is failing (presumably due to validity checking in the canvas setter function for that property looking for a full RGB hex value, such as #000 or #000000) and it's holding on to the existing value instead. That's why you're seeing the streaks - it's repeating the last 'valid' color assignment it got.