Recursive raytracer in 35 lines of JavaScript
jsfiddle.net
jsfiddle.net
> Their combination of a simple algorithm and stunning results are hard to beat.
that's exactly what fascinates me about raytracing. It's pretty straightforward, you literally emulate the light bouncing around, but given enough resources the results can be surprisingly good-looking.
Ray tracing, although very powerful, has some limitations because it goes the other way: It casts rays from the sensor into the scene.
From your comment and another one here, it seems to be the case that actually some of the photons that don't hit the sensor still affect the image (either that, or you can't get back to the source starting at the sensor for some of the photons). In other words, if a light source emits a trillion photons everywhere in the room, and your sensor (the idealized camera) catches ten million photons, then it's not strictly equivalent to trace back the ten million maths to the light source, and ignore the ones that didn't make it to the idealized camera.
If it were equivalent, you wouldn't need "photon tracing and ray tracing" or bidirectionality.
But I'm struggling at where the symmetry breaks down, since it seems that tracing a path back from the sensor along the same angles should produce the same result as tracing it forward from the light source - for the photons that directly or indirectly (after a certain number of bounces or passing through the materials) make it to the idealized camera.
But the ones that don't make it to the idealized camera - how can they still affect the frame? Or (equivalently), when is it the case that you can trace it forward to the camera but not backward from the camera?
Why do you need bidirectionality? Where does the symmetry break down?
When you do ray tracing, you don't immediately know if 10 million photons were captured. You know how many rays you are going to send based on the resolution of the image. This also means there's issues with say light coming from narrow apertures because you limit yourself to a finite number of rays.
If you use photon tracing and a light source sends 10 million photons and 70,000 are absorbed that's 70,000 data points to define the image which may be plotted on a 200x200 canvas. If you use ray tracing with a 200x200 canvas you will have the same size of image, but only get 40,000 samples. Even if you expand the size of the canvas, there may be some photons which can reach the camera but whose path the ray tracer can't reach.
For instance, say some photons hit the camera at pixel x-coordinates 10.0003 to 10.0005 through a fine aperture.
This will illuminate the camera in a photon tracing simulation. The ray tracer will not capture that photon unless its resolution were 10,000 times higher. The ray tracer will trace back from 10, 11. It can't do every intermediary step. The photon tracer can account for those circumstances.
The issue at hand is: we don't experience it, but light behaves in a thermodynamic (dynamic) equilibrium way. You don't see the transients, because the equilibrium takes nanoseconds to converge, but when you turn on a light all your room is exchanging photons until it settles at a rate where everywhere is receiving as much as it's irradiating plus what's wasted as heat, and the total heat is equal to the energy coming through the light sources. Finding those values is solving the so called light transport equation -- and this clearly requires probing geometrical information from all over the place.
In the sunlit room case, all that light is a) heating the room and b) going outside. Now let me try to build a physical model based on your intuition: this equilibrium dynamic depends on the rate of absorption/reflection of each surface. If you have experience with EE, the room is essentially a resonator, where walls are reflecting some and absorbing some until it's absorbing as much as there is light coming in. The less absorbing the walls are, the greater the Q factor of the resonator is: the light is going to bounce a lot and build intensity before it gets absorbed. This is why dark walled rooms are so dramatically, well, darker than white rooms -- the Q factor is not bounded. If your walls were perfect mirrors the intensity would build up with time to +inf.
* trace a photon from the light source with x bounces
* trace a ray from the camera with x bounces
Now the end points of those traces are not connected but you can calculate the probability that they can 'see' each other. You can use this calculation for the light transport from the light source (photon) to the camera (pixel).Edit: maybe this image will make it clear: http://lebedev.as/web_images/historyGlobal/15.png
The 'deterministic step' connects the raydiance from the light to the pixel.
photon tracing is quite different - instead of starting from the pixel you accumulate your results.
as such i consider the original comment not only accurate, but insightful. (if ambiguous)
// Non-minified source in 35 lines for HN, because it's the latest fad :)
https://www.hnsearch.com/search#request/submissions&q=%2235+...https://www.hnsearch.com/search#request/submissions&q=%2230+...
> Note that the goal here was to make the source code as small as possible, not clarity; so even the original code before minification is a horrible mess. This doesn’t do justice to the elegance and simplicity of proper raytracer code; I’m writing a book to right this wrong.
Raytracing is not exactly a lightweight calculation. My first raytracer was TurboSilver 3D on the Amiga, in 1990 (actually one of the first commercial raytracers ever produced). "Photorealistic" images at 7.5 Mhz. For an image like this, you'd set up the scene, hit the render button, and grab a quick lunch. When you came back, the scene would be about 2/3rds rendered, and you'd watch it for a while, thrilled by every new pixel that pushed itself onto the screen. Then you'd go get coffee and hope the scene was done when you got back.
Now, the same scene (say, 320x200px) renders in an eyeblink on my phone, driven by a high-level universal scripting language I can tweak at will. This is beyond amazing. It's fucking transcendent.
(Oy vey, I feel old. Where'd I put my dentures? BTW: get off my lawn, etc.)
var w = 1000;c.style.width = '500px';
http://www.kevinbeason.com/smallpt/ (+ source code and explanation)
http://davibu.interfree.it/opencl/smallptgpu/smallptGPU.html
All VERY interesting stuff.
The great thing about such demos is, that everyone is able to read and run it within minutes.
But I won't quit! If you're interested, I'm already proud of what I have :) http://i.imgur.com/8wwSsab.png
On Chrome 31, it takes 3307 ms to render the image and on IE11 it takes only 2320 milliseconds.
So am I in the matrix?
This is one of the coolest points of Javascript IMHO: you can see the result and interact with it directly in your browser. Right here you will find someone tweaking the code for supersampling, and you can apply it yourself and see the result without hassle.
This generates an uncontrollable and very positive propagation effect.
but nobody is talking about it :( Maybe I should render a movie or something.
I just checked, there is already WebCL and an implementation for WebKit (https://github.com/SRA-SiliconValley/webkit-webcl).
Here is a video: http://www.youtube.com/watch?v=9Ttux1A-Nuc
Any suggestions?
What helped me:
learn about vectors
learn about (vector) normalization
learn about camera models http://www.ventrella.com/Ideas/Camera/Arm_Camera.pdf
learn about pixels (pixels are just dots without size)
use a 3D coordinate-system that works for you (mine is: x = right, y = forward, z = up)
start with a simple camera model (always looking forward)
normalize all direction vectors
place the screen of pixels 1 unit in front of the camera
normalize the screen of pixels
know that the center pixel is on the forward vector of the camera
try to calculate a vector from the camera position to the left top of the pixel screen in front of the cameraAlso, I'm halfway through writing a Computer Graphics textbook, half of it dedicated to raytracing.
(on a not-particularly-raytracing-related note, I can really recommend to anyone interested the lesson about colour spaces, first time the point of CIExy and sRGB became clear to me. also for anyone wondering why the colours in F.lux / Redshift shift the way they do, check the "blackbody radiation" chapter)
There's plenty of links on the web, but if you're really serious (it can be quite addictive writing one), get hold of the "Raytracing/Rendering bible" : Physically Based Rendering by Matt Pharr and Greg Humphreys.
There's also a plethora of research freely available with cutting edge techniques to read.
+ see my other comment https://news.ycombinator.com/item?id=6771403
// Shorten some names. var math = Math;
I had a really, really ugly trick that saved me a couple of bytes which I removed before posting to HN. I figured out I was using canvas.getImageData() and canvas.putImageData(). So I did this: var tID = "tImageDatA"; canvas["ge"+tID](); canvas["pu"+tID"](); You can see that in the original source: http://gabrielgambetta.com/tiny_raytracer_full.js
Not my proudest hack :D
Is that BASIC CODE mixed in with bugs bunny??! Raytracer or no raytracer, this is exceedingly cool.
BBC Basic was amazing in hindsight.
Bugs Boni !
E=Math,F=E.sqrt,G=E.maxgranted the js is highly size optimised, and that probably required some reasonable effort. i see nothing clever here at all. also, the fact that its 35 lines is a weird measure - i can see ways to reduce that trivially - why isn't everything to do with the render baked into the final loop?.
the byte count is a more useful measure.
4k/64k executable demos are much more impressive - even though there is a stack of technology underneath you have to do things like butcher your C/C++ standard libraries or not use them at all...
For one thing, it's a reminder of how awesome the technology stack that we all take for granted is.
A good way to do that is to write your comment from a "Yes and..." perspective, rather than a "Yes but..." perspective. In one case you're showing the author how tall the wall front of him is, in the other you show him how you yourself climbed that wall when you were in his position.
It helps a lot :)
- born in uruguay
- worked his way up to google
- learned BASIC at 5 (and made childhood drawings that included handwritten basic code)
- read First Blood at 9
- wrote first short story at 7
Meanwhile I go to grandparent poster's site and find... well. I think I sort of understand where the criticism is coming from.
I'm not criticizing the author or his work, I'm just saying that writing a recursive function that does p + kv recursively shouldn't take a lot of code. Do I need to end each comment with a smiley face to prevent it from being taken the wrong way?
It doesn't take a lot of code, sure. But "a cross-platform game framework in 100,000 lines of C++" is not the current fad in HN ;)
I think it's more a matter of saying "Yes, good job on figuring out how to do p + kv recursively! Here are links to {papers|books|lectures|other code} that go further if you want to explore this topic more" rather than saying "Oh, you figured out how to do p + kv recursively, just like millions of other CS freshman. Good for you".
It's the little details that make online communities pleasant :)
If it uses a recursive raytracing algorithm does that not make it a raytracer? It traces rays recursively like all, well, ray tracers.
It's just that people tend to think about povray and renderman when "raytracers" are mentioned, and thus, fitting a raytracer into 30 lines of javascript may seem impossible, while actually it's entirely possible because the core idea of the algorithm is quite simple - this is what this demo shows and it is exactly the reason it's a good demo.
Not really. At least neither me, nor (I'd say) the HN crowd, would expect something like povray or renderman given the title of the article.
What we'd expect, an implementation of a ray tracing algorithm, and not a full featured program, we got.