# Nifty GUI 1.3 - Usecase Scenarios

This document contains typical NiftyGUI usecase scenarios, such as adding effects, game states, and creating typical game screens.

Requirements: These tips assume that you have read and understood the Creating JME3 User Interfaces with Nifty GUI tutorial, and have already laid out a basic GUI that interacts with your JME3 application. Here you learn how you integrate the GUI better, and add effects and advanced controls.

## Switch Game States

In a JME game, you typically have three game states:

1. Stopped: The game is stopped, a StartScreen is displayed.
2. Running: The game is running, the in-game HudScreen is displayed.
3. Paused: The game is paused, a PausedScreen is displayed.

(Aside: Additionally, the Stopped state often contains a LoadScreen, LogonScreen, OptionsScreen, CharacterCreationScreen, HighScoreScreen, CreditsScreen, etc. Some games let you access the OptionsScreen in the Paused state as well. The Running state can also contain an InventoryScreen, ItemShopScreen, StatsScreen, SkillScreen, etc.)

In JME, game states are implemented as custom AppState objects. Write each AppState so it brings its own input mappings, rootNode content, update loop behaviour, etc with it.

1. Stopped: StartScreen AppState + GuiInputs AppState
2. Paused: PausedScreen AppState + GuiInputs AppState
3. Running: HudScreen AppState + InGameInputs AppState + BulletAppState (jme physics), ???

When the player switches between game states, you detach one set of AppStates, and attach another. For example, when the player pauses the running game, you use a boolean switch to pause the game loop and deactivate the game inputs (shooting, navigation). The screen is overlayed with a PausedScreen, which contains a visible mouse pointer and a Continue button. When the player clicks Continue, the mouse pointer is deactivated, the in-game input and navigational mappings are activated, and the game loop continues.

## Get Access to Application and Update Loop

Since you are writing a jME3 application, you can additionally make any ScreenController class extend the AbstractAppState class. This gives the ScreenController access to the application object and to the update loop!

    public class StartScreenState extends AbstractAppState {

      private ViewPort viewPort;
      private Node rootNode;
      private Node guiNode;
      private AssetManager assetManager;
      private Node localRootNode = new Node("Start Screen RootNode");
      private Node localGuiNode = new Node("Start Screen GuiNode");
      private final ColorRGBA backgroundColor = ColorRGBA.Gray;

    public StartScreenState(SimpleApplication app){
        this.rootNode     = app.getRootNode();
        this.viewPort     = app.getViewPort();
        this.guiNode      = app.getGuiNode();
        this.assetManager = app.getAssetManager();
      }

      @Override
      public void initialize(AppStateManager stateManager, Application app) {
        super.initialize(stateManager, app);
        /** init the screen */
      }

      @Override
      public void update(float tpf) {
        /** any main loop action happens here */
      }

      @Override
      public void stateAttached(AppStateManager stateManager) {
        rootNode.attachChild(localRootNode);
        guiNode.attachChild(localGuiNode);
        viewPort.setBackgroundColor(backgroundColor);
      }

      @Override
      public void stateDetached(AppStateManager stateManager) {
        rootNode.detachChild(localRootNode);
        guiNode.detachChild(localGuiNode);
      }

    }

## Know Your Variables

Variable | Description
--- | ---
${CALL.myMethod()} | Calls a method in the current ScreenController and gets the method's return String. The method can also be void and have a side effect, e.g. play a sound etc.
${ENV.HOME} | Returns the path to user's home directory.
${ENV.key} | Looks up `key` in the environment variables. Use it like Java's System.getEnv("key").
${PROP.key} | looks up `key` in the Nifty properties. Use Nifty.setGlobalproperties(properties) and Nifty.getGlobalproperties("key"). Or SystemGetProperties(key);

See also:

## Use ScreenControllers for Mutally Exclusive Functionality

Technically you are free to create one ScreenController class for each screen, or reuse the same ScreenController for all or some of them. In the end it may be best to create individual ScreenControllers for functionality that is mutually exclusive.

For example, create a `MyHudScreen.java` for the `hud` screen, and a `MyStartScreen.java` for the `start` screen.

- Include all user interface methods that are needed during the game (while the HUD is up) in `MyHudScreen.java`. Then make this class control all screens that can be up during the game (the HUD screen, a MiniMap screen, an Inventory screen, an Abilities or Skills screen, etc). All these screens possibly share data (game data, player data), so it makes sense to control them all with methods of the same `MyHudScreen.java` class.
- The start screen, however, is mostly independent of the running game. Include all user interface methods that are needed outside the game (while you are on the start screen) in `MyStartScreen.java`. Then make this class control all screens that can be up outside the game (the Start screen, a Settings/Options screen, a HighScore screen, etc). All these classes need to read and write saved game data, so it makes sense to control them all with methods of the same `MyStartScreen.java` class.

