### Install obj2gltf globally Source: https://github.com/cesiumgs/obj2gltf/blob/main/README.md Install the package via npm to access the command-line interface. ```bash npm install -g obj2gltf ``` -------------------------------- ### Convert OBJ with Custom MTL Mappings Source: https://context7.com/cesiumgs/obj2gltf/llms.txt Example of converting an OBJ model using custom options, including interpreting MTL file properties for metallic-roughness PBR workflow. Ensure necessary files like textures are accessible. ```javascript // Example: Converting a model with a properly configured MTL file // model.mtl contents: // newmtl MyMaterial // Kd 1.0 1.0 1.0 // Ks 0.5 0.5 0.5 # metallic value (for metallicRoughness mode) // Ns 0.3 # roughness value (for metallicRoughness mode) // map_Kd diffuse.png // map_Ks metallic.png // map_Ns roughness.png // map_Bump normal.png const options = { binary: true, metallicRoughness: true, // Interpret Ks as metallic, Ns as roughness packOcclusion: true }; obj2gltf("model.obj", options).then(glb => { fs.writeFileSync("model.glb", glb); }); ``` -------------------------------- ### Install OBJ2GLTF as a Project Dependency Source: https://context7.com/cesiumgs/obj2gltf/llms.txt Add obj2gltf as a dependency to your Node.js project for programmatic usage. ```bash npm install obj2gltf --save ``` -------------------------------- ### Run ESLint in watch mode Source: https://github.com/cesiumgs/obj2gltf/blob/main/README.md Starts a process that automatically runs ESLint whenever a file is saved. ```bash npm run eslint-watch ``` -------------------------------- ### Generate documentation Source: https://github.com/cesiumgs/obj2gltf/blob/main/README.md Creates project documentation using JSDoc and outputs it to the doc folder. ```bash npm run jsdoc ``` -------------------------------- ### Convert OBJ via command-line Source: https://github.com/cesiumgs/obj2gltf/blob/main/README.md Execute conversion commands to generate glTF or GLB files from an OBJ source. ```bash obj2gltf -i model.obj ``` ```bash obj2gltf -i model.obj -o model.gltf ``` ```bash obj2gltf -i model.obj -o model.glb ``` -------------------------------- ### Run ESLint Source: https://github.com/cesiumgs/obj2gltf/blob/main/README.md Performs linting on the entire codebase. ```bash npm run eslint ``` -------------------------------- ### Convert OBJ to GLB as a library Source: https://github.com/cesiumgs/obj2gltf/blob/main/README.md Use the library with binary options to output a GLB file. ```javascript const obj2gltf = require("obj2gltf"); const fs = require("fs"); const options = { binary: true, }; obj2gltf("model.obj", options).then(function (glb) { fs.writeFileSync("model.glb", glb); }); ``` -------------------------------- ### Convert PBR-Ready Models Source: https://context7.com/cesiumgs/obj2gltf/llms.txt Bypass traditional material conversion for models with existing PBR textures. Choose between metallic-roughness or specular-glossiness workflows. ```javascript const obj2gltf = require("obj2gltf"); const fs = require("fs"); // When your MTL file already contains metallic-roughness values // (metallic in Ks/map_Ks, roughness in Ns/map_Ns) const metallicRoughnessOptions = { binary: true, metallicRoughness: true, packOcclusion: true // Pack ambient occlusion into metallic-roughness texture }; obj2gltf("models/pbr_model.obj", metallicRoughnessOptions) .then(function (glb) { fs.writeFileSync("output/pbr_model.glb", glb); console.log("PBR model converted successfully"); }); // When your MTL file has specular-glossiness values // (specular in Ks/map_Ks, glossiness in Ns/map_Ns) const specGlossOptions = { binary: true, specularGlossiness: true // Uses KHR_materials_pbrSpecularGlossiness extension }; obj2gltf("models/specgloss_model.obj", specGlossOptions) .then(function (glb) { fs.writeFileSync("output/specgloss_model.glb", glb); console.log("Specular-glossiness model converted successfully"); }); ``` -------------------------------- ### Convert with Full Options Source: https://context7.com/cesiumgs/obj2gltf/llms.txt Provides fine-grained control over the conversion process, including material settings, texture overrides, and axis transformations. ```javascript const obj2gltf = require("obj2gltf"); const fs = require("fs"); const path = require("path"); const options = { // Output format binary: false, // Output glTF JSON (false) or glb buffer (true) // Resource handling separate: false, // Write separate buffer and texture files separateTextures: false, // Write only separate texture files // Material settings metallicRoughness: false, // MTL values are already metallic-roughness PBR specularGlossiness: false, // MTL values are already specular-glossiness PBR unlit: false, // Use KHR_materials_unlit extension doubleSidedMaterial: false, // Make materials double-sided // Texture handling checkTransparency: false, // Check each pixel for transparency packOcclusion: false, // Pack occlusion in metallic-roughness texture // Security secure: false, // Prevent reading outside obj directory // Axis transformation inputUpAxis: "Y", // Input up axis: "X", "Y", or "Z" outputUpAxis: "Y", // Output up axis: "X", "Y", or "Z" // Processing triangleWindingOrderSanitization: false, // Fix winding order issues // Override textures (for models without proper MTL files) overridingTextures: { baseColorTexture: "textures/diffuse.png", normalTexture: "textures/normal.png", occlusionTexture: "textures/ao.png", emissiveTexture: "textures/emissive.png", alphaTexture: "textures/alpha.png", // OR use packed PBR textures: // metallicRoughnessOcclusionTexture: "textures/pbr.png", // specularGlossinessTexture: "textures/specGloss.png" }, // Output directory for separate resources outputDirectory: "output/", // Custom logger logger: function (message) { console.log("[OBJ2GLTF]", message); } }; obj2gltf("models/scene.obj", options) .then(function (gltf) { const jsonString = JSON.stringify(gltf, null, 2); fs.writeFileSync("output/scene.gltf", jsonString); console.log("Conversion complete with custom options"); }) .catch(function (error) { console.error("Error:", error.message); }); ``` -------------------------------- ### Convert OBJ to glTF JSON Source: https://context7.com/cesiumgs/obj2gltf/llms.txt Demonstrates basic conversion to glTF JSON using both Promise-based and async/await patterns. ```javascript const obj2gltf = require("obj2gltf"); const fs = require("fs"); // Basic conversion to glTF JSON obj2gltf("models/cube.obj") .then(function (gltf) { // gltf is a JavaScript object representing the glTF JSON const data = Buffer.from(JSON.stringify(gltf, null, 2)); fs.writeFileSync("output/cube.gltf", data); console.log("Conversion complete!"); }) .catch(function (error) { console.error("Conversion failed:", error.message); }); // Using async/await async function convertModel() { try { const gltf = await obj2gltf("models/cube.obj"); fs.writeFileSync("output/cube.gltf", JSON.stringify(gltf, null, 2)); } catch (error) { console.error("Error:", error.message); } } ``` -------------------------------- ### Run project tests Source: https://github.com/cesiumgs/obj2gltf/blob/main/README.md Executes the test suite for the Node.js module. ```bash npm run test ``` -------------------------------- ### obj2gltf Converter Options Source: https://github.com/cesiumgs/obj2gltf/blob/main/README.md This section details the command-line options for the obj2gltf converter, which allows for the transformation of OBJ files into glTF format with various customization options. ```APIDOC ## obj2gltf Converter Options ### Description This document outlines the command-line options available for the `obj2gltf` converter. These options allow for fine-grained control over the conversion process from OBJ to glTF format, including texture handling, material properties, and security. ### Options - `--secure` (boolean) - Optional - Prevent the converter from reading texture or mtl files outside of the input obj directory. Defaults to `false`. - `--packOcclusion` (boolean) - Optional - Pack the occlusion texture in the red channel of metallic-roughness texture. Defaults to `false`. - `--metallicRoughness` (boolean) - Optional - Indicates that the values in the mtl file are already metallic-roughness PBR values and no conversion step should be applied. Metallic is stored in the Ks and map_Ks slots and roughness is stored in the Ns and map_Ns slots. Defaults to `false`. - `--specularGlossiness` (boolean) - Optional - Indicates that the values in the mtl file are already specular-glossiness PBR values and no conversion step should be applied. Specular is stored in the Ks and map_Ks slots and glossiness is stored in the Ns and map_Ns slots. The glTF will be saved with the `KHR_materials_pbrSpecularGlossiness` extension. Defaults to `false`. - `--unlit` (boolean) - Optional - The glTF will be saved with the KHR_materials_unlit extension. Defaults to `false`. - `--metallicRoughnessOcclusionTexture` (string) - Optional - Path to the metallic-roughness-occlusion texture that should override textures in the .mtl file, where occlusion is stored in the red channel, roughness is stored in the green channel, and metallic is stored in the blue channel. The model will be saved with a pbrMetallicRoughness material. This is often convenient in workflows where the .mtl does not exist or is not set up to use PBR materials. Intended for models with a single material. - `--specularGlossinessTexture` (string) - Optional - Path to the specular-glossiness texture that should override textures in the .mtl file, where specular color is stored in the red, green, and blue channels and specular glossiness is stored in the alpha channel. The model will be saved with a material using the KHR_materials_pbrSpecularGlossiness extension. - `--occlusionTexture` (string) - Optional - Path to the occlusion texture that should override textures in the .mtl file. - `--normalTexture` (string) - Optional - Path to the normal texture that should override textures in the .mtl file. ### Usage Example ```bash obj2gltf --input model.obj --output model.gltf --metallicRoughness --metallicRoughnessOcclusionTexture textures/metalRoughOcclusion.png ``` ### Notes - The `--metallicRoughness` and `--specularGlossiness` flags are mutually exclusive. - The `--metallicRoughnessOcclusionTexture` is intended for models with a single material. ``` -------------------------------- ### Basic OBJ to glTF Conversion Source: https://context7.com/cesiumgs/obj2gltf/llms.txt Convert an OBJ file to glTF format using the command line. The output format is determined by the file extension or the --binary flag. ```bash # Basic conversion to glTF obj2gltf -i model.obj ``` ```bash # Convert to glTF with explicit output path obj2gltf -i model.obj -o model.gltf ``` ```bash # Convert to binary glb format obj2gltf -i model.obj -o model.glb ``` ```bash # Or use the --binary flag obj2gltf -i model.obj -b ``` -------------------------------- ### Converting with Separate Resources Source: https://context7.com/cesiumgs/obj2gltf/llms.txt Write out separate buffer and texture files instead of embedding them in the glTF, useful for large models or when you need to share resources. ```bash # Write separate buffers and textures obj2gltf -i model.obj -o model.gltf --separate ``` ```bash # Write only separate textures (buffers embedded) obj2gltf -i model.obj -o model.gltf --separateTextures ``` -------------------------------- ### Run test coverage Source: https://github.com/cesiumgs/obj2gltf/blob/main/README.md Generates test coverage reports using nyc. ```bash npm run coverage ``` -------------------------------- ### Batch Process Multiple OBJ Files Source: https://context7.com/cesiumgs/obj2gltf/llms.txt Converts multiple OBJ files in a directory to glTF format using parallel processing with a concurrency limit. Ensure the output directory exists before running. ```javascript const obj2gltf = require("obj2gltf"); const fs = require("fs-extra"); const path = require("path"); async function batchConvert(inputDir, outputDir, options = {}) { // Ensure output directory exists await fs.ensureDir(outputDir); // Find all OBJ files const files = await fs.readdir(inputDir); const objFiles = files.filter(file => path.extname(file).toLowerCase() === ".obj"); console.log(`Found ${objFiles.length} OBJ files to convert`); const defaultOptions = { binary: true, ...options }; // Process files in parallel with concurrency limit const results = []; const concurrencyLimit = 4; for (let i = 0; i < objFiles.length; i += concurrencyLimit) { const batch = objFiles.slice(i, i + concurrencyLimit); const promises = batch.map(async (file) => { const inputPath = path.join(inputDir, file); const outputName = path.basename(file, ".obj") + ".glb"; const outputPath = path.join(outputDir, outputName); try { console.time(`Converting ${file}`); const glb = await obj2gltf(inputPath, defaultOptions); await fs.writeFile(outputPath, glb); console.timeEnd(`Converting ${file}`); return { file, status: "success", outputPath }; } catch (error) { console.error(`Failed to convert ${file}:`, error.message); return { file, status: "error", error: error.message }; } }); const batchResults = await Promise.all(promises); results.push(...batchResults); } // Summary const successful = results.filter(r => r.status === "success").length; const failed = results.filter(r => r.status === "error").length; console.log(`\nBatch conversion complete: ${successful} succeeded, ${failed} failed`); return results; } // Usage batchConvert("models/input", "models/output", { checkTransparency: true, doubleSidedMaterial: true }); ``` -------------------------------- ### Convert OBJ to Binary GLB Source: https://context7.com/cesiumgs/obj2gltf/llms.txt Converts an OBJ file to a binary GLB buffer by setting the binary option to true. ```javascript const obj2gltf = require("obj2gltf"); const fs = require("fs"); const options = { binary: true }; obj2gltf("models/character.obj", options) .then(function (glb) { // glb is a Buffer containing the binary glTF data fs.writeFileSync("output/character.glb", glb); console.log("GLB file written successfully"); console.log("File size:", glb.length, "bytes"); }) .catch(function (error) { console.error("Conversion failed:", error.message); }); ```