Gorilla.Viewport Unit Reference

Overview

The Gorilla.Viewport unit provides the core viewport component for Gorilla3D rendering. It contains the TGorillaViewport class, which is the primary container for 3D scenes and replaces FireMonkey's standard TViewport3D component.

Classes

TGorillaViewport

Main viewport class for rendering 3D scenes using Gorilla3D.

Inheritance: TControl → TGorillaViewport

Platforms: All Gorilla3D supported platforms (Windows, macOS, Linux, Android, iOS)

Public Properties

Property Type Description
Context TContext3D Get or set the current 3D context. Do not change unless you know what you are doing.
CurrentCamera TCamera Returns the currently applied camera component (user or design camera).
Gizmo TControl3D Returns the embedded gizmo component (TGorillaGizmo) for design-time Control3D editing.
FPS Double Legacy frame rate: with UseFixedFrameRate the rate of the frame rate timer, otherwise an estimate from the scene rendering time. For the real output use FramesPerSecond.
FramesPerSecond Single Frames that really reach the screen per second of wall clock (= Diagnostics.RealFramesPerSecond). Includes frame limits (FixedFrameRate, VSync). Updated every 30 frames, 0 while DiagnosticsMeasuring is off.
DeltaTime Double Seconds between the start of the previous and the current rendered frame - the value to scale per-frame movement with. 0 on the first frame. Not clamped after pauses. Always measured.
CurrentFrameTime Double Start of the current rendered frame in seconds, counted from the first rendered frame of this viewport.
PreviousFrameTime Double Start of the previous rendered frame in seconds. DeltaTime = CurrentFrameTime - PreviousFrameTime.
ViewportScale Single Texture scale handed to the render context: the display scale (HighRes), or 1 as soon as a render resolution or HighRes on a scaled display is in use - then ViewToRenderPoint / RenderToViewPoint do the mapping. Not the render resolution factor, see RenderScale.
RenderSize TPoint RenderWidth x RenderHeight as one value. Writing it calls SetRenderSize (one rebuild for both values). Point(0, 0) = native resolution. Not published, because TPoint cannot be streamed.
Smooth Boolean Activate or deactivate smooth rendering.
SceneBounds TBoundingBox Returns the lately computed scenery boundary.
CurrentFrustum TGorillaFrustum Returns the lately computed camera frustum.
Saturation TPoint3D Get or set saturation values applied while color merging. Contains 3 parts: X=Opaque, Y=Translucent, Z=Composite saturation.
LockRendering Boolean Lock or unlock the rendering process.
EditMode Boolean Activate/deactivate edit mode at design-time (also available at runtime).
FogMode TGorillaFogMode Get or set fog computation mode (linear, exp, exp2).
FragmentDepthRendering Boolean Enable/disable pre-render pass for fragment depth rendering. Improves translucent rendering but affects performance.
CurrentRenderer TRenderer Get or set the current active renderer.
MainPassRenderer TRenderer Returns the main pass renderer.
Diagnostics TRenderingDiagnostics Frame statistics, measured while DiagnosticsMeasuring (or DiagnosticsActive) is set.
RenderingList TList<TControl3D> Access the list of objects to be rendered.

Published Properties

Viewport Settings
Property Type Default Description
RendererType TRendererType ForwardRenderer Define which renderer to use: ForwardRenderer (WBOIT, recommended) or LegacyRenderer (single framebuffer).
ManualRendering Boolean False Enable manual rendering mode where viewport only renders when RenderManual() is called. Only effective with UseFixedFrameRate = False.
UseFixedFrameRate Boolean True (False on iOS) Enable fixed framerate rendering: the viewport renders continuously from its own frame rate tick. Available on Windows, macOS, Linux and Android - on Linux and Android (since v1.5.4) the tick paces the rendering and the frame is rendered inside the FMX paint cycle. Not available on iOS (always False).
FixedFrameRate Integer 60 Fixed frame rate value (only affects rendering if UseFixedFrameRate is enabled).
FrustumCulling Boolean True Enable or disable frustum culling for performance optimization.
HighRes Boolean False Render in the physical display resolution on high-DPI displays (Android, Windows with a display scaling above 100 %). RenderScale multiplies on top.
VSync Boolean False Limit frame rate between FixedFrameRate and monitor refresh rate.
NearPlane Single 0.1 Near plane rendering clipping distance.
FarPlane Single 10000.0 Far plane rendering clipping distance.
Render Resolution
Property Type Default Description
RenderWidth Integer 0 Fixed render resolution width in pixels. Only effective if RenderWidth AND RenderHeight are greater than 0, then RenderScale is ignored. 0 = native resolution. At runtime prefer SetRenderSize to change both at once.
RenderHeight Integer 0 Fixed render resolution height in pixels. See RenderWidth.
RenderScale Single 1 Factor on the native resolution (incl. the HighRes display scale), if no fixed resolution is set. 0.5 renders a quarter of the pixels, values above 1 render supersampled. Uniform, so the aspect ratio stays the one of the viewport. Clamped to 0.1 .. 4.
RenderFit TGorillaRenderFit rfLetterbox Placement of a fixed resolution with a different aspect ratio than the viewport: letterbox (centered, black borders) or stretch (distorted, fills the viewport). No effect with RenderScale.
RenderFilter TGorillaRenderFilter rflLinear Interpolation when the image is scaled onto the viewport: linear or nearest (blocky). Only relevant if the render resolution differs from the viewport. Nearest only works on canvases that honor the HighSpeed flag of TCanvas.DrawBitmap (Direct2D, Skia); the FMX GPU canvas always scales linear.

Changing RenderWidth, RenderHeight, RenderScale or RenderFit rebuilds the render targets of the viewport and of all render passes without an individual size, like a resize. RenderFilter only repaints. See Render Resolution and Scaling.

Fog Settings
Property Type Default Description
Fog Boolean False Enable or disable fog computation.
FogKind TGorillaFogKind fkLinear Fog computation mode: fkLinear, fkExp, or fkExp2.
FogDensity Single - Density of computed fog.
FogStart Single - Lower limit of fog by distance.
FogEnd Single - Upper limit of fog by distance.
FogColor TAlphaColor - Fog color (TAlphaColor format).
FogColorF TAlphaColorF - Fog color (TAlphaColorF format).
Rendering Effects
Property Type Default Description
OpaqueSaturation Single 0.0 Saturation of opaque object rendering (ForwardRenderer/DeferredRenderer only).
TranslucentSaturation Single 1.5 Saturation of translucent object rendering (ForwardRenderer/DeferredRenderer only).
CompositeSaturation Single 0.0 Saturation of final composition (ForwardRenderer/DeferredRenderer only).
EmissiveBlur Integer 0 Emissive rendering blurring intensity. 0 deactivates. Higher values affect performance.
FXAA Integer 0 Number of FXAA anti-aliasing steps (0-8). Higher values = softer edges but lower performance.
Global Illumination (GAME_PACKAGE only)
Property Type Range Description
GlobalIllumDetail Integer 0-7 Detail level of global illumination. 0=off, 1-7=increasing voxel sizes (32-512).
GlobalIllumSoftness Single 0.0-5.0 Softness of global illumination including shadows and reflections.
ShadowStrength Single 0.0-10.0 Strength/darkness of shadows in global illumination.
ReflectionStrength Single 0.0-10.0 Strength/intensity of reflections in global illumination.
Design Settings
Property Type Description
DesignPosition TPosition3D Design camera target position (for design-time usage).
DesignRotationAngle TPosition3D Design camera target rotation angle (for design-time usage).
UsingDesignCamera Boolean Use the built-in design camera or custom camera.
Diagnostics
Property Type Default Description
DiagnosticsActive Boolean False Shows the diagnostics overlay. Only the display - the values are measured by DiagnosticsMeasuring. While the overlay is shown, the values are measured in any case.
DiagnosticsMeasuring Boolean True Collects the frame statistics (Diagnostics, FramesPerSecond, FPS). Switch off to save the measuring work per frame; the frame rates then read 0. Does not affect DeltaTime, CurrentFrameTime, PreviousFrameTime, OnBeforeRender and OnAfterRender.
RendererOutputLayer TRendererOutputLayer - Control which renderer output layers to display.
Standard Component Properties

Standard FireMonkey properties: Align, Anchors, Camera, ClipChildren, ClipParent, Color, Cursor, DragMode, EnableDragHighlight, Enabled, Height, HitTest, Locked, Padding, MSAA, Margins, Opacity, PopupMenu, Position, RotationAngle, RotationCenter, Scale, Size, Visible, Width.

Events
Event Type Description
OnBeforeRender TGorillaFrameEvent Called once per rendered frame, BEFORE the scene is rendered - the place for per-frame logic, changes show in this frame. Runs on the main thread inside the render lock: moving, adding or removing objects is fine; freeing the viewport, calling ProcessMessages or RenderManual is not.
OnAfterRender TGorillaFrameEvent Called once per rendered frame, AFTER the frame is complete and the render lock is released. Changes show from the next frame on. Suited for reading Diagnostics or capturing the image.

