|
| 1 | +""" |
| 2 | +Parser and metadata handler for cached binary versions of obj files |
| 3 | +""" |
| 4 | +import gzip |
| 5 | +import json |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import struct |
| 9 | +from datetime import datetime |
| 10 | + |
| 11 | +from pywavefront.material import Material, MaterialParser |
| 12 | + |
| 13 | +logger = logging.getLogger("pywavefront") |
| 14 | + |
| 15 | + |
| 16 | +def cache_name(file_name): |
| 17 | + """Generate the name of the binary cache file""" |
| 18 | + return "{}.bin".format(file_name) |
| 19 | + |
| 20 | + |
| 21 | +def meta_name(file_name): |
| 22 | + """Generate the name of the meta file""" |
| 23 | + return "{}.json".format(file_name) |
| 24 | + |
| 25 | + |
| 26 | +class CacheLoader(object): |
| 27 | + material_parser_cls = MaterialParser |
| 28 | + |
| 29 | + def __init__(self, file_name, wavefront, strict=False, create_materials=False, encoding='utf-8', parse=True, **kwargs): |
| 30 | + self.wavefront = wavefront |
| 31 | + self.file_name = file_name |
| 32 | + self.path = os.path.dirname(file_name) |
| 33 | + self.encoding = encoding |
| 34 | + self.strict = strict |
| 35 | + self.dir = os.path.dirname(file_name) |
| 36 | + self.meta = None |
| 37 | + |
| 38 | + def parse(self): |
| 39 | + meta_exists = os.path.exists(meta_name(self.file_name)) |
| 40 | + cache_exists = os.path.exists(cache_name(self.file_name)) |
| 41 | + |
| 42 | + if not meta_exists or not cache_exists: |
| 43 | + # If both files are missing, things are normal |
| 44 | + if not meta_exists and not cache_exists: |
| 45 | + logger.info("%s has no cache files", self.file_name) |
| 46 | + else: |
| 47 | + logger.warning("%s are missing a .bin or .json file. Cache loading will be disabled.", self.file_name) |
| 48 | + |
| 49 | + return False |
| 50 | + |
| 51 | + logger.info("%s loading cached version", self.file_name) |
| 52 | + |
| 53 | + self.meta = Meta.from_file(meta_name(self.file_name)) |
| 54 | + self._parse_mtllibs() |
| 55 | + self._load_vertex_buffers() |
| 56 | + |
| 57 | + return True |
| 58 | + |
| 59 | + def load_vertex_buffer(self, fd, material, length): |
| 60 | + """ |
| 61 | + Load vertex data from file. Can be overriden to reduce data copy |
| 62 | +
|
| 63 | + :param fd: file object |
| 64 | + :param material: The material these vertices belong to |
| 65 | + :param length: Byte length of the vertex data |
| 66 | + """ |
| 67 | + material.vertices = struct.unpack('{}f'.format(length // 4), fd.read(length)) |
| 68 | + |
| 69 | + def _load_vertex_buffers(self): |
| 70 | + """Load each vertex buffer into each material""" |
| 71 | + fd = gzip.open(cache_name(self.file_name), 'rb') |
| 72 | + |
| 73 | + for buff in self.meta.vertex_buffers: |
| 74 | + |
| 75 | + mat = self.wavefront.materials.get(buff['material']) |
| 76 | + if not mat: |
| 77 | + mat = Material(name=buff['material'], is_default=True) |
| 78 | + self.wavefront.materials[mat.name] = mat |
| 79 | + |
| 80 | + mat.vertex_format = buff['vertex_format'] |
| 81 | + self.load_vertex_buffer(fd, mat, buff['byte_length']) |
| 82 | + |
| 83 | + fd.close() |
| 84 | + |
| 85 | + def _parse_mtllibs(self): |
| 86 | + """Load mtl files""" |
| 87 | + for mtllib in self.meta.mtllibs: |
| 88 | + try: |
| 89 | + materials = self.material_parser_cls( |
| 90 | + os.path.join(self.path, mtllib), |
| 91 | + encoding=self.encoding, |
| 92 | + strict=self.strict).materials |
| 93 | + except IOError: |
| 94 | + raise IOError("Failed to load mtl file:".format(os.path.join(self.path, mtllib))) |
| 95 | + |
| 96 | + for name, material in materials.items(): |
| 97 | + self.wavefront.materials[name] = material |
| 98 | + |
| 99 | + |
| 100 | +class CacheWriter(object): |
| 101 | + |
| 102 | + def __init__(self, file_name, wavefront): |
| 103 | + self.file_name = file_name |
| 104 | + self.wavefront = wavefront |
| 105 | + self.meta = Meta() |
| 106 | + |
| 107 | + def write(self): |
| 108 | + logger.info("%s creating cache", self.file_name) |
| 109 | + |
| 110 | + self.meta.mtllibs = self.wavefront.mtllibs |
| 111 | + |
| 112 | + offset = 0 |
| 113 | + fd = gzip.open(cache_name(self.file_name), 'wb') |
| 114 | + |
| 115 | + for mat in self.wavefront.materials.values(): |
| 116 | + |
| 117 | + if len(mat.vertices) == 0: |
| 118 | + continue |
| 119 | + |
| 120 | + self.meta.add_vertex_buffer( |
| 121 | + mat.name, |
| 122 | + mat.vertex_format, |
| 123 | + offset, |
| 124 | + len(mat.vertices) * 4, |
| 125 | + ) |
| 126 | + offset += len(mat.vertices) * 4 |
| 127 | + fd.write(struct.pack('{}f'.format(len(mat.vertices)), *mat.vertices)) |
| 128 | + |
| 129 | + fd.close() |
| 130 | + self.meta.write(meta_name(self.file_name)) |
| 131 | + |
| 132 | + |
| 133 | +class Meta(object): |
| 134 | + """ |
| 135 | + Metadata for binary obj cache files |
| 136 | + """ |
| 137 | + format_version = "0.1" |
| 138 | + |
| 139 | + def __init__(self, **kwargs): |
| 140 | + self._mtllibs = kwargs.get('mtllibs') or [] |
| 141 | + self._vertex_buffers = kwargs.get('vertex_buffers') or [] |
| 142 | + self._version = kwargs.get('version') or self.format_version |
| 143 | + self._created_at = kwargs.get('created_at') or datetime.now().isoformat() |
| 144 | + |
| 145 | + def add_vertex_buffer(self, material, vertex_format, byte_offset, byte_length): |
| 146 | + """Add a vertex buffer""" |
| 147 | + self._vertex_buffers.append({ |
| 148 | + "material": material, |
| 149 | + "vertex_format": vertex_format, |
| 150 | + "byte_offset": byte_offset, |
| 151 | + "byte_length": byte_length, |
| 152 | + }) |
| 153 | + |
| 154 | + @classmethod |
| 155 | + def from_file(cls, path): |
| 156 | + with open(path, 'r') as fd: |
| 157 | + data = json.loads(fd.read()) |
| 158 | + |
| 159 | + return cls(**data) |
| 160 | + |
| 161 | + def write(self, path): |
| 162 | + """Save the metadata as json""" |
| 163 | + with open(path, 'w') as fd: |
| 164 | + fd.write(json.dumps( |
| 165 | + { |
| 166 | + "created_at": self._created_at, |
| 167 | + "version": self._version, |
| 168 | + "mtllibs": self._mtllibs, |
| 169 | + "vertex_buffers": self._vertex_buffers, |
| 170 | + }, |
| 171 | + indent=2, |
| 172 | + )) |
| 173 | + |
| 174 | + @property |
| 175 | + def version(self): |
| 176 | + return self._version |
| 177 | + |
| 178 | + @property |
| 179 | + def created_at(self): |
| 180 | + return self._created_at |
| 181 | + |
| 182 | + @property |
| 183 | + def vertex_buffers(self): |
| 184 | + return self._vertex_buffers |
| 185 | + |
| 186 | + @property |
| 187 | + def mtllibs(self): |
| 188 | + return self._mtllibs |
| 189 | + |
| 190 | + @mtllibs.setter |
| 191 | + def mtllibs(self, value): |
| 192 | + self._mtllibs = value |
0 commit comments