pyglet.graphics.draw

class Batch(
context: SurfaceContext | None = None,
initial_count: int = 32,
) → None

Manage a collection of drawables for batched rendering.

Many drawable pyglet objects accept an optional Batch argument in their constructors. By giving a Batch to multiple objects, you can tell pyglet that you expect to draw all of these objects at once, so it can optimise its use of OpenGL. Hence, drawing a Batch is often much faster than drawing each contained drawable separately.

The following example creates a batch, adds two sprites to the batch, and then draws the entire batch:

batch = pyglet.graphics.Batch()
car = pyglet.sprite.Sprite(car_image, batch=batch)
boat = pyglet.sprite.Sprite(boat_image, batch=batch)

def on_draw():
    batch.draw()

While any drawables can be added to a Batch, only those with the same draw mode, shader program, and group can be optimised together.

Internally, a Batch manages a set of VertexDomains along with information about how the domains are to be drawn. To implement batching on a custom drawable, get your vertex domains from the given batch instead of setting them up yourself.

Initialize a graphics batch.

Parameters:
  • context (SurfaceContext | None) – The SurfaceContext this batch will create resources against.

  • initial_count (int) – The initial vertex count of the buffers created by this batch.

add_pass(
draw_pass: DrawPass,
) → DrawPass

Register an additional ordered rendering pass.

Geometry is added to it with VertexList.add_pass().

The default geometry registration made by batch= is unchanged.

Added in version 3.0.

Return type:

DrawPass

create_vertex_storage(
*,
layouts: Iterable[VertexLayout] = (),
chunk_size: int = 4096,
sharing_policy: Literal['separate', 'shared'] = 'separate',
) → VertexStorage

Create a storage namespace for geometry owned by this batch.

Parameters:
  • layouts (Iterable[VertexLayout]) – Vertex layouts to register with the storage initially. Layouts supplied to vertex_list() methods are registered on demand as well.

  • chunk_size (int) – Initial allocation size, in vertices, for storage buffers.

  • sharing_policy (Literal['separate', 'shared']) – 'separate' gives each compatible domain its own vertex buffer. 'shared' lets compatible domains share buffers.

Return type:

VertexStorage

Returns:

The new VertexStorage, which can be passed as storage to this batch’s vertex-list creation methods.

delete_empty_domains() → None

Deletes all empty domains and all of their buffers.

Should not need to be called through normal usage, as this will occur periodically.

Return type:

None

draw() → None

Draw the batch.

If the draw list is dirty, a new one will be created and applied.

Return type:

None

draw_pass(draw_pass: DrawPass | None) → None

Draw the default pass or one registered additional rendering pass.

Parameters:

draw_pass (DrawPass | None) – The registered pass to draw, or None to draw only the default batch registration without any additional passes.

Return type:

None

draw_subset(
vertex_lists: Sequence[VertexList | IndexedVertexList],
) → None

Draw only some vertex lists in the batch.

The use of this method is highly discouraged, as it is quite inefficient. Usually an application can be redesigned so that batches can always be drawn in their entirety, using draw.

The given vertex lists must belong to this batch; behaviour is undefined if this condition is not met.

Parameters:

vertex_lists (Sequence[VertexList | IndexedVertexList]) – Vertex lists to draw.

Return type:

None

draw_with_options() → Generator[BatchDrawOptions, Any, None]

A context manager for specifying draw options before drawing.

Can be used as a context manager:

with batch.draw_with_options() as options:
    options.camera = new_camera

Upon exit of the context, the draw list functions will be called.

Added in version 3.0.

Return type:

Generator[BatchDrawOptions, Any, None]

get_domain(
indexed: bool,
instanced: bool,
mode: GeometryMode,
group: Group | None,
vertex_layout: VertexLayout,
*,
storage: VertexStorage | None = None,
) → VertexDomain

Get, or create, the vertex domain corresponding to the given arguments.

mode is the render mode such as GL_LINES or GL_TRIANGLES

Return type:

VertexDomain

invalidate() → None

Force the batch to update the draw list.

This method can be used to force the batch to re-compute the draw list when the ordering of groups has changed.

Added in version 1.2.

Return type:

None

migrate(
vertex_list: VertexList | IndexedVertexList,
mode: GeometryMode,
group: Group,
batch: Batch,
) → None

Migrate a vertex list to another batch and/or group.

vertex_list and mode together identify the vertex list to migrate. group and batch are new owners of the vertex list after migration.

The results are undefined if mode is not correct or if vertex_list does not belong to this batch (they are not checked and will not necessarily throw an exception immediately).

batch can remain unchanged if only a group change is desired.