Both events fire only for frames that are really rendered (never for a paint that only shows the previous image), with and without UseFixedFrameRate, and not at design time. Unlike OnPaint, which follows FMX painting, they match the rendered frames 1:1. See Frame Timing and Per-Frame Logic.

Standard FireMonkey events: OnDragDrop, OnDragEnd, OnDragEnter, OnDragLeave, OnDragOver, OnKeyDown, OnKeyUp, OnClick, OnDblClick, OnCanFocus, OnEnter, OnExit, OnMouseDown, OnMouseMove, OnMouseUp, OnMouseWheel, OnMouseEnter, OnMouseLeave, OnPainting, OnPaint, OnResize, OnResized.

Public Methods

Rendering Control
procedure BeginUpdate(); override;
procedure EndUpdate(); override;
procedure EndUpdateWithoutInvalidate(); virtual;

Batch property changes into single render instruction to optimize performance.

procedure Lock(); virtual;
procedure Unlock(); virtual;

Lock/unlock the viewport for thread-safe operations.

procedure Invalidate(); virtual;

Mark the viewport for redraw.

procedure RenderManual(); virtual;

Manually trigger rendering when ManualRendering is enabled.

procedure ForceUpdateEffects(); virtual;

Force update of all rendering effects.

Render List Management
procedure RebuildRenderingList(); virtual;
procedure RenderRenderList(const ARenderContext: PRenderContext);
procedure RenderRenderListByMode(AOpaque: Boolean);

Manage and render the list of 3D objects.

Render Pass Management
procedure AddRenderPass(const AController: TComponent); virtual;
procedure RemoveRenderPass(const AController: TComponent); virtual;
procedure UpdateRenderPasses(); virtual;
procedure UpdateRenderPassesOnResize(); virtual;
procedure CleanupRenderPasses(const AController: TComponent); virtual;

Manage custom render passes in the pipeline.

Coordinate Conversion
function ScreenToWorld(const APoint2D: TPointF): TPoint3D; virtual;
function WorldToScreen(const APoint3D: TPoint3D): TPointF; virtual;

Convert between screen and world coordinates. The 2D point is in local viewport coordinates, also with a changed render resolution: scale, letterbox offset and stretch are mapped internally.

Render Resolution
procedure SetRenderSize(const AWidth, AHeight: Integer); overload;
procedure SetRenderSize(const ASize: TPoint); overload;

Set RenderWidth and RenderHeight at once with a single rebuild of the render targets. Setting both properties one after the other rebuilds twice, and the first rebuild runs with a mixed, unwanted resolution. Negative values are treated as 0. SetRenderSize(0, 0) switches back to the native resolution.

function IsRenderScaled(): Boolean;
function HasFixedRenderResolution(): Boolean;

IsRenderScaled is True if the scene is not rendered in the native resolution, because a fixed resolution or a RenderScale other than 1 is set. HasFixedRenderResolution is True if RenderWidth and RenderHeight are both greater than 0.

function GetRenderTargetSize(): TPoint;

Size in pixels of the main render target - the resolution the scene is really rendered in. Either the fixed RenderWidth x RenderHeight, or the viewport size multiplied by the display scale (HighRes) and RenderScale (at least 1 x 1 for a visible viewport). Render passes without an individual size use the same.

function GetRenderDisplayRect(): TRectF;

Rectangle in local viewport coordinates the rendered image is shown in. LocalRect, except for a fixed resolution with rfLetterbox.

function GetRenderAspectRatio(): Single;

Aspect ratio (width / height) of the rendered image - the one the camera projection is built with.

function ViewToRenderPoint(const APoint: TPointF): TPointF;
function RenderToViewPoint(const APoint: TPointF): TPointF;

Convert a point in local viewport coordinates (e.g. a mouse position) into the coordinate space the render context expects for picking (TContext3D.Pick, TGorillaContext.ScreenToWorld), and back. Identity, as long as neither a render resolution nor HighRes on a scaled display is in use. Only needed if you call the context yourself - the viewport methods above already convert.

Object Selection
function ObjectAtPoint(P: TPointF): IControl; override;
function RayCastIntersect(const P: TPointF): TControl3D; virtual;

Find objects at specific screen positions using raycasting.

Camera Access
function GetDesignCamera(): TCamera; virtual;
function GetDesignCameraController(): TGorillaSmoothCameraController; virtual;

Access the built-in design camera and controller.

Screenshot
function MakeScreenshot(): FMX.Graphics.TBitmap;

Capture the current viewport rendering as a bitmap. The bitmap has the size of the viewport (multiplied by the display scale), not the render resolution; an image of a different resolution is scaled in as shown on screen, letterbox borders stay transparent.

Gizmo Management
procedure ShowGizmo(); overload;
procedure ShowGizmo(const ACtrl: TControl3D); overload;
procedure ChangeGizmoMode(const AMode: Byte);
procedure HideGizmo();
function IsGizmoActive(): Boolean;
function GetGizmoActivatedControl(): TControl3D;

Control the design-time gizmo for object manipulation.

Design Mode
procedure StartDesignMode();
procedure EndDesignMode();

Enter and exit design mode programmatically.

Display Settings
procedure UpdateDisplayRefreshRate(); virtual;

Update the cached display refresh rate.

Helper Classes

TGorillaRenderingHelper

Helper class for rendering operations.

Public Class Methods

class function Renderable(const ACtrl: TControl3D; const AFrustum: TGorillaFrustum;
  const AComponentState: TComponentState; var ASceneBounds: TBoundingBox;
  const AFrustumCulling: Boolean; const ACheckVisibility: Boolean): Boolean;

Determine if a control should be rendered based on frustum culling and visibility.

class procedure UpdateSceneBounds(const ACtrl: TControl3D;
  const AComponentState: TComponentState; var ASceneBounds: TBoundingBox);

Update scene bounds based on a control's bounding box.

Types

TGorillaFogKind

Enumeration for fog modes (wrapper for TGorillaFogMode).

Values:

  • fkLinear - Linear fog calculation
  • fkExp - Exponential fog calculation
  • fkExp2 - Exponential squared fog calculation

TGorillaRenderFit

Placement of the image of a fixed render resolution whose aspect ratio differs from the viewport. Scoped enum - write TGorillaRenderFit.rfLetterbox.

Values:

  • rfLetterbox - Keep the aspect ratio of the render resolution, center the image and fill the borders black (default)
  • rfStretch - Stretch the image onto the whole viewport (distorted, like a low resolution in fullscreen mode)

TGorillaRenderFilter

Interpolation of the rendered image when it is scaled onto the viewport. Scoped enum - write TGorillaRenderFilter.rflLinear.

Values:

  • rflLinear - Smooth (bilinear) scaling (default)
  • rflNearest - Blocky scaling, e.g. for a pixel-art look

TGorillaFrameEvent

TGorillaFrameEvent = procedure(ASender: TObject; const ADeltaTime: Double) of object;

Event type of OnBeforeRender and OnAfterRender. ADeltaTime is TGorillaViewport.DeltaTime in seconds.

TRenderingDiagnostics

Record containing rendering performance diagnostics. Measured while TGorillaViewport.DiagnosticsMeasuring or DiagnosticsActive is set; the averages and frame rates are updated once per measure window of AverageFrameTimeClip (30) frames.

Fields:

  • Enabled - Overlay shown (= DiagnosticsActive). Not the measuring switch
  • TotalFrames - Total number of frames rendered while measuring
  • AverageFrameTime - Average work per frame in milliseconds, without the idle time between two frames
  • AverageFramesPerSecond - Headroom: 1000 / AverageFrameTime, the rate the renderer could sustain
  • RealFramesPerSecond - Output: frames per second of wall clock, including frame limits (= TGorillaViewport.FramesPerSecond)
  • DrawCalls - Number of draw calls
  • DrawInstances - Number of draw instances
  • TotalVertexCount - Total vertices processed
  • TotalIndexCount - Total indices processed
  • RenderPasses - Number of render passes
  • RenderListSize - Size of rendering list
  • RenderedObjects - Number of objects rendered
  • DisplayRefreshRate - Monitor refresh rate

Constants

Default Frame Rates

GORILLA_FRAMERATE_FIXED_DEFAULT = 60;  // All platforms

Usage Notes

  1. Compatibility: TGorillaViewport replaces FireMonkey's TViewport3D and TForm3D. They are not compatible.

  2. Fog Requirements: Fog effect requires TGorillaDefaultMaterialSource materials and is incompatible with standard FMX materials.

  3. Performance: Use BeginUpdate/EndUpdate to batch property changes. Enable ManualRendering for better control over rendering cycles. Set DiagnosticsMeasuring to False if no frame statistics are needed.

  4. Per-frame logic: Use OnBeforeRender and DeltaTime instead of OnPaint or a timer. DeltaTime is not clamped - limit it after pauses (debugger, hidden window).

  5. Frustum Culling: Improves performance but may affect render passes using different view matrices.

  6. Global Illumination: Only available in GAME_PACKAGE edition.

  7. Render Resolution: RenderScale or a fixed resolution (SetRenderSize) changes only the internal render targets, not the monitor resolution. Do not change them every frame - each change rebuilds all render targets.

See Also