Foros del Web » Programando para Internet » Python »

necesita ayuda con python y opengl

Estas en el tema de necesita ayuda con python y opengl en el foro de Python en Foros del Web. el tema es este tengo un modelo del 3ds max en formato .obj y tengo este cargador de textura ke se llama Texture2D.py: from OpenGL.GL ...
  #1 (permalink)  
Antiguo 06/12/2010, 13:45
 
Fecha de Ingreso: diciembre-2010
Mensajes: 162
Antigüedad: 13 años, 4 meses
Puntos: 1
Pregunta necesita ayuda con python y opengl

el tema es este tengo un modelo del 3ds max en formato .obj y tengo este cargador de textura ke se llama Texture2D.py:


from OpenGL.GL import *
from OpenGL.GLU import *
import Image


class Texture2D:
def __init__(self, file, wrap=GL_REPEAT, minFilter=GL_LINEAR, magFilter=GL_LINEAR, texenv=GL_MODULATE):
self.file = file
self.wrapS = wrap
self.wrapT = wrap
self.minFilter = minFilter
self.magFilter = magFilter
self.texenv = texenv
self.defined = False
self.id = 0

def define(self):
img = Image.open(self.file).transpose(Image.FLIP_TOP_BOT TOM).convert('RGBA')
width = 2
while width < img.size[0]: width *= 2
width /= 2
height = 2
while height < img.size[1]: height *= 2
height /= 2
if (width != img.size[0]) or (height != img.size[1]):
img = img.resize((width,height))

self.id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, self.id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, self.wrapS)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, self.wrapT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, self.minFilter)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, self.magFilter)
if (self.minFilter == GL_NEAREST_MIPMAP_NEAREST) or \
(self.minFilter == GL_NEAREST_MIPMAP_LINEAR) or \
(self.minFilter == GL_LINEAR_MIPMAP_NEAREST) or \
(self.minFilter == GL_LINEAR_MIPMAP_LINEAR):
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, img.size[0], img.size[1],
GL_RGBA, GL_UNSIGNED_BYTE, img.tostring())
else:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.size[0], img.size[1],
0, GL_RGBA, GL_UNSIGNED_BYTE, img.tostring())
glBindTexture(GL_TEXTURE_2D, 0)
self.defined = True

def apply(self):
if not self.defined:
self.define()
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, self.texenv)
glBindTexture(GL_TEXTURE_2D, self.id)
if self.id != 0:
glEnable(GL_TEXTURE_2D)
else:
glDisable(GL_TEXTURE_2D)

def disable(self):
glBindTexture(GL_TEXTURE_2D, 0)
glDisable(GL_TEXTURE_2D)

despues tengo el cargador de modelo ke se llama LOADEROBJ.py:

import string
from OpenGL.GL import *
from Texture2D import *


class OBJFace:
def __init__(self, vertices, normals, texcoords, obj):
self.vertices = vertices
self.normals = normals
self.texcoords = texcoords
self.obj = obj
def draw(self):
glBegin(GL_POLYGON)
for i in range(0, len(self.vertices)):
if self.normals[i] > 0:
glNormal3fv(self.obj.normals[self.normals[i] - 1])
if self.texcoords[i] > 0:
glTexCoord2fv(self.obj.texcoords[self.texcoords[i] - 1])
glVertex3fv(self.obj.vertices[self.vertices[i] - 1])
glEnd()

class OBJUseMtl:
def __init__(self, mtl):
self.material = mtl
def draw(self):
if self.material.has_key('Ka'):
glMaterialfv(GL_FRONT, GL_AMBIENT, self.material['Ka'])
else:
glMaterialfv(GL_FRONT, GL_AMBIENT, [0, 0, 0, 0])
if self.material.has_key('Kd'):
glMaterialfv(GL_FRONT, GL_DIFFUSE, self.material['Kd'])
else:
glMaterialfv(GL_FRONT, GL_DIFFUSE, [0, 0, 0, 0])
if self.material.has_key('Ks'):
glMaterialfv(GL_FRONT, GL_SPECULAR, self.material['Ks'])
else:
glMaterialfv(GL_FRONT, GL_SPECULAR, [0, 0, 0, 0])
if self.material.has_key('Ns'):
glMaterialf(GL_FRONT, GL_SHININESS, self.material['Ns'])
if self.material.has_key('map_Kd'):
self.material['map_Kd'].apply()
else:
glDisable(GL_TEXTURE_2D)

