INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Create a single file with all versions. | def create_file(self, bucket, key, file_versions):
"""Create a single file with all versions."""
objs = []
for file_ver in file_versions:
f = FileInstance.create().set_uri(
file_ver['full_path'],
file_ver['size'],
'md5:{0}'.format(file_... |
Delete the bucket. | def delete_buckets(cls, record):
"""Delete the bucket."""
files = record.get('_files', [])
buckets = set()
for f in files:
buckets.add(f.get('bucket'))
for b_id in buckets:
b = Bucket.get(b_id)
b.deleted = True |
Filter persistent identifiers. | def missing_pids(self):
"""Filter persistent identifiers."""
missing = []
for p in self.pids:
try:
PersistentIdentifier.get(p.pid_type, p.pid_value)
except PIDDoesNotExistError:
missing.append(p)
return missing |
Prepare data. | def prepare_revisions(self):
"""Prepare data."""
# Prepare revisions
self.revisions = []
it = [self.data['record'][0]] if self.latest_only \
else self.data['record']
for i in it:
self.revisions.append(self._prepare_revision(i)) |
Get files from data dump. | def prepare_files(self):
"""Get files from data dump."""
# Prepare files
files = {}
for f in self.data['files']:
k = f['full_name']
if k not in files:
files[k] = []
files[k].append(f)
# Sort versions
for k in files.keys... |
Prepare persistent identifiers. | def prepare_pids(self):
"""Prepare persistent identifiers."""
self.pids = []
for fetcher in self.pid_fetchers:
val = fetcher(None, self.revisions[-1][1])
if val:
self.pids.append(val) |
Check if record is deleted. | def is_deleted(self, record=None):
"""Check if record is deleted."""
record = record or self.revisions[-1][1]
return any(
col == 'deleted'
for col in record.get('collections', [])
) |
Load community from data dump. | def load_community(data, logos_dir):
"""Load community from data dump.
:param data: Dictionary containing community data.
:type data: dict
:param logos_dir: Path to a local directory with community logos.
:type logos_dir: str
"""
from invenio_communities.models import Community
from inv... |
Load community featuring from data dump. | def load_featured(data):
"""Load community featuring from data dump.
:param data: Dictionary containing community featuring data.
:type data: dict
"""
from invenio_communities.models import FeaturedCommunity
obj = FeaturedCommunity(id=data['id'],
id_community=data['i... |
Dump data from Invenio legacy. | def dump(thing, query, from_date, file_prefix, chunk_size, limit, thing_flags):
"""Dump data from Invenio legacy."""
init_app_context()
file_prefix = file_prefix if file_prefix else '{0}_dump'.format(thing)
kwargs = dict((f.strip('-').replace('-', '_'), True) for f in thing_flags)
try:
th... |
Check data in Invenio legacy. | def check(thing):
"""Check data in Invenio legacy."""
init_app_context()
try:
thing_func = collect_things_entry_points()[thing]
except KeyError:
click.Abort(
'{0} is not in the list of available things to migrate: '
'{1}'.format(thing, collect_things_entry_points... |
Registers event handlers used by this widget e. g. mouse click/ motion and window resize. This will allow the widget to redraw itself upon resizing of the window in case the position needs to be adjusted. | def registerEventHandlers(self):
"""
Registers event handlers used by this widget, e.g. mouse click/motion and window resize.
This will allow the widget to redraw itself upon resizing of the window in case the position needs to be adjusted.
"""
self.peng.registerEventHan... |
Property that will always be a 2 - tuple representing the position of the widget. Note that this method may call the method given as pos in the initializer. The returned object will actually be an instance of a helper class to allow for setting only the x/ y coordinate. This property also respects any: py: class: Conta... | def pos(self):
"""
Property that will always be a 2-tuple representing the position of the widget.
Note that this method may call the method given as ``pos`` in the initializer.
The returned object will actually be an instance of a helper class to allow for setting only... |
Similar to: py: attr: pos but for the size instead. | def size(self):
"""
Similar to :py:attr:`pos` but for the size instead.
"""
if isinstance(self._size,list) or isinstance(self._size,tuple):
s = self._size
elif callable(self._size):
w,h = self.submenu.size[:]
s = self._size(w,h)
else:
... |
Property used for determining if the widget should be clickable by the user. This is only true if the submenu of this widget is active and this widget is enabled. The widget may be either disabled by setting this property or the: py: attr: enabled attribute. | def clickable(self):
"""
Property used for determining if the widget should be clickable by the user.
This is only true if the submenu of this widget is active and this widget is enabled.
The widget may be either disabled by setting this property or the :py:attr:`enable... |
Deletes resources of this widget that require manual cleanup. Currently removes all actions event handlers and the background. The background itself should automatically remove all vertex lists to avoid visual artifacts. Note that this method is currently experimental as it seems to have a memory leak. | def delete(self):
"""
Deletes resources of this widget that require manual cleanup.
Currently removes all actions, event handlers and the background.
The background itself should automatically remove all vertex lists to avoid visual artifacts.
Note that... |
Draws the background and the widget itself. Subclasses should use super () to call this method or rendering may glitch out. | def on_redraw(self):
"""
Draws the background and the widget itself.
Subclasses should use ``super()`` to call this method, or rendering may glitch out.
"""
if self.bg is not None:
if not self.bg.initialized:
self.bg.init_bg()
... |
Calculates the Cartesian coordinates from spherical coordinates. pos is a simple offset to offset the result with. radius is the radius of the input. rot is a 2 - tuple of ( azimuth polar ) angles. Angles are given in degrees. Most directions in this game use the same convention. The azimuth ranges from 0 to 360 degree... | def calcSphereCoordinates(pos,radius,rot):
"""
Calculates the Cartesian coordinates from spherical coordinates.
``pos`` is a simple offset to offset the result with.
``radius`` is the radius of the input.
``rot`` is a 2-tuple of ``(azimuth,polar)`` angles.
Angles are given in... |
Simple vector helper function returning the length of a vector. v may be any vector with any number of dimensions | def v_magnitude(v):
"""
Simple vector helper function returning the length of a vector.
``v`` may be any vector, with any number of dimensions
"""
return math.sqrt(sum(v[i]*v[i] for i in range(len(v)))) |
Normalizes the given vector. The vector given may have any number of dimensions. | def v_normalize(v):
"""
Normalizes the given vector.
The vector given may have any number of dimensions.
"""
vmag = v_magnitude(v)
return [ v[i]/vmag for i in range(len(v)) ] |
Transforms the given texture coordinates using the internal texture coordinates. Currently the dimensionality of the input texture coordinates must always be 2 and the output is 3 - dimensional with the last coordinate always being zero. The given texture coordinates are fitted to the internal texture coordinates. Note... | def transformTexCoords(self,data,texcoords,dims=2):
"""
Transforms the given texture coordinates using the internal texture coordinates.
Currently, the dimensionality of the input texture coordinates must always be 2 and the output is 3-dimensional with the last coordinate always being ... |
Helper method ensuring per - entity bone data has been properly initialized. Should be called at the start of every method accessing per - entity data. data is the entity to check in dictionary form. | def ensureBones(self,data):
"""
Helper method ensuring per-entity bone data has been properly initialized.
Should be called at the start of every method accessing per-entity data.
``data`` is the entity to check in dictionary form.
"""
if "_bones" not in... |
Sets the rotation of this bone on the given entity. data is the entity to modify in dictionary form. rot is the rotation of the bone in the format used in: py: func: calcSphereCoordinates () \. | def setRot(self,data,rot):
"""
Sets the rotation of this bone on the given entity.
``data`` is the entity to modify in dictionary form.
``rot`` is the rotation of the bone in the format used in :py:func:`calcSphereCoordinates()`\ .
"""
self.ensureBones(d... |
Sets the length of this bone on the given entity. data is the entity to modify in dictionary form. blength is the new length of the bone. | def setLength(self,data,blength):
"""
Sets the length of this bone on the given entity.
``data`` is the entity to modify in dictionary form.
``blength`` is the new length of the bone.
"""
self.ensureBones(data)
data["_bones"][self.name]["length"]... |
Sets the parent of this bone for all entities. Note that this method must be called before many other methods to ensure internal state has been initialized. This method also registers this bone as a child of its parent. | def setParent(self,parent):
"""
Sets the parent of this bone for all entities.
Note that this method must be called before many other methods to ensure internal state has been initialized.
This method also registers this bone as a child of its parent.
"""
... |
Sets the OpenGL state required for proper drawing of the model. Mostly rotates and translates the camera. It is important to call: py: meth: unsetRotate () after calling this method to properly unset state and avoid OpenGL errors. | def setRotate(self,data):
"""
Sets the OpenGL state required for proper drawing of the model.
Mostly rotates and translates the camera.
It is important to call :py:meth:`unsetRotate()` after calling this method to properly unset state and avoid OpenGL errors.
""... |
Returns the point this bone pivots around on the given entity. This method works recursively by calling its parent and then adding its own offset. The resulting coordinate is relative to the entity not the world. | def getPivotPoint(self,data):
"""
Returns the point this bone pivots around on the given entity.
This method works recursively by calling its parent and then adding its own offset.
The resulting coordinate is relative to the entity, not the world.
"""
pp... |
Returns the vertices of this region already transformed and ready - to - use. Internally uses: py: meth: Bone. transformVertices () \. | def getVertices(self,data):
"""
Returns the vertices of this region already transformed and ready-to-use.
Internally uses :py:meth:`Bone.transformVertices()`\ .
"""
return self.bone.transformVertices(data,self.vertices,self.dims) |
Returns the texture coordinates if any to accompany the vertices of this region already transformed. Note that it is recommended to check the: py: attr: enable_tex flag first. Internally uses: py: meth: Material. transformTexCoords () \. | def getTexCoords(self,data):
"""
Returns the texture coordinates, if any, to accompany the vertices of this region already transformed.
Note that it is recommended to check the :py:attr:`enable_tex` flag first.
Internally uses :py:meth:`Material.transformTexCoords()`\ .... |
Callback that is called to initialize this animation on a specific actor. Internally sets the _anidata key of the given dict data \. jumptype is either jump or animate to define how to switch to this animation. | def startAnimation(self,data,jumptype):
"""
Callback that is called to initialize this animation on a specific actor.
Internally sets the ``_anidata`` key of the given dict ``data``\ .
``jumptype`` is either ``jump`` or ``animate`` to define how to switch to this animat... |
Callback that should be called regularly to update the animation. It is recommended to call this method about 60 times a second for smooth animations. Irregular calling of this method will be automatically adjusted. This method sets all the bones in the given actor to the next state of the animation. Note that: py: met... | def tickEntity(self,data):
"""
Callback that should be called regularly to update the animation.
It is recommended to call this method about 60 times a second for smooth animations. Irregular calling of this method will be automatically adjusted.
This method sets all th... |
Sets the state required for this actor. Currently translates the matrix to the position of the actor. | def set_state(self):
"""
Sets the state required for this actor.
Currently translates the matrix to the position of the actor.
"""
x,y,z = self.obj.pos
glTranslatef(x,y,z) |
Resets the state required for this actor to the default state. Currently resets the matrix to its previous translation. | def unset_state(self):
"""
Resets the state required for this actor to the default state.
Currently resets the matrix to its previous translation.
"""
x,y,z = self.obj.pos
glTranslatef(-x,-y,-z) |
Sets the state required for this vertex region. Currently binds and enables the texture of the material of the region. | def set_state(self):
"""
Sets the state required for this vertex region.
Currently binds and enables the texture of the material of the region.
"""
glEnable(self.region.material.target)
glBindTexture(self.region.material.target, self.region.material.id)
s... |
Resets the state required for this actor to the default state. Currently only disables the target of the texture of the material it may still be bound. | def unset_state(self):
"""
Resets the state required for this actor to the default state.
Currently only disables the target of the texture of the material, it may still be bound.
"""
glDisable(self.region.material.target)
self.region.bone.unsetRotate(self.data) |
Ensures that the given obj has been initialized to be used with this model. If the object is found to not be initialized it will be initialized. | def ensureModelData(self,obj):
"""
Ensures that the given ``obj`` has been initialized to be used with this model.
If the object is found to not be initialized, it will be initialized.
"""
if not hasattr(obj,"_modeldata"):
self.create(obj,cache=True)
... |
Initializes per - actor data on the given object for this model. If cache is set to True the entity will not be redrawn after initialization. Note that this method may set several attributes on the given object most of them starting with underscores. During initialization of vertex regions several vertex lists will be ... | def create(self,obj,cache=False):
"""
Initializes per-actor data on the given object for this model.
If ``cache`` is set to True, the entity will not be redrawn after initialization.
Note that this method may set several attributes on the given object, most of them star... |
Cleans up any left over data structures including vertex lists that reside in GPU memory. Behaviour is undefined if it is attempted to use this model with the same object without calling: py: meth: create () first. It is very important to call this method manually during deletion as this will delete references to data ... | def cleanup(self,obj):
"""
Cleans up any left over data structures, including vertex lists that reside in GPU memory.
Behaviour is undefined if it is attempted to use this model with the same object without calling :py:meth:`create()` first.
It is very important to call... |
Redraws the model of the given object. Note that currently this method probably won t change any data since all movement and animation is done through pyglet groups. | def redraw(self,obj):
"""
Redraws the model of the given object.
Note that currently this method probably won't change any data since all movement and animation is done through pyglet groups.
"""
self.ensureModelData(obj)
data = obj._modeldata
vl... |
Actually draws the model of the given object to the render target. Note that if the batch used for this object already existed drawing will be skipped as the batch should be drawn by the owner of it. | def draw(self,obj):
"""
Actually draws the model of the given object to the render target.
Note that if the batch used for this object already existed, drawing will be skipped as the batch should be drawn by the owner of it.
"""
self.ensureModelData(obj)
... |
Sets the animation to be used by the object. See: py: meth: Actor. setAnimation () for more information. | def setAnimation(self,obj,animation,transition=None,force=False):
"""
Sets the animation to be used by the object.
See :py:meth:`Actor.setAnimation()` for more information.
"""
self.ensureModelData(obj)
data = obj._modeldata
# Validity check
... |
Sets the model this actor should use when drawing. This method also automatically initializes the new model and removes the old if any. | def setModel(self,model):
"""
Sets the model this actor should use when drawing.
This method also automatically initializes the new model and removes the old, if any.
"""
if self.model is not None:
self.model.cleanup(self)
self.model = model
m... |
Sets the animation the model of this actor should show. animation is the name of the animation to switch to. transition can be used to override the transition between the animations. force can be used to force reset the animation even if it is already running. If there is no model set for this actor a: py: exc: Runtime... | def setAnimation(self,animation,transition=None,force=False):
"""
Sets the animation the model of this actor should show.
``animation`` is the name of the animation to switch to.
``transition`` can be used to override the transition between the animations.
... |
Moves the actor using standard trigonometry along the current rotational vector.: param float dist: Distance to move.. todo:: Test this method also with negative distances | def move(self,dist):
"""
Moves the actor using standard trigonometry along the current rotational vector.
:param float dist: Distance to move
.. todo::
Test this method, also with negative distances
"""
x, y = self._rot
y_a... |
write the collection of reports to the given path | def write_reports(self, relative_path, suite_name, reports,
package_name=None):
"""write the collection of reports to the given path"""
dest_path = self.reserve_file(relative_path)
with open(dest_path, 'wb') as outf:
outf.write(toxml(reports, suite_name, packag... |
reserve a XML file for the slice at <relative_path >. xml | def reserve_file(self, relative_path):
"""reserve a XML file for the slice at <relative_path>.xml
- the relative path will be created for you
- not writing anything to that file is an error
"""
if os.path.isabs(relative_path):
raise ValueError('%s must be a relative ... |
convert test reports into an xml file | def toxml(test_reports, suite_name,
hostname=gethostname(), package_name="tests"):
"""convert test reports into an xml file"""
testsuites = et.Element("testsuites")
testsuite = et.SubElement(testsuites, "testsuite")
test_count = len(test_reports)
if test_count < 1:
raise ValueErr... |
Sets up the OpenGL state. This method should be called once after the config has been created and before the main loop is started. You should not need to manually call this method as it is automatically called by: py: meth: run () \. Repeatedly calling this method has no effects. | def setup(self):
"""
Sets up the OpenGL state.
This method should be called once after the config has been created and before the main loop is started.
You should not need to manually call this method, as it is automatically called by :py:meth:`run()`\ .
Repeate... |
Sets the fog system up. The specific options available are documented under: confval: graphics. fogSettings \. | def setupFog(self):
"""
Sets the fog system up.
The specific options available are documented under :confval:`graphics.fogSettings`\ .
"""
fogcfg = self.cfg["graphics.fogSettings"]
if not fogcfg["enable"]:
return
glEnable(GL_FOG)
... |
Runs the application in the current thread. This method should not be called directly especially when using multiple windows use: py: meth: Peng. run () instead. Note that this method is blocking as rendering needs to happen in the main thread. It is thus recommendable to run your game logic in another thread that shou... | def run(self,evloop=None):
"""
Runs the application in the current thread.
This method should not be called directly, especially when using multiple windows, use :py:meth:`Peng.run()` instead.
Note that this method is blocking as rendering needs to happen in the main th... |
Changes to the given menu. menu must be a valid menu name that is currently known... versionchanged:: 1. 2a1 The push/ pop handlers have been deprecated in favor of the new: py: meth: Menu. on_enter () <peng3d. menu. Menu. on_enter > \: py: meth: Menu. on_exit () <peng3d. menu. Menu. on_exit > \ etc. events. | def changeMenu(self,menu):
"""
Changes to the given menu.
``menu`` must be a valid menu name that is currently known.
.. versionchanged:: 1.2a1
The push/pop handlers have been deprecated in favor of the new :py:meth:`Menu.on_enter() <peng3d.menu.M... |
Adds a menu to the list of menus. | def addMenu(self,menu):
"""
Adds a menu to the list of menus.
"""
# If there is no menu selected currently, this menu will automatically be made active.
# Add the line above to the docstring if fixed
self.menus[menu.name]=menu
self.peng.sendEvent("peng3d:window.me... |
Internal event handling method. This method extends the behavior inherited from: py: meth: pyglet. window. Window. dispatch_event () by calling the various: py: meth: handleEvent () methods. By default: py: meth: Peng. handleEvent () \: py: meth: handleEvent () and: py: meth: Menu. handleEvent () are called in this ord... | def dispatch_event(self,event_type,*args):
"""
Internal event handling method.
This method extends the behavior inherited from :py:meth:`pyglet.window.Window.dispatch_event()` by calling the various :py:meth:`handleEvent()` methods.
By default, :py:meth:`Peng.handleEven... |
Toggles mouse exclusivity via pyglet s: py: meth: set_exclusive_mouse () method. If override is given it will be used instead. You may also read the current exclusivity state via: py: attr: exclusive \. | def toggle_exclusivity(self,override=None):
"""
Toggles mouse exclusivity via pyglet's :py:meth:`set_exclusive_mouse()` method.
If ``override`` is given, it will be used instead.
You may also read the current exclusivity state via :py:attr:`exclusive`\ .
"""
... |
Configures OpenGL to draw in 2D. Note that wireframe mode is always disabled in 2D - Mode but can be re - enabled by calling glPolygonMode ( GL_FRONT_AND_BACK GL_LINE ) \. | def set2d(self):
"""
Configures OpenGL to draw in 2D.
Note that wireframe mode is always disabled in 2D-Mode, but can be re-enabled by calling ``glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)``\ .
"""
# Light
glDisable(GL_LIGHTING)
# To avoid... |
Configures OpenGL to draw in 3D. This method also applies the correct rotation and translation as set in the supplied camera cam \. It is discouraged to use: py: func: glTranslatef () or: py: func: glRotatef () directly as this may cause visual glitches. If you need to configure any of the standard parameters see the d... | def set3d(self,cam):
"""
Configures OpenGL to draw in 3D.
This method also applies the correct rotation and translation as set in the supplied camera ``cam``\ .
It is discouraged to use :py:func:`glTranslatef()` or :py:func:`glRotatef()` directly as this may cause visual glitche... |
Re - draws the text by calculating its position. Currently the text will always be centered on the position of the label. | def redraw_label(self):
"""
Re-draws the text by calculating its position.
Currently, the text will always be centered on the position of the label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
sel... |
Re - draws the label by calculating its position. Currently the label will always be centered on the position of the label. | def redraw_label(self):
"""
Re-draws the label by calculating its position.
Currently, the label will always be centered on the position of the label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
x... |
Changes the submenu that is displayed.: raises ValueError: if the name was not previously registered | def changeSubMenu(self,submenu):
"""
Changes the submenu that is displayed.
:raises ValueError: if the name was not previously registered
"""
if submenu not in self.submenus:
raise ValueError("Submenu %s does not exist!"%submenu)
elif submenu == self.... |
Draws the submenu and its background. Note that this leaves the OpenGL state set to 2d drawing. | def draw(self):
"""
Draws the submenu and its background.
Note that this leaves the OpenGL state set to 2d drawing.
"""
# Sets the OpenGL state for 2D-Drawing
self.window.set2d()
# Draws the background
if isinstance(self.bg,Layer):
... |
Deletes the widget by the given name. Note that this feature is currently experimental as there seems to be a memory leak with this method. | def delWidget(self,widget):
"""
Deletes the widget by the given name.
Note that this feature is currently experimental as there seems to be a memory leak with this method.
"""
# TODO: fix memory leak upon widget deletion
#print("*"*50)
#print("Start delWi... |
Sets the background of the submenu. The background may be a RGB or RGBA color to fill the background with. Alternatively a: py: class: peng3d. layer. Layer instance or other object with a. draw () method may be supplied. It is also possible to supply any other method or function that will get called. Also the strings f... | def setBackground(self,bg):
"""
Sets the background of the submenu.
The background may be a RGB or RGBA color to fill the background with.
Alternatively, a :py:class:`peng3d.layer.Layer` instance or other object with a ``.draw()`` method may be supplied.
It is a... |
Helper function converting the actual widget position and size into a usable and offsetted form. This function should return a 6 - tuple of ( sx sy x y bx by ) where sx and sy are the size x and y the position and bx and by are the border size. All values should be in pixels and already include all offsets as they are ... | def getPosSize(self):
"""
Helper function converting the actual widget position and size into a usable and offsetted form.
This function should return a 6-tuple of ``(sx,sy,x,y,bx,by)`` where sx and sy are the size, x and y the position and bx and by are the border size.
... |
Overrideable function that generates the colors to be used by various borderstyles. Should return a 5 - tuple of ( bg o i s h ) \. bg is the base color of the background. o is the outer color it is usually the same as the background color. i is the inner color it is usually lighter than the background color. s is the s... | def getColors(self):
"""
Overrideable function that generates the colors to be used by various borderstyles.
Should return a 5-tuple of ``(bg,o,i,s,h)``\ .
``bg`` is the base color of the background.
``o`` is the outer color, it is usually the same as t... |
if not self. widget. pressed: self. vlist_cross. colors = 6 * bg else: if self. borderstyle == flat: c = [ min ( bg [ 0 ] + 8 255 ) min ( bg [ 1 ] + 8 255 ) min ( bg [ 2 ] + 8 255 ) ] elif self. borderstyle == gradient: c = h elif self. borderstyle == oldshadow: c = h elif self. borderstyle == material: c = s self. vli... | def redraw_bg(self):
# Convenience variables
sx,sy = self.widget.size
x,y = self.widget.pos
bx,by = self.border
# Button background
# Outer vertices
# x y
v1 = x, y+sy
v2 = x+sx, y+sy
v3 = x, ... |
Re - calculates the position of the Label. | def redraw_label(self):
"""
Re-calculates the position of the Label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
self._label.anchor_x = "left"
self._label.x = x+sx/2.+sx
self._label.y = y+sy/2.+sy*... |
Adds a keybind to the internal registry. Keybind names should be of the format namespace: category. subcategory. name \ e. g. peng3d: actor. player. controls. forward for the forward key combo for the player actor.: param str keybind: Keybind string as described above: param str kbname: Name of the keybind may be used ... | def add(self,keybind,kbname,handler,mod=True):
"""
Adds a keybind to the internal registry.
Keybind names should be of the format ``namespace:category.subcategory.name``\ e.g. ``peng3d:actor.player.controls.forward`` for the forward key combo for the player actor.
:para... |
Changes a keybind of a specific keybindname.: param str kbname: Same as kbname of: py: meth: add (): param str combo: New key combination | def changeKeybind(self,kbname,combo):
"""
Changes a keybind of a specific keybindname.
:param str kbname: Same as kbname of :py:meth:`add()`
:param str combo: New key combination
"""
for key,value in self.keybinds.items():
if kbname in value:
... |
Helper method to simplify checking if a modifier is held.: param str modname: Name of the modifier see: py: data: MODNAME2MODIFIER: param int modifiers: Bitmask to check in same as the modifiers argument of the on_key_press etc. handlers | def mod_is_held(self,modname,modifiers):
"""
Helper method to simplify checking if a modifier is held.
:param str modname: Name of the modifier, see :py:data:`MODNAME2MODIFIER`
:param int modifiers: Bitmask to check in, same as the modifiers argument of the on_key_press etc. han... |
Handles a key combination and dispatches associated events. First all keybind handlers registered via: py: meth: add will be handled then the pyglet event: peng3d: pgevent: on_key_combo with params ( combo symbol modifiers release mod ) is sent to the: py: class: Peng () instance. Also sends the events: peng3d: event: ... | def handle_combo(self,combo,symbol,modifiers,release=False,mod=True):
"""
Handles a key combination and dispatches associated events.
First, all keybind handlers registered via :py:meth:`add` will be handled,
then the pyglet event :peng3d:pgevent:`on_key_combo` with params ``(co... |
Registers needed keybinds and schedules the: py: meth: update Method. You can control what keybinds are used via the: confval: controls. controls. forward etc. Configuration Values. | def registerEventHandlers(self):
"""
Registers needed keybinds and schedules the :py:meth:`update` Method.
You can control what keybinds are used via the :confval:`controls.controls.forward` etc. Configuration Values.
"""
# Forward
self.peng.keybinds.add(self.pen... |
Returns the movement vector according to held buttons and the rotation.: return: 3 - Tuple of ( dx dy dz ): rtype: tuple | def get_motion_vector(self):
"""
Returns the movement vector according to held buttons and the rotation.
:return: 3-Tuple of ``(dx,dy,dz)``
:rtype: tuple
"""
if any(self.move):
x, y = self.actor._rot
strafe = math.degrees(math.atan2(*self.... |
Registers the motion and drag handlers. Note that because of the way pyglet treats mouse dragging there is also an handler registered to the on_mouse_drag event. | def registerEventHandlers(self):
"""
Registers the motion and drag handlers.
Note that because of the way pyglet treats mouse dragging, there is also an handler registered to the on_mouse_drag event.
"""
self.world.registerEventHandler("on_mouse_motion",self.on_mouse_mot... |
Registers the up and down handlers. Also registers a scheduled function every 60th of a second causing pyglet to redraw your window with 60fps. | def registerEventHandlers(self):
"""
Registers the up and down handlers.
Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps.
"""
# Crouch/fly down
self.peng.keybinds.add(self.peng.cfg["controls.controls.cro... |
Should be called regularly to move the actor. This method does nothing if the: py: attr: enabled property is set to False. This method is called automatically and should not be called manually. | def update(self,dt):
"""
Should be called regularly to move the actor.
This method does nothing if the :py:attr:`enabled` property is set to False.
This method is called automatically and should not be called manually.
"""
if not self.enabled:
... |
Internal method used for moving the player.: param float dt: Time delta since the last call to this method | def update(self,dt):
"""
Internal method used for moving the player.
:param float dt: Time delta since the last call to this method
"""
speed = self.movespeed
d = dt * speed # distance covered this tick.
dx, dy, dz = self.get_motion_vector()
# New... |
Called by the initializer to add all widgets. Widgets are discovered by searching through the: py: attr: WIDGETS class attribute. If a key in: py: attr: WIDGETS is also found in the keyword arguments and not none the function with the name given in the value of the key will be called with its only argument being the va... | def add_widgets(self,**kwargs):
"""
Called by the initializer to add all widgets.
Widgets are discovered by searching through the :py:attr:`WIDGETS` class attribute.
If a key in :py:attr:`WIDGETS` is also found in the keyword arguments and
not none, the function with the... |
Adds the main label of the dialog. This widget can be triggered by setting the label label_main to a string. This widget will be centered on the screen. | def add_label_main(self,label_main):
"""
Adds the main label of the dialog.
This widget can be triggered by setting the label ``label_main`` to a string.
This widget will be centered on the screen.
"""
# Main Label
self.wlabel_main = text.Label("... |
Adds an OK button to allow the user to exit the dialog. This widget can be triggered by setting the label label_ok to a string. This widget will be mostly centered on the screen but below the main label by the double of its height. | def add_btn_ok(self,label_ok):
"""
Adds an OK button to allow the user to exit the dialog.
This widget can be triggered by setting the label ``label_ok`` to a string.
This widget will be mostly centered on the screen, but below the main label
by the double of it... |
Helper method that exits the dialog. This method will cause the previously active submenu to activate. | def exitDialog(self):
"""
Helper method that exits the dialog.
This method will cause the previously active submenu to activate.
"""
if self.prev_submenu is not None:
# change back to the previous submenu
# could in theory form a stack if one dial... |
Adds a confirm button to let the user confirm whatever action they were presented with. This widget can be triggered by setting the label label_confirm to a string. This widget will be positioned slightly below the main label and to the left of the cancel button. | def add_btn_confirm(self,label_confirm):
"""
Adds a confirm button to let the user confirm whatever action they were presented with.
This widget can be triggered by setting the label ``label_confirm`` to a string.
This widget will be positioned slightly below the main l... |
Adds a cancel button to let the user cancel whatever choice they were given. This widget can be triggered by setting the label label_cancel to a string. This widget will be positioned slightly below the main label and to the right of the confirm button. | def add_btn_cancel(self,label_cancel):
"""
Adds a cancel button to let the user cancel whatever choice they were given.
This widget can be triggered by setting the label ``label_cancel`` to a string.
This widget will be positioned slightly below the main label and to th... |
Updates the progressbar by re - calculating the label. It is not required to manually call this method since setting any of the properties of this class will automatically trigger a re - calculation. | def update_progressbar(self):
"""
Updates the progressbar by re-calculating the label.
It is not required to manually call this method since setting any of the
properties of this class will automatically trigger a re-calculation.
"""
n,nmin,nmax = self.wprogressb... |
Adds a progressbar and label displaying the progress within a certain task. This widget can be triggered by setting the label label_progressbar to a string. The progressbar will be displayed centered and below the main label. The progress label will be displayed within the progressbar. The label of the progressbar may ... | def add_progressbar(self,label_progressbar):
"""
Adds a progressbar and label displaying the progress within a certain task.
This widget can be triggered by setting the label ``label_progressbar`` to
a string.
The progressbar will be displayed centered and below... |
createWindow ( cls = window. PengWindow * args ** kwargs ) Creates a new window using the supplied cls \. If cls is not given: py: class: peng3d. window. PengWindow () will be used. Any other positional or keyword arguments are passed to the class constructor. Note that this method currently does not support using mult... | def createWindow(self,cls=None,caption_t=None,*args,**kwargs):
"""
createWindow(cls=window.PengWindow, *args, **kwargs)
Creates a new window using the supplied ``cls``\ .
If ``cls`` is not given, :py:class:`peng3d.window.PengWindow()` will be used.
Any ... |
Runs the application main loop. This method is blocking and needs to be called from the main thread to avoid OpenGL bugs that can occur. evloop may optionally be a subclass of: py: class: pyglet. app. base. EventLoop to replace the default event loop. | def run(self,evloop=None):
"""
Runs the application main loop.
This method is blocking and needs to be called from the main thread to avoid OpenGL bugs that can occur.
``evloop`` may optionally be a subclass of :py:class:`pyglet.app.base.EventLoop` to replace the defaul... |
Handles a pyglet event. This method is called by: py: meth: PengWindow. dispatch_event () and handles all events. See: py: meth: registerEventHandler () for how to listen to these events. This method should be used to send pyglet events. For new code it is recommended to use: py: meth: sendEvent () instead. For tunneli... | def sendPygletEvent(self,event_type,args,window=None):
"""
Handles a pyglet event.
This method is called by :py:meth:`PengWindow.dispatch_event()` and handles all events.
See :py:meth:`registerEventHandler()` for how to listen to these events.
This meth... |
Registers an event handler. The specified callable handler will be called every time an event with the same event_type is encountered. All event arguments are passed as positional arguments. This method should be used to listen for pyglet events. For new code it is recommended to use: py: meth: addEventListener () inst... | def addPygletListener(self,event_type,handler):
"""
Registers an event handler.
The specified callable handler will be called every time an event with the same ``event_type`` is encountered.
All event arguments are passed as positional arguments.
This m... |
Sends an event with attached data. event should be a string of format <namespace >: <category1 >. <subcategory2 >. <name > \. There may be an arbitrary amount of subcategories. Also note that this format is not strictly enforced but rather recommended by convention. data may be any Python Object but it usually is a dic... | def sendEvent(self,event,data=None):
"""
Sends an event with attached data.
``event`` should be a string of format ``<namespace>:<category1>.<subcategory2>.<name>``\ .
There may be an arbitrary amount of subcategories. Also note that this
format is not strictly enforced,... |
Adds a handler to the given event. A event may have an arbitrary amount of handlers though assigning too many handlers may slow down event processing. For the format of event \ see: py: meth: sendEvent () \. func is the handler which will be executed with two arguments event_type and data \ as supplied to: py: meth: se... | def addEventListener(self,event,func,raiseErrors=False):
"""
Adds a handler to the given event.
A event may have an arbitrary amount of handlers, though assigning too
many handlers may slow down event processing.
For the format of ``event``\ , see :py:meth:`send... |
Removes the given handler from the given event. If the event does not exist a: py: exc: NameError is thrown. If the handler has not been registered previously also a: py: exc: NameError will be thrown. | def delEventListener(self,event,func):
"""
Removes the given handler from the given event.
If the event does not exist, a :py:exc:`NameError` is thrown.
If the handler has not been registered previously, also a :py:exc:`NameError` will be thrown.
"""
if ... |
Sets the default language for all domains. For recommendations regarding the format of the language code see: py: class: TranslationManager \. Note that the lang parameter of both: py: meth: translate () and: py: meth: translate_lazy () will override this setting. Also note that the code won t be checked for existence ... | def setLang(self,lang):
"""
Sets the default language for all domains.
For recommendations regarding the format of the language code, see
:py:class:`TranslationManager`\ .
Note that the ``lang`` parameter of both :py:meth:`translate()` and
:py:meth:`tran... |
Generates a list of languages based on files found on disk. The optional domain argument may specify a domain to use when checking for files. By default all domains are checked. This internally uses the: py: mod: glob built - in module and the: confval: i18n. lang. format config option to find suitable filenames. It th... | def discoverLangs(self,domain="*"):
"""
Generates a list of languages based on files found on disk.
The optional ``domain`` argument may specify a domain to use when checking
for files. By default, all domains are checked.
This internally uses the :py:mod:`glob`... |
Add the camera to the internal registry. Each camera name must be unique or else only the most recent version will be used. This behavior should not be relied on because some objects may cache objects. Additionally only instances of: py: class: Camera () <peng3d. camera. Camera > may be used everything else raises a: p... | def addCamera(self,camera):
"""
Add the camera to the internal registry.
Each camera name must be unique, or else only the most recent version will be used. This behavior should not be relied on because some objects may cache objects.
Additionally, only instances of :py... |
Adds the supplied: py: class: WorldView () object to the internal registry. The same restrictions as for cameras apply e. g. no duplicate names. Additionally only instances of: py: class: WorldView () may be used everything else raises a: py: exc: TypeError \. | def addView(self,view):
"""
Adds the supplied :py:class:`WorldView()` object to the internal registry.
The same restrictions as for cameras apply, e.g. no duplicate names.
Additionally, only instances of :py:class:`WorldView()` may be used, everything else raises a :py:... |
Returns the view with name name \. Raises a: py: exc: ValueError if the view does not exist. | def getView(self,name):
"""
Returns the view with name ``name``\ .
Raises a :py:exc:`ValueError` if the view does not exist.
"""
if name not in self.views:
raise ValueError("Unknown world view")
return self.views[name] |
Renders the world in 3d - mode. If you want to render custom terrain you may override this method. Be careful that you still call the original method or else actors may not be rendered. | def render3d(self,view=None):
"""
Renders the world in 3d-mode.
If you want to render custom terrain, you may override this method. Be careful that you still call the original method or else actors may not be rendered.
"""
for actor in self.actors.values():
a... |
Renders the world. | def render3d(self,view=None):
"""
Renders the world.
"""
super(StaticWorld,self).render3d(view)
self.batch3d.draw() |
Sets the active camera. This method also calls the: py: meth: Camera. on_activate () <peng3d. camera. Camera. on_activate > event handler if the camera is not already active. | def setActiveCamera(self,name):
"""
Sets the active camera.
This method also calls the :py:meth:`Camera.on_activate() <peng3d.camera.Camera.on_activate>` event handler if the camera is not already active.
"""
if name == self.activeCamera:
return # Cam is alre... |
Fake event handler same as: py: meth: WorldView. on_menu_enter () but forces mouse exclusivity. | def on_menu_enter(self,old):
"""
Fake event handler, same as :py:meth:`WorldView.on_menu_enter()` but forces mouse exclusivity.
"""
super(WorldViewMouseRotatable,self).on_menu_enter(old)
self.world.peng.window.toggle_exclusivity(True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.