# $Header: /home/abe/school/manual/ray-project/RCS/python.html,v 1.2 2010/06/05 16:29:47 abe Exp abe $
import math
class vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def scan():
radius = 0.5
point = vector(0.0, 0.0, 0.0)
fromvec = vector(0.0, -1.0, 3.0)
to = vector(0.0, 0.0, -1.0)
while fromvec.y < 1.0:
fromvec.x = -1.0
while fromvec.x < 1.0:
vec = vminus(fromvec, point)
b = innerproduct(to, vec)
c = innerproduct(vec, vec) - radius*radius
d = b * b - c
if d < 0: # ray is not intersect
back_color()
fromvec.x = fromvec.x + 2.0/200
continue
det = math.sqrt(d)
t = -b + det
if t < 0: # object is behind eye
back_color()
fromvec.x = fromvec.x + 2.0/200
continue
shading(t, fromvec, to, point)
fromvec.x = fromvec.x + 2.0/200
fromvec.y = fromvec.y + 2.0/200
def shading(t, fromvec, to, point):
l = vector(0.577, -0.577, -0.577) # light normalize(1, -1, -1)
ac = vector(0.1, 0.1, 0.1) # ambient light color
col = vector(1, 0, 0) # color of an object
too = vector(to.x * t, to.y * t, to.z * t)
c = vplus(fromvec, too)
c = vminus(c, point)
c = normalize(c)
val = innerproduct(c, l)
r = int(255.0 * (col.x * val + ac.x))
g = int(255.0 * (col.y * val + ac.y))
b = int(255.0 * (col.z * val + ac.z))
if r > 255:
r = 255
if g > 255:
g = 255
if b > 255:
b = 255
if r < 0:
r = 0
if g < 0:
g = 0
if b < 0:
b = 0
print('%d %d %d' % (r, g, b))
def write_header():
print 'P3\n200 200\n255'
def back_color():
print '100 100 100'
def vplus(a, b):
return vector( a.x + b.x, a.y + b.y, a.z + b.z)
def vminus(a, b):
return vector( a.x - b.x, a.y - b.y, a.z - b.z)
def innerproduct(a, b):
return a.x * b.x + a.y * b.y + a.z * b.z
def normalize(a):
s = a.x * a.x + a.y * a.y + a.z * a.z
d = math.sqrt(s)
return vector(a.x/d, a.y/d, a.z/d)
write_header()
scan()