Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_3D_sphere.py
- from Tkinter import *
- from PIL import Image, ImageTk
- import random
- import math
- import time
- ww = 600
- hh = 600
- shades = range(255,1,-1)
- def normalize(v):
- len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
- return (v[0]/len, v[1]/len, v[2]/len)
- def dot(x,y):
- d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
- return -d if d < 0 else 0
- def draw_sphere(r, k, ambient, light):
- pixels = [(128,128,128)]*(ww*hh)
- for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
- x = i + 0.5
- for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
- y = j/2 + 0.5
- if x*x + y*y <= r*r:
- vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
- b = dot(light,vec)**k + ambient
- intensity = int((1-b)*(len(shades)-1))
- c = shades[intensity] if 0 <= intensity < len(shades) else shades[0]
- pixels[int(x+((y-(hh/2))*ww))] = (0,c,0)
- return pixels
- root = Tk()
- root.title("Tk 3D Sphere")
- root.geometry("%dx%d+-10+0"%(ww,hh))
- canvas = Canvas(root, width=ww, height=hh)
- canvas.pack()
- pixels = [(0,128,0)]*(ww*hh)
- light = normalize((30,30,-50))
- pixels = draw_sphere(ww/2-20,4,0.1, light)
- img = Image.new("RGB", (ww, hh))
- img.putdata(pixels)
- 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