actor.py 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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()
  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. final_name = '_'.join([
  70. str(subject_id),
  71. ntpath.basename(base_image_path),
  72. ])
  73. final_path = os.path.join(cache_dir, final_name)
  74. base_image.save(final_path)
  75. return final_path
  76. def get_default_appliable_images(self) -> typing.List[Image.Image]:
  77. return []
  78. def freeze(self) -> None:
  79. """
  80. Set object to freeze mode: No visual modification can be done anymore
  81. """
  82. self._freeze = True
  83. def stop_actions(self, action_types: typing.Tuple[typing.Type[cocos.actions.Action], ...]) -> None:
  84. for action in self.actions:
  85. if isinstance(action, action_types):
  86. self.remove_action(action)
  87. def update_cshape(self) -> None:
  88. self.cshape = collision_model.AARectShape(
  89. euclid.Vector2(self.position[0], self.position[1]),
  90. self.width // 2,
  91. self.height // 2,
  92. )
  93. self.need_update_cshape = False
  94. def update_position(self, new_position: euclid.Vector2) -> None:
  95. if self._freeze:
  96. return
  97. self.position = new_position
  98. self.cshape.center = new_position # Note: if remove: strange behaviour: drag change actor position with anomaly
  99. def build_animation_images(self) -> None:
  100. """
  101. Fill self.animation_images with self.animation_image_paths
  102. :return: None
  103. """
  104. for animation_name, animation_image_paths in self.animation_image_paths.items():
  105. self.animation_images[animation_name] = []
  106. for animation_image_path in animation_image_paths:
  107. final_image_path = self.path_manager.path(animation_image_path)
  108. self.animation_images[animation_name].append(
  109. pyglet.resource.image(
  110. final_image_path,
  111. )
  112. )
  113. def get_images_for_animation(self, animation_name: str) -> typing.List[pyglet.image.TextureRegion]:
  114. return self.animation_images.get(animation_name)
  115. def get_inanimate_image(self) -> pyglet.image.TextureRegion:
  116. return self.current_image
  117. def update_image(self, new_image: pyglet.image.TextureRegion):
  118. if self._freeze:
  119. return
  120. self.image = new_image
  121. self.image_anchor = new_image.width // 2, new_image.height // 2