Gorilla.Mesh Unit Reference
Overview
The Gorilla.Mesh unit provides the core mesh component for Gorilla3D rendering. It contains the TGorillaMesh class, which represents individual 3D meshes with geometry data, materials, and rendering capabilities. Each mesh within a TGorillaModel is an instance of TGorillaMesh.
Classes
TGorillaMesh
Default Gorilla3D mesh control. Can be used as standalone component or child of TGorillaModel. Each mesh inside a model is a TGorillaMesh instance.
Inheritance: TGorillaTransform → TGorillaMesh
Platforms: All Gorilla3D supported platforms (Windows, macOS, Linux, Android, iOS)
Public Properties
| Property | Type | Description |
|---|---|---|
| Model | TGorillaControl | Get or set parent model component holding reference to mesh instance. |
| ReferencedName | String | Reference name for identifying mesh explicitly. |
| MeshData | TMeshData | Returns internal mesh data object with vertex and indices buffers. May be empty if mesh is STATIC for memory savings. |
| VertexJoints | TVertexJointsList | Returns used vertex joints list for skeletal animation. |
| Meshes | TGorillaMeshList | Returns list of sub-meshes. |
| Coordinates | TPoint3DDynArray | Get or set vertex coordinates array. |
| Vertices | TVertexDataMap | Get or set vertex data map containing all vertex attributes. |
| IsStatic | Boolean | Get or set static mesh flag. Static meshes prebuffer vertex data to GPU, clearing CPU memory. |
| WrapMode | TMeshWrapMode | Get or set mesh wrap mode for texture coordinates. |
| FlatShading | Boolean | Enable or disable flat shading. Recalculates normals per-face instead of per-vertex. |
Published Properties
| Property | Type | Default | Description |
|---|---|---|---|
| MaterialSource | TMaterialSource | nil | Get or set material source for mesh rendering. |
| Shadows | Boolean | False | Whether this mesh receives cascaded shadows. Setting True flips the linked default material(s) to ShadowMethod = CascadedShadowMapping and propagates to all sub-meshes. |
| CastShadows | Boolean | True | Whether this mesh is rendered into the cascaded-shadow depth atlas as a caster. Set False to keep an object from throwing a shadow — e.g. a water surface or transparent wall that sits between the light and the scene and would otherwise shadow everything beneath it. Independent of Shadows. |
| Wireframe | Boolean | False | Enable wireframe rendering (performance intensive, debugging only). |
| WireframeMaterial | TMaterialSource | nil | Material source for wireframe rendering in post-processing. |
| ShowNormals | Boolean | False | Enable normal visualization (performance intensive). |
| NormalsColor | TAlphaColor | - | Color for rendered normals if ShowNormals is active. |
| ShowBoundingBox | Boolean | False | Inherited from TGorillaControl. Renders the box of GetAnimatedBoundingBox() around the mesh and its sub-meshes (main render pass only). Works for static meshes too. |
| BoundingBoxColor | TAlphaColor | Orange | Inherited from TGorillaControl. Line color of the box drawn by ShowBoundingBox. |
| Instances | TGorillaMeshInstances | - | Collection managing mesh instances for GPU instancing. |
| Materials | TGorillaMeshMaterialCollection | - | Read-only design-time collection showing linked material sources. |
| Behaviours | TGorillaMeshBehaviourCollection | - | Collection of material behaviours attached to mesh. |
| MeshCollection | TGorillaMeshCollection | - | Read-only design-time collection showing submeshes. |
Standard properties: Width, Height, Depth, Position, Scale, RotationAngle, Visible, Opacity, etc.
Constructor & Destructor
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
Public Methods
Geometry Access
function GetBoundingBox(): TBoundingBox; override;
Returns absolute bounding box with applied mesh and local matrices.
function GetAnimatedBoundingBox(): TBoundingBox; override;
Returns the bounding box of the current vertices in local space of this mesh (relative to AbsoluteMatrix), as union with all sub-meshes. This is the box drawn by ShowBoundingBox.
Per (sub-)mesh the source is: the box stored with the current cached animation frame of the model, otherwise the live (CPU animated or dynamic) vertex buffer, otherwise the static vertex data of the mesh definition, which is where static meshes (IsStatic = True) keep their data. The mesh matrix (WrapMode) and the transformations of the sub-meshes are applied. Returns TBoundingBox.Empty if no mesh has vertices.
TGorillaSingletonMesh (and with it TGorillaCube, TGorillaSphere, ...) returns its body box (GetBodySize()) instead, the same box IsMarked draws. The base implementation in TGorillaControl returns the size box (Width, Height, Depth) of the control.
var
LWorld: TBoundingBox;
begin
LWorld := GorillaMesh1.GetAnimatedBoundingBox().Transform(GorillaMesh1.AbsoluteMatrix);
end;
Instancing
See Models - Instancing for a complete guide.
function AddInstanceItem(AName: String): TGorillaMeshInstance; overload;
function AddInstanceItem(AName: String; ATransform: TMatrix3D): Integer; overload;
Adds a TGorillaMeshInstance item to the Instances collection. The first overload returns the item (identity transform), the second one applies the matrix and returns the index of the item in Instances. Items are passed on to all sub-meshes.
Example:
var LInst := GorillaModel1.AddInstanceItem('Tree_1');
LInst.BeginUpdate();
try
LInst.Position.Point := Point3D(10, 0, 5);
LInst.RotationAngle.Point := Point3D(0, 45, 0);
LInst.Scale.Point := Point3D(2, 2, 2);
finally
LInst.EndUpdate();
end;
procedure BeginInstancesEditing();
procedure EndInstancesEditing();
Locks the instance collection, all instance items and all sub-meshes for mass manipulation. EndInstancesEditing() rebuilds all instance matrices and the instance buffers once. Always pair both calls in a try..finally block.
Example:
GorillaModel1.BeginInstancesEditing();
try
for var I := 0 to 999 do
begin
var LInst := GorillaModel1.AddInstanceItem(Format('Rock_%d', [I]));
LInst.Position.Point := Point3D(Random(100) - 50, 0, Random(100) - 50);
LInst.RotationAngle.Y := Random(360);
end;
finally
GorillaModel1.EndInstancesEditing();
end;
function AddInstance(ATransform: TMatrix3D): Integer;
Adds a plain matrix to the instance cache without creating a collection item (fastest, runtime only). Returns the cache index (starting at 1). Not passed on to sub-meshes and dropped as soon as the instance items of the mesh change.
function GetInstance(AIndex: Integer): TMatrix3D;
procedure SetInstance(AIndex: Integer; const AValue: TMatrix3D);
Get or set a transformation matrix in the instance cache by its cache index. Index 0 is the mesh itself and is overwritten every frame. Additional instances start at index 1 (item Instances.Items[I] is cache index I + 1). For instance items, prefer changing Position, RotationAngle and Scale of the item - SetInstance() is overwritten when the cache is rebuilt from the items.
Example:
// move a matrix-only instance
var LIdx := Mesh.AddInstance(TMatrix3D.CreateTranslation(Point3D(10, 0, 0)));
Mesh.SetInstance(LIdx, TMatrix3D.CreateTranslation(Point3D(10, 2, 0)));
function DeleteInstance(AIndex: Integer): Boolean;
procedure ClearInstances();
DeleteInstance() removes the instance item at the given collection index. ClearInstances() removes all instance items and all matrix-only instances.
Ray Casting and Triangle Picking
function RayCastIntersect(const ARayPos, ARayDir: TPoint3D;
var AIntersection, ANormal: TPoint3D): Boolean; reintroduce;
Performs ray cast intersection test on this mesh using absolute ray position and direction. Returns TRUE if ray intersects any triangle, with intersection point and normal vector at that position. Searches entire mesh hierarchy including all submeshes.
Important: Requires absolute world-space ray position and direction vectors.
Example:
var
RayPos, RayDir: TPoint3D;
Intersection, Normal: TPoint3D;
begin
// Absolute world-space ray
RayPos := Point3D(0, 10, 0);
RayDir := Point3D(0, -1, 0); // Downward
if Mesh.RayCastIntersect(RayPos, RayDir, Intersection, Normal) then
begin
ShowMessage('Hit at: ' + Intersection.ToString);
ShowMessage('Normal: ' + Normal.ToString);
end;
end;
function PickTriangle(const X, Y: Single;
var AIntersection, ANormal: TPoint3D; out A, B, C: TPoint3D): Boolean; overload;
Detects intersected triangle using screen coordinates (X, Y in pixels). Converts screen coordinates to 3D ray and performs intersection test. Returns TRUE if triangle hit, providing intersection point, normal, and absolute triangle corner coordinates (A, B, C).
Parameters:
X, Y- Screen coordinates in pixelsAIntersection- Output: 3D intersection point (world space)ANormal- Output: Surface normal at intersectionA, B, C- Output: Triangle corner positions (world space)
Example:
var
Intersection, Normal: TPoint3D;
A, B, C: TPoint3D;
begin
// Mouse click at screen position
if Mesh.PickTriangle(MouseX, MouseY, Intersection, Normal, A, B, C) then
begin
ShowMessage('Triangle hit at: ' + Intersection.ToString);
ShowMessage(Format('Triangle corners: [%s, %s, %s]',
[A.ToString, B.ToString, C.ToString]));
end;
end;
function PickTriangle(const X, Y: Single;
var AResult: TTriangleRayCastResult): Boolean; overload;
Detects intersected triangle using screen coordinates and returns comprehensive result structure. Provides intersection point, normal, triangle corners, distance, and reference to intersected object.
Parameters:
X, Y- Screen coordinates in pixelsAResult- Output: Complete ray cast result structure
Example:
var
Result: TTriangleRayCastResult;
begin
if Mesh.PickTriangle(MouseX, MouseY, Result) then
begin
ShowMessage(Format('Hit at distance: %.2f', [Result.T]));
ShowMessage('Point: ' + 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 intersected object
if Assigned(Result.Instance) then
ShowMessage('Hit object: ' + TComponent(Result.Instance).Name);
end;
end;
function PickTriangle(const ARayPos, ARayDir: TVector3D;
var AIntersection, ANormal: TPoint3D; out A, B, C: TPoint3D): Boolean; overload;
Detects intersected triangle using absolute ray position and direction. Returns intersection point, normal, and triangle corner coordinates.
Important: Requires absolute world-space ray vectors.
Parameters:
ARayPos- Absolute ray start position (world space)ARayDir- Absolute ray direction vector (world space)AIntersection- Output: 3D intersection pointANormal- Output: Surface normal at intersectionA, B, C- Output: Triangle corner positions
Example:
var
RayPos, RayDir: TVector3D;
Intersection, Normal: TPoint3D;
A, B, C: TPoint3D;
begin
// Setup ray from camera position
RayPos := Vector3D(Camera.Position.X, Camera.Position.Y, Camera.Position.Z);
RayDir := Vector3D(0, 0, 1); // Forward
if Mesh.PickTriangle(RayPos, RayDir, Intersection, Normal, A, B, C) then
begin
// Process triangle intersection
ShowMessage('Triangle hit!');
end;
end;
function PickTriangle(const ARayPos, ARayDir: TVector3D;
var AResult: TTriangleRayCastResult): Boolean; overload;
Detects intersected triangle using absolute ray position and direction and returns comprehensive result structure.
Important: Requires absolute world-space ray vectors.
Parameters:
ARayPos- Absolute ray start position (world space)ARayDir- Absolute ray direction vector (world space)AResult- Output: Complete ray cast result structure
Example:
var
Result: TTriangleRayCastResult;
RayPos, RayDir: TVector3D;
begin
RayPos := Vector3D(0, 100, 0);
RayDir := Vector3D(0, -1, 0); // Downward ray
if Mesh.PickTriangle(RayPos, RayDir, Result) then
begin
ShowMessage(Format('Hit at distance: %.2f units', [Result.T]));
ShowMessage('Intersection: ' + Result.Intersection.ToString);
ShowMessage('Normal: ' + Result.Normal.ToString);
// Calculate impact details
var ImpactForce := 100.0 / Result.T; // Force based on distance
end;
end;
Material Management
procedure ApplyMaterialSource(AValue: TMaterialSource);
Applies material source to mesh and all submeshes recursively.
Utility Methods
procedure ComputeTangentsAndBinormals();
Computes tangent and binormal vectors for normal mapping. Called automatically when needed.
procedure BuildTriangleMesh();
Debugging routine creating simple triangle in mesh data. Deletes existing data.
Helper Classes
TGorillaMeshInstance
Collection item describing one GPU instance of a mesh. Returned by TGorillaMesh.AddInstanceItem().
Inheritance: TCollectionItem → TGorillaMeshInstance
Properties
| Property | Type | Description |
|---|---|---|
| Position | TPosition3D | Absolute translation of the instance (not relative to the mesh). |
| RotationAngle | TPosition3D | Rotation in degrees around X, Y, Z. |
| Scale | TPosition3D | Scaling, default (1, 1, 1). |
| RotationCenter | TPosition3D | Pivot of the rotation, default (0, 0, 0). |
| DisplayName | String | Name of the instance. |
| Transform | TMatrix3D | Read-only resulting matrix (Scale → Rotation → Translation). |
| OwnerMesh | TGorillaMesh | Mesh owning this instance. |
Methods
procedure BeginUpdate();
procedure EndUpdate();
Defers the matrix rebuild and the rebuild of the instance buffer until the outermost EndUpdate(). Use it when changing several properties of one instance. For many instances use TGorillaMesh.BeginInstancesEditing().
procedure SetTransform(const ATransform: TMatrix3D);
Sets the instance by a matrix and extracts Position, Scale and RotationAngle from it.
procedure ResetRotationAngle();
procedure UpdateTransform();
ResetRotationAngle() resets the rotation to zero. UpdateTransform() recomputes Transform from the properties (does nothing while updating).
TGorillaMeshInstances
Collection managing mesh instances for GPU instancing.
Inheritance: TOwnedCollection → TGorillaMeshInstances
Properties
| Property | Type | Description |
|---|---|---|
| OwnerMesh | TGorillaMesh | Returns owning mesh component. |
| CacheUpdated | Boolean | Indicates if instance cache was updated. |
| CachedInstancesPtr | PMatrix3D | Pointer to cached instances array. |
| CachedInstancesCount | Integer | Number of cached instances. |
Methods
function AddInstance(const ATransform: TMatrix3D; const ACreateItem: Boolean;
AName: String = ''): Integer;
Add new instance to collection. For runtime, reduce memory by setting ACreateItem to false.
Example:
// Add instances without creating collection items (memory efficient)
for var x := 0 to 9 do
for var z := 0 to 9 do
begin
var Transform := TMatrix3D.CreateTranslation(Point3D(x * 2, 0, z * 2));
Mesh.Instances.AddInstance(Transform, False);
end;
function GetInstance(AIndex: Integer): TMatrix3D;
procedure SetInstance(AIndex: Integer; const AValue: TMatrix3D);
Get or update specific instance transformation by index.
function DeleteInstance(AIndex: Integer): Boolean;
Delete specific instance by index. Adjusts cache accordingly. Returns success.
procedure ClearInstances();
Clears all items and cached instances.
procedure UpdateInstanceCache(); overload;
procedure UpdateInstanceCache(const ABaseTransform: TMatrix3D;
const AInstances: TArray<TMatrix3D>); overload;
Updates internal instance cache for GPU rendering.
function ToArray(): TArray<TMatrix3D>;
Returns instances as array of transformation matrices.
TGorillaMeshInstance
Individual mesh instance with transform properties.
Inheritance: TCollectionItem → TGorillaMeshInstance
Published Properties
| Property | Type | Description |
|---|---|---|
| DisplayName | String | Instance display name. |
| Position | TPosition3D | Instance position. |
| Scale | TPosition3D | Instance scale. |
| RotationAngle | TPosition3D | Instance rotation angles. |
| RotationCenter | TPosition3D | Instance rotation center. |
Public Properties
| Property | Type | Description |
|---|---|---|
| Transform | TMatrix3D | Computed transformation matrix. |
| OwnerMesh | TGorillaMesh | Returns owning mesh. |
Methods
procedure UpdateTransform();
procedure SetTransform(const ATransform: TMatrix3D);
procedure ResetRotationAngle();
TGorillaMeshMaterialCollection
Read-only design-time collection showing linked material sources.
Inheritance: TGorillaReadOnlyCollection → TGorillaMeshMaterialCollection
Methods
class procedure Update(ACollection: TGorillaMeshMaterialCollection;
AMesh: TGorillaMesh); reintroduce;
Updates collection to reflect current mesh materials.
function MaterialExists(AMaterial: TMaterialSource): Boolean;
Checks if material exists in collection.
TGorillaMeshCollection
Read-only design-time collection showing submeshes.
Inheritance: TGorillaReadOnlyCollection → TGorillaMeshCollection
Methods
class procedure Update(ACollection: TGorillaMeshCollection;
AMesh: TGorillaMesh); reintroduce;
Updates collection to reflect current submeshes.
function MeshExists(AMesh: TGorillaMesh): Boolean;
Checks if mesh exists in collection.
TGorillaMeshBehaviourCollection
Collection managing material behaviours attached to mesh.
Inheritance: TGorillaReadOnlyCollection → TGorillaMeshBehaviourCollection
Methods
class procedure Update(ACollection: TGorillaMeshBehaviourCollection;
AMesh: TGorillaMesh); reintroduce;
Updates collection to reflect current behaviours.
function BehaviourExists(ABehaviour: TGorillaMaterialBehaviour): Boolean;
Checks if behaviour exists in collection.
Helper Types
TGorillaMeshList
List of TGorillaMesh instances.
TGorillaMeshList = TObjectList<TGorillaMesh>;
TVertexJointsList
List managing vertex joint information for skeletal animation.
Usage Examples
Creating a Mesh
var
Mesh: TGorillaMesh;
begin
Mesh := TGorillaMesh.Create(Self);
Mesh.Parent := Viewport;
Mesh.MaterialSource := MyMaterial;
end;
GPU Instancing
var
Mesh: TGorillaMesh;
Transform: TMatrix3D;
begin
Mesh := TGorillaMesh.Create(Self);
Mesh.Parent := Viewport;
// Add 100 instances
for var i := 0 to 99 do
begin
Transform := TMatrix3D.CreateTranslation(
Point3D(Random(100) - 50, 0, Random(100) - 50)
);
Mesh.Instances.AddInstance(Transform, False); // No collection item = memory efficient
end;
end;
Accessing Sub-Meshes
// Iterate through all submeshes
for var i := 0 to Mesh.Meshes.Count - 1 do
begin
var SubMesh := Mesh.Meshes[i];
ShowMessage('SubMesh: ' + SubMesh.Name);
// Apply material to submesh
SubMesh.MaterialSource := BodyMaterial;
end;
Static Mesh Optimization
// Mark mesh as static for better performance
Mesh.IsStatic := True;
// Static meshes prebuffer to GPU and clear CPU memory
// Use for meshes that never change geometry
Flat Shading
// Enable flat shading for hard-edge look
Mesh.FlatShading := True;
// Normals recalculated per-face instead of per-vertex
Wireframe Rendering
Mesh.Wireframe := True;
Mesh.WireframeMaterial := WireframeMaterialSource;
// Warning: Performance intensive, use for debugging only
Normal Visualization
Mesh.ShowNormals := True;
Mesh.NormalsColor := TAlphaColors.Green;
// Shows normal directions for debugging
Ray Casting and Triangle Picking
Using RayCastIntersect
var
RayPos, RayDir: TPoint3D;
Intersection, Normal: TPoint3D;
begin
// Absolute world-space ray
RayPos := Point3D(0, 10, 0);
RayDir := Point3D(0, -1, 0); // Downward
if Mesh.RayCastIntersect(RayPos, RayDir, Intersection, Normal) then
begin
ShowMessage('Hit at: ' + Intersection.ToString);
ShowMessage('Surface normal: ' + Normal.ToString);
end;
end;
Using PickTriangle with Screen Coordinates
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 Mesh.PickTriangle(X, Y, Intersection, Normal, A, B, C) then
begin
ShowMessage('Clicked on mesh at: ' + Intersection.ToString);
ShowMessage(Format('Triangle corners: [%s, %s, %s]',
[A.ToString, B.ToString, C.ToString]));
// Visualize hit point
Sphere.Position.Point := Intersection;
end;
end;
Using PickTriangle with Result Structure
procedure TForm1.Viewport1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var
Result: TTriangleRayCastResult;
begin
if Mesh.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 all triangle corners
for var i := 0 to 2 do
ShowMessage(Format('Corner %d: %s', [i, Result.Triangle[i].ToString]));
// Check which object was hit
if Assigned(Result.Instance) then
begin
if Result.Instance is TGorillaMesh then
ShowMessage('Hit mesh: ' + TGorillaMesh(Result.Instance).Name);
end;
end;
end;
Using PickTriangle with Absolute Ray
var
Result: TTriangleRayCastResult;
RayPos, RayDir: TVector3D;
begin
// Cast ray from above downward
RayPos := Vector3D(Character.Position.X, 100, Character.Position.Z);
RayDir := Vector3D(0, -1, 0);
if Mesh.PickTriangle(RayPos, RayDir, Result) then
begin
// Found ground height
var GroundHeight := Result.Intersection.Y;
Character.Position.Y := GroundHeight + 1.0; // Place character on ground
ShowMessage(Format('Ground found at height: %.2f', [GroundHeight]));
end;
end;
Modifying Instances
// Animate instances
for var i := 0 to Mesh.Instances.CachedInstancesCount - 1 do
begin
var Transform := Mesh.Instances.GetInstance(i);
// Rotate instance
Transform := Transform * TMatrix3D.CreateRotationY(0.01);
Mesh.Instances.SetInstance(i, Transform);
end;
// Update cache after modifications
Mesh.Instances.UpdateInstanceCache();
Accessing Vertex Data
// Get vertex positions
var Coords := Mesh.Coordinates;
for var i := Low(Coords) to High(Coords) do
ShowMessage(Coords[i].ToString);
// Warning: Static meshes may have empty vertex data on CPU
if not Mesh.IsStatic then
begin
// Modify vertices
var Vertices := Mesh.Vertices;
// ... modify vertex data ...
Mesh.Vertices := Vertices;
end;
Material Management
// Apply material to mesh and all submeshes
Mesh.ApplyMaterialSource(MyMaterial);
// Apply to specific mesh only
Mesh.MaterialSource := MyMaterial;
Constants
Mesh Defaults
GORILLA_POLYGON_MAXSIZE = 16; // Maximum polygon size
Usage Notes
-
Static Meshes: Set IsStatic = True for meshes with unchanging geometry to improve performance and reduce memory.
-
GPU Instancing: Use AddInstance with ACreateItem = False for memory-efficient instancing at runtime.
-
Wireframe/Normals: Both features are performance intensive. Use for debugging only.
-
Flat Shading: Recalculates normals per-face. Use for hard-edge modeling style.
-
Sub-Meshes: Complex models contain mesh hierarchies. Iterate through Meshes collection to access all parts.
-
Vertex Data Access: Static meshes may have empty CPU vertex data. Check IsStatic before accessing.
-
Ray Casting and Triangle Picking:
- Use
RayCastIntersectfor absolute world-space ray tests - Use
PickTrianglewith screen coordinates (X, Y) for mouse interaction - Use
PickTrianglewith absolute ray for custom ray tests - All methods perform deep search on entire mesh hierarchy including submeshes
TTriangleRayCastResultprovides complete intersection details including distance, normal, triangle corners, and intersected object reference
- Use
See Also
- Models User Guide
- Gorilla.Model Unit
- Gorilla.DefTypes Unit
Gorilla.TransformUnit — transformation helpers (no reference page yet)