Parameters:
  • vertex_list (VertexList | IndexedVertexList) – A vertex list currently belonging to this batch.

  • mode (GeometryMode) – The current GL drawing mode of the vertex list.

  • group (Group) – The new group to migrate to.

  • batch (Batch) – The batch to migrate to (or the current batch).

Return type:

None

update_shader(
vertex_list: VertexList | IndexedVertexList,
mode: GeometryMode,
group: Group,
program: ShaderProgram,
) → bool

Migrate a vertex list to another domain that has the specified shader attributes.

The results are undefined if mode is not correct or if vertex_list does not belong to this batch (they are not checked and will not necessarily throw an exception immediately).

Parameters:
Return type:

bool

Returns:

False if the domain’s no longer match. The caller should handle this scenario.

vertex_list(
vertex_layout: VertexLayout,
count: int,
mode: GeometryMode,
group: Group | None = None,
*,
storage: VertexStorage | None = None,
**data: Any,
) → VertexList

Create a vertex list from authoritative geometry formats.

vertex_layout defines the buffer components, types, and normalization. The group’s shader supplies the matching input locations.

Parameters:
  • vertex_layout (VertexLayout) – The authoritative format of the vertex attributes.

  • count (int) – Number of vertices in the list.

  • mode (GeometryMode) – A GeometryMode value, such as TRIANGLES or LINES.

  • group (Group | None) – Optional render state. Geometry can be attached later with set_group().

  • storage (VertexStorage | None) – Storage created by this batch to use for the geometry, or None to use the batch’s default storage.

  • data (Any) – Initial vertex-attribute data, keyed by attribute name.

Return type:

VertexList

Returns:

The created vertex list.

vertex_list_indexed(
vertex_layout: VertexLayout,
count: int,
mode: GeometryMode,
indices: Sequence[int],
group: Group | None = None,
*,
storage: VertexStorage | None = None,
**data: Any,
) → IndexedVertexList

Create an indexed vertex list from authoritative geometry formats.

Parameters:
  • vertex_layout (VertexLayout) – The authoritative format of the vertex attributes.

  • count (int) – Number of vertices in the list.

  • mode (GeometryMode) – A GeometryMode value, such as TRIANGLES or LINES.

  • indices (Sequence[int]) – Indices into the vertex list that define the primitives to draw.

  • group (Group | None) – Optional render state. Geometry can be attached later with set_group().

  • storage (VertexStorage | None) – Storage created by this batch to use for the geometry, or None to use the batch’s default storage.

  • data (Any) – Initial vertex-attribute data, keyed by attribute name.

Return type:

IndexedVertexList

Returns:

The created indexed vertex list.

vertex_list_instanced(
vertex_layout: VertexLayout,
count: int,
mode: GeometryMode,
group: Group,
*,
storage: VertexStorage | None = None,
**data: Any,
) → VertexList

Create an instanced vertex list from authoritative geometry formats.

Parameters:
  • vertex_layout (VertexLayout) – The authoritative format of the vertex attributes.

  • count (int) – Number of vertices in the list.

  • mode (GeometryMode) – A GeometryMode value, such as TRIANGLES or LINES.

  • group (Group) – Group containing the shader program and render state for the vertex list. Instance divisors are defined by vertex_layout.

  • storage (VertexStorage | None) – Storage created by this batch to use for the geometry, or None to use the batch’s default storage.

  • data (Any) – Initial vertex-attribute data, keyed by attribute name.

Return type:

VertexList

Returns:

The created instanced vertex list.

vertex_list_instanced_indexed(
vertex_layout: VertexLayout,
count: int,
mode: GeometryMode,
indices: Sequence[int],
group: Group,
*,
storage: VertexStorage | None = None,
**data: Any,
) → IndexedVertexList

Create an indexed instanced vertex list from authoritative geometry formats.

Parameters:
  • vertex_layout (VertexLayout) – The authoritative format of the vertex attributes.

  • count (int) – Number of vertices in the list.

  • mode (GeometryMode) – A GeometryMode value, such as TRIANGLES or LINES.

  • indices (Sequence[int]) – Indices into the vertex list that define the primitives to draw.

  • group (Group) – Group containing the shader program and render state for the vertex list. Instance divisors are defined by vertex_layout.

  • storage (VertexStorage | None) – Storage created by this batch to use for the geometry, or None to use the batch’s default storage.

  • data (Any) – Initial vertex-attribute data, keyed by attribute name.

Return type:

IndexedVertexList

Returns:

The created indexed instanced vertex list.

