Python3D的实现
2023-08-18 18:20:02
发布于:浙江
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
def calculate_normal(v1, v2, v3):
normal = np.cross(np.array(v2) - np.array(v1), np.array(v3) - np.array(v1))
magnitude = np.linalg.norm(normal)
return normal / magnitude
def calculate_diffuse_color(normal, light_position, vertex_position):
light_direction = np.array(light_position) - np.array(vertex_position)
distance = np.linalg.norm(light_direction)
light_direction_normalized = light_direction / distance # Normalize light direction vector
dot_product = np.dot(normal, light_direction_normalized)
intensity = max(0, dot_product) # Ensure intensity is not negative
return intensity
pygame.init()
display = (1000, 700)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)
glTranslatef(0.0, 0.0, -4)
glShadeModel(GL_SMOOTH)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glMaterialfv(GL_FRONT, GL_DIFFUSE, [0.3, 0.3, 0.3, 1.0])
glMaterialfv(GL_FRONT, GL_SPECULAR, [0.005, 0.005, 0.005, 0.0])
#glMaterialfv(GL_FRONT, GL_EMISSION, [0.3, 0.3, 0.3, 0.0])
glMaterialfv(GL_FRONT, GL_SHININESS, 1.8) # 调整镜面高光度值
glLightfv(GL_LIGHT0, GL_POSITION, [225, 225, 225])
vertices = (
(1, -1, -1),
(1, 1, -1),
(-1, 1, -1),
(-1, -1, -1),
(1, -1, 1),
(1, 1, 1),
(-1, 1, 1),
(-1, -1, 1)
)
edges = (
(0, 1),
(1, 2),
(2, 3),
(3, 0),
(4, 5),
(5, 6),
(6, 7),
(7, 4),
(0, 4),
(1, 5),
(2, 6),
(3, 7)
)
faces = (
(0, 1, 2, 3),
(3, 2, 6, 7),
(7, 6, 5, 4),
(4, 5, 1, 0),
(1, 5, 6, 2),
(4, 0, 3, 7)
)
def cube():
for face in faces:
normal = calculate_normal(vertices[face[0]], vertices[face[1]], vertices[face[2]])
glNormal3fv(normal)
glBegin(GL_QUADS)
for vertex in face:
diffuse_intensity = calculate_diffuse_color(normal, (200, 200, 200), np.array(vertices[vertex]))
glColor3f(diffuse_intensity, diffuse_intensity, diffuse_intensity)
glVertex3fv(vertices[vertex])
glEnd()
rotation_scale = 0.5
while True:
x_rotation = 0
y_rotation = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEMOTION:
x, y = event.rel
x_rotation += y * rotation_scale
y_rotation += x * rotation_scale
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glRotatef(x_rotation, 1, 0, 0)
glRotatef(y_rotation, 0, 1, 0)
cube()
pygame.display.flip()
pygame.time.wait(10)
使用说明:
别忘了安装pygame、OpenGL和numpy!
安装方式:
pip install pygame
pip install OpenGL
pip install numpy
全部评论 2
6
2023-08-18 来自 广东
0我知道这是C++社区,但是不代表我不能玩Python(doge
2023-08-18 来自 浙江
0
有帮助,赞一个