All files / src/exporter/scene Unity.ts

32.56% Statements 56/172
11.11% Branches 7/63
52% Functions 13/25
32.53% Lines 54/166

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 3911x 1x             1x   1x 1x         1x   2x         1x 5x                           4x         4x   4x 4x   4x   4x 4x 4x 4x   4x 2x       4x           1x                                                                       1x                                                                                                 1x 2x                                     2x   2x           1x           3x       3x 3x             1x 4x   4x 8x 8x 8x                             4x     1x                                                 1x                                                     2x             2x 9380x 9380x           2x 2x 9380x 9380x 9380x                       2x 9380x   9380x                                                                                                                                                           9380x       1x  
import * as fs from 'fs';
import * as yaml from 'yaml';
 
import { SchemaJson, Node, Transform3D, MeshRenderer } from '@drecom/scene-graph-schema';
 
import SceneExporter from '../../interface/SceneExporter';
import SceneExporterPlugin from '../../interface/SceneExporterPlugin';
 
import AssetFileMap from '../../asset/AssetFileMap';
 
import * as IUnity from '../../interface/Unity';
import UnityAssetFile from '../../asset/UnityAssetFile';
 
/**
 * Unity scene exporter
 */
export default class Unity implements SceneExporter {
 
  private guidMap: Map<string, UnityAssetFile> = new Map<string, UnityAssetFile>();
 
  /**
   * Returns runtime identifier string.
   */
  public getIdentifier(): string {
    return 'unity';
  }
 
  /**
   * export scene graph
   *
   * - createGuidMap
   * - (for each scene file)
   *   - loadSceneFile
   *     - addUnityAssetFiles
   *       - addUnityAssetFile
   *     - loadSceneFile (recursive)
   *   - createSceneGraph
   */
  public createSceneGraphSchemas(
    sceneFiles: string[],
    assetRoot: string,
    plugins?: Map<string, SceneExporterPlugin>
  ): Map<string, SchemaJson> {
    const graphs = new Map<string, SchemaJson>();
 
    const assetFileMap = new AssetFileMap(assetRoot);
    assetFileMap.scan();
 
    this.guidMap = this.createGuidMap(assetFileMap);
 
    sceneFiles.forEach((sceneFile) => {
      const sceneJson = this.loadSceneFile(sceneFile);
      const graph = this.createSceneGraph(sceneJson);
      graphs.set(sceneFile, graph);
 
      if (plugins) {
        this.pluginPostProcess(graph, sceneJson, assetFileMap, plugins);
      }
    });
 
    return graphs;
  }
 
  /**
   * Read scene file using file system and convert to javascript object.
   */
  public loadSceneFile(sceneFile: string): any {
    const components: IUnity.Scene = {};
 
    const content = fs.readFileSync(sceneFile).toString();
    // TODO: parseAllDocuments takes long time
    const documents = yaml.parseAllDocuments(content);
 
    const childEntities: { anchor: string, entity: IUnity.SceneEntity }[] = [];
 
    // parse scene components
    documents.forEach((document) => {
      const json = document.toJSON();
      const anchor = Object.keys((document.anchors as any).map)[0];
      const componentName = Object.keys(json)[0];
      const prefab = (componentName === IUnity.Component.Name.PREFAB_INSTANCE) ? true : false;
      const data = json[componentName];
      const entity: IUnity.SceneEntity = { prefab, componentName, data };
      components[anchor] = entity;
 
      if (entity.componentName === IUnity.Component.Name.PREFAB_INSTANCE) {
        childEntities.push({ anchor, entity });
      }
    });
 
    this.addUnityAssetFiles(components);
 
    const childSceneFiles = this.collectChildSceneFiles(components);
 
    childSceneFiles.forEach((item) => {
      const nestedComponents = this.loadSceneFile(item.path);
      components[item.anchor].data = nestedComponents;
    });
 
    return components;
  }
 
