Search is not available for this dataset
text stringlengths 75 104k |
|---|
def swap_buffers(self):
"""
Swaps buffers, incement the framecounter and pull events.
"""
self.frames += 1
glfw.swap_buffers(self.window)
self.poll_events() |
def resize(self, width, height):
"""
Sets the new size and buffer size internally
"""
self.width = width
self.height = height
self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window)
self.set_default_viewport() |
def check_glfw_version(self):
"""
Ensure glfw library version is compatible
"""
print("glfw version: {} (python wrapper version {})".format(glfw.get_version(), glfw.__version__))
if glfw.get_version() < self.min_glfw_version:
raise ValueError("Please update glfw bina... |
def key_event_callback(self, window, key, scancode, action, mods):
"""
Key event callback for glfw.
Translates and forwards keyboard event to :py:func:`keyboard_event`
:param window: Window event origin
:param key: The key that was pressed or released.
:param scancode: T... |
def ctx() -> moderngl.Context:
"""ModernGL context"""
win = window()
if not win.ctx:
raise RuntimeError("Attempting to get context before creation")
return win.ctx |
def quad_2d(width, height, xpos=0.0, ypos=0.0) -> VAO:
"""
Creates a 2D quad VAO using 2 triangles with normals and texture coordinates.
Args:
width (float): Width of the quad
height (float): Height of the quad
Keyword Args:
xpos (float): Center position x
ypos (float):... |
def translate_buffer_format(vertex_format):
"""Translate the buffer format"""
buffer_format = []
attributes = []
mesh_attributes = []
if "T2F" in vertex_format:
buffer_format.append("2f")
attributes.append("in_uv")
mesh_attributes.append(("TEXCOORD_0", "in_uv", 2))
if "... |
def load(self):
"""Deferred loading"""
path = self.find_scene(self.meta.path)
if not path:
raise ValueError("Scene '{}' not found".format(self.meta.path))
if path.suffix == '.bin':
path = path.parent / path.stem
data = pywavefront.Wavefront(str(path), c... |
def start(self):
"""
Start the timer by recoding the current ``time.time()``
preparing to report the number of seconds since this timestamp.
"""
if self.start_time is None:
self.start_time = time.time()
# Play after pause
else:
# Add the du... |
def stop(self) -> float:
"""
Stop the timer
Returns:
The time the timer was stopped
"""
self.stop_time = time.time()
return self.stop_time - self.start_time - self.offset |
def get_time(self) -> float:
"""
Get the current time in seconds
Returns:
The current time in seconds
"""
if self.pause_time is not None:
curr_time = self.pause_time - self.offset - self.start_time
return curr_time
curr_time = time.ti... |
def set_time(self, value: float):
"""
Set the current time. This can be used to jump in the timeline.
Args:
value (float): The new time
"""
if value < 0:
value = 0
self.offset += self.get_time() - value |
def resolve_loader(self, meta: SceneDescription):
"""
Resolve scene loader based on file extension
"""
for loader_cls in self._loaders:
if loader_cls.supports_file(meta):
meta.loader_cls = loader_cls
break
else:
raise Improp... |
def on_key_press(self, symbol, modifiers):
"""
Pyglet specific key press callback.
Forwards and translates the events to :py:func:`keyboard_event`
"""
self.keyboard_event(symbol, self.keys.ACTION_PRESS, modifiers) |
def on_key_release(self, symbol, modifiers):
"""
Pyglet specific key release callback.
Forwards and translates the events to :py:func:`keyboard_event`
"""
self.keyboard_event(symbol, self.keys.ACTION_RELEASE, modifiers) |
def on_mouse_motion(self, x, y, dx, dy):
"""
Pyglet specific mouse motion callback.
Forwards and traslates the event to :py:func:`cursor_event`
"""
# screen coordinates relative to the lower-left corner
self.cursor_event(x, self.buffer_height - y, dx, dy) |
def on_resize(self, width, height):
"""
Pyglet specific callback for window resize events.
"""
self.width, self.height = width, height
self.buffer_width, self.buffer_height = width, height
self.resize(width, height) |
def swap_buffers(self):
"""
Swap buffers, increment frame counter and pull events
"""
if not self.window.context:
return
self.frames += 1
self.window.flip()
self.window.dispatch_events() |
def sphere(radius=0.5, sectors=32, rings=16) -> VAO:
"""
Creates a sphere.
Keyword Args:
radius (float): Radius or the sphere
rings (int): number or horizontal rings
sectors (int): number of vertical segments
Returns:
A :py:class:`demosys.opengl.vao.VAO` instance
""... |
def draw(self, current_time, frame_time):
"""
Calls the superclass ``draw()`` methods and checks ``HEADLESS_FRAMES``/``HEADLESS_DURATION``
"""
super().draw(current_time, frame_time)
if self.headless_duration and current_time >= self.headless_duration:
self.close() |
def swap_buffers(self):
"""
Headless window currently don't support double buffering.
We only increment the frame counter here.
"""
self.frames += 1
if self.headless_frames and self.frames >= self.headless_frames:
self.close() |
def load(self, meta: ResourceDescription) -> Any:
"""
Loads a resource or return existing one
:param meta: The resource description
"""
self._check_meta(meta)
self.resolve_loader(meta)
return meta.loader_cls(meta).load() |
def add(self, meta):
"""
Add a resource to this pool.
The resource is loaded and returned when ``load_pool()`` is called.
:param meta: The resource description
"""
self._check_meta(meta)
self.resolve_loader(meta)
self._resources.append(meta) |
def load_pool(self):
"""
Loads all the data files using the configured finders.
"""
for meta in self._resources:
resource = self.load(meta)
yield meta, resource
self._resources = [] |
def resolve_loader(self, meta: ResourceDescription):
"""
Attempts to assign a loader class to a resource description
:param meta: The resource description instance
"""
meta.loader_cls = self.get_loader(meta, raise_on_error=True) |
def get_loader(self, meta: ResourceDescription, raise_on_error=False) -> BaseLoader:
"""
Attempts to get a loader
:param meta: The resource description instance
:param raise_on_error: Raise ImproperlyConfigured if the loader cannot be resolved
:returns: The requested loader clas... |
def keyPressEvent(self, event):
"""
Pyqt specific key press callback function.
Translates and forwards events to :py:func:`keyboard_event`.
"""
self.keyboard_event(event.key(), self.keys.ACTION_PRESS, 0) |
def keyReleaseEvent(self, event):
"""
Pyqt specific key release callback function.
Translates and forwards events to :py:func:`keyboard_event`.
"""
self.keyboard_event(event.key(), self.keys.ACTION_RELEASE, 0) |
def resize(self, width, height):
"""
Pyqt specific resize callback.
"""
if not self.fbo:
return
# pyqt reports sizes in actual buffer size
self.width = width // self.widget.devicePixelRatio()
self.height = height // self.widget.devicePixelRatio()
... |
def draw(self, texture, pos=(0.0, 0.0), scale=(1.0, 1.0)):
"""
Draw texture using a fullscreen quad.
By default this will conver the entire screen.
:param pos: (tuple) offset x, y
:param scale: (tuple) scale x, y
"""
if not self.initialized:
... |
def draw_depth(self, texture, near, far, pos=(0.0, 0.0), scale=(1.0, 1.0)):
"""
Draw depth buffer linearized.
By default this will draw the texture as a full screen quad.
A sampler will be used to ensure the right conditions to draw the depth buffer.
:param near: Near plan... |
def _init_texture2d_draw(self):
"""Initialize geometry and shader for drawing FBO layers"""
if not TextureHelper._quad:
TextureHelper._quad = geometry.quad_fs()
# Shader for drawing color layers
TextureHelper._texture2d_shader = context.ctx().program(
vert... |
def _init_depth_texture_draw(self):
"""Initialize geometry and shader for drawing FBO layers"""
from demosys import geometry
if not TextureHelper._quad:
TextureHelper._quad = geometry.quad_fs()
# Shader for drawing depth layers
TextureHelper._depth_shader = ... |
def draw(self, current_time, frame_time):
"""
Draws a frame. Internally it calls the
configured timeline's draw method.
Args:
current_time (float): The current time (preferrably always from the configured timer class)
frame_time (float): The duration of the previ... |
def clear(self):
"""
Clear the window buffer
"""
self.ctx.fbo.clear(
red=self.clear_color[0],
green=self.clear_color[1],
blue=self.clear_color[2],
alpha=self.clear_color[3],
depth=self.clear_depth,
) |
def clear_values(self, red=0.0, green=0.0, blue=0.0, alpha=0.0, depth=1.0):
"""
Sets the clear values for the window buffer.
Args:
red (float): red compoent
green (float): green compoent
blue (float): blue compoent
alpha (float): alpha compoent
... |
def keyboard_event(self, key, action, modifier):
"""
Handles the standard keyboard events such as camera movements,
taking a screenshot, closing the window etc.
Can be overriden add new keyboard events. Ensure this method
is also called if you want to keep the standard features.... |
def cursor_event(self, x, y, dx, dy):
"""
The standard mouse movement event method.
Can be overriden to add new functionality.
By default this feeds the system camera with new values.
Args:
x: The current mouse x position
y: The current mouse y position
... |
def set_default_viewport(self):
"""
Calculates the viewport based on the configured aspect ratio in settings.
Will add black borders if the window do not match the viewport.
"""
# The expected height with the current viewport width
expected_height = int(self.buffer_width ... |
def start(self):
"""Start the timer"""
self.music.start()
if not self.start_paused:
self.rocket.start() |
def toggle_pause(self):
"""Toggle pause mode"""
self.controller.playing = not self.controller.playing
self.music.toggle_pause() |
def supports_file(cls, meta):
"""Check if the loader has a supported file extension"""
path = Path(meta.path)
for ext in cls.file_extensions:
if path.suffixes[:len(ext)] == ext:
return True
return False |
def get(self, name) -> Track:
"""
Get or create a Track object.
:param name: Name of the track
:return: Track object
"""
name = name.lower()
track = self.track_map.get(name)
if not track:
track = Track(name)
self.tacks.append(track... |
def find_commands(command_dir: str) -> List[str]:
"""
Get all command names in the a folder
:return: List of commands names
"""
if not command_dir:
return []
return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
if not is_pkg and not name.startswith('_')] |
def execute_from_command_line(argv=None):
"""
Currently the only entrypoint (manage.py, demosys-admin)
"""
if not argv:
argv = sys.argv
# prog_name = argv[0]
system_commands = find_commands(system_command_dir())
project_commands = find_commands(project_command_dir())
project_pa... |
def update(self, **kwargs):
"""Override settings values"""
for name, value in kwargs.items():
setattr(self, name, value) |
def add_program_dir(self, directory):
"""Hack in program directory"""
dirs = list(self.PROGRAM_DIRS)
dirs.append(directory)
self.PROGRAM_DIRS = dirs |
def add_texture_dir(self, directory):
"""Hack in texture directory"""
dirs = list(self.TEXTURE_DIRS)
dirs.append(directory)
self.TEXTURE_DIRS = dirs |
def add_data_dir(self, directory):
"""Hack in a data directory"""
dirs = list(self.DATA_DIRS)
dirs.append(directory)
self.DATA_DIRS = dirs |
def content(self, attributes: List[str]):
"""Build content tuple for the buffer"""
formats = []
attrs = []
for attrib_format, attrib in zip(self.attrib_formats, self.attributes):
if attrib not in attributes:
formats.append(attrib_format.pad_str())
... |
def render(self, program: moderngl.Program, mode=None, vertices=-1, first=0, instances=1):
"""
Render the VAO.
Args:
program: The ``moderngl.Program``
Keyword Args:
mode: Override the draw mode (``TRIANGLES`` etc)
vertices (int): The number of vertic... |
def render_indirect(self, program: moderngl.Program, buffer, mode=None, count=-1, *, first=0):
"""
The render primitive (mode) must be the same as the input primitive of the GeometryShader.
The draw commands are 5 integers: (count, instanceCount, firstIndex, baseVertex, baseInstance).
A... |
def transform(self, program: moderngl.Program, buffer: moderngl.Buffer,
mode=None, vertices=-1, first=0, instances=1):
"""
Transform vertices. Stores the output in a single buffer.
Args:
program: The ``moderngl.Program``
buffer: The ``moderngl.buffer`` ... |
def buffer(self, buffer, buffer_format: str, attribute_names, per_instance=False):
"""
Register a buffer/vbo for the VAO. This can be called multiple times.
adding multiple buffers (interleaved or not)
Args:
buffer: The buffer data. Can be ``numpy.array``, ``moderngl.Buffer`... |
def index_buffer(self, buffer, index_element_size=4):
"""
Set the index buffer for this VAO
Args:
buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``
Keyword Args:
index_element_size (int): Byte size of each element. 1, 2 or 4
"""
if not ty... |
def instance(self, program: moderngl.Program) -> moderngl.VertexArray:
"""
Obtain the ``moderngl.VertexArray`` instance for the program.
The instance is only created once and cached internally.
Returns: ``moderngl.VertexArray`` instance
"""
vao = self.vaos.get(program.gl... |
def release(self, buffer=True):
"""
Destroy the vao object
Keyword Args:
buffers (bool): also release buffers
"""
for key, vao in self.vaos:
vao.release()
if buffer:
for buff in self.buffers:
buff.buffer.release()
... |
def cube(width, height, depth, center=(0.0, 0.0, 0.0), normals=True, uvs=True) -> VAO:
"""
Creates a cube VAO with normals and texture coordinates
Args:
width (float): Width of the cube
height (float): Height of the cube
depth (float): Depth of the cube
Keyword Args:
ce... |
def draw(self, mesh, projection_matrix=None, view_matrix=None, camera_matrix=None, time=0):
"""
Draw code for the mesh. Should be overriden.
:param projection_matrix: projection_matrix (bytes)
:param view_matrix: view_matrix (bytes)
:param camera_matrix: camera_matrix (bytes)
... |
def pause(self):
"""Pause the music"""
self.pause_time = self.get_time()
self.paused = True
self.player.pause() |
def get_time(self) -> float:
"""
Get the current time in seconds
Returns:
The current time in seconds
"""
if self.paused:
return self.pause_time
return self.player.get_time() / 1000.0 |
def parse_package_string(path):
"""
Parse the effect package string.
Can contain the package python path or path to effect class in an effect package.
Examples::
# Path to effect pacakge
examples.cubes
# Path to effect class
examples.cubes.Cubes
Args:
path... |
def get_dirs(self) -> List[str]:
"""
Get all effect directories for registered effects.
"""
for package in self.packages:
yield os.path.join(package.path, 'resources') |
def get_effect_resources(self) -> List[Any]:
"""
Get all resources registed in effect packages.
These are typically located in ``resources.py``
"""
resources = []
for package in self.packages:
resources.extend(package.resources)
return resources |
def add_package(self, name):
"""
Registers a single package
:param name: (str) The effect package to add
"""
name, cls_name = parse_package_string(name)
if name in self.package_map:
return
package = EffectPackage(name)
package.load()
... |
def get_package(self, name) -> 'EffectPackage':
"""
Get a package by python path. Can also contain path to an effect.
Args:
name (str): Path to effect package or effect
Returns:
The requested EffectPackage
Raises:
EffectError when no package... |
def find_effect_class(self, path) -> Type[Effect]:
"""
Find an effect class by class name or full python path to class
Args:
path (str): effect class name or full python path to effect class
Returns:
Effect class
Raises:
EffectError if no cl... |
def runnable_effects(self) -> List[Type[Effect]]:
"""Returns the runnable effect in the package"""
return [cls for cls in self.effect_classes if cls.runnable] |
def load_package(self):
"""FInd the effect package"""
try:
self.package = importlib.import_module(self.name)
except ModuleNotFoundError:
raise ModuleNotFoundError("Effect package '{}' not found.".format(self.name)) |
def load_effects_classes(self):
"""Iterate the module attributes picking out effects"""
self.effect_classes = []
for _, cls in inspect.getmembers(self.effect_module):
if inspect.isclass(cls):
if cls == Effect:
continue
if issubcla... |
def load_resource_module(self):
"""Fetch the resource list"""
# Attempt to load the dependencies module
try:
name = '{}.{}'.format(self.name, 'dependencies')
self.dependencies_module = importlib.import_module(name)
except ModuleNotFoundError as err:
ra... |
def create(file_format='png', name=None):
"""
Create a screenshot
:param file_format: formats supported by PIL (png, jpeg etc)
"""
dest = ""
if settings.SCREENSHOT_PATH:
if not os.path.exists(settings.SCREENSHOT_PATH):
print("SCREENSHOT_PATH does not exist. creating: {}".form... |
def draw(self, time, frametime, target):
"""
Fetch track value for every runnable effect.
If the value is > 0.5 we draw it.
"""
for effect in self.effects:
value = effect.rocket_timeline_track.time_value(time)
if value > 0.5:
effect... |
def load(self):
"""Load a 2d texture"""
self._open_image()
components, data = image_data(self.image)
texture = self.ctx.texture(
self.image.size,
components,
data,
)
texture.extra = {'meta': self.meta}
if self.me... |
def from_single(cls, meta: ProgramDescription, source: str):
"""Initialize a single glsl string containing all shaders"""
instance = cls(meta)
instance.vertex_source = ShaderSource(
VERTEX_SHADER,
meta.path or meta.vertex_shader,
source
)
... |
def from_separate(cls, meta: ProgramDescription, vertex_source, geometry_source=None, fragment_source=None,
tess_control_source=None, tess_evaluation_source=None):
"""Initialize multiple shader strings"""
instance = cls(meta)
instance.vertex_source = ShaderSource(
... |
def create(self):
"""
Creates a shader program.
Returns:
ModernGL Program instance
"""
# Get out varyings
out_attribs = []
# If no fragment shader is present we are doing transform feedback
if not self.fragment_source:
... |
def find_out_attribs(self):
"""
Get all out attributes in the shader source.
:return: List of attribute names
"""
names = []
for line in self.lines:
if line.strip().startswith("out "):
names.append(line.split()[2].replace(';', ''))
... |
def print(self):
"""Print the shader lines"""
print("---[ START {} ]---".format(self.name))
for i, line in enumerate(self.lines):
print("{}: {}".format(str(i).zfill(3), line))
print("---[ END {} ]---".format(self.name)) |
def create_effect(self, label: str, name: str, *args, **kwargs) -> Effect:
"""
Create an effect instance adding it to the internal effects dictionary using the label as key.
Args:
label (str): The unique label for the effect instance
name (str): Name or full python... |
def load(self):
"""
Loads this project instance
"""
self.create_effect_classes()
self._add_resource_descriptions_to_pools(self.create_external_resources())
self._add_resource_descriptions_to_pools(self.create_resources())
for meta, resource in resources... |
def _add_resource_descriptions_to_pools(self, meta_list):
"""
Takes a list of resource descriptions adding them
to the resource pool they belong to scheduling them for loading.
"""
if not meta_list:
return
for meta in meta_list:
getattr(r... |
def reload_programs(self):
"""
Reload all shader programs with the reloadable flag set
"""
print("Reloading programs:")
for name, program in self._programs.items():
if getattr(program, 'program', None):
print(" - {}".format(program.meta.label))
... |
def get_effect(self, label: str) -> Effect:
"""
Get an effect instance by label
Args:
label (str): The label for the effect instance
Returns:
Effect class instance
"""
return self._get_resource(label, self._effects, "effect") |
def get_effect_class(self, class_name, package_name=None) -> Type[Effect]:
"""
Get an effect class from the effect registry.
Args:
class_name (str): The exact class name of the effect
Keyword Args:
package_name (str): The python path to the effect packag... |
def get_scene(self, label: str) -> Scene:
"""
Gets a scene by label
Args:
label (str): The label for the scene to fetch
Returns:
Scene instance
"""
return self._get_resource(label, self._scenes, "scene") |
def get_texture(self, label: str) -> Union[moderngl.Texture, moderngl.TextureArray,
moderngl.Texture3D, moderngl.TextureCube]:
"""
Get a texture by label
Args:
label (str): The label for the texture to fetch
Returns:
... |
def get_data(self, label: str) -> Any:
"""
Get a data resource by label
Args:
label (str): The labvel for the data resource to fetch
Returns:
The requeted data object
"""
return self._get_resource(label, self._data, "data") |
def _get_resource(self, label: str, source: dict, resource_type: str):
"""
Generic resoure fetcher handling errors.
Args:
label (str): The label to fetch
source (dict): The dictionary to look up the label
resource_type str: The display name of the reso... |
def get_runnable_effects(self) -> List[Effect]:
"""
Returns all runnable effects in the project.
:return: List of all runnable effects
"""
return [effect for name, effect in self._effects.items() if effect.runnable] |
def image_data(image):
"""Get components and bytes for an image"""
# NOTE: We might want to check the actual image.mode
# and convert to an acceptable format.
# At the moment we load the data as is.
data = image.tobytes()
components = len(data) // (image.size[0] * image.size[1]... |
def run_from_argv(self, argv):
"""
Called by the system when executing the command from the command line.
This should not be overridden.
:param argv: Arguments from command line
"""
parser = self.create_parser(argv[0], argv[1])
options = parser.parse_args... |
def create_parser(self, prog_name, subcommand):
"""
Create argument parser and deal with ``add_arguments``.
This method should not be overriden.
:param prog_name: Name of the command (argv[0])
:return: ArgumentParser
"""
parser = argparse.ArgumentParser(p... |
def validate_name(self, name):
"""
Can the name be used as a python module or package?
Raises ``ValueError`` if the name is invalid.
:param name: the name to check
"""
if not name:
raise ValueError("Name cannot be empty")
# Can the name be ... |
def bbox(width=1.0, height=1.0, depth=1.0):
"""
Generates a bounding box with (0.0, 0.0, 0.0) as the center.
This is simply a box with ``LINE_STRIP`` as draw mode.
Keyword Args:
width (float): Width of the box
height (float): Height of the box
depth (float): Depth of the box
... |
def _find_last_of(self, path, finders):
"""Find the last occurance of the file in finders"""
found_path = None
for finder in finders:
result = finder.find(path)
if result:
found_path = result
return found_path |
def initial_sanity_check(self):
"""Checks if we can create the project"""
# Check for python module collision
self.try_import(self.project_name)
# Is the name a valid identifier?
self.validate_name(self.project_name)
# Make sure we don't mess with existing direc... |
def create_entrypoint(self):
"""Write manage.py in the current directory"""
with open(os.path.join(self.template_dir, 'manage.py'), 'r') as fd:
data = fd.read().format(project_name=self.project_name)
with open('manage.py', 'w') as fd:
fd.write(data)
os.c... |
def get_template_dir(self):
"""Returns the absolute path to template directory"""
directory = os.path.dirname(os.path.abspath(__file__))
directory = os.path.dirname(os.path.dirname(directory))
directory = os.path.join(directory, 'project_template')
return directory |
def resolve_loader(self, meta: ProgramDescription):
"""
Resolve program loader
"""
if not meta.loader:
meta.loader = 'single' if meta.path else 'separate'
for loader_cls in self._loaders:
if loader_cls.name == meta.loader:
meta.loader_cls ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.