class OBJFile:
def __init__(self, filename):
self.vertices = []
self.normals = []
self.texcoords = []
self.materials = {}
self.commands = []
file = open(filename, "r")
lines = file.readlines()
for line in lines:
values = string.split(line)
if len(values) < 1:
continue
if values[0] == 'v':
x = string.atof(values[1])
y = string.atof(values[2])
z = string.atof(values[3])
self.vertices.append([x,y,z])
elif values[0] == 'vn':
x = string.atof(values[1])
y = string.atof(values[2])
z = string.atof(values[3])
self.normals.append([x,y,z])
elif values[0] == 'vt':
s = string.atof(values[1])
t = string.atof(values[2])
self.texcoords.append([s,t])
elif values[0] == 'mtllib':
self.loadMtllib(values[1])
elif values[0] == 'f':
face = []
texcoords = []
norms = []
for v in values[1:]:
w = string.split(v,'/')
face.append(string.atoi(w[0]))
if len(w) >= 2 and len(w[1]) > 0:
texcoords.append(string.atoi(w[1]))
else:
texcoords.append(0)

AHORA HICE ESTE PROGRAMA:

from OpenGL.GL import*
from OpenGL.GLUT import*
from OpenGL.GLU import*
try:
from LOADEROBJ import*
except:
print "no se pudo cargar archivo"

def dibujar():

#limpia la pantalla y el buffer de profundidad
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT)
glClearColor(1,1,1,1)
glLoadIdentity()



glutSwapBuffers()


def main():

glutInit(())
glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RG BA)
glutInitWindowSize(600,600)
glutInitWindowPosition(0,0)
glutCreateWindow("hola")
glutDisplayFunc(dibujar)

glutMainLoop()

main()
EL PROBLEMA ES QUE ME SALE LA PANTALLA EN NEGRO Y NINGUN MODELO.
EN file=open(filename,"r") le coloque filename a "pelotita2.obj" por ejemplo ke es mi modelo PERO NO HAY CASO NO ME MUESTRA LA ESFERA LA TEXTURA LA ETENGO EN TGA. LUEGO PROBE CON UNA COPIA DE LA ESFERA EXPORTANDOLA NUEVAMENTE A .OBJ Y CON UNA TEXTURA CON UNA IMAGEN DE MAPA DE BITS PERO TAMPOCO ME CARGA EL MODELO: POR FAVOR QUE ALGUIEN ME RESPONDE ESTOY REALMENTE INTERESADO EN CARGAR UN MODELITO EN OPENGL CON PYTHON.
  #2 (permalink)  
Antiguo 06/12/2010, 16:05
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: necesita ayuda con python y opengl

Nunca estas creando instancias de esas clases.
  #3 (permalink)  
Antiguo 06/12/2010, 18:47
 
Fecha de Ingreso: diciembre-2010
Mensajes: 162
Antigüedad: 13 años, 4 meses
Puntos: 1
Pregunta Respuesta: necesita ayuda con python y opengl

bueno y la instancia a las clases las hago en el tercer archivo/programa no?? y en ese caso hago instancias de todas las clases tanto de loaderobj.py y de texture2d.py? o solo de loader.py? gracias hermano por responderme sos un genio
  #4 (permalink)  
Antiguo 07/12/2010, 09:52
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: necesita ayuda con python y opengl

Si las instancias las haces en el main.

En cuanto a la estructura de las clases no se exactamente como funcionen, ya que no están documentadas y no parece ser intuitivo el uso de esas clases.

Hay muchas cosas que se pueden simplificar, por ejemplo en lugar de has_key para saber si un diccionario tiene un elemento pudiste haber usado el operador in.

En vez de importar string y usar atof, pudiste haber usado float.

