gltfjsx

repository·master·Indexed 26 days ago

https://github.com/pmndrs/gltfjsx

A command-line tool and API that converts GLTF/GLB assets into declarative, reusable React Three Fiber JSX components. It supports asset transformation for the web (Draco compression, pruning, and texture resizing), TypeScript definition generation, and auto-instancing to reduce draw calls. The tool can be run via npx or used as a standalone parse API to convert GLTF objects or Three.js scenes into JSX strings.

Tokens
1.9K
Snippets
5
Records
10
Agent score
41%

What's inside gltfjsx

  1. Add TypeScript definitions with --types

    master

    Use the --types flag to generate a type-safe JSX component. This allows you to define a GLTFResult type that maps the nodes and materials from the GLTF file to specific Three.js types.

    type GLTFResult = GLTF & {
      nodes: { robot: THREE.Mesh; rocket: THREE.Mesh }
      materials: { metal: THREE.MeshStandardMaterial; wood: THREE.MeshStandardMaterial }
    }
    
    export default function Model(props: JSX.IntrinsicElements['group']) {
      const { nodes, materials } = useGLTF<GLTFResult>('/model.gltf')
  2. Project Requirements

    master

    To use gltfjsx, ensure the following requirements are met:

    • Node.js: Must be installed.
    • GLTF File Location: The file must be present in your project's /public folder.
    • three: version >= 122.x
    • @react-three/fiber: version >= 5.x
    • @react-three/drei: version >= 2.x
  3. Transform assets for the web using --transform

    master

    The --transform flag creates a binary-packed, draco-compressed, texture-resized, webp-compressed, deduped, instanced, and pruned .glb file ready for web consumption. This can reduce asset size by 70%-90%. It creates a copy of the original file with the suffix -transformed.glb.

    Example command:

    npx gltfjsx model.gltf --transform
    npx gltfjsx model.gltf --transform
  4. Install and use gltfjsx via npx

    master

    You can use gltfjsx without a permanent installation by using npx. This tool converts GLTF assets into declarative and reusable react-three-fiber JSX components.

    Basic usage:

    npx gltfjsx [Model.glb] [options]
    npx gltfjsx model.gltf --transform
  5. Use Auto-instancing with --instance and --instanceall

    master

    The --instance flag identifies similar geometry and creates instances using drei/Merged. The --instanceall flag creates instances for every geometry to minimize draw calls.

    To use instancing, you must import both the Instances wrapper and the Model component generated by the tool. Wrap your models in the Instances component to benefit from reduced draw calls.

  6. Use the gltfjsx CLI

    master

    Convert GLTF/GLB models into React components using the gltfjsx command-line tool. You can run it via npx.

    Basic Usage:

    $ npx gltfjsx [Model.glb] [options]

    By default, the tool generates a .jsx file named after the model (capitalized). If the --types flag is used, it generates a .tsx file.

  7. Use the parse API stand-alone

    master

    You can use the parse function directly in your code to convert a loaded GLTF object or a Three.js scene into JSX string content.

    Parsing a GLTF object:

    import { parse } from 'gltfjsx'
    import { GLTFLoader, DRACOLoader } from 'three-stdlib'
    
    const gltfLoader = new GLTFLoader()
    const dracoloader = new DRACOLoader()
    dracoloader.setDecoderPath('https://www.gstatic.com/draco/v1/decoders/')
    gltfLoader.setDRACOLoader(dracoloader)
    
    gltfLoader.load(url, (gltf) => {
      const jsx = parse(gltf, optionalConfig)
    })

    Parsing a scene (Object3D):

    const jsx = parse(scene, optionalConfig)
    import { parse } from 'gltfjsx'
    import { GLTFLoader, DRACOLoader } from 'three-stdlib'
    
    const gltfLoader = new GLTFLoader()
    const dracoloader = new DRACOLoader()
    dracoloader.setDecoderPath('https://www.gstatic.com/draco/v1/decoders/')
    gltfLoader.setDRACOLoader(dracoloader)
    
    gltfLoader.load(url, (gltf) => {
      const jsx = parse(gltf, optionalConfig)
    })
  8. Use GLTFStructureLoader for testing

    master

    The GLTFStructureLoader allows you to extract the structure of a GLTF asset without loading actual binaries or textures. This is useful for running tests in environments where heavy assets are unavailable.

    import { GLTFStructureLoader } from 'gltfjsx'
    import fs from 'fs/promises'
    
    const loader = new GLTFStructureLoader()
    const data = await fs.readFile('./model.glb')
    const { scene } = await new Promise((res) => loader.parse(data, '', res))
  9. Reference the gltfjsx CLI options

    master

    The following options are available when running the gltfjsx command line tool:

    FlagLongDescription
    -o--outputOutput file name/path
    -t--typesAdd Typescript definitions
    -k--keepnamesKeep original names
    -K--keepgroupsKeep (empty) groups, disable pruning
    -b--bonesLay out bones declaratively (default: false)
    -m--metaInclude metadata (as userData)
    s--shadowsLet meshes cast and receive shadows
    -w--printwidthPrettier printWidth (default: 120)
    -p--precisionNumber of fractional digits (default: 3)
    -d--dracoDraco binary path
    -r--rootSets directory from which .gltf file is served
    -i--instanceInstance re-occuring geometry
    -I--instanceallInstance every geometry (for cheaper re-use)
    -E--exportdefaultUse default export
    -T--transformTransform the asset for the web (draco, prune, resize)
    -R--resolutionResolution for texture resizing (default: 1024)
    -j--keepmeshesDo not join compatible meshes
    -M--keepmaterialsDo not palette join materials
    -f--formatTexture format (default: "webp")
    -S--simplifyMesh simplification (default: false)
    --ratioSimplifier ratio (default: 0)
    --errorSimplifier error threshold (default: 0.0001)
    -c--consoleLog JSX to console, won't produce a file
    -D--debugDebug output
  10. Reference gltfjsx CLI flags

    master

    The following flags are available when using the gltfjsx CLI to control the output and transformation of your models:

    Output & Format

    • --output, -o <string>: Specify the output file name or path.
    • --types, -t: Add TypeScript definitions (outputs .tsx).
    • --exportdefault, -E: Use a default export in the generated component.
    • --console, -c: Log the JSX to the console instead of producing a file.

    Component Structure

    • --keepnames, -k: Keep original names from the GLTF file.
    • --keepgroups, -K: Keep (empty) groups, disabling pruning.
    • --bones, -b: Lay out bones declaratively (default: false).
    • --meta, -m: Include metadata as userData.
    • --shadows, -s: Let meshes cast and receive shadows.
    • --instance, -i: Instance re-occurring geometry.
    • --instanceall, -I: Instance every geometry (for cheaper re-use).

    Asset Transformation

    • --transform, -T: Transform the asset for the web (enables Draco, pruning, and resizing).
      • --resolution, -R <number>: Resolution for texture resizing (default: 1024).
      • --keepmeshes, -j: Do not join compatible meshes.
      • --keepmaterials, -M: Do not palette join materials.
      • --format, -f <string>: Texture format (default: "webp").
      • --simplify, -S: Enable mesh simplification (default: false).
        • --ratio <number>: Simplifier ratio (default: 0.75).
        • --error <number>: Simplifier error threshold (default: 0.001).

    Technical Settings

    • --draco, -d <string>: Path to the Draco binary.
    • --root, -r <string>: Sets the directory from which the .gltf file is served.
    • --printwidth, -w <number>: Prettier printWidth (default: 1000).
    • --precision, -p <number>: Number of fractional digits (default: 3).
    • --debug, -D: Enable debug output.