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_ver['checksum']),
)
obj = ObjectVersion.create(bucket, key).set_file(f)
obj.created = arrow.get(
file_ver['creation_date']).datetime.replace(tzinfo=None)
objs.append(obj)
# Set head version
db.session.commit()
return objs[-1] |
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():
files[k].sort(key=lambda x: x['version'])
self.files = files |
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 invenio_communities.utils import save_and_validate_logo
logo_ext_washed = logo_ext_wash(data['logo_ext'])
c = Community(
id=data['id'],
id_user=data['id_user'],
title=data['title'],
description=data['description'],
page=data['page'],
curation_policy=data['curation_policy'],
last_record_accepted=iso2dt_or_none(data['last_record_accepted']),
logo_ext=logo_ext_washed,
ranking=data['ranking'],
fixed_points=data['fixed_points'],
created=iso2dt(data['created']),
updated=iso2dt(data['last_modified']),
)
logo_path = join(logos_dir, "{0}.{1}".format(c.id, logo_ext_washed))
db.session.add(c)
if isfile(logo_path):
with open(logo_path, 'rb') as fp:
save_and_validate_logo(fp, logo_path, c.id)
db.session.commit() |
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['id_community'],
start_date=iso2dt(data['start_date']))
db.session.add(obj)
db.session.commit() |
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:
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()))
click.echo("Querying {0}...".format(thing))
count, items = thing_func.get(query, from_date, limit=limit, **kwargs)
progress_i = 0 # Progress bar counter
click.echo("Dumping {0}...".format(thing))
with click.progressbar(length=count) as bar:
for i, chunk_ids in enumerate(grouper(items, chunk_size)):
with open('{0}_{1}.json'.format(file_prefix, i), 'w') as fp:
fp.write("[\n")
for _id in chunk_ids:
try:
json.dump(
thing_func.dump(_id, from_date, **kwargs),
fp,
default=set_serializer
)
fp.write(",")
except Exception as e:
click.secho("Failed dump {0} {1} ({2})".format(
thing, _id, e.message), fg='red')
progress_i += 1
bar.update(progress_i)
# Strip trailing comma.
fp.seek(fp.tell()-1)
fp.write("\n]") |
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()))
click.echo("Querying {0}...".format(thing))
count, items = thing_func.get_check()
i = 0
click.echo("Checking {0}...".format(thing))
with click.progressbar(length=count) as bar:
for _id in items:
thing_func.check(_id)
i += 1
bar.update(i) |
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.registerEventHandler("on_mouse_press",self.on_mouse_press)
self.peng.registerEventHandler("on_mouse_release",self.on_mouse_release)
self.peng.registerEventHandler("on_mouse_drag",self.on_mouse_drag)
self.peng.registerEventHandler("on_mouse_motion",self.on_mouse_motion)
self.peng.registerEventHandler("on_resize",self.on_resize) |
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: Container set as its parent any offset will be added automatically. Note that setting this property will override any callable set permanently. | 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 the x/y coordinate.
This property also respects any :py:class:`Container` set as its parent, any offset will be added automatically.
Note that setting this property will override any callable set permanently.
"""
if isinstance(self._pos,list) or isinstance(self._pos,tuple):
r = self._pos
elif callable(self._pos):
w,h = self.submenu.size[:]
r = self._pos(w,h,*self.size)
else:
raise TypeError("Invalid position type")
ox,oy = self.submenu.pos
r = r[0]+ox,r[1]+oy
#if isinstance(self.submenu,ScrollableContainer) and not self._is_scrollbar:# and self.name != "__scrollbar_%s"%self.submenu.name: # Widget inside scrollable container and not the scrollbar
# r = r[0],r[1]+self.submenu.offset_y
return _WatchingList(r,self._wlredraw_pos) |
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:
raise TypeError("Invalid size type")
s = s[:]
if s[0]==-1:
s[0]=self.getMinSize()[0]
if s[1]==-1:
s[1]=self.getMinSize()[1]
# Prevents crashes with negative size
s = [max(s[0],0),max(s[1],0)]
return _WatchingList(s,self._wlredraw_size) |
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:`enabled` attribute.
"""
if not isinstance(self.submenu,Container):
return self.submenu.name == self.submenu.menu.activeSubMenu and self.submenu.menu.name == self.window.activeMenu and self.enabled
else:
return self.submenu.clickable and self.enabled |
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 this method is currently experimental, as it seems to have a memory leak.
"""
# TODO: fix memory leak upon widget deletion
del self.bg.widget
del self.bg
#self.clickable=False
del self._pos
del self._size
self.actions = {}
for e_type,e_handlers in self.peng.eventHandlers.items():
if True or e_type in eh:
to_del = []
for e_handler in e_handlers:
# Weird workaround due to implementation details of WeakMethod
if isinstance(e_handler,weakref.ref):
if super(weakref.WeakMethod,e_handler).__call__() is self:
to_del.append(e_handler)
elif e_handler is self:
to_del.append(e_handler)
for d in to_del:
try:
#print("Deleting handler %s of type %s"%(d,e_type))
del e_handlers[e_handlers.index(d)]
except Exception:
#print("Could not delete handler %s, memory leak may occur"%d)
import traceback;traceback.print_exc() |
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()
self.bg.initialized=True
self.bg.redraw_bg()
super(Widget,self).on_redraw() |
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 degrees with 0 degrees pointing directly to the x - axis. The polar angle ranges from - 90 to 90 with - 90 degrees pointing straight down and 90 degrees straight up. A visualization of the angles required is given in the source code of this function. | 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 degrees. Most directions in this game use the same convention.
The azimuth ranges from 0 to 360 degrees with 0 degrees pointing directly to the x-axis.
The polar angle ranges from -90 to 90 with -90 degrees pointing straight down and 90 degrees straight up.
A visualization of the angles required is given in the source code of this function.
"""
# Input angles should be in degrees, as in the rest of the game
# E.g. phi=inclination and theta=azimuth
# phi is yrad
# Look from above
#(Z goes positive towards you)
#
# Y- Z-
# | /
# | / "far"
# |/
# X- ------+-------> X+
# /| yrad |
# "near" / |<-----+
# / | "polar angle"
# Z+ Y+
# theta is xrad
# Look from above
#(Z goes positive towards you)
#
# Y- Z-
# | /
# | / "far"
# |/
# X- ------+-------> X+
# /| xrad |
# "near" /<-------+
# / | "azimuth angle"
# Z+ Y+
# Based on http://stackoverflow.com/questions/39647735/calculation-of-spherical-coordinates
# https://en.wikipedia.org/wiki/Spherical_coordinate_system
# http://stackoverflow.com/questions/25404613/converting-spherical-coordinates-to-cartesian?rq=1
phi,theta = rot
phi+=90 # very important, took me four days of head-scratching to figure out
phi,theta = math.radians(phi),math.radians(theta)
x = pos[0]+radius * math.sin(phi) * math.cos(theta)
y = pos[1]+radius * math.sin(phi) * math.sin(theta)
z = pos[2]+radius * math.cos(phi)
return x,y,z |
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 that values higher than 1 or lower than 0 may result in unexpected visual glitches. The length of the given texture coordinates should be divisible by the dimensionality. | 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 zero.
The given texture coordinates are fitted to the internal texture coordinates. Note that values higher than 1 or lower than 0 may result in unexpected visual glitches.
The length of the given texture coordinates should be divisible by the dimensionality.
"""
assert dims==2 # TODO
out = []
origcoords = self.tex_coords
min_u,min_v = origcoords[0],origcoords[1]
max_u,max_v = origcoords[6],origcoords[7]
diff_u,diff_v = max_u-min_u, max_v-min_v
itexcoords = iter(texcoords)
for u,v in zip(itexcoords,itexcoords): # Based on http://stackoverflow.com/a/5389547/3490549
out_u = min_u+(diff_u*u)
out_v = min_v+(diff_v*v)
out.extend((out_u,out_v,0))
return out |
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 data:
data["_bones"]={}
if self.name not in data["_bones"]:
data["_bones"][self.name]={"rot":self.start_rot[:],"length":self.blength} |
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(data)
rot = rot[0]%360,max(-90, min(90, rot[1]))
data["_bones"][self.name]["rot"]=rot |
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"]=blength |
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.
"""
self.parent = parent
self.parent.child_bones[self.name]=self |
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.
"""
self.parent.setRotate(data)
glPushMatrix()
x,y = self.getRot(data)
pivot = self.getPivotPoint(data)
px,py,pz = pivot
#ppx,ppy,ppz = self.parent.getPivotPoint(data)
#rot_vec = px-ppx,py-ppy,pz-ppz
#print([px,py,pz],[ppx,ppy,ppz],rot_vec,[x,y],self.getLength(data))
#norm = v_normalize(rot_vec,self.name) if v_magnitude(rot_vec)==0 else [0,1,0] # prevents a zero divison error
normx = [0,1,0] # currently fixed to the up vector, should be changed in the future for proper rotation that is not along the y or z axis
normy = [0,0,1]
#offset = -px,-py,-pz
glTranslatef(px,py,pz)#-offset[0],-offset[1],-offset[2])
glRotatef(x-self.start_rot[0], normx[0],normx[1],normx[2])
glRotatef(y-self.start_rot[1], normy[0],normy[1],normy[2])
glTranslatef(-px,-py,-pz)#offset[0],offset[1],offset[2]) |
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.
"""
ppos = self.parent.getPivotPoint(data)
rot = self.parent.getRot(data)
length = self.parent.getLength(data)
out = calcSphereCoordinates(ppos,length,rot)
return out |
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()`\ .
"""
return self.material.transformTexCoords(data,self.tex_coords,self.tex_dims) |
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 animation.
"""
data["_anidata"]={}
adata = data["_anidata"]
adata["keyframe"]=0
adata["last_tick"]=time.time()
adata["jumptype"]=jumptype
adata["phase"]="transition" |
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: meth: startAnimation () must have been called before calling this method. | 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 the bones in the given actor to the next state of the animation.
Note that :py:meth:`startAnimation()` must have been called before calling this method.
"""
adata = data["_anidata"]
if adata.get("anitype",self.name)!=self.name:
return # incorrectly called
dt = time.time()-adata.get("last_tick",time.time())
adata["last_tick"]=time.time()
if adata.get("phase","transition")=="transition":
# If transitioning to this animation
if adata.get("jumptype",self.default_jt)=="jump":
# Jumping to the animation, e.g. set all bones to the start frame
for bone,dat in self.start_frame.get("bones",{}).items():
if "rot" in dat:
self.bones[bone].setRot(data,dat["rot"])
if "length" in dat:
self.bones[bone].setLength(data,dat["length"])
adata["phase"]="animation"
if self.atype=="keyframes":
adata["from_frame"]=self.start_frame.get("frame",0)
elif adata.get("jumptype",self.default_jt)=="animate":
raise NotImplementedError("Animation update phase transition type animate not yet implemented")
# Not yet working
if "transition_frame" not in adata:
adata["transition_frame"] = 0
tlen = self.anidata.get("transition_length",self.anidata.get("length",60)/3)
tspeed = self.anidata.get("transition_speed",self.anidata.get("keyframespersecond",60))
framediff=int(dt/(1./tspeed)) # Number of frames that have passed since the last update
overhang = dt-(framediff*(1./tspeed)) # time that has passed but is not enough for a full frame
adata["last_tick"]-=overhang # causes the next frame to include the overhang from this frame
if framediff == 0:
return # optimization that saves time
frame1 = adata["transition_frame"]
adata["transition_frame"]+=framediff
if adata["transition_frame"]>tlen:
adata["phase"]="animation"
if self.atype=="keyframes":
adata["from_frame"]=self.start_frame.get("frame",0)
return
frame2 = adata["transition_frame"]
if "frombones" not in adata:
frombones = {}
for bname,bone in self.bones.items():
frombones[bname]={"rot":bone.getRot(data),"length":bone.getLength(data)}
adata["frombones"] = frombones
if "tobones" not in adata:
tobones = {}
for bname,bone in self.start_frame["bones"].items():
tobones[bname]=bone
adata["tobones"] = tobones
frombones = adata["frombones"]
tobones = adata["tobones"]
from_frame = 0
to_frame = tlen
for bname,bone in self.bones.items():
# rot
if bname not in frombones or bname not in tobones:
continue
from_rot = frombones[bname]["rot"]
to_rot = tobones[bname]["rot"]
from_x,from_y=from_rot
to_x,to_y=to_rot
delta_per_frame_x = (to_x-from_x)/(to_frame-from_frame)
delta_per_frame_y = (to_y-from_y)/(to_frame-from_frame)
delta_x = delta_per_frame_x*(frame2-frame1)
delta_y = delta_per_frame_y*(frame2-frame1)
rot = bone.getRot(data)
new_rot = [rot[0]+delta_x,rot[1]+delta_y]
bone.setRot(data,new_rot)
# length
# Not yet implemented
elif adata["phase"]=="animation":
# If animating
if self.atype == "static":
pass # Should not need any updates as the transition will set the bones
elif self.atype == "keyframes":
framediff=int(dt/(1./self.kps)) # Number of frames that have passed since the last update
overhang = dt-(framediff*(1./self.kps)) # time that has passed but is not enough for a full frame
adata["last_tick"]-=overhang # causes the next frame to include the overhang from this frame
if framediff == 0:
return # optimization that saves time
frame1 = adata["keyframe"]
adata["keyframe"]+=framediff
if adata["keyframe"]>self.anilength:
repeat = True
adata["keyframe"]%=self.anilength
else:
repeat = False
frame2 = adata["keyframe"]
if repeat:
frame1 = frame2
frame2+=1
for bname,bone in self.bones.items():
# Rot
if bname in self.rframes_per_bone:
from_frame = None#adata["from_frame"]
to_frame = None
for framenum,rot in self.rframes_per_bone[bname].items():
if (from_frame is None or framenum>from_frame) and framenum<=frame1:
# from_frame is the largest frame number that is before the starting point
from_frame = framenum
if (to_frame is None or framenum<to_frame) and framenum>=frame2:
# to_frame is the smallest frame number that is after the end point
to_frame = framenum
if from_frame is None or to_frame is None:
raise ValueError("Invalid frames for bone %s in animation %s"%(bname,self.name))
if from_frame==to_frame or repeat:
if self.anidata.get("repeat","jump")=="jump":
for b,dat in self.start_frame.get("bones",{}).items():
if "rot" in dat:
self.bones[b].setRot(data,dat["rot"])
if "length" in dat:
self.bones[b].setLength(data,dat["length"])
elif self.anidata.get("repeat","jump")=="animate":
from_frame = adata["to_frame"]
adata["from_frame"]=from_frame
adata["to_frame"]=to_frame
from_rot = self.rframes_per_bone[bname][from_frame]
to_rot = self.rframes_per_bone[bname][to_frame]
from_x,from_y=from_rot
to_x,to_y=to_rot
if self.anidata.get("interpolation","linear") == "linear":
delta_per_frame_x = (to_x-from_x)/(to_frame-from_frame)
delta_per_frame_y = (to_y-from_y)/(to_frame-from_frame)
delta_x = delta_per_frame_x*(frame2-frame1)
delta_y = delta_per_frame_y*(frame2-frame1)
rot = bone.getRot(data)
new_rot = [rot[0]+delta_x,rot[1]+delta_y]
elif self.anidata["interpolation"] == "jump":
new_rot = to_x,to_y
else:
raise ValueError("Invalid interpolation method '%s' for animation %s"%(self.anidata["interpolation"],self.name))
bone.setRot(data,new_rot)
# Length
if bname in self.lframes_per_bone:
# Not yet implemented
pass
else:
# Should not be possible, but still
raise ValueError("Invalid animation type %s for animation %s during tick"%(self.atype,name)) |
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)
self.region.bone.setRotate(self.data) |
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)
if "_modelcache" not in obj._modeldata:
# Assume all initialization is missing, simply reinitialize
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 created. If the given object has an attribute called batch3d it will be used else it will be created. If the batch already existed the: py: meth: draw () method will do nothing else it will draw the batch. Memory leaks may occur if this is called more than once on the same object without calling: py: meth: cleanup () first. | 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 starting with underscores.
During initialization of vertex regions, several vertex lists will be created.
If the given object has an attribute called ``batch3d`` it will be used, else it will be created.
If the batch already existed, the :py:meth:`draw()` method will do nothing, else it will draw the batch.
Memory leaks may occur if this is called more than once on the same object without calling :py:meth:`cleanup()` first.
"""
obj._modeldata = {}
data = obj._modeldata
data["_model"]=self
data["_modelcache"] = {}
moddata = data["_modelcache"]
# Model group, for pos of entity
moddata["group"] = JSONModelGroup(self,data,obj)
modgroup = moddata["group"]
if not hasattr(obj,"batch3d"):
obj.batch3d = pyglet.graphics.Batch()
data["_manual_render"]=True
# Vlists/Regions
moddata["vlists"] = {}
for name,region in self.modeldata["regions"].items():
v = region.getVertices(data)
vlistlen = int(len(v)/region.dims)
if region.enable_tex:
vlist = obj.batch3d.add(vlistlen,region.getGeometryType(data),JSONRegionGroup(self,data,region,modgroup),
"v3f/static",
"t3f/static",
)
else:
vlist = obj.batch3d.add(vlistlen,region.getGeometryType(data),modgroup,
"v3f/static",
)
moddata["vlists"][name]=vlist
self.setAnimation(obj,self.modeldata["default_animation"].name,transition="jump")
self.data = data
if not cache:
self.redraw(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 this method manually during deletion as this will delete references to data objects stored in global variables of third - party modules. | 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 this method manually during deletion as this will delete references to data objects stored in global variables of third-party modules.
"""
if not hasattr(obj,"_modeldata"):
return # already not initialized
data = obj._modeldata
if "_modelcache" in data:
moddata = data["_modelcache"]
if "vlists" in moddata:
for vlist in list(moddata["vlists"].keys()):
del moddata["vlists"][vlist]
del moddata["vlists"]
if "_bones" in data:
for bone in list(data["_bones"].keys()):
del data["_bones"][bone]
del data["_bones"]
if "_anidata" in data:
adata = data["_anidata"]
if "_schedfunc" in adata:
pyglet.clock.unschedule(adata["_schedfunc"])
if data.get("_manual_render",False):
del obj.batch3d
# Removes open vertex lists and other caches
if "_modelcache" not in data:
return
moddata = data["_modelcache"]
if "vlist" in moddata:
moddata["vlist"].delete() # Free up the graphics memory
if "group" in moddata:
del moddata["group"]
del data["_modelcache"], moddata |
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
vlists = data["_modelcache"]["vlists"]
for name,region in self.modeldata["regions"].items():
vlists[name].vertices = region.getVertices(data)
if region.enable_tex:
vlists[name].tex_coords = region.getTexCoords(data) |
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)
data = obj._modeldata
if data.get("_manual_render",False):
obj.batch3d.draw() |
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
if animation not in self.modeldata["animations"]:
raise ValueError("There is no animation of name '%s' for model '%s'"%(animation,self.modelname))
if data.get("_anidata",{}).get("anitype",None)==animation and not force:
return # animation is already running
# Cache the obj to improve readability
anim = self.modeldata["animations"][animation]
# Set to default if not set
if transition is None:
transition = anim.default_jt
# Notify the animation to allow it to initialize itself
anim.startAnimation(data,transition)
# initialize animation data
if "_anidata" not in data:
data["_anidata"]={}
adata = data["_anidata"]
adata["anitype"]=animation
if "_schedfunc" in adata:
# unschedule the old animation, if any
# prevents clashing and crashes
pyglet.clock.unschedule(adata["_schedfunc"])
# Schedule the animation function
def schedfunc(*args):
# This function is defined locally to create a closure
# The closure stores the local variables, e.g. anim and data even after the parent function has finished
# Note that this may also prevent the garbage collection of any objects defined in the parent scope
anim.tickEntity(data)
# register the function to pyglet
pyglet.clock.schedule_interval(schedfunc,1./(anim.kps if anim.atype=="keyframes" else 60))
# save it for later for de-initialization
adata["_schedfunc"] = schedfunc |
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
model.create(self) |
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: RuntimeError will be raised. | 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.
``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:`RuntimeError` will be raised.
"""
if self.model is None:
raise RuntimeError("Can only set animation if a model is set")
self.model.setAnimation(self,animation,transition,force) |
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_angle = math.radians(y)
x_angle = math.radians(x)
m = math.cos(y_angle)
dy = math.sin(y_angle)
dy = 0.0
dx = math.cos(x_angle)
dz = math.sin(x_angle)
dx,dy,dz = dx*dist,dy*dist,dz*dist
x,y,z = self._pos
self.pos = x+dx,y+dy,z+dz
return dx,dy,dz |
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, package_name=package_name))
return dest_path |
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 path' % relative_path)
dest_path = os.path.join(self.root_dir, '%s.xml' % relative_path)
if os.path.exists(dest_path):
raise ValueError('%r must not already exist' % dest_path)
if dest_path in self.expected_xunit_files:
raise ValueError('%r already reserved' % dest_path)
dest_dir = os.path.dirname(dest_path)
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
self.expected_xunit_files.append(dest_path)
return dest_path |
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 ValueError('there must be at least one test report')
assert test_count > 0, 'expecting at least one test'
error_count = len([r for r in test_reports if r.errors])
failure_count = len([r for r in test_reports if r.failures])
ts = test_reports[0].start_ts
start_timestamp = datetime.fromtimestamp(ts).isoformat()
total_duration = test_reports[-1].end_ts - test_reports[0].start_ts
def quote_attribute(value):
return value if value is not None else "(null)"
testsuite.attrib = dict(
id="0",
errors=str(error_count),
failures=str(failure_count),
tests=str(test_count),
hostname=quote_attribute(hostname),
timestamp=quote_attribute(start_timestamp),
time="%f" % total_duration,
name=quote_attribute(suite_name),
package=quote_attribute(package_name),
)
for r in test_reports:
test_name = r.name
test_duration = r.end_ts - r.start_ts
class_name = r.src_location
testcase = et.SubElement(testsuite, "testcase")
testcase.attrib = dict(
name=test_name,
classname=quote_attribute(class_name),
time="%f" % test_duration,
)
if r.errors or r.failures:
if r.failures:
failure = et.SubElement(testcase, "failure")
failure.attrib = dict(
type="exception",
message=quote_attribute('\n'.join(['%s' % e for e in r.failures])),
)
else:
error = et.SubElement(testcase, "error")
error.attrib = dict(
type="exception",
message=quote_attribute('\n'.join(['%s' % e for e in r.errors])),
)
return et.tostring(testsuites, encoding="utf-8") |
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()`\ .
Repeatedly calling this method has no effects.
"""
if self._setup:
return
self._setup = True
# Ensures that default values are supplied
#self.cleanConfig()
# Sets min/max window size, if specified
if self.cfg["graphics.min_size"] is not None:
self.set_minimum_size(*self.cfg["graphics.min_size"])
if self.cfg["graphics.max_size"] is not None:
self.set_maximum_size(*self.cfg["graphics.max_size"])
# Sets up basic OpenGL state
glClearColor(*self.cfg["graphics.clearColor"])
glEnable(GL_DEPTH_TEST)
glEnable(GL_BLEND)
glShadeModel(GL_SMOOTH)
if self.cfg["graphics.fogSettings"]["enable"]:
self.setupFog()
if self.cfg["graphics.lightSettings"]["enable"]:
self.setupLight() |
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)
if fogcfg["color"] is None:
fogcfg["color"] = self.cfg["graphics.clearColor"]
# Set the fog color.
glFogfv(GL_FOG_COLOR, (GLfloat * 4)(*fogcfg["color"]))
# Set the performance hint.
glHint(GL_FOG_HINT, GL_DONT_CARE) # TODO: add customization, including headless support
# Specify the equation used to compute the blending factor.
glFogi(GL_FOG_MODE, GL_LINEAR)
# How close and far away fog starts and ends. The closer the start and end,
# the denser the fog in the fog range.
glFogf(GL_FOG_START, fogcfg["start"])
glFogf(GL_FOG_END, fogcfg["end"]) |
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 should be started before calling this method. 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 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 should be started before calling this method.
``evloop`` may optionally be a subclass of :py:class:`pyglet.app.base.EventLoop` to replace the default event loop.
"""
self.setup()
if evloop is not None:
pyglet.app.event_loop = evloop
pyglet.app.run() # This currently just calls the basic pyglet main loop, maybe implement custom main loop for more control |
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.Menu.on_enter>`\ , :py:meth:`Menu.on_exit() <peng3d.menu.Menu.on_exit>`\ , etc. events.
"""
if menu not in self.menus:
raise ValueError("Menu %s does not exist!"%menu)
elif menu == self.activeMenu:
return # Ignore double menu activation to prevent bugs in menu initializer
old = self.activeMenu
self.activeMenu = menu
if old is not None:
self.menus[old].on_exit(menu)
self.menus[old].doAction("exit")
#self.pop_handlers()
self.menu.on_enter(old)
self.menu.doAction("enter")
self.peng.sendEvent("peng3d:window.menu.change",{"peng":self.peng,"window":self,"old":old,"menu":menu}) |
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.menu.add",{"peng":self.peng,"window":self,"menu":menu}) |
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 order to handle events. Note that some events may not be handled by all handlers during early startup. | 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.handleEvent()`\ , :py:meth:`handleEvent()` and :py:meth:`Menu.handleEvent()` are called in this order to handle events.
Note that some events may not be handled by all handlers during early startup.
"""
super(PengWindow,self).dispatch_event(event_type,*args)
try:
p = self.peng
m = self.menu
except AttributeError:
# To prevent early startup errors
if hasattr(self,"peng") and self.peng.cfg["debug.events.logerr"]:
print("Error:")
traceback.print_exc()
return
p.handleEvent(event_type,args,self)
self.handleEvent(event_type,args)
m.handleEvent(event_type,args) |
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`\ .
"""
if override is not None:
new = override
else:
new = not self.exclusive
self.exclusive = new
self.set_exclusive_mouse(self.exclusive)
self.peng.sendEvent("peng3d:window.toggle_exclusive",{"peng":self.peng,"window":self,"exclusive":self.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 accidental wireframe GUIs and fonts
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL)
width, height = self.get_size()
glDisable(GL_DEPTH_TEST)
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, 0, height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() |
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 docs about: doc:/ configoption \. The: confval: graphics. wireframe config value can be used to enable a wireframe mode useful for debugging visual glitches. | 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 glitches.
If you need to configure any of the standard parameters, see the docs about :doc:`/configoption`\ .
The :confval:`graphics.wireframe` config value can be used to enable a wireframe mode, useful for debugging visual glitches.
"""
if not isinstance(cam,camera.Camera):
raise TypeError("cam is not of type Camera!")
# Light
#glEnable(GL_LIGHTING)
if self.cfg["graphics.wireframe"]:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
width, height = self.get_size()
glEnable(GL_DEPTH_TEST)
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(self.cfg["graphics.fieldofview"], width / float(height), self.cfg["graphics.nearclip"], self.cfg["graphics.farclip"]) # default 60
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
x, y = cam.rot
glRotatef(x, 0, 1, 0)
glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
x, y, z = cam.pos
glTranslatef(-x, -y, -z) |
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
self._label.font_name = self.font_name
self._label.font_size = self.font_size
self._label.font_color = self.font_color
self._label.x = int(x+sx/2.)
self._label.y = int(y+sy/2.)
self._label.width = self.size[0]
self._label.height = self.size[1]
self._label._update() |
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 = x+self.bg.border[0]
y = y+sy/2.-self._text.font_size/4.
w = self.size[0]
h = self.size[1]
self._text.x,self._text.y = x,y
self._text.width,self._text.height=w,h
self._default.x,self._default.y = x,y
self._default.width,self._default.height=w,h
self._text._update() # Needed to prevent the label from drifting to the top-left after resizing by odd amounts
self._default._update() |
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.activeSubMenu:
return # Ignore double submenu activation to prevent bugs in submenu initializer
old = self.activeSubMenu
self.activeSubMenu = submenu
if old is not None:
self.submenus[old].on_exit(submenu)
self.submenus[old].doAction("exit")
self.submenu.on_enter(old)
self.submenu.doAction("enter") |
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):
self.bg._draw()
elif hasattr(self.bg,"draw") and callable(self.bg.draw):
self.bg.draw()
elif isinstance(self.bg,list) or isinstance(self.bg,tuple):
self.bg_vlist.draw(GL_QUADS)
elif callable(self.bg):
self.bg()
elif isinstance(self.bg,Background):
# The background will be drawn via the batch
if not self.bg.initialized:
self.bg.init_bg()
self.bg.redraw_bg()
self.bg.initialized=True
elif self.bg=="blank":
pass
else:
raise TypeError("Unknown background type")
# In case the background modified relevant state
self.window.set2d()
# Check that all widgets that need redrawing have been redrawn
for widget in self.widgets.values():
if widget.do_redraw:
widget.on_redraw()
widget.do_redraw = False
# Actually draw the content
self.batch2d.draw()
# Call custom draw methods where needed
for widget in self.widgets.values():
widget.draw() |
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 delWidget")
if isinstance(widget,BasicWidget):
widget = widget.name
if widget not in self.widgets:
return
w = self.widgets[widget]
#print("refs: %s"%sys.getrefcount(w))
w.delete()
del self.widgets[widget]
del widget
#w_wref = weakref.ref(w)
#print("GC: GARBAGE")
#print(gc.garbage)
#print("Widget Info")
#print(w_wref())
#import objgraph
#print("Objgraph")
#objgraph.show_refs([w], filename='./mem_widget.png')
#print("refs: %s"%sys.getrefcount(w))
#w_r = gc.get_referrers(w)
#print("GC: REFS")
#for w_ref in w_r:
# print(repr(w_ref)[:512])
#print("GC: END")
#print("len: %s"%len(w_r))
#del w_ref,w_r
#print("after del %s"%w_wref())
#print("refs: %s"%sys.getrefcount(w))
del w |
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 flat \ gradient \ oldshadow and material may be given resulting in a background that looks similar to buttons. Lastly the string blank may be passed to skip background drawing. | 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 also possible to supply any other method or function that will get called.
Also, the strings ``flat``\ , ``gradient``\ , ``oldshadow`` and ``material`` may be given, resulting in a background that looks similar to buttons.
Lastly, the string ``"blank"`` may be passed to skip background drawing.
"""
self.bg = bg
if isinstance(bg,list) or isinstance(bg,tuple):
if len(bg)==3 and isinstance(bg,list):
bg.append(255)
self.bg_vlist.colors = bg*4
elif bg in ["flat","gradient","oldshadow","material"]:
self.bg = ContainerButtonBackground(self,borderstyle=bg)
self.on_resize(self.window.width,self.window.height) |
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 used directly for generation of vertex data. This method can also be overridden to limit the background to a specific part of its widget. | 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.
All values should be in pixels and already include all offsets, as they are used directly for generation of vertex data.
This method can also be overridden to limit the background to a specific part of its widget.
"""
sx,sy = self.widget.size
x,y = self.widget.pos
bx,by = self.border
return sx,sy,x,y,bx,by |
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 shadow color it is usually quite a bit darker than the background. h is the highlight color it is usually quite a bit lighter than the background. | 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 the background color.
``i`` is the inner color, it is usually lighter than the background color.
``s`` is the shadow color, it is usually quite a bit darker than the background.
``h`` is the highlight color, it is usually quite a bit lighter than the background.
"""
bg = self.submenu.bg[:3] if isinstance(self.submenu.bg,list) or isinstance(self.submenu.bg,tuple) else [242,241,240]
o,i = bg, [min(bg[0]+8,255),min(bg[1]+8,255),min(bg[2]+8,255)]
s,h = [max(bg[0]-40,0),max(bg[1]-40,0),max(bg[2]-40,0)], [min(bg[0]+12,255),min(bg[1]+12,255),min(bg[2]+12,255)]
# Outer,Inner,Shadow,Highlight
return bg,o,i,s,h |
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. vlist_cross. colors = 6 * c # Convenience variables sx sy = self. widget. size x y = self. widget. pos bx by = self. border v1 = x + bx y + ( sy - by * 2 )/ 2 + by v2 = x + sx/ 2 y + ( sy - by * 2 )/ 4 + by v3 = v6 v4 = x + sx y + sy v5 = x + sx/ 2 y + by v6 = x + bx y + ( sy - by * 2 )/ 4 + by self. vlist_cross. vertices = v2 + v1 + v6 + v5 + v4 + v3 | 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, y
v4 = x+sx, y
# Inner vertices
# x y
v5 = x+bx, y+sy-by
v6 = x+sx-bx, y+sy-by
v7 = x+bx, y+by
v8 = x+sx-bx, y+by
# 5 Quads, for edges and the center
qb1 = v5+v6+v2+v1
qb2 = v8+v4+v2+v6
qb3 = v3+v4+v8+v7
qb4 = v3+v7+v5+v1
qc = v7+v8+v6+v5
v = qb1+qb2+qb3+qb4+qc
self.vlist.vertices = v
bg = self.submenu.bg[:3] if isinstance(self.submenu.bg,list) or isinstance(self.submenu.bg,tuple) else [242,241,240]
o,i = bg, [min(bg[0]+8,255),min(bg[1]+8,255),min(bg[2]+8,255)]
s,h = [max(bg[0]-40,0),max(bg[1]-40,0),max(bg[2]-40,0)], [min(bg[0]+12,255),min(bg[1]+12,255),min(bg[2]+12,255)]
# Outer,Inner,Shadow,Highlight
if self.borderstyle == "flat":
if self.widget.pressed:
i = s
cb1 = i+i+i+i
cb2 = i+i+i+i
cb3 = i+i+i+i
cb4 = i+i+i+i
cc = i+i+i+i
elif self.borderstyle == "gradient":
if self.widget.pressed:
i = s
elif self.widget.is_hovering:
i = [min(i[0]+6,255),min(i[1]+6,255),min(i[2]+6,255)]
cb1 = i+i+o+o
cb2 = i+o+o+i
cb3 = o+o+i+i
cb4 = o+i+i+o
cc = i+i+i+i
elif self.borderstyle == "oldshadow":
if self.widget.pressed:
i = s
s,h = h,s
elif self.widget.is_hovering:
i = [min(i[0]+6,255),min(i[1]+6,255),min(i[2]+6,255)]
s = [min(s[0]+6,255),min(s[1]+6,255),min(s[2]+6,255)]
cb1 = h+h+h+h
cb2 = s+s+s+s
cb3 = s+s+s+s
cb4 = h+h+h+h
cc = i+i+i+i
elif self.borderstyle == "material":
if self.widget.pressed:
i = [max(bg[0]-20,0),max(bg[1]-20,0),max(bg[2]-20,0)]
elif self.widget.is_hovering:
i = [max(bg[0]-10,0),max(bg[1]-10,0),max(bg[2]-10,0)]
cb1 = s+s+o+o
cb2 = s+o+o+s
cb3 = o+o+s+s
cb4 = o+s+s+o
cc = i+i+i+i
else:
raise ValueError("Invalid Border style")
c = cb1+cb2+cb3+cb4+cc
self.vlist.colors = c
# Cross
# Old method that displayed a tick
"""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.vlist_cross.colors = 6*c
# Convenience variables
sx,sy = self.widget.size
x,y = self.widget.pos
bx,by = self.border
v1 = x+bx, y+(sy-by*2)/2+by
v2 = x+sx/2, y+(sy-by*2)/4+by
v3 = v6
v4 = x+sx, y+sy
v5 = x+sx/2, y+by
v6 = x+bx, y+(sy-by*2)/4+by
self.vlist_cross.vertices = v2+v1+v6+v5+v4+v3"""
# TODO: add better visual indicator
v1 = x+bx*1.5, y+sy-by*1.5
v2 = x+sx-bx*1.5, y+sy-by*1.5
v3 = x+bx*1.5, y+by*1.5
v4 = x+sx-bx*1.5, y+by*1.5
self.vlist_check.colors = self.checkcolor*4 if self.widget.pressed else i*4
self.vlist_check.vertices = v3+v4+v2+v1 |
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*.15
self._label._update() |
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 to later change the keybinding without re - registering: param function handler: Function or any other callable called with the positional arguments ( symbol modifiers release ) if the keybind is pressed or released: param int mod: If the keybind should respect modifiers | 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.
:param str keybind: Keybind string, as described above
:param str kbname: Name of the keybind, may be used to later change the keybinding without re-registering
:param function handler: Function or any other callable called with the positional arguments ``(symbol,modifiers,release)`` if the keybind is pressed or released
:param int mod: If the keybind should respect modifiers
"""
keybind = keybind.lower()
if mod:
if keybind not in self.keybinds:
self.keybinds[keybind]=[]
self.keybinds[keybind].append(kbname)
else:
if keybind not in self.keybinds_nm:
self.keybinds_nm[keybind]=[]
self.keybinds_nm[keybind].append(kbname)
self.kbname[kbname]=handler
self.peng.sendEvent("peng3d:keybind.add",{"peng":self.peng,"keybind":keybind,"kbname":kbname,"handler":handler,"mod":mod}) |
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:
del value[value.index(kbname)]
break
if combo not in self.keybinds:
self.keybinds[combo]=[]
self.keybinds[combo].append(kbname)
self.peng.sendEvent("peng3d.keybind.change",{"peng":self.peng,"kbname":kbname,"combo":combo}) |
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. handlers
"""
modifier = MODNAME2MODIFIER[modname.lower()]
return modifiers&modifier |
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: peng3d: keybind. combo \: peng3d: event: peng3d: keybind. combo. press and: peng3d: event peng3d: keybind. combo. release \.: params str combo: Key combination pressed: params int symbol: Key pressed passed from the same argument within pyglet: params int modifiers: Modifiers held while the key was pressed: params bool release: If the combo was released: params bool mod: If the combo was sent without mods | 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 ``(combo,symbol,modifiers,release,mod)`` is sent to the :py:class:`Peng()` instance.
Also sends the events :peng3d:event:`peng3d:keybind.combo`\, :peng3d:event:`peng3d:keybind.combo.press` and :peng3d:event`peng3d:keybind.combo.release`\ .
:params str combo: Key combination pressed
:params int symbol: Key pressed, passed from the same argument within pyglet
:params int modifiers: Modifiers held while the key was pressed
:params bool release: If the combo was released
:params bool mod: If the combo was sent without mods
"""
if self.peng.cfg["controls.keybinds.debug"]:
print("combo: nm=%s %s"%(mod,combo))
if mod:
for kbname in self.keybinds.get(combo,[]):
self.kbname[kbname](symbol,modifiers,release)
else:
for kbname in self.keybinds_nm.get(combo,[]):
self.kbname[kbname](symbol,modifiers,release)
self.peng.sendPygletEvent("on_key_combo",(combo,symbol,modifiers,release,mod))
self.peng.sendEvent("peng3d:keybind.combo",{"peng":self.peng,"combo":combo,"symbol":symbol,"modifiers":modifiers,"release":release,"mod":mod})
if release:
self.peng.sendEvent("peng3d:keybind.combo.release",{"peng":self.peng,"combo":combo,"symbol":symbol,"modifiers":modifiers,"release":release,"mod":mod})
else:
self.peng.sendEvent("peng3d:keybind.combo.press",{"peng":self.peng,"combo":combo,"symbol":symbol,"modifiers":modifiers,"release":release,"mod":mod}) |
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.peng.cfg["controls.controls.forward"],"peng3d:actor.%s.player.controls.forward"%self.actor.uuid,self.on_fwd_down,False)
# Backward
self.peng.keybinds.add(self.peng.cfg["controls.controls.backward"],"peng3d:actor.%s.player.controls.backward"%self.actor.uuid,self.on_bwd_down,False)
# Strafe Left
self.peng.keybinds.add(self.peng.cfg["controls.controls.strafeleft"],"peng3d:actor.%s.player.controls.strafeleft"%self.actor.uuid,self.on_left_down,False)
# Strafe Right
self.peng.keybinds.add(self.peng.cfg["controls.controls.straferight"],"peng3d:actor.%s.player.controls.straferight"%self.actor.uuid,self.on_right_down,False)
pyglet.clock.schedule_interval(self.update,1.0/60) |
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.move))
y_angle = math.radians(y)
x_angle = math.radians(x + strafe)
dy = 0.0
dx = math.cos(x_angle)
dz = math.sin(x_angle)
else:
dy = 0.0
dx = 0.0
dz = 0.0
return (dx, dy, dz) |
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_motion)
self.world.registerEventHandler("on_mouse_drag",self.on_mouse_drag) |
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.crouch"],"peng3d:actor.%s.player.controls.crouch"%self.actor.uuid,self.on_crouch_down,False)
# Jump/fly up
self.peng.keybinds.add(self.peng.cfg["controls.controls.jump"],"peng3d:actor.%s.player.controls.jump"%self.actor.uuid,self.on_jump_down,False)
pyglet.clock.schedule_interval(self.update,1.0/60) |
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:
return
dy = self.speed * dt * self.move
x,y,z = self.actor._pos
newpos = x,dy+y,z
self.actor.pos = newpos |
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 position in space, before accounting for gravity.
dx, dy, dz = dx * d, dy * d, dz * d
#dy+=self.vert*VERT_SPEED
x,y,z = self._pos
newpos = dx+x, dy+y, dz+z
self.pos = newpos |
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 value of the keyword argument. For more complex usage scenarios it is also possible to override this method in a subclass but the original method should always be called to ensure compatibility with classes relying on this feature. | 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 name given in the value of the key will
be called with its only argument being the value of the keyword argument.
For more complex usage scenarios, it is also possible to override this method
in a subclass, but the original method should always be called to ensure
compatibility with classes relying on this feature.
"""
for name,fname in self.WIDGETS.items():
if name in kwargs and kwargs[name] is not None:
assert hasattr(self,fname)
assert callable(getattr(self,fname))
getattr(self,fname)(kwargs[name]) |
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("label_main",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw/2,sh/2-bh/2),
size=[0,0],
label=label_main,
#multiline=True, # TODO: implement multine dialog
)
self.wlabel_main.size = lambda sw,sh: (sw,self.wlabel_main._label.font_size)
self.addWidget(self.wlabel_main) |
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 its height.
"""
# OK Button
self.wbtn_ok = button.Button("btn_ok",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw/2,sh/2-bh/2-bh*2),
size=[0,0],
label=label_ok,
borderstyle=self.borderstyle
)
self.wbtn_ok.size = lambda sw,sh: (self.wbtn_ok._label.font_size*8,self.wbtn_ok._label.font_size*2)
self.addWidget(self.wbtn_ok)
def f():
self.doAction("click_ok")
self.exitDialog()
self.wbtn_ok.addAction("click",f) |
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 dialog opens another
self.menu.changeSubMenu(self.prev_submenu)
self.prev_submenu = None |
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 label and to the left
of the cancel button.
"""
# Confirm Button
self.wbtn_confirm = button.Button("btn_confirm",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw-4,sh/2-bh/2-bh*2),
size=[0,0],
label=label_confirm,
borderstyle=self.borderstyle
)
self.wbtn_confirm.size = lambda sw,sh: (self.wbtn_confirm._label.font_size*8,self.wbtn_confirm._label.font_size*2)
self.addWidget(self.wbtn_confirm)
def f():
self.doAction("confirm")
self.exitDialog()
self.wbtn_confirm.addAction("click",f) |
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 the right
of the confirm button.
"""
# Cancel Button
self.wbtn_cancel = button.Button("btn_cancel",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2+4,sh/2-bh/2-bh*2),
size=[0,0],
label=label_cancel,
borderstyle=self.borderstyle
)
self.wbtn_cancel.size = lambda sw,sh: (self.wbtn_cancel._label.font_size*8,self.wbtn_cancel._label.font_size*2)
self.addWidget(self.wbtn_cancel)
def f():
self.doAction("cancel")
self.exitDialog()
self.wbtn_cancel.addAction("click",f) |
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.wprogressbar.n,self.wprogressbar.nmin,self.wprogressbar.nmax
if (nmax-nmin)==0:
percent = 0 # prevents ZeroDivisionError
else:
percent = max(min((n-nmin)/(nmax-nmin),1.),0.)*100
dat = {"value":round(n,4),"n":round(n,4),"nmin":round(nmin,4),"nmax":round(nmax,4),"percent":round(percent,4),"p":round(percent,4)}
txt = self._label_progressbar.format(**dat)
self.wprogresslabel.label = txt |
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 be a string containing formatting codes which will be resolved via the format () method. Currently there are six keys available: n and value are the current progress rounded to 4 decimal places. nmin is the minimum progress value rounded to 4 decimal places. nmax is the maximum progress value rounded to 4 decimal places. p and percent are the percentage value that the progressbar is completed rounded to 4 decimal places. By default the progressbar label will be { percent } % displaying the percentage the progressbar is complete. | 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 the main label.
The progress label will be displayed within the progressbar.
The label of the progressbar may be a string containing formatting codes
which will be resolved via the ``format()`` method.
Currently, there are six keys available:
``n`` and ``value`` are the current progress rounded to 4 decimal places.
``nmin`` is the minimum progress value rounded to 4 decimal places.
``nmax`` is the maximum progress value rounded to 4 decimal places.
``p`` and ``percent`` are the percentage value that the progressbar is completed
rounded to 4 decimal places.
By default, the progressbar label will be ``{percent}%`` displaying the percentage
the progressbar is complete.
"""
# Progressbar
self.wprogressbar = slider.AdvancedProgressbar("progressbar",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw/2,self.wlabel_main.pos[1]-bh*1.5),
size=[0,0],
#label=label_progressbar # TODO: add label
borderstyle=self.borderstyle
)
self.addWidget(self.wprogressbar)
# Progress Label
self.wprogresslabel = text.Label("progresslabel",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw/2,self.wprogressbar.pos[1]+8),
size=[0,0],
label="", # set by update_progressbar()
)
self.wprogresslabel.size = lambda sw,sh: (sw,self.wprogresslabel._label.font_size)
self.addWidget(self.wprogresslabel)
self.wprogressbar.size = lambda sw,sh: (sw*0.8,self.wprogresslabel._label.font_size+10)
self._label_progressbar = label_progressbar
if getattr(label_progressbar,"_dynamic",False):
def f():
self.label_progressbar = str(label_progressbar)
self.peng.i18n.addAction("setlang",f)
self.wprogressbar.addAction("progresschange",self.update_progressbar)
self.update_progressbar() |
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 multiple windows... todo:: Implement having multiple windows. | 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 other positional or keyword arguments are passed to the class constructor.
Note that this method currently does not support using multiple windows.
.. todo::
Implement having multiple windows.
"""
if cls is None:
from . import window
cls = window.PengWindow
if self.window is not None:
raise RuntimeError("Window already created!")
self.sendEvent("peng3d:window.create.pre",{"peng":self,"cls":cls})
if caption_t is not None:
kwargs["caption"] = "Peng3d Application"
self.window = cls(self,*args,**kwargs)
self.sendEvent("peng3d:window.create.post",{"peng":self,"window":self.window})
if self.cfg["rsrc.enable"] and self.resourceMgr is None:
self.sendEvent("peng3d:rsrc.init.pre",{"peng":self,"basepath":self.cfg["rsrc.basepath"]})
self.resourceMgr = resource.ResourceManager(self,self.cfg["rsrc.basepath"])
self.rsrcMgr = self.resourceMgr
self.sendEvent("peng3d:rsrc.init.post",{"peng":self,"rsrcMgr":self.resourceMgr})
if self.cfg["i18n.enable"] and self.i18n is None:
self.sendEvent("peng3d:i18n.init.pre",{"peng":self})
self.i18n = i18n.TranslationManager(self)
self._t = self.i18n.t
self._tl = self.i18n.tl
self.sendEvent("peng3d:i18n.init.post",{"peng":self,"i18n":self.i18n})
if caption_t is not None:
self.window.set_caption(self.t(caption_t))
def f():
self.window.set_caption(self.t(caption_t))
self.i18n.addAction("setlang",f)
return self.window |
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 default event loop.
"""
self.sendEvent("peng3d:peng.run",{"peng":self,"window":self.window,"evloop":evloop})
self.window.run(evloop)
self.sendEvent("peng3d:peng.exit",{"peng":self}) |
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 tunneling pyglet events use event names of the format pyglet: <event > and for the data use { args: <args as list > window: <window object or none > src: <event source > event_type: <event type > } Note that you should send pyglet events only via this method the above event will be sent automatically. Do not use this method to send custom events use: py: meth: sendEvent instead. | 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 method should be used to send pyglet events.
For new code, it is recommended to use :py:meth:`sendEvent()` instead.
For "tunneling" pyglet events, use event names of the format ``pyglet:<event>``
and for the data use ``{"args":<args as list>,"window":<window object or none>,"src":<event source>,"event_type":<event type>}``
Note that you should send pyglet events only via this method, the above event will be sent automatically.
Do not use this method to send custom events, use :py:meth:`sendEvent` instead.
"""
args = list(args)
self.sendEvent("pyglet:%s"%event_type,{"peng":self,"args":args,"window":window,"src":self,"event_type":event_type})
self.sendEvent("peng3d:pyglet",{"peng":self,"args":args,"window":window,"src":self,"event_type":event_type})
if event_type not in ["on_draw","on_mouse_motion"] and self.cfg["debug.events.dump"]:
print("Event %s with args %s"%(event_type,args))
if event_type in self.pygletEventHandlers:
for whandler in self.pygletEventHandlers[event_type]:
# This allows for proper collection of deleted handler methods by using weak references
handler = whandler()
if handler is None:
del self.pygletEventHandlers[event_type][self.pygletEventHandlers[event_type].index(whandler)]
handler(*args) |
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 () instead. See: py: meth: handleEvent () for information about tunneled pyglet events. For custom events use: py: meth: addEventListener () instead. | 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 method should be used to listen for pyglet events.
For new code, it is recommended to use :py:meth:`addEventListener()` instead.
See :py:meth:`handleEvent()` for information about tunneled pyglet events.
For custom events, use :py:meth:`addEventListener()` instead.
"""
if self.cfg["debug.events.register"]:
print("Registered Event: %s Handler: %s"%(event_type,handler))
if event_type not in self.pygletEventHandlers:
self.pygletEventHandlers[event_type]=[]
# Only a weak reference is kept
if inspect.ismethod(handler):
handler = weakref.WeakMethod(handler)
else:
handler = weakref.ref(handler)
self.pygletEventHandlers[event_type].append(handler) |
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 dictionary containing relevant parameters. For example most built - in events use a dictionary containing at least the peng key set to an instance of this class. If there are no handlers for the event a corresponding message will be printed to the log file. To prevent spam the maximum amount of ignored messages can be configured via: confval: events. maxignore and defaults to 3. If the config value: confval: debug. events. dumpfile is a file path the event type will be added to an internal list and be saved to the given file during program exit. | 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, but rather recommended by convention.
``data`` may be any Python Object, but it usually is a dictionary containing relevant parameters.
For example, most built-in events use a dictionary containing at least the ``peng`` key set to an instance of this class.
If there are no handlers for the event, a corresponding message will be printed to the log file.
To prevent spam, the maximum amount of ignored messages can be configured via :confval:`events.maxignore` and defaults to 3.
If the config value :confval:`debug.events.dumpfile` is a file path, the event type will be added to an internal list and be saved to the given file during program exit.
"""
if self.cfg["debug.events.dumpfile"]!="" and event not in self.event_list:
self.event_list.add(event)
if event not in self.eventHandlers:
if event not in self.events_ignored or self.events_ignored[event]<=self.cfg["events.maxignore"]: # Prevents spamming logfile with ignored event messages
# TODO: write to logfile
# Needs a logging module first...
self.events_ignored[event] = self.events_ignored.get(event,0)+1
return
for handler in self.eventHandlers[event]:
f = handler[0]
try:
f(event,data)
except Exception:
if not handler[1]:
raise
else:
# TODO: write to logfile
if self.cfg["events.removeonerror"]:
self.delEventListener(event,f) |
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: sendEvent () \. If raiseErrors is True exceptions caused by the handler will be re - raised. Defaults to False \. | 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:`sendEvent()`\ .
``func`` is the handler which will be executed with two arguments, ``event_type`` and ``data``\ , as supplied to :py:meth:`sendEvent()`\ .
If ``raiseErrors`` is True, exceptions caused by the handler will be re-raised.
Defaults to ``False``\ .
"""
if not isinstance(event,str):
raise TypeError("Event types must always be strings")
if event not in self.eventHandlers:
self.eventHandlers[event]=[]
self.eventHandlers[event].append([func,raiseErrors]) |
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 event not in self.eventHandlers:
raise NameError("No handlers exist for event %s"%event)
if [func,True] in self.eventHandlers[event]:
del self.eventHandlers[event][self.eventHandlers[event].index(func)]
elif [func,False] in self.eventHandler[event]:
del self.eventHandlers[event][self.eventHandlers[event].index(func)]
else:
raise NameError("This handler is not registered for event %s"%event)
if self.eventHandlers[event] == []:
del self.eventHandlers[event] |
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 or plausibility. This may cause the fallback strings to be displayed instead if the language does not exist. Calling this method will cause the setlang action and the: peng3d: event peng3d: i18n. set_lang event to be triggered. Note that both action and event will be triggered even if the language did not actually change. This method also automatically updates the: confval: i18n. lang config value. | 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:`translate_lazy()` will override this setting.
Also note that the code won't be checked for existence or plausibility.
This may cause the fallback strings to be displayed instead if the language
does not exist.
Calling this method will cause the ``setlang`` action and the
:peng3d:event`peng3d:i18n.set_lang` event to be triggered. Note that both
action and event will be triggered even if the language did not actually change.
This method also automatically updates the :confval:`i18n.lang` config value.
"""
self.lang = lang
self.peng.cfg["i18n.lang"] = lang
if lang not in self.cache:
self.cache[lang]={}
self.doAction("setlang")
self.peng.sendEvent("peng3d:i18n.set_lang",{"lang":self.lang,"i18n":self}) |
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 then applies the regex in: confval: i18n. discover_regex to extract the language code. | 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` built-in module and the
:confval:`i18n.lang.format` config option to find suitable filenames.
It then applies the regex in :confval:`i18n.discover_regex` to extract the
language code.
"""
rsrc = self.peng.cfg["i18n.lang.format"].format(domain=domain,lang="*")
pattern = self.peng.rsrcMgr.resourceNameToPath(rsrc,self.peng.cfg["i18n.lang.ext"])
files = glob.iglob(pattern)
langs = set()
r = re.compile(self.peng.cfg["i18n.discover_regex"])
for f in files:
m = r.fullmatch(f)
if m is not None:
langs.add(m.group("lang"))
return list(langs) |
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: py: exc: TypeError \. | 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:class:`Camera() <peng3d.camera.Camera>` may be used, everything else raises a :py:exc:`TypeError`\ .
"""
if not isinstance(camera,Camera):
raise TypeError("camera is not of type Camera!")
self.cameras[camera.name]=camera |
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:exc:`TypeError`\ .
"""
if not isinstance(view,WorldView):
raise TypeError("view is not of type WorldView!")
self.views[view.name]=view |
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():
actor.render(view) |
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 already active
if name not in self.world.cameras:
raise ValueError("Unknown camera name")
old = self.activeCamera
self.activeCamera = name
self.cam.on_activate(old) |
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.