blender/doc/python_api/examples/gpu.8.py
Oktay Comu 7818ee73b2 Fix #147614: Update docs with faster copy of pixels in GPU Module example
This PR updates the [Copy Off-screen Rendering result back to RAM
example in the Python GPU Module docs. As recommended by @Lia-32 in
#147614, copying the buffer using the list slicing notation is much
faster than the list comprehension currently used in the example.

Pull Request: https://projects.blender.org/blender/blender/pulls/163354
2026-09-16 07:43:35 +02:00

48 lines
1.3 KiB
Python

"""
Copy Off-screen Rendering result back to RAM
--------------------------------------------
This will create a new image with the given name.
If it already exists, it will override the existing one.
"""
import bpy
import gpu
import random
from mathutils import Matrix
from gpu_extras.presets import draw_circle_2d
IMAGE_NAME = "Generated Image"
WIDTH = 512
HEIGHT = 512
RING_AMOUNT = 10
offscreen = gpu.types.GPUOffScreen(WIDTH, HEIGHT)
with offscreen.bind():
fb = gpu.state.active_framebuffer_get()
fb.clear(color=(0.0, 0.0, 0.0, 0.0))
with gpu.matrix.push_pop():
# Reset matrices -> use normalized device coordinates [-1, 1].
gpu.matrix.load_matrix(Matrix.Identity(4))
gpu.matrix.load_projection_matrix(Matrix.Identity(4))
for i in range(RING_AMOUNT):
draw_circle_2d(
(random.uniform(-1, 1), random.uniform(-1, 1)),
(1, 1, 1, 1), random.uniform(0.1, 1),
segments=20,
)
buffer = fb.read_color(0, 0, WIDTH, HEIGHT, 4, 0, 'FLOAT')
offscreen.free()
if IMAGE_NAME not in bpy.data.images:
bpy.data.images.new(IMAGE_NAME, WIDTH, HEIGHT)
image = bpy.data.images[IMAGE_NAME]
image.scale(WIDTH, HEIGHT)
buffer.dimensions = WIDTH * HEIGHT * 4
image.pixels[:] = buffer