-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_mesh.py
More file actions
182 lines (156 loc) · 5.95 KB
/
Copy pathbase_mesh.py
File metadata and controls
182 lines (156 loc) · 5.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
from dataclasses import dataclass
import numpy as np
import OpenGL.GL as gl
from . import vao_factory
from .abstract_vao import VertexData
from .bbox import BBox
from .log import logger
class Face:
"""
Simple face structure for mesh geometry.
Holds indices for vertices, UVs, and normals.
"""
slots = ("vertex", "uv", "normal")
def __init__(self):
self.vertex: list[int] = []
self.uv: list[int] = []
self.normal: list[int] = []
class BaseMesh:
"""
Base class for mesh geometry.
Provides storage for vertices, normals, UVs, faces, and VAO management.
"""
def __init__(self):
self.vertex: list = []
self.normals: list = []
self.uv: list = []
self.faces: list[Face] = []
self.vao = None
self.bbox = None
self.min_x: float = 0.0
self.max_x: float = 0.0
self.min_y: float = 0.0
self.max_y: float = 0.0
self.min_z: float = 0.0
self.max_z: float = 0.0
self.texture_id: int = 0
self.texture: bool = False
def is_triangular(self) -> bool:
"""
Check if all faces in the mesh are triangles.
Returns:
bool: True if all faces are triangles, False otherwise.
"""
return all(len(f.vertex) == 3 for f in self.faces)
def _should_skip_vao_creation(self, reset_vao: bool) -> bool:
"""Check if VAO creation should be skipped."""
if self.vao is None:
return False
if reset_vao:
logger.warning("VAO exist so returning")
return True
logger.warning("Creating new VAO")
return False
def _validate_triangular_mesh(self) -> None:
"""Validate that the mesh is composed of triangles."""
if not self.is_triangular():
logger.error("Can only create VBO from all Triangle data at present")
raise RuntimeError("Can only create VBO from all Triangle data at present")
def create_vao(self, reset_vao: bool = False) -> None:
"""
Create a Vertex Array Object (VAO) for the mesh.
Only supports triangular meshes.
Args:
reset_vao: If True, will not create a new VAO if one already exists.
Raises:
RuntimeError: If the mesh is not composed entirely of triangles.
"""
# Handle existing VAO based on reset_vao flag
if self._should_skip_vao_creation(reset_vao):
return
# Validate mesh is triangular
self._validate_triangular_mesh()
data_pack_type = gl.GL_TRIANGLES
@dataclass
class VertData:
"""
Structure for a single vertex's data, including position, normal, and UV.
"""
x: float = 0.0
y: float = 0.0
z: float = 0.0
nx: float = 0.0
ny: float = 0.0
nz: float = 0.0
u: float = 0.0
v: float = 0.0
def as_array(self) -> np.ndarray:
return np.array(
[self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v],
dtype=np.float32,
)
vbo_mesh: list[VertData] = []
for face in self.faces:
for i in range(3):
d = VertData()
d.x = self.vertex[face.vertex[i]].x
d.y = self.vertex[face.vertex[i]].y
d.z = self.vertex[face.vertex[i]].z
if self.normals and self.uv:
d.nx = self.normals[face.normal[i]].x
d.ny = self.normals[face.normal[i]].y
d.nz = self.normals[face.normal[i]].z
d.u = self.uv[face.uv[i]].x
d.v = 1 - self.uv[face.uv[i]].y # Flip V for OpenGL
elif self.normals and not self.uv:
d.nx = self.normals[face.normal[i]].x
d.ny = self.normals[face.normal[i]].y
d.nz = self.normals[face.normal[i]].z
elif not self.normals and self.uv:
d.u = self.uv[face.uv[i]].x
d.v = 1 - self.uv[face.uv[i]].y
vbo_mesh.append(d)
mesh_data = np.concatenate([v.as_array() for v in vbo_mesh]).astype(np.float32)
self.vao = vao_factory.VAOFactory.create_vao(
vao_factory.VAOType.SIMPLE, data_pack_type
)
with self.vao as vao:
mesh_size = len(mesh_data) // 8
vao.set_data(VertexData(mesh_data, mesh_size))
# vertex
vao.set_vertex_attribute_pointer(0, 3, gl.GL_FLOAT, 8 * 4, 0)
# normals
vao.set_vertex_attribute_pointer(1, 3, gl.GL_FLOAT, 8 * 4, 3 * 4)
# uvs
vao.set_vertex_attribute_pointer(2, 2, gl.GL_FLOAT, 8 * 4, 6 * 4)
vao.set_num_indices(mesh_size)
self.calc_dimensions()
self.bbox = BBox.from_extents(
self.min_x, self.max_x, self.min_y, self.max_y, self.min_z, self.max_z
)
def calc_dimensions(self) -> None:
"""
Calculate the bounding box extents for the mesh.
Updates min_x, max_x, min_y, max_y, min_z, max_z.
"""
if not self.vertex:
return
self.min_x = self.max_x = self.vertex[0].x
self.min_y = self.max_y = self.vertex[0].y
self.min_z = self.max_z = self.vertex[0].z
for v in self.vertex:
self.min_x = min(self.min_x, v.x)
self.max_x = max(self.max_x, v.x)
self.min_y = min(self.min_y, v.y)
self.max_y = max(self.max_y, v.y)
self.min_z = min(self.min_z, v.z)
self.max_z = max(self.max_z, v.z)
def draw(self) -> None:
"""
Draw the mesh using its VAO and bound texture (if any).
"""
if self.vao:
if self.texture_id:
gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_id)
with self.vao as vao:
vao.draw()