Aquí dejo el script, formateado bonito y en un solo archivo.
Código Python:
Ver original
  1. import string
  2. from OpenGL.GL import *
  3. from OpenGL.GLU import *
  4. from OpenGL.GLUT import *
  5. import Image
  6.  
  7.  
  8. class Texture2D:
  9.     def __init__(self, file, wrap=GL_REPEAT, minFilter=GL_LINEAR, magFilter=GL_LINEAR, texenv=GL_MODULATE):
  10.         self.file = file
  11.         self.wrapS = wrap
  12.         self.wrapT = wrap
  13.         self.minFilter = minFilter
  14.         self.magFilter = magFilter
  15.         self.texenv = texenv
  16.         self.defined = False
  17.         self.id = 0
  18.  
  19.     def define(self):
  20.         img = Image.open(self.file).transpose(Image.FLIP_TOP_BOTTOM).convert('RGBA')
  21.         width = 2
  22.         while width < img.size[0]: width *= 2
  23.         width /= 2
  24.         height = 2
  25.         while height < img.size[1]: height *= 2
  26.         height /= 2
  27.         if (width != img.size[0]) or (height != img.size[1]):
  28.             img = img.resize((width,height))
  29.        
  30.         self.id = glGenTextures(1)
  31.         glBindTexture(GL_TEXTURE_2D, self.id)
  32.         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, self.wrapS)
  33.         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, self.wrapT)
  34.         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, self.minFilter)
  35.         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, self.magFilter)
  36.         if (self.minFilter == GL_NEAREST_MIPMAP_NEAREST) or \
  37.            (self.minFilter == GL_NEAREST_MIPMAP_LINEAR) or \
  38.            (self.minFilter == GL_LINEAR_MIPMAP_NEAREST) or \
  39.            (self.minFilter == GL_LINEAR_MIPMAP_LINEAR):
  40.             gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, img.size[0], img.size[1],
  41.                                 GL_RGBA, GL_UNSIGNED_BYTE, img.tostring())
  42.         else:
  43.             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.size[0], img.size[1],
  44.                            0, GL_RGBA, GL_UNSIGNED_BYTE, img.tostring())
  45.         glBindTexture(GL_TEXTURE_2D, 0)
  46.         self.defined = True
  47.  
  48.     def apply(self):
  49.         if not self.defined:
  50.             self.define()
  51.         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, self.texenv)
  52.         glBindTexture(GL_TEXTURE_2D, self.id)
  53.         if self.id != 0:
  54.             glEnable(GL_TEXTURE_2D)
  55.         else:
  56.             glDisable(GL_TEXTURE_2D)
  57.  
  58.     def disable(self):
  59.         glBindTexture(GL_TEXTURE_2D, 0)
  60.         glDisable(GL_TEXTURE_2D)
  61.  
  62. #despues tengo el cargador de modelo ke se llama LOADEROBJ.py:
  63.  
  64. class OBJFace:
  65.     def __init__(self, vertices, normals, texcoords, obj):
  66.         self.vertices = vertices
  67.         self.normals = normals
  68.         self.texcoords = texcoords
  69.         self.obj = obj
  70.     def draw(self):
  71.         glBegin(GL_POLYGON)
  72.         for i in range(0, len(self.vertices)):
  73.             if self.normals[i] > 0:
  74.                 glNormal3fv(self.obj.normals[self.normals[i] - 1])
  75.             if self.texcoords[i] > 0:
  76.                 glTexCoord2fv(self.obj.texcoords[self.texcoords[i] - 1])
  77.             glVertex3fv(self.obj.vertices[self.vertices[i] - 1])
  78.         glEnd()
  79.  
  80. class OBJUseMtl:
  81.     def __init__(self, mtl):
  82.         self.material = mtl
  83.     def draw(self):
  84.         if self.material.has_key('Ka'):
  85.             glMaterialfv(GL_FRONT, GL_AMBIENT, self.material['Ka'])
  86.         else:
  87.             glMaterialfv(GL_FRONT, GL_AMBIENT, [0, 0, 0, 0])
  88.         if self.material.has_key('Kd'):
  89.             glMaterialfv(GL_FRONT, GL_DIFFUSE, self.material['Kd'])
  90.         else:
  91.             glMaterialfv(GL_FRONT, GL_DIFFUSE, [0, 0, 0, 0])
  92.         if self.material.has_key('Ks'):
  93.             glMaterialfv(GL_FRONT, GL_SPECULAR, self.material['Ks'])
  94.         else:
  95.             glMaterialfv(GL_FRONT, GL_SPECULAR, [0, 0, 0, 0])
  96.         if self.material.has_key('Ns'):
  97.             glMaterialf(GL_FRONT, GL_SHININESS, self.material['Ns'])
  98.         if self.material.has_key('map_Kd'):
  99.             self.material['map_Kd'].apply()
  100.         else:
  101.             glDisable(GL_TEXTURE_2D)
  102.  
  103. class OBJFile:
  104.     def __init__(self, filename):
  105.         self.vertices = []
  106.         self.normals = []
  107.         self.texcoords = []
  108.         self.materials = {}
  109.         self.commands = []
  110.         file = open(filename, "r")
  111.         lines = file.readlines()
  112.         for line in lines:
  113.             values = string.split(line)
  114.             if len(values) < 1:
  115.                 continue
  116.             if values[0] == 'v':
  117.                 x = string.atof(values[1])
  118.                 y = string.atof(values[2])
  119.                 z = string.atof(values[3])
  120.                 self.vertices.append([x,y,z])
  121.             elif values[0] == 'vn':
  122.                 x = string.atof(values[1])
  123.                 y = string.atof(values[2])
  124.                 z = string.atof(values[3])
  125.                 self.normals.append([x,y,z])
  126.             elif values[0] == 'vt':
  127.                 s = string.atof(values[1])
  128.                 t = string.atof(values[2])
  129.                 self.texcoords.append([s,t])
  130.             elif values[0] == 'mtllib':
  131.                 self.loadMtllib(values[1])
  132.             elif values[0] == 'f':
  133.                 face = []
  134.                 texcoords = []
  135.                 for v in values[1:]:
  136.                     w = string.split(v,'/')
  137.                     face.append(string.atoi(w[0]))
  138.                     if len(w) >= 2 and len(w[1]) > 0:
  139.                         texcoords.append(string.atoi(w[1]))
  140.                     else:
  141.                         texcoords.append(0)
  142.  
  143. def dibujar():
  144.     #limpia la pantalla y el buffer de profundidad
  145.     glClearColor(0, 0, 0, 0)
  146.     glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT)
  147.     glLoadIdentity()
  148.    
  149.    
  150.  
  151.     glutSwapBuffers()
  152.    
  153.    
  154. def main():
  155.     glutInit(())
  156.     glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA)
  157.     glutInitWindowSize(600,600)
  158.     glutInitWindowPosition(0,0)
  159.     glutCreateWindow("hola")
  160.     glutDisplayFunc(dibujar)
  161.        
  162.     glutMainLoop()
  163.  
  164. main()
  #5 (permalink)  
