# Class GameView

java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.gpu.RenderView
com.codename1.gaming.GameView

All Implemented Interfaces:
  `Animation, Editable, StyleListener, Iterable<Component>`

Direct Known Subclasses:
  `GameSceneView`

public abstract class GameView extends RenderView

A GPU accelerated game surface: a `com.codename1.gpu.RenderView` that hosts a `SpriteRenderer` over a `Scene` and calls your `#update(double)` once per frame.

Subclass it, build your world by adding `Sprite`s to `#getScene()`, advance the game in `#update(double)`, add the view to a `com.codename1.ui.Form` and call `#start()`:

    class MyGame extends GameView {
        final Sprite player = new Sprite(playerImage);
        MyGame() { getScene().add(player); player.setPosition(160, 240); }

        protected void update(double dt) {
            if (getInput().isGameKeyDown(Display.GAME_RIGHT)) {
                player.setX(player.getX() + 200 * dt);   // 200 px/second
            }
        }
    }

    Form f = new Form("Game", new BorderLayout());
    MyGame game = new MyGame();
    f.add(BorderLayout.CENTER, game);
    f.show();
    game.start();

Rendering is GPU driven: the underlying `RenderView` runs the frame loop (a display link on device, the software rasterizer in the simulator), so there is no EDT busy loop. Drawing is handled for you by the `SpriteRenderer` -- you only position sprites. The `deltaSeconds` passed to `#update(double)` is the wall clock time since the previous frame; multiply movement by it to stay framerate independent. With `#setFixedTimestep(double)` the update is stepped at a fixed interval for deterministic physics, and `#getInterpolationAlpha()` gives a 0..1 blend factor.

`#update(double)` runs on the render thread together with drawing. Keep it non blocking -- offload asset loading to a background thread and hand the result back with `com.codename1.ui.CN#callSerially(java.lang.Runnable)`.

- ## Field Summary

  ### Fields inherited from class Component

  `BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR`

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `GameView()`

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `addModel(Model model)`
  Adds a 3D `Model` to be drawn in the perspective camera alongside the sprites.
  `protected void`
  `deinitialize()`
  Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.
  `void`
  `frame(double deltaSeconds)`
  Drives game logic each frame -- invoked by the `SpriteRenderer` before the scene is drawn.
  `GameCamera`
  `getCamera()`
  The camera this view renders through.
  `TouchControls`
  `getControls()`
  The on-screen touch controls for this view (a virtual joystick and buttons).
  `double`
  `getFixedTimestep()`
  `GameInput`
  `getInput()`
  The pollable input state for this view.
  `double`
  `getInterpolationAlpha()`
  The 0..1 fraction of a fixed step left after the last update, for interpolating rendered positions.
  `Light`
  `getLight()`
  The directional light shading lit 3D `Model`s in perspective mode.
  `Scene`
  `getScene()`
  The scene drawn by this view; add and remove `Sprite`s here.
  `boolean`
  `handlesInput()`
  While running the view consumes all key events (including the directional pad and fire button) so they are not stolen for focus traversal.
  `protected void`
  `initComponent()`
  Allows subclasses to bind functionality that relies on fully initialized and "ready for action" component state
  `boolean`
  `isPaused()`
  `boolean`
  `isRunning()`
  `void`
  `keyPressed(int keyCode)`
  If this Component is focused, the key pressed event will call this method
  `void`
  `keyReleased(int keyCode)`
  If this Component is focused, the key released event will call this method
  `protected void`
  `onSetup(GraphicsDevice device)`
  Override to allocate GPU resources (meshes, textures, `Model`s) once the GPU device is ready.
  `void`
  `pause()`
  Pauses updates; frames still render but `#update(double)` is not called.
  `void`
  `pointerDragged(int[] x, int[] y)`
  If this Component is focused, the pointer dragged event will call this method
  `void`
  `pointerPressed(int[] x, int[] y)`
  If this Component is focused, the pointer pressed event will call this method
  `void`
  `pointerReleased(int[] x, int[] y)`
  If this Component is focused, the pointer released event will call this method
  `void`
  `removeModel(Model model)`
  Removes a previously added 3D `Model`.
  `void`
  `resume()`
  Resumes after `#pause()`.
  `void`
  `setClearColor(int argb)`
  Sets the ARGB color the view is cleared to each frame.
  `void`
  `setFixedTimestep(double seconds)`
  Sets a fixed update interval in seconds (0 disables, the default).
  `void`
  `setup(GraphicsDevice device)`
  Forwards GPU setup to `#onSetup(com.codename1.gpu.GraphicsDevice)`.
  `void`
  `start()`
  Starts the game loop (continuous rendering).
  `void`
  `stop()`
  Stops the game loop (no further frames until `#start()`).
  `protected abstract void`
  `update(double deltaSeconds)`
  Advance the game by the given amount of time.

  ### Methods inherited from class RenderView

  `getPeer, getRenderer, isContinuous, isSupported, requestRender, setContinuous`

  ### Methods inherited from class Container

  `add, add, add, add, add, add, addAll, addComponent, addComponent, addComponent, addComponent, animateHierarchy, animateHierarchyAndWait, animateHierarchyFade, animateHierarchyFadeAndWait, animateLayout, animateLayoutAndWait, animateLayoutFade, animateLayoutFadeAndWait, animateUnlayout, animateUnlayoutAndWait, applyRTL, calcPreferredSize, cancelRepaints, clearClientProperties, constrainHeightWhenScrollable, constrainWidthWhenScrollable, contains, createAnimateHierarchy, createAnimateHierarchyFade, createAnimateLayout, createAnimateLayoutFade, createAnimateLayoutFadeAndWait, createAnimateMotion, createAnimateUnlayout, createReplaceTransition, dragInitiated, drop, encloseIn, encloseIn, findDropTargetAt, findFirstFocusable, fireClicked, flushReplace, forceRevalidate, getBottomGap, getChildrenAsList, getClosestComponentTo, getComponentAt, getComponentAt, getComponentCount, getComponentIndex, getGridPosX, getGridPosY, getLayout, getLayoutHeight, getLayoutWidth, getLeadComponent, getLeadParent, getResponderAt, getSafeAreaRoot, getScrollIncrement, getSideGap, getUIManager, initLaf, invalidate, isEnabled, isSafeArea, isSafeAreaRoot, isScrollableX, isScrollableY, isSelectableInteraction, isSurface, iterator, iterator, layoutContainer, morph, morphAndWait, paint, paintComponentBackground, paintGlass, paramString, pointerPressed, refreshTheme, removeAll, removeComponent, replace, replace, replaceAndWait, replaceAndWait, replaceAndWait, revalidate, revalidateLater, revalidateWithAnimationSafety, scrollComponentToVisible, setCellRenderer, setEnabled, setLayout, setLeadComponent, setSafeArea, setSafeAreaRoot, setScrollable, setScrollableX, setScrollableY, setScrollIncrement, setShouldCalcPreferredSize, setShouldLayout, setUIManager, updateTabIndices`

  ### Methods inherited from class Component

  `addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, contains, containsOrOwns, createStyleAnimation, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getHeight, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getUIID, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initCustomStyle, initDisabledStyle, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyRepeated, laidOut, longKeyPress, longPointerPress, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerReleased, putClientProperty, refreshTheme, refreshTheme, remove, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setPropertyValue, setPullToRefresh, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUIIDFinal, setUnselectedStyle, setVerticalScrollBounds, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains`

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait`

  ### Methods inherited from interface Iterable

  `forEach`

- ## Constructor Details

  - ### GameView

    public GameView()

- ## Method Details

  - ### update

    protected abstract void update(double deltaSeconds)
    Advance the game by the given amount of time. Called once per frame (or repeatedly at a fixed interval when `#setFixedTimestep(double)` is used).

  - ### getScene

    public Scene getScene()
    The scene drawn by this view; add and remove `Sprite`s here.

  - ### getInput

    public GameInput getInput()
    The pollable input state for this view.

  - ### getControls

    public TouchControls getControls()
    The on-screen touch controls for this view (a virtual joystick and buttons). Add controls to it to make the game playable on touch devices; whatever you add feeds the same `GameInput` your keyboard handling already reads.

  - ### getCamera

    public GameCamera getCamera()
    The camera this view renders through. It starts in 2D mode; call `GameCamera#setPerspective(float, float, float)` on it to switch the view into a 3D perspective with billboarded sprites.

  - ### getLight

    public Light getLight()
    The directional light shading lit 3D `Model`s in perspective mode.

  - ### addModel

    public void addModel(Model model)
    Adds a 3D `Model` to be drawn in the perspective camera alongside the sprites. Build models from `#onSetup(com.codename1.gpu.GraphicsDevice)`, where the GPU device is available.

  - ### removeModel

    public void removeModel(Model model)
    Removes a previously added 3D `Model`.

  - ### onSetup

    protected void onSetup(GraphicsDevice device)

    Override to allocate GPU resources (meshes, textures, `Model`s) once the GPU device is ready. Invoked once on the render thread before the first frame -- the only place you can call `com.codename1.gpu.Primitives` / `com.codename1.gpu.GltfLoader`, which need the device. The default does nothing.

    ###### Parameters

    - `device`: the GPU device for creating meshes, textures and buffers

  - ### setup

    public void setup(GraphicsDevice device)
    Forwards GPU setup to `#onSetup(com.codename1.gpu.GraphicsDevice)`.

  - ### setClearColor

    public void setClearColor(int argb)
    Sets the ARGB color the view is cleared to each frame.

  - ### start

    public void start()
    Starts the game loop (continuous rendering). Safe to call before or after the view is shown.

  - ### stop

    public void stop()
    Stops the game loop (no further frames until `#start()`).

  - ### pause

    public void pause()
    Pauses updates; frames still render but `#update(double)` is not called.

  - ### resume

    public void resume()
    Resumes after `#pause()`.

  - ### isRunning

    public boolean isRunning()

  - ### isPaused

    public boolean isPaused()

  - ### setFixedTimestep

    public void setFixedTimestep(double seconds)
    Sets a fixed update interval in seconds (0 disables, the default). With a fixed timestep `#update(double)` may be called several times per frame to catch up, and `#getInterpolationAlpha()` returns the leftover fraction.

  - ### getFixedTimestep

    public double getFixedTimestep()

  - ### getInterpolationAlpha

    public double getInterpolationAlpha()
    The 0..1 fraction of a fixed step left after the last update, for interpolating rendered positions. Always 1 with a variable timestep.

  - ### initComponent

    protected void initComponent()
    Allows subclasses to bind functionality that relies on fully initialized and "ready for action" component state Re-applies the running state once the GPU peer exists and starts listening for pointer events at the form level.
    Overrides:
      `initComponent` in class `RenderView`

  - ### deinitialize

    protected void deinitialize()
    Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. This allows the component to deregister animators and cleanup after itself. This method is the opposite of the initComponent() method. Stops listening for pointer events when detached.
    Overrides:
      `deinitialize` in class `Component`

  - ### frame

    public void frame(double deltaSeconds)
    Drives game logic each frame -- invoked by the `SpriteRenderer` before the scene is drawn.

  - ### handlesInput

    public boolean handlesInput()
    While running the view consumes all key events (including the directional pad and fire button) so they are not stolen for focus traversal.
    Overrides:
      `handlesInput` in class `Component`
    Returns:
      true if key events are being used for focus traversal ; otherwise false

  - ### keyPressed

    public void keyPressed(int keyCode)
    Description copied from class: `Container`

    If this Component is focused, the key pressed event will call this method

    ###### Parameters

    - `keyCode`: the key code value to indicate a physical key.
    Overrides:
      `keyPressed` in class `Container`

  - ### keyReleased

    public void keyReleased(int keyCode)
    Description copied from class: `Container`

    If this Component is focused, the key released event will call this method

    ###### Parameters

    - `keyCode`: the key code value to indicate a physical key.
    Overrides:
      `keyReleased` in class `Container`

  - ### pointerPressed

    public void pointerPressed(int[] x, int[] y)
    Description copied from class: `Component`

    If this Component is focused, the pointer pressed event will call this method

    ###### Parameters

    - `x`: the pointer x coordinate

    - `y`: the pointer y coordinate

    Overrides:
      `pointerPressed` in class `Component`

  - ### pointerDragged

    public void pointerDragged(int[] x, int[] y)
    Description copied from class: `Component`

    If this Component is focused, the pointer dragged event will call this method

    ###### Parameters

    - `x`: the pointer x coordinate

    - `y`: the pointer y coordinate

    Overrides:
      `pointerDragged` in class `Component`

  - ### pointerReleased

    public void pointerReleased(int[] x, int[] y)
    Description copied from class: `Component`

    If this Component is focused, the pointer released event will call this method

    ###### Parameters

    - `x`: the pointer x coordinate

    - `y`: the pointer y coordinate

    Overrides:
      `pointerReleased` in class `Component`