  private collectChildSceneFiles(scene: IUnity.Scene): {
    anchor: string;
    path: string;
  }[] {
    const childSceneFiles: {
      anchor: string;
      path: string;
    }[] = [];
 
    Object.entries(scene).forEach((array: any[]) => {
      const anchor: string = array[0] as string;
      const entity: IUnity.SceneEntity = array[1] as IUnity.SceneEntity;
      if (!entity.sgmed || !entity.sgmed.assets) {
        return;
      }
 
      let key = null;
      switch (entity.componentName) {
        // FIXME: direct string literal
        case IUnity.Component.Name.PREFAB_INSTANCE: key = 'm_SourcePrefab'; break;
        default: break;
      }
 
      if (!key) {
        return;
      }
 
      const assets = entity.sgmed.assets[key];
      if (!assets) {
        return;
      }
 
      const file = assets[0].file;
      if (!file) {
        return;
      }
 
      childSceneFiles.push({
        anchor,
        path: file.asset
      });
    });
 
    return childSceneFiles;
  }
 
  /**
   * Create scene graph with scene file dto and collected resource map
   */
  public createSceneGraph(json: any): SchemaJson {
    const graph: SchemaJson = {
      scene: [],
      metadata: {
        width: 0,
        height: 0,
        positiveCoord: {
          xRight: true,
          yDown:  false,
          zFront: false
        },
        baseCoordinate: {
          x: 'center',
          y: 'center',
          z: 'center'
        },
        format: this.getIdentifier()
      }
    };
 
    this.appendComponents(json, graph);
 
    return graph;
  }
 
  /**
   * Execute plugin post process
   */
  public pluginPostProcess(
    graph: SchemaJson,
    sceneJson: any[],
    assetFileMap: AssetFileMap,
    plugins?: Map<string, SceneExporterPlugin>
  ): void {
    Iif (!plugins) {
      return;
    }
 
    plugins.forEach((plugin) => {
      plugin.extendSceneGraph(graph, sceneJson, assetFileMap);
    });
  }
 
  /**
   * Created supported resource map
   */
  protected createGuidMap(assetFileMap: AssetFileMap): Map<string, UnityAssetFile> {
    const guidMap = new Map<string, UnityAssetFile>();
 
    assetFileMap.forEach((item) => {
      const metaFile = item.filePath;
      Eif (!UnityAssetFile.isMetaFile(metaFile)) {
        return;
      }
 
      const content = fs.readFileSync(metaFile, 'utf-8');
 
      try {
        const json: IUnity.File.Meta = yaml.parse(content);
        const assetFile = UnityAssetFile.createWithMetaFile(metaFile);
        guidMap.set(json.guid, assetFile);
      } catch (e) {
        // can not avoid unity's invalid yaml semantic
        console.warn(metaFile, e.message);
      }
    });
 
    return guidMap;
  }
 
  protected addUnityAssetFiles(scene: IUnity.Scene): void {
    Object.entries(scene).forEach((array: any) => {
      const entity = array[1] as IUnity.SceneEntity;
      switch (entity.componentName) {
        case IUnity.Component.Name.GAME_OBJECT: {
          // FIXME: direct string literal
          this.addUnityAssetFile(entity, 'm_CorrespondingSourceObject');
          break;
        }
        case IUnity.Component.Name.PREFAB_INSTANCE: {
          // FIXME: direct string literal
          this.addUnityAssetFile(entity, 'm_SourcePrefab');
          break;
        }
        case IUnity.Component.Name.SKINNED_MESH_RENDERER: {
          // FIXME: direct string literal
          this.addUnityAssetFile(entity, 'm_Mesh');
          this.addUnityAssetFile(entity, 'm_Materials');
          break;
        }
        default: break;
      }
    });
  }
 
  protected addUnityAssetFile(entity: IUnity.SceneEntity, key: string): void {
    const value = entity.data[key];
    if (!value) {
      return;
    }
 
    entity.sgmed = entity.sgmed || {};
    entity.sgmed.assets = entity.sgmed.assets || {};
    entity.sgmed.assets[key] = [];
 
    const assets: IUnity.File.Element.FileReference[]
      = (value.constructor.name === 'Array') ? value : [value];
    assets.forEach((item: IUnity.File.Element.FileReference) => {
      const ref = item as IUnity.File.Element.FileReference;
      if (!ref.guid) {
        return;
      }
 
      const file = this.guidMap.get(`${ref.guid}`);
      if (!file) {
        return;
      }
 
      entity.sgmed!.assets![key].push({ ref, file });
    });
  }
 
