Models

The TGorillaModel component is the primary container for loading and managing 3D models in Gorilla3D. It automatically handles sub-meshes, materials, animations, lights, cameras, and armatures, providing a comprehensive solution for 3D model integration.

Important: All 3D models must be children of a TGorillaViewport instance to be rendered.

Supported File Formats

Gorilla3D supports 12+ model formats with varying feature sets:

Format Key Features Animation Support Export
G3D Complete support including animations, lights, cameras; internal format ✓ Yes ✓ Yes
USD .usd, .usda, .usdc, .usdz; meshes, materials, textures, UsdSkel skeletons ✓ Yes ✓ Yes (.usda, .usdc, .usdz)
glTF/GLB 2.0 format only; PBR materials, skinning ✓ Yes ✓ Yes (.glb)
DAE (Collada) Animations, lights, cameras; v1.4+ ✓ Yes ✗ No
FBX Animations, lights, cameras; Binary only (v7.1-7.7) ✓ Yes (v7.3-7.7) ✗ No
OBJ ASCII format ✗ No ✓ Yes
STL Binary and ASCII ✗ No ✓ Yes
Babylon Limited features ○ Partial ✗ No
PLY Limited features ✗ No ✗ No
SketchUp Limited features ✗ No ✗ No

USD (Universal Scene Description)

All four USD flavours are handled by one loader (Gorilla.USD.Loader), the format is picked by the file extension:

Extension Container Notes
.usda / .usd ASCII stage Human readable, easy to diff
.usdc Binary crate Compact, fast to parse
.usdz ZIP archive Carries the stage and its textures; the AR format of iOS Quick Look

The importer builds the full Gorilla3D model definition from the stage: meshes, materials with their textures (inside .usdz they are read straight out of the archive), UsdSkel skeletons including the joint hierarchy and rest poses, and SkelAnimation clips, which arrive as regular TGorillaAnimation objects:

// The extension decides the parser - nothing else to set up
GorillaModel1.LoadFromFile('models/character.usdz');

// SkelAnimation clips arrive in the regular animation manager
for var LName in GorillaModel1.AnimationManager.Animations.Keys do
  Memo1.Lines.Add(LName);

GorillaModel1.AnimationManager.PlayAnimation('Walk');

Loading Models

Design-Time Loading

Embedded Models

Store model data directly in .fmx files for quick prototyping:

  1. Add a TGorillaModel component to your form
  2. Set the Source property to your model file path
  3. The model data will be embedded in binary format

Warning: Large embedded models slow IDE performance and can cause memory issues (3GB IDE-32Bit limit). When storing larges textures and vertex-data the IDE slows down due to .fmx file storing process, which is performed on making changes at design time.

Asset Packages

Link external ZIP archives for better development workflow:

  1. Add a TGorillaAssetsManager component
  2. Create or link an asset package
  3. Set the model's AssetsManager and PackageName properties
  4. Set the Source property to the model filename
// Design-time setup
GorillaModel1.AssetsManager := GorillaAssetsManager1;
GorillaModel1.PackageName := 'MyAssets';
GorillaModel1.Source := 'character.dae';

Runtime Loading

Method 1: LoadNewModelFromFile

Creates a new model instance and loads data from file:

var
  MyModel: TGorillaModel;
begin
  MyModel := TGorillaModel.LoadNewModelFromFile(
    Viewport,                    // Owner
    nil,                         // Package (nil = load from file)
    'models\character.dae',      // Filename
    []                          // Caching flags
  );
  MyModel.Parent := Viewport;
end;

With an asset package:

var
  MyModel: TGorillaModel;
begin
  MyModel := TGorillaModel.LoadNewModelFromFile(
    Viewport,
    MyAssetsPackage,
    'character.g3d',
    GORILLA_ANIMATION_CACHING_DEFAULT
  );
  MyModel.Parent := Viewport;
end;

Method 2: LoadFromFile

Loads data into an existing model instance:

GorillaModel1.LoadFromFile(nil, 'models\character.dae', []);

Method 3: Advanced Loading with TGorillaLoadOptions

For fine-grained control over the loading process:

var
  Options: TGorillaLoadOptions;
begin
  Options := TGorillaLoadOptions.Create('models\scene.fbx', [], nil, nil);

  // Configure options
  Options.ImportLights := False;
  Options.ImportCameras := False;
  Options.ImportAnimations := True;
  Options.Caching := GORILLA_ANIMATION_CACHING_DEFAULT;

  // Limit texture sizes
  Options.TextureLimits := TPoint.Create(2048, 2048);

  // Load the model
  GorillaModel1.LoadFromFile(Options);
end;

Texture memory: TextureLimits makes imported textures smaller — it trades resolution for memory and applies only to textures this model brings with it. If your problem is the total video memory of a scene, GPU block compression is usually the better first step: it saves a factor of four across all textures without touching their resolution. The two combine.

Loading from Stream

For loading from memory or custom sources:

var
  Stream: TFileStream;
begin
  Stream := TFileStream.Create('model.dae', fmOpenRead);
  try
    GorillaModel1.LoadFromStream(
      nil,                  // Package
      Stream,              // Stream
      'model.dae',         // Path/filename for format detection
      []                   // Caching flags
    );
  finally
    Stream.Free;
  end;
end;

Animation Management

Loading Additional Animations

