How to load 3D models of "obj" files to a Pyopengl application?

Asked

Viewed 1,893 times

1

How to take a ". obj" and import to Pyopengl? ex: take a 3D model of Blender and place it in a scene in Pyopengl?

1 answer

3

To import 3D graphics files (e.g., Wavefront obj, Collada, etc.) in an application Pyopengl, 4 simple operations are required:

  • Create a dialog for the application
  • Configure the parameters of Opengl
  • Load data from file(s) (s) to data structures within the program (and other application components)
  • Create a looping which: at each step, transfers the data to Opengl (display) and changes the properties of objects (update)

Modeling of the Objects

In the Blender (or any other 3D tool), the objects are formed by various components, for example:

  • Geometry (vertices, faces, UV coordinates of textures, etc.)
  • Materials (dissemination, reflection, transparency, etc.)
  • Textures (images, Bump maps, Displacement maps, etc.)

When exporting the template to a file obj, there are several options to choose what will be exported (eg include UV, Normal, etc.).

Below is a screenshot of the options menu to export a template or object to the format obj in Blender version 2.76b:

Menu de opções de exportação de arquivos WaveFront obj, do software Blender versão 2.76b

The more details you export, the more complex the application development, which will need to handle these details.

Example of generated files:

The image below represents a simple cube (only the geometry has been defined):

Cubo simples, apenas a geometria foi definida

This cube, when exported, generates the following file obj:

# Blender v2.76 (sub 0) OBJ File: ''
# www.blender.org
o Cube
v 1.000000 0.000000 -1.000000
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 1.000000
v -1.000000 0.000000 -1.000000
v 1.000000 2.000000 -0.999999
v 0.999999 2.000000 1.000001
v -1.000000 2.000000 1.000000
v -1.000000 2.000000 -1.000000
s off
f 2 3 4
f 8 7 6
f 5 6 2
f 6 7 3
f 3 7 8
f 1 4 8
f 1 2 4
f 5 8 6
f 1 5 2
f 2 6 3
f 4 3 8
f 5 1 8

The image below represents a more complex cube, with materials and lighting:

inserir a descrição da imagem aqui

When exported, this cube generates 2 files:

A file obj with the definition of geometry:

# Blender v2.76 (sub 0) OBJ File: ''
# www.blender.org
mtllib cubo.mtl
o Cube
v 1.000000 0.000000 -1.000000
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 1.000000
v -1.000000 0.000000 -1.000000
v 1.000000 2.000000 -0.999999
v 0.999999 2.000000 1.000001
v -1.000000 2.000000 1.000000
v -1.000000 2.000000 -1.000000
vt 0.666467 0.333134
vt 0.333533 0.333134
vt 0.333533 0.000200
vt 0.666467 0.000200
vt 0.333134 0.333133
vt 0.000200 0.333134
vt 0.000200 0.000200
vt 0.333133 0.000200
vt 0.333134 0.333533
vt 0.333133 0.666467
vt 0.000200 0.666467
vt 0.000200 0.333533
vt 0.333134 0.666866
vt 0.333133 0.999800
vt 0.000200 0.999800
vt 0.000200 0.666866
vt 0.666867 0.333134
vt 0.666867 0.000200
vt 0.999800 0.000200
vt 0.999800 0.333134
vt 0.666467 0.333533
vt 0.666467 0.666467
vt 0.333533 0.666467
vt 0.333533 0.333533
vn 0.000000 -1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 1.000000 0.000000 0.000000
vn -0.000000 -0.000000 1.000000
vn -1.000000 -0.000000 -0.000000
vn 0.000000 0.000000 -1.000000
usemtl Material.001
s off
f 1/1/1 2/2/1 3/3/1 4/4/1
f 5/5/2 8/6/2 7/7/2 6/8/2
f 1/9/3 5/10/3 6/11/3 2/12/3
f 2/13/4 6/14/4 7/15/4 3/16/4
f 3/17/5 7/18/5 8/19/5 4/20/5
f 5/21/6 1/22/6 4/23/6 8/24/6

