### Download and Render Material Examples Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/index.html Download material examples and optionally render them. PhysicallyBased rendering requires MaterialXView to be installed. ```bash ./build_examples.sh ``` -------------------------------- ### Install and Build Packages Source: https://github.com/kwokcb/materialxmaterials/blob/main/README.md Install dependent packages and build or run a package from the package folders. ```shell npm install # Install dependent packages npm run [build/start] # Build distribution or run the package ``` -------------------------------- ### Start GPUOpen Material Download via npm (NodeJS) Source: https://github.com/kwokcb/materialxmaterials/blob/main/README.html Initiate the download of a specific material, 'Moss Green Solid Granite', using the NodeJS GPUOpen loader via npm start. ```bash npm start -- -n "Moss Green Solid Granite" ``` -------------------------------- ### Install Javascript Dependencies and Build Source: https://github.com/kwokcb/materialxmaterials/blob/main/README.html Install Node.js dependent packages and then build the distribution or run the Javascript package. ```bash npm install ``` ```bash npm run [build/start] ``` -------------------------------- ### Install materialxMaterials Package Source: https://github.com/kwokcb/materialxmaterials/blob/main/examples/materialxMaterials_tutorial.ipynb Install the materialxMaterials package by cloning the repository and using pip. ```python # pip install . ``` -------------------------------- ### Download Sample Materials Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/index.html Use this build script to download sample materials using the installed package. ```bash ./build_download.sh ``` -------------------------------- ### Run GPUOpen Loader (NodeJS) Source: https://github.com/kwokcb/materialxmaterials/blob/main/README.html Run the GPUOpen loader utility from the javascript folder using npm start with arguments. ```bash npm start -- [] ``` -------------------------------- ### Initialize GPUOpenLoader and Get Material Count Source: https://github.com/kwokcb/materialxmaterials/blob/main/examples/materialxMaterials_tutorial.ipynb Initialize the GPUOpenLoader to download materials from the AMD GPUOpen database and retrieve the total count of available materials. ```python from materialxMaterials import GPUOpenLoader loader = GPUOpenLoader.GPUOpenMaterialLoader() # Download materials materials = loader.getMaterials() materialNames = loader.getMaterialNames() materialCount = len(materialNames) print(f'Available number of materials: {materialCount}') ``` -------------------------------- ### Download Materials from PhysicallyBased Database Source: https://github.com/kwokcb/materialxmaterials/blob/main/examples/materialxMaterials_tutorial.ipynb Initializes the PhysicallyBasedMaterialXLoader and downloads a list of available materials from the PhysicallyBased database. Requires MaterialX and the library to be installed. ```python from materialxMaterials import physicallyBasedMaterialX as pbmx import MaterialX as mx jsonMat = None pb_loader = pbmx.PhysicallyBasedMaterialLoader(mx, None) jsonMat = pb_loader.getMaterialsFromURL() print(f'Found {len(jsonMat)} materials in PhysicallyBased MaterialX library.') ``` -------------------------------- ### Download Material List from AmbientCG Source: https://github.com/kwokcb/materialxmaterials/blob/main/examples/materialxMaterials_tutorial.ipynb Initializes the AmbientCGLoader and downloads the list of available materials from the ambientCG database. Requires MaterialX and the library to be installed. ```python from materialxMaterials import ambientCGLoader import MaterialX as mx # Create the loader loader = ambientCGLoader.AmbientCGLoader(mx, None) # Download the list of available materials materials = loader.downloadMaterialsList() materialNames = loader.getMaterialNames() materialCount = len(materialNames) print(f'Found {materialCount} materials in AmbientCG library') ``` -------------------------------- ### Build and Update Package Data Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/index.html Execute the build script to install the package and run commands for updating package data. ```bash ./build.sh ``` -------------------------------- ### Get Material Previews Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_g_p_u_open_loader_8py_source.html Returns a list of material previews. Optionally recomputes them if `force` is True or if they haven't been loaded. ```python if not self.materialPreviews or force: self.computeMaterialPreviews() return self.materialPreviews ``` -------------------------------- ### getMaterials Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_g_p_u_open_material_loader.html Gets lists of materials from the GPUOpen material database. It fetches materials in batches, with a default batch size of 50. ```APIDOC ## getMaterials(batchSize = 50) ### Description Get lists of materials from the GPUOpen material database. It fetches materials in batches, with a default batch size of 50. ### Parameters #### Path Parameters - **batchSize** (number) - Optional - Number of materials to fetch per batch. Defaults to 50. ### Returns #### Success Response - **List** - List of material lists ``` -------------------------------- ### MaterialX Library Inspector Setup Source: https://github.com/kwokcb/materialxmaterials/blob/main/README.html This NodeJS/Express application serves as a general purpose MaterialX material inspector, supporting ambientCg and GPUOpen. ```javascript const express = require('express'); const path = require('path'); const app = express(); const port = process.env.PORT || 3000; // Serve static files from the 'public' directory app.use(express.static(path.join(__dirname, 'public'))); // Example route for fetching materials (implementation would go here) app.get('/api/materials', (req, res) => { // Logic to fetch and return material data res.json({ message: 'Material data endpoint' }); }); app.listen(port, () => { console.log(`MaterialX Inspector listening at http://localhost:${port}`); }); ``` -------------------------------- ### Install Python Package Source: https://github.com/kwokcb/materialxmaterials/blob/main/README.md Installs the MaterialX Python package using pip. This command also handles the installation of dependent Python packages. ```shell pip install . ``` -------------------------------- ### Build API Documentation Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/index.html Prepare documentation and run Doxygen to build API documentation. ```bash ./buildDocs.sh ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/index.html Install dependent packages for Javascript utilities using npm. This should be run from the package folders. ```bash npm install ``` -------------------------------- ### Initialize Material and Package URLs Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_g_p_u_open_material_loader.html Sets up the base URLs for fetching materials and packages. This is part of the class constructor. ```javascript this.url = `${this.rootUrl}/materials`; this.packageUrl = `${this.rootUrl}/packages`; ``` -------------------------------- ### Create MaterialX Document and Import Library Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/classmaterialx_materials_1_1physically_based_material_x_1_1_physically_based_material_loader.html Initializes a MaterialX document and imports the standard library. This is a prerequisite for adding shaders and materials. ```python self.doc = self.mx.createDocument() if not self.doc: return None self.doc.importLibrary(self.stdlib) ``` -------------------------------- ### Install npm Dependency Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/DoxygenAwesome/README.md Add the Doxygen Awesome CSS theme as a development dependency to your project using npm. This command installs a specific version of the theme. ```sh cd your-project npm install https://github.com/jothepro/doxygen-awesome-css#v2.4.1 --save-dev ls -l node_modules/@jothepro/doxygen-awesome-css ``` -------------------------------- ### Load Remapping from Installed Package Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/classmaterialx_materials_1_1physically_based_material_x_1_1_physically_based_material_loader.html Reads material remapping configurations from a JSON file within the installed package. Handles FileNotFoundError by logging a warning and using default keys. ```python import importlib.resources # Read PhysicallyBasedToMtlxMappings.json installed package self.remapMap = {} try: with importlib.resources.files("materialxMaterials.data").joinpath(self.remapFile).open("r", encoding="utf-8") as json_file: self.logger.info(f'> Load remapping from installed package: {self.remapFile}') self.remapMap = json.load(json_file) except FileNotFoundError: self.logger.warning('> No remapping file found in installed package. Using default remapping keys.') ``` -------------------------------- ### Initialize UI and Theme - JavaScript Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/main_8js_source.html Sets up the application's theme based on user preferences and handles theme toggling. It also injects necessary CSS for disabled elements. ```javascript function setTheme(mode) { document.documentElement.setAttribute('data-bs-theme', mode); document.getElementById('themeIcon').className = mode === 'dark' ? 'bi bi-sun' : 'bi bi-moon'; } document.addEventListener('DOMContentLoaded', function () { // Inject CSS for disabled-grid if not present if (!document.getElementById('disabled-grid-style')) { const style = document.createElement('style'); style.id = 'disabled-grid-style'; style.textContent = '.disabled-grid { pointer-events: none !important; opacity: 0.5 !important; filter: grayscale(0.5); transition: opacity 0.3s; }'; document.head.appendChild(style); } // Parse desiredTextureFormat from URL query string const urlParams = new URLSearchParams(window.location.search); const urlFormat = urlParams.get('desiredTextureFormat'); if (urlFormat) { testFormat = urlFormat.toLowerCase(); // This appears to be all that PolyHaven supports for now if (testFormat === 'jpg' || testFormat === 'png' || testFormat === 'exr') { desiredTextureFormat = testFormat; console.log('Texture format set from URL:', desiredTextureFormat); } } // Initialize the Poly Haven API polyHavenAPI = new [JsPolyHavenAPILoader](class_js_poly_haven_a_p_i_loader.html)(); // Set theme based on browser preference or default to light mode const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)").matches; if (prefersDarkScheme) { setTheme('dark'); } else { setTheme('light'); } document.getElementById('themeToggleBtn').addEventListener('click', function () { const isDark = document.documentElement.getAttribute('data-bs-theme') === 'dark'; setTheme(isDark ? 'light' : 'dark'); }); // https://icons.getbootstrap.com/icons/card-image/ const svgString = ` `; // Convert to base64 data URL } ``` -------------------------------- ### Get MaterialX Document Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/physically_based_material_x_8py_source.html Retrieves the MaterialX document object. ```python def getMaterialXDocument(self) -> mx.Document: ''' Get the MaterialX document ``` -------------------------------- ### __init__ Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/classmaterialx_materials_1_1poly_haven_loader_1_1_poly_haven_loader.html Initializes the PolyHavenLoader with API endpoints and headers required for interacting with the PolyHaven API. ```APIDOC ## __init__ ### Description Initializes the PolyHavenLoader with API endpoints and headers. ### Method __init__ ### Parameters - **self** (*type*): Description ### Code Example ```python loader = PolyHavenLoader() ``` ``` -------------------------------- ### getJSONMaterialNames() Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader.html Get a list of the names of the Physically Based Materials. ```APIDOC ## getJSONMaterialNames() ### Description Retrieves a list containing the names of all available Physically Based Materials. ### Method GET (implied) ### Endpoint (Not specified, likely an internal method) ### Returns - `{string[]}` - A list of Physically Based Material names. ``` -------------------------------- ### get_physlib_definition_name Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_js_material_x_physically_based_8js_source.html Gets the name of the Physically Based MaterialX definition. ```APIDOC ## get_physlib_definition_name ### Description Gets the name of the Physically Based MaterialX definition. ### Method GET ### Endpoint /get_physlib_definition_name ### Parameters None ### Response #### Success Response (200) - **physlib_definition_name** (string) - The name of the Physically Based MaterialX definition. ``` -------------------------------- ### GPUOpen Loader Package Setup Source: https://github.com/kwokcb/materialxmaterials/blob/main/README.html This Node.js package allows access to fetch materials from the GPU Open site. It requires node-fetch for HTTP requests and yargs for command line parsing. ```javascript const fetch = require('node-fetch'); const yargs = require('yargs/yargs'); const { hideBin } = require('yargs/helpers'); const argv = yargs(hideBin(process.argv)) .option('url', { alias: 'u', type: 'string', description: 'URL of the material to fetch' }) .help() .alias('help', 'h') .argv; async function fetchMaterial(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const materialData = await response.json(); console.log('Material data fetched:', materialData); } catch (error) { console.error('Error fetching material:', error); } } if (argv.url) { fetchMaterial(argv.url); } else { console.log('Please provide a URL using the --url option.'); } ``` -------------------------------- ### get_physlib_category Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_js_material_x_physically_based_8js_source.html Gets the Physically Based MaterialX surface category. ```APIDOC ## get_physlib_category ### Description Gets the Physically Based MaterialX surface category. ### Method GET ### Endpoint /get_physlib_category ### Parameters None ### Response #### Success Response (200) - **physlib_category** (string) - The category string for the Physically Based MaterialX surface. ``` -------------------------------- ### get_physlib_definition Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_js_material_x_physically_based_8js_source.html Gets the Physically Based MaterialX definition NodeDef. ```APIDOC ## get_physlib_definition ### Description Gets the Physically Based MaterialX definition NodeDef. ### Method GET ### Endpoint /get_physlib_definition ### Parameters None ### Response #### Success Response (200) - **nodeDef** (object) - The NodeDef for the Physically Based MaterialX definition. Returns null if `physlib` is not available. ``` -------------------------------- ### get_physlib Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_js_material_x_physically_based_8js_source.html Gets the Physically Based MaterialX definition library. ```APIDOC ## get_physlib ### Description Gets the Physically Based MaterialX definition library. ### Method GET ### Endpoint /get_physlib ### Parameters None ### Response #### Success Response (200) - **physlib** (object) - The Physically Based MaterialX definition library. ``` -------------------------------- ### Get MaterialX Document Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/classmaterialx_materials_1_1physically_based_material_x_1_1_physically_based_material_loader.html Retrieves the MaterialX document managed by the loader. ```python def getMaterialXDocument(self) -> mx.Document: ''' Get the MaterialX document @return The MaterialX document ''' return self.doc ``` -------------------------------- ### get_physlib_implementation_name Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_js_material_x_physically_based_8js_source.html Gets the name of the Physically Based MaterialX implementation (nodegraph). ```APIDOC ## get_physlib_implementation_name ### Description Gets the name of the Physically Based MaterialX implementation (nodegraph). ### Method GET ### Endpoint /get_physlib_implementation_name ### Parameters None ### Response #### Success Response (200) - **physlib_implementation_name** (string) - The name of the Physically Based MaterialX implementation. ``` -------------------------------- ### Fetch Materials in Batches using JsGPUOpenMaterialLoader Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_g_p_u_open_material_loader.html Initiates the process of fetching materials from the GPUOpen material database in batches. It sets up the initial URL with batch size and offset parameters. This method is asynchronous and prepares the instance for subsequent material retrieval. ```javascript this.materials = []; this.materialNames = []; let url = this.url; // Get batches of materials. Start with the first N. let params = new URLSearchParams({ limit: batchSize, offset: 0 }); // Append & parameters to url using params if (params) { url += '?' + params.toString(); } let haveMoreMaterials = true; ``` -------------------------------- ### getInputRemapping Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader-members.html Gets the input remapping configuration for a given shading model. ```APIDOC ## getInputRemapping(shadingModel) ### Description Retrieves the input remapping rules associated with a specific shading model. This is used to map generic inputs to specific implementations. ### Method N/A (This is a method call within the JsPhysicallyBasedMaterialLoader class) ### Endpoint N/A ### Parameters - **shadingModel** (string) - Required - The name of the shading model for which to retrieve input remapping. ### Request Example N/A ### Response - **remapping**: Object - An object containing the input remapping configuration for the specified shading model. ``` -------------------------------- ### Initialize GPUOpenMaterialLoader Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/classmaterialx_materials_1_1_g_p_u_open_loader_1_1_g_p_u_open_material_loader.html Initializes the GPUOpen material loader by setting up API endpoint URLs and initializing logging. ```python def __init__(self): ''' Initialize the GPUOpen material loader. ''' self.root_url = 'https://api.matlib.gpuopen.com/api' self.url = self.root_url + '/materials' self.package_url = self.root_url + '/packages' self.render_url = self.root_url + '/renders' self.materialPreviews = None self.materials = None self.materialNames = None self.renders = None self.logger = logging.getLogger('GPUO') logging.basicConfig(level=logging.INFO) ``` -------------------------------- ### Get MaterialX Document Object Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader.html Retrieves the internal MaterialX document object. ```javascript getMaterialXDocument() { return this.doc; } ``` -------------------------------- ### Download GPUOpen Material by Name (NodeJS) Source: https://github.com/kwokcb/materialxmaterials/blob/main/README.html Download a specific material, 'Moss Green Solid Granite', using the NodeJS GPUOpen loader script. ```bash node gpuOpenFetch.js -n "Moss Green Solid Granite" ``` -------------------------------- ### Build or Run Javascript Package Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/index.html Build the distribution or run the Javascript package from the package folders. ```bash npm run [build/start] ``` -------------------------------- ### Get Asset Database Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/classmaterialx_materials_1_1ambient_c_g_loader_1_1_ambient_c_g_loader.html Retrieves the asset database, which is stored as an instance variable. ```python def getDataBase(self): ''' @brief Get asset database @return Asset database ''' return self.database ``` -------------------------------- ### Main Entry Point for MaterialXMaterials Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/____main_____8py_source.html The main function parses command-line arguments to select and execute specific material loader scripts (e.g., physicallyBasedMaterialXCmd.py, GPUOpenLoaderCmd.py). It handles help messages and validates the provided command. ```python import sys, os import subprocess def main() -> int: ''' Main entry point for running commands in the package. ''' argCount = len(sys.argv) if argCount < 2: print('No arguments provided. Use -h or --help for help.') return 1 if sys.argv[1] == '-h' or sys.argv[1] == '--help': print('Usage: python -m materialxMaterials [options] where command is gpuopen, physbased, acg (AmbientCG), or polyhaven') return 0 # Check if the command is valid cmdArgs = sys.argv[1:] if cmdArgs[0] == 'physbased': cmdArgs[0] = 'physicallyBasedMaterialXCmd.py' elif cmdArgs[0] == 'gpuopen': cmdArgs[0] = 'GPUOpenLoaderCmd.py' elif cmdArgs[0] == 'acg': cmdArgs[0] = 'ambientCGLoaderCmd.py' elif cmdArgs[0] == 'polyhaven': cmdArgs[0] = 'polyHavenLoaderCmd.py' else: print('Unknown command specified:', cmdArgs[0]) return 1 packageLocation = os.path.dirname(__file__) python_exec = sys.executable script_path = os.path.join(packageLocation, cmdArgs[0]) cmd = [python_exec, script_path] + cmdArgs[1:] print('Running command:', ' '.join(cmd)) # Run the command return subprocess.call(cmd, shell=False) if __name__ == '__main__': sys.exit(main()) ``` -------------------------------- ### getMaterialXString() Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader.html Get the MaterialX document as a string. Returns an empty string if no document is available. ```APIDOC ## getMaterialXString() ### Description Retrieves the MaterialX document formatted as a string. If no MaterialX document is loaded, an empty string is returned. ### Method GET (implied) ### Endpoint (Not specified, likely an internal method) ### Returns - `{string}` - The MaterialX document as a string, or an empty string if no document exists. ``` -------------------------------- ### Get Material Previews Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/classmaterialx_materials_1_1_g_p_u_open_loader_1_1_g_p_u_open_material_loader.html Retrieves computed material previews. Optionally forces a recomputation. ```python def getMaterialPreviews(self, force = False) -> list | None: if not self.materialPreviews or force: self.computeMaterialPreviews() return self.materialPreviews ``` -------------------------------- ### Initialize MaterialX Definitions and Materials Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/physically_based_material_x_8py_source.html Initializes Physically Based MaterialX definitions, materials, remappings, and translators. Loads materials from a file if provided and exists, otherwise fetches from a URL. It also creates and validates the MaterialX definition library. ```python def initialize_definitions_and_materials(self, materials_file : str = ''): ''' @brief Initialize Physically Based MaterialX definitions, materials, remappings, and translators. @return None ''' # Load information from PhysicallyBased site, and initialize remappings if materials_file and os.path.exists(materials_file): self.loadMaterialsFromFile(materials_file) else: self.getMaterialsFromURL() self.initializeInputRemapping() # Create Physically Based MaterialX definition library self.physlib = self.create_definition(None) self.logger.info('> Created Physically Based MaterialX definition library...') status, error = self.physlib.validate() if not status: self.logger.info(mx.prettyPrint(self.physlib)) self.logger.error('> Error validating NodeDef document:') self.logger.error(error) else: self.logger.info('> Definition documents passed validation.') # Create all translators ``` -------------------------------- ### Get Asset Database Material List Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/classmaterialx_materials_1_1ambient_c_g_loader_1_1_ambient_c_g_loader.html Retrieves the list of assets from the asset database. ```python def getDataBaseMaterialList(self): ''' @brief Get asset database material list @return Material list ''' return self.assets ``` -------------------------------- ### Main Execution Block Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_g_p_u_open_loader_cmd_8py_source.html This is the main entry point for the script. It calls the GPUOpenLoaderCmd function to initiate the material loading process when the script is executed directly. ```python if __name__ == '__main__': GPUOpenLoaderCmd() ``` -------------------------------- ### initialize_definitions_and_materials Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader-members.html Initializes MaterialX definitions and materials, optionally specifying shading models and material names. ```APIDOC ## initialize_definitions_and_materials(shadingModel='standard_surface', materialNames=[], force=false) ### Description Initializes MaterialX definitions and materials. This method can be used to load specific materials or all materials associated with a given shading model. The `force` parameter can be used to re-initialize even if already loaded. ### Method N/A (This is a method call within the JsPhysicallyBasedMaterialLoader class) ### Endpoint N/A ### Parameters - **shadingModel** (string) - Optional - The shading model to use for initialization. Defaults to 'standard_surface'. - **materialNames** (Array) - Optional - A list of specific material names to initialize. If empty, all materials for the specified shading model are initialized. - **force** (boolean) - Optional - If true, re-initializes definitions and materials even if they have already been loaded. Defaults to false. ``` -------------------------------- ### Get Material Names from JSON Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/physically_based_material_x_8py_source.html Retrieves a list of material names from the loaded JSON object. ```python def getJSONMaterialNames(self) -> list: ''' Get the list of material names from the JSON object @return The list of material names ''' return self.materialNames ``` -------------------------------- ### Get JSON Object of Materials Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/physically_based_material_x_8py_source.html Retrieves the JSON object that represents the Physically Based Materials. ```python def getJSON(self) -> dict: ''' Get the JSON object representing the Physically Based Materials ''' return self.materials ``` -------------------------------- ### Run GPUOpen Loader Directly (NodeJS) Source: https://github.com/kwokcb/materialxmaterials/blob/main/README.html Execute the GPUOpen loader script directly using Node.js with arguments. ```bash node gpuOpenFetch.js [] ``` -------------------------------- ### Initialize GPUOpenMaterialLoader Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_g_p_u_open_loader_8py_source.html Initializes the GPUOpen material loader by setting up API endpoints for materials, packages, and renders. It also initializes internal variables to store fetched data and sets up a logger. ```python import requests, json, os, io, re, zipfile, logging # type: ignore from http import HTTPStatus # Note: MaterialX is not currently a dependency since no MaterialX processing is required. #import MaterialX as mx import io import zipfile from io import BytesIO from PIL import Image as PILImage import base64 class GPUOpenMaterialLoader(): ''' This class is used to load materials from the GPUOpen material database. See: https://api.matlib.gpuopen.com/api/swagger/ for API information. ''' def __init__(self): ''' Initialize the GPUOpen material loader. ''' self.root_url = 'https://api.matlib.gpuopen.com/api' self.url = self.root_url + '/materials' self.package_url = self.root_url + '/packages' self.render_url = self.root_url + '/renders' self.materialPreviews = None self.materials = None self.materialNames = None self.renders = None self.logger = logging.getLogger('GPUO') logging.basicConfig(level=logging.INFO) ``` -------------------------------- ### Get Physically Based MaterialX Library Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader.html Returns the Physically Based MaterialX definition library. ```javascript { // Get the Physically Based MaterialX definition library. return this.physlib; } ``` -------------------------------- ### Define Honey Material Source: https://github.com/kwokcb/materialxmaterials/blob/main/examples/README.md Defines a material that uses the honey shader. This setup is for a translucent material. ```xml ``` -------------------------------- ### Download Material Package Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/main_8js_source.html Prepares and triggers the download of a MaterialX package. It checks the cache for an existing package, creates it if not found, and then initiates the file download. ```javascript const resolution = document.getElementById('materialResolution').value; const materialName = currentSelectedMaterial.name.replace(/[^a-z0-9]/gi, '_').toLowerCase(); const downloadBtn = document.getElementById('downloadMaterial'); const originalText = downloadBtn.innerHTML; downloadBtn.innerHTML = 'Preparing download...'; downloadBtn.disabled = true; try { const cacheKey = `${currentSelectedMaterial.id}_${resolution}`; let zipBlob = materialPackageCache[cacheKey]; if (!zipBlob) { zipBlob = await polyHavenAPI.createMaterialXPackage(currentSelectedMaterial, resolution); materialPackageCache[cacheKey] = zipBlob; } const url = URL.createObjectURL(zipBlob); const a = document.createElement('a'); a.href = url; a.download = `${materialName}_${resolution}_materialx.zip`; document.body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); }); } catch (e) { console.error('Error downloading material:', e); downloadBtn.innerHTML = originalText; downloadBtn.disabled = false; } ``` -------------------------------- ### Get JSON Material Names Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader.html Returns a list containing the names of all available Physically Based Materials. ```javascript getJSONMaterialNames() { return this.materialNames } ``` -------------------------------- ### Initialize Resolutions Dictionary Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/poly_haven_loader_8py_source.html Sets up a dictionary to hold resolution data, defaulting to None. ```python resolutions = { "1k": None, "2k": None, "4k": None, "8k": None } ``` -------------------------------- ### Get Physically Based MaterialX Definition Name Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader.html Returns the name of the Physically Based MaterialX definition. ```javascript { // Get the Physically Based MaterialX definition name. return this.physlib_definition_name; } ``` -------------------------------- ### initialize_definitions_and_materials Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/physically_based_material_x_8py_source.html Initializes Physically Based MaterialX definitions, materials, remappings, and translators from a specified file. ```APIDOC ## initialize_definitions_and_materials ### Description Initialize Physically Based MaterialX definitions, materials, remappings, and translators. ### Method ```python initialize_definitions_and_materials(self, materials_file: str = '') ``` ### Parameters - **materials_file** (str, Optional): The path to the file containing material definitions. Defaults to an empty string. ``` -------------------------------- ### initialize_definitions_and_materials Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/functions_func.html Initializes definitions and materials. This function is available via JsPhysicallyBasedMaterialLoader and materialxMaterials.physicallyBasedMaterialX.PhysicallyBasedMaterialLoader. ```APIDOC ## initialize_definitions_and_materials() ### Description Initializes definitions and materials. ### Returns - [JsPhysicallyBasedMaterialLoader](class_js_physically_based_material_loader.html#a1b4932b31d1015707f796e4d4051667a) - [materialxMaterials.physicallyBasedMaterialX.PhysicallyBasedMaterialLoader](classmaterialx_materials_1_1physically_based_material_x_1_1_physically_based_material_loader.html#a4ed42e9680cbcc85b61c635e4e3dd780) ``` -------------------------------- ### Get Physically Based MaterialX Surface Category Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader.html Returns the Physically Based MaterialX surface category. ```javascript { // Get the Physically Based MaterialX surface category. return this.physlib_category; } ``` -------------------------------- ### PhysicallyBasedMaterialLoader.initializeInputRemapping Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/physically_based_material_x_8py_source.html Initializes the remapping keys for different shading models. ```APIDOC ## initializeInputRemapping() ### Description Initialize remapping keys for different shading models. ``` -------------------------------- ### Get and Print Material Names Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/namespacematerialx_materials_1_1ambient_c_g_loader_cmd.html Retrieves a list of available material names from the loader and prints them to the console. ```python materialNames = loader.getMaterialNames() print(f'{materialNames}') ``` -------------------------------- ### Get Asset Database Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/ambient_c_g_loader_8py_source.html Retrieves the asset database. This method provides access to the underlying database structure. ```python return self.database ``` -------------------------------- ### Compute Material Previews Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/classmaterialx_materials_1_1_g_p_u_open_loader_1_1_g_p_u_open_material_loader.html Retrieves and formats material preview URLs from the loaded GPUOpen material database. Returns an empty list if no materials or renders are available. ```python def computeMaterialPreviews(self) -> list: ''' Get the material preview URLs for the materials loaded from the GPUOpen material database. Returns list of items of the form: { 'title': material_title, 'preview_url': url } If no materials or renders are loaded, then an empty list is returned. '" ``` -------------------------------- ### Get Material Names Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_js_g_p_u_open_loader_8js_source.html Returns an array of all material names that have been loaded. Useful for populating dropdowns or lists. ```javascript getMaterialNames() { return this.materialNames; } ``` -------------------------------- ### Initialize Ambient CG Loader Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/ambient_c_g_loader_8py_source.html Initializes the Ambient CG Loader, checks for MaterialX module availability, and determines OpenPBR support based on the MaterialX version. Loads the standard library if not already provided. ```python if not mx_module: self.logger.critical(f'> {self._getMethodName()}: MaterialX module not specified.') return # Check for OpenPBR support which is only available in 1.39 and above version_major, version_minor, version_patch = self.mx.getVersionIntegers() self.logger.info(f'Using MaterialX version: {version_major}.{version_minor}.{version_patch}') if (version_major >=1 and version_minor >= 39) or version_major > 1: self.logger.debug('> OpenPBR shading model supported') self.support_openpbr = True # Load the MaterialX standard library if not provided if not self.stdlib: self.stdlib = self.mx.createDocument() libFiles = self.mx.loadLibraries(mx.getDefaultDataLibraryFolders(), mx.getDefaultDataSearchPath(), self.stdlib) self.logger.debug(f'> Loaded standard library: {libFiles}') ``` -------------------------------- ### Get Material List Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/_js_g_p_u_open_loader_8js_source.html Returns the currently loaded list of materials. Ensure materials are fetched before calling this. ```javascript getMaterialList() { return this.materials; } ``` -------------------------------- ### Create a Working MaterialX Document Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/physically_based_material_x_8py_source.html Creates a new MaterialX document and loads the standard library definitions into it. This is useful for setting up a base document for further operations. ```python doc : mx.Document = mx.createDocument() stdlib : mx.Document = mx.createDocument() searchPath : mx.FileSearchPath = mx.getDefaultDataSearchPath() libraryFolders : list[mx.FilePath]= mx.getDefaultDataLibraryFolders() libraryFiles : set[str] = mx.loadLibraries(libraryFolders, searchPath, stdlib) doc.setDataLibrary(stdlib) nodedefs : list[mx.NodeDef] = doc.getNodeDefs() result = { "doc": doc, "stdlib": stdlib } return result ``` -------------------------------- ### Get Physically Based Materials as JSON Source: https://github.com/kwokcb/materialxmaterials/blob/main/documents/html/class_js_physically_based_material_loader.html Retrieves the list of Physically Based Materials formatted as a JSON object. ```javascript getJSON() { return this.materials } ```