Antiguo 07/12/2010, 10:31
 
Fecha de Ingreso: diciembre-2010
Mensajes: 162
Antigüedad: 13 años, 4 meses
Puntos: 1
Respuesta: necesita ayuda con python y opengl

muchas gracias, por la respuesta nunca habia escrito a un foro. de todas formas me puse a leer sobre clases en python para entenderlo mejor
  #6 (permalink)  
Antiguo 08/12/2010, 09:28
 
Fecha de Ingreso: diciembre-2010
Mensajes: 162
Antigüedad: 13 años, 4 meses
Puntos: 1
Pregunta Respuesta: necesita ayuda con python y opengl

bueno mira en la clase objfile cambie en las condiciones if x=strin.atof

por x=float como me dijiste ahora tengo este problema ke no se como usar esos numeros flotantes que lee de un archivo de texto el tema es ke en opengl uso para dibujar
glVertex3f(0.1,2.0,0.0) no?? y ahi tengo un vertice
como paso ahora los datos flotantes de x,y y z de la lista vertices al que le anexo esos valores x, y, y z. yo entendi que en la clase OBJFile del archivo LOADEROBJ crea listas vacias primero y despues le va agregando los valores flotantes x,y, y z. espero haber entendido bien, pero como uso esos numeros flotantes para dibujar un cubo y meterlos en opengl para ke dibuje con glVertex3f(valor x, valor y, valor z) ahi me kede confundido
  #7 (permalink)  
