Alex8433

mankey

Jun 20th, 2020 (edited)
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1.  
  2.  
  3. '''
  4. 3D Rotating Monkey Head
  5. ========================
  6.  
  7. This example demonstrates using OpenGL to display a rotating monkey head. This
  8. includes loading a Blender OBJ file, shaders written in OpenGL's Shading
  9. Language (GLSL), and using scheduled callbacks.
  10.  
  11. The monkey.obj file is an OBJ file output from the Blender free 3D creation
  12. software. The file is text, listing vertices and faces and is loaded
  13. using a class in the file objloader.py. The file simple.glsl is
  14. a simple vertex and fragment shader written in GLSL.
  15. '''
  16.  
  17. from kivy.app import App
  18. from kivy.clock import Clock
  19. from kivy.core.window import Window
  20. from kivy.uix.widget import Widget
  21. from kivy.resources import resource_find
  22. from kivy.graphics.transformation import Matrix
  23. from kivy.graphics.opengl import glEnable, glDisable, GL_DEPTH_TEST
  24. from kivy.graphics import RenderContext, Callback, PushMatrix, PopMatrix, \
  25. Color, Translate, Rotate, Mesh, UpdateNormalMatrix
  26. from objloader import ObjFile
  27.  
  28.  
  29. class Renderer(Widget):
  30. def __init__(self, **kwargs):
  31. self.canvas = RenderContext(compute_normal_mat=True)
  32. self.canvas.shader.source = resource_find('simple.glsl')
  33. self.scene = ObjFile(resource_find("monkey.obj"))
  34. super(Renderer, self).__init__(**kwargs)
  35. with self.canvas:
  36. self.cb = Callback(self.setup_gl_context)
  37. PushMatrix()
  38. self.setup_scene()
  39. PopMatrix()
  40. self.cb = Callback(self.reset_gl_context)
  41. Clock.schedule_interval(self.update_glsl, 1 / 60.)
  42.  
  43. def setup_gl_context(self, *args):
  44. glEnable(GL_DEPTH_TEST)
  45.  
  46. def reset_gl_context(self, *args):
  47. glDisable(GL_DEPTH_TEST)
  48.  
  49. def update_glsl(self, delta):
  50. asp = self.width / float(self.height)
  51. proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
  52. self.canvas['projection_mat'] = proj
  53. self.canvas['diffuse_light'] = (1.0, 1.0, 0.8)
  54. self.canvas['ambient_light'] = (0.1, 0.1, 0.1)
  55. self.rot.angle += delta * 100
  56.  
  57. def setup_scene(self):
  58. Color(1, 1, 1, 1)
  59. PushMatrix()
  60. Translate(0, 0, -3)
  61. self.rot = Rotate(1, 0, 1, 0)
  62. m = list(self.scene.objects.values())[0]
  63. UpdateNormalMatrix()
  64. self.mesh = Mesh(
  65. vertices=m.vertices,
  66. indices=m.indices,
  67. fmt=m.vertex_format,
  68. mode='triangles',
  69. )
  70. PopMatrix()
  71.  
  72.  
  73. class RendererApp(App):
  74. def build(self):
  75. return Renderer()
  76.  
  77.  
  78. if __name__ == "__main__":
  79. RendererApp().run()
  80.  
Add Comment
Please, Sign In to add comment