scene.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import os
  2. from .. import constants, logger
  3. from . import (
  4. base_classes,
  5. texture,
  6. material,
  7. geometry,
  8. object as object_,
  9. utilities,
  10. io,
  11. api
  12. )
  13. class Scene(base_classes.BaseScene):
  14. """Class that handles the contruction of a Three scene"""
  15. def __init__(self, filepath, options=None):
  16. logger.debug("Scene().__init__(%s, %s)", filepath, options)
  17. self._defaults = {
  18. constants.METADATA: constants.DEFAULT_METADATA.copy(),
  19. constants.GEOMETRIES: [],
  20. constants.MATERIALS: [],
  21. constants.IMAGES: [],
  22. constants.TEXTURES: []
  23. }
  24. base_classes.BaseScene.__init__(self, filepath, options or {})
  25. source_file = api.scene_name()
  26. if source_file:
  27. self[constants.METADATA][constants.SOURCE_FILE] = source_file
  28. @property
  29. def valid_types(self):
  30. """
  31. :return: list of valid node types
  32. """
  33. valid_types = [api.constants.MESH]
  34. if self.options.get(constants.HIERARCHY, False):
  35. valid_types.append(api.constants.EMPTY)
  36. if self.options.get(constants.CAMERAS):
  37. logger.info("Adding cameras to valid object types")
  38. valid_types.append(api.constants.CAMERA)
  39. if self.options.get(constants.LIGHTS):
  40. logger.info("Adding lights to valid object types")
  41. valid_types.append(api.constants.LAMP)
  42. return valid_types
  43. def geometry(self, value):
  44. """Find a geometry node that matches either a name
  45. or uuid value.
  46. :param value: name or uuid
  47. :type value: str
  48. """
  49. logger.debug("Scene().geometry(%s)", value)
  50. return _find_node(value, self[constants.GEOMETRIES])
  51. def image(self, value):
  52. """Find a image node that matches either a name
  53. or uuid value.
  54. :param value: name or uuid
  55. :type value: str
  56. """
  57. logger.debug("Scene().image%s)", value)
  58. return _find_node(value, self[constants.IMAGES])
  59. def material(self, value):
  60. """Find a material node that matches either a name
  61. or uuid value.
  62. :param value: name or uuid
  63. :type value: str
  64. """
  65. logger.debug("Scene().material(%s)", value)
  66. return _find_node(value, self[constants.MATERIALS])
  67. def parse(self):
  68. """Execute the parsing of the scene"""
  69. logger.debug("Scene().parse()")
  70. if self.options.get(constants.MAPS):
  71. self._parse_textures()
  72. if self.options.get(constants.MATERIALS):
  73. self._parse_materials()
  74. self._parse_geometries()
  75. self._parse_objects()
  76. def texture(self, value):
  77. """Find a texture node that matches either a name
  78. or uuid value.
  79. :param value: name or uuid
  80. :type value: str
  81. """
  82. logger.debug("Scene().texture(%s)", value)
  83. return _find_node(value, self[constants.TEXTURES])
  84. def write(self):
  85. """Write the parsed scene to disk."""
  86. logger.debug("Scene().write()")
  87. data = {}
  88. embed_anim = self.options.get(constants.EMBED_ANIMATION, True)
  89. embed = self.options.get(constants.EMBED_GEOMETRY, True)
  90. compression = self.options.get(constants.COMPRESSION)
  91. extension = constants.EXTENSIONS.get(
  92. compression,
  93. constants.EXTENSIONS[constants.JSON])
  94. export_dir = os.path.dirname(self.filepath)
  95. for key, value in self.items():
  96. if key == constants.GEOMETRIES:
  97. geometries = []
  98. for geom in value:
  99. if not embed_anim:
  100. geom.write_animation(export_dir)
  101. geom_data = geom.copy()
  102. if embed:
  103. geometries.append(geom_data)
  104. continue
  105. geo_type = geom_data[constants.TYPE].lower()
  106. if geo_type == constants.GEOMETRY.lower():
  107. geom_data.pop(constants.DATA)
  108. elif geo_type == constants.BUFFER_GEOMETRY.lower():
  109. geom_data.pop(constants.ATTRIBUTES)
  110. geom_data.pop(constants.METADATA)
  111. url = 'geometry.%s%s' % (geom.node, extension)
  112. geometry_file = os.path.join(export_dir, url)
  113. geom.write(filepath=geometry_file)
  114. geom_data[constants.URL] = os.path.basename(url)
  115. geometries.append(geom_data)
  116. data[key] = geometries
  117. elif isinstance(value, list):
  118. data[key] = []
  119. for each in value:
  120. data[key].append(each.copy())
  121. elif isinstance(value, dict):
  122. data[key] = value.copy()
  123. io.dump(self.filepath, data, options=self.options)
  124. if self.options.get(constants.COPY_TEXTURES):
  125. texture_folder = self.options.get(constants.TEXTURE_FOLDER)
  126. for geo in self[constants.GEOMETRIES]:
  127. logger.info("Copying textures from %s", geo.node)
  128. geo.copy_textures(texture_folder)
  129. def _parse_geometries(self):
  130. """Locate all geometry nodes and parse them"""
  131. logger.debug("Scene()._parse_geometries()")
  132. # this is an important step. please refer to the doc string
  133. # on the function for more information
  134. api.object.prep_meshes(self.options)
  135. geometries = []
  136. # now iterate over all the extracted mesh nodes and parse each one
  137. for mesh in api.object.extracted_meshes():
  138. logger.info("Parsing geometry %s", mesh)
  139. geo = geometry.Geometry(mesh, self)
  140. geo.parse()
  141. geometries.append(geo)
  142. logger.info("Added %d geometry nodes", len(geometries))
  143. self[constants.GEOMETRIES] = geometries
  144. def _parse_materials(self):
  145. """Locate all non-orphaned materials and parse them"""
  146. logger.debug("Scene()._parse_materials()")
  147. materials = []
  148. for material_name in api.material.used_materials():
  149. logger.info("Parsing material %s", material_name)
  150. materials.append(material.Material(material_name, parent=self))
  151. logger.info("Added %d material nodes", len(materials))
  152. self[constants.MATERIALS] = materials
  153. def _parse_objects(self):
  154. """Locate all valid objects in the scene and parse them"""
  155. logger.debug("Scene()._parse_objects()")
  156. try:
  157. scene_name = self[constants.METADATA][constants.SOURCE_FILE]
  158. except KeyError:
  159. scene_name = constants.SCENE
  160. self[constants.OBJECT] = object_.Object(None, parent=self)
  161. self[constants.OBJECT][constants.TYPE] = constants.SCENE.title()
  162. self[constants.UUID] = utilities.id_from_name(scene_name)
  163. objects = []
  164. if self.options.get(constants.HIERARCHY, False):
  165. nodes = api.object.assemblies(self.valid_types, self.options)
  166. else:
  167. nodes = api.object.nodes(self.valid_types, self.options)
  168. for node in nodes:
  169. logger.info("Parsing object %s", node)
  170. obj = object_.Object(node, parent=self[constants.OBJECT])
  171. objects.append(obj)
  172. logger.info("Added %d object nodes", len(objects))
  173. self[constants.OBJECT][constants.CHILDREN] = objects
  174. def _parse_textures(self):
  175. """Locate all non-orphaned textures and parse them"""
  176. logger.debug("Scene()._parse_textures()")
  177. textures = []
  178. for texture_name in api.texture.textures():
  179. logger.info("Parsing texture %s", texture_name)
  180. tex_inst = texture.Texture(texture_name, self)
  181. textures.append(tex_inst)
  182. logger.info("Added %d texture nodes", len(textures))
  183. self[constants.TEXTURES] = textures
  184. def _find_node(value, manifest):
  185. """Find a node that matches either a name
  186. or uuid value.
  187. :param value: name or uuid
  188. :param manifest: manifest of nodes to search
  189. :type value: str
  190. :type manifest: list
  191. """
  192. for index in manifest:
  193. uuid = index.get(constants.UUID) == value
  194. name = index.node == value
  195. if uuid or name:
  196. return index
  197. else:
  198. logger.debug("No matching node for %s", value)