Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_ray_trace.py
- from Tkinter import *
- from PIL import Image, ImageTk
- 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)
- 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
- fromvec.x = fromvec.x + 2.0/200
- continue
- det = math.sqrt(d)
- t = -b + det
- if t < 0: # object is behind eye
- 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
- pic[int(fromvec.x*100+100)+(int(fromvec.y*100+100)*200)] = (r, g, b)
- 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)
- sq = 200
- pic = [(100,100,100) for z in range(sq*sq)]
- scan()
- root = Tk()
- root.title("Tk Ray Trace")
- root.geometry("%dx%d+0+0"%(sq,sq))
- canvas = Canvas(root, width=sq, height=sq)
- canvas.grid()
- img = Image.new("RGB",(sq, sq))
- img.putdata(pic)
- imgTk = ImageTk.PhotoImage(img)
- canvas.create_image(0, 0, anchor=NW, image=imgTk)
- canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement