PySSV Module Reference
Public API
The pySSV.ssv_canvas.SSVCanvas
is one of the core components of pySSV, it’s what manages and provides and
interface for the three major internal components: the renderer, the widget, and the shader preprocessor.
- pySSV.canvas(size: Tuple[int, int] | None = (640, 480), backend: str = 'opengl', gl_version: Tuple[int, int] | None = None, standalone: bool = False, target_framerate: int = 60, use_renderdoc: bool = False, supports_line_directives: bool | None = None)[source]
Creates a new
SSVCanvas
which contains the render widget and manages the render context.- Parameters:
size (Tuple[int, int] | None) – the default resolution of the renderer as a tuple:
(width: int, height: int)
.backend (str) – the rendering backend to use; currently supports:
"opengl"
.gl_version (Tuple[int, int] | None) – optionally, the minimum version of OpenGL to support. Accepts a tuple of (major, minor), eg: gl_version=(4, 2) for OpenGL 4.2 Core.
standalone (bool) – whether the canvas should run standalone, or attempt to create a Jupyter Widget for rendering.
target_framerate (int) – the default framerate to target when running.
use_renderdoc (bool) – optionally, an instance of the Renderdoc in-app api to provide support for frame capturing and analysis in renderdoc.
supports_line_directives (bool | None) – whether the shader compiler supports
#line
directives (Nvidia GPUs only). Set toNone
for automatic detection. If you get ‘extension not supported: GL_ARB_shading_language_include’ errors, set this toFalse
.
- pySSV.ssv_canvas.OnMouseDelegate
A callable with parameters matching the signature:
on_mouse(mouse_down: tuple[bool, bool, bool], mouse_pos: tuple[int, int], mouse_wheel_delta: float) -> None: ...
mouse_down: a tuple of booleans representing the mouse button state (left, right, middle).mouse_pos: a tuple of ints representing the mouse position relative to the canvas in pixels.mouse_wheel_delta: how many pixels the mousewheel has scrolled since the last callback.alias of
Callable
[[Tuple
[bool
,bool
,bool
],Tuple
[int
,int
],float
],None
]
- pySSV.ssv_canvas.OnKeyDelegate
A callable with parameters matching the signature:
on_key(key: str, down: bool) -> None: ...
key: the name of key in this event. Possible values can be found here: https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_valuesdown: whether the key is being pressed.
- pySSV.ssv_canvas.OnFrameRenderedDelegate
A callable with parameters matching the signature:
on_key(delta_time: float) -> None: ...
key: the time in seconds since the last frame was rendered.
- class pySSV.ssv_canvas.SSVCanvas(size: Tuple[int, int] | None, backend: str = 'opengl', gl_version: Tuple[int, int] | None = None, standalone: bool = False, target_framerate: int = 60, use_renderdoc: bool = False, supports_line_directives: bool | None = None)[source]
An SSV canvas manages the OpenGL rendering context, shaders, and the jupyter widget
Creates a new SSV Canvas object which manages the graphics context and render widget/window.
- Parameters:
size (Tuple[int, int] | None) – the default resolution of the renderer as a tuple:
(width: int, height: int)
.backend (str) – the rendering backend to use; currently supports:
"opengl"
.gl_version (Tuple[int, int] | None) – optionally, the minimum version of OpenGL to support. Accepts a tuple of (major, minor), eg: gl_version=(4, 2) for OpenGL 4.2 Core.
standalone (bool) – whether the canvas should run standalone, or attempt to create a Jupyter Widget for rendering.
target_framerate (int) – the default framerate to target when running.
use_renderdoc (bool) – optionally, an instance of the Renderdoc in-app api to provide support for frame capturing and analysis in renderdoc.
supports_line_directives (bool | None) – whether the shader compiler supports
#line
directives (Nvidia GPUs only). Set toNone
for automatic detection. If you get ‘extension not supported: GL_ARB_shading_language_include’ errors, set this toFalse
.
- property main_render_buffer: SSVRenderBuffer
Gets the main render buffer associated with this
SSVCanvas
.- Returns:
the main render buffer.
- property standalone: bool
Gets whether this canvas outputs to a standalone window as opposed to a jupyter widget.
- property widget: SSVRenderWidget | None
Gets the render widget object. Only defined when
standalone
isFalse
.
- property main_camera: SSVCameraController
Gets the main camera controller.
- property mouse_down: Tuple[bool, bool, bool]
Gets the current mouse button state as a tuple of
bool
. [left, right, middle]
- property mouse_pos: Tuple[int, int]
Gets the current mouse position relative to the canvas in pixels.
- property preprocessor
Gets this canvas’ preprocessor instance. Useful if you need to manually add compiler defines/macros.
- property frame_number
Gets the number of frames that have been rendered since this canvas was run.
- property canvas_time: float
Gets or sets the current canvas time (this is the value used by the shader’s
uTime
uniform). Note that due to renderer latency there will be some offset to time value get/set here.
- on_start(callback: Callable[[], None], remove: bool = False)[source]
Registers/unregisters a callback which is invoked when this canvas’s
run()
method is called, before any frames are rendered.
- on_mouse_event(callback: Callable[[Tuple[bool, bool, bool], Tuple[int, int], float], None], remove: bool = False)[source]
Registers/unregisters a callback which is invoked when.
- on_keyboard_event(callback: Callable[[str, bool], None], remove: bool = False)[source]
Registers/unregisters a callback which is invoked when.
- on_frame_rendered(callback: Callable[[float], None], remove: bool = False)[source]
Registers/unregisters a callback which is invoked when.
- run(stream_mode: str | SSVStreamingMode = SSVStreamingMode.JPG, stream_quality: float | None = None, never_kill=False) None [source]
Starts the render loop and displays the Jupyter Widget (or render window if in standalone mode).
- Parameters:
stream_mode (str | SSVStreamingMode) – the encoding format to use to transmit rendered frames from the render process to the Jupyter widget.
stream_quality (float | None) – the encoding quality to use for the given encoding format. Takes a float between 0-100 (some stream modes support values larger than 100, others clamp it internally), where 100 results in the highest quality. This value is scaled to give a bit rate target or quality factor for the chosen encoder. Pass in
None
to use the encoder’s default quality settings.never_kill – disables the watchdog responsible for stopping the render process when the widget is no longer being displayed. Warning: The only way to stop a renderer started with this enabled is to restart the Jupyter kernel.
- Return type:
None
- stop(force=False) None [source]
Stops the current canvas from rendering continuously. The renderer is not released and can be restarted.
- Parameters:
force – kills the render process and releases resources. SSVCanvases cannot be restarted if they have been force stopped.
- Return type:
None
- pause() None [source]
Pauses the current canvas, preventing new frames from being rendered and freezing time.
- Return type:
None
- unpause() None [source]
Unpauses the current canvas, and resumes playback at the time the canvas was paused at.
- Return type:
None
- shader(shader_source: str, additional_template_directory: str | None = None, additional_templates: List[str] | None = None, shader_defines: Dict[str, str] | None = None, compiler_extensions: List[str] | None = None)[source]
Registers, compiles and attaches a shader to the main render buffer.
- Parameters:
shader_source (str) – the shader source code to preprocess. It should contain the necessary
#pragma SSV <template_name>
directive see Built In Shader Templates for more information.additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.
additional_templates (List[str] | None) – a list of custom shader templates (source code, not paths).See Writing Shader Templates for information about using custom shader templates.
shader_defines (Dict[str, str] | None) – extra preprocessor defines to be enabled globally.
compiler_extensions (List[str] | None) – a list of GLSL extensions required by this shader (eg:
GL_EXT_control_flow_attributes
)
- update_uniform(uniform_name: str, value: Any, share_with_render_buffer: bool = True, share_with_canvas: bool = True) None [source]
Sets the value of a uniform associated with the main full-screen shader.
- Parameters:
uniform_name (str) – the name of the uniform to set.
value (Any) – the value to set. Must be compatible with the destination uniform.
share_with_render_buffer (bool) – update this uniform across all shaders in this render buffer.
share_with_canvas (bool) – update this uniform across all shaders in this canvas.
- Return type:
None
- render_buffer(size: Tuple[int, int], name: str | None = None, order: int = 0, dtype: str = 'f1', components: int = 4) SSVRenderBuffer [source]
Creates a new render buffer for this canvas. Useful for effects requiring multi pass rendering.
- Parameters:
size (Tuple[int, int]) – the resolution of the new render buffer to create.
name (str | None) – the name of this render buffer. This is the name given to the automatically generated uniform declaration. If set to
None
a name is automatically generated.order (int) – a number to hint the renderer as to the order to render the buffers in. Smaller values are rendered first; the main render buffer has an order of 999999.
dtype (str) – the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).
components (int) – how many vector components should each pixel have (RGB=3, RGBA=4).
- Returns:
a new render buffer object.
- Return type:
- texture(data: ndarray[Any, dtype[_ScalarType_co]] | Image, uniform_name: str | None, force_2d: bool = False, force_3d: bool = False, override_dtype: str | None = None, treat_as_normalized_integer: bool = True, declare_uniform: bool = True) SSVTexture [source]
Creates or updates a texture from the NumPy array provided.
- Parameters:
data (ndarray[Any, dtype[_ScalarType_co]] | Image) – a NumPy array or a PIL/Pillow Image containing the image data to copy to the texture.
uniform_name (str | None) – optionally, the name of the shader uniform to associate this texture with. If
None
is specified, a name is automatically generated in the form ‘uTexture{n}’force_2d (bool) – when set, forces the texture to be treated as 2-dimensional, even if it could be represented by a 1D texture. This only applies in the ambiguous case where a 2D single component texture has a height <= 4 (eg:
np.array([[0.0, 0.1, 0.2], [0.3, 0.4, 0.5], [0.6, 0.7, 0.8]])
), with this parameter set toFalse
, the array would be converted to a 1D texture with a width of 3 and 3 components; setting this toTrue
ensures that it becomes a 3x3 texture with 1 component.force_3d (bool) – when set, forces the texture to be treated as 3-dimensional, even if it could be represented by a 2D texture. See the description of the
force_2d
parameter for a full explanation.override_dtype (str | None) – optionally, a moderngl datatype to force on the texture. See https://moderngl.readthedocs.io/en/latest/topics/texture_formats.html for the full list of available texture formats.
treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.
declare_uniform (bool) – when set, a shader uniform is automatically declared for this uniform in shaders.
- Return type:
- get_texture(uniform_name: str) SSVTexture | None [source]
Gets a texture that’s already been defined on this canvas.
- Parameters:
uniform_name (str) – the name of the uniform associated with this texture.
- Returns:
the texture object or
None
if no texture was found with that name.- Return type:
SSVTexture | None
- save_image(image_type: SSVStreamingMode = SSVStreamingMode.JPG, quality: float = 95, size: Tuple[int, int] | None = None, render_buffer: int = 0, suppress_ui: bool = False) bytes [source]
Saves the current frame as an image.
- Parameters:
image_type (SSVStreamingMode) – the image compression algorithm to use.
quality (float) – the encoding quality to use for the given encoding format. Takes a float between 0-100 (some stream modes support values larger than 100, others clamp it internally), where 100 results in the highest quality. This value is scaled to give a bit rate target or quality factor for the chosen encoder.
size (Tuple[int, int] | None) – optionally, the width and height of the saved image. If set to
None
uses the current resolution of the render buffer.render_buffer (int) – the uid of the render buffer to save.
suppress_ui (bool) – whether any active SSVGUI should be suppressed.
- Returns:
the bytes representing the compressed image.
- Return type:
- dbg_query_shader_template(shader_template_name: str, additional_template_directory: str | None = None, additional_templates=None) str [source]
Gets the list of arguments a given shader template expects and returns a string containing their usage info.
- Parameters:
- Returns:
the shader template’s auto generated help string.
- Return type:
- dbg_query_shader_templates(additional_template_directory: str | None = None) str [source]
Gets a list of all the shader templates available to the preprocessor.
- dbg_preprocess_shader(shader_source: str, additional_template_directory: str | None = None, additional_templates: List[str] | None = None, shader_defines: Dict[str, str] | None = None, compiler_extensions: List[str] | None = None, pretty_print: bool = True) str | Dict[str, str] [source]
Runs the preprocessor on a shader and returns the results. Useful for debugging shaders.
- Parameters:
shader_source (str) – the shader source code to preprocess. It should contain the necessary
#pragma SSV <template_name>
directive see Built In Shader Templates for more information.additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.
additional_templates (List[str] | None) – a list of custom shader templates (source code, not paths).See Writing Shader Templates for information about using custom shader templates.
shader_defines (Dict[str, str] | None) – extra preprocessor defines to be enabled globally.
compiler_extensions (List[str] | None) – a list of GLSL extensions required by this shader (eg:
GL_EXT_control_flow_attributes
)pretty_print (bool) – when enabled returns a single string containing all the preprocessed shaders
- Return type:
- dbg_log_context(full=False)[source]
Logs the OpenGL information to the console for debugging.
- Parameters:
full – whether to log all of the OpenGL context information (including extensions).
Canvas Objects
These classes must be constructed by an pySSV.ssv_canvas.SSVCanvas
.
- class pySSV.ssv_render_buffer.SSVRenderBuffer(canvas: SSVCanvas, render_process_client: SSVRenderProcessClient, preprocessor: SSVShaderPreprocessor, render_buffer_uid: int | None, render_buffer_name: str, order: int, size: tuple[int, int], dtype: str, components: int)[source]
A lightweight class representing a native render buffer.
Used Internally
Note that
SSVRenderBuffer
objects should be constructed using the factory method on anSSVCanvas
.- Parameters:
canvas (SSVCanvas) – the canvas creating this render buffer.
render_process_client (SSVRenderProcessClient) – the render process connection belonging to the canvas.
preprocessor (SSVShaderPreprocessor) – the preprocessor belonging to the canvas.
render_buffer_uid (Optional[int]) – the UID to give this render buffer. Set to
None
to generate one automatically.render_buffer_name (str) – the name of this render buffer. This is the name given to the automatically generated uniform declaration.
order (int) – the render order of the render buffer. Smaller numbers are rendered first.
size (tuple[int, int]) – the resolution of the render buffer.
dtype (str) – the moderngl datatype of the render buffer.
components (int) – how many vector components should each pixel have (RGB=3, RGBA=4).
- property full_screen_vertex_buffer: SSVVertexBuffer
Gets the default full-screen vertex buffer for this render buffer.
- property order: int
Gets or sets the render order of this render buffer. This number to hint the renderer as to the order to render the buffers in. Smaller values are rendered first; the main render buffer has an order of 999999.
- property components: int
Gets or sets how many vector components each pixel should have (RGB=3, RGBA=4).
- property dtype: str
Gets or sets the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).
- property vertex_buffers: Tuple[SSVVertexBuffer, ...]
Gets the tuple of vertex buffers registered to this render buffer.
- shader(shader_source: str, additional_template_directory: str | None = None, additional_templates: list[str] | None = None, shader_defines: dict[str, str] | None = None, compiler_extensions: list[str] | None = None)[source]
Registers, compiles and attaches a full-screen shader to this render buffer.
- Parameters:
shader_source (str) – the shader source code to preprocess. It should contain the necessary
#pragma SSV <template_name>
directive see Built In Shader Templates for more information.additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.
additional_templates (list[str] | None) – a list of custom shader templates (source code, not paths).See Writing Shader Templates for information about using custom shader templates.
shader_defines (dict[str, str] | None) – extra preprocessor defines to be enabled globally.
compiler_extensions (list[str] | None) – a list of GLSL extensions required by this shader (eg:
GL_EXT_control_flow_attributes
)
- update_uniform(uniform_name: str, value: Any, share_with_render_buffer: bool = True, share_with_canvas: bool = False) None [source]
Sets the value of a uniform associated with this buffer’s full-screen shader.
- Parameters:
uniform_name (str) – the name of the uniform to set.
value (Any) – the value to set. Must be compatible with the destination uniform.
share_with_render_buffer (bool) – update this uniform across all shaders in this render buffer.
share_with_canvas (bool) – update this uniform across all shaders in this canvas.
- Return type:
None
- vertex_buffer() SSVVertexBuffer [source]
Creates a new draw call and associated vertex buffer on this render buffer.
- Returns:
A new vertex buffer object.
- Return type:
- delete_vertex_buffer(buffer: SSVVertexBuffer)[source]
Removes a vertex buffer from this render buffer, releasing its resources.
- Parameters:
buffer (SSVVertexBuffer) – the vertex buffer to remove.
- class pySSV.ssv_vertex_buffer.SSVVertexBuffer(draw_call_uid: int | None, render_buffer: SSVRenderBuffer, render_process_client: SSVRenderProcessClient, preprocessor: SSVShaderPreprocessor)[source]
A lightweight class representing a vertex buffer associated with a draw call.
Used internally
Note that
SSVVertexBuffer
objects should be constructed using the factory method on either anSSVCanvas
or anSSVRenderBuffer
.- Parameters:
draw_call_uid (Optional[int]) –
render_buffer (SSVRenderBuffer) –
render_process_client (SSVRenderProcessClient) –
preprocessor (SSVShaderPreprocessor) –
- update_vertex_buffer(vertex_array: ndarray[Any, dtype[_ScalarType_co]], vertex_attributes: tuple[str, ...] = ('in_vert', 'in_color'), index_array: ndarray[Any, dtype[_ScalarType_co]] | None = None)[source]
Updates the data inside a vertex buffer.
- Parameters:
vertex_array (ndarray[Any, dtype[_ScalarType_co]]) – a numpy array containing the new vertex data.
index_array (ndarray[Any, dtype[_ScalarType_co]] | None) – optionally, a numpy array containing the indices of vertices ordered to make triangles.
vertex_attributes (tuple[str, ...]) – a tuple of the names of the vertex attributes to map to in the shader, in the order that they appear in the vertex array.
- shader(shader_source: str, additional_template_directory: str | None = None, additional_templates: list[str] | None = None, shader_defines: dict[str, str] | None = None, compiler_extensions: list[str] | None = None)[source]
Registers, compiles and attaches a shader to the draw call associated with this vertex buffer.
- Parameters:
shader_source (str) – the shader source code to preprocess. It should contain the necessary
#pragma SSV <template_name>
directive see Built In Shader Templates for more information.additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.
additional_templates (list[str] | None) – a list of custom shader templates (source code, not paths).See Writing Shader Templates for information about using custom shader templates.
shader_defines (dict[str, str] | None) – extra preprocessor defines to be enabled globally.
compiler_extensions (list[str] | None) – a list of GLSL extensions required by this shader (eg:
GL_EXT_control_flow_attributes
)
- update_uniform(uniform_name: str, value: Any, share_with_render_buffer: bool = False, share_with_canvas: bool = False) None [source]
Sets the value of a uniform associated with this draw call.
- Parameters:
uniform_name (str) – the name of the uniform to set.
value (Any) – the value to set. Must be compatible with the destination uniform.
share_with_render_buffer (bool) – update this uniform across all shaders in this render buffer.
share_with_canvas (bool) – update this uniform across all shaders in this canvas.
- Return type:
None
- class pySSV.ssv_camera.MoveDir(value)[source]
Represents a cardinal direction to move in.
- NONE = 0
- FORWARD = 1
- BACKWARD = 2
- LEFT = 3
- RIGHT = 4
- UP = 5
- DOWN = 6
- class pySSV.ssv_camera.SSVCamera[source]
A simple class representing a camera.
- direction: ndarray[Any, dtype[float32]]
A normalised vector pointing in the direction the camera is facing.
- property rotation_matrix: ndarray[Any, dtype[float32]]
Gets the current view matrix of the camera, without the translation component.
- property projection_matrix
Gets the current projection matrix of the camera.
- class pySSV.ssv_camera.SSVCameraController[source]
A simple class representing a camera controller.
- class pySSV.ssv_camera.SSVLookCameraController[source]
A camera controller which supports mouse look controls.
- class pySSV.ssv_camera.SSVOrbitCameraController[source]
A camera controller which supports orbiting around a given target.
- property target_pos
Gets or sets the point around which to orbit.
- property orbit_dist
Gets or sets the distance from the target position to orbit at.
- mouse_change(mouse_pos: Tuple[int, int], mouse_down: Tuple[bool, bool, bool])[source]
Updates the camera with a mouse event.
- pySSV.ssv_texture.determine_texture_shape(data: ndarray[Any, dtype[_ScalarType_co]], override_dtype: str | None, treat_as_normalized_integer: bool = True) tuple[int, int, int, int, str | None] [source]
Attempts to determine suitable texture parameters given an ndarray. This method returns (0,0,0,0,None) if a suitable format cannot be found.
- Parameters:
data (ndarray[Any, dtype[_ScalarType_co]]) – the ndarray to parse.
override_dtype (str | None) – optionally, a moderngl dtype string to use instead of the numpy dtype.
treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.
- Returns:
(components, depth, height, width, dtype)
- Return type:
- class pySSV.ssv_texture.SSVTexture(texture_uid: int | None, render_process_client: SSVRenderProcessClient, preprocessor: SSVShaderPreprocessor, data: npt.NDArray | Image.Image, uniform_name: str, force_2d: bool = False, force_3d: bool = False, override_dtype: str | None = None, treat_as_normalized_integer: bool = True, declare_uniform: bool = True)[source]
A lightweight class representing a Texture object.
Used Internally
Note that
SSVTexture
objects should be constructed using the factory method on either anSSVCanvas
.- Parameters:
texture_uid (Optional[int]) – the UID to give this texture buffer. Set to
None
to generate one automatically.render_process_client (SSVRenderProcessClient) – the render process connection belonging to the canvas.
preprocessor (SSVShaderPreprocessor) – the preprocessor belonging to the canvas.
data (Union[npt.NDArray, Image.Image]) – a NumPy array or a PIL/Pillow Image containing the image data to copy to the texture.
uniform_name (str) – the name of the shader uniform to associate this texture with.
force_2d (bool) – when set, forces the texture to be treated as 2-dimensional, even if it could be represented by a 1D texture. This only applies in the ambiguous case where a 2D single component texture has a height <= 4 (eg:
np.array([[0.0, 0.1, 0.2], [0.3, 0.4, 0.5], [0.6, 0.7, 0.8]])
), with this parameter set toFalse
, the array would be converted to a 1D texture with a width of 3 and 3 components; setting this toTrue
ensures that it becomes a 3x3 texture with 1 component.force_3d (bool) – when set, forces the texture to be treated as 3-dimensional, even if it could be represented by a 2D texture. See the description of the
force_2d
parameter for a full explanation.override_dtype (Optional[str]) – optionally, a moderngl datatype to force on the texture.
treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.
declare_uniform (bool) – when set, a shader uniform is automatically declared for this uniform in shaders.
- property components: int
Gets the number of components for a single pixel (RGB=3, RGBA=4). Always at least 1, never more than 4.
- property dtype: str
Gets the data type of a single component in the texture.
See https://moderngl.readthedocs.io/en/latest/topics/texture_formats.html for a full list of available data types.
- property linear_filtering: None
Sets whether the texture should use nearest neighbour (
False
) or linear (True
) interpolation.
- property linear_mipmap_filtering: None
Sets whether different mipmap levels should blend linearly (
True
) or not (False
).
- property anisotropy: None
Sets the number of anisotropy samples to use. (minimum of 1 = disabled, maximum of 16)
- property is_valid: bool
Gets whether this texture object represents a valid texture that hasn’t been destroyed yet.
GUI Library
pySSV provides a simple to use immediate-mode GUI library to add interactivity to your shaders. A GUI can be created
for a given canvas by calling the pySSV.ssv_gui.create_gui()
method which returns a new
pySSV.ssv_gui.SSVGUI
.
- class pySSV.ssv_gui.SSVGUIShaderMode(value)[source]
Represents the shader features needed to render a GUI element when using the built-in UI shader.
- SOLID = 0
- TRANSPARENT = 1
- TEXT = 2
- TEXTURE = 4
- SHADOWED = 8
- ROUNDING = 16
- OUTLINE = 32
- class pySSV.ssv_gui.TextAlign(value)[source]
An enumeration.
- LEFT = 0
- CENTRE = 1
- CENTER = 1
- RIGHT = 2
- class pySSV.ssv_gui.Rect(x: int = 0, y: int = 0, width: int = 20, height: int = 20)[source]
Represents a 2D rectangle in pixel space.
- pySSV.ssv_gui.SSVGUIDrawDelegate
draw(gui: SSVGUI, rect: Rect) -> None
- Type:
A delegate for a GUIElement draw function. It should follow the signature
- pySSV.ssv_gui.SSVGUIPreLayoutDelegate
A delegate for a GUIElement pre layout function. It should follow the signature:
draw(gui: SSVGUI) -> tuple[width: int, height: int]
- class pySSV.ssv_gui.SSVGUIElement(draw_func: Callable[[SSVGUI, Rect], None], control_width: int, control_height: int, expand: bool, layout: bool, overlay_last: bool, pre_layout_func: Callable[[SSVGUI], Tuple[int, int]] | None)[source]
A class representing a single GUI element for use by the layout engine.
- Parameters:
- class pySSV.ssv_gui.SSVGUILayoutContainer(gui: SSVGUI, vertical: bool = True, enabled: bool | Reference[bool] = True, squeeze: bool = False, pad: bool = False)[source]
A GUILayoutContainer stores a list gui elements (represented by their draw functions). It automatically lays out all of its elements either vertically or horizontally when its
draw()
method is called. AnSSVGUILayoutContainer
can itself be put inside another layout container.- Parameters:
- draw(gui: SSVGUI, max_bounds: Rect)[source]
Lays out and draws all the elements within this container in the order they were added.
- property min_width: int
Measures the minimum width of a given layout group by recursively measuring all of its children.
- property min_height: int
Measures the minimum height of a given layout group by recursively measuring all of its children.
- add_element(draw_callback: Callable[[SSVGUI, Rect], None], control_width: int, control_height: int, expand: bool = False, layout: bool = True, overlay_last: bool = False, pre_layout_callback: Callable[[SSVGUI], Tuple[int, int]] | None = None)[source]
Adds a GUI element to this Layout Container.
- Parameters:
draw_callback (Callable[[SSVGUI, Rect], None]) – the draw function of the GUI element
control_width (int) – the requested width of the control. The layout engine can give a larger width than this if the
expand
option is enabled; if the layout group hassqueeze
enabled, the actual width may be smaller than requested.control_height (int) – the requested height of the control. The layout engine can give a larger height than this if the
expand
option is enabled; if the layout group hassqueeze
enabled, the actual height may be smaller than requested.expand (bool) – whether the element should attempt to fill all remaining space in the container. If multiple elements have
expand
set, then the remaining space is shared. The element’s minimum size is still determined by the defined layout size.layout (bool) – whether this element should participate in automatic layout. If disabled, the element doesn’t count towards layout calculations and is given the full
Rect
of the Layout Container. The element will still be drawn in the order specified.overlay_last (bool) – whether this element should be overlaid on top of the last element drawn.
pre_layout_callback (Callable[[SSVGUI], Tuple[int, int]] | None) – the callback is invoked just before the element is laid out, it’s useful for Layout Group elements which might not know their minimum size until just before layout.
- class pySSV.ssv_gui.SSVGUI(canvas: SSVCanvas, render_buffer: SSVRenderBuffer)[source]
An immediate mode GUI library for pySSV.
Creates a new GUI and binds its event listeners to the given canvas.
- Parameters:
canvas (SSVCanvas) – the canvas to get events from.
render_buffer (SSVRenderBuffer) – the buffer to render into.
- property padding: Tuple[int, int, int, int]
Gets or sets the amount of padding between GUI elements in pixels.
- property rounding_radius: float
Gets or sets the default corner radius for GUI elements, in pixels.
- on_gui(callback: Callable[[SSVGUI], None], remove: bool = False)[source]
Registers/unregisters a callback to this GUI’s on_gui event which is called any time the GUI is invalidated and needs to be redrawn.
All GUI drawing operations should occur within the callback registered here. Calling GUI drawing functions outside of this callback results in undefined behaviour.
- on_post_gui(callback: Callable[[SSVGUI], None], remove: bool = False)[source]
Registers/unregisters a callback to this GUI’s on_post_gui event which is called just after the GUI drawn.
GUI drawing operations are not permitted within this callback; but any
Reference
values returned by GUI elements will have been updated by the time this callback is invoked.
- begin_horizontal(width: int | None = None, height: int | None = None, pad: bool = False, squeeze: bool = True)[source]
Starts a new horizontal layout group. All GUI elements created after this call will flow horizontally, left to right until
end_horizontal()
is called.- Parameters:
width (int | None) – optionally override the width of this layout group. Defaults to the current
layout_control_width
.height (int | None) – optionally override the height of this layout group. Defaults to the current
layout_control_height
.pad (bool) – whether padding should be created between this layout group and the last GUI element.
squeeze (bool) – whether this layout group should attempt to squeeze the elements contained within if they would have otherwise overflowed.
- begin_vertical(width: int | None = None, height: int | None = None, pad: bool = False, squeeze: bool = False)[source]
Starts a new vertical layout group. All GUI elements created after this call will flow vertically, top to bottom until
end_vertical()
is called.- Parameters:
width (int | None) – optionally override the width of this layout group. Defaults to the current
layout_control_width
.height (int | None) – optionally override the height of this layout group. Defaults to the current
layout_control_height
.pad (bool) – whether padding should be created between this layout group and the last GUI element.
squeeze (bool) – whether this layout group should attempt to squeeze the elements contained within if they would have otherwise overflowed.
- end_vertical() SSVGUILayoutContainer [source]
Ends a vertical layout group.
- Return type:
- begin_toggle(enabled: bool | Reference[bool], width: int | None = None, height: int | None = None, pad: bool = False, squeeze: bool = False)[source]
Starts a new toggle layout group. GUI elements contained within this group can be shown or hidden using the
enabled
field. All GUI elements created after this call will flow vertically, top to bottom untilend_toggle()
is called.- Parameters:
enabled (bool | Reference[bool]) – a boolean or a reference to a boolean for whether the contents of this group should be shown.
width (int | None) – optionally override the width of this layout group. Defaults to the current
layout_control_width
.height (int | None) – optionally override the height of this layout group. Defaults to the current
layout_control_height
.pad (bool) – whether padding should be created between this layout group and the last GUI element.
squeeze (bool) – whether this layout group should attempt to squeeze the elements contained within if they would have otherwise overflowed.
- rect(colour: Colour, rect: Rect | None = None, overlay_last: bool = False)[source]
Creates a rectangle GUI element.
- Parameters:
- rounded_rect(colour: Colour, outline: bool = False, radius: float | None = None, rect: Rect | None = None, overlay_last: bool = False)[source]
Creates a rounded rectangle GUI element.
- Parameters:
colour (Colour) – the colour of the rectangle.
outline (bool) – whether the rectangle should be outlined.
radius (float | None) – the rounding radius in pixels. This can be set to an arbitrarily high number to create circles/pills. Set to
None
to use the GUI’srounding_radius
.rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.
overlay_last (bool) – whether the layout engine should overlay this element onto the last drawn element.
- label(text: str, colour: ~pySSV.ssv_colour.Colour = <pySSV.ssv_colour.Colour object>, font_size: float | None = None, x_offset: int = 0, weight: float = 0.5, italic: bool = False, shadow: bool = False, align: ~pySSV.ssv_gui.TextAlign = TextAlign.LEFT, enforce_hinting: bool = True, rect: ~pySSV.ssv_gui.Rect | None = None, overlay_last: bool = False)[source]
Creates a label GUI element.
- Parameters:
text (str) – the text to display.
colour (Colour) – the colour of the rectangle.
font_size (float | None) – the font size in pt.
x_offset (int) – how far to indent the text in pixels.
weight (float) – the font weight [0-1], where 0.5 is the native font weight. The font renderer uses SDF fonts which allows variable font weight rendering for free within certain limits (since this is only an effect, at the extremes type quality is degraded).
italic (bool) – whether the text should be rendered in faux italic. This effect simply applies a shear transformation to the rendered characters, so it will work on any font, but won’t look as good as a proper italic font.
shadow (bool) – whether the text should be rendered with a shadow. This incurs a very small extra rendering cost, and tends to have visual artifacts when the font weight is high.
align (TextAlign) – the horizontal alignment of the text.
enforce_hinting (bool) – this option applies rounding to the font size and position to force it to line up with the pixel grid to improve sharpness. This is only effective if the font texture was rendered with hinting enabled in the first place. This can result in aliasing when animating font size/text position.
rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.
overlay_last (bool) – whether the layout engine should overlay this element onto the last drawn element.
- label_3d(text: str, pos: ~typing.Tuple[float, float, float], colour: ~pySSV.ssv_colour.Colour = <pySSV.ssv_colour.Colour object>, font_size: float | None = None, weight: float = 0.5, italic: bool = False, shadow: bool = False, align: ~pySSV.ssv_gui.TextAlign = TextAlign.CENTRE, enforce_hinting: bool = True)[source]
Creates a label GUI element which is transformed in 3d space using the canvas’s camera.
- Parameters:
text (str) – the text to display.
pos (Tuple[float, float, float]) – the 3d position of the label.
colour (Colour) – the colour of the rectangle.
font_size (float | None) – the font size in pt.
weight (float) – the font weight [0-1], where 0.5 is the native font weight. The font renderer uses SDF fonts which allows variable font weight rendering for free within certain limits (since this is only an effect, at the extremes type quality is degraded).
italic (bool) – whether the text should be rendered in faux italic. This effect simply applies a shear transformation to the rendered characters, so it will work on any font, but won’t look as good as a proper italic font.
shadow (bool) – whether the text should be rendered with a shadow. This incurs a very small extra rendering cost, and tends to have visual artifacts when the font weight is high.
align (TextAlign) – the horizontal alignment of the text.
enforce_hinting (bool) – this option applies rounding to the font size and position to force it to line up with the pixel grid to improve sharpness. This is only effective if the font texture was rendered with hinting enabled in the first place. This can result in aliasing when animating font size/text position.
- button(text: str, colour: Colour | None = None, radius: float | None = None, rect: Rect | None = None) Reference[bool] [source]
Creates a button GUI element.
Since the actual drawing of GUI elements is deferred till after layout has been updated (which occurs just after the on_gui event finishes), the result of whether the button has been clicked or not is not known when this method returns. Wait until the
on_post_gui
event (or the start of the nexton_gui
) event to get the value of the button.- Parameters:
text (str) – the button text.
colour (Colour | None) – the colour of the button rectangle.
radius (float | None) – optionally, the corner radius of the button rectangle.
rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.
- Returns:
a reference to a boolean which will be set to
True
if the button was clicked.- Return type:
- slider(text: str, value: float, min_value: float = 0.0, max_value: float = 1.0, step_size: float = 0, power: float = 1.0, colour: Colour | None = None, track_thickness: float = 4, rect: Rect | None = None) Reference[float] [source]
Creates a slider GUI element.
Since the actual drawing of GUI elements is deferred till after layout has been updated (which occurs just after the on_gui event finishes), the updated value of this slider is not known when this method returns. Wait until the
on_post_gui
event (or the start of the nexton_gui
) event to get the new value of this slider. Until then the value returned by the slider will be the value passed in to it.- Parameters:
text (str) – the label of the slider.
value (float) – the current value of the slider.
min_value (float) – the minimum value of the slider.
max_value (float) – the maximum value of the slider.
step_size (float) – the step size to round the slider value to.
power (float) – an exponent to raise the value of the slider to, useful for creating non-linear sliders.
colour (Colour | None) – the colour of the rectangle.
track_thickness (float) – the thickness of the slider track in pixels.
rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.
- Returns:
a reference to a float which will be set to the new value of the slider.
- Return type:
- checkbox(text: str, value: bool | Reference[bool], colour: Colour | None = None, radius: float | None = None, rect: Rect | None = None) Reference[bool] [source]
Creates a checkbox GUI element.
Since the actual drawing of GUI elements is deferred till after layout has been updated (which occurs just after the on_gui event finishes), the updated value of this checkbox is not known when this method returns. Wait until the
on_post_gui
event (or the start of the nexton_gui
) event to get the new value of this checkbox. Until then the value returned by the checkbox will be the value passed in to it.- Parameters:
text (str) – the label of the checkbox.
value (bool | Reference[bool]) – whether the checkbox is currently checked.
colour (Colour | None) – the colour of the checkbox.
radius (float | None) – optionally, the corner radius of the checkbox.
rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.
- Returns:
a reference to a float which will be set to the new value of the checkbox.
- Return type:
- pySSV.ssv_gui.create_gui(canvas: SSVCanvas) SSVGUI [source]
Creates a new full screen GUI and render buffer and binds it to the canvas (the render buffer’s order defaults to 100).
- class pySSV.ssv_colour.Colour(r: float = 0, g: float = 0, b: float = 0, a: float = 1)[source]
Represents an RGBA colour.
Creates a new colour object
- Parameters:
- class pySSV.ssv_fonts.SSVCharacterDefinition(id: int, char: str, x: int, y: int, width: int, height: int, x_offset: int, y_offset: int, x_advance: int)[source]
- Parameters:
- class pySSV.ssv_fonts.SSVFont(font_path: str)[source]
Constructs a new SSVFont instance from an existing
.fnt
file.A
.fnt
file is a Bitmap Font file which is an xml file following the schema defined here: https://www.angelcode.com/products/bmfont/doc/file_format.htmlFont files can be generated using: https://github.com/soimy/msdf-bmfont-xml
- Parameters:
font_path (str) – the path to the font file to load.
Internal Modules
As a user you generally won’t need to interact with these modules, the documentation provided here is for developers wanting to extend pySSV and power users wanting to better understand how pySSV works internally.
Utilities
- class pySSV.ssv_logging.SSVFormatter(fmt)[source]
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.
Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting,
str.format()
({}
) formatting orstring.Template
formatting in your format string.Changed in version 3.2: Added the
style
parameter.- format(record: LogRecord) str [source]
Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
- class pySSV.ssv_logging.SSVLogStream[source]
A StringIO pipe for sending log messages with a severity level.
- class pySSV.ssv_logging.SSVStreamHandler(stream=None)[source]
Initialize the handler.
If stream is not specified, sys.stderr is used.
- Parameters:
stream (SSVLogStream | TextIO) –
- stream: SSVLogStream | TextIO
- emit(record: LogRecord) None [source]
Emit a record.
If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.
- Parameters:
record (LogRecord) –
- Return type:
None
- pySSV.ssv_logging.set_output_stream(stream: TextIOBase, level=20, prefix='pySSV')[source]
- Parameters:
stream (TextIOBase) –
- pySSV.ssv_logging.set_severity(severity: int)[source]
Sets the minimum message severity to be logged.
- Parameters:
severity (int) – the logging severity as an integer. Preset severity levels are defined in the
logging
module. Possible values include:logging.DEBUG
,logging.INFO
,logging.WARN
,logging.ERROR
, etc…
- pySSV.ssv_logging.get_severity() int [source]
Gets the minimum severity level of the current logger.
- Returns:
the minimum severity level of the logger.
- Return type:
- pySSV.ssv_logging.log(msg, *args, severity=10, raw=False)[source]
Logs a message to the console.
- Parameters:
msg – message to log to the console
args – objects to log to the console
severity – the severity to log the message with, severity levels are defined in the
logging
module.raw – logs the message without any formatting
- class pySSV.environment.Env(value)[source]
An enumeration.
- JUPYTER_NOTEBOOK = 'notebook'
- JUPYTERLAB = 'lab'
- JUPYTERLITE = 'lite'
- SAGEMAKER = 'sagemaker'
- HYPHA = 'hypha'
- COLAB = 'colab'
- class pySSV.ssv_callback_dispatcher.SSVCallbackDispatcher[source]
A simple event callback dispatcher class similar to the
ipywidgets.widgets.widget.CallbackDispatcher
.
- class pySSV.ssv_future.Future[source]
Represents a lightweight, low-level Event-backed future.
For more complex async requirements, the asyncio library is probably a better idea.
- property result: T
- set_result(val: T)[source]
Sets the result of the Future object and notifies objects waiting for the result.
- Parameters:
val (T) – the result to set.
- wait_result(timeout: float | None = None) T | None [source]
Waits synchronously until the result is available and then returns it.
- Parameters:
timeout (float | None) – the maximum amount of time in seconds to wait for the result. Set to
None
to wait indefinitely.- Returns:
the awaited result or
None
if the operation timed out.- Return type:
T | None
Renderer
- class pySSV.ssv_render.ShaderStage(value)[source]
An enum representing an OpenGL shader stage.
- VERTEX = 'vertex'
- TESSELLATION = 'tessellation'
- GEOMETRY = 'geometry'
- PIXEL = 'pixel'
- COMPUTE = 'compute'
- class pySSV.ssv_render.SSVStreamingMode(value)[source]
Represents an image/video streaming mode for pySSV. Note that some of these streaming formats may not be supported on all platforms.
- JPG = 'jpg'
- PNG = 'png'
- VP8 = 'vp8'
- VP9 = 'vp9'
- H264 = 'h264'
- HEVC = 'hevc'
Not supported
- MPEG4 = 'mpeg4'
Not supported
- MJPEG = 'mjpeg'
- class pySSV.ssv_render.SSVRender(gl_version: int | None = None, use_renderdoc_api: bool = False)[source]
An abstract rendering backend for SSV
Initialises a new renderer (and backing graphics context) with the given options.
- Parameters:
- abstract render() bool [source]
Renders a complete frame.
- Returns:
whether the frame rendered successfully.
- Return type:
- abstract read_frame(components: int = 4, frame_buffer_uid: int = 0) bytes [source]
Gets the current contents of the frame buffer as a byte array.
- abstract read_frame_into(buffer: bytearray, components: int = 4, frame_buffer_uid: int = 0) None [source]
Gets the current contents of the frame buffer as a byte array.
- abstract log_context_info(full=False) None [source]
Logs the OpenGL information to the console for debugging.
- Parameters:
full – whether to log all of the OpenGL context information (including extensions).
- Return type:
None
- abstract get_supported_extensions() Set[str] [source]
Gets the set of supported OpenGL shader compiler extensions.
- abstract update_frame_buffer(frame_buffer_uid: int, order: int | None, size: Tuple[int, int] | None, uniform_name: str | None, components: int | None = 4, dtype: str | None = 'f1') None [source]
Updates the resolution/format of the given frame buffer. Note that framebuffer 0 is always used for output. If the given framebuffer id does not exist, it is created.
Setting a parameter to
None
preserves the current value for that frame buffer.- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer to update/create. Buffer 0 is the output framebuffer.
order (int | None) – the sorting order to render the frame buffers in, smaller values are rendered first.
size (Tuple[int, int] | None) – the new resolution of the framebuffer.
uniform_name (str | None) – the name of the uniform to bind this frame buffer to.
components (int | None) – how many vector components should each pixel have (RGB=3, RGBA=4).
dtype (str | None) – the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).
- Return type:
None
- abstract delete_frame_buffer(frame_buffer_uid: int) None [source]
Destroys the given framebuffer. Note that framebuffer 0 can’t be destroyed as it is the output framebuffer.
- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer to destroy.
- Return type:
None
- abstract update_uniform(frame_buffer_uid: int | None, draw_call_uid: int | None, uniform_name: str, value: Any) None [source]
Updates the value of a named shader uniform.
- Parameters:
frame_buffer_uid (int | None) – the uid of the framebuffer of the uniform to update. Set to
None
to update across all buffers.draw_call_uid (int | None) – the uid of the draw call of the uniform to update. Set to
None
to update across all buffers.uniform_name (str) – the name of the shader uniform to update.
value (Any) – the new value of the shader uniform. (Must be convertible to a GLSL type)
- Return type:
None
- abstract update_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int, vertex_array: ndarray[Any, dtype[_ScalarType_co]] | None, index_array: ndarray[Any, dtype[_ScalarType_co]] | None, vertex_attributes: Tuple[str] | None) None [source]
Updates the data inside a vertex buffer.
- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer of the vertex buffer to update.
draw_call_uid (int) – the uid of the draw call of the vertex buffer to update.
vertex_array (ndarray[Any, dtype[_ScalarType_co]] | None) – a numpy array containing the new vertex data.
index_array (ndarray[Any, dtype[_ScalarType_co]] | None) – optionally, a numpy array containing the indices of vertices ordered to make triangles.
vertex_attributes (Tuple[str] | None) – a tuple of the names of the vertex attributes to map to in the shader, in the order that they appear in the vertex array.
- Return type:
None
- abstract delete_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int) None [source]
Deletes an existing vertex buffer.
- abstract register_shader(frame_buffer_uid: int, draw_call_uid: int, vertex_shader: str, fragment_shader: str | None, tess_control_shader: str | None, tess_evaluation_shader: str | None, geometry_shader: str | None, compute_shader: str | None, primitive_type: str | None = None) None [source]
Compiles and registers a shader to a given framebuffer.
- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer to register the shader to.
draw_call_uid (int) – the uid of the draw call to register the shader to.
vertex_shader (str) – the preprocessed vertex shader GLSL source.
fragment_shader (str | None) – the preprocessed fragment shader GLSL source.
tess_control_shader (str | None) – the preprocessed tessellation control shader GLSL source.
tess_evaluation_shader (str | None) – the preprocessed tessellation evaluation shader GLSL source.
geometry_shader (str | None) – the preprocessed geometry shader GLSL source.
compute_shader (str | None) – [Not implemented] the preprocessed compute shader GLSL source.
primitive_type (str | None) – what type of input primitive to treat the vertex data as. One of (“TRIANGLES”, “LINES”, “POINTS), defaults to “TRIANGLES” if
None
.
- Return type:
None
- abstract update_texture(texture_uid: int, data: ndarray[Any, dtype[_ScalarType_co]], uniform_name: str | None, override_dtype: str | None, rect: Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None, treat_as_normalized_integer: bool) None [source]
Creates or updates a texture from the NumPy array provided.
- Parameters:
texture_uid (int) – the uid of the texture to create or update.
data (ndarray[Any, dtype[_ScalarType_co]]) – a NumPy array containing the image data to copy to the texture.
uniform_name (str | None) – the name of the shader uniform to associate this texture with.
override_dtype (str | None) – optionally, a moderngl override
rect (Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None) – optionally, a rectangle (left, top, right, bottom) specifying the area of the target texture to update.
treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.
- Return type:
None
- abstract update_texture_sampler(texture_uid: int, repeat_x: bool | None, repeat_y: bool | None, linear_filtering: bool | None, linear_mipmap_filtering: bool | None, anisotropy: int | None, build_mip_maps: bool) None [source]
Updates a texture’s sampling settings. Parameters set to
None
are not updated.- Parameters:
texture_uid (int) – the uid of the texture to update.
repeat_x (bool | None) – whether the texture should repeat or be clamped in the x-axis.
repeat_y (bool | None) – whether the texture should repeat or be clamped in the y-axis.
linear_filtering (bool | None) – whether the texture should use nearest neighbour (
False
) or linear (True
) interpolation.linear_mipmap_filtering (bool | None) – whether different mipmap levels should blend linearly (
True
) or not (False
).anisotropy (int | None) – the number of anisotropy samples to use. (minimum of 1 = disabled, maximum of 16)
build_mip_maps (bool) – when set to
True
, immediately builds mipmaps for the texture.
- Return type:
None
- abstract delete_texture(texture_uid: int) None [source]
Destroys the given texture object.
- Parameters:
texture_uid (int) – the uid of the texture to destroy.
- Return type:
None
- abstract renderdoc_capture_frame(filename: str | None) None [source]
Triggers a frame capture with Renderdoc if it’s initialised.
- Parameters:
filename (str | None) – optionally, the filename and path to save the capture with.
- Return type:
None
- abstract set_start_time(start_time: float) None [source]
Sets the renderer’s start time; this is used by the renderer to compute the canvas time which is injected into shaders.
- Parameters:
start_time (float) – the start time of the renderer in seconds since the start of the epoch.
- Return type:
None
- pySSV.ssv_render_opengl.load_render_doc(renderdoc_path: str | None = None) RENDERDOC_API_1_6_0 [source]
- Parameters:
renderdoc_path (str | None) –
- Return type:
- class pySSV.ssv_render_opengl.SSVDrawCall[source]
Stores a reference to all the objects needed to represent a single draw call belonging to a render buffer.
- class pySSV.ssv_render_opengl.SSVRenderBufferOpenGL(order: int, needs_gc: bool, frame_buffer: Framebuffer, render_texture: Texture, draw_calls: Dict[int, SSVDrawCall], uniform_name: str)[source]
Stores a reference to all the OpenGL objects needed to render a single render buffer.
- Parameters:
- frame_buffer: Framebuffer
- render_texture: Texture
- draw_calls: Dict[int, SSVDrawCall]
- class pySSV.ssv_render_opengl.SSVTextureOpenGL(texture: Texture | Texture3D, uniform_name: str)[source]
Stores a reference to an OpenGL texture object.
- Parameters:
texture (Texture | Texture3D) –
uniform_name (str) –
- texture: Texture | Texture3D
- class pySSV.ssv_render_opengl.SSVRenderOpenGL(gl_version: int | None = None, use_renderdoc_api: bool = False)[source]
A rendering backend for SSV based on OpenGL
Initialises a new renderer (and backing graphics context) with the given options.
- Parameters:
- log_context_info(full=False)[source]
Logs the OpenGL information to the console for debugging.
- Parameters:
full – whether to log all of the OpenGL context information (including extensions)
- get_supported_extensions() Set[str] [source]
Gets the set of supported OpenGL shader compiler extensions.
- update_frame_buffer(frame_buffer_uid: int, order: int | None, size: Tuple[int, int] | None, uniform_name: str | None, components: int | None = 4, dtype: str | None = 'f1')[source]
Updates the resolution/format of the given frame buffer. Note that framebuffer 0 is always used for output. If the given framebuffer id does not exist, it is created.
Setting a parameter to
None
preserves the current value for that frame buffer.- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer to update/create. Buffer 0 is the output framebuffer.
order (int | None) – the sorting order to render the frame buffers in, smaller values are rendered first.
size (Tuple[int, int] | None) – the new resolution of the framebuffer.
uniform_name (str | None) – the name of the uniform to bind this frame buffer to.
components (int | None) – how many vector components should each pixel have (RGB=3, RGBA=4).
dtype (str | None) – the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).
- delete_frame_buffer(frame_buffer_uid: int)[source]
Destroys the given framebuffer. Note that framebuffer 0 can’t be destroyed as it is the output framebuffer.
- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer to destroy.
- update_uniform(frame_buffer_uid: int | None, draw_call_uid: int | None, uniform_name: str, value: Any)[source]
Updates the value of a named shader uniform.
- Parameters:
frame_buffer_uid (int | None) – the uid of the framebuffer of the uniform to update. Set to
None
to update across all buffers.draw_call_uid (int | None) – the uid of the draw call of the uniform to update. Set to
None
to update across all buffers.uniform_name (str) – the name of the shader uniform to update.
value (Any) – the new value of the shader uniform. (Must be convertible to a GLSL type)
- update_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int, vertex_array: ndarray[Any, dtype[_ScalarType_co]] | None, index_array: ndarray[Any, dtype[_ScalarType_co]] | None, vertex_attributes: Tuple[str] | None)[source]
Updates the data inside a vertex buffer.
- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer of the vertex buffer to update.
draw_call_uid (int) – the uid of the draw call of the vertex buffer to update.
vertex_array (ndarray[Any, dtype[_ScalarType_co]] | None) – a numpy array containing the new vertex data.
index_array (ndarray[Any, dtype[_ScalarType_co]] | None) – optionally, a numpy array containing the indices of vertices ordered to make triangles.
vertex_attributes (Tuple[str] | None) – a tuple of the names of the vertex attributes to map to in the shader, in the order that they appear in the vertex array.
- delete_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int)[source]
Deletes an existing vertex buffer.
- register_shader(frame_buffer_uid: int, draw_call_uid: int, vertex_shader: str, fragment_shader: str | None, tess_control_shader: str | None, tess_evaluation_shader: str | None, geometry_shader: str | None, compute_shader: str | None, primitive_type: str | None = None)[source]
Compiles and registers a shader to a given framebuffer.
- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer to register the shader to.
draw_call_uid (int) – the uid of the draw call to register the shader to.
vertex_shader (str) – the preprocessed vertex shader GLSL source.
fragment_shader (str | None) – the preprocessed fragment shader GLSL source.
tess_control_shader (str | None) – the preprocessed tessellation control shader GLSL source.
tess_evaluation_shader (str | None) – the preprocessed tessellation evaluation shader GLSL source.
geometry_shader (str | None) – the preprocessed geometry shader GLSL source.
compute_shader (str | None) – [Not implemented] the preprocessed compute shader GLSL source.
primitive_type (str | None) – what type of input primitive to treat the vertex data as. One of (“TRIANGLES”, “LINES”, “POINTS), defaults to “TRIANGLES” if
None
.
- update_texture(texture_uid: int, data: ndarray[Any, dtype[_ScalarType_co]], uniform_name: str | None, override_dtype: str | None, rect: Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None, treat_as_normalized_integer: bool)[source]
Creates or updates a texture from the NumPy array provided.
- Parameters:
texture_uid (int) – the uid of the texture to create or update.
data (ndarray[Any, dtype[_ScalarType_co]]) – a NumPy array containing the image data to copy to the texture.
uniform_name (str | None) – the name of the shader uniform to associate this texture with.
override_dtype (str | None) – optionally, a moderngl override
rect (Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None) – optionally, a rectangle (left, top, right, bottom) specifying the area of the target texture to update.
treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.
- update_texture_sampler(texture_uid: int, repeat_x: bool | None, repeat_y: bool | None, linear_filtering: bool | None, linear_mipmap_filtering: bool | None, anisotropy: int | None, build_mip_maps: bool)[source]
Updates a texture’s sampling settings. Parameters set to
None
are not updated.- Parameters:
texture_uid (int) – the uid of the texture to update.
repeat_x (bool | None) – whether the texture should repeat or be clamped in the x-axis.
repeat_y (bool | None) – whether the texture should repeat or be clamped in the y-axis.
linear_filtering (bool | None) – whether the texture should use nearest neighbour (
False
) or linear (True
) interpolation.linear_mipmap_filtering (bool | None) – whether different mipmap levels should blend linearly (
True
) or not (False
).anisotropy (int | None) – the number of anisotropy samples to use. (minimum of 1 = disabled, maximum of 16)
build_mip_maps (bool) – when set to
True
, immediately builds mipmaps for the texture.
- delete_texture(texture_uid: int)[source]
Destroys the given texture object.
- Parameters:
texture_uid (int) – the uid of the texture to destroy.
- read_frame(components: int = 4, frame_buffer_uid: int = 0)[source]
Gets the current contents of the frame buffer as a byte array.
- read_frame_into(buffer, components: int = 4, frame_buffer_uid: int = 0)[source]
Gets the current contents of the frame buffer as a byte array.
- class pySSV.ssv_render_process_client.SSVRenderProcessClient(backend: str, gl_version: int | None = None, timeout: float | None = 1, use_renderdoc_api: bool = False)[source]
This class creates, manages, and provides a communication interface for the render process (an
SSVRenderProcessServer
).Initialises a new Render Process Client and starts the render process.
- Parameters:
- property is_alive
- subscribe_on_render(observer: Callable[[bytes], None])[source]
Subscribes an event handler to the on_render event, triggered after each frame is rendered.
- unsubscribe_on_render(observer: Callable[[bytes], None])[source]
Unsubscribes an event handler from the on_render event.
- subscribe_on_log(observer: Callable[[str], None])[source]
Subscribes an event handler to the on_log event, triggered when the render process logs a message.
- unsubscribe_on_log(observer: Callable[[str], None])[source]
Unsubscribes an event handler from the on_log event.
- update_frame_buffer(frame_buffer_uid: int, order: int | None, size: Tuple[int, int] | None, uniform_name: str | None, components: int | None = 4, dtype: str | None = 'f1')[source]
Updates the resolution/format of the given frame buffer. Note that framebuffer 0 is always used for output. If the given framebuffer id does not exist, it is created.
Setting a parameter to
None
preserves the current value for that frame buffer.- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer to update/create. Buffer 0 is the output framebuffer.
order (int | None) – the sorting order to render the frame buffers in, smaller values are rendered first.
size (Tuple[int, int] | None) – the new resolution of the framebuffer.
uniform_name (str | None) – the name of the uniform to bind this frame buffer to.
components (int | None) – how many vector components should each pixel have (RGB=3, RGBA=4).
dtype (str | None) – the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).
- delete_frame_buffer(buffer_uid: int)[source]
Destroys the given framebuffer. Note that framebuffer 0 can’t be destroyed as it is the output framebuffer.
- Parameters:
buffer_uid (int) – the id of the framebuffer to destroy.
- render(target_framerate: float, stream_mode: str, encode_quality: float | None = None)[source]
Starts rendering frames at the given framerate.
- Parameters:
target_framerate (float) – the framerate to render at. Set to -1 to render a single frame.
stream_mode (str) – the streaming format to use to send the frames to the widget.
encode_quality (float | None) – the encoding quality to use for the given encoding format. Takes a float between 0-100 (some stream modes support values larger than 100, others clamp it internally), where 100 results in the highest quality. This value is scaled to give a bit rate target or quality factor for the chosen encoder. Pass in
None
to use the encoder’s default quality settings.
- set_timeout(time: float | None = 1)[source]
Sets the maximum time the render process will wait for a heartbeat before killing itself. Set to None to disable the watchdog.
- Parameters:
time (float | None) – timeout in seconds.
- update_uniform(frame_buffer_uid: int | None, draw_call_uid: int | None, uniform_name: str, value: Any)[source]
Updates the value of a named shader uniform.
- Parameters:
frame_buffer_uid (int | None) – the uid of the framebuffer of the uniform to update. Set to
None
to update across all buffers.draw_call_uid (int | None) – the uid of the draw call of the uniform to update. Set to
None
to update across all buffers.uniform_name (str) – the name of the shader uniform to update.
value (Any) – the new value of the shader uniform. (Must be convertible to a GLSL type)
- update_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int, vertex_array: ndarray[Any, dtype[_ScalarType_co]] | None, index_array: ndarray[Any, dtype[_ScalarType_co]] | None, vertex_attributes: Tuple[str, ...] | None)[source]
Updates the data inside a vertex buffer.
- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer of the vertex buffer to update.
draw_call_uid (int) – the uid of the draw call of the vertex buffer to update.
vertex_array (ndarray[Any, dtype[_ScalarType_co]] | None) – a numpy array containing the new vertex data.
index_array (ndarray[Any, dtype[_ScalarType_co]] | None) – optionally, a numpy array containing the indices of vertices ordered to make triangles.
vertex_attributes (Tuple[str, ...] | None) – a tuple of the names of the vertex attributes to map to in the shader, in the order that they appear in the vertex array.
- delete_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int)[source]
Deletes an existing vertex buffer.
- update_texture(texture_uid: int, data: ndarray[Any, dtype[_ScalarType_co]], uniform_name: str | None, override_dtype: str | None, rect: Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None, treat_as_normalized_integer: bool)[source]
Creates or updates a texture from the NumPy array provided.
- Parameters:
texture_uid (int) – the uid of the texture to create or update.
data (ndarray[Any, dtype[_ScalarType_co]]) – a NumPy array containing the image data to copy to the texture.
uniform_name (str | None) – the name of the shader uniform to associate this texture with.
override_dtype (str | None) – Optionally, a moderngl override
rect (Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None) – optionally, a rectangle (left, top, right, bottom) specifying the area of the target texture to update.
treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.
- update_texture_sampler(texture_uid: int, repeat_x: bool | None = None, repeat_y: bool | None = None, linear_filtering: bool | None = None, linear_mipmap_filtering: bool | None = None, anisotropy: int | None = None, build_mip_maps: bool = False)[source]
Updates a texture’s sampling settings. Parameters set to
None
are not updated.- Parameters:
texture_uid (int) – the uid of the texture to update.
repeat_x (bool | None) – whether the texture should repeat or be clamped in the x-axis.
repeat_y (bool | None) – whether the texture should repeat or be clamped in the y-axis.
linear_filtering (bool | None) – whether the texture should use nearest neighbour (
False
) or linear (True
) interpolation.linear_mipmap_filtering (bool | None) – whether different mipmap levels should blend linearly (
True
) or not (False
).anisotropy (int | None) – the number of anisotropy samples to use. (minimum of 1 = disabled, maximum of 16)
build_mip_maps (bool) – when set to
True
, immediately builds mipmaps for the texture.
- delete_texture(texture_uid: int)[source]
Destroys the given texture object.
- Parameters:
texture_uid (int) – the uid of the texture to destroy.
- register_shader(frame_buffer_uid: int, draw_call_uid: int, vertex_shader: str, fragment_shader: str | None = None, tess_control_shader: str | None = None, tess_evaluation_shader: str | None = None, geometry_shader: str | None = None, compute_shader: str | None = None, primitive_type: str | None = None)[source]
Compiles and registers a shader to a given framebuffer.
- Parameters:
frame_buffer_uid (int) – the uid of the framebuffer to register the shader to.
draw_call_uid (int) – the uid of the draw call to register the shader to.
vertex_shader (str) – the preprocessed vertex shader GLSL source.
fragment_shader (str | None) – the preprocessed fragment shader GLSL source.
tess_control_shader (str | None) – the preprocessed tessellation control shader GLSL source.
tess_evaluation_shader (str | None) – the preprocessed tessellation evaluation shader GLSL source.
geometry_shader (str | None) – the preprocessed geometry shader GLSL source.
compute_shader (str | None) – [Not implemented] the preprocessed compute shader GLSL source.
primitive_type (str | None) – what type of input primitive to treat the vertex data as. One of (“TRIANGLES”, “LINES”, “POINTS), defaults to “TRIANGLES” if
None
.
- renderdoc_capture_frame(filename: str | None)[source]
Triggers a frame capture with Renderdoc if it’s initialised.
- Parameters:
filename (str | None) – optionally, the filename and path to save the capture with.
- set_start_time(start_time: float) None [source]
Sets the renderer’s start time; this is used by the renderer to compute the canvas time which is injected into shaders.
- Parameters:
start_time (float) – the start time of the renderer in seconds since the start of the epoch.
- Return type:
None
- get_context_info(timeout: float | None = None) Dict[str, str] | None [source]
Returns the OpenGL context information.
- get_frame_times(timeout: float | None = None) Tuple[float, float, float, float] | None [source]
Gets the frame time statistics from the renderer. This function is blocking and shouldn’t be called too often.
- Returns the following statistics:
avg_frame_time: Average time taken to render a frame (calculated each frame using:
last_avg_frame_time * 0.9 + frame_time * 0.1
)max_frame_time: The maximum frame time since this function was last called. (Using
dbg_log_frame_times
interferes with this value.)avg_encode_time: Average time taken to encode a frame for streaming (calculated each frame using:
last_avg_encode_time * 0.9 + encode_time * 0.1
)max_encode_time: The maximum time taken to encode a frame for streaming since this function was last called. (Using
dbg_log_frame_times
interferes with this value.)
- get_supported_extensions(timeout: float | None = None) Set[str] | None [source]
Gets the set of supported OpenGL shader compiler extensions.
- save_image(image_type: SSVStreamingMode, quality: float, size: Tuple[int, int] | None, render_buffer: int, suppress_ui: bool) Future[bytes] [source]
Saves the current frame as an image.
- Parameters:
image_type (SSVStreamingMode) – the image compression algorithm to use.
quality (float) – the encoding quality to use for the given encoding format. Takes a float between 0-100 (some stream modes support values larger than 100, others clamp it internally), where 100 results in the highest quality. This value is scaled to give a bit rate target or quality factor for the chosen encoder.
size (Tuple[int, int] | None) – optionally, the width and height of the saved image. If set to
None
uses the current resolution of the render buffer.render_buffer (int) – the uid of the render buffer to save.
suppress_ui (bool) – whether any active SSVGUIs should be suppressed.
- Returns:
the bytes representing the compressed image.
- Return type:
- dbg_log_context_info(full=False)[source]
Logs the OpenGL information to the console for debugging.
- Parameters:
full – whether to log all of the OpenGL context information (including extensions).
- dbg_log_frame_times(enabled=True)[source]
Enables or disables frame time logging.
- Parameters:
enabled – whether to log frame times.
- class pySSV.ssv_render_process_server.SSVRenderProcessLogger(tx_queue: Queue)[source]
A StringIO pipe for sending log messages to, this class pipes incoming messages to “LogM” commands.
- Parameters:
tx_queue (Queue) –
- class pySSV.ssv_render_process_server.SSVRenderProcessServer(backend: str, gl_version: int | None, command_queue_tx: Queue, command_queue_rx: Queue, log_severity: int, timeout: float | None, use_renderdoc_api: bool = False)[source]
This class listens for render commands and dispatches them to the renderer. This class is intended to be constructed in a dedicated process by SSVRenderProcessClient.
Jupyter Widget
- pySSV.ssv_render_widget.OnSaveImageDelegate
A callable with parameters matching the signature:
on_save_image(image_type: SSVStreamingMode, quality: float, size: Optional[Tuple[int, int]], render_buffer: int): ...
image_type: the image codec to save the image with.quality: a value between 0-100, indicating the image quality (larger values are higher quality). Forpng
this represents compression quality (higher values result in smaller files, but take longer to compress).size: the resolution of the saved image. When set toNone
, uses the current resolution of the render buffer (this also prevents an additional frame from being rendered).render_buffer: the uid of the render buffer to save.suppress_ui: whether any active SSVGUIs should be supressed.alias of
Callable
[[SSVStreamingMode
,float
,Optional
[Tuple
[int
,int
]],int
,bool
],None
]
- class pySSV.ssv_render_widget.SSVRenderWidget(**kwargs: Any)[source]
An SSV Render Widget manages the state and communication of the Jupyter Widget responsible for displaying rendered results embedded in a Jupyter notebook.
Public constructor
- streaming_mode
An enum whose value must be in a given sequence.
- stream_data_binary
A trait for byte strings.
- stream_data_ascii
A trait for unicode strings.
- use_websockets
A boolean (True, False) trait.
- websocket_url
A trait for unicode strings.
- canvas_width
An int trait.
- canvas_height
An int trait.
- status_connection
A boolean (True, False) trait.
- status_logs
A trait for unicode strings.
- mouse_pos_x
An int trait.
- mouse_pos_y
An int trait.
- enable_renderdoc
A boolean (True, False) trait.
- frame_rate
A float trait.
- frame_times
A trait for unicode strings.
- on_heartbeat(callback: Callable[[], None], remove=False)[source]
Register a callback to execute when the widget receives a heartbeat from the client.
- Parameters:
callback (Callable[[], None]) – the function to be called when a heartbeat is received.
remove – set to true to remove the callback from the list of callbacks.
- on_play(callback: Callable[[], None], remove=False)[source]
Register a callback to execute when the widget’s play button is pressed.
- Parameters:
callback (Callable[[], None]) – the function to be called when the play button is pressed.
remove – set to true to remove the callback from the list of callbacks.
- on_stop(callback: Callable[[], None], remove=False)[source]
Register a callback to execute when the widget’s stop button is pressed.
- Parameters:
callback (Callable[[], None]) – the function to be called when the stop button is pressed.
remove – set to true to remove the callback from the list of callbacks.
- on_click(callback: Callable[[bool, int], None], remove=False)[source]
Register a callback to execute when the widget receives a mouseup or mousedown event.
- on_key(callback: Callable[[str, bool], None], remove=False)[source]
Register a callback to execute when the widget receives a keyup or keydown event.
- on_mouse_wheel(callback: Callable[[float], None], remove=False)[source]
Register a callback to execute when the widget receives a mouse wheel event.
- on_save_image(callback: Callable[[SSVStreamingMode, float, Tuple[int, int] | None, int, bool], None], remove=False)[source]
Register a callback to execute when the widget’s ‘save image’ button is pressed.
- on_renderdoc_capture(callback: Callable[[], None], remove=False)[source]
Register a callback to execute when the widget’s renderdoc capture button is pressed.
- Parameters:
callback (Callable[[], None]) – the function to be called when the event is raised.
remove – set to true to remove the callback from the list of callbacks.
- class pySSV.ssv_render_widget.SSVRenderWidgetLogIO(widget: SSVRenderWidget)[source]
- Parameters:
widget (SSVRenderWidget) –
- class pySSV.ssv_canvas_stream_server.SSVCanvasStreamServerHTTP(msg_queue: SimpleQueue, is_alive: Callable[[], bool], *args, **kwargs)[source]
- class pySSV.ssv_canvas_stream_server.SSVCanvasStreamServer(http: bool = False, port: int | None = None, timeout: float = 10)[source]
A basic websocket/http server which serves frame data to the SSV canvas.
- property is_alive
Shader Preprocessor
- class pySSV.ssv_shader_preprocessor.SSVShaderPreprocessor(gl_version: str, supports_line_directives: bool)[source]
This class is responsible for preprocessing shader source code and shader templates into platform specific, ready to compile shaders for each pipeline stage.
- property global_defines: Dict[str, str]
Gets the (mutable) dictionary of compiler macros which are defined globally in all shaders. This does not include any macros defined by the
SSVShaderPreprocessor
itself. The dict contains key-value pairs where the key is the macro name and the value is the macro definition (as a C preprocessor macro).
- preprocess(source: str, filepath: str | None = None, additional_template_directory: str | None = None, additional_templates: List[str] | None = None, shader_defines: Dict[str, str] | None = None, compiler_extensions: List[str] | None = None) Dict[str, str] [source]
Preprocesses an SSV shader into multiple processed shaders for each pipeline.
- Parameters:
source (str) – the shader source code to preprocess. It should contain the necessary
#pragma SSV <template_name>
directive see Built In Shader Templates for more information.filepath (str | None) – the filepath of the shader, used to help the preprocessor give more meaningful error messages.
additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.
additional_templates (List[str] | None) – a list of custom shader templates (source code, not paths). See Writing Shader Templates for information about using custom shader templates.
shader_defines (Dict[str, str] | None) – extra preprocessor defines to be enabled globally.
compiler_extensions (List[str] | None) – a list of GLSL extensions required by this shader (eg:
GL_EXT_control_flow_attributes
)
- Returns:
a dict of compiled shaders for each of the required pipeline stages.
- Return type:
- dbg_query_shader_templates(additional_template_directory: str | None = None) List[SSVTemplatePragmaData] [source]
Gets a list of all the shader templates available to the preprocessor.
- Parameters:
additional_template_directory (str | None) – a path to a directory containing custom shader templates.
- Returns:
A list of shader template metadata definitions.
- Return type:
- dbg_query_shader_template(template_name: str, additional_template_directory: str | None = None, additional_templates: List[str] | None = None) str [source]
Gets the list of arguments a given shader template expects and returns a string containing their usage info.
- Parameters:
- Returns:
the shader template’s auto generated help string.
- Return type:
- class pySSV.ssv_shader_source_preprocessor.SSVShaderSourcePreprocessor(shader_source)[source]
This class is responsible for the actual preprocessing of the shader template. It extends the
pcpp.Preprocessor
to add functionality needed to support our custom #include and #pragma directives.
- class pySSV.ssv_pragma_parser.SSVTemplatePragmaParser[source]
This class is responsible for parsing #pragma definitions in SSV shader templates.
Refer to Writing Shader Templates for details on writing shader templates.
- on_include_not_found(is_malformed, is_system_include, curdir, includepath)[source]
Used internally by the parser.
- on_directive_unknown(directive, toks, ifpassthru, precedingtoks)[source]
Used internally by the parser.
- parse(input, source=None, ignore=None) Dict[str, List[SSVTemplatePragmaData]] [source]
Parses the #pragma directives of a shader template.
- Parameters:
input – the source of the shader template.
source – the path to the source file.
ignore –
- Returns:
a dictionary of parsed shader template commands.
- Return type:
- class pySSV.ssv_pragma_parser.SSVShaderPragmaParser[source]
This class is responsible for parsing #pragma definitions in SSV shaders.
- on_directive_unknown(directive, toks, ifpassthru, precedingtoks)[source]
Used internally by the parser.
- parse(input, source=None, ignore=None) SSVShaderPragmaData [source]
Parses the #pragma directives of a shader.
- Parameters:
input – the source of the shader.
source – the path to the source file.
ignore –
- Returns:
an object of parsed shader template info.
- Return type:
- class pySSV.ssv_shader_args_tokenizer.SSVShaderArgsTokenizer[source]