Class GLArea
- All Implemented Interfaces:
Accessible,Buildable,ConstraintTarget,Proxy
GtkGLArea sets up its own GLContext, and creates a custom
GL framebuffer that the widget will do GL rendering onto. It also ensures
that this framebuffer is the default GL rendering target when rendering.
The completed rendering is integrated into the larger GTK scene graph as
a texture.
In order to draw, you have to connect to the Gtk.GLArea::render
signal, or subclass GtkGLArea and override the GtkGLAreaClass.render
virtual function.
The GtkGLArea widget ensures that the GdkGLContext is associated with
the widget's drawing area, and it is kept updated when the size and
position of the drawing area changes.
Drawing with GtkGLArea
The simplest way to draw using OpenGL commands in a GtkGLArea is to
create a widget instance and connect to the Gtk.GLArea::render signal:
The render() function will be called when the GtkGLArea is ready
for you to draw its content:
The initial contents of the framebuffer are transparent.
static gboolean
render (GtkGLArea *area, GdkGLContext *context)
{
// inside this function it's safe to use GL; the given
// GdkGLContext has been made current to the drawable
// surface used by the {@code GtkGLArea} and the viewport has
// already been set to be the size of the allocation
// we can start by clearing the buffer
glClearColor (0, 0, 0, 0);
glClear (GL_COLOR_BUFFER_BIT);
// record the active framebuffer ID, so we can return to it
// with {@code glBindFramebuffer (GL_FRAMEBUFFER, screen_fb)} should
// we, for instance, intend on utilizing the results of an
// intermediate render texture pass
GLuint screen_fb = 0;
glGetIntegerv (GL_FRAMEBUFFER_BINDING, &screen_fb);
// draw your object
// draw_an_object ();
// we completed our drawing; the draw commands will be
// flushed at the end of the signal emission chain, and
// the buffers will be drawn on the window
return TRUE;
}
void setup_glarea (void)
{
// create a GtkGLArea instance
GtkWidget *gl_area = gtk_gl_area_new ();
// connect to the "render" signal
g_signal_connect (gl_area, "render", G_CALLBACK (render), NULL);
}
If you need to initialize OpenGL state, e.g. buffer objects or
shaders, you should use the Gtk.Widget::realize signal;
you can use the Gtk.Widget::unrealize signal to clean up.
Since the GdkGLContext creation and initialization may fail, you
will need to check for errors, using getError().
An example of how to safely initialize the GL state is:
static void
on_realize (GtkGLArea *area)
{
// We need to make the context current if we want to
// call GL API
gtk_gl_area_make_current (area);
// If there were errors during the initialization or
// when trying to make the context current, this
// function will return a GError for you to catch
if (gtk_gl_area_get_error (area) != NULL)
return;
// You can also use gtk_gl_area_set_error() in order
// to show eventual initialization errors on the
// GtkGLArea widget itself
GError *internal_error = NULL;
init_buffer_objects (&error);
if (error != NULL)
{
gtk_gl_area_set_error (area, error);
g_error_free (error);
return;
}
init_shaders (&error);
if (error != NULL)
{
gtk_gl_area_set_error (area, error);
g_error_free (error);
return;
}
}
If you need to change the options for creating the GdkGLContext
you should use the Gtk.GLArea::create-context signal.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classGLArea.Builder<B extends GLArea.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static interfaceFunctional interface declaration of theCreateContextCallbackcallback.static classTheGtkGLAreaClassstructure contains only private data.static interfaceFunctional interface declaration of theRenderCallbackcallback.static interfaceFunctional interface declaration of theResizeCallbackcallback.Nested classes/interfaces inherited from class org.gnome.gtk.Widget
Widget.DestroyCallback, Widget.DirectionChangedCallback, Widget.HideCallback, Widget.KeynavFailedCallback, Widget.MapCallback, Widget.MnemonicActivateCallback, Widget.MoveFocusCallback, Widget.QueryTooltipCallback, Widget.RealizeCallback, Widget.ShowCallback, Widget.StateFlagsChangedCallback, Widget.UnmapCallback, Widget.UnrealizeCallback, Widget.Widget$Impl, Widget.WidgetClassNested classes/interfaces inherited from class org.gnome.gobject.InitiallyUnowned
InitiallyUnowned.InitiallyUnownedClassNested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClassNested classes/interfaces inherited from interface org.gnome.gtk.Accessible
Accessible.Accessible$Impl, Accessible.AccessibleInterfaceNested classes/interfaces inherited from interface org.gnome.gtk.Buildable
Buildable.Buildable$Impl, Buildable.BuildableIfaceNested classes/interfaces inherited from interface org.gnome.gtk.ConstraintTarget
ConstraintTarget.ConstraintTarget$Impl, ConstraintTarget.ConstraintTargetInterface -
Constructor Summary
ConstructorsConstructorDescriptionGLArea()Creates a new GLArea.GLArea(MemorySegment address) Create a GLArea proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionprotected GLAreaasParent()Returns this instance as if it were its parent type.voidBinds buffers to the framebuffer.static GLArea.Builder<? extends GLArea.Builder> builder()AGLArea.Builderobject constructs aGLAreawith the specified properties.protected GLContextclass closure for theGtkGLArea::create-contextsignalEmits the "create-context" signal.booleanemitRender(@Nullable GLContext context) Emits the "render" signal.voidemitResize(int width, int height) Emits the "resize" signal.Gets the allowed APIs.getApi()Gets the API that is currently in use.booleanReturns whether the area is in auto render mode or not.@Nullable GLContextRetrieves theGdkGLContextused byarea.@Nullable GErrorgetError()Gets the current error set on thearea.booleanReturns whether the area has a depth buffer.booleanReturns whether the area has a stencil buffer.static MemoryLayoutThe memory layout of the native struct.voidgetRequiredVersion(Out<Integer> major, Out<Integer> minor) Retrieves the required version of OpenGL.static @Nullable TypegetType()Get the GType of the GLArea classbooleangetUseEs()Deprecated.voidEnsures that theGdkGLContextused by this GLArea is associated with theGtkGLArea.Emitted when the widget is being realized.onRender(GLArea.RenderCallback handler) Emitted every time the contents of theGtkGLAreashould be redrawn.onResize(GLArea.ResizeCallback handler) Emitted once when the widget is realized, and then each time the widget is changed while realized.voidMarks the currently rendered data (if any) as invalid, and queues a redraw of the widget.protected booleanclass closure for theGtkGLArea::rendersignalprotected voidresize(int width, int height) class closeure for theGtkGLArea::resizesignalvoidsetAllowedApis(Set<GLAPI> apis) Sets the allowed APIs to create a context with.voidsetAllowedApis(GLAPI... apis) Sets the allowed APIs to create a context with.voidsetAutoRender(boolean autoRender) Sets whether theGtkGLAreais in auto render mode.voidSets an error on the area which will be shown instead of the GL rendering.voidsetHasDepthBuffer(boolean hasDepthBuffer) Sets whether theGtkGLAreashould use a depth buffer.voidsetHasStencilBuffer(boolean hasStencilBuffer) Sets whether theGtkGLAreashould use a stencil buffer.voidsetRequiredVersion(int major, int minor) Sets the required version of OpenGL to be used when creating the context for the widget.voidsetUseEs(boolean useEs) Deprecated.Methods inherited from class org.gnome.gtk.Widget
actionSetEnabled, activateActionIfExists, activateDefault, activateWidget, addController, addCssClass, addMnemonicLabel, addTickCallback, allocate, childFocus, computeBounds, computeExpand, computeExpand, computePoint, computeTransform, contains, createPangoContext, createPangoLayout, cssChanged, directionChanged, disposeTemplate, dragCheckThreshold, emitDestroy, emitDirectionChanged, emitHide, emitKeynavFailed, emitMap, emitMnemonicActivate, emitMoveFocus, emitQueryTooltip, emitRealize, emitShow, emitStateFlagsChanged, emitUnmap, emitUnrealize, errorBell, focus, getAllocatedBaseline, getAllocatedHeight, getAllocatedWidth, getAllocation, getAncestor, getBaseline, getCanFocus, getCanTarget, getChildVisible, getClipboard, getColor, getCssClasses, getCssName, getCursor, getDefaultDirection, getDirection, getDisplay, getFirstChild, getFocusable, getFocusChild, getFocusOnClick, getFontMap, getFontOptions, getFrameClock, getHalign, getHasTooltip, getHeight, getHexpand, getHexpandSet, getLastChild, getLayoutManager, getLimitEvents, getMapped, getMarginBottom, getMarginEnd, getMarginStart, getMarginTop, getName, getNative, getNextSibling, getOpacity, getOverflow, getPangoContext, getParent, getPreferredSize, getPrevSibling, getPrimaryClipboard, getRealized, getReceivesDefault, getRequestMode, getRoot, getScaleFactor, getSensitive, getSettings, getSize, getSizeRequest, getStateFlags, getStyleContext, getTemplateChild, getTooltipMarkup, getTooltipText, getValign, getVexpand, getVexpandSet, getVisible, getWidth, grabFocus, hasCssClass, hasDefault, hasFocus, hasVisibleFocus, hide, inDestruction, initTemplate, insertActionGroup, insertAfter, insertBefore, isAncestor, isDrawable, isFocus, isSensitive, isVisible, keynavFailed, listMnemonicLabels, map, measure, mnemonicActivate, moveFocus, observeChildren, observeControllers, onDestroy, onDirectionChanged, onHide, onKeynavFailed, onMap, onMnemonicActivate, onMoveFocus, onQueryTooltip, onRealize, onShow, onStateFlagsChanged, onUnmap, onUnrealize, pick, pick, queryTooltip, queueAllocate, queueDraw, queueResize, realize, removeController, removeCssClass, removeMnemonicLabel, removeTickCallback, root, setCanFocus, setCanTarget, setChildVisible, setCssClasses, setCursor, setCursorFromName, setDefaultDirection, setDirection, setFocusable, setFocusChild, setFocusOnClick, setFontMap, setFontOptions, setHalign, setHasTooltip, setHexpand, setHexpandSet, setLayoutManager, setLimitEvents, setMarginBottom, setMarginEnd, setMarginStart, setMarginTop, setName, setOpacity, setOverflow, setParent, setReceivesDefault, setSensitive, setSizeRequest, setStateFlags, setStateFlags, setTooltipMarkup, setTooltipText, setValign, setVexpand, setVexpandSet, setVisible, shouldLayout, show, sizeAllocate, sizeAllocate, snapshot, snapshotChild, stateFlagsChanged, systemSettingChanged, translateCoordinates, triggerTooltipQuery, unmap, unparent, unrealize, unroot, unsetStateFlags, unsetStateFlagsMethods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newv, notify, notify, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withPropertiesMethods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCodeMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.gnome.gtk.Accessible
announce, getAccessibleParent, getAccessibleRole, getAtContext, getBounds, getFirstAccessibleChild, getNextAccessibleSibling, getPlatformState, resetProperty, resetRelation, resetState, setAccessibleParent, updateNextAccessibleSibling, updatePlatformState, updateProperty, updateRelation, updateStateMethods inherited from interface org.gnome.gtk.Buildable
getBuildableId
-
Constructor Details
-
GLArea
Create a GLArea proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
GLArea
public GLArea()Creates a new GLArea.
-
-
Method Details
-
getType
-
getMemoryLayout
The memory layout of the native struct.- Returns:
- the memory layout
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuperkeyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName(). This will call the native function pointer of this virtual method in the typeclass of the parent type. -
attachBuffers
public void attachBuffers()Binds buffers to the framebuffer.Ensures that the this GLArea framebuffer object is made the current draw and read target, and that all the required buffers for the this GLArea are created and bound to the framebuffer.
This function is automatically called before emitting the
Gtk.GLArea::rendersignal, and doesn't normally need to be called by application code. -
getAllowedApis
Gets the allowed APIs.- Returns:
- the allowed APIs
- Since:
- 4.12
-
getApi
-
getAutoRender
public boolean getAutoRender()Returns whether the area is in auto render mode or not.- Returns:
trueif the this GLArea is auto rendering,falseotherwise
-
getContext
Retrieves theGdkGLContextused byarea.- Returns:
- the
GdkGLContext
-
getError
-
getHasDepthBuffer
public boolean getHasDepthBuffer()Returns whether the area has a depth buffer.- Returns:
trueif the this GLArea has a depth buffer,falseotherwise
-
getHasStencilBuffer
public boolean getHasStencilBuffer()Returns whether the area has a stencil buffer.- Returns:
trueif the this GLArea has a stencil buffer,falseotherwise
-
getRequiredVersion
Retrieves the required version of OpenGL.- Parameters:
major- return location for the required major versionminor- return location for the required minor version
-
getUseEs
Deprecated.UsegetApi()Returns whether theGtkGLAreashould use OpenGL ES.See
setUseEs(boolean).- Returns:
trueif theGtkGLAreashould create an OpenGL ES context andfalseotherwise
-
makeCurrent
public void makeCurrent()Ensures that theGdkGLContextused by this GLArea is associated with theGtkGLArea.This function is automatically called before emitting the
Gtk.GLArea::rendersignal, and doesn't normally need to be called by application code. -
queueRender
public void queueRender()Marks the currently rendered data (if any) as invalid, and queues a redraw of the widget.This ensures that the
Gtk.GLArea::rendersignal is emitted during the draw.This is only needed when
setAutoRender(boolean)has been called with afalsevalue. The default behaviour is to emitGtk.GLArea::renderon each draw. -
setAllowedApis
-
setAllowedApis
Sets the allowed APIs to create a context with.You should check
Gtk.GLArea:apibefore drawing with either API.By default, all APIs are allowed.
- Parameters:
apis- the allowed APIs- Since:
- 4.12
-
setAutoRender
public void setAutoRender(boolean autoRender) Sets whether theGtkGLAreais in auto render mode.If
autoRenderistruetheGtk.GLArea::rendersignal will be emitted every time the widget draws. This is the default and is useful if drawing the widget is faster.If
autoRenderisfalsethe data from previous rendering is kept around and will be used for drawing the widget the next time, unless the window is resized. In order to force a renderingqueueRender()must be called. This mode is useful when the scene changes seldom, but takes a long time to redraw.- Parameters:
autoRender- a boolean
-
setError
Sets an error on the area which will be shown instead of the GL rendering.This is useful in the
Gtk.GLArea::create-contextsignal if GL context creation fails.- Parameters:
error- a newGError, ornullto unset the error
-
setHasDepthBuffer
public void setHasDepthBuffer(boolean hasDepthBuffer) Sets whether theGtkGLAreashould use a depth buffer.If
hasDepthBufferistruethe widget will allocate and enable a depth buffer for the target framebuffer. Otherwise there will be none.- Parameters:
hasDepthBuffer-trueto add a depth buffer
-
setHasStencilBuffer
public void setHasStencilBuffer(boolean hasStencilBuffer) Sets whether theGtkGLAreashould use a stencil buffer.If
hasStencilBufferistruethe widget will allocate and enable a stencil buffer for the target framebuffer. Otherwise there will be none.- Parameters:
hasStencilBuffer-trueto add a stencil buffer
-
setRequiredVersion
public void setRequiredVersion(int major, int minor) Sets the required version of OpenGL to be used when creating the context for the widget.This function must be called before the area has been realized.
- Parameters:
major- the major versionminor- the minor version
-
setUseEs
Deprecated.Sets whether the this GLArea should create an OpenGL or an OpenGL ES context.You should check the capabilities of the
GdkGLContextbefore drawing with either API.- Parameters:
useEs- whether to use OpenGL or OpenGL ES
-
createContext
class closure for theGtkGLArea::create-contextsignal -
render
class closure for theGtkGLArea::rendersignal -
resize
protected void resize(int width, int height) class closeure for theGtkGLArea::resizesignal -
onCreateContext
public SignalConnection<GLArea.CreateContextCallback> onCreateContext(GLArea.CreateContextCallback handler) Emitted when the widget is being realized.This allows you to override how the GL context is created. This is useful when you want to reuse an existing GL context, or if you want to try creating different kinds of GL options.
If context creation fails then the signal handler can use
setError(org.gnome.glib.GError)to register a more detailed error of how the construction failed.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitCreateContext
Emits the "create-context" signal. SeeonCreateContext(org.gnome.gtk.GLArea.CreateContextCallback). -
onRender
Emitted every time the contents of theGtkGLAreashould be redrawn.The
contextis bound to theareaprior to emitting this function, and the buffers are painted to the window once the emission terminates.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitRender
Emits the "render" signal. SeeonRender(org.gnome.gtk.GLArea.RenderCallback). -
onResize
Emitted once when the widget is realized, and then each time the widget is changed while realized.This is useful in order to keep GL state up to date with the widget size, like for instance camera properties which may depend on the width/height ratio.
The GL context for the area is guaranteed to be current when this signal is emitted.
The default handler sets up the GL viewport.
- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitResize
public void emitResize(int width, int height) Emits the "resize" signal. SeeonResize(org.gnome.gtk.GLArea.ResizeCallback). -
builder
AGLArea.Builderobject constructs aGLAreawith the specified properties. Use the variousset...()methods to set properties, and finish construction withGLArea.Builder.build().- Returns:
- the builder object
-
getApi()