r/tinycode • • 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

35 comments sorted by

13

u/[deleted] Jan 09 '13

Nice!

I love how clean Python code can be.

3

u/Yeknom Jan 10 '13

Thanks

2

u/oulipo Jan 14 '13

I quickly added custom size & subsampling antialiasing :) http://pastebin.com/U5tsN7L7

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.

3

u/Yeknom Jan 10 '13

Yea. I could also have the readout more useful perhaps too rather than just displaying the current pixel column.

3

u/theinternetftw Jan 10 '13 edited Jan 10 '13

Very cool, btw. Thinking about hacking a viewing screen and scene controls into it while still keeping it clear and concise (with some of those controls being for lowering resolution and bounces to have that interactivity be even moderately usable, of course).

I've actually been playing around with raytracing recently by porting the code from this video to python/pygame (which was a hoot, considering the guy has a habit of using modern features (here OpenMP) while making use of direct BIOS calls that he can access due to running everything in DOSBOX).

The port's about 350 lines, with a concurrent version being just a few lines more and giving me a 70% speedup on my dual-core machine.

Anyway, I say all that to tell you I tried to make your code concurrent the same way I did that port, but it made yours 6s slower. Thought you might be interested in that (though the fault's probably in my understanding of something or another). Here's that code, if you were curious.

3

u/Yeknom Jan 10 '13

Nice work! I had a play round with it but couldn't get it to run any faster, although on my machine your version is no slower than mine. I also tried increasing the number of process and that did slow it down.

I recently added multi-threading a ray tracer i had written in in c++ and that was then able to achieve 12fps at 800x600 with reflective and translucent materials. To boost performance the light was being pre-baked which also allowed for light to be reflected, refracted, and scattered. I find you can just keep adding features :)

3

u/theinternetftw Jan 10 '13 edited Jan 10 '13

Surprisingly, not using a class for vectors improves runtime by 2x.

(which is why I used those more cumbersome functions in my raytracing code, but I'd forgotten just how dramatic the speedup was)

1

u/Yeknom Jan 10 '13

So the maxRecur is not actually used in this implementation. It would be used if the trace function was made recursive. Making the trace function recursive would allow it to model translucent, and reflective surfaces. The maxRecur value would be decremented each time the function was called so the ray tracer could avoid tracing to infinity for example between two mirrors or inside something with total internal reflection.

TLDR: Not used

4

u/Twirrim Jan 10 '13

Is there a particular reason why functions are quicker than classes? Naively I assumed that mostly under the surface it would execute / optimize mostly the same?

thought I'd randomly chuck these through pypy 1.9, 26s->11s for the standard code python vs pypy, then 16s->11s for your function based code.

→ More replies (4)
→ More replies (2)

1

u/[deleted] Jan 10 '13

Or even just comment it out entirely for a speedier execution

2

u/theinternetftw Jan 10 '13

I commented it out and got essentially zero speedup (i.e. it was so small I couldn't account for it by just casually timing the program). Sometimes printing stuff (even hundreds of lines) just isn't a factor in performance.

2

u/[deleted] Jan 10 '13

Weird, IO is super costly on my machine.

→ More replies (1)

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.

3

u/Yeknom Jan 10 '13

That's awesome! I'm currently working on getting the raytracer working an embedded system.

http://www.ti.com/graphics/tool/EK_LM3S1968_08_09.jpg

It has a 128x96 4 bit grey scale OLED screen which should be pretty good i think. However there is no Floating Point Unit on the chip so that might slow things down a little.

2

u/hhatinen Jan 11 '13

Sounds like an interesting project! Coping without floating point arithmetic might feel kind of hard at first, but when you get used to it it won't be that bad. One trick is to make fractions disappear in your calculations by expanding your calculations. It takes a bit of creativity to do so but achieving results by doing so will be rewarding.

I actually wrote a raytracer for x86 some while ago using only fixed point arithmetic. Don't ask why, but I just felt like it would be a good practice. Also I made a demo using the "engine" and entered it into a competition. Seems like someone uploaded it to youtube as well! http://www.youtube.com/watch?v=5tPEa0I3pCI (christ, it's been 8 years already?)

2

u/Yeknom Jan 11 '13

This is so cool. I love the constructive geometry. Its something I've always been keen to to try.

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

from collections import namedtuple
Intersection = namedtuple('Intersection', 'p d n obj'.split())
Ray = namedtuple('Ray', 'o d'.split())                         

1

u/Yeknom May 16 '13

Nice, I have never used namedtuples before

5

u/sleepingsquirrel Jan 10 '13

Here's another tiny ray tracer in 99 lines of C++.

2

u/RobotCaleb Jan 10 '13

definitely*

5

u/theinternetftw Jan 10 '13

Nope, I'm sure those features defiantly fought to not be added.

2

u/Yeknom Jan 10 '13

Ahh. Yea those damn features

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.

4

u/theinternetftw Jan 10 '13

For it to be thin it'd have to be an ellipsoid, which isn't defined in the code. All you can do with a sphere is define a center and radius. But a giant sphere alone might work fine. So big you couldn't see the curvature...

3

u/delta_epsilon_zeta Jan 10 '13

Yeah, something like that. I was just recalling what the author of SmallPT did, I didn't have the code in front of me (was on my phone).

2

u/gfixler Jan 10 '13

Like too much air in a balloon!

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..