@loaders.gl/tile-converter 3.0.10 → 3.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/dist.es5.min.js +14 -14
  2. package/dist/dist.es5.min.js.map +1 -1
  3. package/dist/dist.min.js +14 -14
  4. package/dist/dist.min.js.map +1 -1
  5. package/dist/es5/i3s-converter/i3s-converter.js +27 -16
  6. package/dist/es5/i3s-converter/i3s-converter.js.map +1 -1
  7. package/dist/es5/pgm-loader.js +1 -1
  8. package/dist/esm/3d-tiles-converter/3d-tiles-converter.js +11 -11
  9. package/dist/esm/3d-tiles-converter/3d-tiles-converter.js.map +1 -1
  10. package/dist/esm/3d-tiles-converter/helpers/b3dm-converter.js +1 -1
  11. package/dist/esm/3d-tiles-converter/helpers/b3dm-converter.js.map +1 -1
  12. package/dist/esm/i3s-converter/helpers/geometry-converter.js +2 -2
  13. package/dist/esm/i3s-converter/helpers/geometry-converter.js.map +1 -1
  14. package/dist/esm/i3s-converter/helpers/node-debug.js +2 -2
  15. package/dist/esm/i3s-converter/helpers/node-debug.js.map +1 -1
  16. package/dist/esm/i3s-converter/helpers/node-pages.js +2 -2
  17. package/dist/esm/i3s-converter/helpers/node-pages.js.map +1 -1
  18. package/dist/esm/i3s-converter/i3s-converter.js +36 -28
  19. package/dist/esm/i3s-converter/i3s-converter.js.map +1 -1
  20. package/dist/esm/i3s-converter/json-templates/shared-resources.js +2 -2
  21. package/dist/esm/i3s-converter/json-templates/shared-resources.js.map +1 -1
  22. package/dist/esm/i3s-server/controllers/index-controller.js +1 -1
  23. package/dist/esm/i3s-server/controllers/index-controller.js.map +1 -1
  24. package/dist/esm/lib/utils/compress-util.js +13 -13
  25. package/dist/esm/lib/utils/compress-util.js.map +1 -1
  26. package/dist/esm/lib/utils/file-utils.js +1 -1
  27. package/dist/esm/lib/utils/file-utils.js.map +1 -1
  28. package/dist/esm/lib/utils/statistic-utills.js +5 -5
  29. package/dist/esm/lib/utils/statistic-utills.js.map +1 -1
  30. package/dist/esm/pgm-loader.js +1 -1
  31. package/package.json +14 -14
  32. package/src/i3s-converter/i3s-converter.ts +10 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/3d-tiles-converter/3d-tiles-converter.ts"],"names":["join","process","transform","load","I3SLoader","I3SAttributeLoader","Tileset3D","Tile3D","PGMLoader","i3sObbTo3dTilesObb","convertScreenThresholdToGeometricError","writeFile","removeDir","calculateFilesSize","timeConverter","TILESET","tilesetTemplate","B3dmConverter","createObbFromMbs","I3S","Tiles3DConverter","constructor","options","tilesetPath","vertexCounter","conversionStartTime","geoidHeightModel","sourceTileset","attributeStorageInfo","convert","inputUrl","outputPath","tilesetName","maxDepth","egmFilePath","hrtime","console","log","sourceTilesetJson","root","header","obb","mbs","e","rootTile","boundingVolume","box","geometricError","children","_addChildren","tileset","JSON","stringify","_finishConversion","slpk","parentSourceNode","parentNode","level","childNodeInfo","sourceChild","_loadChildNode","push","contentUrl","_loadTile","content","vertexCount","attributes","_loadChildAttributes","child","b3dm","uri","id","Uint8Array","unloadContent","nodePages","nodePagesTile","formTileFromNodePages","loader","nodeUrl","_relativeUrlToFullUrl","url","href","i3s","loadOptions","isTileHeader","loadContent","baseUrl","relativeUrl","resultArray","split","relativeUrlArray","folder","slice","promises","attributeUrls","index","length","attribute","attributeName","name","attributeType","_getAttributeType","attributesList","Promise","all","_replaceNestedArrays","Object","assign","attributeValues","valueType","objectIds","attributeObject","key","Array","from","params","filesSize","diff","conversionTime"],"mappings":";AAGA,SAAQA,IAAR,QAAmB,MAAnB;AACA,OAAOC,OAAP,MAAoB,SAApB;AACA,OAAOC,SAAP,MAAsB,oBAAtB;AACA,SAAQC,IAAR,QAAmB,kBAAnB;AACA,SAAQC,SAAR,EAAmBC,kBAAnB,QAA4C,iBAA5C;AACA,SAAQC,SAAR,EAAmBC,MAAnB,QAAgC,mBAAhC;AAEA,SAAQC,SAAR,QAAwB,eAAxB;AACA,S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MAAMvG,kBAAkB,CAACsG,MAAD,CAA1C;AACA,UAAME,IAAI,GAAGpH,OAAO,CAACkC,MAAR,CAAe,KAAKV,mBAApB,CAAb;AACA,UAAM6F,cAAc,GAAGxG,aAAa,CAACuG,IAAD,CAApC;AAEAjF,IAAAA,OAAO,CAACC,GAAR,CAAa,kDAAb;AACAD,IAAAA,OAAO,CAACC,GAAR,CAAa,wBAAuBlB,GAAI,EAAxC;AACAiB,IAAAA,OAAO,CAACC,GAAR,CAAa,0BAAyBiF,cAAe,EAArD;AACAlF,IAAAA,OAAO,CAACC,GAAR,CAAa,gBAAb,EAA8B,KAAKb,aAAnC;AACAY,IAAAA,OAAO,CAACC,GAAR,CAAa,gBAAb,EAA8B+E,SAA9B,EAAyC,QAAzC;AACAhF,IAAAA,OAAO,CAACC,GAAR,CAAa,kDAAb;AACD;;AApQmC","sourcesContent":["import type {AttributeStorageInfo, FeatureAttribute, NodeReference} from '@loaders.gl/i3s';\nimport type {Node3D} from '@loaders.gl/3d-tiles';\n\nimport {join} from 'path';\nimport process from 'process';\nimport transform from 'json-map-transform';\nimport {load} from '@loaders.gl/core';\nimport {I3SLoader, I3SAttributeLoader} from '@loaders.gl/i3s';\nimport {Tileset3D, Tile3D} from '@loaders.gl/tiles';\n\nimport {PGMLoader} from '../pgm-loader';\nimport {i3sObbTo3dTilesObb} from './helpers/i3s-obb-to-3d-tiles-obb';\nimport {convertScreenThresholdToGeometricError} from '../lib/utils/lod-conversion-utils';\nimport {writeFile, removeDir} from '../lib/utils/file-utils';\nimport {calculateFilesSize, timeConverter} from '../lib/utils/statistic-utills';\nimport {TILESET as tilesetTemplate} from './json-templates/tileset';\nimport B3dmConverter from './helpers/b3dm-converter';\nimport {createObbFromMbs} from '../i3s-converter/helpers/coordinate-converter';\nimport {GeoidHeightModel} from '../lib/geoid-height-model';\n\nconst I3S = 'I3S';\n\n/**\n * Converter from i3s to 3d-tiles\n */\nexport default class Tiles3DConverter {\n options: any;\n tilesetPath: string;\n vertexCounter: number;\n conversionStartTime: [number, number];\n geoidHeightModel: GeoidHeightModel;\n sourceTileset: Tileset3D;\n attributeStorageInfo: AttributeStorageInfo;\n\n constructor() {\n this.options = {};\n this.tilesetPath = '';\n this.vertexCounter = 0;\n this.conversionStartTime = [0, 0];\n this.geoidHeightModel = null;\n this.sourceTileset = null;\n this.attributeStorageInfo = null;\n }\n\n /**\n * Convert i3s format data to 3dTiles\n * @param options\n * @param options.inputUrl the url to read the tileset from\n * @param options.outputPath the output filename\n * @param options.tilesetName the output name of the tileset\n * @param options.egmFilePath location of *.pgm file to convert heights from ellipsoidal to gravity-related format\n * @param options.maxDepth The max tree depth of conversion\n */\n private async convert(options: {\n inputUrl: string;\n outputPath: string;\n tilesetName: string;\n maxDepth: number;\n egmFilePath: string;\n }): Promise<any> {\n const {inputUrl, outputPath, tilesetName, maxDepth, egmFilePath} = options;\n this.conversionStartTime = process.hrtime();\n this.options = {maxDepth};\n\n console.log('Loading egm file...'); // eslint-disable-line\n this.geoidHeightModel = await load(egmFilePath, PGMLoader);\n console.log('Loading egm file completed!'); // eslint-disable-line\n\n const sourceTilesetJson = await load(inputUrl, I3SLoader, {});\n this.sourceTileset = new Tileset3D(sourceTilesetJson, {});\n\n if (!this.sourceTileset.root.header.obb) {\n this.sourceTileset.root.header.obb = createObbFromMbs(this.sourceTileset.root.header.mbs);\n }\n\n this.tilesetPath = join(`${outputPath}`, `${tilesetName}`);\n this.attributeStorageInfo = sourceTilesetJson.attributeStorageInfo;\n // Removing the tilesetPath needed to exclude erroneous files after conversion\n try {\n await removeDir(this.tilesetPath);\n } catch (e) {\n // do nothing\n }\n\n const rootTile: Node3D = {\n boundingVolume: {\n box: i3sObbTo3dTilesObb(this.sourceTileset.root.header.obb, this.geoidHeightModel)\n },\n geometricError: convertScreenThresholdToGeometricError(this.sourceTileset.root),\n children: []\n };\n\n await this._addChildren(this.sourceTileset.root, rootTile, 1);\n\n const tileset = transform({root: rootTile}, tilesetTemplate);\n await writeFile(this.tilesetPath, JSON.stringify(tileset), 'tileset.json');\n\n this._finishConversion({slpk: false, outputPath, tilesetName});\n }\n\n /**\n * The recursive function of traversal of a nodes tree\n * @param parentSourceNode the parent node tile object (@loaders.gl/tiles/Tile3D)\n * @param parentNode object in resulting tileset\n * @param level a current level of a tree depth\n */\n private async _addChildren(\n parentSourceNode: Tile3D,\n parentNode: Node3D,\n level: number\n ): Promise<void> {\n if (this.options.maxDepth && level > this.options.maxDepth) {\n return;\n }\n for (const childNodeInfo of parentSourceNode.header.children || []) {\n const sourceChild = await this._loadChildNode(parentSourceNode, childNodeInfo);\n parentSourceNode.children.push(sourceChild);\n if (sourceChild.contentUrl) {\n await this.sourceTileset._loadTile(sourceChild);\n this.vertexCounter += sourceChild.content.vertexCount;\n\n let attributes = null;\n if (this.attributeStorageInfo) {\n attributes = await this._loadChildAttributes(sourceChild, this.attributeStorageInfo);\n }\n\n if (!sourceChild.header.obb) {\n sourceChild.header.obb = createObbFromMbs(sourceChild.header.mbs);\n }\n\n const boundingVolume = {\n box: i3sObbTo3dTilesObb(sourceChild.header.obb, this.geoidHeightModel)\n };\n const child: Node3D = {\n boundingVolume,\n geometricError: convertScreenThresholdToGeometricError(sourceChild),\n children: []\n };\n\n const b3dm = await new B3dmConverter().convert(sourceChild, attributes);\n child.content = {\n uri: `${sourceChild.id}.b3dm`,\n boundingVolume\n };\n await writeFile(this.tilesetPath, new Uint8Array(b3dm), `${sourceChild.id}.b3dm`);\n parentNode.children.push(child);\n\n sourceChild.unloadContent();\n await this._addChildren(sourceChild, child, level + 1);\n } else {\n await this._addChildren(sourceChild, parentNode, level + 1);\n }\n }\n }\n\n /**\n * Load a child node having information from the node header\n * @param parentNode a parent node tile object (@loaders.gl/tiles/Tile3D)\n * @param childNodeInfo child information from 3DNodeIndexDocument\n * (https://github.com/Esri/i3s-spec/blob/master/docs/1.7/nodeReference.cmn.md)\n */\n private async _loadChildNode(parentNode: Tile3D, childNodeInfo: NodeReference): Promise<Tile3D> {\n let header;\n if (this.sourceTileset.tileset.nodePages) {\n console.log(`Node conversion: ${childNodeInfo.id}`); // eslint-disable-line no-console,no-undef\n header = await this.sourceTileset.tileset.nodePagesTile.formTileFromNodePages(\n childNodeInfo.id\n );\n } else {\n const {loader} = this.sourceTileset;\n const nodeUrl = this._relativeUrlToFullUrl(parentNode.url, childNodeInfo.href);\n // load metadata\n const options = {\n i3s: {\n ...this.sourceTileset.loadOptions,\n isTileHeader: true,\n loadContent: false\n }\n };\n\n console.log(`Node conversion: ${nodeUrl}`); // eslint-disable-line no-console,no-undef\n header = await load(nodeUrl, loader, options);\n }\n return new Tile3D(this.sourceTileset, header, parentNode);\n }\n\n /**\n * Make an url of a resource from its relative url having the base url\n * @param baseUrl the base url. A resulting url will be related from this url\n * @param relativeUrl a realtive url of a resource\n */\n private _relativeUrlToFullUrl(baseUrl: string, relativeUrl: string): string {\n let resultArray = baseUrl.split('/');\n const relativeUrlArray = relativeUrl.split('/');\n for (const folder of relativeUrlArray) {\n switch (folder) {\n case '.':\n continue; // eslint-disable-line no-continue\n case '..':\n resultArray = resultArray.slice(0, -1);\n break;\n default:\n resultArray.push(folder);\n }\n }\n return resultArray.join('/');\n }\n\n /**\n * Do loading all attributes related to particular node.\n * @param sourceChild\n * @param attributeStorageInfo\n * @returns Promise of attributes object.\n */\n private async _loadChildAttributes(\n sourceChild: Tile3D,\n attributeStorageInfo: AttributeStorageInfo\n ): Promise<FeatureAttribute> {\n const promises = [];\n const {attributeUrls} = sourceChild.header;\n\n for (let index = 0; index < attributeUrls.length; index++) {\n const inputUrl = attributeUrls[index];\n const attribute = attributeStorageInfo[index];\n const options = {\n attributeName: attribute.name,\n attributeType: this._getAttributeType(attribute)\n };\n\n promises.push(load(inputUrl, I3SAttributeLoader, options));\n }\n const attributesList = await Promise.all(promises);\n this._replaceNestedArrays(attributesList);\n return Object.assign({}, ...attributesList);\n }\n\n /**\n * Returns attribute type for loading attributes\n * @param attribute\n * Workaround for I3S v1.6. There is no attribute.attributeValues.valueType field in attribute.\n * There is an 'Oid32' type if attribute has objectIds property.\n * Doc: https://github.com/Esri/i3s-spec/blob/master/docs/1.6/attributeStorageInfo.cmn.md\n */\n private _getAttributeType(attribute: AttributeStorageInfo): string {\n if (attribute.attributeValues) {\n return attribute.attributeValues.valueType;\n } else if (attribute.objectIds) {\n return 'Oid32';\n }\n return '';\n }\n\n /**\n * Make simple arrays from attribute typed arrays.\n * @param attributesList\n */\n private _replaceNestedArrays(attributesList: FeatureAttribute[]): void {\n for (let index = 0; index < attributesList.length; index++) {\n const attributeObject = attributesList[index];\n\n for (const key in attributeObject) {\n attributeObject[key] = Array.from(attributeObject[key]);\n }\n }\n }\n\n /**\n * Print statistics in the end of conversion\n * @param params - output files data\n */\n private async _finishConversion(params: {\n slpk: boolean;\n outputPath: string;\n tilesetName: string;\n }): Promise<void> {\n const filesSize = await calculateFilesSize(params);\n const diff = process.hrtime(this.conversionStartTime);\n const conversionTime = timeConverter(diff);\n\n console.log(`------------------------------------------------`); // eslint-disable-line\n console.log(`Finish conversion of ${I3S}`); // eslint-disable-line\n console.log(`Total conversion time: ${conversionTime}`); // eslint-disable-line\n console.log(`Vertex count: `, this.vertexCounter); // eslint-disable-line\n console.log(`File(s) size: `, filesSize, ' bytes'); // eslint-disable-line\n console.log(`------------------------------------------------`); // eslint-disable-line\n }\n}\n"],"file":"3d-tiles-converter.js"}
1
+ {"version":3,"sources":["../../../src/3d-tiles-converter/3d-tiles-converter.ts"],"names":["join","process","transform","load","I3SLoader","I3SAttributeLoader","Tileset3D","Tile3D","PGMLoader","i3sObbTo3dTilesObb","convertScreenThresholdToGeometricError","writeFile","removeDir","calculateFilesSize","timeConverter","TILESET","tilesetTemplate","B3dmConverter","createObbFromMbs","I3S","Tiles3DConverter","constructor","options","tilesetPath","vertexCounter","conversionStartTime","geoidHeightModel","sourceTileset","attributeStorageInfo","convert","inputUrl","outputPath","tilesetName","maxDepth","egmFilePath","hrtime","console","log","sourceTilesetJson","root","header","obb","mbs","e","rootTile","boundingVolume","box","geometricError","children","_addChildren","tileset","JSON","stringify","_finishConversion","slpk","parentSourceNode","parentNode","level","childNodeInfo","sourceChild","_loadChildNode","push","contentUrl","_loadTile","content","vertexCount","attributes","_loadChildAttributes","child","b3dm","uri","id","Uint8Array","unloadContent","nodePages","nodePagesTile","formTileFromNodePages","loader","nodeUrl","_relativeUrlToFullUrl","url","href","i3s","loadOptions","isTileHeader","loadContent","baseUrl","relativeUrl","resultArray","split","relativeUrlArray","folder","slice","promises","attributeUrls","index","length","attribute","attributeName","name","attributeType","_getAttributeType","attributesList","Promise","all","_replaceNestedArrays","Object","assign","attributeValues","valueType","objectIds","attributeObject","key","Array","from","params","filesSize","diff","conversionTime"],"mappings":";AAGA,SAAQA,IAAR,QAAmB,MAAnB;AACA,OAAOC,OAAP,MAAoB,SAApB;AACA,OAAOC,SAAP,MAAsB,oBAAtB;AACA,SAAQC,IAAR,QAAmB,kBAAnB;AACA,SAAQC,SAAR,EAAmBC,kBAAnB,QAA4C,iBAA5C;AACA,SAAQC,SAAR,EAAmBC,MAAnB,QAAgC,mBAAhC;AAEA,SAAQC,SAAR,QAAwB,eAAxB;AACA,SAAQC,kBAAR,QAAiC,mCAAjC;AACA,SAAQC,sCAAR,QAAqD,mCAArD;AACA,SAAQC,SAAR,EAAmBC,SAAnB,QAAmC,yBAAnC;AACA,SAAQC,kBAAR,EAA4BC,aAA5B,QAAgD,+BAAhD;AACA,SAAQC,OAAO,IAAIC,eAAnB,QAAyC,0BAAzC;AACA,OAAOC,aAAP,MAA0B,0BAA1B;AACA,SAAQC,gBAAR,QAA+B,+CAA/B;AAGA,MAAMC,GAAG,GAAG,KAAZ;AAKA,eAAe,MAAMC,gBAAN,CAAuB;AASpCC,EAAAA,WAAW,GAAG;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;;AACZ,SAAKC,OAAL,GAAe,EAAf;AACA,SAAKC,WAAL,GAAmB,EAAnB;AACA,SAAKC,aAAL,GAAqB,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iB,CAACJ,SAAD,EAA0C;AACjE,QAAIA,SAAS,CAACW,eAAd,EAA+B;AAC7B,aAAOX,SAAS,CAACW,eAAV,CAA0BC,SAAjC;AACD,KAFD,MAEO,IAAIZ,SAAS,CAACa,SAAd,EAAyB;AAC9B,aAAO,OAAP;AACD;;AACD,WAAO,EAAP;AACD;;AAMOL,EAAAA,oBAAoB,CAACH,cAAD,EAA2C;AACrE,SAAK,IAAIP,KAAK,GAAG,CAAjB,EAAoBA,KAAK,GAAGO,cAAc,CAACN,MAA3C,EAAmDD,KAAK,EAAxD,EAA4D;AAC1D,YAAMgB,eAAe,GAAGT,cAAc,CAACP,KAAD,CAAtC;;AAEA,WAAK,MAAMiB,GAAX,IAAkBD,eAAlB,EAAmC;AACjCA,QAAAA,eAAe,CAACC,GAAD,CAAf,GAAuBC,KAAK,CAACC,IAAN,CAAWH,eAAe,CAACC,GAAD,CAA1B,CAAvB;AACD;AACF;AACF;;AAM8B,QAAjB3D,iBAAiB,CAAC8D,MAAD,EAIb;AAChB,UAAMC,SAAS,GAAG,MAAMvG,kBAAkB,CAACsG,MAAD,CAA1C;AACA,UAAME,IAAI,GAAGpH,OAAO,CAACkC,MAAR,CAAe,KAAKV,mBAApB,CAAb;AACA,UAAM6F,cAAc,GAAGxG,aAAa,CAACuG,IAAD,CAApC;AAEAjF,IAAAA,OAAO,CAACC,GAAR;AACAD,IAAAA,OAAO,CAACC,GAAR,gCAAoClB,GAApC;AACAiB,IAAAA,OAAO,CAACC,GAAR,kCAAsCiF,cAAtC;AACAlF,IAAAA,OAAO,CAACC,GAAR,mBAA8B,KAAKb,aAAnC;AACAY,IAAAA,OAAO,CAACC,GAAR,mBAA8B+E,SAA9B,EAAyC,QAAzC;AACAhF,IAAAA,OAAO,CAACC,GAAR;AACD;;AApQmC","sourcesContent":["import type {AttributeStorageInfo, FeatureAttribute, NodeReference} from '@loaders.gl/i3s';\nimport type {Node3D} from '@loaders.gl/3d-tiles';\n\nimport {join} from 'path';\nimport process from 'process';\nimport transform from 'json-map-transform';\nimport {load} from '@loaders.gl/core';\nimport {I3SLoader, I3SAttributeLoader} from '@loaders.gl/i3s';\nimport {Tileset3D, Tile3D} from '@loaders.gl/tiles';\n\nimport {PGMLoader} from '../pgm-loader';\nimport {i3sObbTo3dTilesObb} from './helpers/i3s-obb-to-3d-tiles-obb';\nimport {convertScreenThresholdToGeometricError} from '../lib/utils/lod-conversion-utils';\nimport {writeFile, removeDir} from '../lib/utils/file-utils';\nimport {calculateFilesSize, timeConverter} from '../lib/utils/statistic-utills';\nimport {TILESET as tilesetTemplate} from './json-templates/tileset';\nimport B3dmConverter from './helpers/b3dm-converter';\nimport {createObbFromMbs} from '../i3s-converter/helpers/coordinate-converter';\nimport {GeoidHeightModel} from '../lib/geoid-height-model';\n\nconst I3S = 'I3S';\n\n/**\n * Converter from i3s to 3d-tiles\n */\nexport default class Tiles3DConverter {\n options: any;\n tilesetPath: string;\n vertexCounter: number;\n conversionStartTime: [number, number];\n geoidHeightModel: GeoidHeightModel;\n sourceTileset: Tileset3D;\n attributeStorageInfo: AttributeStorageInfo;\n\n constructor() {\n this.options = {};\n this.tilesetPath = '';\n this.vertexCounter = 0;\n this.conversionStartTime = [0, 0];\n this.geoidHeightModel = null;\n this.sourceTileset = null;\n this.attributeStorageInfo = null;\n }\n\n /**\n * Convert i3s format data to 3dTiles\n * @param options\n * @param options.inputUrl the url to read the tileset from\n * @param options.outputPath the output filename\n * @param options.tilesetName the output name of the tileset\n * @param options.egmFilePath location of *.pgm file to convert heights from ellipsoidal to gravity-related format\n * @param options.maxDepth The max tree depth of conversion\n */\n private async convert(options: {\n inputUrl: string;\n outputPath: string;\n tilesetName: string;\n maxDepth: number;\n egmFilePath: string;\n }): Promise<any> {\n const {inputUrl, outputPath, tilesetName, maxDepth, egmFilePath} = options;\n this.conversionStartTime = process.hrtime();\n this.options = {maxDepth};\n\n console.log('Loading egm file...'); // eslint-disable-line\n this.geoidHeightModel = await load(egmFilePath, PGMLoader);\n console.log('Loading egm file completed!'); // eslint-disable-line\n\n const sourceTilesetJson = await load(inputUrl, I3SLoader, {});\n this.sourceTileset = new Tileset3D(sourceTilesetJson, {});\n\n if (!this.sourceTileset.root.header.obb) {\n this.sourceTileset.root.header.obb = createObbFromMbs(this.sourceTileset.root.header.mbs);\n }\n\n this.tilesetPath = join(`${outputPath}`, `${tilesetName}`);\n this.attributeStorageInfo = sourceTilesetJson.attributeStorageInfo;\n // Removing the tilesetPath needed to exclude erroneous files after conversion\n try {\n await removeDir(this.tilesetPath);\n } catch (e) {\n // do nothing\n }\n\n const rootTile: Node3D = {\n boundingVolume: {\n box: i3sObbTo3dTilesObb(this.sourceTileset.root.header.obb, this.geoidHeightModel)\n },\n geometricError: convertScreenThresholdToGeometricError(this.sourceTileset.root),\n children: []\n };\n\n await this._addChildren(this.sourceTileset.root, rootTile, 1);\n\n const tileset = transform({root: rootTile}, tilesetTemplate);\n await writeFile(this.tilesetPath, JSON.stringify(tileset), 'tileset.json');\n\n this._finishConversion({slpk: false, outputPath, tilesetName});\n }\n\n /**\n * The recursive function of traversal of a nodes tree\n * @param parentSourceNode the parent node tile object (@loaders.gl/tiles/Tile3D)\n * @param parentNode object in resulting tileset\n * @param level a current level of a tree depth\n */\n private async _addChildren(\n parentSourceNode: Tile3D,\n parentNode: Node3D,\n level: number\n ): Promise<void> {\n if (this.options.maxDepth && level > this.options.maxDepth) {\n return;\n }\n for (const childNodeInfo of parentSourceNode.header.children || []) {\n const sourceChild = await this._loadChildNode(parentSourceNode, childNodeInfo);\n parentSourceNode.children.push(sourceChild);\n if (sourceChild.contentUrl) {\n await this.sourceTileset._loadTile(sourceChild);\n this.vertexCounter += sourceChild.content.vertexCount;\n\n let attributes = null;\n if (this.attributeStorageInfo) {\n attributes = await this._loadChildAttributes(sourceChild, this.attributeStorageInfo);\n }\n\n if (!sourceChild.header.obb) {\n sourceChild.header.obb = createObbFromMbs(sourceChild.header.mbs);\n }\n\n const boundingVolume = {\n box: i3sObbTo3dTilesObb(sourceChild.header.obb, this.geoidHeightModel)\n };\n const child: Node3D = {\n boundingVolume,\n geometricError: convertScreenThresholdToGeometricError(sourceChild),\n children: []\n };\n\n const b3dm = await new B3dmConverter().convert(sourceChild, attributes);\n child.content = {\n uri: `${sourceChild.id}.b3dm`,\n boundingVolume\n };\n await writeFile(this.tilesetPath, new Uint8Array(b3dm), `${sourceChild.id}.b3dm`);\n parentNode.children.push(child);\n\n sourceChild.unloadContent();\n await this._addChildren(sourceChild, child, level + 1);\n } else {\n await this._addChildren(sourceChild, parentNode, level + 1);\n }\n }\n }\n\n /**\n * Load a child node having information from the node header\n * @param parentNode a parent node tile object (@loaders.gl/tiles/Tile3D)\n * @param childNodeInfo child information from 3DNodeIndexDocument\n * (https://github.com/Esri/i3s-spec/blob/master/docs/1.7/nodeReference.cmn.md)\n */\n private async _loadChildNode(parentNode: Tile3D, childNodeInfo: NodeReference): Promise<Tile3D> {\n let header;\n if (this.sourceTileset.tileset.nodePages) {\n console.log(`Node conversion: ${childNodeInfo.id}`); // eslint-disable-line no-console,no-undef\n header = await this.sourceTileset.tileset.nodePagesTile.formTileFromNodePages(\n childNodeInfo.id\n );\n } else {\n const {loader} = this.sourceTileset;\n const nodeUrl = this._relativeUrlToFullUrl(parentNode.url, childNodeInfo.href);\n // load metadata\n const options = {\n i3s: {\n ...this.sourceTileset.loadOptions,\n isTileHeader: true,\n loadContent: false\n }\n };\n\n console.log(`Node conversion: ${nodeUrl}`); // eslint-disable-line no-console,no-undef\n header = await load(nodeUrl, loader, options);\n }\n return new Tile3D(this.sourceTileset, header, parentNode);\n }\n\n /**\n * Make an url of a resource from its relative url having the base url\n * @param baseUrl the base url. A resulting url will be related from this url\n * @param relativeUrl a realtive url of a resource\n */\n private _relativeUrlToFullUrl(baseUrl: string, relativeUrl: string): string {\n let resultArray = baseUrl.split('/');\n const relativeUrlArray = relativeUrl.split('/');\n for (const folder of relativeUrlArray) {\n switch (folder) {\n case '.':\n continue; // eslint-disable-line no-continue\n case '..':\n resultArray = resultArray.slice(0, -1);\n break;\n default:\n resultArray.push(folder);\n }\n }\n return resultArray.join('/');\n }\n\n /**\n * Do loading all attributes related to particular node.\n * @param sourceChild\n * @param attributeStorageInfo\n * @returns Promise of attributes object.\n */\n private async _loadChildAttributes(\n sourceChild: Tile3D,\n attributeStorageInfo: AttributeStorageInfo\n ): Promise<FeatureAttribute> {\n const promises = [];\n const {attributeUrls} = sourceChild.header;\n\n for (let index = 0; index < attributeUrls.length; index++) {\n const inputUrl = attributeUrls[index];\n const attribute = attributeStorageInfo[index];\n const options = {\n attributeName: attribute.name,\n attributeType: this._getAttributeType(attribute)\n };\n\n promises.push(load(inputUrl, I3SAttributeLoader, options));\n }\n const attributesList = await Promise.all(promises);\n this._replaceNestedArrays(attributesList);\n return Object.assign({}, ...attributesList);\n }\n\n /**\n * Returns attribute type for loading attributes\n * @param attribute\n * Workaround for I3S v1.6. There is no attribute.attributeValues.valueType field in attribute.\n * There is an 'Oid32' type if attribute has objectIds property.\n * Doc: https://github.com/Esri/i3s-spec/blob/master/docs/1.6/attributeStorageInfo.cmn.md\n */\n private _getAttributeType(attribute: AttributeStorageInfo): string {\n if (attribute.attributeValues) {\n return attribute.attributeValues.valueType;\n } else if (attribute.objectIds) {\n return 'Oid32';\n }\n return '';\n }\n\n /**\n * Make simple arrays from attribute typed arrays.\n * @param attributesList\n */\n private _replaceNestedArrays(attributesList: FeatureAttribute[]): void {\n for (let index = 0; index < attributesList.length; index++) {\n const attributeObject = attributesList[index];\n\n for (const key in attributeObject) {\n attributeObject[key] = Array.from(attributeObject[key]);\n }\n }\n }\n\n /**\n * Print statistics in the end of conversion\n * @param params - output files data\n */\n private async _finishConversion(params: {\n slpk: boolean;\n outputPath: string;\n tilesetName: string;\n }): Promise<void> {\n const filesSize = await calculateFilesSize(params);\n const diff = process.hrtime(this.conversionStartTime);\n const conversionTime = timeConverter(diff);\n\n console.log(`------------------------------------------------`); // eslint-disable-line\n console.log(`Finish conversion of ${I3S}`); // eslint-disable-line\n console.log(`Total conversion time: ${conversionTime}`); // eslint-disable-line\n console.log(`Vertex count: `, this.vertexCounter); // eslint-disable-line\n console.log(`File(s) size: `, filesSize, ' bytes'); // eslint-disable-line\n console.log(`------------------------------------------------`); // eslint-disable-line\n }\n}\n"],"file":"3d-tiles-converter.js"}
@@ -149,7 +149,7 @@ export default class B3dmConverter {
149
149
  return 'image/png';
150
150
 
151
151
  default:
152
- console.warn(`Unexpected texture format in I3S: ${format}`);
152
+ console.warn("Unexpected texture format in I3S: ".concat(format));
153
153
  return 'image/jpeg';
154
154
  }
155
155
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/3d-tiles-converter/helpers/b3dm-converter.js"],"names":["encode","encodeSync","GLTFScenegraph","GLTFWriter","Tile3DWriter","ImageWriter","Matrix4","Vector3","Z_UP_TO_Y_UP_MATRIX","B3dmConverter","convert","i3sTile","attributes","gltf","buildGltf","b3dm","gltfEncoded","Uint8Array","type","featuresLength","_getFeaturesLength","batchTable","material","indices","originalIndices","cartesianOrigin","content","gltfBuilder","textureIndex","_addI3sTextureToGltf","pbrMaterialInfo","_convertI3sMaterialToGltfMaterial","materialIndex","addMaterial","positions","positionsValue","value","_normalizePositions","normals","_checkNormals","_generateSynteticIndices","length","size","meshIndex","addMesh","transformMatrix","_generateTransformMatrix","nodeIndex","addNode","matrix","sceneIndex","addScene","nodeIndices","setDefaultScene","createBinaryChunk","gltfBuffer","texture","header","textureFormat","selectedTexture","pbrMetallicRoughness","baseColorTexture","source","image","mimeType","_deduceMimeTypeFromFormat","imageBuffer","imageIndex","addImage","addTexture","colors","newPositionsValue","Float32Array","index","vertex","subarray","originVector","vertexVector","Array","from","subtract","set","translateOriginMatrix","translate","result","multiplyLeft","_generateBatchId","faceRanges","batchIdArraySize","batchId","rangeIndex","currentBatchId","fromIndex","untilPosition","fill","vertexCount","Uint32Array","format","console","warn","isTextureIndexExists","alphaMode","doubleSided","metallicFactor","roughnessFactor","texCoord","baseColorFactor","_setGltfTexture","materialDefinition","emissiveTexture","metallicRoughnessTexture","normalTexture","occlusionTexture","firstKey","Object","keys","find"],"mappings":"AAAA,SAAQA,MAAR,EAAgBC,UAAhB,QAAiC,kBAAjC;AACA,SAAQC,cAAR,EAAwBC,UAAxB,QAAyC,kBAAzC;AACA,SAAQC,YAAR,QAA2B,sBAA3B;AACA,SAAQC,WAAR,QAA0B,oBAA1B;AACA,SAAQC,OAAR,EAAiBC,OAAjB,QAA+B,eAA/B;AAEA,MAAMC,mBAAmB,GAAG,IAAIF,OAAJ,CAAY,CAAC,CAAD,EAAI,CAAJ,EAAO,CAAP,EAAU,CAAV,EAAa,CAAb,EAAgB,CAAhB,EAAmB,CAAC,CAApB,EAAuB,CAAvB,EAA0B,CAA1B,EAA6B,CAA7B,EAAgC,CAAhC,EAAmC,CAAnC,EAAsC,CAAtC,EAAyC,CAAzC,EAA4C,CAA5C,EAA+C,CAA/C,CAAZ,CAA5B;AAEA,eAAe,MAAMG,aAAN,CAAoB;AACpB,QAAPC,OAAO,CAACC,OAAD,EAAUC,UAAU,GAAG,IAAvB,EAA6B;AACxC,SAAKD,OAAL,GAAeA,OAAf;AACA,UAAME,IAAI,GAAG,MAAM,KAAKC,SAAL,CAAeH,OAAf,CAAnB;AACA,UAAMI,IAAI,GAAGd,UAAU,CACrB;AACEe,MAAAA,WAAW,EAAE,IAAIC,UAAJ,CAAeJ,IAAf,CADf;AAEEK,MAAAA,IAAI,EAAE,MAFR;AAGEC,MAAAA,cAAc,EAAE,KAAKC,kBAAL,CAAwBR,UAAxB,CAHlB;AAIES,MAAAA,UAAU,EAAET;AAJd,KADqB,EAOrBR,YAPqB,CAAvB;AASA,WAAOW,IAAP;AACD;;AAEc,QAATD,SAAS,CAACH,OAAD,EAAU;AACvB,UAAM;AAACW,MAAAA,QAAD;AAAWV,MAAAA,UAAX;AAAuBW,MAAAA,OAAO,EAAEC,eAAhC;AAAiDC,MAAAA;AAAjD,QAAoEd,OAAO,CAACe,OAAlF;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A,QAAQ,EAAE;AAF6C,OAAzD;AAID,KARM,MAQA,IAAIG,kBAAkB,CAACG,aAAvB,EAAsC;AAC3CzF,MAAAA,QAAQ,CAACyF,aAAT,GAAyB;AACvBtC,QAAAA,KAAK,EAAE7C,YADgB;AAEvB6E,QAAAA,QAAQ,EAAE;AAFa,OAAzB;AAID,KALM,MAKA,IAAIG,kBAAkB,CAACI,gBAAvB,EAAyC;AAC9C1F,MAAAA,QAAQ,CAAC0F,gBAAT,GAA4B;AAC1BvC,QAAAA,KAAK,EAAE7C,YADmB;AAE1B6E,QAAAA,QAAQ,EAAE;AAFgB,OAA5B;AAID;;AACD,WAAOnF,QAAP;AACD;;AAODF,EAAAA,kBAAkB,CAACR,UAAD,EAAa;AAC7B,QAAI,CAACA,UAAL,EAAiB;AACf,aAAO,CAAP;AACD;;AACD,UAAMqG,QAAQ,GAAGC,MAAM,CAACC,IAAP,CAAYvG,UAAZ,EAAwB,CAAxB,CAAjB;AACA,WAAOA,UAAU,CAACqG,QAAD,CAAV,CAAqBxE,MAA5B;AACD;;AAMDF,EAAAA,aAAa,CAACD,OAAD,EAAU;AAErB,WAAOA,OAAO,CAAC8E,IAAR,CAAchF,KAAD,IAAWA,KAAxB,CAAP;AACD;;AA/QgC","sourcesContent":["import {encode, encodeSync} from '@loaders.gl/core';\nimport {GLTFScenegraph, GLTFWriter} from '@loaders.gl/gltf';\nimport {Tile3DWriter} from '@loaders.gl/3d-tiles';\nimport {ImageWriter} from '@loaders.gl/images';\nimport {Matrix4, Vector3} from '@math.gl/core';\n\nconst Z_UP_TO_Y_UP_MATRIX = new Matrix4([1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1]);\n\nexport default class B3dmConverter {\n async convert(i3sTile, attributes = null) {\n this.i3sTile = i3sTile;\n const gltf = await this.buildGltf(i3sTile);\n const b3dm = encodeSync(\n {\n gltfEncoded: new Uint8Array(gltf),\n type: 'b3dm',\n featuresLength: this._getFeaturesLength(attributes),\n batchTable: attributes\n },\n Tile3DWriter\n );\n return b3dm;\n }\n\n async buildGltf(i3sTile) {\n const {material, attributes, indices: originalIndices, cartesianOrigin} = i3sTile.content;\n const gltfBuilder = new GLTFScenegraph();\n\n const textureIndex = await this._addI3sTextureToGltf(i3sTile, gltfBuilder);\n const pbrMaterialInfo = this._convertI3sMaterialToGltfMaterial(material, textureIndex);\n const materialIndex = gltfBuilder.addMaterial(pbrMaterialInfo);\n\n const positions = attributes.positions;\n const positionsValue = positions.value;\n attributes.positions.value = this._normalizePositions(positionsValue, cartesianOrigin);\n if (attributes.normals && !this._checkNormals(attributes.normals.value)) {\n delete attributes.normals;\n }\n const indices =\n originalIndices || this._generateSynteticIndices(positionsValue.length / positions.size);\n const meshIndex = gltfBuilder.addMesh({\n attributes,\n indices,\n material: materialIndex\n });\n const transformMatrix = this._generateTransformMatrix(cartesianOrigin);\n const nodeIndex = gltfBuilder.addNode({meshIndex, matrix: transformMatrix});\n const sceneIndex = gltfBuilder.addScene({nodeIndices: [nodeIndex]});\n gltfBuilder.setDefaultScene(sceneIndex);\n\n gltfBuilder.createBinaryChunk();\n\n const gltfBuffer = encodeSync(gltfBuilder.gltf, GLTFWriter);\n\n return gltfBuffer;\n }\n\n /**\n * Update gltfBuilder with texture from I3S tile\n * @param {object} i3sTile - Tile3D object\n * @param {GLTFScenegraph} gltfBuilder - gltfScenegraph instance to construct GLTF\n * @returns {Promise<number | null>} - GLTF texture index\n */\n async _addI3sTextureToGltf(i3sTile, gltfBuilder) {\n const {\n content: {texture, material, attributes},\n header: {textureFormat}\n } = i3sTile;\n let textureIndex = null;\n let selectedTexture = texture;\n if (!texture && material) {\n selectedTexture =\n material.pbrMetallicRoughness &&\n material.pbrMetallicRoughness.baseColorTexture &&\n material.pbrMetallicRoughness.baseColorTexture.texture.source.image;\n }\n if (selectedTexture) {\n const mimeType = this._deduceMimeTypeFromFormat(textureFormat);\n const imageBuffer = await encode(selectedTexture, ImageWriter);\n const imageIndex = gltfBuilder.addImage(imageBuffer, mimeType);\n textureIndex = gltfBuilder.addTexture({imageIndex});\n delete attributes.colors;\n }\n return textureIndex;\n }\n\n /**\n * Generate a positions array which is correct for 3DTiles/GLTF format\n * @param {Float64Array} positionsValue - the input geometry positions array\n * @param {number[]} cartesianOrigin - the tile center in the cartesian coordinate system\n * @returns {Float32Array} - the output geometry positions array\n */\n _normalizePositions(positionsValue, cartesianOrigin) {\n const newPositionsValue = new Float32Array(positionsValue.length);\n for (let index = 0; index < positionsValue.length; index += 3) {\n const vertex = positionsValue.subarray(index, index + 3);\n const originVector = new Vector3(cartesianOrigin);\n let vertexVector = new Vector3(Array.from(vertex));\n vertexVector = vertexVector.subtract(originVector);\n newPositionsValue.set(vertexVector, index);\n }\n return newPositionsValue;\n }\n\n /**\n * Generate the transformation matrix for GLTF node:\n * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-node\n * 1. Create the translate transformation from cartesianOrigin (the positions array stores offsets from this cartesianOrigin)\n * 2. Create the rotation transformation to rotate model from z-up coordinates (I3S specific) to y-up coordinates (GLTF specific)\n * @param {number[]} cartesianOrigin - the tile center in the cartesian coordinate system\n * @returns {Matrix4} - an array of 16 numbers (4x4 matrix)\n */\n _generateTransformMatrix(cartesianOrigin) {\n const translateOriginMatrix = new Matrix4().translate(cartesianOrigin);\n const result = translateOriginMatrix.multiplyLeft(Z_UP_TO_Y_UP_MATRIX);\n return result;\n }\n\n /**\n * Generate batchId attribute from faceRanges.\n * @param {Uint32Array} faceRanges - the source array\n * @returns {Float32Array} batchId list.\n */\n _generateBatchId(faceRanges) {\n const batchIdArraySize = (faceRanges[faceRanges.length - 1] + 1) * 3;\n const batchId = new Float32Array(batchIdArraySize);\n let rangeIndex = 0;\n let currentBatchId = 0;\n\n for (let index = 0; index < faceRanges.length / 2; index++) {\n const fromIndex = faceRanges[rangeIndex] * 3;\n const untilPosition = (faceRanges[rangeIndex + 1] + 1) * 3;\n\n batchId.fill(currentBatchId, fromIndex, untilPosition);\n rangeIndex += 2;\n currentBatchId += 1;\n }\n return batchId;\n }\n\n /**\n * luma.gl can not work without indices now:\n * https://github.com/visgl/luma.gl/blob/d8cad75b9f8ca3e578cf078ed9d19e619c2ddbc9/modules/experimental/src/gltf/gltf-instantiator.js#L115\n * This method generates syntetic indices array: [0, 1, 2, 3, .... , vertexCount-1]\n * @param {number} vertexCount - vertex count in the geometry\n * @returns {Uint32Array} indices array.\n */\n _generateSynteticIndices(vertexCount) {\n const result = new Uint32Array(vertexCount);\n for (let index = 0; index < vertexCount; index++) {\n result.set([index], index);\n }\n return result;\n }\n\n /**\n * Deduce mime type by format from `textureSetDefinition.formats[0].format`\n * https://github.com/Esri/i3s-spec/blob/master/docs/1.7/textureSetDefinitionFormat.cmn.md\n * @param {string} format - format name\n * @returns {string} mime type.\n */\n _deduceMimeTypeFromFormat(format) {\n switch (format) {\n case 'jpg':\n return 'image/jpeg';\n case 'png':\n return 'image/png';\n default:\n console.warn(`Unexpected texture format in I3S: ${format}`); // eslint-disable-line no-console, no-undef\n return 'image/jpeg';\n }\n }\n\n /**\n * Convert i3s material to GLTF compatible material\n * @param {object} material - i3s material definition\n * @param {number | null} textureIndex - texture index in GLTF\n * @returns {object} GLTF material\n */\n _convertI3sMaterialToGltfMaterial(material, textureIndex) {\n const isTextureIndexExists = textureIndex !== null;\n\n if (!material) {\n material = {\n alphaMode: 'OPAQUE',\n doubleSided: false,\n pbrMetallicRoughness: {\n metallicFactor: 0,\n roughnessFactor: 1\n }\n };\n\n if (isTextureIndexExists) {\n material.pbrMetallicRoughness.baseColorTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else {\n material.pbrMetallicRoughness.baseColorFactor = [1, 1, 1, 1];\n }\n\n return material;\n }\n\n if (textureIndex !== null) {\n material = this._setGltfTexture(material, textureIndex);\n }\n\n return material;\n }\n\n /**\n * Set texture properties in material with GLTF textureIndex\n * @param {object} materialDefinition - i3s material definition\n * @param {number} textureIndex - texture index in GLTF\n * @returns {void}\n */\n _setGltfTexture(materialDefinition, textureIndex) {\n const material = {\n ...materialDefinition,\n pbrMetallicRoughness: {...materialDefinition.pbrMetallicRoughness}\n };\n // I3SLoader now support loading only one texture. This elseif sequence will assign this texture to one of\n // properties defined in materialDefinition\n if (\n materialDefinition.pbrMetallicRoughness &&\n materialDefinition.pbrMetallicRoughness.baseColorTexture\n ) {\n material.pbrMetallicRoughness.baseColorTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else if (materialDefinition.emissiveTexture) {\n material.emissiveTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else if (\n materialDefinition.pbrMetallicRoughness &&\n materialDefinition.pbrMetallicRoughness.metallicRoughnessTexture\n ) {\n material.pbrMetallicRoughness.metallicRoughnessTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else if (materialDefinition.normalTexture) {\n material.normalTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else if (materialDefinition.occlusionTexture) {\n material.occlusionTexture = {\n index: textureIndex,\n texCoord: 0\n };\n }\n return material;\n }\n\n /*\n * Returns Features length based on attribute array in attribute object.\n * @param {Object} attributes\n * @returns {Number} Features length .\n */\n _getFeaturesLength(attributes) {\n if (!attributes) {\n return 0;\n }\n const firstKey = Object.keys(attributes)[0];\n return attributes[firstKey].length;\n }\n\n /* Checks that normals buffer is correct\n * @param {TypedArray} normals\n * @returns {boolean} true - normals are correct; false - normals are incorrect\n */\n _checkNormals(normals) {\n // If all normals === 0, the resulting tileset is all in black colors on Cesium\n return normals.find((value) => value);\n }\n}\n"],"file":"b3dm-converter.js"}
1
+ {"version":3,"sources":["../../../../src/3d-tiles-converter/helpers/b3dm-converter.js"],"names":["encode","encodeSync","GLTFScenegraph","GLTFWriter","Tile3DWriter","ImageWriter","Matrix4","Vector3","Z_UP_TO_Y_UP_MATRIX","B3dmConverter","convert","i3sTile","attributes","gltf","buildGltf","b3dm","gltfEncoded","Uint8Array","type","featuresLength","_getFeaturesLength","batchTable","material","indices","originalIndices","cartesianOrigin","content","gltfBuilder","textureIndex","_addI3sTextureToGltf","pbrMaterialInfo","_convertI3sMaterialToGltfMaterial","materialIndex","addMaterial","positions","positionsValue","value","_normalizePositions","normals","_checkNormals","_generateSynteticIndices","length","size","meshIndex","addMesh","transformMatrix","_generateTransformMatrix","nodeIndex","addNode","matrix","sceneIndex","addScene","nodeIndices","setDefaultScene","createBinaryChunk","gltfBuffer","texture","header","textureFormat","selectedTexture","pbrMetallicRoughness","baseColorTexture","source","image","mimeType","_deduceMimeTypeFromFormat","imageBuffer","imageIndex","addImage","addTexture","colors","newPositionsValue","Float32Array","index","vertex","subarray","originVector","vertexVector","Array","from","subtract","set","translateOriginMatrix","translate","result","multiplyLeft","_generateBatchId","faceRanges","batchIdArraySize","batchId","rangeIndex","currentBatchId","fromIndex","untilPosition","fill","vertexCount","Uint32Array","format","console","warn","isTextureIndexExists","alphaMode","doubleSided","metallicFactor","roughnessFactor","texCoord","baseColorFactor","_setGltfTexture","materialDefinition","emissiveTexture","metallicRoughnessTexture","normalTexture","occlusionTexture","firstKey","Object","keys","find"],"mappings":"AAAA,SAAQA,MAAR,EAAgBC,UAAhB,QAAiC,kBAAjC;AACA,SAAQC,cAAR,EAAwBC,UAAxB,QAAyC,kBAAzC;AACA,SAAQC,YAAR,QAA2B,sBAA3B;AACA,SAAQC,WAAR,QAA0B,oBAA1B;AACA,SAAQC,OAAR,EAAiBC,OAAjB,QAA+B,eAA/B;AAEA,MAAMC,mBAAmB,GAAG,IAAIF,OAAJ,CAAY,CAAC,CAAD,EAAI,CAAJ,EAAO,CAAP,EAAU,CAAV,EAAa,CAAb,EAAgB,CAAhB,EAAmB,CAAC,CAApB,EAAuB,CAAvB,EAA0B,CAA1B,EAA6B,CAA7B,EAAgC,CAAhC,EAAmC,CAAnC,EAAsC,CAAtC,EAAyC,CAAzC,EAA4C,CAA5C,EAA+C,CAA/C,CAAZ,CAA5B;AAEA,eAAe,MAAMG,aAAN,CAAoB;AACpB,QAAPC,OAAO,CAACC,OAAD,EAAUC,UAAU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,CAACD,OAAD,EAAU;AAErB,WAAOA,OAAO,CAAC8E,IAAR,CAAchF,KAAD,IAAWA,KAAxB,CAAP;AACD;;AA/QgC","sourcesContent":["import {encode, encodeSync} from '@loaders.gl/core';\nimport {GLTFScenegraph, GLTFWriter} from '@loaders.gl/gltf';\nimport {Tile3DWriter} from '@loaders.gl/3d-tiles';\nimport {ImageWriter} from '@loaders.gl/images';\nimport {Matrix4, Vector3} from '@math.gl/core';\n\nconst Z_UP_TO_Y_UP_MATRIX = new Matrix4([1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1]);\n\nexport default class B3dmConverter {\n async convert(i3sTile, attributes = null) {\n this.i3sTile = i3sTile;\n const gltf = await this.buildGltf(i3sTile);\n const b3dm = encodeSync(\n {\n gltfEncoded: new Uint8Array(gltf),\n type: 'b3dm',\n featuresLength: this._getFeaturesLength(attributes),\n batchTable: attributes\n },\n Tile3DWriter\n );\n return b3dm;\n }\n\n async buildGltf(i3sTile) {\n const {material, attributes, indices: originalIndices, cartesianOrigin} = i3sTile.content;\n const gltfBuilder = new GLTFScenegraph();\n\n const textureIndex = await this._addI3sTextureToGltf(i3sTile, gltfBuilder);\n const pbrMaterialInfo = this._convertI3sMaterialToGltfMaterial(material, textureIndex);\n const materialIndex = gltfBuilder.addMaterial(pbrMaterialInfo);\n\n const positions = attributes.positions;\n const positionsValue = positions.value;\n attributes.positions.value = this._normalizePositions(positionsValue, cartesianOrigin);\n if (attributes.normals && !this._checkNormals(attributes.normals.value)) {\n delete attributes.normals;\n }\n const indices =\n originalIndices || this._generateSynteticIndices(positionsValue.length / positions.size);\n const meshIndex = gltfBuilder.addMesh({\n attributes,\n indices,\n material: materialIndex\n });\n const transformMatrix = this._generateTransformMatrix(cartesianOrigin);\n const nodeIndex = gltfBuilder.addNode({meshIndex, matrix: transformMatrix});\n const sceneIndex = gltfBuilder.addScene({nodeIndices: [nodeIndex]});\n gltfBuilder.setDefaultScene(sceneIndex);\n\n gltfBuilder.createBinaryChunk();\n\n const gltfBuffer = encodeSync(gltfBuilder.gltf, GLTFWriter);\n\n return gltfBuffer;\n }\n\n /**\n * Update gltfBuilder with texture from I3S tile\n * @param {object} i3sTile - Tile3D object\n * @param {GLTFScenegraph} gltfBuilder - gltfScenegraph instance to construct GLTF\n * @returns {Promise<number | null>} - GLTF texture index\n */\n async _addI3sTextureToGltf(i3sTile, gltfBuilder) {\n const {\n content: {texture, material, attributes},\n header: {textureFormat}\n } = i3sTile;\n let textureIndex = null;\n let selectedTexture = texture;\n if (!texture && material) {\n selectedTexture =\n material.pbrMetallicRoughness &&\n material.pbrMetallicRoughness.baseColorTexture &&\n material.pbrMetallicRoughness.baseColorTexture.texture.source.image;\n }\n if (selectedTexture) {\n const mimeType = this._deduceMimeTypeFromFormat(textureFormat);\n const imageBuffer = await encode(selectedTexture, ImageWriter);\n const imageIndex = gltfBuilder.addImage(imageBuffer, mimeType);\n textureIndex = gltfBuilder.addTexture({imageIndex});\n delete attributes.colors;\n }\n return textureIndex;\n }\n\n /**\n * Generate a positions array which is correct for 3DTiles/GLTF format\n * @param {Float64Array} positionsValue - the input geometry positions array\n * @param {number[]} cartesianOrigin - the tile center in the cartesian coordinate system\n * @returns {Float32Array} - the output geometry positions array\n */\n _normalizePositions(positionsValue, cartesianOrigin) {\n const newPositionsValue = new Float32Array(positionsValue.length);\n for (let index = 0; index < positionsValue.length; index += 3) {\n const vertex = positionsValue.subarray(index, index + 3);\n const originVector = new Vector3(cartesianOrigin);\n let vertexVector = new Vector3(Array.from(vertex));\n vertexVector = vertexVector.subtract(originVector);\n newPositionsValue.set(vertexVector, index);\n }\n return newPositionsValue;\n }\n\n /**\n * Generate the transformation matrix for GLTF node:\n * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-node\n * 1. Create the translate transformation from cartesianOrigin (the positions array stores offsets from this cartesianOrigin)\n * 2. Create the rotation transformation to rotate model from z-up coordinates (I3S specific) to y-up coordinates (GLTF specific)\n * @param {number[]} cartesianOrigin - the tile center in the cartesian coordinate system\n * @returns {Matrix4} - an array of 16 numbers (4x4 matrix)\n */\n _generateTransformMatrix(cartesianOrigin) {\n const translateOriginMatrix = new Matrix4().translate(cartesianOrigin);\n const result = translateOriginMatrix.multiplyLeft(Z_UP_TO_Y_UP_MATRIX);\n return result;\n }\n\n /**\n * Generate batchId attribute from faceRanges.\n * @param {Uint32Array} faceRanges - the source array\n * @returns {Float32Array} batchId list.\n */\n _generateBatchId(faceRanges) {\n const batchIdArraySize = (faceRanges[faceRanges.length - 1] + 1) * 3;\n const batchId = new Float32Array(batchIdArraySize);\n let rangeIndex = 0;\n let currentBatchId = 0;\n\n for (let index = 0; index < faceRanges.length / 2; index++) {\n const fromIndex = faceRanges[rangeIndex] * 3;\n const untilPosition = (faceRanges[rangeIndex + 1] + 1) * 3;\n\n batchId.fill(currentBatchId, fromIndex, untilPosition);\n rangeIndex += 2;\n currentBatchId += 1;\n }\n return batchId;\n }\n\n /**\n * luma.gl can not work without indices now:\n * https://github.com/visgl/luma.gl/blob/d8cad75b9f8ca3e578cf078ed9d19e619c2ddbc9/modules/experimental/src/gltf/gltf-instantiator.js#L115\n * This method generates syntetic indices array: [0, 1, 2, 3, .... , vertexCount-1]\n * @param {number} vertexCount - vertex count in the geometry\n * @returns {Uint32Array} indices array.\n */\n _generateSynteticIndices(vertexCount) {\n const result = new Uint32Array(vertexCount);\n for (let index = 0; index < vertexCount; index++) {\n result.set([index], index);\n }\n return result;\n }\n\n /**\n * Deduce mime type by format from `textureSetDefinition.formats[0].format`\n * https://github.com/Esri/i3s-spec/blob/master/docs/1.7/textureSetDefinitionFormat.cmn.md\n * @param {string} format - format name\n * @returns {string} mime type.\n */\n _deduceMimeTypeFromFormat(format) {\n switch (format) {\n case 'jpg':\n return 'image/jpeg';\n case 'png':\n return 'image/png';\n default:\n console.warn(`Unexpected texture format in I3S: ${format}`); // eslint-disable-line no-console, no-undef\n return 'image/jpeg';\n }\n }\n\n /**\n * Convert i3s material to GLTF compatible material\n * @param {object} material - i3s material definition\n * @param {number | null} textureIndex - texture index in GLTF\n * @returns {object} GLTF material\n */\n _convertI3sMaterialToGltfMaterial(material, textureIndex) {\n const isTextureIndexExists = textureIndex !== null;\n\n if (!material) {\n material = {\n alphaMode: 'OPAQUE',\n doubleSided: false,\n pbrMetallicRoughness: {\n metallicFactor: 0,\n roughnessFactor: 1\n }\n };\n\n if (isTextureIndexExists) {\n material.pbrMetallicRoughness.baseColorTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else {\n material.pbrMetallicRoughness.baseColorFactor = [1, 1, 1, 1];\n }\n\n return material;\n }\n\n if (textureIndex !== null) {\n material = this._setGltfTexture(material, textureIndex);\n }\n\n return material;\n }\n\n /**\n * Set texture properties in material with GLTF textureIndex\n * @param {object} materialDefinition - i3s material definition\n * @param {number} textureIndex - texture index in GLTF\n * @returns {void}\n */\n _setGltfTexture(materialDefinition, textureIndex) {\n const material = {\n ...materialDefinition,\n pbrMetallicRoughness: {...materialDefinition.pbrMetallicRoughness}\n };\n // I3SLoader now support loading only one texture. This elseif sequence will assign this texture to one of\n // properties defined in materialDefinition\n if (\n materialDefinition.pbrMetallicRoughness &&\n materialDefinition.pbrMetallicRoughness.baseColorTexture\n ) {\n material.pbrMetallicRoughness.baseColorTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else if (materialDefinition.emissiveTexture) {\n material.emissiveTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else if (\n materialDefinition.pbrMetallicRoughness &&\n materialDefinition.pbrMetallicRoughness.metallicRoughnessTexture\n ) {\n material.pbrMetallicRoughness.metallicRoughnessTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else if (materialDefinition.normalTexture) {\n material.normalTexture = {\n index: textureIndex,\n texCoord: 0\n };\n } else if (materialDefinition.occlusionTexture) {\n material.occlusionTexture = {\n index: textureIndex,\n texCoord: 0\n };\n }\n return material;\n }\n\n /*\n * Returns Features length based on attribute array in attribute object.\n * @param {Object} attributes\n * @returns {Number} Features length .\n */\n _getFeaturesLength(attributes) {\n if (!attributes) {\n return 0;\n }\n const firstKey = Object.keys(attributes)[0];\n return attributes[firstKey].length;\n }\n\n /* Checks that normals buffer is correct\n * @param {TypedArray} normals\n * @returns {boolean} true - normals are correct; false - normals are incorrect\n */\n _checkNormals(normals) {\n // If all normals === 0, the resulting tileset is all in black colors on Cesium\n return normals.find((value) => value);\n }\n}\n"],"file":"b3dm-converter.js"}
@@ -487,7 +487,7 @@ function generateImageId(texture, nodeId) {
487
487
  const shiftedWidth = width - 1 << 12;
488
488
  const shiftedHeight = height - 1 << 0;
489
489
  const leftHalf = shiftedLevelCountOfTexture + shiftedIndexOfLevel + shiftedWidth + shiftedHeight;
490
- const imageId = BigInt(`0b${leftHalf.toString(2)}${rightHalf}`);
490
+ const imageId = BigInt("0b".concat(leftHalf.toString(2)).concat(rightHalf));
491
491
  return imageId.toString();
492
492
  }
493
493
 
@@ -599,7 +599,7 @@ function generateStringAttributeBuffer(batchAttributes) {
599
599
  const stringBufferArray = [];
600
600
 
601
601
  for (let index = 0; index < batchAttributes.length; index++) {
602
- const currentString = `${String(batchAttributes[index])}\0`;
602
+ const currentString = "".concat(String(batchAttributes[index]), "\0");
603
603
  const currentStringBuffer = Buffer.from(currentString);
604
604
  const currentStringSize = currentStringBuffer.length;
605
605
  totalNumberOfBytes += currentStringSize;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/i3s-converter/helpers/geometry-converter.js"],"names":["Vector3","Matrix4","Vector4","Ellipsoid","DracoWriter","encode","assert","concatenateArrayBuffers","concatenateTypedArrays","md5","generateAttributes","VALUES_PER_VERTEX","VALUES_PER_TEX_COORD","VALUES_PER_COLOR_ELEMENT","STRING_TYPE","SHORT_INT_TYPE","DOUBLE_TYPE","OBJECT_ID_TYPE","BATCHED_ID_POSSIBLE_ATTRIBUTE_NAMES","convertB3dmToI3sGeometry","tileContent","nodeId","featuresHashArray","attributeStorageInfo","draco","materialAndTextureList","convertMaterials","convertedAttributesMap","convertAttributes","has","push","material","getDefaultMaterial","result","nodesCounter","i","gltf","materials","length","sourceMaterial","id","convertedAttributes","get","texture","_makeNodeResources","vertexCount","positions","triangleCount","faceRange","featureIds","normals","colors","texCoords","featureCount","batchTableJson","makeFeatureIdsUnique","featureIndices","header","Uint32Array","typedFeatureIds","generateBigUint64Array","set","fileBuffer","Uint8Array","buffer","ArrayBuffer","compressedGeometry","generateCompressedGeometry","Float32Array","attributes","convertBatchTableToAttributeBuffers","geometry","sharedResources","getSharedResources","meshMaterial","attributesMap","Map","nodes","scene","convertNodes","attrKey","keys","delete","index","reduce","acc","value","concat","matrix","node","convertNode","nodeMatrix","compositeMatrix","multiplyRight","mesh","convertMesh","children","content","primitive","primitives","outputAttributes","transformVertexArray","vertices","POSITION","cartographicOrigin","cartesianModelMatrix","indices","attributeSpecificTransformation","transformVertexPositions","NORMAL","transformVertexNormals","flattenTexCoords","TEXCOORD_0","flattenColors","COLOR_0","flattenBatchIds","getBatchIdsByAttributeName","args","newVertices","coordIndex","vertex","subarray","vertexVector","Array","from","x","y","z","calleeArgs","transform","WGS84","cartesianToCartographic","subtract","transformAsVector","newTexCoords","texCoord","colorsAttribute","components","newColors","colorIndex","color","colorUint8","j","batchedIds","newBatchIds","batchIds","possibleBatchIdAttributeName","sourceMaterials","convertMaterial","doubleSided","emissiveFactor","map","c","Math","round","alphaMode","toLowerCase","pbrMetallicRoughness","roughnessFactor","metallicFactor","baseColorTexture","source","textureSetDefinitionId","emissiveTexture","baseColorFactor","undefined","gltfMaterials","i3sResources","materialDefinitionInfos","gltfMaterial","materialDefinitionInfo","textureDefinitionInfo","convertGLTFMaterialToI3sSharedResources","textureDefinitionInfos","extractSharedResourcesTextureInfo","colorFactor","extractSharedResourcesMaterialInfo","matDielectricColorComponent","black","unitVector","dielectricSpecular","baseColorVector","firstOperand","multiply","diffuse","lerp","specular","toArray","encoding","mimeType","images","generateImageId","size","image","width","data","height","levelCountOfTexture","indexOfLevel","indexOfTextureInStore","zerosCount","toString","rightHalf","repeat","shiftedLevelCountOfTexture","shiftedIndexOfLevel","shiftedWidth","shiftedHeight","leftHalf","imageId","BigInt","batchTable","replaceMap","getFeaturesReplaceMap","replaceIndicesByUnique","featureMap","oldFeatureId","uniqueFeatureId","getOrCreateUniqueFeatureId","generateStringFromBatchTableByIndex","str","key","batchTableStr","hash","includes","indexOf","indicesArray","attributeBuffers","batchTableWithFeatureIds","OBJECTID","type","getAttributeType","attributeBuffer","generateShortIntegerAttributeBuffer","generateDoubleAttributeBuffer","generateStringAttributeBuffer","attribute","find","attr","name","attributeValues","valueType","count","valuesArray","padding","Float64Array","batchAttributes","stringCountArray","totalNumberOfBytes","stringSizesArray","stringBufferArray","currentString","String","currentStringBuffer","Buffer","currentStringSize","totalBytes","BigUint64Array","featureIndex","generateFeatureIndexAttribute","compressedAttributes","attributesMetadata","Int32Array","method","orderedFeatureIndices","fillIndex","startIndex","endIndex","fill"],"mappings":"AAAA,SAAQA,OAAR,EAAiBC,OAAjB,EAA0BC,OAA1B,QAAwC,eAAxC;AACA,SAAQC,SAAR,QAAwB,qBAAxB;AAEA,SAAQC,WAAR,QAA0B,mBAA1B;AACA,SAAQC,MAAR,EAAgBC,MAAhB,QAA6B,kBAA7B;AACA,SAAQC,uBAAR,EAAiCC,sBAAjC,QAA8D,0BAA9D;AACA,OAAOC,GAAP,MAAgB,KAAhB;AACA,SAAQC,kBAAR,QAAiC,uBAAjC;AAEA,MAAMC,iBAAiB,GAAG,CAA1B;AACA,MAAMC,oBAAoB,GAAG,CAA7B;AACA,MAAMC,wBAAwB,GAAG,CAAjC;AAEA,MAAMC,WAAW,GAAG,QAApB;AACA,MAAMC,cAAc,GAAG,OAAvB;AACA,MAAMC,WAAW,GAAG,SAApB;AACA,MAAMC,cAAc,GAAG,OAAvB;AAMA,MAAMC,mCAAmC,GAAG,CAAC,oBAAD,EAAuB,UAAvB,EAAmC,SAAnC,CAA5C;AAEA,eAAe,eAAeC,wBAAf,CACbC,WADa,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GAAmB,CAApB,IAAyBxE,iBAA1C;AAEA6P,IAAAA,qBAAqB,CAACI,IAAtB,CAA2BH,SAA3B,EAAsCC,UAAtC,EAAkDC,QAAlD;AAEAF,IAAAA,SAAS;AACTC,IAAAA,UAAU,GAAGC,QAAQ,GAAG,CAAxB;AACD;;AAED,SAAOH,qBAAP;AACD","sourcesContent":["import {Vector3, Matrix4, Vector4} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\n\nimport {DracoWriter} from '@loaders.gl/draco';\nimport {encode, assert} from '@loaders.gl/core';\nimport {concatenateArrayBuffers, concatenateTypedArrays} from '@loaders.gl/loader-utils';\nimport md5 from 'md5';\nimport {generateAttributes} from './geometry-attributes';\n\nconst VALUES_PER_VERTEX = 3;\nconst VALUES_PER_TEX_COORD = 2;\nconst VALUES_PER_COLOR_ELEMENT = 4;\n\nconst STRING_TYPE = 'string';\nconst SHORT_INT_TYPE = 'Int32';\nconst DOUBLE_TYPE = 'Float64';\nconst OBJECT_ID_TYPE = 'Oid32';\n/*\n * 'CUSTOM_ATTRIBUTE_2' - Attribute name which includes batch info and used by New York map.\n * _BATCHID - Default attribute name which includes batch info.\n * BATCHID - Legacy attribute name which includes batch info.\n */\nconst BATCHED_ID_POSSIBLE_ATTRIBUTE_NAMES = ['CUSTOM_ATTRIBUTE_2', '_BATCHID', 'BATCHID'];\n\nexport default async function convertB3dmToI3sGeometry(\n tileContent,\n nodeId,\n featuresHashArray,\n attributeStorageInfo,\n draco\n) {\n const materialAndTextureList = convertMaterials(tileContent);\n const convertedAttributesMap = convertAttributes(tileContent);\n\n if (convertedAttributesMap.has('default')) {\n materialAndTextureList.push({\n material: getDefaultMaterial()\n });\n }\n\n const result = [];\n let nodesCounter = nodeId;\n for (let i = 0; i < (tileContent.gltf.materials.length || 1); i++) {\n const sourceMaterial = tileContent.gltf.materials[i] || {id: 'default'};\n if (!convertedAttributesMap.has(sourceMaterial.id)) {\n continue; // eslint-disable-line no-continue\n }\n const convertedAttributes = convertedAttributesMap.get(sourceMaterial.id);\n const {material, texture} = materialAndTextureList[i];\n result.push(\n await _makeNodeResources({\n convertedAttributes,\n material,\n texture,\n tileContent,\n nodeId: nodesCounter,\n featuresHashArray,\n attributeStorageInfo,\n draco\n })\n );\n nodesCounter++;\n }\n\n return result;\n}\n\nasync function _makeNodeResources({\n convertedAttributes,\n material,\n texture,\n tileContent,\n nodeId,\n featuresHashArray,\n attributeStorageInfo,\n draco\n}) {\n const vertexCount = convertedAttributes.positions.length / VALUES_PER_VERTEX;\n const triangleCount = vertexCount / 3;\n const {faceRange, featureIds, positions, normals, colors, texCoords, featureCount} =\n generateAttributes({triangleCount, ...convertedAttributes});\n\n if (tileContent.batchTableJson) {\n makeFeatureIdsUnique(\n featureIds,\n convertedAttributes.featureIndices,\n featuresHashArray,\n tileContent.batchTableJson\n );\n }\n\n const header = new Uint32Array(2);\n const typedFeatureIds = generateBigUint64Array(featureIds);\n\n header.set([vertexCount, featureCount], 0);\n const fileBuffer = new Uint8Array(\n concatenateArrayBuffers(\n header.buffer,\n positions.buffer,\n normals.buffer,\n texture ? texCoords.buffer : new ArrayBuffer(0),\n colors.buffer,\n typedFeatureIds.buffer,\n faceRange.buffer\n )\n );\n const compressedGeometry = draco\n ? await generateCompressedGeometry(vertexCount, convertedAttributes, {\n positions,\n normals,\n texCoords: texture ? texCoords : new Float32Array(0),\n colors,\n featureIds,\n faceRange\n })\n : null;\n\n const attributes = convertBatchTableToAttributeBuffers(\n tileContent.batchTableJson,\n featureIds,\n attributeStorageInfo\n );\n\n return {\n geometry: fileBuffer,\n compressedGeometry,\n texture,\n sharedResources: getSharedResources(tileContent, nodeId),\n meshMaterial: material,\n vertexCount,\n attributes,\n featureCount\n };\n}\n\n/**\n * Convert attributes from the gltf nodes tree to i3s plain geometry\n * @param {Object} tileContent - 3d tile content\n * @returns {Map}\n * Map<{\n * positions: Float32Array,\n * normals: Float32Array,\n * colors: Uint8Array,\n * texCoords: Float32Array\n * }>\n * @todo implement colors support (if applicable for gltf format)\n */\nfunction convertAttributes(tileContent) {\n const attributesMap = new Map();\n\n for (const material of tileContent.gltf.materials || [{id: 'default'}]) {\n attributesMap.set(material.id, {\n positions: new Float32Array(0),\n normals: new Float32Array(0),\n texCoords: new Float32Array(0),\n colors: new Uint8Array(0),\n featureIndices: []\n });\n }\n\n const nodes = tileContent.gltf.scene.nodes;\n convertNodes(nodes, tileContent, attributesMap);\n\n for (const attrKey of attributesMap.keys()) {\n const attributes = attributesMap.get(attrKey);\n if (attributes.positions.length === 0) {\n attributesMap.delete(attrKey);\n continue; // eslint-disable-line no-continue\n }\n const vertexCount = attributes.positions.length / VALUES_PER_VERTEX;\n if (!attributes.colors.length) {\n attributes.colors = new Uint8Array(vertexCount * VALUES_PER_COLOR_ELEMENT);\n for (let index = 0; index < attributes.colors.length; index += 4) {\n attributes.colors.set([255, 255, 255, 255], index);\n }\n }\n if (!attributes.texCoords.length) {\n attributes.texCoords = new Float32Array(vertexCount * VALUES_PER_TEX_COORD);\n for (let index = 0; index < attributes.texCoords.length; index += 2) {\n attributes.texCoords.set([1, 1], index);\n }\n }\n attributes.featureIndices = attributes.featureIndices.reduce((acc, value) => acc.concat(value));\n }\n\n return attributesMap;\n}\n\n/**\n * Gltf has hierarchical structure of nodes. This function converts nodes starting from those which are in gltf scene object.\n * The goal is applying tranformation matrix for all children. Functions \"convertNodes\" and \"convertNode\" work together recursively.\n * @param {Object[]} nodes - gltf nodes array\n * @param {Object} tileContent - 3d tile content\n * @param {Map} attributesMap Map<{positions: Float32Array, normals: Float32Array, texCoords: Float32Array, colors: UInt8Array, featureIndices: Array}> - for recursive concatenation of\n * attributes\n * @param {Matrix4} matrix - transformation matrix - cumulative transformation matrix formed from all parent node matrices\n * @returns {void}\n */\nfunction convertNodes(\n nodes,\n tileContent,\n attributesMap,\n matrix = new Matrix4([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])\n) {\n if (nodes) {\n for (const node of nodes) {\n convertNode(node, tileContent, attributesMap, matrix);\n }\n }\n}\n\n/**\n * Convert all primitives of node and all children nodes\n * @param {Object} node - gltf node\n * @param {Object} tileContent - 3d tile content\n * @param {Map} attributesMap Map<{positions: Float32Array, normals: Float32Array, texCoords: Float32Array, colors: Uint8Array, featureIndices: Array}> - for recursive concatenation of\n * attributes\n * @param {Matrix4} matrix - transformation matrix - cumulative transformation matrix formed from all parent node matrices\n * @todo: optimize arrays concatenation\n */\nfunction convertNode(\n node,\n tileContent,\n attributesMap,\n matrix = new Matrix4([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])\n) {\n const nodeMatrix = node.matrix;\n const compositeMatrix = nodeMatrix ? matrix.multiplyRight(nodeMatrix) : matrix;\n\n const mesh = node.mesh;\n if (mesh) {\n convertMesh(mesh, tileContent, attributesMap, compositeMatrix);\n }\n\n convertNodes(node.children, tileContent, attributesMap, compositeMatrix);\n}\n\n/**\n * Convert all primitives of node and all children nodes\n * @param {Object} mesh - gltf node\n * @param {Object} content - 3d tile content\n * @param {Map} attributesMap Map<{positions: Float32Array, normals: Float32Array, texCoords: Float32Array, colors: Uint8Array, featureIndices: Array}> - for recursive concatenation of\n * attributes\n * @param {Matrix4} matrix - transformation matrix - cumulative transformation matrix formed from all parent node matrices\n * @todo: optimize arrays concatenation\n */\nfunction convertMesh(\n mesh,\n content,\n attributesMap,\n matrix = new Matrix4([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])\n) {\n for (const primitive of mesh.primitives) {\n let outputAttributes = null;\n if (primitive.material) {\n outputAttributes = attributesMap.get(primitive.material.id);\n } else if (attributesMap.has('default')) {\n outputAttributes = attributesMap.get('default');\n }\n assert(outputAttributes !== null, 'Primitive - material mapping failed');\n const attributes = primitive.attributes;\n\n outputAttributes.positions = concatenateTypedArrays(\n outputAttributes.positions,\n transformVertexArray({\n vertices: attributes.POSITION.value,\n cartographicOrigin: content.cartographicOrigin,\n cartesianModelMatrix: content.cartesianModelMatrix,\n nodeMatrix: matrix,\n indices: primitive.indices.value,\n attributeSpecificTransformation: transformVertexPositions\n })\n );\n outputAttributes.normals = concatenateTypedArrays(\n outputAttributes.normals,\n transformVertexArray({\n vertices: attributes.NORMAL && attributes.NORMAL.value,\n cartographicOrigin: content.cartographicOrigin,\n cartesianModelMatrix: content.cartesianModelMatrix,\n nodeMatrix: matrix,\n indices: primitive.indices.value,\n attributeSpecificTransformation: transformVertexNormals\n })\n );\n outputAttributes.texCoords = concatenateTypedArrays(\n outputAttributes.texCoords,\n flattenTexCoords(\n attributes.TEXCOORD_0 && attributes.TEXCOORD_0.value,\n primitive.indices.value\n )\n );\n\n outputAttributes.colors = concatenateTypedArrays(\n outputAttributes.colors,\n flattenColors(attributes.COLOR_0, primitive.indices.value)\n );\n\n outputAttributes.featureIndices.push(\n flattenBatchIds(getBatchIdsByAttributeName(attributes), primitive.indices.value)\n );\n }\n}\n\n/**\n * Convert vertices attributes (POSITIONS or NORMALS) to i3s compatible format\n * @param {object} args - source tile (3DTile)\n * @param {Float32Array} args.vertices - gltf primitive POSITION or NORMAL attribute\n * @param {Object} args.cartographicOrigin - cartographic origin coordinates\n * @param {Object} args.cartesianModelMatrix - a cartesian model matrix to transform coordnates from cartesian to cartographic format\n * @param {Matrix4} args.nodeMatrix - a gltf node transformation matrix - cumulative transformation matrix formed from all parent node matrices\n * @param {Uint8Array} args.indices - gltf primitive indices\n * @param {Function} args.attributeSpecificTransformation - function to do attribute - specific transformations\n * @returns {Float32Array}\n */\nfunction transformVertexArray(args) {\n const {vertices, indices, attributeSpecificTransformation} = args;\n const newVertices = new Float32Array(indices.length * VALUES_PER_VERTEX);\n if (!vertices) {\n return newVertices;\n }\n for (let i = 0; i < indices.length; i++) {\n const coordIndex = indices[i] * VALUES_PER_VERTEX;\n const vertex = vertices.subarray(coordIndex, coordIndex + VALUES_PER_VERTEX);\n let vertexVector = new Vector3(Array.from(vertex));\n\n vertexVector = attributeSpecificTransformation(vertexVector, args);\n\n newVertices[i * VALUES_PER_VERTEX] = vertexVector.x;\n newVertices[i * VALUES_PER_VERTEX + 1] = vertexVector.y;\n newVertices[i * VALUES_PER_VERTEX + 2] = vertexVector.z;\n }\n return newVertices;\n}\n\nfunction transformVertexPositions(vertexVector, calleeArgs) {\n const {cartesianModelMatrix, cartographicOrigin, nodeMatrix} = calleeArgs;\n\n if (nodeMatrix) {\n vertexVector = vertexVector.transform(nodeMatrix);\n }\n\n vertexVector = vertexVector.transform(cartesianModelMatrix);\n Ellipsoid.WGS84.cartesianToCartographic(\n [vertexVector[0], vertexVector[1], vertexVector[2]],\n vertexVector\n );\n vertexVector = vertexVector.subtract(cartographicOrigin);\n return vertexVector;\n}\n\nfunction transformVertexNormals(vertexVector, calleeArgs) {\n const {cartesianModelMatrix, nodeMatrix} = calleeArgs;\n\n if (nodeMatrix) {\n vertexVector = vertexVector.transformAsVector(nodeMatrix);\n }\n\n vertexVector = vertexVector.transformAsVector(cartesianModelMatrix);\n return vertexVector;\n}\n\n/**\n * Convert uv0 (texture coordinates) from coords based on indices to plain arrays, compatible with i3s\n * @param {Float32Array} texCoords - gltf primitive TEXCOORD_0 attribute\n * @param {Uint8Array} indices - gltf primitive indices\n * @returns {Float32Array}\n */\nfunction flattenTexCoords(texCoords, indices) {\n if (!texCoords) {\n return new Float32Array(0);\n }\n const newTexCoords = new Float32Array(indices.length * VALUES_PER_TEX_COORD);\n for (let i = 0; i < indices.length; i++) {\n const coordIndex = indices[i] * VALUES_PER_TEX_COORD;\n const texCoord = texCoords.subarray(coordIndex, coordIndex + VALUES_PER_TEX_COORD);\n newTexCoords[i * VALUES_PER_TEX_COORD] = texCoord[0];\n newTexCoords[i * VALUES_PER_TEX_COORD + 1] = texCoord[1];\n }\n return newTexCoords;\n}\n\n/**\n * Convert color from COLOR_0 based on indices to plain arrays, compatible with i3s\n * @param {object} colorsAttribute - gltf primitive COLOR_0 attribute\n * @param {Uint8Array} indices - gltf primitive indices\n * @returns {Uint8Array}\n */\nfunction flattenColors(colorsAttribute, indices) {\n if (!colorsAttribute) {\n return new Uint8Array(0);\n }\n const components = colorsAttribute.components;\n const colors = colorsAttribute.value;\n const newColors = new Uint8Array(indices.length * components);\n for (let i = 0; i < indices.length; i++) {\n const colorIndex = indices[i] * components;\n const color = colors.subarray(colorIndex, colorIndex + components);\n const colorUint8 = new Uint8Array(components);\n for (let j = 0; j < color.length; j++) {\n colorUint8[j] = color[j] * 255;\n }\n newColors.set(colorUint8, i * components);\n }\n return newColors;\n}\n\n/**\n * Flatten batchedIds list based on indices to right ordered array, compatible with i3s\n * @param {Array} batchedIds - gltf primitive\n * @param {Uint8Array} indices - gltf primitive indices\n * @returns {Array}\n */\nfunction flattenBatchIds(batchedIds, indices) {\n if (!batchedIds.length || !indices.length) {\n return [];\n }\n const newBatchIds = [];\n for (let i = 0; i < indices.length; i++) {\n const coordIndex = indices[i];\n newBatchIds.push(batchedIds[coordIndex]);\n }\n return newBatchIds;\n}\n/**\n * Return batchIds based on possible attribute names for different kind of maps.\n * @param {Object} attributes {attributeName: Float32Array}\n * @returns {Array}\n */\nfunction getBatchIdsByAttributeName(attributes) {\n let batchIds = [];\n\n for (let index = 0; index < BATCHED_ID_POSSIBLE_ATTRIBUTE_NAMES.length; index++) {\n const possibleBatchIdAttributeName = BATCHED_ID_POSSIBLE_ATTRIBUTE_NAMES[index];\n if (\n attributes[possibleBatchIdAttributeName] &&\n attributes[possibleBatchIdAttributeName].value\n ) {\n batchIds = attributes[possibleBatchIdAttributeName].value;\n break;\n }\n }\n\n return batchIds;\n}\n\nfunction convertMaterials(tileContent) {\n const result = [];\n const sourceMaterials = tileContent.gltf.materials;\n for (const sourceMaterial of sourceMaterials) {\n result.push(convertMaterial(sourceMaterial));\n }\n return result;\n}\n\n/**\n * Convert texture and material from gltf 2.0 material object\n * @param {Object} sourceMaterial - material object\n * @returns {Object}\n */\nfunction convertMaterial(sourceMaterial) {\n const material = {\n doubleSided: sourceMaterial.doubleSided,\n emissiveFactor: sourceMaterial.emissiveFactor.map((c) => Math.round(c * 255)),\n // It is in upper case in GLTF: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#alpha-coverage\n // But it is in lower case in I3S: https://github.com/Esri/i3s-spec/blob/master/docs/1.7/materialDefinitions.cmn.md\n alphaMode: (sourceMaterial.alphaMode || 'OPAQUE').toLowerCase(),\n pbrMetallicRoughness: {\n roughnessFactor: sourceMaterial.pbrMetallicRoughness.roughnessFactor,\n metallicFactor: sourceMaterial.pbrMetallicRoughness.metallicFactor\n }\n };\n\n let texture;\n if (sourceMaterial.pbrMetallicRoughness.baseColorTexture) {\n texture = sourceMaterial.pbrMetallicRoughness.baseColorTexture.texture.source;\n material.pbrMetallicRoughness.baseColorTexture = {\n textureSetDefinitionId: 0\n };\n } else if (sourceMaterial.emissiveTexture) {\n texture = sourceMaterial.emissiveTexture.texture.source;\n // ArcGIS webscene doesn't show emissiveTexture but shows baseColorTexture\n material.pbrMetallicRoughness.baseColorTexture = {\n textureSetDefinitionId: 0\n };\n }\n\n if (!texture) {\n // Should use default baseColorFactor if it is not present in source material\n // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-pbrmetallicroughness\n const baseColorFactor = sourceMaterial.pbrMetallicRoughness.baseColorFactor;\n material.pbrMetallicRoughness.baseColorFactor =\n (baseColorFactor && baseColorFactor.map((c) => Math.round(c * 255))) || undefined;\n }\n\n return {material, texture};\n}\n\nfunction getDefaultMaterial() {\n return {\n alphaMode: 'opaque',\n pbrMetallicRoughness: {}\n };\n}\n\n/**\n * Form \"sharedResources\" from gltf materials array\n * @param {Object} tileContent - 3d tile content\n * @returns {Object} {materialDefinitionInfos: Object[], textureDefinitionInfos: Object[]} -\n * 2 arrays in format of i3s sharedResources data https://github.com/Esri/i3s-spec/blob/master/docs/1.7/sharedResource.cmn.md\n */\nfunction getSharedResources(tileContent, nodeId) {\n const gltfMaterials = tileContent.gltf.materials;\n const i3sResources = {};\n\n if (!gltfMaterials || !gltfMaterials.length) {\n return i3sResources;\n }\n\n i3sResources.materialDefinitionInfos = [];\n for (const gltfMaterial of gltfMaterials) {\n const {materialDefinitionInfo, textureDefinitionInfo} = convertGLTFMaterialToI3sSharedResources(\n gltfMaterial,\n nodeId\n );\n i3sResources.materialDefinitionInfos.push(materialDefinitionInfo);\n if (textureDefinitionInfo) {\n i3sResources.textureDefinitionInfos = i3sResources.textureDefinitionInfos || [];\n i3sResources.textureDefinitionInfos.push(textureDefinitionInfo);\n }\n }\n return i3sResources;\n}\n\n/**\n * Convert gltf material into I3S sharedResources data\n * @param {Object} gltfMaterial - gltf material data\n * @returns {Object} - Couple {materialDefinitionInfo, textureDefinitionInfo} extracted from gltf material data\n */\nfunction convertGLTFMaterialToI3sSharedResources(gltfMaterial, nodeId) {\n const texture =\n gltfMaterial.pbrMetallicRoughness.baseColorTexture || gltfMaterial.emissiveTexture;\n let textureDefinitionInfo = null;\n if (texture) {\n textureDefinitionInfo = extractSharedResourcesTextureInfo(texture.texture, nodeId);\n }\n const {baseColorFactor, metallicFactor} = gltfMaterial.pbrMetallicRoughness;\n let colorFactor = baseColorFactor;\n // If alpha channel is 0 try to get emissive factor from gltf material.\n if ((!baseColorFactor || baseColorFactor[3] === 0) && gltfMaterial.emissiveFactor) {\n colorFactor = gltfMaterial.emissiveFactor;\n colorFactor[3] = colorFactor[3] || 1;\n }\n\n return {\n materialDefinitionInfo: extractSharedResourcesMaterialInfo(colorFactor, metallicFactor),\n textureDefinitionInfo\n };\n}\n\n/**\n * Form \"materialDefinition\" which is part of \"sharedResouces\"\n * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materials\n * See formulas in appendix \"Appendix B: BRDF Implementation\":\n * const dielectricSpecular = rgb(0.04, 0.04, 0.04)\n * const black = rgb(0, 0, 0)\n * cdiff = lerp(baseColor.rgb * (1 - dielectricSpecular.r), black, metallic)\n * F0 = lerp(dieletricSpecular, baseColor.rgb, metallic)\n *\n * Assumption: F0 - specular in i3s (\"specular reflection\" <-> \"reflectance value at normal incidence\")\n * cdiff - diffuse in i3s (\"Diffuse color\" <-> \"'c' diffuse\" (c means color?))\n * @param {number[]} baseColorFactor - RGBA color in 0..1 format\n * @param {number} metallicFactor - \"metallicFactor\" attribute of gltf material object\n * @returns {Object}\n */\nfunction extractSharedResourcesMaterialInfo(baseColorFactor, metallicFactor = 0) {\n const matDielectricColorComponent = 0.04 / 255; // Color from rgb (255) to 0..1 resolution\n // All color resolutions are 0..1\n const black = new Vector4(0, 0, 0, 1);\n const unitVector = new Vector4(1, 1, 1, 1);\n const dielectricSpecular = new Vector4(\n matDielectricColorComponent,\n matDielectricColorComponent,\n matDielectricColorComponent,\n 0\n );\n const baseColorVector = new Vector4(baseColorFactor);\n // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material\n // Formulas for Cdiff & F0\n const firstOperand = unitVector.subtract(dielectricSpecular).multiply(baseColorVector);\n const diffuse = firstOperand.lerp(firstOperand, black, metallicFactor);\n dielectricSpecular[3] = 1;\n const specular = dielectricSpecular.lerp(dielectricSpecular, baseColorVector, metallicFactor);\n return {\n diffuse: diffuse.toArray(),\n specular: specular.toArray()\n };\n}\n\n/**\n * Form \"textureDefinition\" which is part of \"sharedResouces\"\n * @param {Object} texture - texture image info\n * @returns {Object}\n */\nfunction extractSharedResourcesTextureInfo(texture, nodeId) {\n return {\n encoding: [texture.source.mimeType],\n images: [\n {\n // 'i3s' has just size which is width of the image. Images are supposed to be square.\n // https://github.com/Esri/i3s-spec/blob/master/docs/1.7/image.cmn.md\n id: generateImageId(texture, nodeId),\n size: texture.source.image.width,\n length: [texture.source.image.data.length]\n }\n ]\n };\n}\n/*\n * Formula for counting imageId:\n * https://github.com/Esri/i3s-spec/blob/0a6366a9249b831db8436c322f8d27521e86cf07/format/Indexed%203d%20Scene%20Layer%20Format%20Specification.md#generating-image-ids\n * @param {Object} texture - texture image info\n * @returns {string}\n */\nfunction generateImageId(texture, nodeId) {\n const {width, height} = texture.source.image;\n const levelCountOfTexture = 1;\n const indexOfLevel = 0;\n const indexOfTextureInStore = nodeId + 1;\n\n const zerosCount = 32 - indexOfTextureInStore.toString(2).length;\n const rightHalf = '0'.repeat(zerosCount).concat(indexOfTextureInStore.toString(2));\n\n const shiftedLevelCountOfTexture = levelCountOfTexture << 28;\n const shiftedIndexOfLevel = indexOfLevel << 24;\n const shiftedWidth = (width - 1) << 12;\n const shiftedHeight = (height - 1) << 0;\n\n const leftHalf = shiftedLevelCountOfTexture + shiftedIndexOfLevel + shiftedWidth + shiftedHeight;\n const imageId = BigInt(`0b${leftHalf.toString(2)}${rightHalf}`);\n return imageId.toString();\n}\n\n/**\n * Make all feature ids unique through all nodes in layout.\n * @param {Array} featureIds\n * @param {Array} featureIndices\n * @param {Array} featuresHashArray\n * @param {Object} batchTable\n * @returns {void}\n */\nfunction makeFeatureIdsUnique(featureIds, featureIndices, featuresHashArray, batchTable) {\n const replaceMap = getFeaturesReplaceMap(featureIds, batchTable, featuresHashArray);\n replaceIndicesByUnique(featureIndices, replaceMap);\n replaceIndicesByUnique(featureIds, replaceMap);\n}\n\n/**\n * Generate replace map to make featureIds unique.\n * @param {Array} featureIds\n * @param {Object} batchTable\n * @param {Array} featuresHashArray\n * @returns {Object}\n */\nfunction getFeaturesReplaceMap(featureIds, batchTable, featuresHashArray) {\n const featureMap = {};\n\n for (let index = 0; index < featureIds.length; index++) {\n const oldFeatureId = featureIds[index];\n const uniqueFeatureId = getOrCreateUniqueFeatureId(index, batchTable, featuresHashArray);\n featureMap[oldFeatureId.toString()] = uniqueFeatureId;\n }\n\n return featureMap;\n}\n\n/**\n * Generates string for unique batch id creation.\n * @param {Object} batchTable\n * @param {Number} index\n * @returns {String}\n */\nfunction generateStringFromBatchTableByIndex(batchTable, index) {\n let str = '';\n for (const key in batchTable) {\n str += batchTable[key][index];\n }\n return str;\n}\n\n/**\n * Return already exited featureId or creates and returns new to support unique feature ids throw nodes.\n * @param {Number} index\n * @param {Object} batchTable\n * @param {Array} featuresHashArray\n * @returns {Number}\n */\nfunction getOrCreateUniqueFeatureId(index, batchTable, featuresHashArray) {\n const batchTableStr = generateStringFromBatchTableByIndex(batchTable, index);\n const hash = md5(batchTableStr);\n\n if (featuresHashArray.includes(hash)) {\n return featuresHashArray.indexOf(hash);\n }\n return featuresHashArray.push(hash) - 1;\n}\n\n/**\n * Do replacement of indices for making them unique through all nodes.\n * @param {Array} indicesArray\n * @param {Object} featureMap\n * @returns {void}\n */\nfunction replaceIndicesByUnique(indicesArray, featureMap) {\n for (let index = 0; index < indicesArray.length; index++) {\n indicesArray[index] = featureMap[indicesArray[index]];\n }\n}\n\n/**\n * Convert batch table data to attribute buffers.\n * @param {Object} batchTable - table with metadata for particular feature.\n * @param {Array} featureIds\n * @param {Array} attributeStorageInfo\n * @returns {Array} - Array of file buffers.\n */\nfunction convertBatchTableToAttributeBuffers(batchTable, featureIds, attributeStorageInfo) {\n const attributeBuffers = [];\n\n if (batchTable) {\n const batchTableWithFeatureIds = {\n OBJECTID: featureIds,\n ...batchTable\n };\n\n for (const key in batchTableWithFeatureIds) {\n const type = getAttributeType(key, attributeStorageInfo);\n\n let attributeBuffer = null;\n\n switch (type) {\n case OBJECT_ID_TYPE:\n case SHORT_INT_TYPE:\n attributeBuffer = generateShortIntegerAttributeBuffer(batchTableWithFeatureIds[key]);\n break;\n case DOUBLE_TYPE:\n attributeBuffer = generateDoubleAttributeBuffer(batchTableWithFeatureIds[key]);\n break;\n case STRING_TYPE:\n attributeBuffer = generateStringAttributeBuffer(batchTableWithFeatureIds[key]);\n break;\n default:\n attributeBuffer = generateStringAttributeBuffer(batchTableWithFeatureIds[key]);\n }\n\n attributeBuffers.push(attributeBuffer);\n }\n }\n\n return attributeBuffers;\n}\n/**\n * Return attribute type.\n * @param {String} key\n * @param {Array} attributeStorageInfo\n * @returns {String} attribute type.\n */\nfunction getAttributeType(key, attributeStorageInfo) {\n const attribute = attributeStorageInfo.find((attr) => attr.name === key);\n return attribute.attributeValues.valueType;\n}\n\n/**\n * Convert short integer to attribute arrayBuffer.\n * @param {Array} featureIds\n * @returns {ArrayBuffer} - Buffer with objectId data.\n */\nfunction generateShortIntegerAttributeBuffer(featureIds) {\n const count = new Uint32Array([featureIds.length]);\n const valuesArray = new Uint32Array(featureIds);\n return concatenateArrayBuffers(count.buffer, valuesArray.buffer);\n}\n\n/**\n * Convert double to attribute arrayBuffer.\n * @param {Array} featureIds\n * @returns {ArrayBuffer} - Buffer with objectId data.\n */\nfunction generateDoubleAttributeBuffer(featureIds) {\n const count = new Uint32Array([featureIds.length]);\n const padding = new Uint8Array(4);\n const valuesArray = new Float64Array(featureIds);\n\n return concatenateArrayBuffers(count.buffer, padding.buffer, valuesArray.buffer);\n}\n\n/**\n * Convert batch table attributes to array buffer with batch table data.\n * @param {Array} batchAttributes\n * @returns {ArrayBuffer} - Buffer with batch table data.\n */\nfunction generateStringAttributeBuffer(batchAttributes) {\n const stringCountArray = new Uint32Array([batchAttributes.length]);\n let totalNumberOfBytes = 0;\n const stringSizesArray = new Uint32Array(batchAttributes.length);\n const stringBufferArray = [];\n\n for (let index = 0; index < batchAttributes.length; index++) {\n const currentString = `${String(batchAttributes[index])}\\0`;\n const currentStringBuffer = Buffer.from(currentString);\n const currentStringSize = currentStringBuffer.length;\n totalNumberOfBytes += currentStringSize;\n stringSizesArray[index] = currentStringSize;\n stringBufferArray.push(currentStringBuffer);\n }\n\n const totalBytes = new Uint32Array([totalNumberOfBytes]);\n\n return concatenateArrayBuffers(\n stringCountArray.buffer,\n totalBytes.buffer,\n stringSizesArray.buffer,\n ...stringBufferArray\n );\n}\n\n/**\n * Convert featureIds to BigUint64Array.\n * @param {Array} featureIds\n * @returns {BigUint64Array} - Array of feature ids in BigUint64 format.\n */\nfunction generateBigUint64Array(featureIds) {\n const typedFeatureIds = new BigUint64Array(featureIds.length);\n for (let index = 0; index < featureIds.length; index++) {\n typedFeatureIds[index] = BigInt(featureIds[index]);\n }\n return typedFeatureIds;\n}\n\n/**\n * Generates draco compressed geometry\n * @param {Number} vertexCount\n * @param {Object} convertedAttributes\n * @returns {Promise<object>} - COmpressed geometry.\n */\nasync function generateCompressedGeometry(vertexCount, convertedAttributes, attributes) {\n const {positions, normals, texCoords, colors, featureIds, faceRange} = attributes;\n const indices = new Uint32Array(vertexCount);\n\n for (let index = 0; index < indices.length; index++) {\n indices.set([index], index);\n }\n\n const featureIndices = new Uint32Array(\n convertedAttributes.featureIndices.length ? convertedAttributes.featureIndices : vertexCount\n );\n\n const featureIndex = generateFeatureIndexAttribute(featureIndices, faceRange);\n\n const compressedAttributes = {\n positions,\n normals,\n colors,\n 'feature-index': featureIndex\n };\n\n if (texCoords.length) {\n compressedAttributes.texCoords = texCoords;\n }\n\n const attributesMetadata = {\n 'feature-index': {\n 'i3s-attribute-type': 'feature-index',\n 'i3s-feature-ids': new Int32Array(featureIds)\n }\n };\n\n return new Uint8Array(\n await encode({attributes: compressedAttributes, indices}, DracoWriter, {\n draco: {\n method: 'MESH_SEQUENTIAL_ENCODING',\n attributesMetadata\n }\n })\n );\n}\n\n/**\n * Generates ordered feature indices based on face range\n * @param {Uint32Array} featureIndex\n * @param {Uint32Array} faceRange\n * @returns {Uint32Array}\n */\nfunction generateFeatureIndexAttribute(featureIndex, faceRange) {\n const orderedFeatureIndices = new Uint32Array(featureIndex.length);\n let fillIndex = 0;\n let startIndex = 0;\n\n for (let index = 1; index < faceRange.length; index += 2) {\n const endIndex = (faceRange[index] + 1) * VALUES_PER_VERTEX;\n\n orderedFeatureIndices.fill(fillIndex, startIndex, endIndex);\n\n fillIndex++;\n startIndex = endIndex + 1;\n }\n\n return orderedFeatureIndices;\n}\n"],"file":"geometry-converter.js"}
1
+ {"version":3,"sources":["../../../../src/i3s-converter/helpers/geometry-converter.js"],"names":["Vector3","Matrix4","Vector4","Ellipsoid","DracoWriter","encode","assert","concatenateArrayBuffers","concatenateTypedArrays","md5","generateAttributes","VALUES_PER_VERTEX","VALUES_PER_TEX_COORD","VALUES_PER_COLOR_ELEMENT","STRING_TYPE","SHORT_INT_TYPE","DOUBLE_TYPE","OBJECT_ID_TYPE","BATCHED_ID_POSSIBLE_ATTRIBUTE_NAMES","convertB3dmToI3sGeometry","tileContent","nodeId","featuresHashArray","attributeStorageInfo","draco","materialAndTextureList","convertMaterials","convertedAttributesMap","convertAttributes","has","push","material","getDefaultMaterial","result","nodesCounter","i","gltf","materials","length","sourceMaterial","id","convertedAttributes","get","texture","_makeNodeResources","vertexCount","positions","triangleCount","faceRange","featureIds","normals","colors","texCoords","featureCount","batchTableJson","makeFeatureIdsUnique","featureIndices","header","Uint32Array","typedFeatureIds","generateBigUint64Array","set","fileBuffer","Uint8Array","buffer","ArrayBuffer","compressedGeometry","generateCompressedGeometry","Float32Array","attributes","convertBatchTableToAttributeBuffers","geometry","sharedResources","getSharedResources","meshMaterial","attributesMap","Map","nodes","scene","convertNodes","attrKey","keys","delete","index","reduce","acc","value","concat","matrix","node","convertNode","nodeMatrix","compositeMatrix","multiplyRight","mesh","convertMesh","children","content","primitive","primitives","outputAttributes","transformVertexArray","vertices","POSITION","cartographicOrigin","cartesianModelMatrix","indices","attributeSpecificTransformation","transformVertexPositions","NORMAL","transformVertexNormals","flattenTexCoords","TEXCOORD_0","flattenColors","COLOR_0","flattenBatchIds","getBatchIdsByAttributeName","args","newVertices","coordIndex","vertex","subarray","vertexVector","Array","from","x","y","z","calleeArgs","transform","WGS84","cartesianToCartographic","subtract","transformAsVector","newTexCoords","texCoord","colorsAttribute","components","newColors","colorIndex","color","colorUint8","j","batchedIds","newBatchIds","batchIds","possibleBatchIdAttributeName","sourceMaterials","convertMaterial","doubleSided","emissiveFactor","map","c","Math","round","alphaMode","toLowerCase","pbrMetallicRoughness","roughnessFactor","metallicFactor","baseColorTexture","source","textureSetDefinitionId","emissiveTexture","baseColorFactor","undefined","gltfMaterials","i3sResources","materialDefinitionInfos","gltfMaterial","materialDefinitionInfo","textureDefinitionInfo","convertGLTFMaterialToI3sSharedResources","textureDefinitionInfos","extractSharedResourcesTextureInfo","colorFactor","extractSharedResourcesMaterialInfo","matDielectricColorComponent","black","unitVector","dielectricSpecular","baseColorVector","firstOperand","multiply","diffuse","lerp","specular","toArray","encoding","mimeType","images","generateImageId","size","image","width","data","height","levelCountOfTexture","indexOfLevel","indexOfTextureInStore","zerosCount","toString","rightHalf","repeat","shiftedLevelCountOfTexture","shiftedIndexOfLevel","shiftedWidth","shiftedHeight","leftHalf","imageId","BigInt","batchTable","replaceMap","getFeaturesReplaceMap","replaceIndicesByUnique","featureMap","oldFeatureId","uniqueFeatureId","getOrCreateUniqueFeatureId","generateStringFromBatchTableByIndex","str","key","batchTableStr","hash","includes","indexOf","indicesArray","attributeBuffers","batchTableWithFeatureIds","OBJECTID","type","getAttributeType","attributeBuffer","generateShortIntegerAttributeBuffer","generateDoubleAttributeBuffer","generateStringAttributeBuffer","attribute","find","attr","name","attributeValues","valueType","count","valuesArray","padding","Float64Array","batchAttributes","stringCountArray","totalNumberOfBytes","stringSizesArray","stringBufferArray","currentString","String","currentStringBuffer","Buffer","currentStringSize","totalBytes","BigUint64Array","featureIndex","generateFeatureIndexAttribute","compressedAttributes","attributesMetadata","Int32Array","method","orderedFeatureIndices","fillIndex","startIndex","endIndex","fill"],"mappings":"AAAA,SAAQA,OAAR,EAAiBC,OAAjB,EAA0BC,OAA1B,QAAwC,eAAxC;AACA,SAAQC,SAAR,QAAwB,qBAAxB;AAEA,SAAQC,WAAR,QAA0B,mBAA1B;AACA,SAAQC,MAAR,EAAgBC,MAAhB,QAA6B,kBAA7B;AACA,SAAQC,uBAAR,EAAiCC,sBAAjC,QAA8D,0BAA9D;AACA,OAAOC,GAAP,MAAgB,KAAhB;AACA,SAAQC,kBAAR,QAAiC,uBAAjC;AAEA,MAAMC,iBAAiB,GAAG,CAA1B;AACA,MAAMC,oBAAoB,GAAG,CAA7B;AACA,MAAMC,wBAAwB,GAAG,CAAjC;AAEA,MAAMC,WAAW,GAAG,QAApB;AACA,MAAMC,cAAc,GAAG,OAAvB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KAAK,GAAG,CAAjB,EAAoBA,KAAK,GAAGnC,SAAS,CAACV,MAAtC,EAA8C6C,KAAK,IAAI,CAAvD,EAA0D;AACxD,UAAMwL,QAAQ,GAAG,CAAC3N,SAAS,CAACmC,KAAD,CAAT,GAAmB,CAApB,IAAyBxE,iBAA1C;AAEA6P,IAAAA,qBAAqB,CAACI,IAAtB,CAA2BH,SAA3B,EAAsCC,UAAtC,EAAkDC,QAAlD;AAEAF,IAAAA,SAAS;AACTC,IAAAA,UAAU,GAAGC,QAAQ,GAAG,CAAxB;AACD;;AAED,SAAOH,qBAAP;AACD","sourcesContent":["import {Vector3, Matrix4, Vector4} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\n\nimport {DracoWriter} from '@loaders.gl/draco';\nimport {encode, assert} from '@loaders.gl/core';\nimport {concatenateArrayBuffers, concatenateTypedArrays} from '@loaders.gl/loader-utils';\nimport md5 from 'md5';\nimport {generateAttributes} from './geometry-attributes';\n\nconst VALUES_PER_VERTEX = 3;\nconst VALUES_PER_TEX_COORD = 2;\nconst VALUES_PER_COLOR_ELEMENT = 4;\n\nconst STRING_TYPE = 'string';\nconst SHORT_INT_TYPE = 'Int32';\nconst DOUBLE_TYPE = 'Float64';\nconst OBJECT_ID_TYPE = 'Oid32';\n/*\n * 'CUSTOM_ATTRIBUTE_2' - Attribute name which includes batch info and used by New York map.\n * _BATCHID - Default attribute name which includes batch info.\n * BATCHID - Legacy attribute name which includes batch info.\n */\nconst BATCHED_ID_POSSIBLE_ATTRIBUTE_NAMES = ['CUSTOM_ATTRIBUTE_2', '_BATCHID', 'BATCHID'];\n\nexport default async function convertB3dmToI3sGeometry(\n tileContent,\n nodeId,\n featuresHashArray,\n attributeStorageInfo,\n draco\n) {\n const materialAndTextureList = convertMaterials(tileContent);\n const convertedAttributesMap = convertAttributes(tileContent);\n\n if (convertedAttributesMap.has('default')) {\n materialAndTextureList.push({\n material: getDefaultMaterial()\n });\n }\n\n const result = [];\n let nodesCounter = nodeId;\n for (let i = 0; i < (tileContent.gltf.materials.length || 1); i++) {\n const sourceMaterial = tileContent.gltf.materials[i] || {id: 'default'};\n if (!convertedAttributesMap.has(sourceMaterial.id)) {\n continue; // eslint-disable-line no-continue\n }\n const convertedAttributes = convertedAttributesMap.get(sourceMaterial.id);\n const {material, texture} = materialAndTextureList[i];\n result.push(\n await _makeNodeResources({\n convertedAttributes,\n material,\n texture,\n tileContent,\n nodeId: nodesCounter,\n featuresHashArray,\n attributeStorageInfo,\n draco\n })\n );\n nodesCounter++;\n }\n\n return result;\n}\n\nasync function _makeNodeResources({\n convertedAttributes,\n material,\n texture,\n tileContent,\n nodeId,\n featuresHashArray,\n attributeStorageInfo,\n draco\n}) {\n const vertexCount = convertedAttributes.positions.length / VALUES_PER_VERTEX;\n const triangleCount = vertexCount / 3;\n const {faceRange, featureIds, positions, normals, colors, texCoords, featureCount} =\n generateAttributes({triangleCount, ...convertedAttributes});\n\n if (tileContent.batchTableJson) {\n makeFeatureIdsUnique(\n featureIds,\n convertedAttributes.featureIndices,\n featuresHashArray,\n tileContent.batchTableJson\n );\n }\n\n const header = new Uint32Array(2);\n const typedFeatureIds = generateBigUint64Array(featureIds);\n\n header.set([vertexCount, featureCount], 0);\n const fileBuffer = new Uint8Array(\n concatenateArrayBuffers(\n header.buffer,\n positions.buffer,\n normals.buffer,\n texture ? texCoords.buffer : new ArrayBuffer(0),\n colors.buffer,\n typedFeatureIds.buffer,\n faceRange.buffer\n )\n );\n const compressedGeometry = draco\n ? await generateCompressedGeometry(vertexCount, convertedAttributes, {\n positions,\n normals,\n texCoords: texture ? texCoords : new Float32Array(0),\n colors,\n featureIds,\n faceRange\n })\n : null;\n\n const attributes = convertBatchTableToAttributeBuffers(\n tileContent.batchTableJson,\n featureIds,\n attributeStorageInfo\n );\n\n return {\n geometry: fileBuffer,\n compressedGeometry,\n texture,\n sharedResources: getSharedResources(tileContent, nodeId),\n meshMaterial: material,\n vertexCount,\n attributes,\n featureCount\n };\n}\n\n/**\n * Convert attributes from the gltf nodes tree to i3s plain geometry\n * @param {Object} tileContent - 3d tile content\n * @returns {Map}\n * Map<{\n * positions: Float32Array,\n * normals: Float32Array,\n * colors: Uint8Array,\n * texCoords: Float32Array\n * }>\n * @todo implement colors support (if applicable for gltf format)\n */\nfunction convertAttributes(tileContent) {\n const attributesMap = new Map();\n\n for (const material of tileContent.gltf.materials || [{id: 'default'}]) {\n attributesMap.set(material.id, {\n positions: new Float32Array(0),\n normals: new Float32Array(0),\n texCoords: new Float32Array(0),\n colors: new Uint8Array(0),\n featureIndices: []\n });\n }\n\n const nodes = tileContent.gltf.scene.nodes;\n convertNodes(nodes, tileContent, attributesMap);\n\n for (const attrKey of attributesMap.keys()) {\n const attributes = attributesMap.get(attrKey);\n if (attributes.positions.length === 0) {\n attributesMap.delete(attrKey);\n continue; // eslint-disable-line no-continue\n }\n const vertexCount = attributes.positions.length / VALUES_PER_VERTEX;\n if (!attributes.colors.length) {\n attributes.colors = new Uint8Array(vertexCount * VALUES_PER_COLOR_ELEMENT);\n for (let index = 0; index < attributes.colors.length; index += 4) {\n attributes.colors.set([255, 255, 255, 255], index);\n }\n }\n if (!attributes.texCoords.length) {\n attributes.texCoords = new Float32Array(vertexCount * VALUES_PER_TEX_COORD);\n for (let index = 0; index < attributes.texCoords.length; index += 2) {\n attributes.texCoords.set([1, 1], index);\n }\n }\n attributes.featureIndices = attributes.featureIndices.reduce((acc, value) => acc.concat(value));\n }\n\n return attributesMap;\n}\n\n/**\n * Gltf has hierarchical structure of nodes. This function converts nodes starting from those which are in gltf scene object.\n * The goal is applying tranformation matrix for all children. Functions \"convertNodes\" and \"convertNode\" work together recursively.\n * @param {Object[]} nodes - gltf nodes array\n * @param {Object} tileContent - 3d tile content\n * @param {Map} attributesMap Map<{positions: Float32Array, normals: Float32Array, texCoords: Float32Array, colors: UInt8Array, featureIndices: Array}> - for recursive concatenation of\n * attributes\n * @param {Matrix4} matrix - transformation matrix - cumulative transformation matrix formed from all parent node matrices\n * @returns {void}\n */\nfunction convertNodes(\n nodes,\n tileContent,\n attributesMap,\n matrix = new Matrix4([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])\n) {\n if (nodes) {\n for (const node of nodes) {\n convertNode(node, tileContent, attributesMap, matrix);\n }\n }\n}\n\n/**\n * Convert all primitives of node and all children nodes\n * @param {Object} node - gltf node\n * @param {Object} tileContent - 3d tile content\n * @param {Map} attributesMap Map<{positions: Float32Array, normals: Float32Array, texCoords: Float32Array, colors: Uint8Array, featureIndices: Array}> - for recursive concatenation of\n * attributes\n * @param {Matrix4} matrix - transformation matrix - cumulative transformation matrix formed from all parent node matrices\n * @todo: optimize arrays concatenation\n */\nfunction convertNode(\n node,\n tileContent,\n attributesMap,\n matrix = new Matrix4([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])\n) {\n const nodeMatrix = node.matrix;\n const compositeMatrix = nodeMatrix ? matrix.multiplyRight(nodeMatrix) : matrix;\n\n const mesh = node.mesh;\n if (mesh) {\n convertMesh(mesh, tileContent, attributesMap, compositeMatrix);\n }\n\n convertNodes(node.children, tileContent, attributesMap, compositeMatrix);\n}\n\n/**\n * Convert all primitives of node and all children nodes\n * @param {Object} mesh - gltf node\n * @param {Object} content - 3d tile content\n * @param {Map} attributesMap Map<{positions: Float32Array, normals: Float32Array, texCoords: Float32Array, colors: Uint8Array, featureIndices: Array}> - for recursive concatenation of\n * attributes\n * @param {Matrix4} matrix - transformation matrix - cumulative transformation matrix formed from all parent node matrices\n * @todo: optimize arrays concatenation\n */\nfunction convertMesh(\n mesh,\n content,\n attributesMap,\n matrix = new Matrix4([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])\n) {\n for (const primitive of mesh.primitives) {\n let outputAttributes = null;\n if (primitive.material) {\n outputAttributes = attributesMap.get(primitive.material.id);\n } else if (attributesMap.has('default')) {\n outputAttributes = attributesMap.get('default');\n }\n assert(outputAttributes !== null, 'Primitive - material mapping failed');\n const attributes = primitive.attributes;\n\n outputAttributes.positions = concatenateTypedArrays(\n outputAttributes.positions,\n transformVertexArray({\n vertices: attributes.POSITION.value,\n cartographicOrigin: content.cartographicOrigin,\n cartesianModelMatrix: content.cartesianModelMatrix,\n nodeMatrix: matrix,\n indices: primitive.indices.value,\n attributeSpecificTransformation: transformVertexPositions\n })\n );\n outputAttributes.normals = concatenateTypedArrays(\n outputAttributes.normals,\n transformVertexArray({\n vertices: attributes.NORMAL && attributes.NORMAL.value,\n cartographicOrigin: content.cartographicOrigin,\n cartesianModelMatrix: content.cartesianModelMatrix,\n nodeMatrix: matrix,\n indices: primitive.indices.value,\n attributeSpecificTransformation: transformVertexNormals\n })\n );\n outputAttributes.texCoords = concatenateTypedArrays(\n outputAttributes.texCoords,\n flattenTexCoords(\n attributes.TEXCOORD_0 && attributes.TEXCOORD_0.value,\n primitive.indices.value\n )\n );\n\n outputAttributes.colors = concatenateTypedArrays(\n outputAttributes.colors,\n flattenColors(attributes.COLOR_0, primitive.indices.value)\n );\n\n outputAttributes.featureIndices.push(\n flattenBatchIds(getBatchIdsByAttributeName(attributes), primitive.indices.value)\n );\n }\n}\n\n/**\n * Convert vertices attributes (POSITIONS or NORMALS) to i3s compatible format\n * @param {object} args - source tile (3DTile)\n * @param {Float32Array} args.vertices - gltf primitive POSITION or NORMAL attribute\n * @param {Object} args.cartographicOrigin - cartographic origin coordinates\n * @param {Object} args.cartesianModelMatrix - a cartesian model matrix to transform coordnates from cartesian to cartographic format\n * @param {Matrix4} args.nodeMatrix - a gltf node transformation matrix - cumulative transformation matrix formed from all parent node matrices\n * @param {Uint8Array} args.indices - gltf primitive indices\n * @param {Function} args.attributeSpecificTransformation - function to do attribute - specific transformations\n * @returns {Float32Array}\n */\nfunction transformVertexArray(args) {\n const {vertices, indices, attributeSpecificTransformation} = args;\n const newVertices = new Float32Array(indices.length * VALUES_PER_VERTEX);\n if (!vertices) {\n return newVertices;\n }\n for (let i = 0; i < indices.length; i++) {\n const coordIndex = indices[i] * VALUES_PER_VERTEX;\n const vertex = vertices.subarray(coordIndex, coordIndex + VALUES_PER_VERTEX);\n let vertexVector = new Vector3(Array.from(vertex));\n\n vertexVector = attributeSpecificTransformation(vertexVector, args);\n\n newVertices[i * VALUES_PER_VERTEX] = vertexVector.x;\n newVertices[i * VALUES_PER_VERTEX + 1] = vertexVector.y;\n newVertices[i * VALUES_PER_VERTEX + 2] = vertexVector.z;\n }\n return newVertices;\n}\n\nfunction transformVertexPositions(vertexVector, calleeArgs) {\n const {cartesianModelMatrix, cartographicOrigin, nodeMatrix} = calleeArgs;\n\n if (nodeMatrix) {\n vertexVector = vertexVector.transform(nodeMatrix);\n }\n\n vertexVector = vertexVector.transform(cartesianModelMatrix);\n Ellipsoid.WGS84.cartesianToCartographic(\n [vertexVector[0], vertexVector[1], vertexVector[2]],\n vertexVector\n );\n vertexVector = vertexVector.subtract(cartographicOrigin);\n return vertexVector;\n}\n\nfunction transformVertexNormals(vertexVector, calleeArgs) {\n const {cartesianModelMatrix, nodeMatrix} = calleeArgs;\n\n if (nodeMatrix) {\n vertexVector = vertexVector.transformAsVector(nodeMatrix);\n }\n\n vertexVector = vertexVector.transformAsVector(cartesianModelMatrix);\n return vertexVector;\n}\n\n/**\n * Convert uv0 (texture coordinates) from coords based on indices to plain arrays, compatible with i3s\n * @param {Float32Array} texCoords - gltf primitive TEXCOORD_0 attribute\n * @param {Uint8Array} indices - gltf primitive indices\n * @returns {Float32Array}\n */\nfunction flattenTexCoords(texCoords, indices) {\n if (!texCoords) {\n return new Float32Array(0);\n }\n const newTexCoords = new Float32Array(indices.length * VALUES_PER_TEX_COORD);\n for (let i = 0; i < indices.length; i++) {\n const coordIndex = indices[i] * VALUES_PER_TEX_COORD;\n const texCoord = texCoords.subarray(coordIndex, coordIndex + VALUES_PER_TEX_COORD);\n newTexCoords[i * VALUES_PER_TEX_COORD] = texCoord[0];\n newTexCoords[i * VALUES_PER_TEX_COORD + 1] = texCoord[1];\n }\n return newTexCoords;\n}\n\n/**\n * Convert color from COLOR_0 based on indices to plain arrays, compatible with i3s\n * @param {object} colorsAttribute - gltf primitive COLOR_0 attribute\n * @param {Uint8Array} indices - gltf primitive indices\n * @returns {Uint8Array}\n */\nfunction flattenColors(colorsAttribute, indices) {\n if (!colorsAttribute) {\n return new Uint8Array(0);\n }\n const components = colorsAttribute.components;\n const colors = colorsAttribute.value;\n const newColors = new Uint8Array(indices.length * components);\n for (let i = 0; i < indices.length; i++) {\n const colorIndex = indices[i] * components;\n const color = colors.subarray(colorIndex, colorIndex + components);\n const colorUint8 = new Uint8Array(components);\n for (let j = 0; j < color.length; j++) {\n colorUint8[j] = color[j] * 255;\n }\n newColors.set(colorUint8, i * components);\n }\n return newColors;\n}\n\n/**\n * Flatten batchedIds list based on indices to right ordered array, compatible with i3s\n * @param {Array} batchedIds - gltf primitive\n * @param {Uint8Array} indices - gltf primitive indices\n * @returns {Array}\n */\nfunction flattenBatchIds(batchedIds, indices) {\n if (!batchedIds.length || !indices.length) {\n return [];\n }\n const newBatchIds = [];\n for (let i = 0; i < indices.length; i++) {\n const coordIndex = indices[i];\n newBatchIds.push(batchedIds[coordIndex]);\n }\n return newBatchIds;\n}\n/**\n * Return batchIds based on possible attribute names for different kind of maps.\n * @param {Object} attributes {attributeName: Float32Array}\n * @returns {Array}\n */\nfunction getBatchIdsByAttributeName(attributes) {\n let batchIds = [];\n\n for (let index = 0; index < BATCHED_ID_POSSIBLE_ATTRIBUTE_NAMES.length; index++) {\n const possibleBatchIdAttributeName = BATCHED_ID_POSSIBLE_ATTRIBUTE_NAMES[index];\n if (\n attributes[possibleBatchIdAttributeName] &&\n attributes[possibleBatchIdAttributeName].value\n ) {\n batchIds = attributes[possibleBatchIdAttributeName].value;\n break;\n }\n }\n\n return batchIds;\n}\n\nfunction convertMaterials(tileContent) {\n const result = [];\n const sourceMaterials = tileContent.gltf.materials;\n for (const sourceMaterial of sourceMaterials) {\n result.push(convertMaterial(sourceMaterial));\n }\n return result;\n}\n\n/**\n * Convert texture and material from gltf 2.0 material object\n * @param {Object} sourceMaterial - material object\n * @returns {Object}\n */\nfunction convertMaterial(sourceMaterial) {\n const material = {\n doubleSided: sourceMaterial.doubleSided,\n emissiveFactor: sourceMaterial.emissiveFactor.map((c) => Math.round(c * 255)),\n // It is in upper case in GLTF: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#alpha-coverage\n // But it is in lower case in I3S: https://github.com/Esri/i3s-spec/blob/master/docs/1.7/materialDefinitions.cmn.md\n alphaMode: (sourceMaterial.alphaMode || 'OPAQUE').toLowerCase(),\n pbrMetallicRoughness: {\n roughnessFactor: sourceMaterial.pbrMetallicRoughness.roughnessFactor,\n metallicFactor: sourceMaterial.pbrMetallicRoughness.metallicFactor\n }\n };\n\n let texture;\n if (sourceMaterial.pbrMetallicRoughness.baseColorTexture) {\n texture = sourceMaterial.pbrMetallicRoughness.baseColorTexture.texture.source;\n material.pbrMetallicRoughness.baseColorTexture = {\n textureSetDefinitionId: 0\n };\n } else if (sourceMaterial.emissiveTexture) {\n texture = sourceMaterial.emissiveTexture.texture.source;\n // ArcGIS webscene doesn't show emissiveTexture but shows baseColorTexture\n material.pbrMetallicRoughness.baseColorTexture = {\n textureSetDefinitionId: 0\n };\n }\n\n if (!texture) {\n // Should use default baseColorFactor if it is not present in source material\n // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-pbrmetallicroughness\n const baseColorFactor = sourceMaterial.pbrMetallicRoughness.baseColorFactor;\n material.pbrMetallicRoughness.baseColorFactor =\n (baseColorFactor && baseColorFactor.map((c) => Math.round(c * 255))) || undefined;\n }\n\n return {material, texture};\n}\n\nfunction getDefaultMaterial() {\n return {\n alphaMode: 'opaque',\n pbrMetallicRoughness: {}\n };\n}\n\n/**\n * Form \"sharedResources\" from gltf materials array\n * @param {Object} tileContent - 3d tile content\n * @returns {Object} {materialDefinitionInfos: Object[], textureDefinitionInfos: Object[]} -\n * 2 arrays in format of i3s sharedResources data https://github.com/Esri/i3s-spec/blob/master/docs/1.7/sharedResource.cmn.md\n */\nfunction getSharedResources(tileContent, nodeId) {\n const gltfMaterials = tileContent.gltf.materials;\n const i3sResources = {};\n\n if (!gltfMaterials || !gltfMaterials.length) {\n return i3sResources;\n }\n\n i3sResources.materialDefinitionInfos = [];\n for (const gltfMaterial of gltfMaterials) {\n const {materialDefinitionInfo, textureDefinitionInfo} = convertGLTFMaterialToI3sSharedResources(\n gltfMaterial,\n nodeId\n );\n i3sResources.materialDefinitionInfos.push(materialDefinitionInfo);\n if (textureDefinitionInfo) {\n i3sResources.textureDefinitionInfos = i3sResources.textureDefinitionInfos || [];\n i3sResources.textureDefinitionInfos.push(textureDefinitionInfo);\n }\n }\n return i3sResources;\n}\n\n/**\n * Convert gltf material into I3S sharedResources data\n * @param {Object} gltfMaterial - gltf material data\n * @returns {Object} - Couple {materialDefinitionInfo, textureDefinitionInfo} extracted from gltf material data\n */\nfunction convertGLTFMaterialToI3sSharedResources(gltfMaterial, nodeId) {\n const texture =\n gltfMaterial.pbrMetallicRoughness.baseColorTexture || gltfMaterial.emissiveTexture;\n let textureDefinitionInfo = null;\n if (texture) {\n textureDefinitionInfo = extractSharedResourcesTextureInfo(texture.texture, nodeId);\n }\n const {baseColorFactor, metallicFactor} = gltfMaterial.pbrMetallicRoughness;\n let colorFactor = baseColorFactor;\n // If alpha channel is 0 try to get emissive factor from gltf material.\n if ((!baseColorFactor || baseColorFactor[3] === 0) && gltfMaterial.emissiveFactor) {\n colorFactor = gltfMaterial.emissiveFactor;\n colorFactor[3] = colorFactor[3] || 1;\n }\n\n return {\n materialDefinitionInfo: extractSharedResourcesMaterialInfo(colorFactor, metallicFactor),\n textureDefinitionInfo\n };\n}\n\n/**\n * Form \"materialDefinition\" which is part of \"sharedResouces\"\n * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materials\n * See formulas in appendix \"Appendix B: BRDF Implementation\":\n * const dielectricSpecular = rgb(0.04, 0.04, 0.04)\n * const black = rgb(0, 0, 0)\n * cdiff = lerp(baseColor.rgb * (1 - dielectricSpecular.r), black, metallic)\n * F0 = lerp(dieletricSpecular, baseColor.rgb, metallic)\n *\n * Assumption: F0 - specular in i3s (\"specular reflection\" <-> \"reflectance value at normal incidence\")\n * cdiff - diffuse in i3s (\"Diffuse color\" <-> \"'c' diffuse\" (c means color?))\n * @param {number[]} baseColorFactor - RGBA color in 0..1 format\n * @param {number} metallicFactor - \"metallicFactor\" attribute of gltf material object\n * @returns {Object}\n */\nfunction extractSharedResourcesMaterialInfo(baseColorFactor, metallicFactor = 0) {\n const matDielectricColorComponent = 0.04 / 255; // Color from rgb (255) to 0..1 resolution\n // All color resolutions are 0..1\n const black = new Vector4(0, 0, 0, 1);\n const unitVector = new Vector4(1, 1, 1, 1);\n const dielectricSpecular = new Vector4(\n matDielectricColorComponent,\n matDielectricColorComponent,\n matDielectricColorComponent,\n 0\n );\n const baseColorVector = new Vector4(baseColorFactor);\n // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material\n // Formulas for Cdiff & F0\n const firstOperand = unitVector.subtract(dielectricSpecular).multiply(baseColorVector);\n const diffuse = firstOperand.lerp(firstOperand, black, metallicFactor);\n dielectricSpecular[3] = 1;\n const specular = dielectricSpecular.lerp(dielectricSpecular, baseColorVector, metallicFactor);\n return {\n diffuse: diffuse.toArray(),\n specular: specular.toArray()\n };\n}\n\n/**\n * Form \"textureDefinition\" which is part of \"sharedResouces\"\n * @param {Object} texture - texture image info\n * @returns {Object}\n */\nfunction extractSharedResourcesTextureInfo(texture, nodeId) {\n return {\n encoding: [texture.source.mimeType],\n images: [\n {\n // 'i3s' has just size which is width of the image. Images are supposed to be square.\n // https://github.com/Esri/i3s-spec/blob/master/docs/1.7/image.cmn.md\n id: generateImageId(texture, nodeId),\n size: texture.source.image.width,\n length: [texture.source.image.data.length]\n }\n ]\n };\n}\n/*\n * Formula for counting imageId:\n * https://github.com/Esri/i3s-spec/blob/0a6366a9249b831db8436c322f8d27521e86cf07/format/Indexed%203d%20Scene%20Layer%20Format%20Specification.md#generating-image-ids\n * @param {Object} texture - texture image info\n * @returns {string}\n */\nfunction generateImageId(texture, nodeId) {\n const {width, height} = texture.source.image;\n const levelCountOfTexture = 1;\n const indexOfLevel = 0;\n const indexOfTextureInStore = nodeId + 1;\n\n const zerosCount = 32 - indexOfTextureInStore.toString(2).length;\n const rightHalf = '0'.repeat(zerosCount).concat(indexOfTextureInStore.toString(2));\n\n const shiftedLevelCountOfTexture = levelCountOfTexture << 28;\n const shiftedIndexOfLevel = indexOfLevel << 24;\n const shiftedWidth = (width - 1) << 12;\n const shiftedHeight = (height - 1) << 0;\n\n const leftHalf = shiftedLevelCountOfTexture + shiftedIndexOfLevel + shiftedWidth + shiftedHeight;\n const imageId = BigInt(`0b${leftHalf.toString(2)}${rightHalf}`);\n return imageId.toString();\n}\n\n/**\n * Make all feature ids unique through all nodes in layout.\n * @param {Array} featureIds\n * @param {Array} featureIndices\n * @param {Array} featuresHashArray\n * @param {Object} batchTable\n * @returns {void}\n */\nfunction makeFeatureIdsUnique(featureIds, featureIndices, featuresHashArray, batchTable) {\n const replaceMap = getFeaturesReplaceMap(featureIds, batchTable, featuresHashArray);\n replaceIndicesByUnique(featureIndices, replaceMap);\n replaceIndicesByUnique(featureIds, replaceMap);\n}\n\n/**\n * Generate replace map to make featureIds unique.\n * @param {Array} featureIds\n * @param {Object} batchTable\n * @param {Array} featuresHashArray\n * @returns {Object}\n */\nfunction getFeaturesReplaceMap(featureIds, batchTable, featuresHashArray) {\n const featureMap = {};\n\n for (let index = 0; index < featureIds.length; index++) {\n const oldFeatureId = featureIds[index];\n const uniqueFeatureId = getOrCreateUniqueFeatureId(index, batchTable, featuresHashArray);\n featureMap[oldFeatureId.toString()] = uniqueFeatureId;\n }\n\n return featureMap;\n}\n\n/**\n * Generates string for unique batch id creation.\n * @param {Object} batchTable\n * @param {Number} index\n * @returns {String}\n */\nfunction generateStringFromBatchTableByIndex(batchTable, index) {\n let str = '';\n for (const key in batchTable) {\n str += batchTable[key][index];\n }\n return str;\n}\n\n/**\n * Return already exited featureId or creates and returns new to support unique feature ids throw nodes.\n * @param {Number} index\n * @param {Object} batchTable\n * @param {Array} featuresHashArray\n * @returns {Number}\n */\nfunction getOrCreateUniqueFeatureId(index, batchTable, featuresHashArray) {\n const batchTableStr = generateStringFromBatchTableByIndex(batchTable, index);\n const hash = md5(batchTableStr);\n\n if (featuresHashArray.includes(hash)) {\n return featuresHashArray.indexOf(hash);\n }\n return featuresHashArray.push(hash) - 1;\n}\n\n/**\n * Do replacement of indices for making them unique through all nodes.\n * @param {Array} indicesArray\n * @param {Object} featureMap\n * @returns {void}\n */\nfunction replaceIndicesByUnique(indicesArray, featureMap) {\n for (let index = 0; index < indicesArray.length; index++) {\n indicesArray[index] = featureMap[indicesArray[index]];\n }\n}\n\n/**\n * Convert batch table data to attribute buffers.\n * @param {Object} batchTable - table with metadata for particular feature.\n * @param {Array} featureIds\n * @param {Array} attributeStorageInfo\n * @returns {Array} - Array of file buffers.\n */\nfunction convertBatchTableToAttributeBuffers(batchTable, featureIds, attributeStorageInfo) {\n const attributeBuffers = [];\n\n if (batchTable) {\n const batchTableWithFeatureIds = {\n OBJECTID: featureIds,\n ...batchTable\n };\n\n for (const key in batchTableWithFeatureIds) {\n const type = getAttributeType(key, attributeStorageInfo);\n\n let attributeBuffer = null;\n\n switch (type) {\n case OBJECT_ID_TYPE:\n case SHORT_INT_TYPE:\n attributeBuffer = generateShortIntegerAttributeBuffer(batchTableWithFeatureIds[key]);\n break;\n case DOUBLE_TYPE:\n attributeBuffer = generateDoubleAttributeBuffer(batchTableWithFeatureIds[key]);\n break;\n case STRING_TYPE:\n attributeBuffer = generateStringAttributeBuffer(batchTableWithFeatureIds[key]);\n break;\n default:\n attributeBuffer = generateStringAttributeBuffer(batchTableWithFeatureIds[key]);\n }\n\n attributeBuffers.push(attributeBuffer);\n }\n }\n\n return attributeBuffers;\n}\n/**\n * Return attribute type.\n * @param {String} key\n * @param {Array} attributeStorageInfo\n * @returns {String} attribute type.\n */\nfunction getAttributeType(key, attributeStorageInfo) {\n const attribute = attributeStorageInfo.find((attr) => attr.name === key);\n return attribute.attributeValues.valueType;\n}\n\n/**\n * Convert short integer to attribute arrayBuffer.\n * @param {Array} featureIds\n * @returns {ArrayBuffer} - Buffer with objectId data.\n */\nfunction generateShortIntegerAttributeBuffer(featureIds) {\n const count = new Uint32Array([featureIds.length]);\n const valuesArray = new Uint32Array(featureIds);\n return concatenateArrayBuffers(count.buffer, valuesArray.buffer);\n}\n\n/**\n * Convert double to attribute arrayBuffer.\n * @param {Array} featureIds\n * @returns {ArrayBuffer} - Buffer with objectId data.\n */\nfunction generateDoubleAttributeBuffer(featureIds) {\n const count = new Uint32Array([featureIds.length]);\n const padding = new Uint8Array(4);\n const valuesArray = new Float64Array(featureIds);\n\n return concatenateArrayBuffers(count.buffer, padding.buffer, valuesArray.buffer);\n}\n\n/**\n * Convert batch table attributes to array buffer with batch table data.\n * @param {Array} batchAttributes\n * @returns {ArrayBuffer} - Buffer with batch table data.\n */\nfunction generateStringAttributeBuffer(batchAttributes) {\n const stringCountArray = new Uint32Array([batchAttributes.length]);\n let totalNumberOfBytes = 0;\n const stringSizesArray = new Uint32Array(batchAttributes.length);\n const stringBufferArray = [];\n\n for (let index = 0; index < batchAttributes.length; index++) {\n const currentString = `${String(batchAttributes[index])}\\0`;\n const currentStringBuffer = Buffer.from(currentString);\n const currentStringSize = currentStringBuffer.length;\n totalNumberOfBytes += currentStringSize;\n stringSizesArray[index] = currentStringSize;\n stringBufferArray.push(currentStringBuffer);\n }\n\n const totalBytes = new Uint32Array([totalNumberOfBytes]);\n\n return concatenateArrayBuffers(\n stringCountArray.buffer,\n totalBytes.buffer,\n stringSizesArray.buffer,\n ...stringBufferArray\n );\n}\n\n/**\n * Convert featureIds to BigUint64Array.\n * @param {Array} featureIds\n * @returns {BigUint64Array} - Array of feature ids in BigUint64 format.\n */\nfunction generateBigUint64Array(featureIds) {\n const typedFeatureIds = new BigUint64Array(featureIds.length);\n for (let index = 0; index < featureIds.length; index++) {\n typedFeatureIds[index] = BigInt(featureIds[index]);\n }\n return typedFeatureIds;\n}\n\n/**\n * Generates draco compressed geometry\n * @param {Number} vertexCount\n * @param {Object} convertedAttributes\n * @returns {Promise<object>} - COmpressed geometry.\n */\nasync function generateCompressedGeometry(vertexCount, convertedAttributes, attributes) {\n const {positions, normals, texCoords, colors, featureIds, faceRange} = attributes;\n const indices = new Uint32Array(vertexCount);\n\n for (let index = 0; index < indices.length; index++) {\n indices.set([index], index);\n }\n\n const featureIndices = new Uint32Array(\n convertedAttributes.featureIndices.length ? convertedAttributes.featureIndices : vertexCount\n );\n\n const featureIndex = generateFeatureIndexAttribute(featureIndices, faceRange);\n\n const compressedAttributes = {\n positions,\n normals,\n colors,\n 'feature-index': featureIndex\n };\n\n if (texCoords.length) {\n compressedAttributes.texCoords = texCoords;\n }\n\n const attributesMetadata = {\n 'feature-index': {\n 'i3s-attribute-type': 'feature-index',\n 'i3s-feature-ids': new Int32Array(featureIds)\n }\n };\n\n return new Uint8Array(\n await encode({attributes: compressedAttributes, indices}, DracoWriter, {\n draco: {\n method: 'MESH_SEQUENTIAL_ENCODING',\n attributesMetadata\n }\n })\n );\n}\n\n/**\n * Generates ordered feature indices based on face range\n * @param {Uint32Array} featureIndex\n * @param {Uint32Array} faceRange\n * @returns {Uint32Array}\n */\nfunction generateFeatureIndexAttribute(featureIndex, faceRange) {\n const orderedFeatureIndices = new Uint32Array(featureIndex.length);\n let fillIndex = 0;\n let startIndex = 0;\n\n for (let index = 1; index < faceRange.length; index += 2) {\n const endIndex = (faceRange[index] + 1) * VALUES_PER_VERTEX;\n\n orderedFeatureIndices.fill(fillIndex, startIndex, endIndex);\n\n fillIndex++;\n startIndex = endIndex + 1;\n }\n\n return orderedFeatureIndices;\n}\n"],"file":"geometry-converter.js"}
@@ -22,7 +22,7 @@ function validateObb(tileWarnings, node) {
22
22
  return;
23
23
  }
24
24
 
25
- const title = `OBB of Tile (${node.id}) doesn't fit into Parent (${node.parentNode.id}) tile OBB`;
25
+ const title = "OBB of Tile (".concat(node.id, ") doesn't fit into Parent (").concat(node.parentNode.id, ") tile OBB");
26
26
  tileWarnings.push(title);
27
27
  }
28
28
 
@@ -32,7 +32,7 @@ function validateMbs(tileWarnings, node) {
32
32
  const distanceBetweenCenters = tileMbs.center.distanceTo(parentMbs.center);
33
33
 
34
34
  if (distanceBetweenCenters + tileMbs.radius > parentMbs.radius) {
35
- const title = `MBS of Tile (${node.id}) doesn't fit into Parent (${node.parentNode.id}) tile MBS`;
35
+ const title = "MBS of Tile (".concat(node.id, ") doesn't fit into Parent (").concat(node.parentNode.id, ") tile MBS");
36
36
  tileWarnings.push(title);
37
37
  }
38
38
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/i3s-converter/helpers/node-debug.js"],"names":["OrientedBoundingBox","BoundingSphere","CubeGeometry","Vector3","Ellipsoid","validateNodeBoundingVolumes","node","parentNode","obb","mbs","tileWarnings","validateObb","validateMbs","parentObb","createBoundingBoxFromTileObb","tileVertices","getTileObbVertices","isTileObbInsideParentObb","isAllVerticesInsideBoundingVolume","title","id","push","tileMbs","createBoundingSphereFromTileMbs","parentMbs","distanceBetweenCenters","center","distanceTo","radius","halfSize","quaternion","fromCenterHalfSizeQuaternion","geometry","attributes","positions","Float32Array","POSITION","value","obbCenterCartesian","WGS84","cartographicToCartesian","vertices","i","length","positionsVector","rotatedPositions","transformByQuaternion","add","concat","boundingVolume","isVerticesInsideObb","index","point","cartographicPoint","cartesianToCartographic","distance"],"mappings":"AAAA,SAAQA,mBAAR,EAA6BC,cAA7B,QAAkD,kBAAlD;AACA,SAAQC,YAAR,QAA2B,iBAA3B;AACA,SAAQC,OAAR,QAAsB,eAAtB;AACA,SAAQC,SAAR,QAAwB,qBAAxB;AAGA,OAAO,SAASC,2BAAT,CAAqCC,IAArC,EAA2C;AAChD,MAAI,CA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,EAGrBK,SAAS,CAACQ,CAAC,GAAG,CAAL,CAAT,IAAoBb,QAAQ,CAAC,CAAD,CAHP,CAAxB;AAKA,UAAMgB,gBAAgB,GAAGD,eAAe,CACrCE,qBADsB,CACAxC,IAAI,CAACE,GAAL,CAASsB,UADT,EAEtBiB,GAFsB,CAElBT,kBAFkB,CAAzB;AAGAG,IAAAA,QAAQ,GAAGA,QAAQ,CAACO,MAAT,CAAgBH,gBAAhB,CAAX;AACD;;AAED,SAAOJ,QAAP;AACD;;AAED,SAASvB,iCAAT,CAA2C+B,cAA3C,EAA2Df,SAA3D,EAAsE;AACpE,MAAIgB,mBAAmB,GAAG,IAA1B;;AAEA,OAAK,IAAIC,KAAK,GAAG,CAAjB,EAAoBA,KAAK,GAAGjB,SAAS,CAACS,MAAV,GAAmB,CAA/C,EAAkDQ,KAAK,IAAI,CAA3D,EAA8D;AAC5D,UAAMC,KAAK,GAAG,CAAClB,SAAS,CAACiB,KAAD,CAAV,EAAmBjB,SAAS,CAACiB,KAAK,GAAG,CAAT,CAA5B,EAAyCjB,SAAS,CAACiB,KAAK,GAAG,CAAT,CAAlD,CAAd;AACA,UAAME,iBAAiB,GAAGjD,SAAS,CAACmC,KAAV,CAAgBe,uBAAhB,CAAwCF,KAAxC,CAA1B;AAEA,UAAMG,QAAQ,GAAGN,cAAc,CAACtB,UAAf,CAA0B0B,iBAA1B,CAAjB;;AAEA,QAAIE,QAAQ,GAAG,CAAf,EAAkB;AAChBL,MAAAA,mBAAmB,GAAG,KAAtB;AACA;AACD;AACF;;AAED,SAAOA,mBAAP;AACD","sourcesContent":["import {OrientedBoundingBox, BoundingSphere} from '@math.gl/culling';\nimport {CubeGeometry} from '@luma.gl/engine';\nimport {Vector3} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\n\n// TODO Unite Tile validation logic in i3s-17-and-debug with this code.\nexport function validateNodeBoundingVolumes(node) {\n if (!node.parentNode.obb || !node.parentNode.mbs) {\n return null;\n }\n const tileWarnings = [];\n\n validateObb(tileWarnings, node);\n validateMbs(tileWarnings, node);\n\n return tileWarnings;\n}\n\nfunction validateObb(tileWarnings, node) {\n const parentObb = createBoundingBoxFromTileObb(node.parentNode.obb);\n const tileVertices = getTileObbVertices(node);\n const isTileObbInsideParentObb = isAllVerticesInsideBoundingVolume(parentObb, tileVertices);\n\n if (isTileObbInsideParentObb) {\n return;\n }\n\n const title = `OBB of Tile (${node.id}) doesn't fit into Parent (${node.parentNode.id}) tile OBB`;\n tileWarnings.push(title);\n}\n\nfunction validateMbs(tileWarnings, node) {\n const tileMbs = createBoundingSphereFromTileMbs(node.mbs);\n const parentMbs = createBoundingSphereFromTileMbs(node.parentNode.mbs);\n const distanceBetweenCenters = tileMbs.center.distanceTo(parentMbs.center);\n\n if (distanceBetweenCenters + tileMbs.radius > parentMbs.radius) {\n const title = `MBS of Tile (${node.id}) doesn't fit into Parent (${node.parentNode.id}) tile MBS`;\n tileWarnings.push(title);\n }\n}\n\nfunction createBoundingSphereFromTileMbs(mbs) {\n return new BoundingSphere([mbs[0], mbs[1], mbs[2]], mbs[3]);\n}\n\nfunction createBoundingBoxFromTileObb(obb) {\n const {center, halfSize, quaternion} = obb;\n return new OrientedBoundingBox().fromCenterHalfSizeQuaternion(center, halfSize, quaternion);\n}\n\n// TODO check if Obb generates properly\nfunction getTileObbVertices(node) {\n const geometry = new CubeGeometry();\n const halfSize = node.obb.halfSize;\n const {attributes} = geometry;\n const positions = new Float32Array(attributes.POSITION.value);\n const obbCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(node.obb.center);\n\n let vertices = [];\n\n for (let i = 0; i < positions.length; i += 3) {\n const positionsVector = new Vector3(\n (positions[i] *= halfSize[0]),\n (positions[i + 1] *= halfSize[1]),\n (positions[i + 2] *= halfSize[2])\n );\n const rotatedPositions = positionsVector\n .transformByQuaternion(node.obb.quaternion)\n .add(obbCenterCartesian);\n vertices = vertices.concat(rotatedPositions);\n }\n\n return vertices;\n}\n\nfunction isAllVerticesInsideBoundingVolume(boundingVolume, positions) {\n let isVerticesInsideObb = true;\n\n for (let index = 0; index < positions.length / 3; index += 3) {\n const point = [positions[index], positions[index + 1], positions[index + 2]];\n const cartographicPoint = Ellipsoid.WGS84.cartesianToCartographic(point);\n\n const distance = boundingVolume.distanceTo(cartographicPoint);\n\n if (distance > 0) {\n isVerticesInsideObb = false;\n break;\n }\n }\n\n return isVerticesInsideObb;\n}\n"],"file":"node-debug.js"}
1
+ {"version":3,"sources":["../../../../src/i3s-converter/helpers/node-debug.js"],"names":["OrientedBoundingBox","BoundingSphere","CubeGeometry","Vector3","Ellipsoid","validateNodeBoundingVolumes","node","parentNode","obb","mbs","tileWarnings","validateObb","validateMbs","parentObb","createBoundingBoxFromTileObb","tileVertices","getTileObbVertices","isTileObbInsideParentObb","isAllVerticesInsideBoundingVolume","title","id","push","tileMbs","createBoundingSphereFromTileMbs","parentMbs","distanceBetweenCenters","center","distanceTo","radius","halfSize","quaternion","fromCenterHalfSizeQuaternion","geometry","attributes","positions","Float32Array","POSITION","value","obbCenterCartesian","WGS84","cartographicToCartesian","vertices","i","length","positionsVector","rotatedPositions","transformByQuaternion","add","concat","boundingVolume","isVerticesInsideObb","index","point","cartographicPoint","cartesianToCartographic","distance"],"mappings":"AAAA,SAAQA,mBAAR,EAA6BC,cAA7B,QAAkD,kBAAlD;AACA,SAAQC,YAAR,QAA2B,iBAA3B;AACA,SAAQC,OAAR,QAAsB,eAAtB;AACA,SAAQC,SAAR,QAAwB,qBAAxB;AAGA,OAAO,SAASC,2BAAT,CAAqCC,IAArC,EAA2C;AAChD,MAAI,CAACA,IAAI,CAACC,UAAL,CAAgBC,GAAjB,IAAwB,CAACF,IAAI,CAACC,UAAL,CAAgBE,GAA7C,EAAkD;AAChD,WAAO,IAAP;AACD;;AACD,QAAMC,YAAY,GAAG,EAArB;AAEAC,EAAAA,WAAW,CAACD,YAAD,EAAeJ,IAAf,CAAX;AACAM,EAAAA,WAAW,CAACF,YAAD,EAAeJ,I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,CAACO,MAAT,CAAgBH,gBAAhB,CAAX;AACD;;AAED,SAAOJ,QAAP;AACD;;AAED,SAASvB,iCAAT,CAA2C+B,cAA3C,EAA2Df,SAA3D,EAAsE;AACpE,MAAIgB,mBAAmB,GAAG,IAA1B;;AAEA,OAAK,IAAIC,KAAK,GAAG,CAAjB,EAAoBA,KAAK,GAAGjB,SAAS,CAACS,MAAV,GAAmB,CAA/C,EAAkDQ,KAAK,IAAI,CAA3D,EAA8D;AAC5D,UAAMC,KAAK,GAAG,CAAClB,SAAS,CAACiB,KAAD,CAAV,EAAmBjB,SAAS,CAACiB,KAAK,GAAG,CAAT,CAA5B,EAAyCjB,SAAS,CAACiB,KAAK,GAAG,CAAT,CAAlD,CAAd;AACA,UAAME,iBAAiB,GAAGjD,SAAS,CAACmC,KAAV,CAAgBe,uBAAhB,CAAwCF,KAAxC,CAA1B;AAEA,UAAMG,QAAQ,GAAGN,cAAc,CAACtB,UAAf,CAA0B0B,iBAA1B,CAAjB;;AAEA,QAAIE,QAAQ,GAAG,CAAf,EAAkB;AAChBL,MAAAA,mBAAmB,GAAG,KAAtB;AACA;AACD;AACF;;AAED,SAAOA,mBAAP;AACD","sourcesContent":["import {OrientedBoundingBox, BoundingSphere} from '@math.gl/culling';\nimport {CubeGeometry} from '@luma.gl/engine';\nimport {Vector3} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\n\n// TODO Unite Tile validation logic in i3s-17-and-debug with this code.\nexport function validateNodeBoundingVolumes(node) {\n if (!node.parentNode.obb || !node.parentNode.mbs) {\n return null;\n }\n const tileWarnings = [];\n\n validateObb(tileWarnings, node);\n validateMbs(tileWarnings, node);\n\n return tileWarnings;\n}\n\nfunction validateObb(tileWarnings, node) {\n const parentObb = createBoundingBoxFromTileObb(node.parentNode.obb);\n const tileVertices = getTileObbVertices(node);\n const isTileObbInsideParentObb = isAllVerticesInsideBoundingVolume(parentObb, tileVertices);\n\n if (isTileObbInsideParentObb) {\n return;\n }\n\n const title = `OBB of Tile (${node.id}) doesn't fit into Parent (${node.parentNode.id}) tile OBB`;\n tileWarnings.push(title);\n}\n\nfunction validateMbs(tileWarnings, node) {\n const tileMbs = createBoundingSphereFromTileMbs(node.mbs);\n const parentMbs = createBoundingSphereFromTileMbs(node.parentNode.mbs);\n const distanceBetweenCenters = tileMbs.center.distanceTo(parentMbs.center);\n\n if (distanceBetweenCenters + tileMbs.radius > parentMbs.radius) {\n const title = `MBS of Tile (${node.id}) doesn't fit into Parent (${node.parentNode.id}) tile MBS`;\n tileWarnings.push(title);\n }\n}\n\nfunction createBoundingSphereFromTileMbs(mbs) {\n return new BoundingSphere([mbs[0], mbs[1], mbs[2]], mbs[3]);\n}\n\nfunction createBoundingBoxFromTileObb(obb) {\n const {center, halfSize, quaternion} = obb;\n return new OrientedBoundingBox().fromCenterHalfSizeQuaternion(center, halfSize, quaternion);\n}\n\n// TODO check if Obb generates properly\nfunction getTileObbVertices(node) {\n const geometry = new CubeGeometry();\n const halfSize = node.obb.halfSize;\n const {attributes} = geometry;\n const positions = new Float32Array(attributes.POSITION.value);\n const obbCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(node.obb.center);\n\n let vertices = [];\n\n for (let i = 0; i < positions.length; i += 3) {\n const positionsVector = new Vector3(\n (positions[i] *= halfSize[0]),\n (positions[i + 1] *= halfSize[1]),\n (positions[i + 2] *= halfSize[2])\n );\n const rotatedPositions = positionsVector\n .transformByQuaternion(node.obb.quaternion)\n .add(obbCenterCartesian);\n vertices = vertices.concat(rotatedPositions);\n }\n\n return vertices;\n}\n\nfunction isAllVerticesInsideBoundingVolume(boundingVolume, positions) {\n let isVerticesInsideObb = true;\n\n for (let index = 0; index < positions.length / 3; index += 3) {\n const point = [positions[index], positions[index + 1], positions[index + 2]];\n const cartographicPoint = Ellipsoid.WGS84.cartesianToCartographic(point);\n\n const distance = boundingVolume.distanceTo(cartographicPoint);\n\n if (distance > 0) {\n isVerticesInsideObb = false;\n break;\n }\n }\n\n return isVerticesInsideObb;\n}\n"],"file":"node-debug.js"}
@@ -112,8 +112,8 @@ export default class NodePages {
112
112
  for (const [index, nodePage] of this.nodePages.entries()) {
113
113
  const nodePageStr = JSON.stringify(nodePage);
114
114
  const slpkPath = join(layers0Path, 'nodepages');
115
- promises.push(this.writeFile(slpkPath, nodePageStr, `${index.toString()}.json`));
116
- fileMap[`nodePages/${index.toString()}.json.gz`] = `${slpkPath}.json.gz`;
115
+ promises.push(this.writeFile(slpkPath, nodePageStr, "".concat(index.toString(), ".json")));
116
+ fileMap["nodePages/".concat(index.toString(), ".json.gz")] = "".concat(slpkPath, ".json.gz");
117
117
  }
118
118
 
119
119
  const metadata = transform({