And one (or more) files mtl, with the material libraries:

# Blender MTL File: 'cubo.blend'
# Material Count: 2

newmtl Material.001
Ns 96.078431
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2

Application Window

Before starting Opengl, you need to create a execution context ("application window" ) where scene rendering will occur.

Below are four examples of libraries that manage this context (but there are others):

And below, a code snippet to start a window with the GLFW library:

import pyglfw.pyglfw as glfw
import OpenGL.GL as GL

# Inicializa o GLFW
if (not(glfw.init())):
      raise Exception("Impossivel criar a janela GLFW!!!!")

# Configura os parâmetros da janela que será criada
glfw.Window.hint(client_api=glfw.Window.OPENGL_API)
glfw.Window.hint(resizable=False)
glfw.Window.hint(visible=False)

# Cria a janela e guarda uma referência a ela
winHandle = glfw.Window(LARGURA_JANELA, ALTURA_JANELA, "Teste OpenGL")
if (winHandle == 0):
    raise Exception("Impossivel criar a janela!!!")

# Seta o contexto corrente para OpenGL
winHandle.make_current()

#--------------------------------------------------------
# Aqui, deve-se configurar todos os parâmetros do OpenGL
# e carregar os arquivos necessários para a aplicação.
#--------------------------------------------------------

# Tempo de atualização da janela.
# Quanto menor, mais rápido
winHandle.swap_interval(2)

# Abre a janela
winHandle.show()

Configuration of Opengl

The configuration of Opengl depends a lot on the version used and the type of application that will be developed.

Example of settings:

# Configura o tamanho do Viewport
GL.glViewport(0, 0, LARGURA_JANELA, ALTURA_JANELA)

# Seta a cor preta como cor de fundo
GL.glClearColor(0.0, 0.0, 0.0, 1.0)

File Load

If you use the pyglet package (with Pywavefront) or pygame, the ideal is to use the available functions to load the files obj.

If you choose to use a library that nay supports reading of files obj, you can mount a module to open the file (ex: open('arquivo.obj', 'r')), and read the data according to the standard:

Wikipedia - Wavefront . obj file

OBJ specification

In addition to the files with the templates, you will need to upload as well:

  • textures and other images, which can be loaded with the library PIL
  • the shaders (if you use)
  • other application files

If you use shaders in the application, a tip is you install a library to perform 3D calculations with vectors and matrices, such as the Pyrr.

And finally:

Looping Principal

In the main looping, you will move the objects, lighting, etc.

Below is an example of this looping (GLFW):

# Enquanto não houver uma solicitação para fechar a janela
while(not(winHandle.should_close)):
    # Limpa a tela
    GL.glClear(GL.GL_COLOR_BUFFER_BIT)

    # Renderiza a cena - nesta função, você irá desenvolver o
    # processo que alimenta o opengl com os dados da cena (ex: modelos,
    # imagens, texturas, etc.)
    render()

    # Apresenta a cena no dispositivo de saída
    winHandle.swap_buffers()

    # Atualiza estado da aplicação - nesta função, você
    # aplica a lógica do programa  (ex: move objetos, 
    # efetua cálculos de inteligência artificial, 
    # transfere dados, etc.)
    update()

    # Processa eventos do sistema
    glfw.poll_events()

Wikipedia - Index - Category: Computer graphics
(suggestion: consult the English version as well)

Updating:

More programming references with Pyopengl:

Modern Opengl tutorial (python) - Nicolas P. Rougier

Openglcontext Python Tutorials

2D Graphics Rendering tutorial with Pyopengl - Cyrille Rossant, Phd

Download Codes - Jestermons Python Pitstop

3D PROGRAMMING IN PYTHON - PART 1 (older version of Opengl, no use of VBO)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.