Add animations from separate files:

var
  Anim: TGorillaAnimation;
begin
  // Model must be loaded first
  Anim := GorillaModel1.AddAnimationFromFile(
    'character_run.dae',
    []
  );
end;

Important: You can only add animations on an existing model, if the meta data from original model import is still available. Because after reloading a model, it's not loaded from the original file format again. So the meta data from a FBX or DAE is lost and animation data cannot be applied again.

Playing Animations

Access animations through the built-in AnimationManager:

// List all animations
for var AnimName in GorillaModel1.AnimationManager.Animations.Keys do
  Memo1.Lines.Add(AnimName);

// Play an animation
GorillaModel1.AnimationManager.PlayAnimation('Walk');

// Stop current animation
GorillaModel1.AnimationManager.StopAnimation();

// Get current animation
var Current := GorillaModel1.AnimationManager.Current;
if Assigned(Current) then
  ShowMessage('Playing: ' + Current.Id);

Animation Caching

Animation caching improves performance by pre-computing vertex positions:

Flag Description Use Case
VertexPosition Cache vertex positions only (recommended) Fast playback, moderate memory
AllAttributes Cache all vertex attributes Maximum speed, high memory usage
Compressed Compress cached data Large animations, slower than direct caching
// Recommended: Cache vertex positions only
MyModel := TGorillaModel.LoadNewModelFromFile(
  Viewport,
  nil,
  'character.dae',
  [TAnimationCachingFlag.VertexPosition]
);

// For maximum performance (high memory)
MyModel := TGorillaModel.LoadNewModelFromFile(
  Viewport,
  nil,
  'character.dae',
  [TAnimationCachingFlag.AllAttributes]
);

// For large animations (compressed)
MyModel := TGorillaModel.LoadNewModelFromFile(
  Viewport,
  nil,
  'character.dae',
  [TAnimationCachingFlag.VertexPosition, TAnimationCachingFlag.Compressed]
);

Notice: A global constant GORILLA_ANIMATION_CACHING_DEFAULT is recommended for usage.

Model Hierarchy

Understanding the Structure

A loaded model contains a hierarchy of components:

TGorillaModel
├─ TGorillaMesh (Sub-meshes)
│  ├─ TGorillaVertexGroup (Material groups)
│  └─ TGorillaMesh (Nested sub-meshes)
├─ TGorillaArmature (Skeleton)
│  └─ TGorillaJoint (Bones)
├─ TGorillaLight (Embedded lights)
├─ TGorillaCamera (Embedded cameras)
└─ TGorillaAnimation (Animations)

Accessing Sub-Components

// Access meshes
for var i := 0 to GorillaModel1.Meshes.Count - 1 do
begin
  var Mesh := GorillaModel1.Meshes[i];
  ShowMessage('Mesh: ' + Mesh.Name);
end;

// Find specific mesh by name
var HeadMesh := GorillaModel1.FindControlByDeepSearch('Head') as TGorillaMesh;
if Assigned(HeadMesh) then
  HeadMesh.MaterialSource := MyMaterial;

// Access armature
var Armature := GorillaModel1.GetFirstArmature() as TGorillaArmature;
if Assigned(Armature) then
begin
  Armature.ShowJoints := True;
  Armature.JointsRenderColor := TAlphaColors.Red;
end;

Debug Output

Print the model hierarchy to the event log:

GorillaModel1.DebugOut(False);  // FMX hierarchy
GorillaModel1.DebugOut(True);   // Component hierarchy

Material Management

Applying Materials

// Apply material to entire model
GorillaModel1.MaterialSource := MyMaterialSource;

// Apply to specific mesh
var Mesh := GorillaModel1.FindControlByDeepSearch('Body') as TGorillaMesh;
if Assigned(Mesh) then
  Mesh.MaterialSource := BodyMaterial;

// Batch apply materials
GorillaModel1.ApplyMaterialSource(MyMaterialSource);

Warning: Applying a material to the entire model will overwrite individual mesh materials and cannot be automatically restored.

Rendering Features

Wireframe Rendering

// Enable wireframe
GorillaModel1.Wireframe := True;
GorillaModel1.WireframeMaterial := MyWireframeMaterial;

Performance: Wireframe rendering is costly. Use only for debugging.

Normal Visualization

GorillaModel1.ShowNormals := True;
GorillaModel1.NormalsColor := TAlphaColors.Green;

Joint Visualization

GorillaModel1.ShowJoints := True;
GorillaModel1.JointsColor := TAlphaColors.Yellow;

Bounding Box Visualization

ShowBoundingBox draws a box around the current pose of the model. The box follows skin animations (rigged models), vertex animations and animated sub-meshes, and it rotates with the model.

GorillaModel1.ShowBoundingBox := True;
GorillaModel1.BoundingBoxColor := TAlphaColors.Orange; // default

Both properties are published and can be set in the form designer. The box is drawn in the main render pass only (not in shadow, reflection or other render passes).

The properties are declared in TGorillaControl, so they are available on every Gorilla3D control, not only on models. What the box encloses depends on the class:

