Advertisement
here2share

# Tk_3D_sphere.py

Nov 14th, 2020 (edited)
1,654
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. # Tk_3D_sphere.py
  2.  
  3. from Tkinter import *
  4. from PIL import Image, ImageTk
  5. import random
  6. import math
  7. import time
  8. ww = 600
  9. hh = 600
  10.  
  11. shades = range(255,1,-1)
  12.  
  13. def normalize(v):
  14.     len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
  15.     return (v[0]/len, v[1]/len, v[2]/len)
  16.  
  17. def dot(x,y):
  18.     d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
  19.     return -d if d < 0 else 0
  20.  
  21. def draw_sphere(r, k, ambient, light):
  22.     pixels = [(128,128,128)]*(ww*hh)
  23.     for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
  24.         x = i + 0.5
  25.         for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
  26.             y = j/2 + 0.5
  27.             if x*x + y*y <= r*r:
  28.                 vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
  29.                 b = dot(light,vec)**k + ambient
  30.                 intensity = int((1-b)*(len(shades)-1))
  31.                 c = shades[intensity] if 0 <= intensity < len(shades) else shades[0]
  32.                 pixels[int(x+((y-(hh/2))*ww))] = (0,c,0)
  33.     return pixels
  34.  
  35.  
  36.  
  37. root = Tk()
  38. root.title("Tk 3D Sphere")
  39. root.geometry("%dx%d+-10+0"%(ww,hh))
  40. canvas = Canvas(root, width=ww, height=hh)
  41. canvas.pack()
  42.  
  43. pixels = [(0,128,0)]*(ww*hh)
  44.  
  45. light = normalize((30,30,-50))
  46. pixels = draw_sphere(ww/2-20,4,0.1, light)
  47.  
  48. img = Image.new("RGB", (ww, hh))
  49. img.putdata(pixels)
  50.  
  51. imgTk = ImageTk.PhotoImage(img)
  52. canvas.create_image(0, 0, anchor=NW, image=imgTk)
  53. canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement