MaterialXWeb 0.0.2
Utilities for using MaterialX Packages with Web clients
Loading...
Searching...
No Matches
AmbientCGLoader Class Reference

Public Member Functions

 constructor ()
 Class to load materials from the AmbientCG site.
 
 setDebugging (debug=true)
 
 getMaterialNames (key='assetId')
 
 writeMaterialList (materialList, filename)
 
 buildDownloadAttribute (imageFormat='PNG', imageResolution='1')
 
 splitDownloadAttribute (downloadAttribute)
 
 getDownloadedMaterialInformation ()
 
 clearDownloadMaterial ()
 
 writeDownloadedMaterialToFile (path='')
 
async downloadMaterialAsset (assetId, imageFormat='PNG', imageResolution='1', downloadAttributeKey='downloadAttribute', downloadLinkKey='downloadLink')
 
 findMaterial (assetId, key='assetId')
 
 loadMaterialsList (fileName)
 
async downloadMaterialsList ()
 
 getDataBase ()
 
 getDataBaseMaterialList ()
 
async downloadAssetDatabase ()
 
 writeDatabaseToFile (filename)
 
 validateMaterialXDocument (doc)
 
 addComment (doc, commentString)
 
 getMaterialXString (doc)
 

Detailed Description

Definition at line 6 of file JsAmbientCGLoader.js.

Member Function Documentation

◆ addComment()

AmbientCGLoader::addComment ( doc,
commentString )

Add a comment to the MaterialX document.

Parameters
{Object}doc - The MaterialX document to add the comment to.
{string}commentString - The comment string to add.

Definition at line 319 of file JsAmbientCGLoader.js.

319 {
324
325 const comment = doc.addChildOfCategory('comment');
326 comment.setDocString(commentString);
327 }

◆ buildDownloadAttribute()

AmbientCGLoader::buildDownloadAttribute ( imageFormat = 'PNG',
imageResolution = '1' )

Build the download attribute string for a given image format and resolution.

Parameters
{string}imageFormat - The image format to download.
{string}imageResolution - The image resolution to download.
Returns
{string} The download attribute string.

Definition at line 64 of file JsAmbientCGLoader.js.

64 {
70
71 return `${imageResolution}K-${imageFormat}`;
72 }

◆ clearDownloadMaterial()

AmbientCGLoader::clearDownloadMaterial ( )

Clear any cached current material asset.

Definition at line 95 of file JsAmbientCGLoader.js.

95 {
98
99 if (this.downloadMaterial) {
100 this.downloadMaterial = null;
101 }
102 this.downloadMaterialFileName = '';
103 }

◆ constructor()

AmbientCGLoader::constructor ( )

Class to load materials from the AmbientCG site.

The class can convert the materials to MaterialX format for given target shading models.

Parameters
{Object}mxModule - The MaterialX module. Required.
{Object}mxStdlib - The MaterialX standard library. Optional.

Definition at line 13 of file JsAmbientCGLoader.js.

13 {
14 if (AmbientCGLoader.instance) {
15 return AmbientCGLoader.instance;
16 }
17
18 this.logger = console;
19 this.database = {};
20 this.assets = {};
21 this.materials = null;
22 this.materialNames = [];
23 this.csvMaterials = null;
24 this.downloadMaterial = null;
25 this.downloadMaterialFileName = '';
26
27 // Cache the instance
28 AmbientCGLoader.instance = this;
29 }

◆ downloadAssetDatabase()

async AmbientCGLoader::downloadAssetDatabase ( )

Download the asset database for materials from the ambientCG site.

Returns
{Object} The downloaded database.

Definition at line 253 of file JsAmbientCGLoader.js.

253 {
257
258 this.database = {};
259 this.assets = null;
260
261 const url = 'https://ambientcg.com/api/v2/full_json';
262 const headers = { Accept: 'application/json' };
263 const params = {
264 method: 'PBRPhotogrammetry',
265 type: 'Material',
266 sort: 'Alphabet',
267 };
268
269 try {
270 const response = await axios.get(url, { headers, params });
271 if (response.status === 200) {
272 this.database = response.data;
273 this.assets = this.database.foundAssets;
274 } else {
275 this.logger.error(`Status: ${response.status}, ${response.data}`);
276 }
277 } catch (error) {
278 this.logger.error(`Error downloading asset database: ${error}`);
279 }
280
281 return this.database;
282 }

◆ downloadMaterialAsset()

async AmbientCGLoader::downloadMaterialAsset ( assetId,
imageFormat = 'PNG',
imageResolution = '1',
downloadAttributeKey = 'downloadAttribute',
downloadLinkKey = 'downloadLink' )

Download a material with a given id and format + resolution for images.

Parameters
{string}assetId - The string id of the material.
{string}imageFormat - The image format to download. Default is PNG.
{string}imageResolution - The image resolution to download. Default is 1.
{string}downloadAttributeKey - The download attribute key. Default is 'downloadAttribute'.
{string}downloadLinkKey - The download link key. Default is 'downloadLink'.
Returns
{string} File name of downloaded content.

Definition at line 121 of file JsAmbientCGLoader.js.

121 {
130
132
133 const items = this.findMaterial(assetId);
134 const target = this.buildDownloadAttribute(imageFormat, imageResolution);
135 let url = '';
136 let downloadAttribute = '';
137
138 items.forEach(item => {
139 downloadAttribute = item[downloadAttributeKey];
140 if (downloadAttribute === target) {
141 url = item[downloadLinkKey];
142 this.logger.info(`Found Asset: ${assetId}. Download Attribute: ${downloadAttribute} -> ${url}`);
143 }
144 });
145
146 if (!url) {
147 this.logger.error(`No download link found for asset: ${assetId}, attribute: ${target}`);
148 return '';
149 }
150
151 this.downloadMaterialFileName = url.split('file=')[1];
152 console.log('>>>> URL:', url, 'Filename:', this.downloadMaterialFileName);
153
154 try {
155 const response = await fetch(url);
156 if (!response.ok) {
157 throw new Error(`HTTP error! Status: ${response.status}`);
158 }
159
160 // Get the response as an ArrayBuffer
161 const arrayBuffer = await response.arrayBuffer();
162
163 // Convert ArrayBuffer to Buffer
164 this.downloadMaterial = Buffer.from(arrayBuffer);
165 this.logger.info(`Material file downloaded: ${this.downloadMaterialFileName}`);
166
167 } catch (error) {
168 this.downloadMaterialFileName = '';
169 this.logger.error(`Error occurred while downloading the file: ${error}`);
170 }
171
172 return this.downloadMaterialFileName;
173 }
buildDownloadAttribute(imageFormat='PNG', imageResolution='1')
findMaterial(assetId, key='assetId')

◆ downloadMaterialsList()

async AmbientCGLoader::downloadMaterialsList ( )

Download the list of materials from the ambientCG site.

Returns
{Array} Materials list.

Definition at line 199 of file JsAmbientCGLoader.js.

199 {
203
204 //const url = 'https://ambientCG.com/api/v2/downloads_csv';
205 const headers = { Accept: 'application/csv' };
206 const params = {
207 method: 'PBRPhotogrammetry',
208 type: 'Material',
209 sort: 'Alphabet',
210 };
211
212 const url = new URL('https://ambientCG.com/api/v2/downloads_csv');
213 url.searchParams.append('method', 'PBRPhotogrammetry');
214 url.searchParams.append('type', 'Material');
215 url.searchParams.append('sort', 'Alphabet');
216
217 this.logger.info('Downloading materials CSV list...');
218 try {
219 const response = await fetch(url, { headers });
220 if (response.status === 200) {
221 const csvContent = await response.text(); // Extract CSV content as text
222 this.csvMaterials = csvContent;
223 this.materials = parse(csvContent, { columns: true });
224 this.logger.info('Downloaded CSV material list as JSON.');
225 } else {
226 this.materials = null;
227 this.logger.warning(`Failed to fetch the CSV material content. HTTP status code: ${response.status}`);
228 }
229 } catch (error) {
230 this.materials = null;
231 this.logger.error(`Error downloading materials list: ${error}`);
232 }
233
234 return this.materials;
235 }

◆ findMaterial()

AmbientCGLoader::findMaterial ( assetId,
key = 'assetId' )

Get the list of materials matching a material identifier.

Parameters
{string}assetId - Material string identifier.
{string}key - The key to lookup asset identifiers. Default is 'assetId'.
Returns
{Array} List of materials, or empty array if not found.

Definition at line 175 of file JsAmbientCGLoader.js.

175 {
181
182 if (this.materials) {
183 return this.materials.filter(item => item[key] === assetId);
184 }
185 return [];
186 }

◆ getDataBase()

AmbientCGLoader::getDataBase ( )

Get asset database.

Returns
{Object} Asset database.

Definition at line 237 of file JsAmbientCGLoader.js.

237 {
241
242 return this.database;
243 }

◆ getDataBaseMaterialList()

AmbientCGLoader::getDataBaseMaterialList ( )

Get asset database material list.

Returns
{Array} Material list.

Definition at line 245 of file JsAmbientCGLoader.js.

245 {
249
250 return this.assets;
251 }

◆ getDownloadedMaterialInformation()

AmbientCGLoader::getDownloadedMaterialInformation ( )

Get the current downloaded material information.

Returns
{Object} The downloaded material information.

Definition at line 84 of file JsAmbientCGLoader.js.

84 {
88
89 return {
90 filename: this.downloadMaterialFileName,
91 content: this.downloadMaterial
92 };
93 }

◆ getMaterialNames()

AmbientCGLoader::getMaterialNames ( key = 'assetId')

Get the list of material names.

Parameters
{string}key - The key to use for the material name. Default is 'assetId'.
Returns
{Array} The list of material names.

Definition at line 39 of file JsAmbientCGLoader.js.

39 {
44
45 this.materialNames = [];
46 const uniqueNames = new Set();
47 if (this.materials) {
48 this.materials.forEach(item => uniqueNames.add(item[key]));
49 }
50 this.materialNames = Array.from(uniqueNames).sort();
51 return this.materialNames;
52 }

◆ getMaterialXString()

AmbientCGLoader::getMaterialXString ( doc)

Convert the MaterialX document to a string.

Parameters
{Object}doc - The MaterialX document to convert.
Returns
{string} The MaterialX document as a string.

Definition at line 329 of file JsAmbientCGLoader.js.

329 {
334
335 if (!this.mx) {
336 this.logger.error('MaterialX module is required');
337 return;
338 }
339
340 const writeOptions = this.mx.XmlWriteOptions();
341 writeOptions.writeXIncludeEnable = false;
342 writeOptions.elementPredicate = this.skipLibraryElement;
343 return this.mx.writeToXmlString(doc, writeOptions);
344 }

◆ loadMaterialsList()

AmbientCGLoader::loadMaterialsList ( fileName)

Load in the list of downloadable materials from file.

Parameters
{string}fileName - Name of JSON containing list.
Returns
{Array} Materials list.

Definition at line 188 of file JsAmbientCGLoader.js.

188 {
193
194 this.materials = JSON.parse(fs.readFileSync(fileName, 'utf8'));
195 this.logger.info(`Loaded materials list from: ${fileName}`);
196 return this.materials;
197 }

◆ setDebugging()

AmbientCGLoader::setDebugging ( debug = true)

Set the debugging level for the logger.

Parameters
{boolean}debug - True to set the logger to debug level, otherwise False.

Definition at line 31 of file JsAmbientCGLoader.js.

31 {
35
36 this.logger.level = debug ? 'debug' : 'info';
37 }

◆ splitDownloadAttribute()

AmbientCGLoader::splitDownloadAttribute ( downloadAttribute)

Split the download attribute into image format and resolution.

Parameters
{string}downloadAttribute - The download attribute string.
Returns
{Array} A tuple of (imageFormat, imageResolution).
Note
The download attribute is in the format: '1K-PNG'.

Definition at line 74 of file JsAmbientCGLoader.js.

74 {
80
81 const parts = downloadAttribute.split('-');
82 }

◆ validateMaterialXDocument()

AmbientCGLoader::validateMaterialXDocument ( doc)

Validate the MaterialX document.

Parameters
{Object}doc - The MaterialX document to validate.
Returns
{Array} A tuple of (valid, errors) where valid is True if the document is valid, and errors is a list of errors if the document is invalid.

Definition at line 299 of file JsAmbientCGLoader.js.

299 {
304
305 if (!this.mx) {
306 this.logger.error('MaterialX module is required');
307 return [false, ''];
308 }
309
310 if (!doc) {
311 this.logger.warning('MaterialX document is required');
312 return [false, ''];
313 }
314
315 const valid = doc.validate();
316 return [valid, valid ? '' : 'Validation failed'];
317 }

◆ writeDatabaseToFile()

AmbientCGLoader::writeDatabaseToFile ( filename)

Write the database file.

Parameters
{string}filename - The filename to write the JSON file to.
Returns
{boolean} True if the file was written successfully, otherwise False.

Definition at line 284 of file JsAmbientCGLoader.js.

284 {
289
290 if (!this.database) {
291 this.logger.warning('No database to write');
292 return false;
293 }
294
295 fs.writeFileSync(filename, JSON.stringify(this.database, null, 4));
296 return true;
297 }

◆ writeDownloadedMaterialToFile()

AmbientCGLoader::writeDownloadedMaterialToFile ( path = '')

Write the currently downloaded file to file.

Parameters
{string}path - The output path for the material. Default is empty.

Definition at line 105 of file JsAmbientCGLoader.js.

105 {
109
110 const haveDownload = this.downloadMaterialFileName && this.downloadMaterial;
111 if (!haveDownload) {
112 this.logger.warning('No current material downloaded');
113 return;
114 }
115
116 const filename = `${path}/${this.downloadMaterialFileName}`;
117 fs.writeFileSync(filename, this.downloadMaterial);
118 this.logger.info(`Saved downloaded material to: ${filename}`);
119 }

◆ writeMaterialList()

AmbientCGLoader::writeMaterialList ( materialList,
filename )

Write the material list in JSON format to a file.

Parameters
{Array}materialList - The list of materials to write.
{string}filename - The file path to write the list to.

Definition at line 54 of file JsAmbientCGLoader.js.

54 {
59
60 this.logger.info(`Writing material list to file: ${filename}`);
61 fs.writeFileSync(filename, JSON.stringify(materialList, null, 4));
62 }

The documentation for this class was generated from the following file: