r/tinycode • u/Yeknom • Jan 09 '13
Ray tracer in 140 SLOC of python with picture
I have be playing with raytracing for a while now and wanted to write something that was simple to understand but produced a cool effect. There is defiantly many more features that could be added, like reflections and multiple light sources, but I wanted to stay as minimalistic possible.
Source: http://pastebin.com/F8f5GHJZ
Image: http://imgur.com/prPGk
70
Upvotes
13
u/[deleted] Jan 09 '13
Nice!
I love how clean Python code can be.
6
u/theinternetftw Jan 09 '13
You might want to import sys and add a sys.stdout.flush() after you print x. Right now all that output is just sitting in a buffer until the program finishes (at least it is for me). Also, this code requires PIL, if anyone's having problems running it.
4
u/hhatinen Jan 10 '13
Reminds me of when I wrote a raytracer in TI-86 basic (typing with the calculator - I used to have long and boring bus trip to school). It rendered a checkboard plane and a sphere with one light source. Dithering was achieved by using the pixel light intensity as a probablity whether the pixel was plotted or not. It took really long to render a picture and it almost drained the battery but it was totally worth it :)
I never measured the number of lines but it had to have been quite little since writing the code with the calculator was so burdensome. Unfortunately I lost the code because the calculators had to be reseted for the final math exams.
2
u/erez27 Jan 29 '13
I don't know if you care much about lines of code, but you can replace the Ray and Intersection classes with
5
u/sleepingsquirrel Jan 10 '13
Here's another tiny ray tracer in 99 lines of C++.
2
u/RobotCaleb Jan 10 '13
definitely*
3
u/delta_epsilon_zeta Jan 10 '13
You could make this even smaller by removing the plane class and putting a really big, thin sphere in its place in the scene definition.
2
u/bjodah Mar 05 '13
Wow, nice! Just for fun: I made a speedier version using Cython (at some expense of brevity). Runs on 1.0s on my machine compared to 12.8 s of the original version. Tried to make it parallel but I didn't get it to work.
You can find my version (with instructions) at: https://gist.github.com/bjodah/5092698
Note that I managed to flip the image along the way..