Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_3d_panels.py
- import tkinter as tk
- import math
- W = 640
- s = 64
- fov = 800
- r = 0
- root = tk.Tk()
- root.title("# tk_3d_panels.py")
- root.geometry("+0+0")
- canvas = tk.Canvas(root, width=W, height=W, bg='#881308')
- canvas.pack()
- gap = s - 8
- hs = gap / 2
- hz = 0.5
- verts = [
- (-hs, -hs, -hz), (hs, -hs, -hz), (hs, hs, -hz), (-hs, hs, -hz),
- (-hs, -hs, hz), (hs, -hs, hz), (hs, hs, hz), (-hs, hs, hz)
- ]
- faces = [
- [4,5,6,7],
- [1,0,3,2],
- [0,4,7,3],
- [5,1,2,6],
- [0,1,5,4],
- [3,7,6,2]
- ]
- def rotateY(x, y, z, a):
- c = math.cos(a)
- s = math.sin(a)
- return (x*c + z*s, y, -x*s + z*c)
- def rotateX(x, y, z, a):
- c = math.cos(a)
- s = math.sin(a)
- return (x, y*c - z*s, y*s + z*c)
- def update():
- global r
- canvas.delete("all")
- all_faces = []
- for i in range(121):
- tx = (i % 11) * s - W/2
- ty = (i // 11) * s - W/2
- angleY = i/22 + r
- angleX = math.sin(r/10)/2
- transformed = []
- for vx, vy, vz in verts:
- x1, y1, z1 = rotateY(vx, vy, vz, angleY)
- x2, y2, z2 = rotateX(x1, y1, z1, angleX)
- x2 += tx
- y2 += ty
- transformed.append((x2, y2, z2))
- projected = []
- for x, y, z in transformed:
- scale = fov / (fov - z)
- sx = W/2 + x * scale
- sy = W/2 + y * scale
- projected.append((sx, sy))
- color = '#000000' if i % 2 == 0 else '#ffffff'
- for face in faces:
- v0 = transformed[face[0]]
- v1 = transformed[face[1]]
- v2 = transformed[face[2]]
- ax = v1[0] - v0[0]
- ay = v1[1] - v0[1]
- az = v1[2] - v0[2]
- bx = v2[0] - v0[0]
- by = v2[1] - v0[1]
- bz = v2[2] - v0[2]
- nx = ay*bz - az*by
- ny = az*bx - ax*bz
- nz = ax*by - ay*bx
- cx = sum(transformed[idx][0] for idx in face) / 4
- cy = sum(transformed[idx][1] for idx in face) / 4
- cz = sum(transformed[idx][2] for idx in face) / 4
- if nx*(0-cx) + ny*(0-cy) + nz*(fov-cz) > 0:
- z_avg = sum(transformed[idx][2] for idx in face) / 4
- points = []
- for idx in face:
- points.extend(projected[idx])
- all_faces.append((z_avg, points, color))
- all_faces.sort(key=lambda x: x[0])
- for _, points, color in all_faces:
- canvas.create_polygon(points, fill=color)
- r += 0.25
- root.after(1, update)
- update()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment