Skip to content

Commit

Permalink
Merge pull request #107 from labuzm/timers
Browse files Browse the repository at this point in the history
revamped timers
  • Loading branch information
maniek2332 committed Jan 2, 2021
2 parents 163faa6 + 2913aec commit 1f4b56f
Show file tree
Hide file tree
Showing 20 changed files with 223 additions and 165 deletions.
16 changes: 8 additions & 8 deletions demos/physics3/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(self, position):
scale=Vector(0.2, 0.2) + Vector.xy(
math.fabs(random.gauss(0.0, 1.0)),
),
lifetime=60000., # 60 seconds
lifetime=60.,
)

self.hitbox = self.add_child(HitboxNode(
Expand Down Expand Up @@ -76,18 +76,18 @@ def __init__(self):
z_index=10,
))

self.spawn_timer = Timer(self._spawn_heartbeat, 20,
single_shot=False)
self.spawn_timer.start()
self.spawn_timer = Timer(self._spawn_heartbeat)
self.spawn_timer.start(0.02, self)

def _spawn_heartbeat(self):
def _spawn_heartbeat(self, context):
if random.random() > 0.8:
initial_position = Vector(
random.uniform(0, 300), -20.
)
self.space.add_child(
FallingPiece(initial_position)
)
return context.interval

def _perform_shape_query(self):
results = self.space.query_shape_overlaps(
Expand All @@ -103,7 +103,7 @@ def _perform_shape_query(self):
position=cp.point_b,
shape=Circle(0.5),
color=Color(1., 0., 0., 1.),
lifetime=200,
lifetime=0.2,
z_index=3,
))

Expand All @@ -117,7 +117,7 @@ def _perform_point_query(self):
position=r.point,
shape=Circle(0.5),
color=Color(1., 1., 0., 1.),
lifetime=200,
lifetime=0.2,
z_index=3,
))

Expand All @@ -130,7 +130,7 @@ def _perform_ray_query(self, point_a, point_b):
position=r.point,
shape=Circle(0.5),
color=Color(1., 0., 1., 1.),
lifetime=200,
lifetime=0.2,
z_index=3,
))

Expand Down
6 changes: 6 additions & 0 deletions demos/physics4/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ def update(self, dt):
if event.keyboard_key.key_down == Keycode.q:
self.engine.quit()

if event.keyboard_key.key_down == Keycode.t:
if self.time_scale < 1:
self.time_scale = 1
else:
self.time_scale = 0.3

for node in self.nodes:
distance_vector = self.attractor.position - node.position
distance = distance_vector.length()
Expand Down
25 changes: 15 additions & 10 deletions demos/timers/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import os
import math
import time
import random

from kaa.timers import Timer
Expand All @@ -15,8 +17,8 @@ class TtlNode(BodyNode):

def __init__(self, **kwargs):
ttl = kwargs.pop('ttl')
self.ttl_timer = Timer(self.delete, ttl)
self.ttl_timer.start()
self.ttl_timer = Timer(lambda c: self.delete())
self.ttl_timer.start_global(ttl)
super().__init__(**kwargs)


Expand All @@ -28,23 +30,26 @@ def __init__(self):
SpaceNode(position=Vector(0, 0))
)
self.python_image = Sprite(PYTHON_IMAGE_PATH)
self.timer = Timer(self.spawn, 200, single_shot=False)
self.timer.start()
self.timer = Timer(self.spawn)
self.timer.start(0.2, self)
self.spawn()

def spawn(self):
angles = list(range(0, 360, 10))
def spawn(self, context=None):
start = int(math.degrees(math.sin(time.time())))
angles = list(range(start, start + 360, 20))
for angle in angles:
self.space.add_child(
TtlNode(
mass=1e10,
sprite=self.python_image,
angular_velocity=1,
ttl=random.randrange(3000, 6000),
angular_velocity=2,
ttl=random.uniform(2, 6),
shape=Polygon.from_box(Vector(20, 20)),
velocity=Vector.from_angle_degrees(angle) * 50
velocity=Vector.from_angle_degrees(angle) * 60
)
)
if context:
return context.interval

def update(self, dt):
for event in self.input.events():
Expand All @@ -55,7 +60,7 @@ def update(self, dt):
if self.timer.is_running:
self.timer.stop()
else:
self.timer.start()
self.timer.start(0.2, self)


if __name__ == '__main__':
Expand Down
18 changes: 9 additions & 9 deletions demos/transitions/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,23 @@ def __init__(self):
self.python_img = Sprite(PYTHON_IMAGE_PATH)

self.transition = NodeTransitionsSequence([
NodePositionTransition(Vector(-100., -100.), 3000.,
NodePositionTransition(Vector(-100., -100.), 3.,
advance_method=AttributeTransitionMethod.add,
loops=3,
easing=Easing.elastic_in_out),
NodePositionTransition(Vector(100., 0.), 3000.,
NodePositionTransition(Vector(100., 0.), 3.,
advance_method=AttributeTransitionMethod.add,
easing=Easing.back_in_out),
NodeTransitionDelay(1500.),
NodeTransitionDelay(1.5),
NodeTransitionCallback(
lambda node: setattr(node, 'sprite', None)
),
NodeTransitionsParallel([
NodePositionTransition(Vector(-50., 100.), 3000.,
NodePositionTransition(Vector(-50., 100.), 3.,
advance_method=AttributeTransitionMethod.add),
NodeRotationTransition(1., 5000.),
NodeScaleTransition(Vector(2., 2.), 3000.),
NodeColorTransition(Color(0., 1., 0., 0.5), 4000.),
NodeRotationTransition(1., 5.),
NodeScaleTransition(Vector(2., 2.), 3.),
NodeColorTransition(Color(0., 1., 0., 0.5), 4.),
], back_and_forth=True),
])

Expand All @@ -64,7 +64,7 @@ def __init__(self):
Sprite(EXPLOSION_IMAGE_PATH), Vector(64, 64),
)
self.sprite_transition = NodeSpriteTransition(
spritesheet_frames, 1000., loops=0, back_and_forth=True,
spritesheet_frames, 1., loops=0, back_and_forth=True,
easing=Easing.quartic_out,
)

Expand Down Expand Up @@ -94,7 +94,7 @@ def __init__(self):
position=Vector(-50., 50.),
sprite=self.python_img,
velocity=Vector(0., 30.),
transition=BodyNodeVelocityTransition(Vector(0., -30.), 10000.),
transition=BodyNodeVelocityTransition(Vector(0., -30.), 10.),
)
)

Expand Down
6 changes: 3 additions & 3 deletions demos/transitions2/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ def __init__(self):
self.obj.transitions_manager.set(
'movement',
NodeTransition(
Node.position, Vector(100, 30), 3000.,
Node.position, Vector(100, 30), 3.,
advance_method=AttributeTransitionMethod.add,
loops=0, back_and_forth=True,
)
)

def _randomize_color_transition(self):
return NodeTransition(
Node.color, random_color(), 2000.,
Node.color, random_color(), 2.,
loops=0, back_and_forth=True,
)

Expand All @@ -60,7 +60,7 @@ def update(self, dt):
self.obj.transitions_manager.set(
'pseudo_timer',
NodeTransitionsSequence([
NodeTransitionDelay(1000.),
NodeTransitionDelay(1.),
NodeTransitionCallback(
lambda node: node.transitions_manager.set(
'color', self._randomize_color_transition(),
Expand Down
1 change: 1 addition & 0 deletions src/kaa/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ set(CYTHON_FILES
kaacore/hashing.pxd
kaacore/easings.pxd
kaacore/spatial_index.pxd
kaacore/clock.pxd

extra/include/pythonic_callback.h
extra/include/python_exceptions_wrapper.h
Expand Down
4 changes: 2 additions & 2 deletions src/kaa/custom_transitions.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ cdef cppclass CPyNodeCustomTransition(CNodeTransitionCustomizable):
const CEasing easing):
this.prepare_func = prepare_func
this.evaluate_func = evaluate_func
this.duration = duration * warping.duration_factor()
this.internal_duration = duration
this.duration = CDuration(duration * warping.duration_factor())
this.internal_duration = CDuration(duration)
this.warping = warping
this._easing = easing

Expand Down
53 changes: 25 additions & 28 deletions src/kaa/engine.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -47,28 +47,6 @@ cdef class _Engine:
def current_scene(self):
return (<CPyScene*>get_c_engine().current_scene()).get_py_scene()

def change_scene(self, Scene scene not None):
get_c_engine().change_scene(scene._c_scene.get())

def run(self, Scene scene not None):
cdef:
CScene* c_scene = scene._c_scene.get()
CEngine* c_engine = get_c_engine()
with nogil:
c_engine.run(c_scene)

def quit(self):
get_c_engine().quit()

def get_displays(self):
cdef vector[CDisplay] c_displays = get_c_engine().get_displays()
cdef CDisplay c_disp
displays_list = []

for c_disp in c_displays:
displays_list.append(Display._wrap_c_display(c_disp))
return displays_list

@property
def virtual_resolution(self):
cdef CUVec2 c_virtual_resolution = get_c_engine().virtual_resolution()
Expand All @@ -87,12 +65,6 @@ cdef class _Engine:
<uint32_t>get_c_engine().virtual_resolution_mode()
)

@property
def virtual_resolution_mode(self):
return VirtualResolutionMode(
<uint32_t>get_c_engine().virtual_resolution_mode()
)

@virtual_resolution_mode.setter
def virtual_resolution_mode(self, new_mode):
get_c_engine().virtual_resolution_mode(
Expand All @@ -107,6 +79,31 @@ cdef class _Engine:
def audio(self):
return self._audio_manager

def get_fps(self):
return get_c_engine().get_fps()

def change_scene(self, Scene scene not None):
get_c_engine().change_scene(scene._c_scene.get())

def run(self, Scene scene not None):
cdef:
CScene* c_scene = scene._c_scene.get()
CEngine* c_engine = get_c_engine()
with nogil:
c_engine.run(c_scene)

def quit(self):
get_c_engine().quit()

def get_displays(self):
cdef vector[CDisplay] c_displays = get_c_engine().get_displays()
cdef CDisplay c_disp
displays_list = []

for c_disp in c_displays:
displays_list.append(Display._wrap_c_display(c_disp))
return displays_list

def stop(self):
if not is_c_engine_initialized():
raise ValueError('Engine is already stopped.')
Expand Down
9 changes: 4 additions & 5 deletions src/kaa/extra/include/pythonic_callback.h
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,6 @@ class PythonicCallbackResult {
typedef PythonicCallbackResult<int> (*CythonCollisionHandler)(const PythonicCallbackWrapper&, Arbiter,
CollisionPair, CollisionPair);


CollisionHandlerFunc bind_cython_collision_handler(
const CythonCollisionHandler cy_handler, PythonicCallbackWrapper callback
)
Expand All @@ -168,14 +167,14 @@ CollisionHandlerFunc bind_cython_collision_handler(
}


typedef PythonicCallbackResult<void> (*CythonTimerCallback)(const PythonicCallbackWrapper&);
typedef PythonicCallbackResult<Duration> (*CythonTimerCallback)(const PythonicCallbackWrapper&, TimerContext);

TimerCallback bind_cython_timer_callback(
const CythonTimerCallback cy_handler, PythonicCallbackWrapper callback
const CythonTimerCallback cy_handler, const PythonicCallbackWrapper callback
)
{
return [cy_handler, callback{std::move(callback)}]() {
std::move(cy_handler(callback)).unwrap_result();
return [cy_handler, callback{std::move(callback)}](TimerContext context) -> Duration {
return cy_handler(callback, context).unwrap_result();
};
}

Expand Down
10 changes: 10 additions & 0 deletions src/kaa/kaacore/clock.pxd
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
cdef extern from "<chrono>" namespace "std::chrono" nogil:
cdef cppclass duration[Repr, Period=*]:
duration()
duration(Repr) except +

Repr count()


cdef extern from "kaacore/clock.h" nogil:
ctypedef duration[long double] CDuration "kaacore::Duration"
9 changes: 5 additions & 4 deletions src/kaa/kaacore/custom_transitions.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ from libcpp.memory cimport unique_ptr
from libcpp.functional cimport function

from .nodes cimport CNodePtr
from .clock cimport CDuration
from .transitions cimport CTransitionStateBase, CTransitionWarping
from .easings cimport CEasing
from .glue cimport CPythonicCallbackWrapper, CPythonicCallbackResult
Expand All @@ -10,20 +11,20 @@ from .exceptions cimport raise_py_error

cdef extern from "kaacore/transitions.h":
cdef cppclass CNodeTransitionCustomizable "kaacore::NodeTransitionCustomizable":
double duration
double internal_duration
CDuration duration
CDuration internal_duration
CTransitionWarping warping
CEasing _easing

CNodeTransitionCustomizable() \
except +raise_py_error
CNodeTransitionCustomizable(const double duration, const CTransitionWarping& warping) \
CNodeTransitionCustomizable(const CDuration duration, const CTransitionWarping& warping) \
except +raise_py_error

unique_ptr[CTransitionStateBase] prepare_state(CNodePtr node) nogil const
void evaluate(CTransitionStateBase* state, CNodePtr node, const double t) nogil const

ctypedef function[void(CNodePtr)] CNodeTransitionCallbackFunc "kaacore::NodeTransitionCallbackFunc";
ctypedef function[void(CNodePtr)] CNodeTransitionCallbackFunc "kaacore::NodeTransitionCallbackFunc"


cdef extern from "extra/include/pythonic_callback.h":
Expand Down

0 comments on commit 1f4b56f

Please sign in to comment.