threadingGameLoop.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at
  2. # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import pypdevs.accurate_time as time
  16. from threading import Lock
  17. _GLLOCK = Lock()
  18. class ThreadingGameLoop(object):
  19. """
  20. Game loop subsystem for realtime simulation. Time will only progress when a *step* call is made.
  21. """
  22. def __init__(self):
  23. """
  24. Constructor
  25. """
  26. self.next_event = float('inf')
  27. def step(self):
  28. """
  29. Perform a step in the simulation. Actual processing is done in a seperate thread.
  30. """
  31. with _GLLOCK: # Thread-safety
  32. if time.time() >= self.next_event:
  33. self.next_event = float('inf')
  34. getattr(self, "func")()
  35. def wait(self, delay, func):
  36. """
  37. Wait for the specified time, or faster if interrupted
  38. :param time: time to wait
  39. :param func: the function to call
  40. """
  41. self.func = func
  42. self.next_event = time.time() + delay
  43. def interrupt(self):
  44. """
  45. Interrupt the waiting thread
  46. """
  47. self.next_event = 0