group_children: dict[Group, list[Group]]
group_map: dict[Group, dict[tuple[bool, bool, GeometryMode, VertexLayout, VertexStorage], VertexDomain]]
initial_count: int
top_groups: list[Group]
class BatchDrawOptions(
framebuffer: object | None = None,
camera: BaseCamera | _DefaultCameraMarker | None = <pyglet.graphics.draw._DefaultCameraMarker object>,
viewport: tuple | None = None,
scissor: tuple | CameraScissor | None = None,
clear_color: tuple[float,
float,
float,
float] | None=None,
) → None

A draw pass encompasses the starting data of a batched draw.

A user may fill some or none of the arguments.

resolve(
ctx: SurfaceContext,
) → DrawPass

Resolves the draw options to give a final DrawPass.

Return type:

DrawPass

camera: BaseCamera | _DefaultCameraMarker | None = <pyglet.graphics.draw._DefaultCameraMarker object>

The camera to use at the start. None disables the initial camera.

clear_color: tuple[float, float, float, float] | None = None
framebuffer: object | None = None

The framebuffer render target. If not specified, the window framebuffer.

scissor: tuple | CameraScissor | None = None
viewport: tuple | None = None
class DrawContext(
surface_ctx: SurfaceContextT,
backend_ctx: BackendContextT,
draw_pass: DrawPass,
renderer: BackendRenderer,
camera_stack: list[CameraScopeProtocol] = <factory>,
viewport_stack: list = <factory>,
scissor_stack: list = <factory>,
active_shader_program: ShaderProgram | None = None,
_applied_camera: CameraScopeProtocol | None = None,
_applied_viewport: tuple[int,
int,
int,
int] | None=None,
) → None

Transient context passed to group state during a draw.

apply_camera_scope(
*,
commit: bool = True,
apply_scissor: bool = True,
) → None
Return type:

None

apply_clear_color(r: float, g: float, b: float, a: float) → None
Return type:

None

apply_scissor() → None
Return type:

None

apply_viewport() → None
Return type:

None

begin() → None
Return type:

None

property active_camera: CameraScopeProtocol
property active_scissor: tuple | None
active_shader_program: ShaderProgram | None = None
property active_viewport: tuple | None
backend_ctx: BackendContextT
camera_stack: list[CameraScopeProtocol]
draw_pass: DrawPass
renderer: BackendRenderer
scissor_stack: list
surface_ctx: SurfaceContextT
viewport_stack: list
class DrawPass(
framebuffer: object | None = None,
camera: BaseCamera | _DefaultCameraMarker | None = <pyglet.graphics.draw._DefaultCameraMarker object>,
viewport: tuple | None = None,
scissor: CameraScissor | tuple | None = None,
clear_color: tuple[float,
float,
float,
float] | None=None,
order: int = 0,
name: str | None = None,
) → None

Configuration for one ordered batch submission.

resolve(
ctx: SurfaceContext,
) → DrawPass

Fill unspecified values from ctx while preserving pass identity.

Return type:

DrawPass

camera: BaseCamera | _DefaultCameraMarker | None = <pyglet.graphics.draw._DefaultCameraMarker object>

Camera for this pass. None disables it; the default uses the context camera.

clear_color: tuple[float, float, float, float] | None = None

Clear color override, or the surface context’s clear color when omitted.

framebuffer: object | None = None

Render target, or None for the context’s default framebuffer.

name: str | None = None

Optional label for diagnostics and tooling.

order: int = 0

Submission order among this batch’s additional passes.

scissor: CameraScissor | tuple | None = None

Scissor override, or the active camera’s scissor when omitted.

viewport: tuple | None = None

Viewport override, or the active camera’s viewport when omitted.

class Group(order: int = 0, parent: Group | None = None) → None

Group of common state.

Group provides extra control over how drawables are handled within a Batch. When a batch draws a drawable, it ensures its group’s state is set; this can include binding textures, shaders, or setting any other parameters. It also sorts the groups before drawing.

In the following example, the background sprite is guaranteed to be drawn before the car and the boat:

batch = pyglet.graphics.Batch()
background = pyglet.graphics.Group(order=0)
foreground = pyglet.graphics.Group(order=1)

background = pyglet.sprite.Sprite(background_image, batch=batch, group=background)
car = pyglet.sprite.Sprite(car_image, batch=batch, group=foreground)
boat = pyglet.sprite.Sprite(boat_image, batch=batch, group=foreground)

def on_draw():
    batch.draw()

Initialize a rendering group.

Parameters:
  • order (int) – Set the order to render above or below other Groups. Lower orders are drawn first.

  • parent (Group | None) – Group to contain this Group; its state will be set before this Group’s state.

add_comparison(value: Any) → None

