Last active
August 29, 2015 14:23
-
-
Save mmajewsk/5487c62d6b14b3f8b40d to your computer and use it in GitHub Desktop.
Python 2d ray tracing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The MIT License | |
Copyright (c) 2015 Hawker | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def _range_when_zero(iterlist): | |
for i, pixel in enumerate(iterlist): | |
if pixel == 0: | |
return i | |
else: | |
return float(len(iterlist)) | |
def _count_step(d_x, d_y, x, y, i, sina, minim): | |
if minim == 1: | |
return np.floor(sina*i), i | |
else: | |
return i, np.floor(i/sina) | |
def _range_when_non_zero(d_x, d_y, x, y, tab): | |
maxval = max(d_x, d_y) | |
sina = d_x/float(d_y) | |
minim = (d_x, d_y).index(maxval) | |
for i in xrange(maxval): | |
step_x, step_y = _count_step(d_x, d_y, x, y, i, sina, minim) | |
value = tab[y+step_y, x+step_x, 0] | |
if value == 0: | |
return np.sqrt(step_x**2 + step_y**2) | |
return np.sqrt(d_x**2 + d_y**2) | |
def trace_ray(tab, start, end): | |
x0, y0 = map(int,start) | |
x1, y1 = map(int,end) | |
d_x = x1 - x0 | |
d_y = y1 - y0 | |
if d_x == 0: | |
ym = (y0,y1) | |
return _range_when_zero(iterlist=tab[min(ym):max(ym), x0, 0]) | |
elif d_y == 0: | |
xm = (x0,x1) | |
return _range_when_zero(iterlist=tab[y0, min(xm):max(xm), 0]) | |
else: | |
return _range_when_non_zero(d_x, d_y, x0, y0, tab) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment