forked from dantros/grafica
-
Notifications
You must be signed in to change notification settings - Fork 11
/
ex_obj_reader.py
269 lines (193 loc) · 8.68 KB
/
ex_obj_reader.py
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# coding=utf-8
"""Rendering a OBJ file simplified"""
import glfw
from OpenGL.GL import *
import OpenGL.GL.shaders
import numpy as np
import sys
import os.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import grafica.transformations as tr
import grafica.basic_shapes as bs
import grafica.easy_shaders as es
import grafica.lighting_shaders as ls
import grafica.performance_monitor as pm
from grafica.assets_path import getAssetPath
__author__ = "Daniel Calderon"
__license__ = "MIT"
# A class to store the application control
class Controller:
def __init__(self):
self.fillPolygon = True
# We will use the global controller as communication with the callback function
controller = Controller()
def on_key(window, key, scancode, action, mods):
if action != glfw.PRESS:
return
global controller
if key == glfw.KEY_SPACE:
controller.fillPolygon = not controller.fillPolygon
elif key == glfw.KEY_ESCAPE:
glfw.set_window_should_close(window, True)
def readFaceVertex(faceDescription):
aux = faceDescription.split('/')
assert len(aux[0]), "Vertex index has not been defined."
faceVertex = [int(aux[0]), None, None]
assert len(aux) == 3, "Only faces where its vertices require 3 indices are defined."
if len(aux[1]) != 0:
faceVertex[1] = int(aux[1])
if len(aux[2]) != 0:
faceVertex[2] = int(aux[2])
return faceVertex
def readOBJ(filename, color):
vertices = []
normals = []
textCoords= []
faces = []
with open(filename, 'r') as file:
for line in file.readlines():
aux = line.strip().split(' ')
if aux[0] == 'v':
vertices += [[float(coord) for coord in aux[1:]]]
elif aux[0] == 'vn':
normals += [[float(coord) for coord in aux[1:]]]
elif aux[0] == 'vt':
assert len(aux[1:]) == 2, "Texture coordinates with different than 2 dimensions are not supported"
textCoords += [[float(coord) for coord in aux[1:]]]
elif aux[0] == 'f':
N = len(aux)
faces += [[readFaceVertex(faceVertex) for faceVertex in aux[1:4]]]
for i in range(3, N-1):
faces += [[readFaceVertex(faceVertex) for faceVertex in [aux[i], aux[i+1], aux[1]]]]
vertexData = []
indices = []
index = 0
# Per previous construction, each face is a triangle
for face in faces:
# Checking each of the triangle vertices
for i in range(0,3):
vertex = vertices[face[i][0]-1]
normal = normals[face[i][2]-1]
vertexData += [
vertex[0], vertex[1], vertex[2],
color[0], color[1], color[2],
normal[0], normal[1], normal[2]
]
# Connecting the 3 vertices to create a triangle
indices += [index, index + 1, index + 2]
index += 3
return bs.Shape(vertexData, indices)
if __name__ == "__main__":
# Initialize glfw
if not glfw.init():
glfw.set_window_should_close(window, True)
width = 600
height = 600
title = "Reading a *.obj file"
window = glfw.create_window(width, height, title, None, None)
if not window:
glfw.terminate()
glfw.set_window_should_close(window, True)
glfw.make_context_current(window)
# Connecting the callback function 'on_key' to handle keyboard events
glfw.set_key_callback(window, on_key)
# Defining shader programs
pipeline = ls.SimpleGouraudShaderProgram()
mvpPipeline = es.SimpleModelViewProjectionShaderProgram()
# Telling OpenGL to use our shader program
glUseProgram(pipeline.shaderProgram)
# Setting up the clear screen color
glClearColor(0.85, 0.85, 0.85, 1.0)
# As we work in 3D, we need to check which part is in front,
# and which one is at the back
glEnable(GL_DEPTH_TEST)
# Convenience function to ease initialization
def createGPUShape(pipeline, shape):
gpuShape = es.GPUShape().initBuffers()
pipeline.setupVAO(gpuShape)
gpuShape.fillBuffers(shape.vertices, shape.indices, GL_STATIC_DRAW)
return gpuShape
# Creating shapes on GPU memory
gpuAxis = createGPUShape(mvpPipeline, bs.createAxis(7))
shapeSuzanne = readOBJ(getAssetPath('suzanne.obj'), (0.9, 0.6, 0.2))
gpuSuzanne = createGPUShape(pipeline, shapeSuzanne)
shapeCarrot = readOBJ(getAssetPath('carrot.obj'), (0.6, 0.9, 0.5))
gpuCarrot = createGPUShape(pipeline, shapeCarrot)
# Setting uniforms that will NOT change on each iteration
glUseProgram(pipeline.shaderProgram)
glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "La"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Ld"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Ls"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Ka"), 0.2, 0.2, 0.2)
glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Kd"), 0.9, 0.9, 0.9)
glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Ks"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "lightPosition"), -3, 0, 3)
glUniform1ui(glGetUniformLocation(pipeline.shaderProgram, "shininess"), 100)
glUniform1f(glGetUniformLocation(pipeline.shaderProgram, "constantAttenuation"), 0.001)
glUniform1f(glGetUniformLocation(pipeline.shaderProgram, "linearAttenuation"), 0.1)
glUniform1f(glGetUniformLocation(pipeline.shaderProgram, "quadraticAttenuation"), 0.01)
# Setting up the projection transform
projection = tr.perspective(60, float(width)/float(height), 0.1, 100)
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "projection"), 1, GL_TRUE, projection)
glUseProgram(mvpPipeline.shaderProgram)
glUniformMatrix4fv(glGetUniformLocation(mvpPipeline.shaderProgram, "projection"), 1, GL_TRUE, projection)
glUniformMatrix4fv(glGetUniformLocation(mvpPipeline.shaderProgram, "model"), 1, GL_TRUE, tr.identity())
t0 = glfw.get_time()
camera_theta = -3*np.pi/4
perfMonitor = pm.PerformanceMonitor(glfw.get_time(), 0.5)
# glfw will swap buffers as soon as possible
glfw.swap_interval(0)
while not glfw.window_should_close(window):
# Measuring performance
perfMonitor.update(glfw.get_time())
glfw.set_window_title(window, title + str(perfMonitor))
# Using GLFW to check for input events
glfw.poll_events()
# Getting the time difference from the previous iteration
t1 = glfw.get_time()
dt = t1 - t0
t0 = t1
if (glfw.get_key(window, glfw.KEY_LEFT) == glfw.PRESS):
camera_theta -= 2 * dt
if (glfw.get_key(window, glfw.KEY_RIGHT) == glfw.PRESS):
camera_theta += 2* dt
# Setting up the view transform
R = 12
camX = R * np.sin(camera_theta)
camY = R * np.cos(camera_theta)
viewPos = np.array([camX, camY, 7])
view = tr.lookAt(
viewPos,
np.array([0,0,1]),
np.array([0,0,1])
)
# Clearing the screen in both, color and depth
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Filling or not the shapes depending on the controller state
if (controller.fillPolygon):
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
else:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
# Drawing shapes
glUseProgram(pipeline.shaderProgram)
glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "viewPosition"), viewPos[0], viewPos[1], viewPos[2])
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "view"), 1, GL_TRUE, view)
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "model"), 1, GL_TRUE, tr.uniformScale(3))
pipeline.drawCall(gpuSuzanne)
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "model"), 1, GL_TRUE,
tr.matmul([
tr.uniformScale(3),
tr.rotationX(np.pi/2),
tr.translate(1.5,-0.25,0)])
)
pipeline.drawCall(gpuCarrot)
glUseProgram(mvpPipeline.shaderProgram)
glUniformMatrix4fv(glGetUniformLocation(mvpPipeline.shaderProgram, "view"), 1, GL_TRUE, view)
mvpPipeline.drawCall(gpuAxis, GL_LINES)
# Once the drawing is rendered, buffers are swap so an uncomplete drawing is never seen.
glfw.swap_buffers(window)
# freeing GPU memory
gpuAxis.clear()
gpuSuzanne.clear()
gpuCarrot.clear()
glfw.terminate()