Adds a value to compare between groups of this type.

Return type:

None

set_blend(
blend_src: BlendFactor,
blend_dst: BlendFactor,
blend_op: BlendOp = BlendOp.ADD,
*,
blend_src_alpha: BlendFactor | None = None,
blend_dst_alpha: BlendFactor | None = None,
blend_op_alpha: BlendOp | None = None,
) → None

Set the blend state.

Supplying either alpha factor selects separate RGB/alpha blending. Supplying an alpha operation selects separate RGB/alpha equations. Regular and separate blending replace each other as one group state.

Parameters:
  • blend_src (BlendFactor) – Source blend factor used for incoming fragment color values.

  • blend_dst (BlendFactor) – Destination blend factor used for framebuffer color values.

  • blend_op (BlendOp) – Blend operation used to combine the source and destination RGB values, and alpha when blend_op_alpha is omitted. Defaults to additive blending.

  • blend_src_alpha (BlendFactor | None) – Independent source alpha factor. Defaults to blend_src.

  • blend_dst_alpha (BlendFactor | None) – Independent destination alpha factor. Defaults to blend_dst.

  • blend_op_alpha (BlendOp | None) – Independent alpha blend operation. Defaults to blend_op.

Return type:

None

set_camera(camera: CameraScopeProtocol) → None

Set a camera scope for this group.

The camera object is applied during batch draw inside a draw context. If the camera/view provides an effective scissor area, a matching camera scissor state is attached automatically.

Parameters:

camera (CameraScopeProtocol) – Camera or camera-like object that provides viewport state, begins and ends its drawing scope, and may provide a scissor area for this group.

Return type:

None

set_color_mask(red: bool, green: bool, blue: bool, alpha: bool) → None

Set which color channels are writable.

Parameters:
  • red (bool) – Whether drawing may modify the red channel.

  • green (bool) – Whether drawing may modify the green channel.

  • blue (bool) – Whether drawing may modify the blue channel.

  • alpha (bool) – Whether drawing may modify the alpha channel.

Return type:

None

set_cull_face(face: CullFace) → None

Enable face culling for the selected face set.

Parameters:

face (CullFace) – Faces to cull.

Return type:

None

set_depth_range(near: float, far: float) → None

Set the normalized depth range used by the viewport.

Parameters:
  • near (float) – Window-space depth value for the near end of the viewport range.

  • far (float) – Window-space depth value for the far end of the viewport range.

Return type:

None

set_depth_test(func: CompareOp) → None

Set the depth comparison state.

Parameters:

func (CompareOp) – Comparison operation used to decide whether a fragment passes the depth test.

Return type:

None

set_depth_write(flag: bool) → None

Set whether drawing to the depth buffer is enabled.

Parameters:

flag (bool) – True to write depth values, or False to preserve the depth buffer.

Return type:

None

set_front_face(face: FrontFace) → None

Set the winding order used to identify front-facing triangles.

Parameters:

face (FrontFace) – Winding order treated as front-facing.

Return type:

None

set_polygon_offset(factor: float, units: float) → None

Enable polygon offset for filled primitives.

Parameters:
  • factor (float) – Scale applied to the polygon’s depth slope.

  • units (float) – Constant depth offset added to the polygon.

Return type:

None

set_sample_coverage(value: float, invert: bool = False) → None

Set multisample coverage and enable sample coverage testing.

Parameters:
  • value (float) – Fraction of samples to keep, from 0.0 to 1.0.

  • invert (bool) – Whether to invert the selected sample coverage mask.

Return type:

None

set_scissor(scissor_object: ScissorProtocol) → None

Set the scissor state.

Parameters:

scissor_object (ScissorProtocol) – Object describing the scissor rectangle to apply while this group is drawn.

Return type:

None

set_shader_program(program: ShaderProgram) → None

Set the shader program state.

Parameters:

program (ShaderProgram) – Shader program to bind while this group is drawn.

Return type:

None

set_shader_uniforms(
program: ShaderProgram,
uniforms: dict[str, Any],
) → None

Set shader uniform values.

Parameters:
  • program (ShaderProgram) – Shader program that owns the uniforms.

  • uniforms (dict[str, Any]) – Mapping of uniform names to values to apply to the shader program while this group is drawn.

Return type:

None

set_state(state: State) → None

Sets a state to be applied to the group.

If the state is an enforced state, setting a new state will not update any children.

Parameters:

state (State) – State instance to apply when this group is drawn. States of the same concrete type replace any previously assigned state of that type. Derived state order and hashing are deferred until the group is first used.

Return type:

None

set_state_all(ctx: DrawContext) → None

Calls all set states of the underlying Group.

Parameters:

ctx (DrawContext) – Draw context that receives the group’s state changes.

Return type:

None

set_state_recursive(ctx: DrawContext) → None

Set this group and its ancestry.

Call this method if you are using a group in isolation: the parent groups will be called in top-down order, with this class’s set being called last.

Parameters:

ctx (DrawContext) – Draw context that receives the parent and child state changes.

Return type:

None

set_stencil_clear() → None

Clear the stencil buffer when this group becomes active.

Return type:

None

set_stencil_func(func: CompareOp, ref: int, mask: int) → None

Set the stencil comparison function and reference value.

Parameters:
  • func (CompareOp) – Comparison applied between the masked stencil value and reference value.

  • ref (int) – Reference value used by the stencil comparison.

  • mask (int) – Bit mask applied to both the stored stencil value and reference value.

Return type:

None

set_stencil_mask(mask: int) → None

Set the writable stencil bit mask.

Parameters:

mask (int) – Bit mask controlling which stencil bits can be changed by drawing.

Return type:

None

set_stencil_op(
fail: StencilOp,
z_fail: StencilOp,
z_pass: StencilOp,
) → None

Set stencil operations for stencil failure, depth failure, and pass.

Parameters:
  • fail (StencilOp) – Operation when the stencil comparison fails.

  • z_fail (StencilOp) – Operation when stencil passes but the depth test fails.

  • z_pass (StencilOp) – Operation when both stencil and depth tests pass.

Return type:

None

set_stencil_test(enabled: bool = True) → None

Enable or disable stencil testing.

Parameters:

enabled (bool) – True to reject or accept fragments using the stencil function, or False to disable it.

Return type:

None

set_texture(
texture: Texture,
texture_unit: int = 0,
set_id: int = 0,
) → None

Set the texture state.

Parameters:
  • texture (Texture) – The Texture instance that this draw call uses.

  • texture_unit (int) – The binding unit this Texture/Sampler is bound to. In OpenGL this is the Active Texture (glActiveTexture). In Vulkan this is the Sampler binding number in the descriptor.

  • set_id (int) – The set that the sampler belongs to. Only applicable in Vulkan.

Return type:

None

set_textures(
textures: dict[str, Texture],
program: ShaderProgram,
first_texture_unit: int = 0,
set_id: int = 0,
) → None

Set multiple texture states and matching sampler uniforms.

Parameters:
  • textures (dict[str, Texture]) – Mapping of shader sampler uniform names to Texture instances.

  • program (ShaderProgram) – The shader program that owns the sampler uniforms.

  • first_texture_unit (int) – The first binding unit to use. Each texture uses the next unit.

  • set_id (int) – The set that the sampler belongs to. Only applicable in Vulkan.

Return type:

None

set_uniform_buffer(
region: UniformBufferRegion,
binding_index: int | None = None,
) → None

Set a Uniform Buffer Object region state.

Parameters:
  • region (UniformBufferRegion) – A region created by UniformBlock.create_ubo_region.

  • binding_index (int | None) – Optional binding point override. By default, the region uses the binding point assigned to its source uniform block.

Return type:

None

set_viewport(viewport: ViewportProtocol) → None

Set the viewport state.

Parameters:

viewport (ViewportProtocol) – Mutable viewport provider with x, y, width, and height attributes. The current values are read whenever this group state is applied.

Return type:

None

unset_state_all(ctx: DrawContext) → None

Calls all unset states of the underlying Group.

Return type:

None

unset_state_recursive(ctx: DrawContext) → None

Unset this group and its ancestry.

The inverse of set_state_recursive.

Return type:

None

property batches: tuple[Batch, ...]

Which graphics Batches this Group is a part of.

Read Only.

property has_enforced_states: bool

If this group has states that automatically apply to children.

property order: int

Rendering order of this group compared to others.

Lower numbers are drawn first.

property states: tuple[State, ...]

The states that will apply to members of this group.

property visible: bool

Visibility of the group in the rendering pipeline.

Determines whether this Group is visible in any of the Batches it is assigned to. If False, objects in this Group will not be rendered.

class ShaderGroup(
program: ShaderProgram | ShaderProgramView,
order: int = 0,
parent: Group | None = None,
) → None

A group that enables and binds a ShaderProgram.

Initialize a rendering group.

Parameters:
  • order (int) – Set the order to render above or below other Groups. Lower orders are drawn first.

  • parent (Group | None) – Group to contain this Group; its state will be set before this Group’s state.

get_default_batch() → Batch

The built in batch object used for objects that have no specified batch.

Return type:

Batch