Antiguo 08/12/2010, 09:41
 
Fecha de Ingreso: diciembre-2010
Mensajes: 162
Antigüedad: 13 años, 4 meses
Puntos: 1
Pregunta puedo seguir preguntando??

bueno mira en la clase objfile cambie en las condiciones if x=string.atof

por x=float como me dijiste ahora tengo este problema ke no se como usar esos numeros flotantes que lee de un archivo de texto el tema es ke en opengl uso para dibujar
glVertex3f(0.1,2.0,0.0) no?? y ahi tengo un vertice
como paso ahora los datos flotantes de x,y y z de la lista vertices al que le anexo esos valores x, y, y z. yo entendi que en la clase OBJFile del archivo LOADEROBJ crea listas vacias primero y despues le va agregando los valores flotantes x,y, y z. espero haber entendido bien, pero como uso esos numeros flotantes para dibujar un cubo y meterlos en opengl para ke dibuje con glVertex3f(valor x, valor y, valor z) ahi me kede confundido
  #8 (permalink)  
Antiguo 09/12/2010, 21:34
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: necesita ayuda con python y opengl

A si se me había olvidado, no tengo el archivo con el que estas trabajando.

Mas o menos entiendo las clases:
Haces una clase OBJFile y luego le pasas materiales, vertices, textcoords, etc... a la OBJFace
Y al final en el método dibujar utilizas los métodos draw de los objetos que creaste.
  #9 (permalink)  
Antiguo 10/12/2010, 10:57
 
Fecha de Ingreso: diciembre-2010
Mensajes: 162
Antigüedad: 13 años, 4 meses
Puntos: 1
Respuesta: necesita ayuda con python y opengl

bueno mira quise tomar una parte de todo el codigo e ir por partes y me decis si voy bien:
class cargarobj:
def __init__(self,filename):
self.vertices=[] #crea una lista vacia llamada vertice
self.normales=[] #crea una lista vacia llamada normales
self.texcoords=[]
file=open(filename,"r") #define funcion de apertura de archivo para lectura
lines=file.readlines()
for line in lines:
valores=string.split(line)
if len(valores)<1:
continue
if valores[0]=="v":
x=float(valores[1])
y=float(valores[2])
z=float(valores[3])
self.vertices.append([x,y,z]) #anexa x, y, y z a la lista vertices
#imprime en pantalla valores de vertices
print "los valores de vertices son:",([x,y,z])
if valores[0]=="vn":
x=float(valores[1])
y=float(valores[2])
z=float(valores[3])
self.normales.append([x,y,z]) #anexa x,y, y z a la lista normales
#imprime en pantalla valores de normales
print "los valores de normales son:",([x,y,z])
if valores[0]=="vt":
x=float(valores[1])
y=float(valores[2])
z=float(valores[3])
self.texcoords.append([x,y,z])
print "los valores de coordenadas de textura son:", ([x,y,z])


d=cargarobj("CUBO.obj")

cambie como te dije string.atof por float en todos los if. decime si voy bien al principio la clase crea listas vacias llamadas vertices normales texcoords. Una duda es si ([x,y,z]) lo toma como un solo elemento anexado con append a vertices,o sea no tres elemento x y y z me entendes?. Le agregue un print para saber ke iba bien el codigo. luego d=cargarobj es una instancia de la clase no? mejor voy por partes porke soy autodidacta ni sikiera he estudiado programacion ni nada por el estilo. y recien voy agarrandole la mano un poco a python.
  #10 (permalink)  
Antiguo 10/12/2010, 11:02
 
Fecha de Ingreso: diciembre-2010
Mensajes: 162
Antigüedad: 13 años, 4 meses
Puntos: 1
Pregunta Respuesta: necesita ayuda con python y opengl

sigo preguntando algo ke me kedo en el tintero:
en if valores[0]=="v": El [0] significa el primer elemento de la lista no?? ke si el primer elemento de la lista es v ejecuta el if, voy bien?

Etiquetas: cargarmodelo, opengl, pyopengl
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 12:15.