## Create a "Loading..." Screen

Get the full Loading Screen tutorial here.

## Create a Popup Menu

Get the full Nifty GUI PopUp Menu tutorial here.

## Add Visual Effects

You can register effects to screen elements.

- Respond to element events such as onStartScreen, onEndScreen, onHover, onFocus, onActive,
- Trigger effects that change movement, blending, size, color, fading, and much more.

Here is an example that moves a panel when the startScreen opens. You place an < effect > tag inside the element that you want to be affected.

    <panel height="25%" width="35%" ...>
      <effect>
        <onStartScreen name="move" mode="in" direction="top" length="300" startDelay="0" inherit="true"/>
      </effect>
    </panel>

Learn more from the NiftyGUI page:

## Add Sound Effects

Playing sounds using Nifty is also possible with a `playSound` effect as trigger. Remember to first register the sound that you want to play:

    <registerSound id="myclick" filename="Interface/sounds/ButtonClick.ogg" />
    ...
    <label>
      <effect>
        <onClick name="playSound" sound="myclick"/>
      </effect>
    </label>

## Pass ClickLoc From Nifty to Java

After a mouse click, you may want to record the 2D clickLoc and send this info to your Java application. Typical ScreenController methods however only have a String argument. You'd have to convert the String to ints.

To pass the clickLoc as two ints, you can use the special `(int x, int y)` syntax in the ScreenController:

      public void clicked(int x, int y) {
        // here you can use the x and y of the clickLoc
      }

In the Nifty GUI screen code (e.g. XML file) you must call the `(int x, int y)` method without any parameters!

    <interact onClick="clicked()"/>

You can name the method (here `clicked`) what ever you like, as long as you keep the argument syntax.

## Load Several XML Files

The basic Nifty GUI example showed how to use the `nifty.fromXML()` method to load one XML file containing all Nifty GUI screens. The following code sample shows how you can load several XML files into one nifty object. Loading several files with `nifty.addXml()` allows you to split up each screen into one XML file, instead of all into one hard-to-read XML file.

    NiftyJmeDisplay niftyDisplay = new NiftyJmeDisplay(assetManager, inputManager, audioRenderer, viewPort);
    Nifty nifty = niftyDisplay.getNifty();
    nifty.addXml("Interface/Screens/OptionsScreen.xml");
    nifty.addXml("Interface/Screens/StartScreen.xml");
    nifty.gotoScreen("startScreen");
    StartScreenControl screenControl = (StartScreenControl) nifty.getScreen("startScreen").getScreenController();
    OptionsScreenControl optionsControl = (OptionsScreenControl) nifty.getScreen("optionsScreen").getScreenController();
    stateManager.attach(screenControl);
    stateManager.attach(optionsControl);
    guiViewPort.addProcessor(niftyDisplay);

## Register additional explicit screen controllers

In addition to the `nifty.addXml()` methods to attach many nifty XML files, there exists a `nifty.registerScreenController()` method to explicitly attach more screen controllers.

The following code sample shows how you can explicitly attach several screen controllers before adding the XML file to nifty, which would otherwise cause nifty to implicitly instantiate the screen controller class.

    NiftyJmeDisplay niftyDisplay = new NiftyJmeDisplay(assetManager, inputManager, audioRenderer, viewPort);
    Nifty nifty = niftyDisplay.getNifty();

    nifty.registerScreenController(new OptionsScreenController(randomConstructorArgument));
    nifty.addXml("Interface/Screens/OptionsScreen.xml");

## Design Your Own Styles

By default, your Nifty XML screens use the built.in styles:

     <useStyles filename="nifty-default-styles.xml" />

But you can switch to a set of custom styles in your game project's asset directory like this:

     <useStyles filename="Interface/Styles/myCustomStyles.xml" />

Inside myCustomStyles.xml you define styles like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <nifty-styles>
      <useStyles filename="Interface/Styles/Font/myCustomFontStyle.xml" />
      <useStyles filename="Interface/Styles/Button/myCustomButtonStyle.xml" />
      <useStyles filename="Interface/Styles/Label/myCustomLabelStyle.xml" />
      ...
    </nifty-styles>

Learn more about how to create styles by looking at the
for ???nifty-style-black???. Copy it as a template and change it to create your own style.

Learn more from the NiftyGUI page:

gui, documentation, nifty, hud, click, state, states, sound, effect

view online version