Python 向我解释一下,就像我是5:OpenGL4.x渲染管道一样
在过去几周的业余时间里,我一直在看openGL。虽然我没有问题遵循一些旧的NeHe示例,但从我所读到的所有内容来看,OpenGL4是一个完全不同的过程。我可以访问红皮书和超级圣经,但前者仍然提供传统的opengl调用,后者使用自己的库。在理解如何在项目中组合代码时,两者都不是特别有用的。例如,我目前的理解是glu和glut是遗留的,不应该用于OpenGL4 我可以很容易地为假设的模型空间生成顶点。我很难理解一个模特是如何出现在我的屏幕上的。我大约95%的尝试都以黑屏告终 提前谢谢 下面是一些代码:Python 向我解释一下,就像我是5:OpenGL4.x渲染管道一样,python,rendering,pipeline,pyglet,opengl-4,Python,Rendering,Pipeline,Pyglet,Opengl 4,在过去几周的业余时间里,我一直在看openGL。虽然我没有问题遵循一些旧的NeHe示例,但从我所读到的所有内容来看,OpenGL4是一个完全不同的过程。我可以访问红皮书和超级圣经,但前者仍然提供传统的opengl调用,后者使用自己的库。在理解如何在项目中组合代码时,两者都不是特别有用的。例如,我目前的理解是glu和glut是遗留的,不应该用于OpenGL4 我可以很容易地为假设的模型空间生成顶点。我很难理解一个模特是如何出现在我的屏幕上的。我大约95%的尝试都以黑屏告终 提前谢谢 下面是一些代码
# primatives.py
from collections import Iterable
from functools import reduce
import operator
import numpy as np
from exc import UnimplementedMethod
class Primative(object):
SIZE = 1 # number of pixels on a default grid
def __init__(self, point=None, *args, **kwargs):
self.point = point if isinstance(point, Iterable) else [0, 0, 0]
self.point = np.array(self.point, dtype=np.float32)
scaler = [self.SIZE/2]*len(self.point)
self.point = (self.point * scaler).tolist()
@property
def active(self):
attr = "__active__"
if not hasattr(self, attr):
setattr(self, attr, False)
return getattr(self, attr)
@active.setter
def active(self, value):
attr = "__active__"
if value in [True, False]:
setattr(self, attr, value)
return getattr(self, attr)
@property
def vertices(self):
"""Returns a simple list of calculated vertices"""
clsname = self.__class__.__name__
raise UnimplementedMethod(clsname)
@property
def dimension(self):
return len(self.point)
@property
def scaler(self):
attr = "__scaler__"
if not hasattr(self, attr):
size = self.SIZE / 2
setattr(self, attr, [size]*self.dimension)
return getattr(self, attr)
@scaler.setter
def scaler(self, *values):
attr = "__scaler__"
values = values[0] if len(values) == 1 else values
if len(values) == 1 and len(values) != self.point:
if isinstance(values, [int, float]):
setattr(self, attr, [values]*self.dimension)
elif isinstance(values, Iterable):
data = [(v, i)
for v, i in zip(values, xrange(self.dimension))]
value = [v for v, i in data]
if len(value) != self.dimension:
raise ValueError
setattr(self, attr, value)
@property
def translation(self):
attr = "__transalation__"
if not hasattr(self, attr):
size = self.SIZE / 2
setattr(self, attr, [size]*self.dimension)
return getattr(self, attr)
@translation.setter
def transalation(self, *values):
attr = "__transalation__"
values = values[0] if len(values) == 1 else values
if isinstance(values, (int, float)):
setattr(self, attr, [values]*self.dimension)
elif isinstance(values, Iterable):
data = [(v, i)
for v, i in zip(values, xrange(self.dimension))]
value = [v for v, i in data]
if len(value) != self.dimension:
raise ValueError
setattr(self, attr, value)
@property
def rotation(self):
"""
Rotation in radians
"""
attr = "__rotation__"
if not hasattr(self, attr):
setattr(self, attr, [0]*self.dimension)
return getattr(self, attr)
@rotation.setter
def rotation(self, *values):
"""
Rotation in radians
"""
attr = "__rotation__"
values = values[0] if len(values) == 1 else values
if isinstance(values, (int, float)):
setattr(self, attr, [values]*self.dimension)
elif isinstance(values, Iterable):
data = [(v, i)
for v, i in zip(values, xrange(self.dimension))]
value = [v for v, i in data]
if len(value) != self.dimension:
raise ValueError
setattr(self, attr, value)
@property
def volume(self):
clsname = self.__class__.__name__
raise UnimplementedMethod(clsname)
class Cube(Primative):
# G H
# * --------- *
# /| /|
# C / | D / |
# * --------- * |
# | * -------|- *
# | / E | / F
# |/ |/
# * --------- *
# A B
@property
def center_of_mass(self):
"""
Uses density to calculate center of mass
"""
return self.point
@property
def material(self):
clsname = self.__class__.__name__
raise UnimplementedMethod(clsname)
@material.setter
def material(self, value):
clsname = self.__class__.__name__
raise UnimplementedMethod(clsname)
@property
def mass(self):
return self.material.density * self.volume
@property
def volume(self):
func = operator.mul
return reduce(func, self.scaler, 1)
@property
def normals(self):
"""
computes the vertex normals
"""
norm = []
if len(self.point) == 1:
norm = [
# counter clockwise
# x (left hand rule)
(-1), # A
(1) # B
]
elif len(self.point) == 2:
norm = [
# counter clockwise
# x, y (left hand rule)
(-1, -1), # A
(1, -1), # B
(1, 1), # C
(-1, 1) # D
]
elif len(self.point) == 3:
norm = [
# counter clockwise
# x, y, z (left hand rule)
(-1, -1, 1), # A 0
(1, -1, 1), # B 1
(1, 1, 1), # D 2
(-1, 1, 1), # C 3
(-1, -1, -1), # E 4
(1, -1, -1), # F 5
(1, 1, -1), # H 6
(-1, 1, -1), # G 7
]
return norm
@property
def indices(self):
indices = []
if len(self.point) == 2:
indices = [
[[1, 0, 3], [2, 3, 1]], # BAC CDB front
]
elif len(self.point) == 3:
indices = [
[[1, 0, 3], [2, 3, 1]], # BAC CDB front
[[5, 1, 2], [2, 6, 5]], # FBD DHF right
[[4, 5, 6], [6, 7, 4]], # EFH HGE back
[[5, 4, 0], [0, 1, 5]], # FEA ABF bottom
[[0, 4, 7], [7, 3, 0]], # AEG GCA left
[[2, 3, 7], [7, 6, 2]], # DCG GHD top
]
return indices
@property
def nodes(self):
normals = np.array(self.normals, dtype=np.float32)
scaler = np.array(self.scaler, dtype=np.float32)
nodes = normals * scaler
return nodes.tolist()
@property
def vertices(self):
verts = (n for node in self.nodes for n in node)
return verts
还有一点:
# Voxel.py
from collections import Iterable
from time import time
import numpy as np
import pyglet
from pyglet.gl import *
from primatives import Cube
import materials
class Voxel(Cube):
"""
Standard Voxel
"""
def __init__(self, point=None, material=None):
super(Voxel, self).__init__(point=point)
if isinstance(material, materials.Material):
self.material = material
else:
self.material = materials.stone
def __str__(self):
point = ", ".join(str(p) for p in self.point)
material = self.material.name
desc = "<Voxel [%s] (%s)>" % (material, point)
return desc
def __repr__(self):
point = ", ".join(str(p) for p in self.point)
material = self.material.name
desc = "<Voxel %s(%s)>" % (material, point)
return desc
@property
def material(self):
attr = "__material__"
if not hasattr(self, attr):
setattr(self, attr, materials.ether)
return getattr(self, attr)
@material.setter
def material(self, value):
attr = "__material__"
if value in materials.valid_materials:
setattr(self, attr, value)
return getattr(self, attr)
class Chunk(Cube):
"""
A Chunk contains a specified number of Voxels. Chunks are an
optimization to manage voxels which do not change often.
"""
NUMBER = 16
NUMBER_OF_VOXELS_X = NUMBER
NUMBER_OF_VOXELS_Y = NUMBER
NUMBER_OF_VOXELS_Z = NUMBER
def __init__(self, point=None):
point = (0, 0, 0) if point is None else point
super(Chunk, self).__init__(point=point)
self.batch = pyglet.graphics.Batch()
points = []
x_scale = self.NUMBER_OF_VOXELS_X / 2
y_scale = self.NUMBER_OF_VOXELS_Y / 2
z_scale = self.NUMBER_OF_VOXELS_Z / 2
self.rebuild_mesh = True
if len(point) == 1:
points = ((x,) for x in xrange(-x_scale, x_scale))
elif len(point) == 2:
points = ((x, y)
for x in xrange(-x_scale, x_scale)
for y in xrange(-y_scale, y_scale))
elif len(point) == 3:
points = ((x, y, z)
for x in xrange(-x_scale, x_scale)
for y in xrange(-y_scale, y_scale)
for z in xrange(-z_scale, z_scale))
t = time()
self.voxels = dict((point, Voxel(point)) for point in points)
self.active_voxels = dict((p, v)
for p, v in self.voxels.iteritems()
if v.active)
self.inactive_voxels = dict((p, v)
for p, v in self.voxels.iteritems()
if not v.active)
print 'Setup Time: %s' % (time() - t)
@property
def material(self):
return ether
@material.setter
def material(self, value):
if value in materials.valid_materials:
for voxel in self.voxels:
if voxel.material != value:
voxel.material = value
self.rebuild_mesh = True
@property
def mesh(self):
"""
Returns the verticies as defined by the Chunk's Voxels
"""
attr = "__mesh__"
if self.rebuild_mesh == True:
self.mesh_vert_count = 0
vertices = []
t = time()
for point, voxel in self.active_voxels.iteritems():
if voxel.active is True:
vertices.extend(voxel.vertices)
num_verts_in_voxel = len(voxel.normals)
self.mesh_vert_count += num_verts_in_voxel
print "Mesh Generation Time: %s" % time() - t
vertices = tuple(vertices)
setattr(self, attr, vertices)
voxel_count = len(self.active_voxels)
voxel_mesh = self.mesh
count = self.mesh_vert_count
group = None
data = ('v3f/static', vertices)
self.batch.add(count, self.mode, group, data)
return getattr(self, attr)
@property
def center_of_mass(self):
"""
Uses density to calculate center of mass. This is probably only
useful if the chunk represents an object.
"""
center = self.point
points = []
for point, voxel in self.active_voxels.iteritems():
mass = voxel.mass
if mass > 0:
point = [p*mass for p in point]
points.append(point)
points = np.array(points)
means = []
if points.any():
for idx, val in enumerate(self.point):
means.append(np.mean(points[:, idx]))
if means:
center = means
return center
def add(self, voxel):
added = False
point = None
if isinstance(voxel, Voxel):
point = voxel.point
elif isinstance(voxel, Iterable):
point = voxel
if point in self.inactive_voxels.iterkeys():
last = self.voxels[point]
self.voxels[point] = voxel if isinstance(voxel, Voxel) else last
self.voxels[point].active = True
self.active_voxels[point] = self.voxels[point]
self.inactive_voxels.pop(point)
added = True
self.rebuild_mesh = True
return added
def remove(self, voxel):
removed = False
point = None
if isinstance(voxel, Voxel):
point = voxel.point
elif isinstance(voxel, Iterable):
point = voxel
if point in self.active_voxels.iterkeys():
last = self.voxels[point]
self.voxels[point] = voxel if isinstance(voxel, Voxel) else last
self.voxels[point].active = False
self.inactive_voxels[point] = self.voxels[point]
self.active_voxels.pop(point)
removed = True
self.rebuild_mesh = True
return removed
def render(self):
voxels = len(self.active_voxels)
self.batch.draw()
return voxels
if __name__ == "__main__":
import pyglet
from pyglet.gl import *
class Window(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
vox_cnt = self.setup_scene()
print 'Added: %s voxels' % (vox_cnt)
def run(self):
"""wrapper to start the gui loop"""
pyglet.app.run()
def setup_scene(self):
self.chunk = Chunk()
cnt = 0
t = time()
for x in xrange(self.chunk.NUMBER_OF_VOXELS_X):
for y in xrange(self.chunk.NUMBER_OF_VOXELS_Y):
self.chunk.add((x, y))
cnt += 1
print "Setup Scene Time: %s" % (time() - t)
return cnt
def render_scene(self):
y = h = self.height
x = w = self.width
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
# glEnable(GL_DEPTH_TEST)
# glDepthFunc(GL_LESS)
t = time()
voxels_drawn = self.chunk.render()
print 'Render Time: %s' % (time() - t)
print 'Points Rendered %s' % voxels_drawn
# array_len = len(self.vertex_data)
# glDrawArrays(GL_TRIANGLES, 0, array_len)
def on_draw(self, *args, **kwargs):
self.render_scene()
w = Window()
w.run()
#体素.py
从集合导入Iterable
从时间导入时间
将numpy作为np导入
导入pyglet
从pyglet.gl导入*
从导入多维数据集
进口材料
类体素(立方体):
"""
标准体素
"""
定义初始(自身,点=无,材料=无):
超级(体素,自身)。\uuuuu初始\uuuuuuuuuuu(点=点)
如果存在(物料、物料、物料):
自材料=材料
其他:
self.material=materials.stone
定义(自我):
point=“,”.join(str(p)表示self.point中的p)
材质=self.material.name
desc=”“%(材质,点)
返回说明
定义报告(自我):
point=“,”.join(str(p)表示self.point中的p)
材质=self.material.name
desc=”“%(材质,点)
返回说明
@财产
def材料(自身):
属性=“材料”
如果不是hasattr(self,attr):
setattr(自身、属性、材料、乙醚)
返回getattr(self,attr)
@材料设定器
def材料(自身、价值):
属性=“材料”
如果materials.valid\u materials中的值为:
设置属性(自身、属性、值)
返回getattr(self,attr)
类块(多维数据集):
"""
块包含指定数量的体素。块是
优化以管理不经常更改的体素。
"""
数字=16
体素的个数X=个数
体素的数量=数量
体素的数量=数量
定义初始化(自,点=无):
点=(0,0,0)如果点不是其他点
超级(块,自).\uuuu初始化(点=点)
self.batch=pyglet.graphics.batch()
点数=[]
x_比例=self.NUMBER_体素的数量_x/2
y\u比例=自身。体素的数量\u y/2
z_比例=self.NUMBER_体素的数量_z/2
self.rebuild\u mesh=True
如果len(点)==1:
点=((x,)表示x范围内的x(-x_标度,x_标度))
elif len(点)==2:
点=((x,y)
对于x范围内的x(-x_刻度,x_刻度)
对于X范围内的y(-y_刻度,y_刻度))
elif len(点)==3:
点=((x,y,z)
对于x范围内的x(-x_刻度,x_刻度)
对于X范围内的y(-y_比例,y_比例)
对于X范围内的z(-z_刻度,z_刻度))
t=时间()
self.voxels=点中点的dict((点,体素(点)))
self.active_体素=dict((p,v)
对于self.voxels.iteritems()中的p,v
如果v.激活)
self.inactive_体素=dict((p,v)
对于self.voxels.iteritems()中的p,v
如果不是v,则激活)
打印“设置时间:%s%”(时间()-t)
@财产
def材料(自身):
返回乙醚
@材料设定器
def材料(自身、价值):
如果materials.valid\u materials中的值为:
对于self.voxels中的体素:
如果voxel.material!=价值:
voxel.material=值
self.rebuild\u mesh=True
@财产
def网格(自):
"""
返回由块体素定义的垂直
"""
属性=“网格”
如果self.rebuild_mesh==True:
self.mesh\u vert\u count=0
顶点=[]
t=时间()
对于点,self.active\u voxels.iteritems()中的体素:
如果voxel.active为True:
顶点.延伸(体素.顶点)
num_verts_in_voxel=len(体素法线)
self.mesh\u vert\u count+=num\u verts\u in\u体素
打印“网格生成时间:%s”%Time()-t
顶点=元组(顶点)
setattr(自身、属性、顶点)
体素计数=len(自激活体素)
体素网格=自网格
计数=self.mesh\u vert\u计数
组=无
数据=('v3f/static',顶点)
self.batch.add(计数、self.mode、组、数据)
返回getattr(self,attr)
@财产
def质量中心(自身):
"""
使用密度计算质心。这可能只是
如果区块表示对象,则此选项非常有用。
"""
中心=自身点
点数=[]
对于点,self.active\u voxels.iteritems()中的体素:
质量=体素质量
如果质量>0:
点=[p*点中p的质量]
点。追加(点)
点=np.数组(点)
平均数=[]
if points.any():
对于idx,枚举中的val(self.point):
平均值追加(np.平均值(点[:,idx]))
如果是指:
中心=平均数
返回中心
def添加(自身,体素):
添加=错误
点=无
如果存在(体素,体素):
点=体素。点
elif isinstance(体素,Iterable):
点=体素
如果点位于self.inactive\u voxels.iterke
# line 91:
cube.draw() # previously torus.draw()
# line 178: replace the line with the below (GL_TRIANGLES for GL_QUADS)
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_INT, indices)
# line 187:
cube = Cube(0.8) # previously torus = Torus(1, 0.3, 50, 30)
# replace lines 125 through 166 with:
class Cube(object):
Vertices =(0.,0.,0., 1.,0.,0., 0.,0.,1., 1.,0.,1.,
0.,1.,0., 1.,1.,0., 0.,1.,1., 1.,1.,1.)
def __init__(self, scale):
# Create the vertex and normal arrays.
indices = [0,1,3,2, 1,5,7,3, 5,4,6,7,
0,2,6,4, 0,4,5,1, 2,3,7,6]
normals = [ 0.0, -1.0, 0.0,
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
-1.0, 0.0, 0.0,
0.0, 0.0, -1.0,
0.0, 0.0, 1.0]
vertices = [scale * v for v in Cube.Vertices]
vertices = (GLfloat * len(vertices))(*vertices)
normals = (GLfloat * len(normals))(*normals)