Creating Custom Meshes
Gorilla3D provides multiple approaches for creating custom 3D geometry at runtime, from simple polygon-based construction to advanced vertex cache techniques. But besides adding vertex data, further steps are needed like arranging meshes in hierarchy, materials and animations.
Mesh Geometry
At first we have to add mesh geometry / vertex data to finally render anything. There are three main approaches to creating custom meshes:
| Approach | Complexity | Use Case |
|---|---|---|
| Simple Polygon Method | Low | Basic shapes, quick prototyping |
| Direct TMeshData Manipulation | Medium | The old-school method by the TMeshData type of Firemonkey. Effective but not flexible. |
| TVertexCache | Medium-High | Complex geometry, custom normals/UVs, skeletal animation |
Simple Polygon Method
The straightforward approach involves creating a custom mesh class and defining geometry using polygon vertices.
Basic Example: Triangle Mesh
uses
Gorilla.Mesh, Gorilla.DefTypes;
TUserMesh = class(TGorillaSingletonMesh)
public
constructor Create(AOwner : TComponent); override;
procedure Build();
end;
[...]
constructor TUserMesh.Create(AOwner: TComponent);
begin
inherited;
FDef := TMeshDef.Create(nil);
end;
procedure TUserMesh.Build();
begin
with TMeshDef(FDef) do
begin
AddPolygon([PointF(-0.5, -0.5), PointF(0.5, -0.5), PointF(0.5, 0.5), PointF(-0.5, 0.5)]);
AddPolygon([PointF(-0.5, -1.5), PointF(0.5, -1.5), PointF(0.5, -0.75), PointF(-0.5, -0.75)]);
AddPolygon([PointF(-1.5, -1.5), PointF(-0.75, -1.5), PointF(-0.75, -0.75), PointF(-1.5, -0.75)]);
// after all polygon vertices were added
// compute tex-coords, normals, tangents and binormals
CalcTextureCoordinates(TTextureMappingMethod.tmTriplanar);
CalcFaceNormals();
CalcTangentBinormals();
// after vertex data was finally setup - set mesh to static and push data
// to GPU
IsStatic := true;
end;
end;
[...]
// Create a visual instance at runtime
FUserMesh := TUserMesh.Create(GorillaViewport1);
FUserMesh.Parent := GorillaViewport1;
FUserMesh.Position.Point := Point3D(3, -1, 3);
FUserMesh.RotationAngle.X := -45;
// Build the vertex data
FUserMesh.Build();
// Apply an existing material
FUserMesh.MaterialSource := GorillaLambertMaterialSource1;
Creating a Cube
procedure TMyCustomMesh.BuildCubeMesh();
var
LDef: TMeshDef;
Vertices: TPoint3DDynArray;
begin
Self.Clear();
LDef := TMeshDef(FDef);
// Front face
SetLength(Vertices, 4);
Vertices[0] := Point3D(-1, 1, 1);
Vertices[1] := Point3D(1, 1, 1);
Vertices[2] := Point3D(1, -1, 1);
Vertices[3] := Point3D(-1, -1, 1);
LDef.AddPolygon(Vertices);
// Back face
Vertices[0] := Point3D(1, 1, -1);
Vertices[1] := Point3D(-1, 1, -1);
Vertices[2] := Point3D(-1, -1, -1);
Vertices[3] := Point3D(1, -1, -1);
LDef.AddPolygon(Vertices);
// Top face
Vertices[0] := Point3D(-1, 1, -1);
Vertices[1] := Point3D(1, 1, -1);
Vertices[2] := Point3D(1, 1, 1);
Vertices[3] := Point3D(-1, 1, 1);
LDef.AddPolygon(Vertices);
// Bottom face
Vertices[0] := Point3D(-1, -1, 1);
Vertices[1] := Point3D(1, -1, 1);
Vertices[2] := Point3D(1, -1, -1);
Vertices[3] := Point3D(-1, -1, -1);
LDef.AddPolygon(Vertices);
// Right face
Vertices[0] := Point3D(1, 1, 1);
Vertices[1] := Point3D(1, 1, -1);
Vertices[2] := Point3D(1, -1, -1);
Vertices[3] := Point3D(1, -1, 1);
LDef.AddPolygon(Vertices);
// Left face
Vertices[0] := Point3D(-1, 1, -1);
Vertices[1] := Point3D(-1, 1, 1);
Vertices[2] := Point3D(-1, -1, 1);
Vertices[3] := Point3D(-1, -1, -1);
LDef.AddPolygon(Vertices);
// Generate all necessary vertex attributes
LDef.CalcTextureCoordinates();
LDef.CalcFaceNormals();
LDef.CalcTangentBinormals();
LDef.IsStatic := True;
end;
Helper Methods
After defining geometry with AddPolygon(), use these helper methods:
CalcTextureCoordinates()
Automatically generates UV mapping based on vertex positions:
LDef.CalcTextureCoordinates(<TTextureMappingMethod>);
The TTextureMappingMethod type offers different computation algorithms.
| Algorithm | Description |
|---|---|
| TTextureMappingMethod.tmSpherical | |
| TTextureMappingMethod.tmCylindrical | |
| TTextureMappingMethod.tmCubic | |
| TTextureMappingMethod.tmTriplanar |
CalcFaceNormals()
Computes surface normals for lighting:
LDef.CalcFaceNormals();
CalcTangentBinormals()
Calculates tangent and binormal vectors required for normal mapping:
LDef.CalcTangentBinormals();
Making Mesh Static
Transfer mesh data to GPU memory for rendering:
LDef.IsStatic := True;
Important: Set
IsStatic := Trueonly after all geometry is finalized. Once static, vertex data cannot be modified.
Direct TMeshData Manipulation
Firemonkey already offers to generate mesh geometry manually. This is done by TMeshData type.
This class holds a single vertex and index buffer to setting up vertex data.
uses
Gorilla.Mesh, Gorilla.DefTypes, Gorilla.Material.VertexColor;
procedure TForm1.FormCreate(Sender: TObject);
begin
// Create a visual Firemonkey instance
var LMesh := TGorillaSingletonMesh.Create(GorillaViewport1);
LMesh.Parent := GorillaViewport1;
// Request the embedded mesh data instance
var LData := LMesh.MeshData;
if not Assigned(LData) then
raise Exception.Create('custom mesh does not provide TMeshData instance');
// Start generating geometry
try
// Initialize the vertex buffer
LData.VertexBuffer.Length := 4;
LData.VertexBuffer.Vertices[0] := Point3D(-0.5, -0.5, 0.0);
LData.VertexBuffer.Normals[0] := Point3D(0, 0, -1);
LData.VertexBuffer.Color0[0] := TAlphaColors.Red;
LData.VertexBuffer.Vertices[1] := Point3D(+0.5, -0.5, 0.0);
LData.VertexBuffer.Normals[1] := Point3D(0, 0, -1);
LData.VertexBuffer.Color0[1] := TAlphaColors.Green;
LData.VertexBuffer.Vertices[2] := Point3D(+0.5, +0.5, 0.0);
LData.VertexBuffer.Normals[2] := Point3D(0, 0, -1);
LData.VertexBuffer.Color0[2] := TAlphaColors.Blue;
LData.VertexBuffer.Vertices[3] := Point3D(-0.5, +0.5, 0.0);
LData.VertexBuffer.Normals[3] := Point3D(0, 0, -1);
LData.VertexBuffer.Color0[3] := TAlphaColors.Yellow;
// Initialize the index buffer to generate triangles
LData.IndexBuffer.Length := 6;
// 2 triangles to form a quad
// Counter-Clock-Wise Vertex Order (CCW)
LData.IndexBuffer.Indices[0] := 1;
LData.IndexBuffer.Indices[1] := 2;
LData.IndexBuffer.Indices[2] := 3;
LData.IndexBuffer.Indices[3] := 0;
LData.IndexBuffer.Indices[4] := 1;
LData.IndexBuffer.Indices[5] := 3;
// Apply this mesh data to a mesh definition in the background
// to enable static buffering
var LMeshDef := TMeshDef.Create(nil);
// Link it to the Firemonkey instance
LMesh.Def := LMeshDef;
// Push data to the definition and onto the GPU
LMeshDef.ApplyFromMeshData(LData);
LMeshDef.IsStatic := true;
// We have a static buffer, so we do not need that data anymore
LData.Clear;
// Create a vertex color material to see our mesh
var LMaterial := TGorillaVertexColorMaterialSource.Create(LMesh);
LMaterial.Parent := LMesh;
LMesh.MaterialSource := LMaterial;
except
// ... do anything ...
end;
end;
Advanced Technique: TVertexCache
For complex meshes requiring custom normals, multiple texture coordinates, vertex colors, or skeletal animation, use TVertexCache.
TVertexCache Architecture
TVertexCache maintains separate buffers for different vertex attributes:
| Buffer | Type | Purpose |
|---|---|---|
| PositionSource | TList<TPoint3D> | Vertex coordinates |
| NormalSource | TList<TPoint3D> | Surface normals |
| TangentSource | TList<TPoint3D> | Tangent vectors |
| BinormalSource | TList<TPoint3D> | Binormal vectors |
| TextureSource[0..31] | TList<TPointF> | UV coordinates (32 channels) |
| ColorSource[0..3] | TList<TAlphaColor> | Vertex colors (4 channels) |
| Vertices | TList<TVertexData> | Combined vertex structures |
| Indices | TList<UInt32> | Triangle indices |
Workflow
- Create TVertexCache instance
- Populate source buffers (positions, normals, UVs, colors)
- Define triangles/polygons using vertex indices
- Create mesh definition from cache
- Load into TGorillaModel
Basic Example: Custom Mesh with TVertexCache
uses
System.Generics.Collections, System.Generics.Defaults,
Gorilla.DefTypes, Gorilla.Loader;
type
TUserModelBuilder = class
protected
class function DoBuildMesh(AOwner : TMeshDef) : TMeshDef;
public
class function Build() : TModelDef;
class function AddMaterial(AModel : TModelDef; AMesh : TMeshDef;
AId : String; AFileName : String) : TMaterialDef;
class function AddArmatureAndController(AModel : TModelDef;
AMesh : TMeshDef) : TArmatureDef;
class function AddSkinAnimation(AModel : TModelDef;
AArmature : TArmatureDef; AId : String) : TAnimationDef;
end;
[...]
class function TUserModelBuilder.Build() : TModelDef;
var LMesh : TMeshDef;
LArma : TArmatureDef;
begin
// Create the model container
Result := TModelDef.Create(nil, nil);
Result.Id := 'CustomModel1';
// Create and add all meshes to it
LMesh := DoBuildMesh(Result);
// We generate texture coordinates, tangents and binormals automatically
LMesh.CalcTextureCoordinates();
LMesh.CalcTangentBinormals();
// Add a material with texture
AddMaterial(Result, LMesh, 'CustomMaterial1', 'brick-c.jpg');
// Add an armature and skin controller
LArma := AddArmatureAndController(Result, LMesh);
// Add skin animation
AddSkinAnimation(Result, LArma, 'Animation1');
end;
class function TUserModelBuilder.DoBuildMesh(AOwner : TMeshDef) : TMeshDef;
function GetVertexID(const APos, ANormal, ATangent, AColor : Integer) : TVertexID;
begin
FillChar(Result, SizeOf(Result), 0);
Result.Position := APos;
Result.Normal := ANormal;
Result.Tangent := ATangent;
Result.Colors.Count := 1;
Result.Colors.Indices[0] := AColor;
end;
var LCache : TVertexCache;
LVertIdxOfs: Integer;
// In our example we have 3 polygons/quads
LPolys : Array[0..2] of TPolygonID;
I : Integer;
begin
// Create the mesh object and add it to the supplied owner
Result := TMeshDef.Create(AOwner);
Result.Id := 'CustomMesh1';
Result.FaceOrientation := TFaceOrientation.TwoFace;
AOwner.AddMesh(Result);
// Setup a vertex cache
LCache := TVertexCache.Create();
try
LCache.UseBuffersAsArray := true;
// Start pushing vertex data into
LCache.SetPositionSource([
// quad #1 (vertex#0, vertex#1, vertex#2, vertex#3)
-0.5, -0.5, 0, 0.5, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0,
// quad #2 (vertex#4, vertex#5, vertex#6, vertex#7)
-0.5, -1.5, 0, 0.5, -1.5, 0, 0.5, -0.75, 0, -0.5, -0.75, 0,
// quad #3 (vertex#8, vertex#9, vertex#10, vertex#11)
-1.5, -1.5, 0, -0.75, -1.5, 0, -0.75, -0.75, 0, -1.5, -0.75, 0
]);
// All vertices should have the same normal and tangent vector
LCache.SetNormalSource([0, 0, -1]);
LCache.SetNormalSource([1, 0, 0]);
// Each triangle should have its own color
LCache.SetColorSource(0, [1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1]);
// You can work with offsets on the cache - very useful for meshes using the same vertex data
LVertIdxOfs := 0;
// Prepare vertex data indices (from buffers) to add quads
// At first let's clear the triangle vertex data index structures
System.SetLength(LPolys[0], 4);
System.SetLength(LPolys[1], 4);
System.SetLength(LPolys[2], 4);
// Polygon/Quad #1 - Vertex #0, #1, #2, #3 (with its own color)
LPolys[0][0] := GetVertexID(0, 0, 0, 0);
LPolys[0][1] := GetVertexID(1, 0, 0, 0);
LPolys[0][2] := GetVertexID(2, 0, 0, 0);
LPolys[0][3] := GetVertexID(3, 0, 0, 0);
// Polygon/Quad #2 - Vertex #4, #5, #6, #7 (with its own color)
LPolys[1][0] := GetVertexID(4, 0, 0, 1);
LPolys[1][1] := GetVertexID(5, 0, 0, 1);
LPolys[1][2] := GetVertexID(6, 0, 0, 1);
LPolys[1][3] := GetVertexID(7, 0, 0, 1);
// Polygon/Quad #3 - Vertex #8, #9, #10, #11 (with its own color)
LPolys[2][0] := GetVertexID(8, 0, 0, 2);
LPolys[2][1] := GetVertexID(9, 0, 0, 2);
LPolys[2][2] := GetVertexID(10, 0, 0, 2);
LPolys[2][3] := GetVertexID(11, 0, 0, 2);
// Add the polygons one by one - with automatic triangulation
for I := Low(LPolys) to High(LPolys) do
LVertIdxOfs := LCache.AddPolygon(LVertIdxOfs, LPolys[I], LCache.Vertices, LCache.Indices);
// Load the TMeshDef (Result) from the cache
TGorillaLoader.LoadDefFromData(Result, LCache);
// When vertex data is added from cache, the vertex index map may be also produced automatically
// We should add it to the mesh for correct vertex mapping during animations
Result.AddVertexIndexMap(LCache.IndexMap);
finally
FreeAndNil(LCache);
end;
end;
Adding Data to TVertexCache
Individual Append Methods
Add single vertices or attributes:
| Method | Argument | Description |
|---|---|---|
| AddPositionSource | TSingleDynArray | Add a single vertex position by an array of 3 floating point values representing x, y and z |
| AddPositionSource | TPoint3D | Add a single 3D vertex position |
| AddNormalSource | TSingleDynArray | Add a single normal vector by an array of 3 floating point values representing x, y and z |
| AddNormalSource | TPoint3D | Add a single 3D normal vector |
| AddBinormalSource | TSingleDynArray | Add a single binormal vector by an array of 3 floating point values representing x, y and z |
| AddBinormalSource | TPoint3D | Add a single 3D binormal vector |
| AddTangentSource | TSingleDynArray | Add a single tangent vector by an array of 3 floating point values representing x, y and z |
| AddTangentSource | TArray |
Add multiple tangent vectors by an array of tangent vectors |
| AddTangentSource | TPoint3D | Add a single 3D tangent vector |
| AddTextureSource | AIndex, TSingleDynArray, AConvertToUV | Add a single texture coordinate by an array of 2 floating point values representing x, y. AConvertToUV will convert between st and uv coordinates. |
| AddTextureSource | AIndex, TPointF, AConvertToUV | Add a single 2D texture coordinate. AConvertToUV will convert between st and uv coordinates. |
| AddColorSource | AIndex, TSingleDynArray | Add single vertex color by an array of 4 floating point values representing r,g,b,a |
| AddColorSource | AIndex, TAlphaColorF | Add a single color value |
// Add positions one by one
var PosIdx0 := Cache.AddPositionSource(Point3D(0, 0, 0));
var PosIdx1 := Cache.AddPositionSource(Point3D(1, 0, 0));
var PosIdx2 := Cache.AddPositionSource(Point3D(0, 1, 0));
// Add normals
var NormIdx0 := Cache.AddNormalSource(Point3D(0, 0, 1));
var NormIdx1 := Cache.AddNormalSource(Point3D(0, 0, 1));
// Add texture coordinates (channel 0)
var TexIdx0 := Cache.AddTextureSource(0, PointF(0, 0));
var TexIdx1 := Cache.AddTextureSource(0, PointF(1, 0));
var TexIdx2 := Cache.AddTextureSource(0, PointF(0, 1));
// Add vertex colors (channel 0)
var ColorIdx0 := Cache.AddColorSource(0, TAlphaColors.Red);
var ColorIdx1 := Cache.AddColorSource(0, TAlphaColors.Green);
var ColorIdx2 := Cache.AddColorSource(0, TAlphaColors.Blue);
Batch Set Methods
Warning: Pushing multiple vertex data will always clear the specific buffer and will not append the data.
| Method | Argument | Description |
|---|---|---|
| SetPositionSource | TSingleDynArray | Adds an array of multiple vertex positions flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] |
| SetNormalSource | TSingleDynArray | Adds an array of multiple normal vectors flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] |
| SetNormalSource | TSingleDynArray, ATransform | Adds an array of multiple normal vectors flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] and transforms the normal vectors by the supplied transformation matrix. |
| SetBiNormalSource | TSingleDynArray | Adds an array of multiple binormal vectors flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] |
| SetTangentSource | TSingleDynArray | Adds an array of multiple tangent vectors flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] |
| SetTextureSource | AIndex, TSingleDynArray, AConvertToUV | Adds an array of multiple texture coordinates flattened into a straight array of floating point values, like [X1,Y1, X2,Y2, X3,Y3, …] at a certain position (starting with zero). AConvertToUV allows to convert those values between st and uv format. |
| SetColorSource | AIndex, TSingleDynArray | Adds an array of multiple color values flattened into a straight array of floating point values, like [R1,G1,B1,A1, R2,G2,B2,A2, R3,G3,B3,A3, …] at a certain position (starting with zero) |
Replace entire buffers with flattened arrays:
var
Positions: TSingleDynArray;
begin
// Flattened format: [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, ...]
SetLength(Positions, 9); // 3 vertices * 3 components
// Vertex 0
Positions[0] := 0.0;
Positions[1] := 1.0;
Positions[2] := 0.0;
// Vertex 1
Positions[3] := -1.0;
Positions[4] := -1.0;
Positions[5] := 0.0;
// Vertex 2
Positions[6] := 1.0;
Positions[7] := -1.0;
Positions[8] := 0.0;
Cache.SetPositionSource(Positions);
end;
Similarly for normals:
var
Normals: TSingleDynArray;
begin
SetLength(Normals, 9); // 3 normals * 3 components
// All pointing forward
Normals[0] := 0.0; Normals[1] := 0.0; Normals[2] := 1.0;
Normals[3] := 0.0; Normals[4] := 0.0; Normals[5] := 1.0;
Normals[6] := 0.0; Normals[7] := 0.0; Normals[8] := 1.0;
Cache.SetNormalSource(Normals);
end;
Multiple Texture Coordinates
Gorilla3D supports up to 32 texture coordinate channels:
// Primary UV set (channel 0)
Cache.AddTextureSource(0, PointF(0, 0));
Cache.AddTextureSource(0, PointF(1, 0));
// Lightmap UV set (channel 1)
Cache.AddTextureSource(1, PointF(0, 0));
Cache.AddTextureSource(1, PointF(0.5, 0.5));
// Use in vertex definition
Triangle[0].TexCoord0 := 0; // Channel 0 index
Triangle[0].TexCoord1 := 0; // Channel 1 index
Vertex Colors
Support for up to 4 color channels:
// Add vertex colors
Cache.AddColorSource(0, TAlphaColors.Red);
Cache.AddColorSource(0, TAlphaColors.Green);
Cache.AddColorSource(0, TAlphaColors.Blue);
// Use in vertex definition
Triangle[0].Color0 := 0; // Red
Triangle[1].Color0 := 1; // Green
Triangle[2].Color0 := 2; // Blue
Generate Triangles / Polygons
Once we have filled the cache buffer with our vertex data for positions, normals and so on. We need to tell it, which kind of primitive it uses. Vertices could form triangles or polygons.
We could set up our index buffers manually, but often it is more useful to call AddTriangle or AddPolygon to fill indices.
| Method | Description |
|---|---|
| function AddTriangle(const AIndexOffset : Integer; const ATriangle : TTriangleID; const AVertices : TList |
Adds triangle vertices and indices to AVertices and AIndices based on the index values inside of TTriangleID VertexData values are taken from Cache.PositionSource and so on… |
| function AddPolygon(const AIndexOffset : Integer; const APolygon : TPolygonID; const AVertices : TList |
Adds polygon vertices and indices to AVertices and AIndices based on the index values inside of TPolygonID VertexData values are taken from Cache.PositionSource and so on… CAUTION: this method triangulates the polygon automatically |
Hierarchy and Transforms
All mesh definitions inherit from TTransformDef, enabling parent-child relationships.
- TTransformDef
- TSegmentDef: placeholder definition in mesh hierarchy to allow meshes to be attached to joints or armatures
- TArmatureDef: armature/humanoid hierarchy to define a skeleton for animations
- TJointDef: bone/joint that belongs to an armature and defines a part of a skeleton
- TSkinDef: structure to define vertex modification based on a controller
- TCustomMeshDef
- TMeshDef
- TVertexGroupDef
- TModelDef
- TLightDef
- TCameraDef
Each TTransformDef object has an “Owner” and “Children” property to setup a hierarchy.
Add or remove objects to / from a parent object by the methods:
function AddChild(ATransform : TTransformDef) : Integer;
procedure RemoveChild(ATransform : TTransformDef);
procedure ClearChildren();
procedure AddMesh(const AMesh : TMeshDef);
In the following example we setup a model with sub-meshes and a deep hierarchy. You can search on that structure by FindChildById or you can Traverse to do certain things on each of the child instances.
var
ModelDef: TModelDef;
ParentMesh, ChildMesh: TMeshDef;
begin
ModelDef := TModelDef.Create(nil);
ParentMesh := TMeshDef.Create(ModelDef);
ParentMesh.Id := 'Parent';
ModelDef.AddChild(ParentMesh);
ChildMesh := TMeshDef.Create(ModelDef);
ChildMesh.Id := 'Child';
ParentMesh.AddChild(ChildMesh);
// Find child by ID
var Found := ParentMesh.FindChildById('Child', True);
// Traverse hierarchy
ModelDef.Traverse(
true,
function(AOwner : TTransformDef; const AIndex : Integer; ATransf : TTransformDef) : Boolean
begin
// do something
Result := true;
end
);
end;
Vertex Groups
VertexGroups, represented by an TVertexGroupDef instance are helper structures referring to an owner mesh, which holds original vertex data and complete indices list, while this structure only holds a separated index source for partially rendering a mesh.
They are used for example in the FBX format for rendering some triangles with a different material than others.
var
MeshDef: TMeshDef;
Group1, Group2: TVertexGroupDef;
begin
MeshDef := TMeshDef.Create(ModelDef);
// Create vertex groups
Group1 := TVertexGroupDef.Create(MeshDef);
Group1.Id := 'Group1';
MeshDef.AddMesh(Group1);
Group1.IndexSource.AppendIndices([0,1,2]);
// Link a material to render this group differently
Group1.SetMaterialReference(MaterialA);
Group2 := TVertexGroupDef.Create(MeshDef);
Group2.Id := 'Group2';
MeshDef.AddMesh(Group2);
Group2.IndexSource.AppendIndices([0,1,2]);
// Link a material to render this group differently
Group2.SetMaterialReference(MaterialB);
Warning: Vertex groups are currently incompatible with skeletal/vertex animations.
Materials
To expand the dynamic model setup, let's add a material to our sub-mesh.
uses
Gorilla.AssetsManager;
class function TUserModelBuilder.AddMaterial(AModel : TModelDef; AMesh : TMeshDef; AId : String; AFileName : String) : TMaterialDef;
var LTexDef : TTextureDef;
LAsset : TGorillaTextureAsset;
begin
// Materials are attached to the model to reuse them in multiple meshes
Result := TMaterialDef.Create(AModel, AId);
Result.Kind := TMaterialDefKind.mkLambert;
// Create a texture for the material
// 1) Create a standalone asset (possible to request one from an assets package too)
LAsset := TGorillaTextureAsset.Create(nil);
LAsset.ImportFromFile(AFileName);
// 2) Add a diffuse texture in the material
LTexDef := Result.AddTexture(TColorChannelDef.Diffuse, LAsset, true);
// Finally we need to link it to our mesh
AMesh.SetMaterialReference(Result);
end;
Animations
Adding animations can become a very challenging part due to complexity.
Not only an animation definition needs to be defined, but also stages, interpolators + armatures and joints for skeleton/skin animations need to be added and configured.
class function TUserModelBuilder.AddAnimation(AModel : TModelDef; AMesh : TMeshDef; AId : String) : TAnimationDef;
var LStage : TAnimationStageDef;
LInterp : TPoint3DInterpolatorDef;
begin
// Let's start with the animation main object
Result := TAnimationDef.Create(AModel);
Result.Id := 'CustomAnimation1';
AModel.AddAnimation(Result);
// Each animation should contain at least one stage definition
LStage := TAnimationStageDef.Create(Result);
LStage.Id := 'CustomMesh1Stage';
LStage.Reference := AMesh;
Result.AddStage(LStage);
// In our example we simply want to move the mesh
// So we need to create a Point3D interpolator in the stage
LInterp := TPoint3DInterpolatorDef.Create(LStage);
LInterp.Id := 'CustomMesh1PositionInterpolator';
LStage.AddInterpolator(LInterp);
// Configure the animation
LInterp.Path := 'Position.Point';
LInterp.Loop := true;
LInterp.Duration := 3.0; // 3 seconds
// To move the mesh, we need to add keys to the interpolator
LInterp.AddKey(0, Point3D(0, 0, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(0.75, Point3D(0, -0.75, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(1, Point3D(0, -1, 0), TAnimationKeyInterpolationType.Linear);
end;
You can add multiple interpolators per stage, but keep in mind it may slow down performance.
We do support different interpolator types, depending on your needs:
| Interpolator | Description |
|---|---|
| TPoint3DInterpolatorDef | Translation or Scaling interpolator by TPoint3D value to transform a stage reference property. |
| TVector3DInterpolatorDef | Rotation interpolator by TVector3D value to transform a stage reference RotationAngle property. |
| TQuaternion3DInterpolatorDef | Rotation interpolator by TQuaternion3D value to transform a stage reference RotationAngle property. |
| TTransformationInterpolatorDef | Transformation interpolator by TMatrix3D values to transform the stage reference object by position, rotation and scaling. |
| TMeshInterpolatorDef | Vertex position interpolator for direct vertex manipulation of mesh reference. |
Armature & SkinController
To make skin- or skeleton-animations possible you will need an armature with a hierarchy of joints representing the internal skeleton of a body.
class function TUserModelBuilder.AddArmatureAndController(AModel : TModelDef; AMesh : TMeshDef) : TArmatureDef;
var LJt1,
LJt2 : TJointDef;
LCtrl : TControllerDef;
LJtRef : TJointRefDef;
LRes : Integer;
begin
//
// Create an armature definition and link it to the model
//
Result := TArmatureDef.Create(AModel);
Result.Id := 'Armature1';
AModel.AddArmature(Result);
// Afterwards you can add joints / bones for a hierarchy
// Starting with the root joint
Result.Root := TJointDef.Create(Result);
Result.Root.Id := 'SkeletonRoot';
// Then add the first child node with position offset
LJt1 := TJointDef.Create(Result);
LJt1.Id := 'Bone1';
LJt1.Transform := TMatrix3D.CreateTranslation(Point3D(0, -1, 0));
Result.Root.AddJoint(LJt1);
// And another child node with position offset
LJt2 := TJointDef.Create(Result);
LJt2.Id := 'Bone2';
LJt2.Transform := TMatrix3D.CreateTranslation(Point3D(-1, 0, 0));
LJt1.AddJoint(LJt2);
//
// After we have setup the armature with a bone hierarchy, we can create a skin-controller
//
LCtrl := TControllerDef.Create(AMesh);
LCtrl.Id := 'CustomMesh1Controller';
// Add the controller to the model controllers list
AModel.AddController(LCtrl);
// Link the controller also to the armature
Result.AddController(LCtrl);
// Add a skin to our controller - capable to manage deformation data depending on an armature hierarchy
LCtrl.Skin := TSkinDef.Create(LCtrl);
// Add the skeleton root reference joint (standalone reference)
LJtRef := TJointRefDef.Create(Result.Root, LCtrl, true);
LCtrl.Skin.Skeletons.Add(LJtRef);
// We have to link all relevant joint to the skin and add weights and vertex-indices
// "Weights" and "Indices" arrays has to have the same size.
// The sum of all weights (over all joints) for a specific vertex has to be 1.0!
LJtRef := LCtrl.Skin.LinkJoint(Result.Root);
LJtRef.Weights := [0.75, 0.75, 0.75, 0.75, 0.25, 0.25, 0.25, 0.25, 0, 0, 0, 0];
LJtRef.Indices := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
LJtRef := LCtrl.Skin.LinkJoint(LJt1);
LJtRef.Weights := [0.25, 0.25, 0.25, 0.25, 0.75, 0.75, 0.75, 0.75, 0.25, 0.25, 0.25, 0.25];
LJtRef.Indices := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
LJtRef := LCtrl.Skin.LinkJoint(LJt2);
LJtRef.Weights := [0, 0, 0, 0, 0.25, 0.25, 0.25, 0.25, 0.75, 0.75, 0.75, 0.75];
LJtRef.Indices := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
// Verify the setup
LRes := LCtrl.Skin.CheckMeshVerticesToBeAttachedCorrectly();
case LRes of
0 : ; // everything is okey
1 : raise Exception.Create('skin vertex not attached');
2 : raise Exception.Create('skin vertex not attached completely, meaning that total weight value is not equal to 1.0');
3 : raise Exception.Create('no mesh linked');
4 : raise Exception.Create('mesh vertex list is empty');
5 : raise Exception.Create('no skeleton root found');
6 : raise Exception.Create('no joints linked');
else raise Exception.Create('unexpected failure');
end;
end;
Verify mesh vertex weights
It's important that all vertices are attached correctly to a joint and the weight values are in sum 1.0.
LRes := LCtrl.Skin.CheckMeshVerticesToBeAttachedCorrectly();
case LRes of
0 : ; // everything is okey
1 : raise Exception.Create('skin vertex not attached');
2 : raise Exception.Create('skin vertex not attached completely, meaning that total weight value is not equal to 1.0');
3 : raise Exception.Create('no mesh linked');
4 : raise Exception.Create('mesh vertex list is empty');
5 : raise Exception.Create('no skeleton root found');
6 : raise Exception.Create('no joints linked');
else raise Exception.Create('unexpected failure');
end;
Add a Skin-Animation
To animate the armature it's necessary to have compatible animation stages and interpolators.
Related to our armature and bones (joints) before, the code could look something like this:
class function TUserModelBuilder.AddSkinAnimation(AModel : TModelDef;
AArmature : TArmatureDef; AId : String) : TAnimationDef;
var LStage : TAnimationStageDef;
LInterp : TPoint3DInterpolatorDef;
begin
// Let's start with the animation main object
Result := TAnimationDef.Create(AModel);
Result.Id := 'CustomAnimation1';
AModel.AddAnimation(Result);
// ROOT JOINT
// Each animation should contain at least one stage definition
LStage := TAnimationStageDef.Create(Result);
LStage.Id := 'RootBoneStage';
LStage.Reference := AArmature.Root;
Result.AddStage(LStage);
// In our example we simply want to move the mesh
// So we need to create a Point3D interpolator in the stage
LInterp := TPoint3DInterpolatorDef.Create(LStage);
LInterp.Id := 'RootBonePosition';
LStage.AddInterpolator(LInterp);
// Configure the animation
LInterp.Path := 'Position.Point';
LInterp.Loop := true;
LInterp.Duration := 3.0; // 3 seconds
// To move the mesh, we need to add keys to the interpolator
LInterp.AddKey(0, Point3D(0, 0, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(0.75, Point3D(0, -0.75, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(1, Point3D(0, -1, 0), TAnimationKeyInterpolationType.Linear);
// JOINT1
LStage := TAnimationStageDef.Create(Result);
LStage.Id := 'Bone1Stage';
LStage.Reference := AArmature.Root.FindJointById('Bone1');
Result.AddStage(LStage);
// In our example we simply want to move the mesh
// So we need to create a Point3D interpolator in the stage
LInterp := TPoint3DInterpolatorDef.Create(LStage);
LInterp.Id := 'Bone1Rotation';
LStage.AddInterpolator(LInterp);
// Configure the animation
LInterp.Path := 'RotationAngle.Point';
LInterp.Loop := true;
LInterp.Duration := 3.0; // 3 seconds
// To move the mesh, we need to add keys to the interpolator
LInterp.AddKey(0, Point3D(0, 0, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(0.75, Point3D(0, 90, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(1, Point3D(0, 180, 0), TAnimationKeyInterpolationType.Linear);
// JOINT2
LStage := TAnimationStageDef.Create(Result);
LStage.Id := 'Bone2Stage';
LStage.Reference := AArmature.Root.FindJointById('Bone2');
Result.AddStage(LStage);
// In our example we simply want to move the mesh
// So we need to create a Point3D interpolator in the stage
LInterp := TPoint3DInterpolatorDef.Create(LStage);
LInterp.Id := 'Bone2Rotation';
LStage.AddInterpolator(LInterp);
// Configure the animation
LInterp.Path := 'RotationAngle.Point';
LInterp.Loop := true;
LInterp.Duration := 3.0; // 3 seconds
// To move the mesh, we need to add keys to the interpolator
LInterp.AddKey(0, Point3D(0, 0, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(0.75, Point3D(0, 0, -90), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(1, Point3D(0, 0, -180), TAnimationKeyInterpolationType.Linear);
end;
NOTICE: You will need a stage for each joint to be modified during the animation.
TPoint3DInterpolatorDef
Control TPoint3D properties like Position, RotationAngle or Scale by interpolators of that kind. Each 3D point consists of a X, Y and Z value.
TVector3DInterpolatorDef
Control TVector3D properties by interpolators of that kind. Each 3D vector consists of a X, Y, Z and W value.
TTransformationInterpolatorDef
Control TMatrix3D properties by interpolators of that kind. This might be the most common type for fast skin animations. It is able to contain position, rotation and scaling information at once represented by a 4x4 matrix.
TQuaternionInterpolatorDef (Rotation Only)
Quaternions are 4-float vector structur able to manage rotation on 3 axis.
var
QuatInterp: TQuaternionInterpolatorDef;
Quat: TQuaternion3D;
begin
QuatInterp := TQuaternionInterpolatorDef.Create(StageDef);
QuatInterp.TargetId := 'ChildBone';
QuatInterp.PropertyName := 'RotationAngle';
// Create quaternions from Euler angles
Quat := TQuaternion3D.Create(Vector3D(0, 0, 0));
QuatInterp.AddKey(0.0, Quat);
Quat := TQuaternion3D.Create(Vector3D(0, 90, 0));
QuatInterp.AddKey(1.0, Quat);
StageDef.AddInterpolator(QuatInterp);
end;
TMeshInterpolatorDef (Vertex Animation)
By mesh or vertex animation we are able to modify single vertex positions. This is not controlled by vertex weights. Instead you can control vertices explicitly by this method.
var
MeshInterp: TMeshInterpolatorDef;
Vertices: TPoint3DDynArray;
begin
MeshInterp := TMeshInterpolatorDef.Create(StageDef);
MeshInterp.TargetId := 'SkinnedMesh';
// Key 0: Original vertices
SetLength(Vertices, MeshDef.VertexCount);
// ... fill vertices array
MeshInterp.AddKey(0.0, Vertices);
// Key 1: Deformed vertices
// ... modify vertices array
MeshInterp.AddKey(1.0, Vertices);
StageDef.AddInterpolator(MeshInterp);
end;
Materialization
Convert definition structures to renderable FMX components:
procedure TForm1.FormCreate(Sender: TObject);
var LModelDef : TModelDef;
begin
// Create abstract model data
LModelDef := TUserModelBuilder.Build();
// Create visual component for the abstract model data
FModel := TGorillaModel.LoadNewModelFromDef(GorillaViewport1, LModelDef, []);
FModel.Parent := GorillaViewport1;
// For debugging purposes show the bones
FModel.ShowJoints := true;
// Run our skin animation
FModel.AnimationManager.Current.Start;
end;
Complete Example: Animated Triangle
procedure CreateAnimatedTriangle(AViewport: TGorillaViewport);
var
Cache: TVertexCache;
ModelDef: TModelDef;
MeshDef: TMeshDef;
AnimDef: TAnimationDef;
StageDef: TAnimationStageDef;
Interp: TVector3DInterpolatorDef;
Triangle: TTriangleID;
Model: TGorillaModel;
begin
Cache := TVertexCache.Create();
try
// Define triangle
Cache.AddPositionSource(Point3D(0, 1, 0));
Cache.AddPositionSource(Point3D(-1, -1, 0));
Cache.AddPositionSource(Point3D(1, -1, 0));
Cache.AddNormalSource(Point3D(0, 0, 1));
Cache.AddNormalSource(Point3D(0, 0, 1));
Cache.AddNormalSource(Point3D(0, 0, 1));
Triangle[0] := VertexID(0, 0, 0);
Triangle[1] := VertexID(1, 1, 0);
Triangle[2] := VertexID(2, 2, 0);
Cache.AddTriangle(0, Triangle, nil);
// Create model definition
ModelDef := TModelDef.Create(nil);
try
MeshDef := TMeshDef.Create(ModelDef);
MeshDef.Id := 'Triangle';
Cache.ApplyToMeshDef(MeshDef);
ModelDef.AddChild(MeshDef);
// Add rotation animation
AnimDef := TAnimationDef.Create(ModelDef);
AnimDef.Id := 'Spin';
ModelDef.AddAnimation(AnimDef);
StageDef := TAnimationStageDef.Create(AnimDef);
StageDef.Duration := 3.0;
AnimDef.AddStage(StageDef);
Interp := TVector3DInterpolatorDef.Create(StageDef);
Interp.TargetId := 'Triangle';
Interp.PropertyName := 'RotationAngle.Point';
Interp.AddKey(0.0, Vector3D(0, 0, 0));
Interp.AddKey(3.0, Vector3D(0, 360, 0));
StageDef.AddInterpolator(Interp);
// Create visual component
Model := TGorillaModel.LoadNewModelFromDef(AViewport, ModelDef, []);
Model.Parent := AViewport;
// Play animation
if Model.AnimationManager.Animations.Count > 0 then
begin
Model.AnimationManager.Current := Model.AnimationManager.GetFirstAnimation();
Model.AnimationManager.Current.Skeleton.Loop := True;
Model.AnimationManager.Current.Start();
end;
finally
ModelDef.Free();
end;
finally
Cache.Free();
end;
end;
Best Practices
-
Choose the Right Approach: Use simple polygon method for basic shapes or TVertexCache for complex geometry
-
Normalize Weights: Ensure vertex weights sum to 1.0 for skeletal animation
-
Validate Skin: Always call
CheckMeshVerticesToBeAttachedCorrectly()after defining skin weights -
Set IsStatic Appropriately: Only set
IsStatic := Truefor geometry that won't change -
Use Appropriate Index Format: Gorilla3D automatically uses UInt16 on mobile, UInt32 on desktop
-
Avoid Vertex Groups with Animation: Vertex groups currently don't support skeletal/vertex animation
-
Cache Animations: Use caching flags for better animation performance
-
Proper Hierarchy: Use
AddChild()to maintain correct parent-child relationships -
Test Normals: Verify normals point in correct direction for proper lighting
Troubleshooting
Mesh Not Visible
// Check normals are facing camera
Model.CalcFaceNormals();
// Verify mesh has material
if not Assigned(Model.MaterialSource) then
Model.MaterialSource := MyMaterialSource;
// Ensure IsStatic is set
Model.IsStatic := True;
Black/Incorrectly Lit Mesh
// Recalculate normals
Model.CalcFaceNormals();
// For normal mapping
Model.CalcTangentBinormals();
Animation Not Working
// Verify animation is loaded
if Model.AnimationManager.Animations.Count = 0 then
ShowMessage('No animations loaded');
// Check target IDs match
if Interp.TargetId <> MeshDef.Id then
ShowMessage('Target ID mismatch');
// Validate skin
if not LSkinDef.CheckMeshVerticesToBeAttachedCorrectly() then
ShowMessage('Skin validation failed');
Memory Issues
// Clear cache after use
Cache.ClearBuffers();