Class Box
TGorillaModel Current pose of all sub-meshes, follows skin, vertex and node animations
TGorillaMesh Vertices of the mesh and its sub-meshes, including the mesh matrix (WrapMode). Works for static meshes (IsStatic = True) too: their vertices are taken from the mesh definition
TGorillaSingletonMesh (TGorillaCube, TGorillaSphere, TGorillaCylinder, ...) The body size (Width, Height, Depth), the same box IsMarked draws
any other TGorillaControl (f.e. TGorillaGroup) The size box of the control (Width, Height, Depth)

A sub-mesh of a model can show its own box as well, f.e. to highlight a single part:

GorillaModel1.Meshes[0].ShowBoundingBox := True;
GorillaModel1.Meshes[0].BoundingBoxColor := TAlphaColors.Red;

Note: TGorillaParticleEmitter and TGorillaGaussianSplatting render on their own and do not draw the box.

Not the same as IsMarked: the box the IDE draws around a selected model (IsMarked) is built from the static vertex data and does not follow animations. It is kept that way on purpose, because the designer relies on it.

Performance: With animation caching the box of every frame is computed once while caching, so showing it costs (almost) nothing. Without caching all animated vertices are iterated each frame.

Instancing

There are two ways to render the same model several times: GPU instancing (one draw call, shared geometry, material and animation state) and model cloning (independent copies sharing only the vertex data). Use GPU instancing for large numbers of identical objects (trees, rocks, crates, grass), use cloning if every copy needs its own animation or material.

GPU Instancing

Every TGorillaMesh - and therefore every TGorillaModel, TGorillaCube, TGorillaSphere, ... - owns an Instances collection (TGorillaMeshInstances). For each entry the mesh is drawn once more within the same draw call, the GPU only receives a different transformation matrix per instance.

Things to know before you start:

  • The mesh itself is always instance #0. Its transformation (Position, RotationAngle, Scale of the component) is written to slot 0 of the instance list every frame. Each added instance is an additional copy.
  • Instance transformations are absolute. The matrix of an instance replaces the world matrix of the mesh, it is not relative to the mesh's position. Moving the component moves instance #0 only, all other instances stay where they are.
  • Everything else is shared: geometry, material, animation pose, visibility, opacity. You cannot give a single instance its own color or animation - use Model Cloning for that.
  • Add instances to the model, not to a sub-mesh. Instance items of a TGorillaModel are passed on to all of its sub-meshes automatically, so the complete model is instanced.
  • Frustum culling is decided on the bounds of the source mesh only. If FrustumCullingCheck is enabled, all instances disappear as soon as the source mesh leaves the camera view. Keep it disabled for instanced meshes that are spread across the scene.

There are two APIs to add instances:

AddInstanceItem() AddInstance()
Creates a TGorillaMeshInstance collection item only a matrix in the internal instance cache
Edit via Position, RotationAngle, Scale, RotationCenter SetInstance(Index, Matrix)
Visible in the Object Inspector / stored in .fmx yes no
Passed on to sub-meshes of a model yes no - call it on each mesh with geometry
Memory / speed an object with 4 TPosition3D per instance one TMatrix3D per instance (fastest)

Adding Instance Items (AddInstanceItem)

TGorillaMesh provides two overloads:

// Creates an item with identity transform (at the origin) and returns the item itself.
function AddInstanceItem(AName : String) : TGorillaMeshInstance; overload;

// Creates an item, applies the matrix and returns the INDEX of the item in the
// Instances collection (Mesh.Instances.Items[Index]).
function AddInstanceItem(AName : String; ATransform : TMatrix3D) : Integer; overload;

The returned TGorillaMeshInstance is a TCollectionItem with the same transformation properties you know from FMX 3D controls:

Member Description
Position: TPosition3D Translation of the instance (absolute, see above)
RotationAngle: TPosition3D Rotation in degrees around X, Y and Z
Scale: TPosition3D Scaling, default (1, 1, 1)
RotationCenter: TPosition3D Pivot the rotation is performed around, default (0, 0, 0)
DisplayName: String Name of the instance (the AName argument)
Transform: TMatrix3D Read-only, the resulting matrix uploaded to the GPU
OwnerMesh: TGorillaMesh The mesh this instance belongs to
SetTransform(Matrix) Sets the instance by a matrix; Position, Scale and RotationAngle are extracted from it
ResetRotationAngle() Resets the rotation to (0, 0, 0)
BeginUpdate() / EndUpdate() Defers matrix and buffer rebuilds, see below

The matrix is composed in the order Scale → Rotation (around RotationCenter) → Translation.

uses
  Gorilla.Mesh, Gorilla.Model;

procedure TForm1.AddTree(const AName : String; const APos : TPoint3D);
var LInst : TGorillaMeshInstance;
begin
  LInst := GorillaModel1.AddInstanceItem(AName);

  LInst.BeginUpdate();
  try
    LInst.Position.Point      := APos;
    LInst.RotationAngle.Point := Point3D(0, Random(360), 0);
    LInst.Scale.Point         := Point3D(1.5, 1.5, 1.5);
  finally
    LInst.EndUpdate();
  end;
end;

Existing instances are accessed through the collection. Note that the collection does not contain the mesh itself, so Instances.Items[0] is the first additional instance:

var LInst : TGorillaMeshInstance;
begin
  for var I := 0 to GorillaModel1.Instances.Count - 1 do
  begin
    LInst := GorillaModel1.Instances.Items[I] as TGorillaMeshInstance;
    LInst.Position.Y := LInst.Position.Y + 1;
  end;
