actor.py 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # coding: utf-8
  2. import io
  3. import os
  4. import typing
  5. import ntpath
  6. import pyglet
  7. from PIL import Image
  8. import cocos
  9. from cocos import collision_model
  10. from cocos import euclid
  11. from synergine2.config import Config
  12. from synergine2.simulation import Subject
  13. from synergine2_cocos2d.animation import AnimatedInterface
  14. from synergine2_cocos2d.util import PathManager
  15. class Actor(AnimatedInterface, cocos.sprite.Sprite):
  16. animation_image_paths = {} # type: typing.Dict[str, typing.List[str]]
  17. def __init__(
  18. self,
  19. image_path: str,
  20. subject: Subject,
  21. position=(0, 0),
  22. rotation=0,
  23. scale=1,
  24. opacity=255,
  25. color=(255, 255, 255),
  26. anchor=None,
  27. properties: dict=None,
  28. config: Config=None,
  29. **kwargs
  30. ):
  31. # Note: Parameter required, but we want to modify little as possible parent init
  32. assert config, "Config is a required parameter"
  33. self.config = config
  34. self.path_manager = PathManager(config.resolve('global.include_path.graphics'))
  35. default_image_path = self.build_default_image(
  36. subject.id,
  37. self.path_manager.path(image_path),
  38. )
  39. image = pyglet.image.load(os.path.abspath(default_image_path))
  40. self.animation_images = {} # type: typing.Dict[str, typing.List[pyglet.image.TextureRegion]] # nopep8
  41. super().__init__(
  42. image,
  43. position,
  44. rotation,
  45. scale,
  46. opacity,
  47. color,
  48. anchor,
  49. **kwargs
  50. )
  51. self.subject = subject
  52. self.cshape = None # type: collision_model.AARectShape
  53. self.update_cshape()
  54. self.build_animation_images(subject.id)
  55. self.current_image = image
  56. self.need_update_cshape = False
  57. self.properties = properties or {}
  58. self._freeze = False
  59. def build_default_image(self, subject_id: int, base_image_path: str) -> str:
  60. cache_dir = self.config.resolve('global.cache_dir_path')
  61. with open(base_image_path, 'rb') as base_image_file:
  62. base_image = Image.open(base_image_file)
  63. for default_appliable_image in self.get_default_appliable_images():
  64. base_image.paste(
  65. default_appliable_image,
  66. (0, 0),
  67. default_appliable_image,
  68. )
  69. # FIXME NOW: nom des image utilise au dessus
  70. final_name = '_'.join([
  71. str(subject_id),
  72. ntpath.basename(base_image_path),
  73. ])
  74. final_path = os.path.join(cache_dir, final_name)
  75. base_image.save(final_path)
  76. return final_path
  77. def get_default_appliable_images(self) -> typing.List[Image.Image]:
  78. return []
  79. def get_animation_appliable_images(
  80. self,
  81. animation_name: str,
  82. animation_position: int,
  83. ) -> typing.List[Image.Image]:
  84. return []
  85. def freeze(self) -> None:
  86. """
  87. Set object to freeze mode: No visual modification can be done anymore
  88. """
  89. self._freeze = True
  90. def stop_actions(self, action_types: typing.Tuple[typing.Type[cocos.actions.Action], ...]) -> None:
  91. for action in self.actions:
  92. if isinstance(action, action_types):
  93. self.remove_action(action)
  94. def update_cshape(self) -> None:
  95. self.cshape = collision_model.AARectShape(
  96. euclid.Vector2(self.position[0], self.position[1]),
  97. self.width // 2,
  98. self.height // 2,
  99. )
  100. self.need_update_cshape = False
  101. def update_position(self, new_position: euclid.Vector2) -> None:
  102. if self._freeze:
  103. return
  104. self.position = new_position
  105. self.cshape.center = new_position # Note: if remove: strange behaviour: drag change actor position with anomaly
  106. def build_animation_images(self, subject_id: int) -> None:
  107. """
  108. Fill self.animation_images with self.animation_image_paths
  109. :return: None
  110. """
  111. cache_dir = self.config.resolve('global.cache_dir_path')
  112. for animation_name, animation_image_paths in self.animation_image_paths.items():
  113. self.animation_images[animation_name] = []
  114. for i, animation_image_path in enumerate(animation_image_paths):
  115. final_image_path = self.path_manager.path(animation_image_path)
  116. final_image = Image.open(final_image_path)
  117. for appliable_image in self.get_animation_appliable_images(
  118. animation_name,
  119. i,
  120. ):
  121. final_image.paste(
  122. appliable_image,
  123. (0, 0),
  124. appliable_image,
  125. )
  126. # FIXME NOW: nom des image utilise au dessus
  127. final_name = '_'.join([
  128. str(subject_id),
  129. ntpath.basename(final_image_path),
  130. ])
  131. final_path = os.path.join(cache_dir, final_name)
  132. final_image.save(final_path)
  133. self.animation_images[animation_name].append(
  134. pyglet.image.load(
  135. final_path,
  136. )
  137. )
  138. def get_images_for_animation(self, animation_name: str) -> typing.List[pyglet.image.TextureRegion]:
  139. return self.animation_images.get(animation_name)
  140. def get_inanimate_image(self) -> pyglet.image.TextureRegion:
  141. return self.current_image
  142. def update_image(self, new_image: pyglet.image.TextureRegion):
  143. if self._freeze:
  144. return
  145. self.image = new_image
  146. self.image_anchor = new_image.width // 2, new_image.height // 2