  protected appendComponents(scene: IUnity.Scene, graph: SchemaJson): void {
    type GameObjectMapEntry = {
      entity: IUnity.SceneEntity,
      node: Node
    };
 
    // expand prefab instances
    Object.entries(scene).forEach((array: any) => {
      const entity = array[1] as IUnity.SceneEntity;
      Iif (entity.componentName === IUnity.Component.Name.PREFAB_INSTANCE) {
        this.appendComponents(entity.data, graph);
      }
    });
 
    // collect gameobjects
    const gameObjects = new Map<string, GameObjectMapEntry>();
    Object.entries(scene).forEach((array: any) => {
      const anchor = array[0] as string;
      const entity = array[1] as IUnity.SceneEntity;
      Iif (entity.componentName === IUnity.Component.Name.GAME_OBJECT) {
        const gameObject = entity.data as IUnity.Component.GameObject;
        const node: Node = {
          id: anchor,
          name: gameObject.m_Name,
          constructorName: entity.componentName
        };
        gameObjects.set(anchor, { entity, node });
        graph.scene.push(node);
      }
    });
 
    Object.entries(scene).forEach((array: any) => {
      const entity = array[1] as IUnity.SceneEntity;
 
      switch (entity.componentName) {
        case IUnity.Component.Name.TRANSFORM: {
          const transform = entity.data as IUnity.Component.Transform;
          const gameObject = gameObjects.get(`${transform.m_GameObject.fileID}`);
          if (!gameObject) {
            break;
          }
          const transform3d: Transform3D = {
            x: transform.m_LocalPosition.x,
            y: transform.m_LocalPosition.y,
            z: transform.m_LocalPosition.z,
            scale: {
              x: transform.m_LocalScale.x,
              y: transform.m_LocalScale.y,
              z: transform.m_LocalScale.z
            },
            rotation: {
              x: transform.m_LocalRotation.x,
              y: transform.m_LocalRotation.y,
              z: transform.m_LocalRotation.z,
              w: transform.m_LocalRotation.w
            }
          };
          gameObject.node.transform3d = transform3d;
          break;
        }
        case IUnity.Component.Name.SKINNED_MESH_RENDERER: {
          if (!entity.sgmed || !entity.sgmed.assets) {
            break;
          }
 
          const meshRenderer = entity.data as IUnity.Component.SkinnedMeshRenderer;
          const gameObject = gameObjects.get(`${meshRenderer.m_GameObject.fileID}`);
          if (!gameObject) {
            break;
          }
 
          const renderer: MeshRenderer = {
            mesh: { url: '' },
            materials: []
          };
 
          const meshFile = entity.sgmed.assets['m_Mesh'][0].file;
          const materialAssetInfo = entity.sgmed.assets['m_Materials'];
 
          if (meshFile) {
            renderer.mesh!.url = meshFile.asset;
          }
 
          if (materialAssetInfo) {
            materialAssetInfo.forEach((assetInfo: IUnity.SgmedAssetInfo) => {
              const content = fs.readFileSync(assetInfo.file.asset).toString();
              const materialJson = yaml.parse(content) as IUnity.File.Material;
              const textures = materialJson.Material.m_SavedProperties.m_TexEnvs;
 
              textures.forEach((texture) => {
                Object.entries(texture).forEach((array: any[]) => {
                  const textureProp = array[1] as IUnity.File.Element.TextureProperty;
                  if (!textureProp.m_Texture.guid) {
                    return;
                  }
                  const file = this.guidMap.get(textureProp.m_Texture.guid);
                  if (!file) {
                    return;
                  }
                  renderer.materials!.push({
                    url: file.asset
                  });
                });
              });
            });
          }
 
          gameObject.node.meshRenderer = renderer;
          break;
        }
        case IUnity.Component.Name.GAME_OBJECT:
        case IUnity.Component.Name.PREFAB_INSTANCE:
        default: break;
      }
    });
  }
}