end;

The variant with a matrix is handy if you already compute matrices:

var LIdx  : Integer;
    LInst : TGorillaMeshInstance;
begin
  LIdx := GorillaModel1.AddInstanceItem('Crate',
    TMatrix3D.CreateRotationY(DegToRad(45)) *
    TMatrix3D.CreateTranslation(Point3D(4, 0, -2)));

  // Position, Scale and RotationAngle were extracted from the matrix
  LInst := GorillaModel1.Instances.Items[LIdx] as TGorillaMeshInstance;
  LInst.Position.X := 6;
end;

RotationAngle behaves like in FMX: a change of an angle is applied as the difference to the previous value onto an internal quaternion. Setting RotationAngle.Y := 90 on an instance with Y = 45 rotates it by another 45 degrees, so the result is 90 degrees as expected. If you want to set a completely new orientation, call ResetRotationAngle() first or use SetTransform().

Why BeginUpdate / EndUpdate?

Every single property change of an instance - each Position.X, each RotationAngle.Y, each Scale.Point - triggers:

  1. a rebuild of the instance matrix,
  2. a rebuild of the complete instance list of the mesh (all instances, not only the changed one), and
  3. passing this list on to all sub-meshes of the model.

Setting Position, RotationAngle and Scale of one instance therefore rebuilds the list at least three times. BeginUpdate() defers steps 1-3 until the matching EndUpdate(), which rebuilds the matrix and the instance list exactly once. Calls can be nested, only the outermost EndUpdate() performs the rebuild. Always use try..finally, otherwise an exception leaves the instance locked.

BeginUpdate()/EndUpdate() is the right choice when you change one or a few instances. Each EndUpdate() still rebuilds the whole list, so changing N instances this way costs N list rebuilds. For many instances use BeginInstancesEditing().

Mass Manipulation (BeginInstancesEditing / EndInstancesEditing)

TGorillaMesh.BeginInstancesEditing() locks the instance list of the mesh, all of its instance items and all sub-meshes. While locked, property changes and newly added items only update their values. EndInstancesEditing() then rebuilds all instance matrices, the instance list and the sub-mesh lists once:

procedure TForm1.PlantForest(const ACount : Integer);
var LInst : TGorillaMeshInstance;
    LScl  : Single;
begin
  GorillaModel1.BeginInstancesEditing();
  try
    GorillaModel1.ClearInstances();

    for var I := 0 to ACount - 1 do
    begin
      // items created inside the bracket are covered as well
      LInst := GorillaModel1.AddInstanceItem(Format('Tree_%d', [I]));
      LInst.Position.Point      := Point3D(Random(200) - 100, 0, Random(200) - 100);
      LInst.RotationAngle.Point := Point3D(0, Random(360), 0);

      LScl := 0.8 + Random * 0.6;
      LInst.Scale.Point := Point3D(LScl, LScl, LScl);
    end;
  finally
    // single rebuild for all instances
    GorillaModel1.EndInstancesEditing();
  end;
end;

The same pattern is used to animate many instances each frame:

procedure TForm1.SwayTrees(const ATime : Single);
var LInst : TGorillaMeshInstance;
begin
  GorillaModel1.BeginInstancesEditing();
  try
    for var I := 0 to GorillaModel1.Instances.Count - 1 do
    begin
      LInst := GorillaModel1.Instances.Items[I] as TGorillaMeshInstance;
      LInst.RotationAngle.Z := Sin(ATime + I) * 5;
    end;
  finally
    GorillaModel1.EndInstancesEditing();
  end;
end;

Inside BeginInstancesEditing()/EndInstancesEditing() you do not need BeginUpdate()/EndUpdate() on the single items. As with any lock, every BeginInstancesEditing() needs exactly one EndInstancesEditing().

Scenario Use
Change one instance Item.BeginUpdate() / Item.EndUpdate()
Create, change or delete many instances Mesh.BeginInstancesEditing() / Mesh.EndInstancesEditing()
Only the collection of a single mesh, without sub-meshes Mesh.Instances.BeginUpdates() / Mesh.Instances.EndUpdates()

On a TGorillaModel always use BeginInstancesEditing()/EndInstancesEditing() instead of Instances.BeginUpdates()/EndUpdates() - it also takes care of the sub-meshes in the right order.

Matrix-Only Instances (AddInstance)

If you only need to place a large number of static instances at runtime, you can skip the collection items and add plain matrices to the instance cache. This is the fastest and most memory efficient way, but the instances are neither visible in the Object Inspector nor stored in the .fmx file.

procedure AddMatrixInstances(AMesh : TGorillaMesh; const ATransforms : TArray<TMatrix3D>);
begin
  // matrix-only instances are NOT passed on to sub-meshes, so add them to
  // every mesh of the hierarchy that has geometry
  for var LTransform in ATransforms do
    AMesh.AddInstance(LTransform);

  if Assigned(AMesh.Meshes) then
    for var I := 0 to AMesh.Meshes.Count - 1 do
      AddMatrixInstances(AMesh.Meshes[I], ATransforms);
end;

procedure TForm1.FormCreate(Sender: TObject);
var LTransforms : TArray<TMatrix3D>;
begin
  SetLength(LTransforms, 100);
  for var X := 0 to 9 do
    for var Z := 0 to 9 do
      LTransforms[X * 10 + Z] := TMatrix3D.CreateTranslation(Point3D(X * 2, 0, Z * 2));

  AddMatrixInstances(GorillaModel1, LTransforms);
end;

AddInstance() returns the index of the matrix in the instance cache, which can be used with GetInstance()/SetInstance(). Changes are uploaded with the next frame:

var LIdx : Integer;
begin
  LIdx := GorillaCube1.AddInstance(TMatrix3D.CreateTranslation(Point3D(5, 0, 0)));
  // ...
  GorillaCube1.SetInstance(LIdx, TMatrix3D.CreateTranslation(Point3D(5, 2, 0)));
end;

Index 0 of the cache is the mesh itself and is overwritten every frame - GetInstance(0)/SetInstance(0, ...) has no lasting effect. Cache indices of additional instances start at 1.

Do not mix both APIs on the same mesh. Whenever an instance item is added, changed or deleted, the cache is rebuilt from the collection items, and all matrix-only instances are dropped.

Removing Instances

// remove a single instance item by its collection index
GorillaModel1.DeleteInstance(0);

// or free the item directly
GorillaModel1.Instances.Items[3].Free();

// remove all instance items and all matrix-only instances
GorillaModel1.ClearInstances();

TGorillaMesh.DeleteInstance() works on the collection index of instance items. To remove matrix-only instances, call ClearInstances() and add the remaining matrices again. When deleting many items, wrap the loop in BeginInstancesEditing()/EndInstancesEditing() as well.

Design Time

The Instances property of every Gorilla3D mesh, model and primitive is published. Open the collection editor in the Object Inspector, add items and edit their Position, RotationAngle and Scale - the instances are rendered immediately in the form designer and stored in the .fmx file. Terrain planting (see Terrain) creates instance items the same way.

Model Cloning

Instancing can be done by GPU and providing different transformation matrices like above or by cloning the visual component with all of it's data. Both ways have their advantages and disadvantages.

Use instancing if you want to re-render a mesh multiple times Use cloning if you need different visual feedback (like animations or materials), but if you want to reuse the vertex data itself In the following example we show how to load a complex animated model with multiple meshes and animations. We will load up a template (TModelDef), which will be used for duplication. The template (TModelDef) itself will not be rendered in our example, but of course that's possible too.

Each duplicated model will run a different animation to show instanciating is still fast, but allows to handle models differently. This demo code uses cached animations (GORILLA_ANIMATION_CACHING_DEFAULT), otherwise 32 animated instances will not render properly anymore, due to many vertex operations.

Create independent copies with separate animations and materials:

procedure TForm1.InstanciateModel(AModelsPath : String);
const
  NUM_OF_MODELS = 32;
  MODELS_SPACE = 8;

var LAnim     : TGorillaAnimation;
    LMdlPath  : String;
    I         : Integer;
    LPlayInst : TGorillaModel;
    LOfs      : Single;
begin
  LAnim := nil;

  // load player model
  LMdlPath := IncludeTrailingPathDelimiter(AModelsPath) +
    IncludeTrailingPathDelimiter('archer');
  FPlayerTemplate := TGorillaModel.LoadNewModelFromFile(FGorilla, FPackage,
    LMdlPath + 'archer.dae', GORILLA_ANIMATION_CACHING_DEFAULT);
  FPlayerTemplate.Parent := FGorilla;
  FPlayerTemplate.Scale.Point := Point3D(0.05, 0.05, 0.05);
  FPlayerTemplate.SetHitTestValue(false);

  // add various animations
  FPlayerTemplate.AddAnimationFromFile(LMdlPath + 'archer-aim-idle.dae',
    GORILLA_ANIMATION_CACHING_DEFAULT);
  FPlayerTemplate.AddAnimationFromFile(LMdlPath + 'archer-idle2.dae',
    GORILLA_ANIMATION_CACHING_DEFAULT);
  FPlayerTemplate.AddAnimationFromFile(LMdlPath + 'archer-idle3.dae',
    GORILLA_ANIMATION_CACHING_DEFAULT);
  FPlayerTemplate.AddAnimationFromFile(LMdlPath + 'archer-crouch-idle.dae',
    GORILLA_ANIMATION_CACHING_DEFAULT);

  // now create instances
  FPlayerInstances := TObjectList<TGorillaModel>.Create(false);
  I := 0;
  for I := 0 to NUM_OF_MODELS - 1 do
  begin
    // perform a real duplication of visual components by **FALSE** for the second parameter
    // if second parameter is **TRUE**, only proxy components will be produced
    LPlayInst := FPlayerTemplate.Duplicate(FGorilla, false) as TGorillaModel;
    FPlayerInstances.Add(LPlayInst);

    LPlayInst.Parent := FGorilla;

    // line up characters in a row
    LOfs := -(NUM_OF_MODELS div 2) * MODELS_SPACE;
    LPlayInst.Position.Point := Point3D(LOfs + (I * MODELS_SPACE), 0, 0);
    LPlayInst.RotationAngle.X := 180;

    // select one of the available animations - so characters animate differently
    case I mod 4 of
      0  : LAnim := LPlayInst.AnimationManager.Animations.Items['archer-aim-idle.dae'];
      1  : LAnim := LPlayInst.AnimationManager.Animations.Items['archer-idle2.dae'];
      2  : LAnim := LPlayInst.AnimationManager.Animations.Items['archer-idle3.dae'];
      else LAnim := LPlayInst.AnimationManager.Animations.Items['archer-crouch-idle.dae'];
    end;

    // start the duplicated character animation
    if Assigned(LAnim) then
      LAnim.Start();
  end;

  // we ignore the template for rendering
  FPlayerTemplate.Visible := false;
end;

Model Export

Export models to supported formats:

G3D Export (Internal Format)

uses Gorilla.G3D.Exporter;

var
  Exporter: TGorillaG3DExporter;
begin
  Exporter := TGorillaG3DExporter.Create;
  try
    Exporter.Format := TGorillaG3DFormat.BSONFormat;  // Binary
    Exporter.Beautified := False;
    Exporter.Zipped := True;
    Exporter.SaveToFile(GorillaModel1.Def as TModelDef, 'output.g3d');
  finally
    Exporter.Free;
  end;
end;

glTF Export (GLB)

uses Gorilla.GLB.Exporter;

var
  LExp: TGorillaGLBExporter;
begin
  LExp := TGorillaGLBExporter.Create();
  try
    LExp.Generator := 'My Application';  // written into asset.generator
    LExp.SaveToFile(FModel.Def as TModelDef, 'output.glb');
  finally
    LExp.Free();
  end;
end;

Produces a self-contained glTF 2.0 binary file — geometry, PBR materials with embedded images, the node hierarchy, skins and animation samplers all live inside the single .glb container.

USD Export (USDA / USDC / USDZ)

One exporter per container, all three write the same scene structure:

Unit Class Extension Output
Gorilla.USDA.Exporter TGorillaUSDAExporter .usda ASCII stage, textures written next to the file
Gorilla.USDC.Exporter TGorillaUSDCExporter .usdc Binary crate, textures written next to the file
Gorilla.USDZ.Exporter TGorillaUSDZExporter .usdz ZIP archive holding the stage and its textures
uses Gorilla.USDA.Exporter;

var
  LExp: TGorillaUSDAExporter;
begin
  LExp := TGorillaUSDAExporter.Create();
  try
    LExp.UpAxis := 'Y';                // default
    LExp.DefaultPrimName := 'Model';   // name of the root Xform / defaultPrim
    LExp.TimeCodesPerSecond := 24.0;   // default
    LExp.MultiAnimMode := TUSDAMultiAnimMode.VariantSet;
    LExp.SaveToFile(FModel.Def as TModelDef, 'character.usda');
  finally
    LExp.Free();
  end;
end;

Skeletons and animations are exported as UsdSkel: a SkelRoot with its Skeleton, the joint rest poses and one SkelAnimation per clip. Because skel:animationSource is a single-target relationship, multiple clips need a layout decision:

MultiAnimMode Layout
VariantSet (default) One SkelRoot with one Skeleton and one Mesh; every clip is a sibling SkelAnimation, and a variant set anim switches between them. usdview selects the clip in the Meta Data panel, Blender imports all clips as Actions
SeparateSkelRoots One fully self-contained SkelRoot per clip. Portable across every viewer, but the geometry is duplicated per clip
SeparateFiles Each clip is written to its own sibling file <base>_<animName>.usda / .usdc, matching the Unity / Unreal clip-per-asset convention. The file passed to SaveToFile receives the first clip

TGorillaUSDCExporter offers the same properties plus MetersPerUnit (default 1.0) and the two toggles EmitSkinPrimvars / EmitTimeSamples (both True), which control whether skin primvars and animation time samples are written.

For a single distributable file — the format iOS Quick Look and most AR viewers expect — use USDZ:

uses Gorilla.USDZ.Exporter;

var
  LExp: TGorillaUSDZExporter;
begin
  LExp := TGorillaUSDZExporter.Create();
  try
    LExp.InnerFormat := TUSDZInnerFormat.Usda;  // default; Usdc for a binary stage
    LExp.USDAEntryName := 'model.usda';         // stage name inside the archive
    LExp.SaveToFile(FModel.Def as TModelDef, 'character.usdz');
  finally
    LExp.Free();
  end;
end;

TGorillaUSDZExporter descends from TGorillaUSDAExporter, so UpAxis, DefaultPrimName, TimeCodesPerSecond and MultiAnimMode apply here as well. Unlike the .usda exporter it does not dump the textures next to the file — they are packed into the archive.

Picking an Exporter by Extension

Every exporter registers itself for its extension, so a generic save dialog does not need to know the classes:

uses System.IOUtils, Gorilla.Exporter;

var
  LExp: TGorillaExporter;
begin
  LExp := TGorillaExporter.GetExporter(
    LowerCase(TPath.GetExtension(SaveDialog1.FileName)));  // '.glb', '.usdz', ...

  if Assigned(LExp) then
    LExp.SaveToFile(FModel.Def as TModelDef, SaveDialog1.FileName)
  else
    ShowMessage('No exporter registered for this file type.');
end;

GetExporter returns nil for an unregistered extension. The returned instance is owned by the registry — use it, but do not free it. TGorillaExporter.FileTypes holds all registered exporters and can be used to build the filter of the save dialog.

OBJ Export

uses
  Gorilla.OBJ.Exporter;

procedure TForm1.MenuItem1Click(Sender: TObject);
var LOBJExp : TGorillaOBJExporter;
begin    
  if Assigned(FModel) then
  begin
    if SaveDialog1.Execute() then
    begin
        LOBJExp := TGorillaOBJExporter.Create();
        try
          LOBJExp.SaveToFile(FModel.Def as TModelDef, SaveDialog1.FileName);
        finally
          FreeAndNil(LOBJExp);
        end;

        ShowMessage('File successfully stored:'#13#10+
          SaveDialog1.FileName);
      end;
  end;
end;

STL Export

uses
  Gorilla.STL.Exporter;

procedure TForm1.MenuItem1Click(Sender: TObject);
var LSTLExp : TGorillaSTLExporter;
    LToBinary : Boolean;
    LAllowMultipleMeshes : Boolean;
    LUseMultipleFiles : Boolean;
begin
  // ascii and binary format supported
  LToBinary := true;  

  // because STL supports only single meshes per file (per default), 
  // we can split up a model with multiple meshes into multiple files
  LAllowMultipleMeshes := true;
  // but this exporter also allows to export multiple meshes to a single file
  // just set UseMultipleFiles to false
  LUseMultipleFiles := true;

  if Assigned(FModel) then
  begin
    if SaveDialog1.Execute() then
    begin
        LSTLExp := TGorillaSTLExporter.Create();
        try
          LSTLExp.Binary := LToBinary;
          LSTLExp.AllowMultipleMeshes := LAllowMultipleMeshes;
          LSTLExp.UseMultipleFiles := LUseMultipleFiles;
          LSTLExp.SaveToFile(FModel.Def as TModelDef, SaveDialog1.FileName);
        finally
          FreeAndNil(LSTLExp);
        end;

        ShowMessage('File successfully stored:'#13#10+
          SaveDialog1.FileName);
      end;
  end;
end;

Bounding Box

Get model dimensions and bounds:

var
  BBox: TBoundingBox;
begin
  BBox := GorillaModel1.GetBoundingBox();

  ShowMessage(Format(
    'Width: %.2f, Height: %.2f, Depth: %.2f',
    [BBox.Width, BBox.Height, BBox.Depth]
  ));
end;

GetBoundingBox() is computed from the static (bind pose) vertex data. For the bounds of the currently animated pose use GetAnimatedBoundingBox(). It returns the box in local model space, so transform it with AbsoluteMatrix to get world coordinates:

var
  LLocal, LWorld: TBoundingBox;
begin
  LLocal := GorillaModel1.GetAnimatedBoundingBox();
  LWorld := LLocal.Transform(GorillaModel1.AbsoluteMatrix);
end;

For every sub-mesh the box is taken from the first available source:

  1. the box stored with the current cached animation frame,
  2. the live, CPU-animated vertex buffer (animation without caching),
  3. the static vertex data of the mesh definition.

Note: Frames of an animation cache that was stored and loaded again do not carry a box. For those the static box is used.

Ray Casting and Triangle Picking

Gorilla3D provides comprehensive ray casting and triangle picking functionality for detecting intersections with 3D models. This is essential for mouse interaction, collision detection, and object selection.

Using RayCastIntersect

For basic ray-triangle intersection tests using absolute world-space coordinates:

var
  RayPos, RayDir: TPoint3D;
  Intersection, Normal: TPoint3D;
begin
  // Absolute world-space ray
  RayPos := Point3D(0, 10, 0);
  RayDir := Point3D(0, -1, 0);  // Downward

  if GorillaModel1.RayCastIntersect(RayPos, RayDir, Intersection, Normal) then
  begin
    ShowMessage('Hit at: ' + Intersection.ToString);
    ShowMessage('Surface normal: ' + Normal.ToString);
  end;
end;

Using PickTriangle with Screen Coordinates

For mouse interaction, use screen coordinates directly:

procedure TForm1.Viewport1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Single);
var
  Intersection, Normal: TPoint3D;
  A, B, C: TPoint3D;
begin
  // Pick triangle at mouse position
  if GorillaModel1.PickTriangle(X, Y, Intersection, Normal, A, B, C) then
  begin
    ShowMessage('Clicked at: ' + Intersection.ToString);

    // Visualize hit point
    HitMarker.Position.Point := Intersection;
    HitMarker.Visible := True;
  end;
end;

Using PickTriangle with Result Structure

For comprehensive intersection data including distance and object reference:

procedure TForm1.Viewport1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Single);
var
  Result: TTriangleRayCastResult;
begin
  if GorillaModel1.PickTriangle(X, Y, Result) then
  begin
    ShowMessage(Format('Hit at distance: %.2f units', [Result.T]));
    ShowMessage('Intersection: ' + Result.Intersection.ToString);
    ShowMessage('Normal: ' + Result.Normal.ToString);

    // Access triangle corners
    ShowMessage(Format('Triangle: [%s, %s, %s]',
      [Result.Triangle[0].ToString,
       Result.Triangle[1].ToString,
       Result.Triangle[2].ToString]));

    // Check which mesh was hit
    if Assigned(Result.Instance) and (Result.Instance is TGorillaMesh) then
      ShowMessage('Hit mesh: ' + TGorillaMesh(Result.Instance).Name);
  end;
end;

Using PickTriangle with Absolute Ray

For custom ray tests (e.g., ground detection):

var
  Result: TTriangleRayCastResult;
  RayPos, RayDir: TVector3D;
begin
  // Cast ray from character position downward to find ground
  RayPos := Vector3D(Character.Position.X, Character.Position.Y + 1, Character.Position.Z);
  RayDir := Vector3D(0, -1, 0);

  if GorillaModel1.PickTriangle(RayPos, RayDir, Result) then
  begin
    // Place character on ground
    var GroundHeight := Result.Intersection.Y;
    Character.Position.Y := GroundHeight;

    ShowMessage(Format('Ground found at height: %.2f', [GroundHeight]));
  end;
end;

Key Differences

Method Input Use Case
RayCastIntersect Absolute ray (world space) Basic intersection tests with custom rays
PickTriangle (X, Y) Screen coordinates Mouse interaction, object picking
PickTriangle (Ray) Absolute ray (world space) Ground detection, collision checks, AI vision
PickTriangle (Result) Screen or absolute ray When you need detailed intersection data

Important: All methods perform deep search through the entire model hierarchy, testing all submeshes recursively.

Performance Optimization

Static Meshes

Mark meshes as static for better performance when geometry doesn't change:

// Set at load time via TGorillaLoadOptions
Options.VertexDataFlags := [];  // Static mesh

// Or modify after loading
for var i := 0 to GorillaModel1.Meshes.Count - 1 do
  GorillaModel1.Meshes[i].IsStatic := True;

Hit-Testing

Firemonkey provides the HitTest property for all TControl3D objects. This property allows mouse interaction with the specific 3D model. Because this performs ray casting under the hood, it is recommended to disable this feature for elements that do not need mouse interaction (click, mouse-down, mouse-up, mouse-move). When working with large 3D models and many triangles/vertices it is also recommended to deactivate it.

Because the HitTest property can not be overwritten, Gorilla3D provides a traversing method to deactivate complete mesh and model structures with all their sub-meshes.

GorillaModel1.SetHitTestValue(false);

When you set the property value directly, only the specific control will be deactivated. This is useful if you only want selected meshes to be responsive.

GorillaModel1.Meshes[0].HitTest := false;

Texture Size Limiting

Reduce texture memory usage:

var
  Options: TGorillaLoadOptions;
begin
  Options := TGorillaLoadOptions.Create('model.dae', [], nil, nil);
  Options.MaxTextureWidth := 1024;
  Options.MaxTextureHeight := 1024;

  GorillaModel1.LoadFromFile(Options);
end;

Frustum Culling

Enable per-mesh frustum culling:

for var i := 0 to GorillaModel1.Meshes.Count - 1 do
  GorillaModel1.Meshes[i].FrustumCullingCheck := True;

Sketchfab Integration

Download models directly from Sketchfab at runtime:

Note: Requires OAuth credentials from Sketchfab developer portal. Currently disabled for security reasons but can be enabled.

var
  Options: TGorillaLoadOptions;
begin
  Options.FileInfo.OpenFormat := TGorillaFileOpenFormat.fofDownload;
  Options.FileInfo.PathOrUID := 'model-uid';
  Options.FileInfo.URL := 'https://sketchfab.com/api/...';
  Options.FileInfo.OAuthMode := TGorillaOAuthMode.AuthCode;
  Options.FileInfo.ClientId := 'your-client-id';
  Options.FileInfo.ClientSecret := 'your-client-secret';

  GorillaModel1.LoadFromFile(Options);
end;

Important Considerations

Memory Management

  • IDE Limit: 3GB maximum; large embedded models slow performance
  • Recommendation: Use asset packages for development
  • Binary Storage: Models are stored as compressed G3D format in .fmx files

Skinned models with several parts (glTF): Earlier versions stored a skin that drives several meshes incompletely in the .fmx binary data. A glTF mesh with several primitives is such a case, and so is a skin shared by several mesh nodes (e.g. BrainStem). The model looked correct in the designer, but at runtime only one part animated (e.g. only the hair of a character). The binary data now keeps the joint weights of every mesh. Models embedded with an older version have to be loaded again at design time (assign Source once more and save the form). The old binary data cannot be repaired because it does not contain the weights of the other parts.

Asset Packages vs. Embedded

Aspect Embedded Asset Package
IDE Performance Slower with large models Fast
Deployment Single executable Requires external files
Development Slow on changes Fast iteration
Memory Always loaded Loaded on demand

File Format Selection

  • G3D: Best for Gorilla3D, supports all features
  • DAE: Excellent for animations, lights, cameras
  • FBX: Good animation support but binary only
  • glTF/GLB: Modern format, good web asset pipeline integration; import and export
  • USD: Scene interchange with DCC tools and AR — .usda while debugging (readable, diffable), .usdc for size and parse speed, .usdz to ship one file including textures
  • OBJ: Simple static models, widely supported
  • STL: CAD/3D printing, no materials or animations

Best Practices

  1. Use asset packages during development for better IDE performance
  2. Cache animations with VertexPosition flag for balanced performance/memory
  3. Limit texture sizes for mobile platforms
  4. Use GPU instancing for rendering many identical objects
  5. Enable frustum culling for large scenes
  6. Prefer G3D format for final deployment
  7. Test on target platform before deploying
  8. Use LoadFromStream for loading from resources or compressed archives

See Also