### Setup Install and Test Targets
Source: https://github.com/google/draco/blob/main/CMakeLists.txt
Sets up the installation and testing targets for the Draco project. This is typically called at the end of the main configuration block.
```cmake
draco_setup_install_target()
draco_setup_test_targets()
endif()
```
--------------------------------
### Run minimal decoder example
Source: https://github.com/google/draco/blob/main/javascript/npm/draco3d/README.md
Execute a minimal Node.js example script that demonstrates loading only the Draco decoder module.
```bash
node draco_minimal_decoder_example.js
```
--------------------------------
### Run Draco Node.js example
Source: https://github.com/google/draco/blob/main/javascript/npm/draco3d/README.md
Execute the provided Node.js example script to test Draco's encoding and decoding capabilities. This involves copying example files and running the script with Node.
```bash
cp node_modules/draco3d/draco_nodejs_example.js .
cp node_modules/draco3d/bunny.drc .
node draco_nodejs_example.js
```
--------------------------------
### Run Draco Node.js Example
Source: https://github.com/google/draco/blob/main/javascript/npm/draco3dgltf/README.md
Copy the example files and run the Node.js script to test Draco encoding and decoding. This example loads a mesh, decodes it, and then re-encodes it with different settings.
```bash
$ cp node_modules/draco3dgltf/draco_nodejs_example.js .
$ cp node_modules/draco3dgltf/bunny.drc .
$ node draco_nodejs_example.js
```
--------------------------------
### Install Ruby Version with rbenv
Source: https://github.com/google/draco/blob/main/docs/spec/README.md
Installs a specific Ruby version using rbenv. Ensure rbenv is installed first.
```bash
# list all available versions:
$ rbenv install -l
2.2.6
2.3.0-dev
2.3.0-preview1
2.3.0-preview2
2.3.0
# install a Ruby version:
$ rbenv install 2.3.0
```
--------------------------------
### Install Draco using vcpkg
Source: https://github.com/google/draco/blob/main/BUILDING.md
Download and install Draco using the vcpkg dependency manager. This involves cloning vcpkg, bootstrapping it, integrating it with your system, and then installing the draco package.
```bash
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install draco
```
--------------------------------
### Run minimal encoder example
Source: https://github.com/google/draco/blob/main/javascript/npm/draco3d/README.md
Execute a minimal Node.js example script that demonstrates loading only the Draco encoder module.
```bash
node draco_minimal_encoder_example.js
```
--------------------------------
### Run minimal encoder/decoder example
Source: https://github.com/google/draco/blob/main/javascript/npm/draco3d/README.md
Execute a minimal Node.js example script that demonstrates loading both the Draco encoder and decoder modules.
```bash
node draco_minimal_encoder_decoder_example.js
```
--------------------------------
### Install Gem Dependencies with Bundler
Source: https://github.com/google/draco/blob/main/docs/spec/README.md
Installs all gem dependencies required by the project as defined in the Gemfile.lock. Ensure Ruby development headers are installed if needed.
```bash
bundle install
```
--------------------------------
### CMakeLists.txt for Draco Installation Test
Source: https://github.com/google/draco/blob/main/src/draco/tools/install_test/CMakeLists.txt
This CMakeLists.txt file defines a project that builds an executable linked against the Draco library and installs it. It's used to verify that Draco was installed correctly.
```cmake
cmake_minimum_required(VERSION 3.12)
project(install_test C CXX)
include(GNUInstallDirs)
find_package(draco REQUIRED CONFIG)
add_executable(install_check main.cc)
target_link_libraries(install_check PRIVATE draco::draco)
install(TARGETS install_check DESTINATION ${CMAKE_INSTALL_BINDIR})
```
--------------------------------
### Build and Preview Documentation Locally
Source: https://github.com/google/draco/blob/main/docs/spec/README.md
Builds the documentation and starts a local web server using Jekyll. The server watches for file changes and rebuilds automatically.
```bash
bundle exec jekyll serve
```
--------------------------------
### Basic Three.js Scene Setup
Source: https://github.com/google/draco/blob/main/javascript/example/webgl_loader_draco.html
Sets up the essential components for a three.js WebGL scene, including camera, scene, and renderer. Handles window resizing.
```javascript
var camera, scene, renderer;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 0.1, 15 );
camera.position.set( 3, 0.25, 3 );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x443333 );
scene.fog = new THREE.Fog( 0x443333, 1, 4 );
// Ground
var plane = new THREE.Mesh( new THREE.PlaneBufferGeometry( 8, 8 ), new THREE.MeshPhongMaterial( { color: 0x999999, specular: 0x101010 } ) );
plane.rotation.x = - Math.PI / 2;
plane.position.y = 0.03;
plane.receiveShadow = true;
scene.add( plane );
// Lights
var light = new THREE.HemisphereLight( 0x443333, 0x111122 );
scene.add( light );
var light = new THREE.SpotLight();
light.angle = Math.PI / 16;
light.penumbra = 0.5;
light.castShadow = true;
light.position.set( - 1, 1, 1 );
scene.add( light );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
container.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
render();
requestAnimationFrame( animate );
}
function render() {
var timer = Date.now() * 0.0003;
camera.position.x = Math.sin( timer ) * 0.5;
camera.position.z = Math.cos( timer ) * 0.5;
camera.lookAt( new THREE.Vector3( 0, 0.1, 0 ) );
renderer.render( scene, camera );
}
```
--------------------------------
### Install draco3d package
Source: https://github.com/google/draco/blob/main/javascript/npm/draco3d/README.md
Install the draco3d package using npm. This command is typically run in your project's root directory.
```bash
npm install draco3d
```
--------------------------------
### Install draco3dgltf Package
Source: https://github.com/google/draco/blob/main/javascript/npm/draco3dgltf/README.md
Install the draco3dgltf package using npm. This command is typically run in your project's root directory.
```bash
$ npm install draco3dgltf
```
--------------------------------
### Initialize Google Analytics
Source: https://github.com/google/draco/blob/main/docs/_includes/analytics.html
Include this script to initialize the Google Analytics object and start tracking. Ensure your GA tracking ID is correctly set.
```javascript
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-103514536-1', 'auto'); ga('send', 'pageview');
```
--------------------------------
### Configure Draco with Local Googletest
Source: https://github.com/google/draco/blob/main/BUILDING.md
Override the default submodule behavior and configure Draco to use a local Googletest installation by specifying the DRACO_GOOGLETEST_PATH variable.
```bash
cmake ../ -DDRACO_GOOGLETEST_PATH=/path/to/googletest
```
--------------------------------
### Draco Syntax Code Block Example
Source: https://github.com/google/draco/blob/main/docs/spec/README.md
Illustrates the use of fenced code blocks with kramdown and the 'draco-syntax' CSS class for rendering specific syntax elements.
```markdown
~~~~~
DecodeHeader() {
draco_string UI8[5]
major_version UI8
minor_version UI8
encoder_type UI8
encoder_method UI8
flags
}
~~~~~
{:.draco-syntax}
```
--------------------------------
### Build iOS Draco Unity Plugin
Source: https://github.com/google/draco/blob/main/unity/BUILDING.md
Configures CMake for iOS and builds the Draco Unity plugin. Ensure Xcode is installed and the correct deployment target is set.
```bash
cmake path/to/draco -G Xcode \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CONFIGURATION_TYPES=Release \
-DCMAKE_SYSTEM_NAME=iOS \
-DCMAKE_OSX_ARCHITECTURES=armv7\;armv7s\;arm64 \
-DCMAKE_XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH=NO \
-DCMAKE_OSX_DEPLOYMENT_TARGET=10.0 \
-DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=NO \
-DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY="" \
-DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=NO \
-DDRACO_UNITY_PLUGIN=1
xcodebuild
cd Release-iphoneos
tar cjvf libdracodec_unity_ios.tar.bz *.a
```
--------------------------------
### Configure and Load Draco Geometry (JS Decoder)
Source: https://github.com/google/draco/blob/main/javascript/example/README.md
Configure DRACOLoader to use the JavaScript decoder and load a Draco model. This example forces the JS decoder and sets a custom path for decoder files.
```javascript
// (Optional) Change decoder source directory (defaults to
// 'https://www.gstatic.com/draco/versioned/decoders/1.5.7/'). It is recommended
// to always pull your Draco JavaScript and WASM decoders from this URL. Users
// will benefit from having the Draco decoder in cache as more sites start using
// the static URL.
THREE.DRACOLoader.setDecoderPath('./path/to/decoder/');
// (Optional) Force non-WebAssembly JS decoder (without this line, WebAssembly
// is the default if supported).
THREE.DRACOLoader.setDecoderConfig({type: 'js'});
// (Optional) Pre-fetch decoder source files (defaults to load on demand).
THREE.DRACOLoader.getDecoderModule();
var dracoLoader = new THREE.DRACOLoader();
dracoLoader.load( 'model.drc', function ( geometry ) {
scene.add( new THREE.Mesh( geometry ) );
// (Optional) Release the cached decoder module.
THREE.DRACOLoader.releaseDecoderModule();
} );
```
--------------------------------
### Start EdgeBreaker Traversal
Source: https://github.com/google/draco/blob/main/docs/spec/edgebreaker.traversal.md
Initializes the EdgeBreaker traversal process. It sets initial states and calls the appropriate decoding function based on the traversal type.
```c++
void EdgebreakerTraversalStart() {
last_symbol_ = -1;
active_context_ = -1;
if (edgebreaker_traversal_type == STANDARD_EDGEBREAKER) {
DecodeEdgebreakerTraversalStandardData();
} else if (edgebreaker_traversal_type == VALENCE_EDGEBREAKER) {
EdgeBreakerTraversalValenceStart();
}
}
```
--------------------------------
### Conditional Library Alias Setup
Source: https://github.com/google/draco/blob/main/CMakeLists.txt
Sets up library aliases for Draco based on Emscripten and DRACO_JS_GLUE flags. It defines either a shared or static alias for the draco library.
```cmake
if(EMSCRIPTEN AND DRACO_JS_GLUE)
INCLUDES ${draco_include_paths}
LIB_DEPS draco_static)
add_library(draco::draco ALIAS draco_shared)
set_target_properties(draco_shared PROPERTIES EXPORT_NAME draco)
else()
add_library(draco::draco ALIAS draco_static)
set_target_properties(draco_static PROPERTIES EXPORT_NAME draco)
endif()
endif()
```
--------------------------------
### Initialize DRACOLoader and Load Model
Source: https://github.com/google/draco/blob/main/javascript/example/webgl_loader_draco.html
Configure the DRACOLoader and initiate the loading of a Draco compressed model. Ensure the Draco decoder library is accessible.
```javascript
var dracoLoader = new THREE.DRACOLoader();
dracoLoader.load( 'models/bunny.drc', function ( geometry ) {
geometry.computeVertexNormals();
var material = new THREE.MeshStandardMaterial( { vertexColors: THREE.VertexColors } );
var mesh = new THREE.Mesh( geometry, material );
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add( mesh );
} );
```
--------------------------------
### Initialize Googletest Submodule
Source: https://github.com/google/draco/blob/main/BUILDING.md
Clone the Googletest repository, which is included as a submodule, to enable testing support.
```bash
git submodule update --init
```
--------------------------------
### Initialize DRACOLoader and Scene
Source: https://github.com/google/draco/blob/main/javascript/example/webgl_loader_draco_advanced.html
Configures the DRACOLoader with the decoder path and sets up the basic three.js scene, including camera, lighting, and renderer. It's recommended to use the provided CDN URL for the Draco decoders to leverage browser caching.
```javascript
var dracoLoader = new THREE.DRACOLoader();
dracoLoader.setDecoderPath('https://www.gstatic.com/draco/versioned/decoders/1.5.7/');
var camera, cameraTarget, scene, renderer;
function init() {
var container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 1, 15);
camera.position.set(3, 0.15, 3);
cameraTarget = new THREE.Vector3(0, 0, 0);
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x72645b, 2, 15);
var plane = new THREE.Mesh(
new THREE.PlaneBufferGeometry(40, 40),
new THREE.MeshPhongMaterial({ color: 0x999999, specular: 0x101010 })
);
plane.rotation.x = -Math.PI / 2;
plane.position.y = -0.5;
scene.add(plane);
plane.receiveShadow = true;
scene.add(new THREE.HemisphereLight(0x443333, 0x111122));
addShadowedLight(1, 1, 1, 0xffffff, 1.35);
addShadowedLight(0.5, 1, -1, 0xffaa00, 1);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor(scene.fog.color);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
window.addEventListener('resize', onWindowResize, false);
}
function addShadowedLight(x, y, z, color, intensity) {
var directionalLight = new THREE.DirectionalLight(color, intensity);
directionalLight.position.set(x, y, z);
scene.add(directionalLight);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
var timer = Date.now() * 0.0005;
camera.position.x = Math.sin(timer) * 2.5;
camera.position.z = Math.cos(timer) * 2.5;
camera.lookAt(cameraTarget);
renderer.render(scene, camera);
}
```
--------------------------------
### Get Opposite Corner Position
Source: https://github.com/google/draco/blob/main/docs/spec/corner.md
Retrieves the index of the corner opposite to the given corner. Returns -1 if the index is out of bounds.
```c++
int PosOpposite(c) {
if (c >= opposite_corners_.size())
return -1;
return opposite_corners_[c];
}
```
--------------------------------
### Get Right Corner Index
Source: https://github.com/google/draco/blob/main/docs/spec/corner.md
Calculates the index of the right corner relative to a given corner. Returns kInvalidCornerIndex for invalid input.
```c++
int GetRightCorner(corner_id) {
if (corner_id < 0)
return kInvalidCornerIndex;
return PosOpposite(Next(corner_id));
}
```
--------------------------------
### Get Left Corner Index
Source: https://github.com/google/draco/blob/main/docs/spec/corner.md
Calculates the index of the left corner relative to a given corner. Returns kInvalidCornerIndex for invalid input.
```c++
int GetLeftCorner(corner_id) {
if (corner_id < 0)
return kInvalidCornerIndex;
return PosOpposite(Previous(corner_id));
}
```
--------------------------------
### Get Opposite Corner for Attribute
Source: https://github.com/google/draco/blob/main/docs/spec/corner.md
Determines the opposite corner, considering attribute decoders. Returns -1 if the corner is opposite to a seam edge.
```c++
int AttrOpposite(attr, corner) {
if (IsCornerOppositeToSeamEdge(corner))
return -1;
return PosOpposite(corner);
}
```
--------------------------------
### Generate Visual Studio 2019 64-bit Projects on Windows
Source: https://github.com/google/draco/blob/main/BUILDING.md
On Windows, use the -G parameter with 'Visual Studio 16 2019' and '-A x64' to generate 64-bit Visual Studio 2019 project files.
```bash
C:\Users\nobody> cmake ../ -G "Visual Studio 16 2019" -A x64
```
--------------------------------
### Load WebAssembly Decoder
Source: https://github.com/google/draco/blob/main/javascript/time_draco_decode.html
Fetches the Draco WebAssembly decoder file and prepares it for module creation. Requires the WASM binary to be available.
```javascript
function loadWebAssemblyDecoder() {
dracoDecoderType['wasmBinaryFile'] = 'draco_decoder.wasm';
const xhr = new XMLHttpRequest();
xhr.open('GET', decoderPath + 'draco_decoder.wasm', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
dracoDecoderType['wasmBinary'] = xhr.response;
createDecoderModule();
};
xhr.send(null)
}
```
--------------------------------
### Generate Visual Studio 2019 32-bit Projects on Windows
Source: https://github.com/google/draco/blob/main/BUILDING.md
On Windows, use the -G parameter with 'Visual Studio 16 2019' and '-A Win32' to generate 32-bit Visual Studio 2019 project files.
```bash
C:\Users\nobody> cmake ../ -G "Visual Studio 16 2019" -A Win32
```
--------------------------------
### Build Draco for Android (armeabi-v7a)
Source: https://github.com/google/draco/blob/main/BUILDING.md
Build Draco command-line tools for Android with the armeabi-v7a ABI. Ensure you specify the correct NDK path and ABI.
```bash
cmake ../ -DCMAKE_TOOLCHAIN_FILE=../cmake/toolchains/android.cmake \
-DDRACO_ANDROID_NDK_PATH=path/to/ndk -DANDROID_ABI=armeabi-v7a
make
```
--------------------------------
### Build WebAssembly Decoder with Emscripten
Source: https://github.com/google/draco/blob/main/BUILDING.md
Configure the build for the WebAssembly decoder by specifying the Emscripten toolchain file and enabling the WASM build option. Ensure the EMSCRIPTEN environment variable is set.
```bash
# Make the path to emscripten available to cmake.
export EMSCRIPTEN=/path/to/emscripten/tools/parent
# Emscripten.cmake can be found within your Emscripten installation directory,
it should be the subdir: cmake/Modules/Platform/Emscripten.cmake
cmake ../ -DCMAKE_TOOLCHAIN_FILE=/path/to/Emscripten.cmake -DDRACO_WASM=ON
# Build the WebAssembly decoder.
make
# Run the Javascript wrapper through Closure.
java -jar closure.jar --compilation_level SIMPLE --js draco_decoder.js --js_output_file draco_wasm_wrapper.js
```
--------------------------------
### Generate Default CMake Build Files
Source: https://github.com/google/draco/blob/main/BUILDING.md
Run this command from a directory where you want to generate build files, passing the path to your Draco repository. This generates the default toolchain files for your system.
```bash
mkdir build_dir && cd build_dir
cmake ../
```
--------------------------------
### Get Position for Corner
Source: https://github.com/google/draco/blob/main/docs/spec/prediction.normal.decoder.md
Calculates the position for a given corner ID by first converting it to a vertex ID and then using GetPositionForDataId. This is a helper function for geometric normal prediction.
```c++
void GetPositionForCorner(ci, pos) {
CornerToVerts(curr_att_dec, ci, &vert_id, &n, &p);
data_id = vertex_to_encoded_attribute_value_index_map[curr_att_dec][vert_id];
GetPositionForDataId(data_id, pos);
}
```
--------------------------------
### Run Draco Tests
Source: https://github.com/google/draco/blob/main/BUILDING.md
Execute the compiled tests by running the 'draco_tests' executable from your build output directory.
```bash
./draco_tests
```
--------------------------------
### Add Draco Compression to glTF/GLB using draco_transcoder
Source: https://context7.com/google/draco/llms.txt
The draco_transcoder command-line tool adds Draco mesh compression to glTF/GLB assets. Requires building Draco with transcoder support enabled.
```bash
./draco_transcoder -i in.glb -o out.glb
```
```bash
./draco_transcoder -i scene.glb -o scene_compressed.glb -qp 12
```
```bash
cmake ../ -DDRACO_TRANSCODER_SUPPORTED=ON
git submodule update --init # required for Eigen, TinyGLTF, etc.
```
--------------------------------
### Get TexCoord for Entry ID
Source: https://github.com/google/draco/blob/main/docs/spec/prediction.texcoords.decoder.md
Extracts two texture coordinate components (U and V) from the provided data array based on the entry ID. Assumes data is organized by kTexCoordsNumComponents.
```c++
void GetTexCoordForEntryId(entry_id, data, tex_coords) {
data_offset = entry_id * kTexCoordsNumComponents;
tex_coords.push_back(data[data_offset]);
tex_coords.push_back(data[data_offset + 1]);
}
```
--------------------------------
### Logging Functions
Source: https://github.com/google/draco/blob/main/javascript/time_draco_decode.html
Provides functions for logging status messages and managing HTML table output for decoding results. Includes functions to start, add cells to, and finish an HTML table.
```javascript
let dt = '';
function startTable() {
dt += '
';
dt += '| Filename | ';
dt += 'Total milli | ';
dt += 'Decode milli | ';
dt += 'Size bytes | ';
dt += 'Num points | ';
}
function addCell(str, newRow) {
if (newRow)
dt += '
';
dt += '| ' + str + ' | ';
}
function finishTable() {
dt += '
';
document.getElementById('tableOutput').innerHTML = dt;
}
function s_log(str, end_line, reset) {
if (reset)
document.getElementById('status').innerHTML = '';
document.getElementById('status').innerHTML += str;
if (end_line)
document.getElementById('status').innerHTML += "
";
}
```
--------------------------------
### Handle Multiple Decodes Click
Source: https://github.com/google/draco/blob/main/javascript/time_draco_decode.html
Initiates decoding for a multiplied list of files based on user input for decode count. Logs the total number of files and the decoder type.
```javascript
function onDecodeMultipleClick() {
startTable();
const inputs = document.getElementById('u').value.split(',');
const decode_count = parseInt(document.getElementById('decode_count').value);
const build = (typeof WebAssembly !== 'object') ? 'JavaScript' : 'WebAssembly';
s_log('Decoding ' + (decode_count * inputs.length) + ' files... using ' + build, true, true);
let fileList = [];
for (let i = 0; i < decode_count; ++i) {
fileList = fileList.concat(inputs);
}
testMeshDecodingAsync(fileList, 0);
}
```
--------------------------------
### CMake Build with Release and Debug Info
Source: https://github.com/google/draco/blob/main/BUILDING.md
Generate a release build that includes debug information by setting the CMAKE_BUILD_TYPE to RelWithDebInfo.
```bash
cmake ../ -DCMAKE_BUILD_TYPE=RelWithDebInfo
```
--------------------------------
### Get Number of Components
Source: https://github.com/google/draco/blob/main/docs/spec/edgebreaker.decoder.md
Determines the number of components for an attribute based on its decoder type and prediction scheme. Returns 2 for normal prediction differences, otherwise returns the stored component count.
```c++
int GetNumComponents() {
decoder_type = seq_att_dec_decoder_type[curr_att_dec][curr_att];
if (decoder_type == SEQUENTIAL_ATTRIBUTE_ENCODER_NORMALS) {
prediction_scheme = seq_att_dec_prediction_scheme[curr_att_dec][curr_att];
if (prediction_scheme == PREDICTION_DIFFERENCE) {
return 2;
}
}
return att_dec_num_components[curr_att_dec][curr_att];
}
```
--------------------------------
### Get Position for Entry ID
Source: https://github.com/google/draco/blob/main/docs/spec/prediction.texcoords.decoder.md
Retrieves the 3D position coordinates for a given entry ID. It maps the entry ID to a corner, then to a point ID, and finally fetches the original position values.
```c++
void GetPositionForEntryId(entry_id, pos) {
corner = encoded_attribute_value_index_to_corner_map[curr_att_dec][entry_id];
point_id = corner_to_point_map[corner];
mapped_index = indices_map_[0][point_id];
pos_orig = seq_int_att_dec_original_values[0][0];
for (i = 0; i < 3; ++i) {
pos.push_back(pos_orig[(mapped_index * 3) + i]);
}
}
```
--------------------------------
### Build Draco for WebAssembly (Point Cloud Only)
Source: https://github.com/google/draco/blob/main/BUILDING.md
Use this CMake command to build a WebAssembly decoder for point clouds only. Ensure you provide the correct path to your Emscripten toolchain file.
```bash
cmake ../ -DCMAKE_TOOLCHAIN_FILE=/path/to/Emscripten.cmake -DDRACO_WASM=ON -DDRACO_MESH_COMPRESSION=OFF
```
--------------------------------
### Add and Read Geometry/Attribute Metadata in C++
Source: https://context7.com/google/draco/llms.txt
Demonstrates adding string, integer, double, and integer array entries to geometry and attribute metadata. Ensure Draco headers are included and objects are properly managed.
```cpp
#include "draco/metadata/geometry_metadata.h"
#include "draco/point_cloud/point_cloud.h"
draco::PointCloud pc;
// Add top-level geometry metadata
auto geo_metadata = std::make_unique();
geo_metadata->AddEntryString("description", "Stanford Bunny scan");
geo_metadata->AddEntryInt("scan_id", 42);
geo_metadata->AddEntryDouble("scale", 0.001);
std::vector tags = {1, 2, 3};
geo_metadata->AddEntryIntArray("tags", tags);
pc.AddMetadata(std::move(geo_metadata));
// Add per-attribute metadata
draco::GeometryAttribute pos_att;
pos_att.Init(draco::GeometryAttribute::POSITION, nullptr, 3,
draco::DT_FLOAT32, false, 12, 0);
const uint32_t pos_att_id = pc.AddAttribute(pos_att, false, 0);
auto pos_meta = std::make_unique(pos_att_id);
pos_meta->AddEntryString("name", "position");
pos_meta->AddEntryString("units", "meters");
pc.AddAttributeMetadata(pos_att_id, std::move(pos_meta));
// Read metadata back
const draco::GeometryMetadata *meta = pc.GetMetadata();
std::string desc;
meta->GetEntryString("description", &desc); // -> "Stanford Bunny scan"
// Look up attribute by a metadata entry value
const draco::AttributeMetadata *
found =
pc.GetAttributeMetadataByStringEntry("name", "position");
// found->att_unique_id() -> pos_att_id
```
--------------------------------
### Get Position for Data ID
Source: https://github.com/google/draco/blob/main/docs/spec/prediction.normal.decoder.md
Retrieves the position for a given data ID by mapping it through corner and point indices to original sequence values. This function is part of the normal prediction decoding process.
```c++
void GetPositionForDataId(data_id, pos) {
corner = encoded_attribute_value_index_to_corner_map[curr_att_dec][data_id];
point_id = corner_to_point_map[corner];
mapped_index = indices_map_[0][point_id];
pos_orig = seq_int_att_dec_original_values[0][0];
for (i = 0; i < 3; ++i) {
pos.push_back(pos_orig[(mapped_index * 3) + i]);
}
}
```
--------------------------------
### Show Git Remotes
Source: https://github.com/google/draco/blob/main/docs/spec/README.md
Displays the configured Git remotes for the local repository, showing 'origin' and 'upstream'.
```bash
$ git remote
origin
upstream
$ git remote show origin
* remote origin
Fetch URL: git@github.com:/draco.git
Push URL: git@github.com:/draco.git
HEAD branch: main
Remote branch:
main tracked
Local branch configured for 'git pull':
main merges with remote main
Local ref configured for 'git push':
main pushes to main (up to date)
$ git remote show upstream
* remote upstream
Fetch URL: git@github.com:google/draco.git
Push URL: git@github.com:google/draco.git
HEAD branch: main
Remote branch:
main tracked
Local ref configured for 'git push':
main pushes to main (up to date)
```
--------------------------------
### Decode Edgebreaker Connectivity Data
Source: https://github.com/google/draco/blob/main/docs/spec/edgebreaker.decoder.md
Decodes the EdgeBreaker connectivity data. This function orchestrates the parsing of connectivity data, decoding of topology split events, starting the traversal, and finally decoding the connectivity.
```c++
void DecodeEdgebreakerConnectivityData() {
curr_att_dec = 0;
curr_att = 0;
ParseEdgebreakerConnectivityData();
DecodeTopologySplitEvents();
EdgebreakerTraversalStart();
DecodeEdgeBreakerConnectivity();
}
```
--------------------------------
### Compute Original TexCoord Values
Source: https://github.com/google/draco/blob/main/docs/spec/prediction.texcoords.decoder.md
Reconstructs the original texture coordinate values from the encoded data. It iterates through each corner, computes the predicted value, and then applies a decoding transform to get the final original value.
```c++
void MeshPredictionSchemeTexCoordsPortableDecoder_ComputeOriginalValues(num_values)
{
signed_values = seq_int_att_dec_symbols_to_signed_ints[curr_att_dec][curr_att];
num_components = GetNumComponents();
corner_map_size = num_values;
out_values = signed_values;
for (p = 0; p < corner_map_size; ++p) {
corner_id = encoded_attribute_value_index_to_corner_map[curr_att_dec][p];
MeshPredictionSchemeTexCoordsPortablePredictor_ComputePredictedValue(
corner_id, &out_values[0], p, &predicted_value_);
dst_offset = p * num_components;
PredictionSchemeWrapDecodingTransform_ComputeOriginalValue(
&predicted_value_[0], &out_values[dst_offset], &out_values[dst_offset]);
}
seq_int_att_dec_original_values[curr_att_dec][curr_att] = out_values;
}
```
--------------------------------
### Enable Googletest Unit Test Support
Source: https://github.com/google/draco/blob/main/BUILDING.md
Turn on Googletest unit test support by setting the DRACO_TESTS CMake variable during the CMake generation phase.
```bash
cmake ../ -DDRACO_TESTS=ON
```
--------------------------------
### Create and Commit Local Branch
Source: https://github.com/google/draco/blob/main/docs/spec/README.md
Standard Git commands for creating a new local branch, making changes, and committing them.
```git
git co -b my-branch-name
## work ##
git add
git ci -m "Reasonably clear commit message"
```
--------------------------------
### draco_transcoder Command-Line Tool
Source: https://context7.com/google/draco/llms.txt
Adds Draco mesh compression to all meshes in a glTF/GLB asset. Requires building with `-DDRACO_TRANSCODER_SUPPORTED=ON`.
```APIDOC
## draco_transcoder Command-Line Tool
### Description
Adds Draco mesh compression to all meshes in a glTF/GLB asset. Requires building with `-DDRACO_TRANSCODER_SUPPORTED=ON`.
### Usage Examples
* **Add Draco compression to all meshes in a GLB:**
```bash
./draco_transcoder -i in.glb -o out.glb
```
* **Transcode with custom position quantization (12 bits instead of default 11):**
```bash
./draco_transcoder -i scene.glb -o scene_compressed.glb -qp 12
```
* **Build with transcoder support first:**
```bash
cmake ../ -DDRACO_TRANSCODER_SUPPORTED=ON
git submodule update --init # required for Eigen, TinyGLTF, etc.
```
```
--------------------------------
### Update Git Submodules for Transcoding Support
Source: https://github.com/google/draco/blob/main/BUILDING.md
Before building Draco with transcoding support, run this command from within your Draco clone to obtain the necessary submodules.
```bash
# Run this command from within your Draco clone.
$ git submodule update --init
```
--------------------------------
### draco_transcoder Command Line
Source: https://github.com/google/draco/blob/main/README.md
Basic and advanced usage of the draco_transcoder command-line tool for adding Draco compression to glTF assets.
```APIDOC
## draco_transcoder
### Description
Adds Draco compression to glTF assets.
### Method
Command Line Tool
### Endpoint
N/A
### Parameters
#### Path Parameters
- **-i** (string) - Required - Input glTF file path.
- **-o** (string) - Required - Output glTF file path.
- **-qp** (integer) - Optional - Quantization value for the position attribute.
### Request Example
```bash
./draco_transcoder -i in.glb -o out.glb
./draco_transcoder -i in.glb -o out.glb -qp 12
```
```
--------------------------------
### Create Draco Decoder Module
Source: https://github.com/google/draco/blob/main/javascript/time_draco_decode.html
Initializes the Draco decoder module, either WebAssembly or asm.js, after the necessary files are loaded. Enables UI buttons upon successful creation.
```javascript
function createDecoderModule() {
const create_t0 = performance.now();
DracoDecoderModule(dracoDecoderType).then((module) => {
decoderModule = module;
enableButtons();
});
const create_t1 = performance.now();
addCell('DracoModule', true);
addCell(' ' + (create_t1 - create_t0), false);
}
```
--------------------------------
### Copy Draco files into Unity Project
Source: https://github.com/google/draco/blob/main/docs/unity/UNITY.md
Copies necessary Draco files (DLL, C# scripts, .drc.bytes model) into the Unity project's Assets directory. Assumes project is a sibling to the Draco repository.
```bash
# These commands assume you created the project in a sibling directory of the
# Draco repository. If your project is stored elsewhere you'll need to use
# absolute paths.
$ cd path/to/draco
$ mkdir -p ../DracoDemo/Assets/Plugins
$ cp unity/Plugin/dracodec_unity.dll ../DracoDemo/Assets/Plugins/
$ cp unity/DracoMeshLoader.cs ../DracoDemo/Assets/
$ cp unity/DracoDecodingObject.cs ../DracoDemo/Assets/
$ mkdir -p ../DracoDemo/Assets/Resources
$ cp javascript/example/models/bunny.drc \
../DracoDemo/Assets/Resources/bunny.drc.bytes
```
--------------------------------
### Handle Single Decode Click
Source: https://github.com/google/draco/blob/main/javascript/time_draco_decode.html
Initiates the decoding process for a list of files when a button is clicked. Logs the number of files and the decoder type being used.
```javascript
function onDecodeClick() {
startTable();
const inputs = document.getElementById('u').value.split(',');
const build = (typeof WebAssembly !== 'object') ? 'JavaScript' : 'WebAssembly';
s_log('Decoding ' + inputs.length + ' files... using ' + build, true, true);
testMeshDecodingAsync(inputs, 0);
}
```
--------------------------------
### Archive Android Draco Unity Plugins
Source: https://github.com/google/draco/blob/main/unity/BUILDING.md
Archives the built armv7 and arm64 Android plugins into a single tar.bz2 file for Unity.
```bash
tar cjvf libdracodec_unity_android.tar.bz \
armeabi-v7a/libdracodec_unity.so \
arm64-v8a/libdracodec_unity.so
```
--------------------------------
### Build Draco for Android (armv7)
Source: https://github.com/google/draco/blob/main/docs/unity/UNITY.md
Builds Draco for armeabi-v7a Android devices. Ensure CMake and NDK are configured.
```bash
$ cd path/to/draco
$ export CMAKE_ANDROID_NDK=path/to/ndk
$ mkdir armeabi-v7a && cd armeabi-v7a
$ cmake ../ \
-DCMAKE_TOOLCHAIN_FILE=../cmake/toolchains/armv7-android-ndk-libcpp.cmake \
-DDRACO_UNITY_PLUGIN=ON
$ make -j
```
--------------------------------
### Configure Draco with Local Dependencies
Source: https://github.com/google/draco/blob/main/BUILDING.md
Use CMake variables to specify local paths for third-party dependencies like Eigen, filesystem, and tiny_gltf, instead of relying on Git submodules.
```bash
cmake ../ -DRACO_EIGEN_PATH=/path/to/eigen
cmake ../ -DRACO_FILESYSTEM_PATH=/path/to/ghc
cmake ../ -DRACO_TINYGLTF_PATH=/path/to/tinygltf
```
--------------------------------
### Build macOS Draco Unity Plugin
Source: https://github.com/google/draco/blob/main/unity/BUILDING.md
Configures CMake for macOS and builds the Draco Unity plugin bundle. This command specifies architectures for both Intel and Apple Silicon.
```bash
cmake path/to/draco -G Xcode \
-DDRACO_UNITY_PLUGIN=ON \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CONFIGURATION_TYPES=Release \
-DCMAKE_OSX_ARCHITECTURES=arm64\;x86_64
xcodebuild
cd Release
tar cjvf libdracodec_unity_macos.tar.bz dracodec_unity.bundle
```
--------------------------------
### Build Draco for Android (arm64)
Source: https://github.com/google/draco/blob/main/docs/unity/UNITY.md
Builds Draco for arm64-v8a Android devices. Ensure CMake and NDK are configured.
```bash
$ cd path/to/draco
$ export CMAKE_ANDROID_NDK=path/to/ndk
$ mkdir arm64-v8a && cd arm64-v8a
$ cmake ../ \
-DCMAKE_TOOLCHAIN_FILE=../cmake/toolchains/arm64-android-ndk-libcpp.cmake \
-DDRACO_UNITY_PLUGIN=ON
$ make -j
```
--------------------------------
### Copy Windows Draco Library
Source: https://github.com/google/draco/blob/main/unity/README.md
Copies the Draco Unity dynamic-link library for Windows to the Unity project's plugin directory. This enables Draco functionality within the Unity editor and builds on Windows.
```bash
cp path/to/your/dracodec_unity.dll path/to/your/Unity/Project/Assets/Plugins/
```
--------------------------------
### CMake Build with Debug Flags
Source: https://github.com/google/draco/blob/main/BUILDING.md
Configure the build for standard debugging by setting the CMAKE_BUILD_TYPE to Debug.
```bash
cmake ../ -DCMAKE_BUILD_TYPE=Debug
```
--------------------------------
### Initialize Javascript Decoder Buffer
Source: https://github.com/google/draco/blob/main/README.md
To use the Javascript Draco decoder, first create an instance of DracoDecoderModule, then create a DecoderBuffer and set the encoded data into it.
```javascript
// Create the Draco decoder.
const decoderModule = DracoDecoderModule();
const buffer = new decoderModule.DecoderBuffer();
```
--------------------------------
### C++ File I/O Helpers
Source: https://context7.com/google/draco/llms.txt
High-level file I/O helpers for reading and writing meshes from/to various file formats, simplifying common use cases.
```APIDOC
## C++ File I/O Helpers — `ReadMeshFromFile` / `WriteMeshIntoStream`
High-level file I/O helpers in `draco/io/mesh_io.h` that wrap codec setup and stream handling for common use cases.
```cpp
#include "draco/io/mesh_io.h"
#include
// Read a mesh from an OBJ/PLY/STL/DRC file — codec selected by file extension
draco::StatusOr> result =
draco::ReadMeshFromFile("bunny.ply");
if (!result.ok()) {
std::cerr << result.status().error_msg() << std::endl;
return 1;
}
std::unique_ptr mesh = std::move(result).value();
// Write mesh to a binary stream using edgebreaker encoding
std::ofstream ofs("bunny.drc", std::ios::binary);
draco::WriteMeshIntoStream(mesh.get(), std::move(ofs),
draco::MESH_EDGEBREAKER_ENCODING);
// Read back from stream
std::ifstream ifs("bunny.drc", std::ios::binary);
std::unique_ptr loaded_mesh;
draco::ReadMeshFromStream(&loaded_mesh, std::move(ifs));
std::cout << "Reloaded: " << loaded_mesh->num_faces() << " faces\n";
// Read OBJ with metadata (material names, object names stored as attributes)
draco::Options opts;
opts.SetBool("use_metadata", true);
auto mesh_with_meta = draco::ReadMeshFromFile("scene.obj", opts);
```
```
--------------------------------
### Build Javascript Encoder/Decoder with Emscripten
Source: https://github.com/google/draco/blob/main/BUILDING.md
Generate build files using CMake with the Emscripten toolchain file, then build the Javascript encoder and decoder using 'make'.
```bash
cmake ../ -DCMAKE_TOOLCHAIN_FILE=/path/to/Emscripten.cmake
```
```bash
make
```
--------------------------------
### Build Draco for iOS (i386)
Source: https://github.com/google/draco/blob/main/BUILDING.md
Compile Draco for the i386 iOS target using the specified CMake toolchain file and then build using 'make'.
```bash
cmake ../ -DCMAKE_TOOLCHAIN_FILE=../cmake/toolchains/i386-ios.cmake
make
```
--------------------------------
### JavaScript Metadata API: Encoding and Querying
Source: https://context7.com/google/draco/llms.txt
Demonstrates encoding custom key-value metadata to geometry and attributes, and querying it after decoding. Ensure Draco modules are loaded before use.
```javascript
draco3d.createEncoderModule({}).then(function(encoderModule) {
const meshBuilder = new encoderModule.MeshBuilder();
const mesh = new encoderModule.Mesh();
const vertices = new Float32Array([0,0,0, 1,0,0, 0,1,0]);
const indices = new Uint32Array([0,1,2]);
meshBuilder.AddFacesToMesh(mesh, 1, indices);
const posAttId = meshBuilder.AddFloatAttribute(
mesh, encoderModule.POSITION, 3, 3, vertices);
// Build geometry-level metadata
const metadataBuilder = new encoderModule.MetadataBuilder();
const geoMetadata = new encoderModule.Metadata();
metadataBuilder.AddStringEntry(geoMetadata, 'description', 'Test triangle');
metadataBuilder.AddIntEntry(geoMetadata, 'lod', 2);
metadataBuilder.AddDoubleEntry(geoMetadata, 'scale', 0.01);
meshBuilder.AddMetadata(mesh, geoMetadata);
// Build per-attribute metadata
const attMetadata = new encoderModule.Metadata();
metadataBuilder.AddStringEntry(attMetadata, 'name', 'position');
metadataBuilder.AddStringEntry(attMetadata, 'units', 'meters');
meshBuilder.SetMetadataForAttribute(mesh, posAttId, attMetadata);
const encoder = new encoderModule.Encoder();
const encodedData = new encoderModule.DracoInt8Array();
encoder.EncodeMeshToDracoBuffer(mesh, encodedData);
encoderModule.destroy(geoMetadata);
encoderModule.destroy(attMetadata);
encoderModule.destroy(encodedData);
encoderModule.destroy(encoder);
encoderModule.destroy(mesh);
encoderModule.destroy(meshBuilder);
});
// Querying metadata after decoding (decoder side)
draco3d.createDecoderModule({}).then(function(decoderModule) {
// ... decode geometry as shown above, then:
const metaQuerier = new decoderModule.MetadataQuerier();
const geoMeta = decoder.GetMetadata(geometry);
if (metaQuerier.HasEntry(geoMeta, 'description')) {
console.log(metaQuerier.GetStringEntry(geoMeta, 'description'));
// -> "Test triangle"
console.log(metaQuerier.GetIntEntry(geoMeta, 'lod')); // -> 2
}
// Look up attribute by metadata
const posAttId = decoder.GetAttributeIdByMetadataEntry(
geometry, 'name', 'position');
decoderModule.destroy(metaQuerier);
});
```
--------------------------------
### Browser Integration with GStatic CDN Decoder
Source: https://context7.com/google/draco/llms.txt
Loads prebuilt WASM Draco decoders from Google's GStatic CDN for use with three.js. Pinning to versioned URLs is recommended for stability.
```html
```
--------------------------------
### Build Windows Draco Unity Plugin
Source: https://github.com/google/draco/blob/main/unity/BUILDING.md
Configures CMake for Visual Studio 2022 on Windows and builds the Draco Unity plugin DLL. The build is parallelized using the /M flag.
```bash
cmake ../ -G "Visual Studio 17 2022" -A x64 -DDRACO_UNITY_PLUGIN=ON \
-DCMAKE_INSTALL_PREFIX=.
cmake --build . --config Release --target install -- /M:36
cd lib
tar cjvf libdracodec_unity_windows.tar.bz dracodec_unity.dll
```
--------------------------------
### Maya Plugin Library Configuration
Source: https://github.com/google/draco/blob/main/CMakeLists.txt
Configures the Draco Maya plugin library. It sets up the plugin as a MODULE type and configures it as a bundle for Apple platforms.
```cmake
if(DRACO_MAYA_PLUGIN)
draco_add_library(
NAME draco_maya_plugin
TYPE OBJECT
SOURCES ${draco_maya_plug_sources}
DEFINES ${draco_defines}
INCLUDES ${draco_include_paths})
draco_add_library(
NAME draco_maya_wrapper
TYPE MODULE
DEFINES ${draco_defines}
INCLUDES ${draco_include_paths}
OBJLIB_DEPS draco_maya_plugin
LIB_DEPS ${draco_plugin_dependency})
# For Mac, we need to build a .bundle for the plugin.
if(APPLE)
set_target_properties(draco_maya_wrapper PROPERTIES BUNDLE true)
endif()
endif()
```
--------------------------------
### Build Draco for iOS (x86_64)
Source: https://github.com/google/draco/blob/main/BUILDING.md
Compile Draco for the x86_64 iOS target using the specified CMake toolchain file and then build using 'make'.
```bash
cmake ../ -DCMAKE_TOOLCHAIN_FILE=../cmake/toolchains/x86_64-ios.cmake
make
```