gpu.8.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """
  2. Generate a texture using Offscreen Rendering
  3. --------------------------------------------
  4. #. Create an :class:`gpu.types.GPUOffScreen` object.
  5. #. Draw some circles into it.
  6. #. Make a new shader for drawing a planar texture in 3D.
  7. #. Draw the generated texture using the new shader.
  8. """
  9. import bpy
  10. import gpu
  11. import bgl
  12. from mathutils import Matrix
  13. from gpu_extras.batch import batch_for_shader
  14. from gpu_extras.presets import draw_circle_2d
  15. # Create and fill offscreen
  16. ##########################################
  17. offscreen = gpu.types.GPUOffScreen(512, 512)
  18. with offscreen.bind():
  19. bgl.glClear(bgl.GL_COLOR_BUFFER_BIT)
  20. with gpu.matrix.push_pop():
  21. # reset matrices -> use normalized device coordinates [-1, 1]
  22. gpu.matrix.load_matrix(Matrix.Identity(4))
  23. gpu.matrix.load_projection_matrix(Matrix.Identity(4))
  24. amount = 10
  25. for i in range(-amount, amount + 1):
  26. x_pos = i / amount
  27. draw_circle_2d((x_pos, 0.0), (1, 1, 1, 1), 0.5, 200)
  28. # Drawing the generated texture in 3D space
  29. #############################################
  30. vertex_shader = '''
  31. uniform mat4 modelMatrix;
  32. uniform mat4 viewProjectionMatrix;
  33. in vec2 position;
  34. in vec2 uv;
  35. out vec2 uvInterp;
  36. void main()
  37. {
  38. uvInterp = uv;
  39. gl_Position = viewProjectionMatrix * modelMatrix * vec4(position, 0.0, 1.0);
  40. }
  41. '''
  42. fragment_shader = '''
  43. uniform sampler2D image;
  44. in vec2 uvInterp;
  45. void main()
  46. {
  47. gl_FragColor = texture(image, uvInterp);
  48. }
  49. '''
  50. shader = gpu.types.GPUShader(vertex_shader, fragment_shader)
  51. batch = batch_for_shader(
  52. shader, 'TRI_FAN',
  53. {
  54. "position": ((-1, -1), (1, -1), (1, 1), (-1, 1)),
  55. "uv": ((0, 0), (1, 0), (1, 1), (0, 1)),
  56. },
  57. )
  58. def draw():
  59. bgl.glActiveTexture(bgl.GL_TEXTURE0)
  60. bgl.glBindTexture(bgl.GL_TEXTURE_2D, offscreen.color_texture)
  61. shader.bind()
  62. shader.uniform_float("modelMatrix", Matrix.Translation((1, 2, 3)) @ Matrix.Scale(3, 4))
  63. shader.uniform_float("viewProjectionMatrix", bpy.context.region_data.perspective_matrix)
  64. shader.uniform_float("image", 0)
  65. batch.draw(shader)
  66. bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW')