MBM Documentation Release 3.1.f

Michel

Jul 03, 2021

Contents:

1 Mbm Engine 3 1.1 Another Game Engine!...... 3 1.2 Which version should I get?...... 4 1.3 Looking for binary?...... 4 1.4 Main Libraries And Status...... 4 1.5 Games made with mbm...... 5 1.6 Quick start guide...... 7

2 Scene 35 2.1 Main Scene’s flow...... 35 2.2 Scene’s functions...... 36 2.3 Example of Scene...... 38 2.4 Example of Scene class style...... 39 2.5 Example of Scene using coroutine...... 40

3 Table mbm 45 3.1 World...... 46 3.2 mbm...... 54 3.3 Texture...... 69 3.4 Shader...... 73 3.5 Miniz...... 77 3.6 Aes...... 78 3.7 Useful...... 79 3.8 Android...... 84

4 Table camera 87 4.1 Camera 2D methods...... 87 4.2 Camera 2D attributes...... 90 4.3 Camera 3D methods...... 91 4.4 Camera 3D attributes...... 96 4.5 User data acknowledgment...... 97

5 Table font 99 5.1 font methods...... 99 5.2 font methods with editor features...... 102 5.3 Creating a font programmatically...... 105

i 6 Table gif 109 6.1 gif methods...... 109

7 Table line 113 7.1 line methods...... 113 7.2 line shader...... 119

8 Table mesh 123 8.1 mesh methods...... 123 8.2 Creating a mesh programmatically...... 124 8.3 Importing mesh...... 130

9 Table meshDebug 133 9.1 Primitive options...... 133 9.2 static methods...... 137 9.3 meshDebug methods...... 139

10 Table particle 169 10.1 particle methods...... 169 10.2 particle attributes...... 186 10.3 Creating particle programmatically...... 187 10.4 Saving particle to a binary file...... 190

11 Table render2texture 193 11.1 render2texture methods...... 193

12 Table renderizable 203 12.1 Renderizable methods...... 203 12.2 Blending...... 213 12.3 Animation...... 216 12.4 Physics...... 224 12.5 Renderizable attributes...... 225 12.6 User data acknowledgment...... 227

13 Table shader 231 13.1 shader methods...... 231 13.2 pixel shader...... 252 13.3 vertex shader...... 304

14 Table shape 307 14.1 shape methods...... 307

15 Table sprite 317 15.1 sprite methods...... 317 15.2 Creating a sprite programmatically...... 318

16 Table text 331 16.1 text methods...... 331 16.2 text attributes...... 333 16.3 Creating a text programmatically...... 333

17 Table texture 335 17.1 texture methods...... 335 17.2 Creating a texture programmatically...... 336

ii 18 Table tile 339 18.1 tile map definitions...... 339 18.2 tile methods...... 341 18.3 tile object...... 351

19 Table timer 353 19.1 timer callback signature...... 353 19.2 timer methods...... 353 19.3 timer attributes...... 357 19.4 User data acknowledgment...... 357

20 Table vec2 359 20.1 vec2 methods...... 359 20.2 vec2 attributes...... 370 20.3 User data acknowledgment...... 370

21 Table vec3 373 21.1 vec3 methods...... 373 21.2 vec3 attributes...... 383 21.3 User data acknowledgment...... 383

22 Table audio 385 22.1 audio Methods...... 385

23 Editors 389 23.1 File Format...... 389 23.2 Sprite Maker...... 389 23.3 Font Maker...... 390 23.4 Particle Editor...... 395 23.5 Physic Editor...... 396 23.6 Shader Editor...... 399 23.7 Scene Editor...... 400 23.8 Asset Packager...... 406 23.9 Tile Map Editor...... 406 23.10 Texture Packer Editor...... 409

24 Modules 413 24.1 What is a Module?...... 413 24.2 Parsing OBJ wavefront...... 414

25 Module box2d 421 25.1 box2d Methods...... 422 25.2 box2d Body...... 436 25.3 box2d Joint...... 458

26 Module ImGui 499 26.1 Begin / End methods...... 499 26.2 Calc methods...... 512 26.3 Capture methods...... 513 26.4 Color methods...... 514 26.5 CreateContext...... 516 26.6 DestroyContext...... 516 26.7 Flag / Enum...... 516 26.8 General methods...... 525 26.9 Get methods...... 527

iii 26.10 ImDrawList...... 542 26.11 Is methods...... 563 26.12 Save / Load methods...... 574 26.13 Log methods...... 575 26.14 NewFrame / EndFrame...... 577 26.15 Open / Close methods...... 577 26.16 Pop methods...... 578 26.17 Push methods...... 580 26.18 Render...... 583 26.19 Set methods...... 583 26.20 Show methods...... 594 26.21 Style methods...... 596 26.22 Text methods...... 602 26.23 Widgets...... 603

27 Module lsqlite3 651 27.1 Asset...... 651 27.2 Editor...... 656 27.3 Examples...... 656

28 Indices and tables 659

Index 661

iv MBM Documentation, Release 3.1.f

Table of Contents

• Mbm Engine – Another Game Engine! – Which version should I get? – Looking for binary? – Main Libraries And Status – Games made with mbm

* Tower defense * Space ship combat * Puzzle from photos – Quick start guide

* Getting the * Build for Windows * Binary for Windows * Build for * Build for Android * Binary for Android * Command line usage

Contents: 1 MBM Documentation, Release 3.1.f

2 Contents: CHAPTER 1

Mbm Engine

MBM is a given name to a graphics engine which provides basic and essential resources to develop games or graphics applications 2D or 3D. For now, is possible to develop games for Windows , Linux , and Android . The intention is to provide the minimum necessary for game development or graphics application using minimal dependencies. The engine is written in C++11 language using OpenGL-ES on its core and LUA as a scripting language.

Note: Although there is an effort to migrate the whole project to C++11 still there is a lot of mixedC code and maybe is not the best project to be as an example!

1.1 Another Game Engine!

Yes I know! This is a personal project that I have been working for a long time (~ 2004). It started as a way to understand C++, DirectX, 2D, 3D, geometry etc (at the time). How games in general works. Then, I have learned more about game programming and, in the beginning, it was used the concept of framework a lot, which later, became a game engine embeding LUA script. Of course, I had (and still have) to do a lot of improvement/refactoring and also make new features as well! (You might find some comments or variable names in portuguese BR since at the time I used to program in my on language ¯\_()_/¯) But life is the greatest teacher and I have decided to go ahead and make new features, improvements or refactoring according to the demands. It means that when some work in as a new game requires some feature or improvements it is implemented.

3 MBM Documentation, Release 3.1.f

So, if you want to use it, go ahead and occasionally new features or improvements will come (¬¬).

1.2 Which version should I get?

I occasionally tag versions however it is generally safe and recommended to sync to the master. The library is fairly stable for 2D applications and issues tend to be fixed as fast as reported/faced.

1.3 Looking for binary?

Here the latest binaries for Windows. Here the latest binaries for Android. For Linux you must compile by yourself.

1.4 Main Libraries And Status

Library Version Windows Linux Android Required Status OpenGL ES 2.0 YES YES YES YES Complete ANGLE 2.0 YES NO NO Windows Complete LUA 5.4.1 YES YES YES NO Complete LodePNG 20151024 YES YES YES YES Complete Box 2D 2.3.1 YES YES YES NO Stable physics Bullet 3D 2.84 YES YES YES NO in Progress physics LuaSQLite 3 0.9.5 YES YES YES NO Complete SQLite 3 3.24 YES YES YES NO Complete AESCrypt 3.0.9 YES YES YES NO Complete Audiere 1.9.4 YES NO NO Windows Complete PlusWindows 1.0 YES NO NO Windows Complete STB True 1.11 YES YES YES YES Complete Type MiniZ 1.16 YES YES YES YES Complete ImGui 1.75 YES YES NO NO Stable Audiere Native Audio • • NO in Progress

OpenGL ES OpenGL ES is a royalty-free, cross-platform API for rendering advanced 2D and 3D graph- ics on embedded and mobile systems - including consoles, phones, appliances and vehicles. It con- sists of a well-defined subset of desktop OpenGL suitable for low-power devices, and provides a flexible and powerful interface between software and graphics acceleration hardware. Angle Almost Native Graphics Layer Engine. The goal of ANGLE is to allow users of multiple operating systems to seamlessly run OpenGL ES content by translating OpenGL ES API calls to one of the hardware-supported available for that platform. LUA LUA is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming,

4 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

and data description. Although the main feature of this engine is to have LUA script as main way to develop, is not mandatory. You can, if you want, develop in pure C++. LodePNG LodePNG is a PNG image decoder and encoder, all in one, no dependency or linkage to zlib or libpng required. It’s made for C (ISO C90), and has a C++ wrapper with a more convenient interface on top. Box2D Box2D is an open source C++ engine for simulating rigid bodies in 2D. it is available as plugin. The flag to use it in Android is USE_BOX2D. Bullet 3D Bullet 3D is an open source C++ engine for simulating rigid bodies in 3D. It is available as external plugin/module however it is not ready yet :/. LuaSQLite 3 Available as plugin, LuaSQLite 3 is a thin wrapper around the public domain SQLite3 database engine. The flag to use it in Android is USE_LSQLITE3. SQLite 3 SQLite is a C-language library that implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine. It is part of the lsqlite3. AES Crypt AES Crypt is a file encryption API that uses standard Advanced Encryption Standard (AES) to easily and securely encrypt files. Although is not mandatory, it is implicit added to the engine. Audiere Audiere is a audio API. It can play Ogg , MP3, FLAC, uncompressed WAV, AIFF, MOD, S3M, XM, and IT files. It is required only on Windows for now. PlusWindows PlusWindows is a simple library for creating Owner-Drawn components on Windows . It is required only on Windows. STB True Type Do parse, decode, and rasterize characters from true type fonts. MiniZ Miniz is a lossless, high performance data compression library that implements the zlib (RFC 1950) and Deflate (RFC 1951) compressed data format specification standards. ImGui An immediate graphical user interface for C ++ with minimal dependencies. It is mainly used for editor. it is available as plugin. The flag to use it in Android is USE_IMGUI. Audio Unfortunately, this is still time consuming and not every platform is easy to handle with a common built-in music library. The main focus of the engine is graphics, so, for now, we will keep these libraries.

1.5 Games made with mbm

Here some games made using the engine:

1.5.1 Tower defense

This game is still under development.

1.5. Games made with mbm 5 MBM Documentation, Release 3.1.f

1.5.2 Space ship combat

6 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

1.5.3 Puzzle from photos

Let us know if you have some game built using the engine :)

1.6 Quick start guide

Here a quickly description how to build the engine selecting the environment. For now, the engine is available for Windows Linux and Android. More platforms are coming soon!

1.6. Quick start guide 7 MBM Documentation, Release 3.1.f

1.6.1 Getting the source code

Here the needed steps: Get git Install git and clone the project: $ git clone https://bitbucket.org/michel-morais/mini-mbm.git Download instead You also can download the project: https://bitbucket.org/michel-morais/mini-mbm/downloads/

1.6.2 Build for Windows

Install Visual Studio 2019 or above. You might need C++ tools for Visual Studio to be able to compile. Find the solution Go to the folder mini-mbm/platform-msvs/ Open mini-mbm.sln solution:

Figure 1.1: Building project on Visual Studio

Build Find the button Build Solution on Visual Studio and build it: In the end, you should have all project inside the solution built. Now, let’s create an example. . . Main lua let’s create a text file called main.lua in the Windows’Desktop Rename it for main.lua Copy and paste this code:

8 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

Figure 1.2: Building project on Visual Studio

mbm.setColor(1,1,1) --white background

tTexture= texture:new('2dw') --texture mesh

tTexture:load('HB_smile.png') -- load our texture

Next let’s use the following image: Download the HB_smile.png to Desktop folder: download HB_smile. Set the debug properties on Visual Studio to your just created scene main.lua : $ --scene "C:.lua" -w 800 -h 600

Note: Of course your path would be different then this.

Finally, when you run you should be able to see the first scene being loaded:

1.6.3 Binary for Windows

You can get the binaries for Windows here: download mini-mbm-windows-3.2f.zip. What’s in this folder?

1.6.4 Build for Linux

Tools As root install cmake clang g++ gcc build-essential libgles2-mesa-dev libreadline-dev. $ apt-get cmake $ apt-get clang

1.6. Quick start guide 9 MBM Documentation, Release 3.1.f

Figure 1.3: Building project on Visual Studio / Create a empty file and rename it to main.lua

Figure 1.4: Creating a new project on Visual Studio / HB_smile.png

10 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

Figure 1.5: Building project on Visual Studio / debug properties on Visual Studio

$ apt-get g++ $ apt-get gcc $ apt-get install build-essential $ apt-get install libgles2-mesa-dev $ apt-get install libreadline-dev Or As sudo install cmake clang g++ gcc build-essential libgles2-mesa-dev libreadline-dev. $ sudo apt-get cmake $ sudo apt-get clang $ sudo apt-get g++ $ sudo apt-get gcc $ sudo apt-get install build-essential $ sudo apt-get install libgles2-mesa-dev $ sudo apt-get install libreadline-dev Compile Audiere From project folder, install osspd, go to third-party/audiere-1.9.4, config- ure and compile. mini-mbm/$ sudo apt-get install osspd mini-mbm/$ cd third-party/audiere-1.9.4 mini-mbm/$ chmod 777 configure mini-mbm/$ ./configure mini-mbm/$ make Alternative Audiere As described here (https://github.com/poikilos/Audiere/releases), you can install it from this fork: $ cd /tmp $ wget https://github.com/expertmm/Audiere/releases/download/1.10.1/audiere-1.10.1.tar.gz $ tar -xzf audiere-1.10.1.tar.gz $ cd audiere-1.10.1

1.6. Quick start guide 11 MBM Documentation, Release 3.1.f

Figure 1.6: Building project on Visual Studio / First scene

12 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

Figure 1.7: Content of mini-mbm-windows-3.2f.zip for Windows

1.6. Quick start guide 13 MBM Documentation, Release 3.1.f

$ ./configure $ make $ sudo make install

Note: Audiere for linux is only available on audiere_linux branch.

Create a folder Go to the project folder and create a folder build. mini-mbm/$ mkdir build mini-mbm/$ cd build/ Cmake To build your project you must to select a platform and which feature are you going to include: In this case the platform is Linux and we want to include everything (modules and third party libs): mini-mbm/build$ cmake .. -DPLAT=Linux -DUSE_ALL=1 -DCMAKE_BUILD_TYPE=Release Make Now you just need to compile typing make. mini-mbm/build$ make mini-mbm/build$ # or mini-mbm/build$ make -j8 # 8 threads to be faster In the end, it will show you where the folder is, what is the size and what was built:

Figure 1.8: Building for Linux

1.6.5 Build for Android

For Android we are using Linux environment. Tools As root install cmake clang g++ gcc build-essential. $ apt-get cmake $ apt-get clang $ apt-get g++ $ apt-get gcc $ apt-get install build-essential Or As sudo install cmake clang g++ gcc build-essential. $ sudo apt-get cmake $ sudo apt-get clang

14 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

$ sudo apt-get g++ $ sudo apt-get gcc $ sudo apt-get install build-essential NDK For Android is necessary NDK. The engine is using the Android ndk r21b version. Download, extract and export the variable NDK_ROOT to that folder: $ export NDK_ROOT=your-path/android-ndk-r21b

Tip: You can add export NDK_ROOT=your-path/android-ndk-r21b in your .bashrc if you want.

Note: You should not have problem using a major version then r21b. If you have, please let me know.

Create a folder to build Go to the project folder and create a folder build mini-mbm/$ mkdir build mini-mbm/$ cd build/ Cmake To build your project you must to select a platform and which feature are you going to include: In this case the platform is Android and we want to include only LUA (modules and third party libs): You also need to specify the architecture. Cmake will set to default if not specified.

Important: Since Android 7.0, the system prevents apps from dynamically linking against non-NDK libraries. https://developer.android.com/about/versions/nougat/android-7.0-changes.html#ndk For this reason, you have to specify which libraries are you going to use together (box2d, ImGui, lsqlite3 etc ). We do this through the command USE when invoking Cmake: -USE_LSQLITE3=1, -DUSE_IMGUI=1, -DUSE_BOX2D=1, etc. . .

mini-mbm/build$ cmake .. -DPLAT=Android -DANDROID_ABI=arm64-v8a -DUSE_LUA=1 -DCMAKE_BUILD_TYPE=Release Make Now you just need to compile typing make: mini-mbm/build$ make mini-mbm/build$ # or mini-mbm/build$ make -j8 # 8 threads to be faster In the end, it will show you where the folder is, what is the size and what was built:

Note: The needed libraries are libcore_mbm.so, libmini-mbm.so, liblua-5.2.2.so and libc++_shared.so.

The libraries ImGui.so, box2d.so, lsqlite3.so and others plugins are only necessary if will be used in your project. In the figure above, we have not added any plug-in options, so it is not generated any of ImGui.so, box2d.so or lsqlite3.so.

For Android there are more steps to do. . . Install Android Studio You need to install Android Studio. Go to https://developer.android.com/studio download and install Android Studio.

1.6. Quick start guide 15 MBM Documentation, Release 3.1.f

Figure 1.9: Building for Android

Note: You might need to install the latest SDK. At this point the minimum version is Android 4.1.3 (Ice Scream Sandwich).

Create a project Now open Android Studio and create a new project: Select Add No Activity option: Give a name for your project Let’s call it My First Game. Set the language to Java The project has some dependencies on JNI and you must use Java as interface. Folder com/mini/mbm You must to copy the interfaces to the right folder: Go to mini-mbm/platform-android folder and copy the folder com/mini/mbm and its sub-folder to your-project-android/app/src/main/java/com/mini/mbm. mini-mbm/platform-android$ cp -r com ~/AndroidStudioProjects/MyFirstGame/app/src/main/java/com The folder on Android Studio should be like this:

Then After Android Studio update the indices, you will be able to add a new class: Add a class which will extend of the main class of the engine. Let’s call it Main. Main Create a class Main.java which extend from com.mini.mbm.MainJniEngine: Implement Use Android Studio option to implement abstract methods: Your Main class should be like this: package com.example.myfirstgame; import android.content.Intent; import android.graphics.Point; import android.os.Bundle; import com.mini.mbm.MainJniEngine; public final class Main extends MainJniEngine { @Override (continues on next page)

16 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

Figure 1.10: Creating a new project on Android Studio

1.6. Quick start guide 17 MBM Documentation, Release 3.1.f

Figure 1.11: Creating a new project on Android Studio / Add No Activity

18 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

Figure 1.12: Creating a new project on Android Studio / Configure the project

1.6. Quick start guide 19 MBM Documentation, Release 3.1.f

Figure 1.13: Creating a new project on Android Studio / copy com/mini/mbm folder

20 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

Figure 1.14: Creating a new project on Android Studio / Add a class “Main.java”

1.6. Quick start guide 21 MBM Documentation, Release 3.1.f

Figure 1.15: Creating a new project on Android Studio / Class “Main.java” extend from “MainJniEngine”

22 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

Figure 1.16: Creating a new project on Android Studio / implement abstract methods

1.6. Quick start guide 23 MBM Documentation, Release 3.1.f

(continued from previous page) public String getMyVersionAPP() { return null; }

@Override public int getMaxSimultaneousStreams() { return 0; }

@Override public Point getExpectedSizeOfWindow() { return null; }

@Override public String OnDoCommands(String key, String param) { return null; }

@Override public void OnCreate(Bundle icicle) {

}

@Override public void OnResume() {

}

@Override public void OnStart() {

}

@Override public void OnPause() {

}

@Override public void OnStop() {

}

@Override public void OnDestroy() {

}

@Override public void OnActivityResult(int requestCode, int resultCode, Intent data) {

}

@Override public void OnPostCreate(Bundle savedInstanceState) {

(continues on next page)

24 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

(continued from previous page) } }

Libs Now you need to copy the needed libraries to the right folder. Here a table showing the right folders depend on ABI:

ABI Folder Comment arm64-v8a yourProject/app/src/main/ (principal 64) ARMv8 AArch64 instruction set - jniLibs/arm64-v8a/ since NDK r10 (mandatory) armeabi-v7a yourProject/app/src/main/ (principal) ARMv7 based devices with hardware jniLibs/armeabi-v7a/ FPU instructions (VFPv3_D16) armeabi-v7a yourProject/app/src/main/ Same as armeabi-v7a, but sets NEON as with NEON jniLibs/armeabi-v7a/ floating-point unit armeabi-v7a yourProject/app/src/main/ same as armeabi-v7a, but sets VFPv3_D32 as with VFPV3 jniLibs/armeabi-v7a/ floating-point unit x86 yourProject/app/src/main/ IA-32 instruction set jniLibs/x86/ mips yourProject/app/src/main/ MIPS32 instruction set jniLibs/mips/ mips64 yourProject/app/src/main/ MIPS64 instruction set (r6) - since NDK r10 jniLibs/mips64/ x86_64 yourProject/app/src/main/ Intel64 instruction set (r1) - since NDK r10 jniLibs/x86_64/

Note: The ABI option can be set when you invoke cmake setting the argument ANDROID_ABI Examples: mini-mbm/build$ cmake .. -DPLAT=Android -DANDROID_ABI=arm64-v8a -DUSE_LUA=1 -DCMAKE_BUILD_TYPE=Release mini-mbm/build$ cmake .. -DPLAT=Android -DANDROID_ABI=armeabi-v7a -DUSE_LUA=1 -DCMAKE_BUILD_TYPE=Release mini-mbm/build$ cmake .. -DPLAT=Android -DANDROID_ABI=x86 -DUSE_LUA=1 -DCMAKE_BUILD_TYPE=Release

Important: Whenever you change the ABI, clean the whole folder. On build folder do: mini-mbm/build$ make clean mini-mbm/build$ rm -rf * Then do the cmake command selecting the ABI again.

Now, let’s create the jniLibs folder: mini-mbm/platform-android$ mkdir ~/AndroidStudioProjects/MyFirstGame/app/src/main/jniLibs Then for this example, we will copy the folder arm64-v8a within its libs inside to the jniLibs folder. We remove the libraries that we do not use. mini-mbm/$ cp -r bin/release/arm64-v8a/ ~/AndroidStudioProjects/MyFirstGame/app/src/main/jniLibs Android Studio will look like this: Android Manifest Now you need to update the AndroidManifest.xml: Here the default AndroidManifest.xml:

1.6. Quick start guide 25 MBM Documentation, Release 3.1.f

26 Chapter 1. Mbm Engine

Figure 1.17: Creating a new project on Android Studio / jniLibs libraries. MBM Documentation, Release 3.1.f

Update Android Manifest You need to update according to project:

1.6. Quick start guide 27 MBM Documentation, Release 3.1.f

Assets For your scripts, textures, binary files, etc, you must to add them in the folder assets. Let’s create the assets folder in the right place: mini-mbm/platform-android$ mkdir ~/AndroidStudioProjects/MyFirstGame/app/src/main/assets Let’s create a sub-folder to organize some textures: mini-mbm/platform-android$ mkdir ~/AndroidStudioProjects/MyFirstGame/app/src/main/assets/textures Main lua Next let’s create a file called main.lua inside the assets folder.

mbm.addPath('textures') --sub folder to search images

tTexture= texture:new('2dw') --texture mesh

tTexture:load('HB_smile.png') -- load our texture

Let’s copy the image HB_smile.png to assets/textures folder:

Figure 1.18: Creating a new project on Android Studio / HB_smile.png into assets/textures folder

download HB_smile. The final structure should be like this:

Tip: Every time that you update the folder assets you MUST update the internal version: This is the way the engine organize to update from asset folders.

Tip: Always use LUA files encoded to UTF8. Here a script to help you using iconv:

28 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

Figure 1.19: Creating a new project on Android Studio / assets structure

Figure 1.20: Update the return of the method getMyVersionAPP.

1.6. Quick start guide 29 MBM Documentation, Release 3.1.f

$ find . -type f -iname *.lua -exec sh -c 'iconv -f $(file -bi "$1" |sed -e "s/.*[ ]charset=//") -t utf-8 -o converted "$1" && mv converted "$1"' -- This avoid some error on interpret LUA files.

Run At this point, you should be able to run the project. The Log cat in the Android Studio shall logs some useful information.

Figure 1.21: Creating a new project on Android Studio / Running / Log cat

1.6.6 Binary for Android

Even though you have some doubt? Here the project using Android Studio version 3.5.3 : Example full project here Or just would like to take a look on the apk generated? download example apk for Android Or the latest libraries to get start at Android? binary libs for Android version 3.2.a It contains the core of engine and LUA script support to start to develop on Android:

Note: The needed libraries are libcore_mbm.so, libmini-mbm.so, liblua-5.2.2.so and libc++_shared.so. The libraries like ImGui.so, box2d.so, lsqlite3.so and others are plugins and they are only necessary if will be used in your project. If you wish to add any of libraries (plugins) it is necessary to compile with theirs respective flags.

30 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

1.6. Quick start guide 31 MBM Documentation, Release 3.1.f

Important: Since Android 7.0, the system prevents apps from dynamically linking against non-NDK libraries. https://developer.android.com/about/versions/nougat/android-7.0-changes.html#ndk For this reason, you have to specify which libraries are you going to use together (box2d, ImGui, sqlite, etc ). We do this through the flag USE when invoking Cmake: -USE_LSQLITE3=1, -DUSE_IMGUI=1, -DUSE_BOX2D=1, etc. . .

1.6.7 Command line usage

Command line options: mini-mbm Version:3.1.b Usage: mini-mbm [options]... [file_name.lua] or [--scene file_name.lua]... --help display this help -w, --width set window's width -h, --height set window's height -ew,--expectedwidth set expected window's width -eh,--expectedheight set expected window's height --stretch stretch to axis ('x', 'y', or 'xy') default is 'y' --nosplash do not display logo -x, --posx set x window's position -y, --posy set y window's position -s, --scene set scene to load (e.g.: main.lua) -n, --name set window's name -a, --addpath add path to search file at run time --noborder new window without border

note: to add a global variable use '='. example: 'myVarNumber=5.0' 'stringVar=someString' the variable will be stored as number when is number. otherwise the variable will be stored as string. use getGlobal function to get variable at lua script (see doc for more

˓→information)

use space to separate arguments: usage example: mini-mbm --scene main.lua -w 800 -h 600 mini-mbm -s main.lua -w 800 -h 600 'myVarNumber=5.0' 'stringVar=someString

˓→' --nosplash

Table of Contents

• Scene – Main Scene’s flow

* onInitScene * loop * onEndScene

32 Chapter 1. Mbm Engine MBM Documentation, Release 3.1.f

* onRestore – Scene’s functions

* onTouchDown * onTouchUp * onTouchMove * onTouchZoom * onKeyDown * onKeyUp * onInfoJoystick * onKeyDownJoystick * onKeyUpJoystick * onMoveJoystick – Example of Scene – Example of Scene class style – Example of Scene using coroutine

1.6. Quick start guide 33 MBM Documentation, Release 3.1.f

34 Chapter 1. Mbm Engine CHAPTER 2

Scene

Most games use scene mechanism. This engine is no different. When we have a new scene, the previous scene is destroyed and the new scene will become the current scene. It means that only the current scene exists when see the game. This is how scenes in general works. All we need, is to overload functions in the scene script that will be called by the engine. There are a default scene internally. If any function does not exist, the default function is called. Now, let’s see the main flow of a scene:

2.1 Main Scene’s flow

All functions described here can be overloaded.

2.1.1 onInitScene onInitScene The engine will call this method only once during the execution’s script.

2.1.2 loop loop(delta) Called each step. Delta indicate the interval passed since the last step. Parameters number – delta time passed since the last step.

35 MBM Documentation, Release 3.1.f

2.1.3 onEndScene

onEndScene The engine will call this method only once during the scene’ ending. The end of scene occurs when other scene is called or the application is shut down.

2.1.4 onRestore

onRestore Called on restore scene. This usually happen when the device is lost.

2.2 Scene’s functions

2.2.1 onTouchDown

onTouchDown(number key, number x, number y) Called on touch down or click down on screen 2d. Parameters • number – key mouse click or finger on touch screen (start from 1). • number – x coordinate (left is 0). • number – y coordinate (up is 0).

2.2.2 onTouchUp onTouchUp(number key, number x, number y) Called on touch up or click up on screen 2d. Parameters • number – key mouse click or finger on touch screen (start from 1). • number – x coordinate (left is 0). • number – y coordinate (up is 0).

2.2.3 onTouchMove onTouchMove(number key, number x, number y) Called on touch move (mouse or finger) on screen 2d. Parameters • number – key mouse or finger on touch screen (start from 1). • number – x coordinate (left is 0). • number – y coordinate (up is 0).

36 Chapter 2. Scene MBM Documentation, Release 3.1.f

2.2.4 onTouchZoom

onTouchZoom(number zoom) Called on zoom gesture or mouse scroll (values will be -1 and 1). Parameters number – zoom values between -1 and 1.

2.2.5 onKeyDown onKeyDown(number key) Called on key down. Parameters number – key depends on system operation. the engine offers a function getCode and getKey translator for comparison.

2.2.6 onKeyUp

onKeyUp(number key) Called on key up. Parameters number – key depends on system operation. the engine offers a function getCode and getKey translator for comparison.

2.2.7 onInfoJoystick

onInfoJoystick(number player, number maxButtons, string deviceName, string extra) Called on connect joystick. depends on system operation and joystick brand. Parameters • number – player indicate the player number. • number – maxButtons information about how many buttons are available in this joystick. • string – deviceName Joystick’s name. information from device. • string – extra It might have extra information about the joystick.

2.2.8 onKeyDownJoystick onKeyDownJoystick(number player, number key) Called on joystick key down. Parameters • number – player indicate the player number. • number – key pressed on joystick.

2.2.9 onKeyUpJoystick onKeyUpJoystick(number player, number key) Called on joystick key up. Parameters

2.2. Scene’s functions 37 MBM Documentation, Release 3.1.f

• number – player indicate the player number. • number – key pressed on joystick.

2.2.10 onMoveJoystick onMoveJoystick(number player, number lx, number ly, number rx, number ry) Called on joystick move Parameters • number – player indicate the player number. • number – lx left pad on x axis. • number – ly left pad on y axis. • number – rx right pad on x axis. • number – ry right pad on y axis.

Attention: Although the Joystick’s functions had been tested including some joystick available on the market, there are a lot of them. Might not work properly on some devices.

2.3 Example of Scene

Next we will use the following image to play with some scene’s example:

Figure 2.1: crate.png

--example of scene function onInitScene() tTexture= texture:new('2ds') --tTexture is global for the scene tTexture:load('crate.png') --just load the texture (does not care if not found

˓→the texture) tTexture:setScale(0.5,0.5) --adjust the scale end function onTouchMove(key,x,y) (continues on next page)

38 Chapter 2. Scene MBM Documentation, Release 3.1.f

(continued from previous page) tTexture:setPos(x,y) --move according to mouse or touch (we are ignoring the key) end function onTouchDown(key,x,y) local tTextureTmp= texture:new('2ds',x,y) -- create a new local texture. ***this ˓→will be collected by GC*** tTextureTmp:load('crate.png') --Load it tTextureTmp:setScale(0.5,0.5)--adjust the scale tTextureTmp.az= tTexture.az -- adjust the rotation on z angle tTexture.z= tTextureTmp.z-1 --bring to front end function loop(delta) tTexture:rotate('z',math.rad(30)) -- rotate 30 degree per second on z angle end download crate.png download.

2.4 Example of Scene class style

--example of scene class style

local tMyClass={}

tMyClass.onInitScene= function (self) self.tMyTexture= texture:new('2ds') --texture is part of tMyClass now self.tMyTexture:load('crate.png') -- just load the texture (does not

˓→care if not found the texture) self.tMyTexture:setScale(0.5,0.5) --adjust the scale

end

tMyClass.onTouchMove= function(self,key, x,y) self.tMyTexture:setPos(x,y) --move according to mouse or touch (we are

˓→ignoring the key) end

tMyClass.loop= function(self,delta) self.tMyTexture:rotate('z',math.rad(30)) -- rotate 30 degree per second

˓→on z angle end

tMyClass.onTouchDown= function(self,key, x,y) local tTextureTmp= texture:new('2ds',x,y) -- create a new local texture. ˓→***this will be collected by GC*** tTextureTmp:load('crate.png') --Load it tTextureTmp:setScale(0.5,0.5)--adjust the scale tTextureTmp.az= self.tMyTexture.az -- adjust the rotation on z angle self.tMyTexture.z= tTextureTmp.z-1 --bring to front end

(continues on next page)

2.4. Example of Scene class style 39 MBM Documentation, Release 3.1.f

(continued from previous page) local w, h= mbm.getSizeScreen()

--[[ important return the class otherwise won't work ]]

return tMyClass

download.

Figure 2.2: Both scene normal style and scene using class style running.

Important: Both scene normal style and scene using class style produce the same result. In both case, we are not storing the local texture and occasionally will be collected (destroyed).

2.5 Example of Scene using coroutine

By default, scene using class style has coroutine which is a way to divide the initial load in severals steps. Every time that you call coroutine.yield function from lua, there is an interruption and the engine does a loop of render. Below an example of that:

--example of scene using coroutine class style local tMyClass={} tMyClass.onInitScene= function(self) self.tTextures={} for i=1,91 do --we put 91 just to understand how show Loading works (91 represent

˓→the end of the loop (100%)) local x=i * 10 local y=i * 10 local tTexture= texture:new('2ds',x,y) --tTexture is local tTexture:load('crate.png') --just load the texture (does not care if not

˓→found the texture) tTexture:setScale(0.5,0.5) --adjust the scale table.insert(self.tTextures,tTexture) --save tTexture to a table (will not be

˓→destroyed anymore) --call coroutine.yield informing the percentage (1 to 100) which is not

˓→mandatory --could be coroutine.yield() but in this case, will not call onProgress method coroutine.yield(i) end end

--This function only exist for class style and using coroutine --This function is called each step if passed the progress to coroutine.yield

˓→(current and total steps) (continues on next page)

40 Chapter 2. Scene MBM Documentation, Release 3.1.f

(continued from previous page) tMyClass.onProgress= function(self,percent) print(string.format('loaded: %.0f%%',percent)) end tMyClass.onTouchMove= function(self,key,x,y) self.tTextures[#self.tTextures]:setPos(x,y) --move according to mouse or touch

˓→(we are ignoring the key) end tMyClass.onTouchDown= function(self,key,x,y) local tTexture= texture:new('2ds',x,y) -- create a new local texture. tTexture:load('crate.png') --Load it tTexture:setScale(0.5,0.5)--adjust the scale tTexture.az= self.tTextures[#self.tTextures].az -- adjust the rotation on z angle self.tTextures[#self.tTextures].z= tTexture.z-1 --bring to front table.insert(self.tTextures,tTexture) end tMyClass.loop= function(self,delta) for i=1,#self.tTextures do local tTexture= self.tTextures[i] tTexture:rotate('z',math.rad(30)) -- rotate 30 degree per second on z angle end end

--[[ important return the class otherwise won't work ]] return tMyClass download.

Figure 2.3: A scene using class style running using coroutine.

Table of Contents

• Table mbm – World – mbm

* addPath * allPaths * Callback · addOnTouch

* Dialogs · openFile · openMultiFile · saveFile

2.5. Example of Scene using coroutine 41 MBM Documentation, Release 3.1.f

Figure 2.4: The output in the console.

· openFolder · messageBox · inputBox · inputPassword

* FPS · getFps · setFps · setFakeFps

* Global · setGlobal · getGlobal · clearGlobals

* getCamera * get * getSplash * include * loadScene

42 Chapter 2. Scene MBM Documentation, Release 3.1.f

* print * pause * resume * Screen · enableClearScreen · getSizeScreen · getRealSizeScreen · getDisplayMetrics

* setColor * Transform · to2dw · to2ds · to3d

* showConsole * getObjectsRendered * quit – Texture

* Supported image types * createTexture * existTexture * loadTexture – Shader

* getShaderList * existShader * addShader – Miniz

* compress * decompress – Aes

* encrypt * decrypt – Useful

* shuffle * undoShuffle * existFile

2.5. Example of Scene using coroutine 43 MBM Documentation, Release 3.1.f

* getPathEngine * getFullPath * onErrorStop * getKeyName * getKeyCode * isCapitalKeyOn * getIdiom * getUserName * getSceneName * refresh * listFiles – Android

* doCommands * luaFunction

44 Chapter 2. Scene CHAPTER 3

Table mbm

The engine provides a global table (mbm ) to access some useful functions. Let’s start explaining how is organized the renderization through the worlds.

45 MBM Documentation, Release 3.1.f

3.1 World

Explaining how orientation and world works.

World is the way that scene sorts renderizable to be render.

Here the table shows the order to be render:

46 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Order to render world z order Example 1st 3D 1st -2 tMesh = 2nd -1 mesh:new('3D', 3th 0 0,0,-2) 4th 1 tMesh = mesh:new('3D', 5th 2 0,0,-1) tMesh = mesh:new('3D', 0,0,0) tMesh = mesh:new('3D', 0,0,1) tMesh = mesh:new('3D', 0,0,2)

2nd 2DW 1st -2 tSprite = 2nd -1 sprite:new('2DW', 3th 0 0,0,-2) 4th 1 tSprite = sprite:new('2DW', 5th 2 0,0,-1) tSprite = sprite:new('2DW', 0,0,0) tSprite = sprite:new('2DW', 0,0,1) tSprite = sprite:new('2DW', 0,0,2)

3th 2DS 1st -2 tTexture = 2nd -1 texture:new('2DS', 0,0,-2) 3th 0 tTexture = 4th 1 texture:new('2DS', 2 5th 0,0,-1) tTexture = texture:new('2DS', 0,0,0) tTexture = texture:new('2DS', 0,0,1) tTexture = texture:new('2DS', 0,0,2)

3.1. World 47 MBM Documentation, Release 3.1.f

Follow the explanation of how each world works.

The engine provides 3 type of worlds. Each renderizable only can belong to one world. You can specify the world in the renderizable ‘s constructor. The default world is 2DW if not specified. All renderizable has the same option in constructor which is the world and initial position. The position is composed by x, y and z. The z position is what determines the order to render as described on table above.

The world is independent on orientation. See below how portrait orientation and landscape orientation are:

Figure 3.1: Portrait orientation

Note: Regardless the orientation, the coordinates will be according to the world chosen.

48 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Figure 3.2: Landscape orientation

Figure 3.3: crate.png

3.1. World 49 MBM Documentation, Release 3.1.f

For the explanation of world, we will use the following image:

download crate.png

Next, an explanation about the coordinates and cameras.

• A 2DS renderizable is for X,Y coordinates at main screen and do not has camera. – The origin for 2DS is on top-left screen. – The axis X increment to the right. – The axis Y increment down.

2D screen coordinates (portrait orientation)

Figure 3.4: Portrait orientation

Example:

tTexture= texture:new('2DS') if tTexture:load('crate.png') then tTexture:setSize(100,100) end

2D screen coordinates (landscape orientation)

Example:

50 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Figure 3.5: Texture crate.png, 2DS, at 0,0 position and portrait orientation.

Figure 3.6: Landscape orientation

3.1. World 51 MBM Documentation, Release 3.1.f

tTexture= texture:new('2DS') if tTexture:load('crate.png') then tTexture:setSize(100,100) end

Figure 3.7: Texture crate.png, 2DS, at 0,0 position and landscape orientation.

• A 2DW renderizable is for X,Y coordinates in the world and has its own camera. – The origin for 2dw is on center of screen. – The axis X increment to the right. – The axis Y axis increment up.

Figure 3.8: 2D world coordinates (landscape orientation)

Example: tTexture= texture:new('2DW') if tTexture:load('crate.png') then tTexture:setSize(100,100) end

• A 3D renderizable is for 3d coordinates world and has its own camera (independent from 2D). – The origin for 3D is on center of screen.

52 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Figure 3.9: Texture crate.png, 2DW, at 0,0 position and portrait orientation.

3.1. World 53 MBM Documentation, Release 3.1.f

– The axis X increment to the right. – The axis Y increment up. – The axis Z increment in direction to inside the screen.

Figure 3.10: 3D world coordinates (landscape orientation) Example: tTexture= texture:new('3D') if tTexture:load('crate.png') then tTexture:setSize(100,100) end

3.2 mbm

The engine provides a global table (mbm ) to access some useful functions as explained. These functions are described below.

3.2.1 addPath addPath(string newPath) Add a path to search files. This command will feed an internal path list in the engine. The path is used to search file on registered folder. Parameters string – Full path or partial path folder path. Example: if mbm.get("Windows") then mbm.addPath("C:\\my_folder_images") elseif mbm.get("Linux") then mbm.addPath("/var/opt/my_folder_images") elseif mbm.get("Android") then mbm.addPath("my_folder_images") end

3.2.2 allPaths getAllPaths

54 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Retrieve all path known by the engine. return table - tPaths with all paths Example: local tPaths= mbm.getAllPaths() for i=1,#tPaths do print(tPaths[i]) end

3.2.3 Callback addOnTouch addOnTouch(table renderizable, function callback) Add a call back function to a renderizable object to be called when it is touched.

Parameters • table – renderizable object. • function – callback function. Also can be as string.

Example:

--The function has to be the following signature: function onTouchSprite(self, x, y,key) --here we set anim 'break' when is touched. This is an example. self:setAnim('break') end ------it works informing the function name as string: -- mbm.addOnTouch(tMySprite,'onTouchSprite') ------it works informing the literal function: mbm.addOnTouch(tMySprite,onTouchSprite) ------it works informing the anonymous function: -- mbm.addOnTouch(tMySprite, function (self, x, y,key) -- anonymous self:setAnim('break') end)

3.2.4 Dialogs

3.2. mbm 55 MBM Documentation, Release 3.1.f openFile openFile(string defaultFileName*, string extension*, ...) Call a native dialog box to get a file (full path) pointing the defaultFileName and extension allowed. This method does not work on Android.

Parameters • string – default file name as input. • string – extension filter to be applied. Can be 0 or more extensions. Returns string - fileName for success or nil to canceled

Example: local filename= mbm.openFile('mario.png',' *.png','*.jpeg') if filename then print("File",filename) end openMultiFile openMultiFile(string defaultFileName*, string extension*, ...) Call a native dialog box to get one or more files (full path) pointing the defaultFileName and extension allowed. This method does not work on Android.

Parameters • string – default file name as input. • string – extension filter to be applied. Can be 0 or more extensions. Returns table - allFiles for success or nil to canceled

Example: local tFiles= mbm.openMultiFile('mario.png',' *.png','*.jpeg') if tFiles and #tFiles>0 then for i=1,#tFiles do print("File",i,tFiles[i]) end end saveFile saveFile(string defaultFileName*, string extension*, ...) Call a native dialog box to save a file (it will retrieve a full path) pointing the defaultFileName and extension allowed. This method does not work on Android.

Parameters • string – default file name as input. • string – extension filter to be applied. Can be 0 or more extensions.

56 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Returns string - fileName for success or nil to canceled

Example: local filename= mbm.saveFile('test.txt',' *.txt','*.lua') if filename then print("File",filename) end openFolder openFolder(string title*, string* defaultPath) Call a native dialog box to get a folder path pointing the default path optionally. This method does not work on Android.

Parameters • string – title default to be showed on dialog box. • string – default path to folder start. Returns string - folderName for success or nil to canceled

Example: local folderPath= mbm.openFolder('Please choose a folder','C://') --for windows for

˓→example. if folderPath then print("folder",folderPath) end messageBox messageBox(string title*, string message*, string dialogType*, string iconType*) Call a native message box dialog. This method does not work on Android.

Parameters • string – title to be showed on message box. • string – message to be showed on message box. • string – dialog Type one of the valid type as string ok, okcancel, yesno. • string – icon Type one of the valid icon type as string info, warning, error, question. Returns boolean - true for yes/ok or false to no/canceled

Example: local ret= mbm.messageBox('My Application title', 'There is no connection! \n Continue?', 'yesno', 'info') (continues on next page)

3.2. mbm 57 MBM Documentation, Release 3.1.f

(continued from previous page) if ret then print('yes') else print('no') end inputBox inputBox(string title*, string message*, string defaultInput*) Call a native input box dialog. This method does not work on Android.

Parameters • string – title to be showed on input box. • string – message to be showed on input box. • string – default Input a default value as input. Returns string - value for the input or nil if canceled

Example: local name= mbm.inputBox('My Application title', 'Please enter your name:', 'my_name') if name then print('name:',name) end inputPassword inputPassword(string title*, string message*, string defaultInput*) Call a native input box dialog for password. This method does not work on Android.

Parameters • string – title to be showed on input box. • string – message to be showed on input box. • string – default Input a default value as input. Returns string - value for the input or nil if canceled

Example: local password= mbm.inputPassword('My Application title', 'Please enter your password:') if password then print('password:',password) end

58 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

3.2.5 FPS getFps getFps Retrieve the current frames per second. Normally the engine work at 60 fps. The fps can be affected by fakeFps. Returns number - fps Example: local fps= mbm.getFps() print('Fps:',fps) setFps setFps(number fps) Try to force a new FPS rate. Parameters number – fps - the new value must be positive number and logically depends on video board. Example: mbm.setFps(90) setFakeFps setFakeFps(number cycles, number fps) Set a fake FPS rate. A fake FPS rate is useful, for example, when we have to do a massive physics calculate for a short period of time. Also, this is a way to simulate a “slow motion” scene. You just must to put a high FPS for that. After the end of cycle the FPS come back to normal. Parameters • number – cycles making the fake fps. • number – the new value of fake fps. Example: local iFakeFps= 60 local iSeconds=5 mbm.setFakeFps(iFakeFps * iSeconds,iFakeFps)

Hint: • 180 cycles by 60 fps will fake simulate 3 seconds. • 180 cycles by 45 fps will fake simulate 4 seconds. • 300 cycles by 50 fps will fake simulate 6 seconds.

3.2. mbm 59 MBM Documentation, Release 3.1.f

3.2.6 Global setGlobal setGlobal(string key,[string,number,boolean] value) Set a global value. This allows exchange information among scenes using get and set. The value is permanent among scenes. You can use getGlobal to retrieve values. Parameters • number – key to the map • variable – the value can be any of: string, number or boolean Example: mbm.setGlobal('key','something') mbm.setGlobal('level',10) mbm.setGlobal('life','100') mbm.setGlobal('super',true) getGlobal getGlobal(string name) Get a global value. This allows retrieving a value previously set using setGlobal in another scene. Parameters number – key to the map Returns number, string or boolean. depends on setGlobal Example: local key= mbm.getGlobal('key') local level= mbm.getGlobal('level') local life= mbm.getGlobal('life') local super= mbm.getGlobal('super) clearGlobals clearGlobals Clear all global variables. The variable are set by setGlobal and get by getGlobal. They are called global because remains among scenes. Example: mbm.setGlobal('life',100) mbm.clearGlobals() local life= mbm.getGlobal('life') print(life) --nil

3.2.7 getCamera getCamera(string * world) Get a camera which gives you the control to the scene. See camera for more information. Parameters string – world can be '2d' or '3d'. default is '2d'.

60 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Returns camera table reference. Example: camera= mbm.getCamera() --Get camera 2DW camera2d= mbm.getCamera('2d') --Get camera 2DW camera3d= mbm.getCamera('3d') --Get camera 3D

Note: 2d represent 2DW since 2DS has no camera

3.2.8 get get(string what) Check system operation (SO), compilation flags (versions from libs). Parameters string – what question as string. Returns string or boolean or nil The following table shows the parameters available for the engine until now:

Parameter Explanation Result as Windows true if is running on Windows boolean Android true if is running on Android boolean Linux true if is running on Linux boolean Version Get all version used string Mbm Get the current engine version string Box-2d Box 2d version or nil if is string not available Opengl Opengl version or nil if is string not available LUA LUA version or nil if is not string available Audiere Audiere version or nil if is string not available Mini-z Mini-z version or nil if is string not available Exe Name Executable name string USE_EDITOR_FEATURES true if is built with editor fea- boolean tures Useful for editor

USE_SQLITE3 true if is built with sqlite3 boolean compiled USE_DEPRECATED_2_MINOR true if the version is compati- boolean ble < 2 USE_VR true if is built using boolean virtual reality class beta USE_OPENGL_ES true if is using opengles boolean USE_VULKAN true if is using vulkan boolean USE_TILE_MAP_PARSER true if is built with Tiled Map boolean

3.2. mbm 61 MBM Documentation, Release 3.1.f

Example: if mbm.get('Windows') then print('Running on windows') elseif mbm.get('Linux') then print('Running on Linux') elseif mbm.get('Android') then print('Running on Linux') end print('LUA version' ,mbm.get('LUA')) print('Using sqlite3:',mbm.get('USE_SQLITE3') or 'false')

3.2.9 getSplash getSplash Retrieve a splash previously set using the method loadScene.

Returns renderizable - the type is dynamic, depend on loadScene second parameter of course.

Example: scene_1.lua

-- scene_1.lua tSplash= texture:new('2ds') tSplash:load('mario.png',50,50) if mbm.loadScene('scene_2.lua',tSplash) then print('scene loaded successfully') else print('Failed to load scene') end

Example: scene_2.lua

-- scene_2.lua --retrieve the splash set in the previous scene tSplash= mbm.getSplash() tSplash:setPos(100,100)

3.2.10 include include(string fileName) Try to include a LUA script file. Return false on error. Parameters string – fileName to be loaded. Returns boolean - result The main difference between the command include, dofile or require from LUA is that the command will use an internal list (see addPath.), to search the file. Also in case of fail, it will return false (will not throw an exception). Is useful when we wish to continue the main script even some dependencies are not found. Example:

62 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

if mbm.include('saved-data.lua') then print('loading game...') --do something ... else print('There is no saved data...') print('New game then...') end

3.2.11 loadScene loadScene(string fileNameScene, *renderizable splash) Load a new scene.

Parameters • string – fileNameScene file name scene to be loaded. • renderizable – splash table for splash that shows between scenes (optional). Returns boolean - true for success.

Example: if mbm.loadScene('other_Scene.lua') then print('scene loaded successfully') else print('Failed to load scene') end

--passing splash texture as parameter -- tSplash= texture:new('2ds') tSplash:load('mario.png',50,50) if mbm.loadScene('other_Scene.lua',tSplash) then print('scene loaded successfully') else print('Failed to load scene') end

--passing splash file name for texture as parameter -- if mbm.loadScene('other_Scene.lua','loading.png') then print('scene loaded successfully') else print('Failed to load scene') end

Note: The load method will search in all known path. You can add a path to search by the method addPath.

The renderizable as splash parameter can be texture, sprite, mesh, gif or particle. To retrieve the splash in the other scene use getSplash method.

3.2. mbm 63 MBM Documentation, Release 3.1.f

3.2.12 print

print(...) Overload the native print from LUA getting information from current line. Parameters • var-args – accept the same parameter as native print from LUA. • var-args – line if passed will print the line number from LUA file. • var-args – warn, error, info if passed will print the colored tag in the output. • var-args – color if passed will print color in the output. the colors accepted are: red, green, blue, cian, yellow, magenta, white. Example:

Listing 3.1: overload_print.lua

1 print('Normal print')

2

3 print('line','Hello from print')

4

5 print('error','An error ocurred')

6

7 print('error','line','An error ocurred at this line')

8

9 print('green','line','An importatnt thing ocurred at this line')

10

11 print('magenta','line','This color is magenta')

12

13 print('magenta','line','info','This color is magenta?')

14

15 print('warn','line','info','This is an warning?')

16

17 print('warn','line','No, this is an warning!')

18

19 print('info','this is an information!')

20

3.2.13 pause

pause Pause the application. It means to stop any physic, timer, and animation. the main loop and callback function are still called by the engine. However, the delta time and fps are set to zero. Example:

mbm.pause()

3.2.14 resume

resume Resume the application previously paused (see pause).

64 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Figure 3.11: Print from engine

3.2. mbm 65 MBM Documentation, Release 3.1.f

Example: mbm.resume()

3.2.15 Screen enableClearScreen enableClearScreen(boolean enable) Enable or disable clear screen. It is normal any engine clear the screen before starting to render. Some case we may wish to disable this process (enabled by default). Parameters boolean – value to enable or disable clear screen. Example: mbm.enableClearScreen(false) getSizeScreen getSizeScreen Get the back-buffer size. It considers the current camera’s scale. Returns number, number - width, height Example: local iW, iH= mbm.getSizeScreen() getRealSizeScreen getRealSizeScreen Get the real back-buffer size. It does not consider the current camera’s scale. Returns number, number - width, height Example: local iW, iH= mbm.getRealSizeScreen() getDisplayMetrics getDisplayMetrics Get native size windows. Returns number, number - width, height Example: local iW, iH= mbm.getDisplayMetrics()

66 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

3.2.16 setColor setColor(number red, number green, number blue) Change the clear color background. You can disable clear color through enableClearScreen function. Parameters • number – red color. Values between 0.0 and 1.0 • number – green color. Values between 0.0 and 1.0 • number – blue color. Values between 0.0 and 1.0 Example: local r,g,b= 1.0, 0.0, 1.0 mbm.setColor(r,g,b) --set background color

3.2.17 Transform to2dw to2dw(number x, number y) Transform a 2D screen coordinate to 2D world.

Parameters • number – x 2D screen coordinate. • number – y 2D screen coordinate. Returns number, number - x, y

Example: function onTouchDown(key,x,y) local X, Y= mbm.to2dw(x,y) end to2ds to2ds(number x, number y) Transform a 2D world coordinate to 2D screen.

Parameters • number – x 2D world coordinate. • number – y 2D world coordinate. Returns number, number - x, y

Example: local X, Y= mbm.to2ds(100,200)

3.2. mbm 67 MBM Documentation, Release 3.1.f to3d to3d(number x, number y, number howFar) Transform a 2D screen coordinate to 3D world.

Parameters • number – x 2D screen coordinate. • number – y 2D screen coordinate. • number – how far will be in 3D world. Returns number, number, number - x, y, z

Example: local x, y, z= mbm.to3d(300,100,200)

3.2.18 showConsole showConsole(boolean enable) Show console on Windows platform.

Parameters boolean – enable show or hide the screen console on Windows platform.

Example: mbm.showConsole(true)

3.2.19 getObjectsRendered getObjectsRendered(string * word) Retrieve the total objects renderized at the moment. param string world 2d, 3d or all. return number - total objects renderized Example: local iTotalObjRendered= mbm.getObjectsRendered() local iTotalObj2DRendered= mbm.getObjectsRendered('2d') local iTotalObj3DRendered= mbm.getObjectsRendered('3d')

3.2.20 quit quit Quit the application. (The application will call onEndScene if exists) Example:

68 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

mbm.quit()

3.3 Texture

The engine uses LodePNG as default to decode and encoder an image.

3.3.1 Supported image types

The engine use some libraries to load textures and the currently supported extension are: .png .jpeg .jpg .bmp .gif .psd .pic .pnm .hdr .tga .tif.

3.3.2 createTexture createTexture(table pixel, number width, number height, number channel, string *nickName, string *file- NamePng2Save) This method allow to create texture at runtime. The texture can have alpha channel or not. It is also possible to save to as png file.

Note: The pixels for this function are expected in range 0 to 255.

Parameters • table – pixel. Can have 3 or 4 pixel per channel. RGB or RGBA sequential. • number – width texture. • number – height texture. • number – channel texture. Must be 3 or 4. • string – nick name. This will be the name applied to texture (optional). • string – file name. if not nil, the texture will be saved as png (optional). Returns string - nick name for the texture created or nil has failed.

Attention: If the nick name exists (could be a real name for texture) then the function does nothing. It won’t try to replace pixels instead of. You can check if the texture exists calling the function existTexture

Example: function write_pixel(tPixel, width, height, x,y, channel, r,g,b) index= ((y-1) * width * channel)+ ((x-1) * channel) --find the index on the ˓→table to be filled tPixel[index+1]=r tPixel[index+2]=g tPixel[index+3]=b end (continues on next page)

3.3. Texture 69 MBM Documentation, Release 3.1.f

(continued from previous page) local tPixel={} --our table to store the pixels local widthTexture=4 local heightTexture=4 local channel=3 -- no alpha channel local r,g,b= 0x00, 0x00, 0xff --blue

--fill the texture table with gradient color (blue to green) for y=1, heightTexture do

for x=1, widthTexture do write_pixel(tPixel,widthTexture, heightTexture, x,y, channel, r,g,b) end end

--Our texture local sTextureFileName='blue-texture.png'

--is important to check if the texture already exists, --If the texture exists the createTexture method will return ok and do not overwrite

˓→the texture. if not mbm.existTexture(sTextureFileName) then

print(string.format("texture [%s] does not exist! let's create it then!",

˓→sTextureFileName))

sTextureFileName= mbm.createTexture(tPixel, widthTexture, heightTexture, channel, sTextureFileName) end if sTextureFileName ~= nil then print('Successfully created texture:', sTextureFileName) --now the texture exist and can be loaded for example from a textureView object: tex_view= texture:new() tex_view:load(sTextureFileName) --load the texture previously created tex_view:setSize(100,100) --our texture only has 4x4 pixel, lets make the frame

˓→big to be visible else print('Something goes wrong!') end

Figure 3.12: Simple blue texture created at runtime.

Now an example creating a gradient color:

70 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

function write_pixel(tPixel, width, height, x,y, channel, r,g,b,a) index= ((y-1) * width * channel)+ ((x-1) * channel) --find the index on the ˓→table to be filled tPixel[index+1]=r tPixel[index+2]=g tPixel[index+3]=b tPixel[index+4]=a end local tPixel={} --our table to store the pixels local widthTexture= 100 local heightTexture= 100 local channel=4

--fill the texture table with gradient color (blue to green) for y=1, heightTexture do --each column has a gradient collor --blue starts from 255 to 0 --green starts from 0 to 255 local r= 0x00 local g= math.ceil((0xff/ heightTexture) * (y)) local b= math.ceil((0xff/ heightTexture) * (heightTexture- y)) local a= 0xff for x=1, widthTexture do write_pixel(tPixel,widthTexture, heightTexture, x,y, channel, r,g,b,a) end end

--Our texture local sTextureFileName='blue-to-green-gradient-texture.png'

--is important to check if the texture already exists, --If the texture exists the createTexture method will return ok and do not overwrite

˓→the texture. if not mbm.existTexture(sTextureFileName) then

print(string.format("texture [%s] does not exist! let's create it then!",

˓→sTextureFileName))

sTextureFileName= mbm.createTexture(tPixel, widthTexture, heightTexture, channel, sTextureFileName, sTextureFileName) end if sTextureFileName ~= nil then print('Successfully created texture:', sTextureFileName) --now the texture exist and can be loaded for example from a textureView object: tex_view= texture:new() tex_view:load(sTextureFileName) --load the texture previously created else print('Something goes wrong!') end

3.3. Texture 71 MBM Documentation, Release 3.1.f

3.3.3 existTexture existTexture(string name) This method verify if a texture exist internally. Exist means that it was loaded sometime during the execution the application and it is on memory.

Parameters string – name. the name can be also a nickname. Returns boolean - true if the texture exist and was loaded.

Example: local ret= mbm.existTexture('Mario.png') print('Mario.png is loaded in memory:',ret)

3.3.4 loadTexture loadTexture(string file_name_texture, boolean * alpha) Load a texture indicating the file name and if it should have alpha (true by default). This function just load the texture an retrieve details about it. It does not show the texture in the screen. It kept in memory. The next object that will use that texture will get from memory.

Parameters • string – name. the name can be also a nickname. • boolean – alpha. Force or instruct to have alpha (true by default). Returns number - width, number - height, number - id from engine . (the id is zero if has failed to load the texture), boolean - has alpha

Example: local width,height,id, has_alpha= mbm.loadTexture('mario.png') if id ~=0 then print('Texture loaded, width:',width,'height:',height,'has_alpha:',has_alpha) else print('Could not load the texture!') end

72 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Note: If the texture is already loaded the function just return the information. It does not reload the texture.

3.4 Shader

3.4.1 getShaderList getShaderList(boolean returnDetails*, string filter*, boolean bMin*, boolean bMax*, boolean bCode*) This method retrieve one or more existent shader in a table.

Parameters • boolean – return details flag refers to code and variables. Default is false • string – filter can be ps for pixel shader, vs for vertex shader or nil for both. • boolean – bMin flag refers to include the min value. • boolean – bMax flag refers to include the max value. • boolean – bCode flag refers to include the code. Returns table - list of shader detail or list of name (without detail flag).

The following table represent a shader with all flags enabled:

{ name='gradient_horizontal.ps', code=[[ precision mediump float; uniform sampler2D sample0; uniform vec4 right; uniform vec4 left; varying vec2 vTexCoord;

void main() { vec4 c1 = mix(left,right,vTexCoord.x); c1.a = min(texture2D(sample0, vTexCoord).a,c1.a); gl_FragColor = c1; } ]], var= {right={0.5,0.5,0.5,0.5}, left={1,1,1,1}}, min= {right={0.0,0.0,0.0,0.0}, left={0,0,0,0}}, max= {right={1.0,1.0,1.0,1.0}, left={1,1,1,1}} }

The following table represent a return of getShaderList with detail flag disable:

{ [1]='bloom.ps', [2]='brightness.ps', [3]='gradient_horizontal.ps', ... }

Here one example printing all shader name available:

3.4. Shader 73 MBM Documentation, Release 3.1.f

local tShaders= mbm.getShaderList( false,nil) table.sort(tShaders) for i=1,# tShaders do local name= tShaders[i] print(string.format('Shader:[%s]', name)) end

The output:

Shader:[bloom.ps] Shader:[blur directional.ps] Shader:[blur zoom.ps] Shader:[bright extract.ps] Shader:[brightness.ps] Shader:[color it.ps] Shader:[color keying.ps] Shader:[color tone.ps] Shader:[edge gradient magnitude.ps] Shader:[embossed.ps] Shader:[explosion gaussian.ps] Shader:[fade radial.ps] Shader:[fade ripple.ps] Shader:[fade saturate.ps] Shader:[fade twist grid.ps] Shader:[fade twist.ps] Shader:[fade wave.ps] Shader:[fade.ps] Shader:[font.ps] Shader:[frosty out line.ps] Shader:[glass tile.ps] Shader:[invert color.ps] Shader:[luminance.ps] Shader:[magnifying glass.ps] Shader:[multi textura.ps] Shader:[night vision blur.ps] Shader:[night vision.ps] Shader:[old movie.ps] Shader:[out of bounds.ps] Shader:[pinch mouse.ps] Shader:[pinch.ps] Shader:[poisson.ps] Shader:[ripple.ps] Shader:[saturate.ps] Shader:[scale.vs] Shader:[sharpen.ps] Shader:[simple texture.vs] Shader:[sketch.ps] Shader:[smooth magnify.ps] Shader:[spiral.ps] Shader:[texture map.ps] Shader:[tiled map.ps] Shader:[tone mapping.ps] Shader:[toon.ps] Shader:[transparent.ps] Shader:[wave.ps]

74 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

Here other example printing all detail available in the shader brightness.ps: local bVariables= true --enable all variables local filter='brightness.ps' --put nil to print them all local bMin= true --enable min values local bMax= true --enable max values local bCode= true --enable code local tShaders= mbm.getShaderList(bVariables,filter,bMin,bMax,bCode) function print_recursive_table(t,indent) if not indent then indent=0 end if type(t) ~="table" then formatting= string.rep(" \t", indent).. tostring(t) print(formatting) else for k, v in pairs(t) do formatting= string.rep(" \t", indent)..k..":" if type(v) =="table" then print(formatting) print_recursive_table(v, indent+1) else print(formatting.. tostring(v)) end end end end for i=1,# tShaders do local tShader= tShaders[i] print_recursive_table(tShader) end

Output: name: brightness.ps min: brightness: 1: 0 contrast: 1: 0 max: brightness: 1: 1 contrast: 1: 2 var: brightness: 1: 0.5 contrast: 1: 1.5 code: precision mediump float; uniform float brightness; uniform float contrast; uniform sampler2D sample0; varying vec2 vTexCoord;

(continues on next page)

3.4. Shader 75 MBM Documentation, Release 3.1.f

(continued from previous page) vec4 xlat_main(in vec2 uv,in vec4 pixelColor) { pixelColor.xyz /= pixelColor.w; pixelColor.xyz = (((pixelColor.xyz - 0.500000) * max(contrast, 0.000000)) + 0. ˓→500000); pixelColor.xyz += brightness; pixelColor.xyz *= pixelColor.w; return pixelColor; } void main() { vec4 color = texture2D(sample0, vTexCoord); if (color.a == 0.0) discard; else gl_FragColor = xlat_main(vTexCoord,color); }

All shader code are described at shader code.

3.4.2 existShader

existShader(string name) This method verify if a shader exists.

Parameters string – name for both type of shader ps or vs. Returns boolean - result of query.

Example:

if mbm.existShader('blend.ps') then print('blend.ps found!') else print('blend.ps not exists!') end

3.4.3 addShader

addShader(table tShader) Add a new shader to the engine. Note that you must verify if the shader already exist before try to add it using th function existShader. A shader table is described here at shader table.

Parameters table – tShader is a table with information for both type of shader ps or vs. Returns boolean - result of insert.

Example:

76 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

if not mbm.existShader('gradient_horizontal.ps') then local tShaderGradient_horizontal= { name='gradient_horizontal.ps', code=[[ precision mediump float; uniform sampler2D sample0; uniform vec4 right; uniform vec4 left; varying vec2 vTexCoord;

void main() { vec4 c1 = mix(left,right,vTexCoord.x); c1.a = min(texture2D(sample0, vTexCoord).a,c1.a); gl_FragColor = c1; } ]], var= {right={0.5,0.5,0.5,0.5}, left={1,1,1,1}}, min= {right={0.0,0.0,0.0,0.0}, left={0,0,0,0}}, max= {right={1.0,1.0,1.0,1.0}, left={1,1,1,1}} }

if not mbm.addShader(tShaderGradient_horizontal) then print("Error on add shader:",tShaderGradient_horizontal.name) end else print('gradient_horizontal.ps already exists!') end

More about shader can be found at shader table reference.

3.5 Miniz

3.5.1 compress compress(string fileIn, string fileOut*, number level*) Compress a file using the MiniZ library.

Parameters • string – file in is the file that will be compressed. • string – file out is the file name output. If not supplied will overwrite the file in. • number – level of compression. Valid values are between 0 (do not compress) and 10 (max compression by MiniZ lib). Returns boolean - result of compression.

Example: if mbm.compress('/tmp/my_data.txt') then print('Successfully compressed') else (continues on next page)

3.5. Miniz 77 MBM Documentation, Release 3.1.f

(continued from previous page) print('Failed to compress file') end

3.5.2 decompress

decompress(string fileIn, string fileOut*) Decompress a file previously compressed using the method compress which works with the MiniZ library.

Parameters • string – file in is the file that will be decompressed. • string – file out is the file name output. If not supplied will overwrite the file in. Returns boolean - result of decompression.

Example:

if mbm.decompress('/tmp/my_data.txt') then print('Successfully decompressed') else print('Failed to decompress file') end

3.6 Aes

3.6.1 encrypt

encrypt(string fileIn, string fileOut*, string password*) Encrypt a file using the AESCrypt library.

Parameters • string – file in is the file that will be encrypted. • string – file out is the file name output. If not supplied or nil will overwrite the file in. • string – password to be used. If not informed the engine will use the default one which change each release. Returns boolean - result of encrypt.

Example:

if mbm.encrypt('/tmp/my_data.txt',nil,'12345') then print('Successfully encrypted') else print('Failed to encrypt') end

78 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

3.6.2 decrypt

decrypt(string fileIn, string fileOut*, string password*) Decrypt a file previously encrypted using the encrypt method.

Parameters • string – file in is the file that will be decrypted. • string – file out is the file name output. If not supplied or nil will overwrite the file in. • string – password to be used. If not informed the engine will use the default one which change each release. Returns boolean - result of decrypt.

Example:

if mbm.decrypt('/tmp/my_data.txt',nil,'12345') then print('Successfully decrypted') else print('Failed to decrypt') end

3.7 Useful

3.7.1 shuffle

shuffle(string message, string key) Encrypt alphabetic text by using a series of interwoven Caesar ciphers, based on the letters of a keyword. See Vigenère cipher for more information how it works.

Parameters • string – message is the text to be encrypted. • string – key is the keyword to shuffle. Returns string - text encrypted.

Example:

local original='Hello World using Vigenere algorithm' local key='myKeyIsSomethingLikeThis' local msg= mbm.shuffle(original,key) local decryptedMsg= mbm.undoShuffle(msg,key) print('original:',original) --Hello World using Vigenere algorithm print('msg:',msg) --Tcvpm Ogfxh bavtr Fmzlvwdc ejogjwflf print('decrypted:', decryptedMsg)--Hello World using Vigenere algorithm

3.7.2 undoShuffle

undoShuffle(string message, string key)

3.7. Useful 79 MBM Documentation, Release 3.1.f

Undo a encrypt alphabetic text previously encrypted by the method shuffle .

Parameters • string – message is the text to be decrypted. • string – key is the keyword to undo the shuffle. Returns string - text decrypted.

Example: local original='Hello World using Vigenere algorithm' local key='123456What' local msg= mbm.shuffle(original,key) local decryptedMsg= mbm.undoShuffle(msg,key) print('original:',original) --Hello World using Vigenere algorithm print('msg:',msg) --Dllek Whnsd qzigc Vbclnxnl thnokeahf print('decrypted:', decryptedMsg)--Hello World using Vigenere algorithm

3.7.3 existFile existFile(string name) This method verify if a file exist by trying to open it. If the name has not the full path, the engine will try all path known. See addPath.

Parameters string – name. the file name. Returns boolean - true if the file exist.

Example: local ret= mbm.existFile('test.txt') print('Test.txt exists:',ret)

3.7.4 getPathEngine getPathEngine(string* fileName) This method retrieve the path where the engine is running for Linux and Windows. For Android will retrieve a default path to read and write files runtime.

Parameters string – fileName to be concatenated at the end of path. Returns string - full file name or path engine.

Example: local fileName= mbm.getPathEngine('test.data') print('fileName:',fileName)

80 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

3.7.5 getFullPath getFullPath(string* fileName) This method will try to retrieve the full path from a file. If could not retrieve, will return the same file name.

Parameters string – fileName to get the full path. Returns string - full file name or file name.

Example: local fileName= mbm.getFullPath('test.data') print('full path:',fileName)

3.7.6 onErrorStop onErrorStop(boolean value) This method inform the engine to stop calling loop method if an error occurred.

Parameters boolean – value enabling or disabling calling loop method.

Example: mbm.onErrorStop(true)

3.7.7 getKeyName getKeyName(number code) Recover the correspondent name from a value. This change according to the SO. On Windows for example the 27 code is ESC keyboard. It can be used with the methods onKeyDown and onKeyUp.

Parameters number – code number. Returns string - key name.

Note: There is an attempt to standardize this method for all SO however is still on progress.

Example:

--example 1 local keyName= mbm.getKeyName(27) print('keyName:',keyName) -- On Windows the output is 'ESC'

--example 2 function onKeyDown(key) if mbm.getKeyName(key) =='A' then print('A pessed') elseif mbm.getKeyName(key) =='left' then print('go left') (continues on next page)

3.7. Useful 81 MBM Documentation, Release 3.1.f

(continued from previous page) elseif mbm.getKeyName(key) =='right' then print('go right') elseif mbm.getKeyName(key) =='space' then print('Jump!') end end

3.7.8 getKeyCode getKeyCode(number key) Recover the correspondent code from a key (as string). This change according to the SO. On Win- dows for example the 27 code is ESC keyboard. It can be used with the methods onKeyDown and onKeyUp.

Parameters number – key as string. Returns number - code for the input key.

Note: There is an attempt to standardize this method for all SO however is still on progress.

Example:

--example 1 local keyCode= mbm.getKeyCode('ESC') print('keyCode:',keyCode) -- On Windows the output is 27

--example 2 function onKeyDown(key) if mbm.getKeyCode('A') == key then print('A pressed') elseif mbm.getKeyCode('left') == key then print('go left') elseif mbm.getKeyCode('right') == key then print('go right') elseif mbm.getKeyCode('space') == key then print('Jump!') end end

3.7.9 isCapitalKeyOn isCapitalKeyOn Recover the state of Caps Lock on or off. Example: function onKeyDown(key) if mbm.getKeyCode('A') == key then if mbm.isCapitalKeyOn() then print('Key A is uppercase') else (continues on next page)

82 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

(continued from previous page) print('Key a is lowercase') end end end

3.7.10 getIdiom getIdiom Recover the language (region) from the system. The return string is according to the SO.

Returns string - idiom for the SO.

Example: local idiom= mbm.getIdiom() print('idiom:',idiom) --a possible output could be: --pt-BR --American English

3.7.11 getUserName getUserName Recover the user name form current SO.

Returns string - user name for the currently SO.

Example: local user= mbm.getUserName() print('Welcome',user)

3.7.12 getSceneName getSceneName Recover the currently scene name.

Returns string - scene name.

Example: local scene= mbm.getSceneName() print('Scene:',scene)

3.7. Useful 83 MBM Documentation, Release 3.1.f

3.7.13 refresh refresh Force to reload all renderizables object. This is a way to test a lost device graph.

Note: Is not recommend to use this method frequently.

Example: mbm.refresh()

3.7.14 listFiles listFiles(string folder, boolean * recursive) List files in folder

Parameters boolean – recursive indicate to list recursive folders. Returns table - files listed {separator = '/' or '\\', path = 'folder', [1] = file, [2] ...}.

Example: local recursive= true -- if recursive is false it will add a empty table with the

˓→folder name (path). It will not list the files inside. local tFolders= mbm.listFiles('/home/jose/project', recursive) print('separator', tFolders.separator) for i=1,#tFolders do local files= tFolders[i] print('Folder:',files.path) print('Files:') for j=1,#files do print(files[j]) end print('') end

3.8 Android

3.8.1 doCommands doCommands(string command, string parameter) Execute a custom native command on Android platform. For example if we want to do a custom command using Java class, this is the way to that.

Parameters • string – command to be interpreted in native side.

84 Chapter 3. Table mbm MBM Documentation, Release 3.1.f

• string – parameter is a optional parameter to be used in native side.

There are some registered commands in Android. Here they are:

Command parameter explanation API-level Retrieve the current API level on Android vibrate milliseconds • Call vibration method during x milliseconds. • You have to add permis- sion on manifest for this.

Following some examples calling the methods above:

local apiAndroidLevel= mbm.doCommands('API-level') print('The current API on Android is:',apiAndroidLevel)

local ms= 500 mbm.doCommands('vibrate',500) --vibrate for 500 milliseconds

Now a simple implementation: Lua side:

local result= mbm.doCommands('key-command-1','my parameter') print(result) -- prints "OKAY from Java"

Java side:

@Override public String OnDoCommands(String key, String param) { if(key== "key-command-1") { Log.d("java", "my command is :"+ key+" parameter:"+ param); //we can do some specific command here return "OKAY from Java"; } else { return "NOKAY from java!, Command not implemented:"+ key; } }

3.8.2 luaFunction

luaFunction(string function, string parameter) Call a LUA function from Java (Android). Example:

3.8. Android 85 MBM Documentation, Release 3.1.f

/*Call Lua native function*/ luaFunction("print","Hello from Java!");

/*Call my personal defined function*/ luaFunction("some_lua_function","execute");

function some_lua_function(param) --Do something if param =='execute' then print('param is execute. we will execute some command ...') end end

Table of Contents

• Table camera – Camera 2D methods

* camera 2d setPos * camera 2d getRealPos * camera 2d move * camera 2d scaleToScreen – Camera 2D attributes – Camera 3D methods

* camera 3d setPos * camera 3d setFocus * camera 3d setUp * camera 3d getPos * camera 3d getFocus * camera 3d move * camera 3d setFar * camera 3d setNear * camera 3d setAngleOfView – Camera 3D attributes – User data acknowledgment

86 Chapter 3. Table mbm CHAPTER 4

Table camera

Table global instanced by engine to access both camera 2D and 3D to the application. A camera have a scale to make easy to work on device.

Use getCamera method to get a camera 2DW supplying 2D string as parameter. Use getCamera method to get a camera 3D supplying 3D string as parameter.

4.1 Camera 2D methods

4.1.1 camera 2d setPos setPos(number x, number y) Set position using x and y (2D world) position. This method consider camera’s scale. Parameters • number – x position. • number – y position. Example: camera2D= mbm.getCamera('2d') camera2D:setPos(0,0) setPos(table renderizable) Set position using a renderizable object position. This method consider camera’s scale. Parameters table – renderizable object. Example:

87 MBM Documentation, Release 3.1.f

camera2D= mbm.getCamera('2d') tSprite= sprite:new('2d') tSprite:setPos(500,300) camera2D:setPos(tSprite)

setPos(vec2 vector) Set position using a vec2 position. This method consider camera’s scale. Parameters table – vec2 vector. Example:

camera2D= mbm.getCamera('2d') tVec2= vec2:new(100,20) camera2D:setPos(tVec2)

4.1.2 camera 2d getRealPos

getRealPos Return a vec2 which point to the real position (without scale) to the camera 2D. Returns vec2 - position to the camera 2D. Example:

camera2D= mbm.getCamera('2d') local posCamera2d= camera2D:getRealPos() --change the position directly posCamera2d.x=0 posCamera2d.y= 10

4.1.3 camera 2d move

move(number x, number * y) Move x and y units frames by seconds. This method consider the FPS. Parameters • number – x position. • number – y position. Example:

camera2D= mbm.getCamera('2d') camera2D:move(100,50)

--this is equivalent function loop(delta) camera2d.x= camera2d.x+ (delta * 100) camera2d.y= camera2d.y+ (delta * 50) end

move(vec2 position) Move x and y units frames by seconds using a vec2. This method consider the FPS. Parameters number – vec2 position.

88 Chapter 4. Table camera MBM Documentation, Release 3.1.f

Example:

camera2D= mbm.getCamera('2d') vec= vec2:new(100,50) camera2D:move(vec)

--this is equivalent function loop(delta) camera2d.x= camera2d.x+ (delta * vec.x) camera2d.y= camera2d.y+ (delta * vec.y) end

4.1.4 camera 2d scaleToScreen

scaleToScreen(number width, number height, *string axis) Modify the camera 2D scale passing the expected screen width and screen height. The axis instruct to consider the x axis, y axis or both xy axis. The xy axis means that we want to stretch the screen to the client size. If not feed the axis the engine will decide the better axis based on screen size of client. The method to get the scaled size screen is getSizeScreen. Parameters • number – width screen expected. • number – height screen expected. • string – axis to apply the scale. Example:

camera2D= mbm.getCamera('2d') --cause a stretch on screen camera2d:scaleToScreen(1024,768,'xy')

--our application always will fit to the screen on y axis camera2d:scaleToScreen(800,600,'y')

--our application always will fit to the screen on x axis camera2d:scaleToScreen(1920,1080,'x')

Note: Scale to screen allows the application has the same ‘look’ for different screen size. • Let’s take a look at the table bellow understand better. • The camera 2D is set to resolution (width x height) (scaleToScreen) method. • The client width and client height is get by the method getSizeScreen (after set the expected width and height). • The scaled width and scaled height is the size adapted to the client. • The scale sx and scale sy is camera’s attribute.

4.1. Camera 2D methods 89 MBM Documentation, Release 3.1.f

width heightaxis client client scaled scaled camera camera width height width height scale ‘sx’ scale ‘sy’ 800 600 xy 800 600 800 600 1.0 1.0 x 800 600 1.0 1.0 y 800 600 1.0 1.0 1024 768 xy 800 600 1024 768 0.78125 0.78125 x 1024 768 0.78125 0.78125 y 1024 768 0.78125 0.78125 1920 1080 xy 1024 768 1920 1080 0.5333334 0.7111111 x 1920 1440 0.5333334 0.5333334 y 1440 1080 0.7111111 0.7111111

4.2 Camera 2D attributes x, y [read / write] Access the position x and y member from camera. Example: camera2D= mbm.getCamera('2d') camera2D.x= 500 camera2D.y= 250 print('X:',camera2D.x,'Y:',camera2D.y) sx, sy [read / write] Access the scale sx and sy member from camera. Example: camera2D= mbm.getCamera('2d') camera2D.sx= 1.5 camera2D.sy= 1.0 print('Scale X:',camera2D.sx,'Scale Y:',camera2D.sy)

'variable' [read / write] Create a variable to read/write to camera. The type allowed is number, string, boolean, and table and function. Example: camera2D= mbm.getCamera('2d') camera2D.myFloat= 1.5 camera2D.myInt=5 camera2D.myString='Hello there!' print('Accessing the variables myFloat:',camera2D.myFloat) print('Accessing the variables myInt:',camera2D.myInt) print('Accessing the variables myString:',camera2D.myString)

Tip: The variable is stored internally and belongs to the camera. So if we create a variable to the camera and load a new scene, then the variables will NOT be available because it is other scene. If you want to keep variable between scenes use setGlobal and getGlobal for that.

90 Chapter 4. Table camera MBM Documentation, Release 3.1.f

Error: It is important to understand that as all tables used in this engine, this table uses the first index from table to store the userdata pointing to the C++ class internally. There is no mechanism to prevent to access the first index from camera. If you overload the userdata probably the program will crash.

Listing 4.1: Do not do this:

1 camera2D= mbm.getCamera('2d')

2 camera2D:setPos(100,20)

3

4 print(camera2D[1]) -- read, okay will print userdata: 0x32958758b6a7 for example

5

6 camera2D[1]=2 -- Error, this will do your program crash!

4.3 Camera 3D methods

Use getCamera method to get a camera 3D.

4.3.1 camera 3d setPos

setPos(number x, number y, number z) Set position using x, y and z (3D world) position. Parameters • number – x position. • number – y position. • number – z position. Example:

camera3D= mbm.getCamera('3d') camera3D:setPos(0,0,0) --origin

setPos(table renderizable) Set position using a renderizable object position. Parameters table – renderizable object. Example:

camera3D= mbm.getCamera('3d') tMesh= mesh:new('3d') tMesh:setPos(500,300,400) camera3D:setPos(tMesh)

setPos(vec3 vector) Set position using a vec3 position. Parameters table – vec3 vector. Example:

4.3. Camera 3D methods 91 MBM Documentation, Release 3.1.f

camera3D= mbm.getCamera('3d') tVec3= vec3:new(30,20,50) camera3D:setPos(tVec3)

4.3.2 camera 3d setFocus setFocus(number x, number y, number z) Set focus using x, y and z. Parameters • number – x focus. • number – y focus. • number – z focus. Example: camera3D= mbm.getCamera('3d') camera3D:setFocus(0,0,0) --look at the origin setFocus(table renderizable) Set focus using a renderizable object position. Parameters table – renderizable object. Example: camera3D= mbm.getCamera('3d') tMesh= mesh:new('3d') tMesh:setFocus(50,120,20) camera3D:setFocus(tMesh) setFocus(vec3 vector) Set focus using a vec3 position. Parameters table – vec3 vector. Example: camera3D= mbm.getCamera('3d') tVec3= vec3:new(5,15,0) camera3D:setFocus(tVec3)

4.3.3 camera 3d setUp setUp(number x, number y, number z) Set ‘up camera’ using x, y and z. Parameters • number – x ‘up camera’. • number – y ‘up camera’. • number – z ‘up camera’. Example:

92 Chapter 4. Table camera MBM Documentation, Release 3.1.f

camera3D= mbm.getCamera('3d') camera3D:setUp(0,1,0) --default camera3D:setUp(0,-1,0) --upside down setUp(vec3 vector) Set ‘up camera’ using a vec3 position. Parameters table – vec3 vector. Example: camera3D= mbm.getCamera('3d') tVecNormal= vec3:new(0,1,0) tVecUpsideDown= vec3:new(0,-1,0) camera3D:setUp(tVecNormal) --default camera3D:setUp(tVecUpsideDown) --upside down

4.3.4 camera 3d getPos getPos Get the camera’s position.

Returns vec3 - camera’s position .

Example: camera3D= mbm.getCamera('3d') local posCamera= camera3D:getPos() --move camera position to origin posCamera.x=0 posCamera.y=0 posCamera.z=0

4.3.5 camera 3d getFocus getFocus Get the camera’s focus vector.

Returns vec3 - camera’s focus vector .

Example: camera3D= mbm.getCamera('3d') local focus= camera3D:getFocus() --Look at the origin focus.x=0 focus.y=0 focus.z=0

4.3. Camera 3D methods 93 MBM Documentation, Release 3.1.f

4.3.6 camera 3d move

move(number x, number * y, number * z) Move x, y and z units frames by seconds. This method consider the FPS. Parameters • number – x position. • number – y position. • number – z position. Example:

camera3D= mbm.getCamera('3d') camera3D:move(50,60,70)

--this is equivalent function loop(delta) camera3d.x= camera3d.x+ (delta * 50) camera3d.y= camera3d.y+ (delta * 60) camera3d.z= camera3d.z+ (delta * 70) end

move(string direction, number units) • Move to a specific direction. This method consider the FPS.

• R move to the right direction. • L move to the left direction. • U move to up direction. • D move to down direction. • B move to back direction. • F move to forward direction.

Parameters • string – direction to move. Available: R, L, U, D, B and F. • number – units position.

Example:

camera3D= mbm.getCamera('3d') --move to the right 100 FPS camera3D:move('R',100)

getNormal(string direction) • Retrieve the normal from specific direction based on current camera 3d position.

• R get the the right direction. • L get the the left direction. • U get the up direction. • D get the down direction.

94 Chapter 4. Table camera MBM Documentation, Release 3.1.f

• B get the back direction. • F get the forward direction.

Parameters string – direction Available: R, L, U, D, B and F. Returns vec3 - camera’s direction normal vector.

Example: camera3D= mbm.getCamera('3d') local tNormalRight= camera3D:getNormal('R') print(tNormalRight.x)

4.3.7 camera 3d setFar setFar(number far) Set the zFar for 3D projection.

Parameters number – far value. Default is 1000.

Example: camera3D= mbm.getCamera('3d') camera3D:setFar(500)

4.3.8 camera 3d setNear setNear(number near) Set the zNear for 3D projection.

Parameters number – near value. Default is 0.1.

Example: camera3D= mbm.getCamera('3d') camera3D:setNear(2)

4.3.9 camera 3d setAngleOfView setAngleOfView(number degree) Set a angle of view for 3D projection.

Parameters number – degree value. Default is 110.

Example: camera3D= mbm.getCamera('3d') camera3D:setAngleOfView(65)

4.3. Camera 3D methods 95 MBM Documentation, Release 3.1.f

4.4 Camera 3D attributes x, y, z [read / write] Access the position x, y and z member from camera. Example: camera3D= mbm.getCamera('3d') camera3D.x= 100 camera3D.y= 200 camera3D.z= 300 print('X:',camera3D.x,'Y:',camera3D.y,'Z:',camera3D.z) fx, fy, fz [read / write] Access the focus fx, fy and fz member from camera. Example: camera3D= mbm.getCamera('3d') camera3D.fx= 10 camera3D.fy= 15 camera3D.fz=0 print('Looking at X:',camera3D.fx,'Y:',camera3D.fy,'Z:',camera3D.fz)

'variable' [read / write] Create a variable read/write to camera. The type allowed is number, string, boolean, table and function. Example: camera2D= mbm.getCamera('2d') camera2D.myFloat= 2.5 camera2D.myInt=8 camera2D.myString='Hi there!' camera2D.bValue= true camera2D.tUser= {name='Mario' , address='my street'} camera2D.fSayHello= function (self) print('Hello', self.tUser.name) end print('Accessing the variables myFloat:',camera2D.myFloat) print('Accessing the variables myInt:',camera2D.myInt) print('Accessing the variables myString:',camera2D.myString) print('Accessing the variables bValue:',camera2D.bValue) print('Accessing the table tUser:',camera2D.tUser.name,camera2D.tUser.address ) camera2D:fSayHello() -- invoke the function passing self as first argument

Note: The variable is stored internally and belongs to the camera from current scene. The variable is lost when loaded a new scene.

96 Chapter 4. Table camera MBM Documentation, Release 3.1.f

4.5 User data acknowledgment

This table uses the first index to store the userdata C++ class internally. So, if you want to store some values to the table you must use from the second element as exampled bellow:

Listing 4.2: You can do this:

1 camera3D= mbm.getCamera('3d')

2 camera3D:setPos(10,10,10)

3

4 camera3D[2]='my var'

5

6 print(camera3D[2]) -- 'my var'

Error: It is important to understand that as all tables used in this engine, this table uses the first index to store the userdata pointing to the C++ class internally. There is no mechanism to prevent to access the first index from camera. If you overload the userdata, probably the program will crash.

Listing 4.3: Do not do this:

1 camera2D= mbm.getCamera('2d')

2 camera2D:setPos(10,10)

3

4 print(camera2D[1]) -- read, okay will print userdata: 0x44958588a6a8 for example

5

6 camera2D[1]=2 -- Error, this will do your program crash!

Table of Contents

• Table font – font methods

* font new from true type * font new from a binary file * font setSpace * font getSpace * font getHeight * font add * font addText – font methods with editor features

* Size of letter * Displacement for letter in the axis x, y – Creating a font programmatically

4.5. User data acknowledgment 97 MBM Documentation, Release 3.1.f

98 Chapter 4. Table camera CHAPTER 5

Table font

A table font represent a true type font and can be loaded dynamically or loaded from a binary type generated by the engine.

5.1 font methods

5.1.1 font new from true type

new(string file_name, number height, number spaceX, number spaceY, boolean save_image_as_png) Create a new instance of a font passing the file name (extension expected .ttf) and the configuration expected. Parameters • string – file name from true type font .ttf. • number – height from font in units. • number – spaceX between the axis x. • number – spaceY is the \n (new line space). • boolean – save_png is a flag that instruct to save the font’s image as png. Returns font table. Example:

tArial15= font:new('Arial.ttf',15,0,2, true) --parse runtime a new font tArial13= font:new('Arial.ttf',13,0,2, false) --parse runtime other font

Note: The new method will search in all known path. and load the file. You can add a path to search by the method addPath.

99 MBM Documentation, Release 3.1.f

5.1.2 font new from a binary file

new(string file_name) Create a new instance of a font passing the binary file name (extension expected fnt). Parameters string – file name binary. Extension expected fnt. Example:

tArial15= font:new('Arial15.fnt') -- load a file previously created by the engine. tArial13= font:new('Arial13.fnt') -- load a file previously created by the engine.

Note: The fnt is an extension generated by the engine and is a binary file. The new method will search in all known path. and load the file. You can add a path to search by the method addPath.

5.1.3 font setSpace

setSpace(string axis, number value) Change the current space in the axis x or y. Parameters • string – axis x or y. • number – value from space to be applied. Example:

tArial15= font:new('Arial.ttf',15,0,2) --parse runtime a new font tArial15:setSpace('x',18) tArial15:setSpace('y',0)

5.1.4 font getSpace

getSpace(string axis) Retrieve the current space from font. Parameters string – axis x or y. Returns number - space. Example:

tArial15= font:new('Arial.ttf',15,0,2) --parse runtime a new font local x= tArial15:getSpace('x') -- 0 local y= tArial15:getSpace('y') -- 2

5.1.5 font getHeight

getHeight Retrieve the current height from font.

100 Chapter 5. Table font MBM Documentation, Release 3.1.f

Returns number - height. Example:

tArial15= font:new('Arial.ttf',15,0,2) --parse runtime a new font local height= tArial15:getHeight() -- 15

5.1.6 font add

add(string text, string * world, number * x, number * y, number * z) Create a new instance of a text from a font. Same as addText. Parameters • string – text to be drew. • string – world can be 2ds, 2dw or 3d (detail). • number – x position (optional). • number – y position (optional). • number – z position (optional). Example:

tArial15= font:new('Arial.ttf',15,0,2) --parse runtime a new font tText= tArial15:add('Hello text!','2ds',100,100)

Note: It might occurs error related to the character encoding. This can be solved changing the text to UTF8 Without BOM

5.1.7 font addText

addText(string text, string * world, number * x, number * y, number * z) Create a new instance of a text from a font. Same as add. Parameters • string – text to be drew. • string – world can be 2ds, 2dw or 3d (detail). • number – x position (optional). • number – y position (optional). • number – z position (optional). Example:

tArial15= font:new('Arial15.fnt') --load from binary previously generated tText= tArial15:addText('Hello text!','2dw',200,200)

Note: It might occurs error related to the character encoding. This can be solved changing the text to UTF8 Without BOM

5.1. font methods 101 MBM Documentation, Release 3.1.f

5.2 font methods with editor features

Here the methods available when compiled with the flag USE_EDITOR_FEATURES.

5.2.1 Size of letter getSizeLetter(string letter) Get the size of specific letter DO NOT considering the rotation neither scale. Parameters string – letter to be retrieved the size Returns number width, number height - dimension of letter. Example: local height= 20 --the font height local space_x=2 --space between characters in points coordinates local space_y=1 --space between new line characters in points coordinates local save_image_as_png= true --will save a local image as 'font_name-20.png' local base_name='Carlito-Regular' tMyFont= font:new(base_name..'.ttf',height,space_x,space_y,save_image_as_png) local width, height= tMyFont:getSizeLetter('A') print(width,height) -- for this example width:12, height:13 setSizeLetter(string letter, number width, number height) Force a new size of letter indicating the width and height. Parameters • string – letter to be retrieved the size • number – width of letter. • number – height of letter. Example: local height= 60 --the font height local space_x=2 --space between characters in points coordinates local space_y=1 --space between new line characters in points coordinates local save_image_as_png= true --will save a local image as 'font_name-60.png' local base_name='Carlito-Regular' tMyFont= font:new(base_name..'.ttf',height,space_x,space_y,save_image_as_png) local width, height= tMyFont:getSizeLetter('a') print(width,height) -- for this example width:12, height:13 tMyFont:setSizeLetter('',10,0) --10 it is good space for this font size (I am

˓→guessing) --set the new size of letter tMyFont:setSizeLetter('a',width * 2, height) tText= tMyFont:addText("My new size \n Note the 'a'\nsomething stranger",'2dw')

102 Chapter 5. Table font MBM Documentation, Release 3.1.f

Figure 5.1: Change the dimension of the letter ‘a’

5.2.2 Displacement for letter in the axis x, y getLetterXDiff(string letter) Get the displacement for the specific letter in the axis X. By default the value is 0. It can be negative. Parameters string – letter to be retrieved the size Returns number displacement - X of letter. Example: local height= 60 --the font height local space_x=2 --space between characters in points coordinates local space_y=1 --space between new line characters in points coordinates local save_image_as_png= true --will save a local image as 'font_name-60.png' local base_name='Carlito-Regular' tMyFont= font:new(base_name..'.ttf',height,space_x,space_y,save_image_as_png) tMyFont:setSizeLetter('',10,0) --space by default is not good, so we change it tMyFont:setLetterXDiff('e',10) local X= tMyFont:getLetterXDiff('e') print('Displacement:', X) setLetterXDiff(string letter, number value) Force a new displacement for the specific letter in the axis X. The value is added. It can be negative. Parameters • string – letter to be retrieved the size • number – value of displacement. Example: local height= 60 --the font height local space_x=2 --space between characters in points coordinates local space_y=1 --space between new line characters in points coordinates local save_image_as_png= true --will save a local image as 'font_name-60.png' (continues on next page)

5.2. font methods with editor features 103 MBM Documentation, Release 3.1.f

(continued from previous page) local base_name='Carlito-Regular' tMyFont= font:new(base_name..'.ttf',height,space_x,space_y,save_image_as_png) tMyFont:setSizeLetter('',10,0) --space by default is not good, so we change it tMyFont:setLetterXDiff('e',10) tText= tMyFont:add('Some Text: Hello World!!!','2dw')

Figure 5.2: Displacement 10 in the axis X getLetterYDiff(string letter) Get the displacement for the specific letter in the axis Y. By default the value is 0. It can be negative. Parameters string – letter to be retrieved the size Returns number displacement - Y of letter. Example: local height= 60 --the font height local space_x=2 --space between characters in points coordinates local space_y=1 --space between new line characters in points coordinates local save_image_as_png= true --will save a local image as 'font_name-60.png' local base_name='Carlito-Regular' tMyFont= font:new(base_name..'.ttf',height,space_x,space_y,save_image_as_png) tMyFont:setSizeLetter('',10,0) --space by default is not good, so we change it tMyFont:setLetterYDiff('e',10) local y= tMyFont:getLetterYDiff('e') print('Displacement:', y) setLetterYDiff(string letter, number value) Force a new displacement for the specific letter in the axis Y. The value is added. It can be negative. Parameters • string – letter to be retrieved the size • number – value of displacement. Example: local height= 60 --the font height local space_x=2 --space between characters in points coordinates local space_y=1 --space between new line characters in points coordinates local save_image_as_png= true --will save a local image as 'font_name-60.png' local base_name='Carlito-Regular' (continues on next page)

104 Chapter 5. Table font MBM Documentation, Release 3.1.f

(continued from previous page) tMyFont= font:new(base_name..'.ttf',height,space_x,space_y,save_image_as_png) tMyFont:setSizeLetter('',10,0) --space by default is not good, so we change it tMyFont:setLetterYDiff('e',10) tText= tMyFont:add('Some Text: Hello World!!!','2dw')

Figure 5.3: Displacement 10 in the axis Y

5.3 Creating a font programmatically

Here an example how to create a binary font from a true type file format. For this example it will be used the Carlito-Regular true type font. download Carlito-Regular.ttf Example: mbm.setColor(0.3,0.3,0.7) --blue color of background if not mbm.get('USE_EDITOR_FEATURES') then mbm.messageBox('Missing features','Is necessary to compile using USE_EDITOR

˓→FEATURES to run this example','ok','error',0) mbm.quit() end function saveBinaryFont(tText,fileName)

local tMeshDebug= meshDebug:new()

if tMeshDebug:loadFromMemory(tText) then -- require to be compiled using the

˓→editor flag: USE_EDITOR_FEATURES

if tMeshDebug:copyAnimationsFromMesh(tText) then --copy animations created

if tMeshDebug:save(fileName) then

print("Sucessfully saved font!") return true else print("Failed to save font!") end else print("Failed to apply shader and animations!") (continues on next page)

5.3. Creating a font programmatically 105 MBM Documentation, Release 3.1.f

(continued from previous page) end else print("Failed to load font!") end return false end function onInitScene()

local height= 50 --the font height local space_x=2 --space between characters in points coordinates local space_y=1 --space between new line characters in points coordinates local save_image_as_png= true --will save a local image as 'font_name-50.png' local base_name='Carlito-Regular'

tMyFont= font:new(base_name..'.ttf',height,space_x,space_y,save_image_as_png)

--add one text to view local tText= tMyFont:addText('Hello \n Font !\n 0123456789','2dw')

--increase the space width local xSpace,ySpace= tMyFont:getSizeLetter('') tMyFont:setSizeLetter('',10,ySpace) --10 it is good space for this font size (I

˓→am guessing)

--add one font color as animation tText:addAnim('red font animation')

--get the shader of font to change it local shader= tText:getShader() shader:load('font.ps') --just pixel shader, vertex shader is not necessary

shader:setPSall('colorFont',1,0,0) --change color font to red for min, max and

˓→current

local fileNameBinary= base_name..'.fnt'

if saveBinaryFont(tText,fileNameBinary) then tText:destroy() --destroy the existing one to reload from binary file

˓→previously created

tMyFont= font:new(fileNameBinary) --load from binary font

tText= tMyFont:addText('Hello world \n Font !\n 0123456789 \n #2# Second

˓→Animation','2dw') tText:setWildCard('#')--instruct to look a number between '#' that indicate the

˓→animation end end download font_creating_example_1.lua. download Carlito-Regular-50.png.

106 Chapter 5. Table font MBM Documentation, Release 3.1.f

Figure 5.4: font_creating_example_1.lua running

Table of Contents

• Table gif – gif methods

* gif new * gif load * gif setSize

5.3. Creating a font programmatically 107 MBM Documentation, Release 3.1.f

Figure 5.5: Carlito-Regular png generated

108 Chapter 5. Table font CHAPTER 6

Table gif

A table gif inherit from renderizable and implement all methods as usual. Also the animation has a shader table by default which can be accessed by getShader method.

6.1 gif methods

6.1.1 gif new new(string * world, number * x, number * y, number * z) Create a new instance of a gif passing the world desired (detail) and position. Parameters • string – world can be 2ds, 2dw or 3d. • number – x position (optional). • number – y position (optional). • number – z position (optional). Returns gif table. Example: tGif= gif:new('2dw')

6.1.2 gif load

For the gif example we will use the following gif:

Figure 6.1: Lion-King gif animated

109 MBM Documentation, Release 3.1.f download Lion-King.gif load(string file_name) Load a gif from file. Parameters string – file name from file. Example: mbm.setColor(0.3,0.3,0.7) --blue color of background tGif= gif:new('2dw') if tGif:load('Lion-King.gif') then print('Successfully loaded gif:','Lion-King.gif') else print('Failed to loaded gif:','Lion-King.gif') end

Figure 6.2: Lion-King gif running

Note: The load method will search in all known path. You can add a path to search by the method addPath.

6.1.3 gif setSize setSize(number width, number height) Resize the frame size from gif . Parameters • number – width from frame. • number – height from frame. Example: mbm.setColor(1,1,1) --White color of background tGif= gif:new('2dw') if tGif:load('Lion-King.gif') then tGif:setSize(100,100) else print('Failed to loaded gif:','Lion-King.gif') end

Figure 6.3: Lion-King gif resized to 100 x 100

Note: Always the image gif will adapt to the frame size.

110 Chapter 6. Table gif MBM Documentation, Release 3.1.f

Table of Contents

• Table line – line methods

* line new * line add * line set * line setColor * line size * line drawBounding * line setPhysics * line setPhysics – line shader

* line fragment shader * line vertex shader

6.1. gif methods 111 MBM Documentation, Release 3.1.f

112 Chapter 6. Table gif CHAPTER 7

Table line

A table line inherit from renderizable and implement all methods as usual. Also line has a default animation with a particular shader table which can be accessed by getShader method as usual. This table allow to create lines dynamically. Each table line might have one or more lines.

7.1 line methods

7.1.1 line new

new(string * world, number * x, number * y, number * z) Create a new instance of a line passing the world desired (detail) and position. Parameters • string – world can be 2ds, 2dw or 3d. • number – x position (optional). • number – y position (optional). • number – z position (optional). Returns line table. Example:

tLine= line:new('2dw')

7.1.2 line add

add(table[x,y,*z]) Add new line. Optionally the table might have z coordinate. Each x,y,*z is a point in the line. Parameters table – points to line.

113 MBM Documentation, Release 3.1.f

Returns number - index from current line (1 based). Example: tLine= line:new('2dw') local tPoints={0,0, 100,100} --minimum two points to be a line local index= tLine:add(tPoints) print('Line added index:',index)

Figure 7.1: Draw a simple line at 2d world.

Figure 7.2: Output.

Note the difference to 2D screen. more detail tLine= line:new('2ds') -- 2d screen local tPoints={0,0, 100,100} --minimum two points to be a line local index= tLine:add(tPoints)

7.1.3 line set set(table[x,y,*z], number index) Update the line passing the table and index (1 based). Parameters • table – points to line. • number – index to line. Example:

114 Chapter 7. Table line MBM Documentation, Release 3.1.f

tLine= line:new('2ds') local t={0,0,0,500, 500,500, 500,0,0,0} local index= tLine:add(t) local tNewLine={0,0,0,250, 250,250, 250,0,0,0} tLine:set(tNewLine,index)

7.1.4 line setColor setColor(number r, number g, number b, number * a) Update the color from line passing the color RGB and optionally alpha. Parameters • number – r red color (0 to 1). • number – g green color (0 to 1). • number – b blue color (0 to 1). • number – a alpha color (0 to 1) (optional). Example: mbm.setColor(0,0,0) --set background color to black tLine= line:new('2dw') local tXY={-50,-50,-50,50, 50,50, 50,-50,-50,-50} local index= tLine:add(tXY) tLine:setColor(1,1,1) --white color

Figure 7.3: Set line color to white

Note: This method is directly dependent from current (default) shader used on line. This method look for a variable named color. The shader for line is available here.

7.1.5 line size size Retrieve the size of lines added.

7.1. line methods 115 MBM Documentation, Release 3.1.f

Returns number - size of lines added. Example: tLine= line:new('2ds') local t={0,0,0,500, 500,500, 500,0,0,0} local index= tLine:add(t) local size= tLine:size() -- 1

7.1.6 line drawBounding drawBounding(table renderizable, boolean * useAABB) Draw a bounding from a renderizable. The flag useAABB consider the rotation from a object. Parameters • renderizable – render to set values from physics. • boolean – useAABB is a flag enable AABB (default true). Example: mbm.setColor(0,0,0) --set background color to black tTexture= texture:new('2dw') -- new texture tTexture:load('#ffffffff') -- load white color tTexture:setSize(150,50) tLine= line:new('2dw') tLine:drawBounding(tTexture)

Figure 7.4: Draw a simple bounding line. Get the bound from texture.

Disabled AABB: mbm.setColor(0,0,0) --set background color to black tTexture= texture:new('2dw') -- new texture tTexture:load('#ffffffff') -- load white color tTexture:setSize(150,50) tLine= line:new('2dw') tLine:drawBounding(tTexture)

Enabled AABB: mbm.setColor(0,0,0) --set background color to black tTexture= texture:new('2dw') -- new texture tTexture:load('#ffffffff') -- load white color tTexture:setSize(150,50) (continues on next page)

116 Chapter 7. Table line MBM Documentation, Release 3.1.f

Figure 7.5: Draw a simple bounding line. Get the size from texture not considering AABB.

(continued from previous page) tLine= line:new('2dw') tLine:drawBounding(tTexture,true)

Figure 7.6: Draw a simple bounding line. Get the size from texture considering AABB.

7.1.7 line setPhysics setPhysics(table renderizable, boolean * bDrawLines) Set physic from a renderizable (copy the values to itself). The flag bDrawLines instruct to draw the physics line. It is used in general for debugging proposal. Parameters • renderizable – render to set values from physics. • boolean – bDrawLines instruct to draw the line. Example: tShape= shape:new('2dw') tShape:create('rectangle',100,50) local bDrawLines= true tLine= line:new('2dw') tLine:setPhysics(tShape,bDrawLines)

7.1. line methods 117 MBM Documentation, Release 3.1.f

Figure 7.7: Setting the physics and drawing it.

7.1.8 line setPhysics setPhysics(table tPhysics, boolean * bDrawLines)

Apply physics from a table. The flag bDrawLines instruct to draw the physics line. It is very useful in general for debugging proposal.

Parameters • table – info to set values to physics. • boolean – bDrawLines instruct to draw the line (default is false).

The following table describe the table available for the primitives 2d types:

type / position x,y width, height points ray name information ? information ? information ? information ?

rect yes yes no no circle yes yes no yes ellipse yes yes no yes triangle yes no yes no polygon yes no yes no

Example:

1 function onInitScene()

2

3 mbm.setColor(0,0,0) --set background color to black

4

5 local bDrawLines= true --instruct to draw the lines

6 local tRect={type='rect', width=100, height=100, x=0, y=0}

7 local tCircle={type='circle', ray= 50, x=0, y=0}

8 local tEllipse={type='ellipse', width=100, height=70, x=0, y=0}

9 local tTriangle={type='triangle', x=0, y=0, points={[1]={x=-50,y=-50}, -

˓→-must have 3 points

10 [2]={x=0,y=50},

11 [3]={x=50,y=-50}}}

12 local tPolygon={type='polygon', x=0, y=0, points={ --each 3 points

13 [1]={x=-50,y=-50},

14 [2]={x=0,y=0},

15 [3]={x=40,y=-40},

16 [4]={x=50,y=50},

17 [5]={x=0,y=0}, (continues on next page)

118 Chapter 7. Table line MBM Documentation, Release 3.1.f

(continued from previous page)

18 [6]={x=-50,y=50},

19 [7]={x=-250,y=250},

˓→--this point will be ignored

20 }}

21

22

23 tLineRect= line:new('2dw')

24 tLineRect:setPhysics(tRect,bDrawLines)

25 tLineRect.x=-200

26

27 tLineCircle= line:new('2dw')

28 tLineCircle:setPhysics(tCircle,bDrawLines)

29 tLineCircle.x=-100

30

31 tLineEllipse= line:new('2dw')

32 tLineEllipse:setPhysics(tEllipse,bDrawLines)

33 tLineEllipse.x=0

34

35 tLineTriangle= line:new('2dw')

36 tLineTriangle:setPhysics(tTriangle,bDrawLines)

37 tLineTriangle.x= 100

38

39 tLinePolygon= line:new('2dw')

40 tLinePolygon:setPhysics(tPolygon,bDrawLines)

41 tLinePolygon.x= 200

42

43 tAllObjs={}

44 table.insert(tAllObjs,tLineRect)

45 table.insert(tAllObjs,tLineCircle)

46 table.insert(tAllObjs,tLineEllipse)

47 table.insert(tAllObjs,tLineTriangle)

48 table.insert(tAllObjs,tLinePolygon)

49

50 end

51

52

53 function loop(delta)

54 for i=1,#tAllObjs do

55 local tObj= tAllObjs[i]

56 tObj:rotate('z',math.rad(90))

57 end

58 end

download.

Figure 7.8: Example creating physics from lua table.

7.2 line shader

The table line has its own shader and can be accessed by the shortcut setColor. The equivalent using table shader is:

7.2. line shader 119 MBM Documentation, Release 3.1.f

mbm.setColor(0,0,0)

--common local r,g,b,a=1,1,1,1 local tXY={-50,-50,-50,50, 50,50, 50,-50,-50,-50}

--using setColor to modify the line color tLine_1= line:new('2dw') local index= tLine_1:add(tXY) tLine_1:setColor(r,g,b,a) --set the variable color in the shader to white

--using shader to modify the line color tLine_2= line:new('2dw',200) --200 to right (x) index= tLine_2:add(tXY) local tShader= tLine_2:getShader() tShader:setPSall('color',r,g,b,a)--set the variable color in the shader to white

Figure 7.9: changing color using setcolor and shader directly.

7.2.1 line fragment shader

The fragment shader (pixel shader) used for the line is: precision mediump float; uniform vec4 color; void main() { gl_FragColor= color; }

7.2.2 line vertex shader

The vertex shader used for the line is: attribute vec4 aPosition; uniform mat4 mvpMatrix; void main() { gl_Position= mvpMatrix * aPosition; }

120 Chapter 7. Table line MBM Documentation, Release 3.1.f

Table of Contents

• Table mesh – mesh methods

* mesh new * mesh load – Creating a mesh programmatically

* Mesh to a binary file * Create a cube and fill the texture coordinates – Importing mesh

7.2. line shader 121 MBM Documentation, Release 3.1.f

122 Chapter 7. Table line CHAPTER 8

Table mesh

A table mesh inherit from renderizable and implement all methods as usual.. Each animation on mesh has an initial frame and final frame which represent its cycle. Also each animation has a shader table by default which can be accessed by getShader method.

8.1 mesh methods

8.1.1 mesh new new(string * world, number * x, number * y, number * z) Create a new instance of a mesh passing the world desired (detail) and position. Parameters • string – world can be 2ds, 2dw or 3d. • number – x position (optional). • number – y position (optional). • number – z position (optional). Returns mesh table. Example: tMesh= mesh:new('3d') --note that mesh inherits from renderizable

8.1.2 mesh load load(string file_name)

Load a mesh from a binary file (expected .msh extension).

123 MBM Documentation, Release 3.1.f

Parameters string – file name from binary file.

Example: tMesh= mesh:new('3d') if tMesh:load('crate.msh') then print('Successfully loaded mesh:','crate.msh') else print('Failed to loaded mesh:','crate.msh') end

Note: The load method will search in all known path. You can add a path to search by the method addPath.

If you want to create a binary file next an example how to do that.

8.2 Creating a mesh programmatically

It is possible to save any mesh with help of meshDebug. For that it is necessary to prepare the meshDebug based on our renderizable. • First, we have to create coordinates of vertex buffer (indexed buffer based). • We also need to create index buffer (1 index based) for the vertex. • Then we create a meshDebug which will store all the information. • The UV and normal coordinates are not mandatory. For this example we will not fill it. • Next we create a frame informing the stride and add a new subset. • One frame can have one or more subsets. Each subset has its own texture. • Next we add the vertex buffer and index buffer. • The vertex buffer can have normal buffer (optional) and texture coordinates (optional). • Next we set the mesh type (others types are sprite, particle, font, . . . ). • Finally we just need to specify the file name to save through the function save. For the next examples we will use the following texture:

8.2.1 Mesh to a binary file

Follow an example how to save a mesh to a binary file:

1 mbm.setColor(1,1,1) --set background color to white

2

3 function createCubeFace()

4

5 local tCube= { {x=-50,y=-50,z=0},

6 {x=-50,y=50,z=0},

7 {x=50,y=-50,z=0}, (continues on next page)

124 Chapter 8. Table mesh MBM Documentation, Release 3.1.f

Figure 8.1: crate.png

(continued from previous page)

8 {x=50,y=50,z=0}}

9 local tIndex={1,2,3,3,2,4}

10 local sTextureFileName='crate.png'

11

12 return tCube, tIndex, sTextureFileName

13 end

14

15 function saveMeshToBinaryFile(fileName,tVertex,tIndex,sTexture)

16

17 --meshDebug is used to create dynamically mesh in the engine.

18 --For mesh it has to have at least one frame to be able to generate the

˓→mesh

19 local stride=3 --stride only can be 3 or 2. it means (x,y,z) or

˓→(x,y)

20 local tMesh= meshDebug:new() --new mesh debug to store the

˓→information about our mesh

21 local nFrame= tMesh:addFrame(stride) -- Add one frame with stride

˓→3 (x,y,z)

22 local indexFrame= nFrame --(meshDebug uses 1 based index)

23 local indexSubset=1 --first subset (1 based index)

24

25

26 --To add vertex, first we need to add a subset

27 local nSubset= tMesh:addSubSet(indexFrame) --add one subset for the

˓→first frame

28

29 --we are adding vertex to frame (next)

30 --this vertex list has to have at least 3 vertex (one triangle) to be

˓→valid

31 -- The table expected is : {{x,y,z},{x,y,z},{x,y,z}, ...}

32 if not tMesh:addVertex(indexFrame,indexSubset,tVertex) then

33 print("Error on add vertex buffer")

34 return false

35 end

36

37 if not tMesh:addIndex(indexFrame,indexSubset,tIndex) then

38 print("Error on add index buffer")

39 return false

40 end (continues on next page)

8.2. Creating a mesh programmatically 125 MBM Documentation, Release 3.1.f

(continued from previous page)

41

42 --apply the texture to frame / subset

43 if not tMesh:setTexture(indexFrame,indexSubset,sTexture) then

44 print("Error on set texture!")

45 return false

46 end

47

48 tMesh:setType('mesh') -- set it to mesh type

49

50 local calcNormal,calcUv= true,true --Instruct to calculate normal and UV

51 if tMesh:save(fileName,calcNormal,calcUv) then

52 print("Mesh created successfully")

53 return true

54 else

55 print("Failed to create Mesh!")

56 return false

57 end

58

59 end

60

61

62 function onInitScene()

63

64 tMesh= mesh:new('3D') -- our object which will load from binary file

65

66 local sFileNameMesh='crate.msh'

67

68 local tCubeVertex, tCubeIndex, sCubeTextureFileName= createCubeFace() --

˓→create our cube face

69

70 if saveMeshToBinaryFile(sFileNameMesh,tCubeVertex, tCubeIndex,

˓→sCubeTextureFileName) then

71 tMesh:load(sFileNameMesh) --all coordinate already in place

72 else

73 print('Failed to create'.. sFileNameMesh)

74 mbm.quit()

75 end

76

77

78 --set up camera

79 camera3d= mbm.getCamera('3D')

80 camera3d:setPos(0,0,-500)

81 camera3d:setFocus(0,0,0)

82

83 --need to rotate our object

84 tMouse= {x=0,y=0,clicked= false}

85 end

86

87 function onTouchDown(key,x,y)

88 tMouse.clicked= true

89 tMouse.x=x

90 tMouse.y=y

91 end

92

93 function onTouchMove(key,x,y)

94 if tMouse.clicked then

95 local diff_X= tMouse.x-x (continues on next page)

126 Chapter 8. Table mesh MBM Documentation, Release 3.1.f

(continued from previous page)

96 local diff_Y= tMouse.y-y

97 tMouse.x=x

98 tMouse.y=y

99

100 --simple rotation based on mouse

101 tMesh.ay= tMesh.ay+ math.rad(diff_X)

102 tMesh.ax= tMesh.ax+ math.rad(diff_Y)

103

104 end

105 end

106

107 function onTouchUp(key,x,y)

108 tMouse.clicked= false

109 end

download.

Figure 8.2: Mesh flat simple (two triangles)

8.2.2 Create a cube and fill the texture coordinates

For the next example we will create a cube and fill it with our texture coordinates.

mbm.setColor(1,1,1) --set background color to white

function createCube(width,height,depth) --[[ k-uv=1,1 uv=0,0-f______g-uv=1,0, i-uv=0,1 / /| / / | uv=0,1-b /______/c-uv=1,1 | | | | | | | | | | back | | uv=0,1-e|______|___|h-uv=1,1 j-uv=0,0 l-uv=1,1 / | / | / | / |/______|/ uv=0,0-a front d-uv=1,0

]]--

local halfSizeCube={x= width/2, y= height/2, z= depth/2}

local pa= {x=-halfSizeCube.x, y=-halfSizeCube.y, z=-

˓→halfSizeCube.z, u=0, v=0}; local pb= {x=-halfSizeCube.x, y= halfSizeCube.y, z=-

˓→halfSizeCube.z, u=0, v=1}; local pc= {x= halfSizeCube.x, y= halfSizeCube.y, z=-

˓→halfSizeCube.z, u=1, v=1}; local pd= {x= halfSizeCube.x, y=-halfSizeCube.y, z=-

˓→halfSizeCube.z, u=1, v=0}; local pe= {x=-halfSizeCube.x, y=-halfSizeCube.y, z= ˓→halfSizeCube.z, u=0, v=1}; (continues on next page)

8.2. Creating a mesh programmatically 127 MBM Documentation, Release 3.1.f

(continued from previous page) local pf= {x=-halfSizeCube.x, y= halfSizeCube.y, z=

˓→halfSizeCube.z, u=0, v=0}; local pg= {x= halfSizeCube.x, y= halfSizeCube.y, z=

˓→halfSizeCube.z, u=1, v=0}; local ph= {x= halfSizeCube.x, y=-halfSizeCube.y, z=

˓→halfSizeCube.z, u=1, v=1};

--extra because of the texture coordinates local pi= {x= halfSizeCube.x, y= halfSizeCube.y, z=

˓→halfSizeCube.z, u=0, v=1}; local pj= {x= halfSizeCube.x, y=-halfSizeCube.y, z=

˓→halfSizeCube.z, u=0, v=0};

local pk= {x=-halfSizeCube.x, y= halfSizeCube.y, z=

˓→halfSizeCube.z, u=1, v=1}; local pl= {x=-halfSizeCube.x, y=-halfSizeCube.y, z=

˓→halfSizeCube.z, u=1, v=0};

local tCube= {pa,pb,pc,pd,pe,pf,pg,ph,pi,pj,pk,pl};

local a,b,c,d,e,f,g,h,i,j,k,l=1,2,3,4,5,6,7,8,9,10,11,12

local tIndex= { a,b,d, d,b,c, -- front d,c,i, d,i,j, -- right a,l,k, k,b,a, -- left h,g,e, e,g,f, -- back b,f,c, c,f,g, -- top a,d,e, h,e,d -- bellow } local sTextureFileName='crate.png'

return tCube, tIndex, sTextureFileName end

function saveMeshToBinaryFile(fileName,tVertex,tIndex,sTexture)

--meshDebug is used to create dynamically mesh in the engine. --For mesh it has to have at least one frame to be able to generate the

˓→mesh local stride=3 --stride only can be 3 or 2. it means (x,y,z) or

˓→(x,y) local tMesh= meshDebug:new() --new mesh debug to store the

˓→information about our mesh local nFrame= tMesh:addFrame(stride) -- Add one frame with stride

˓→3 (x,y,z) local indexFrame= nFrame --(meshDebug uses 1 based index) local indexSubset=1 --first subset (1 based index)

--To add vertex, first we need to add a subset local nSubset= tMesh:addSubSet(indexFrame) --add one subset for the

˓→first frame

--we are adding vertex to frame (next) --this vertex list has to have at least 3 vertex (one triangle) to be

˓→valid -- The table expected is : {{x,y,z},{x,y,z},{x,y,z}, ...} (continues on next page)

128 Chapter 8. Table mesh MBM Documentation, Release 3.1.f

(continued from previous page) if not tMesh:addVertex(indexFrame,indexSubset,tVertex) then print("Error on add vertex buffer") return false end

if not tMesh:addIndex(indexFrame,indexSubset,tIndex) then print("Error on add index buffer") return false end

--apply the texture to frame / subset if not tMesh:setTexture(indexFrame,indexSubset,sTexture) then print("Error on set texture!") return false end

tMesh:setType('mesh') -- set it to mesh type

local calcNormal,calcUv= true,false --Instruct to calculate normal if tMesh:save(fileName,calcNormal,calcUv) then print("Mesh created successfully") return true else print("Failed to create Mesh!") return false end

end

function onInitScene()

tMesh= mesh:new('3D') -- our object which will load from binary file

local sFileNameMesh='crate.msh'

local width, height, depth= 100, 100, 100

local tCubeVertex, tCubeIndex, sCubeTextureFileName= createCube(width,

˓→height, depth)--create our cube

if saveMeshToBinaryFile(sFileNameMesh,tCubeVertex, tCubeIndex,

˓→sCubeTextureFileName) then tMesh:load(sFileNameMesh) --all coordinate already in place else print('Failed to create'.. sFileNameMesh) mbm.quit() end

--set up camera camera3d= mbm.getCamera('3D') camera3d:setPos(0,0,-500) camera3d:setFocus(0,0,0)

--need to rotate our object tMouse= {x=0,y=0,clicked= false} (continues on next page)

8.2. Creating a mesh programmatically 129 MBM Documentation, Release 3.1.f

(continued from previous page) end

function onTouchDown(key,x,y) tMouse.clicked= true tMouse.x=x tMouse.y=y end

function onTouchMove(key,x,y) if tMouse.clicked then local diff_X= tMouse.x-x local diff_Y= tMouse.y-y tMouse.x=x tMouse.y=y

--simple rotation based on mouse tMesh.ay= tMesh.ay+ math.rad(diff_X) tMesh.ax= tMesh.ax+ math.rad(diff_Y)

end end

function onTouchUp(key,x,y) tMouse.clicked= false end

download.

Figure 8.3: Mesh cube 3D filled with texture coordinates

8.3 Importing mesh

You can find how to Import mesh and also some examples in the modules topic. There you will find some tips and ready to use modules.

Table of Contents

• Table meshDebug – Primitive options

* mode draw * cull face * front face direction – static methods

* meshDebug getInfo * meshDebug getType * meshDebug getExt

130 Chapter 8. Table mesh MBM Documentation, Release 3.1.f

– meshDebug methods

* meshDebug new * meshDebug load * meshDebug save * meshDebug setType * meshDebug animation * meshDebug mode draw * meshDebug Cull face * meshDebug front face * meshDebug frame * meshDebug subset * meshDebug vertex * meshDebug index buffer * meshDebug texture * meshDebug stride * meshDebug normal * meshDebug UV * meshDebug Physics * meshDebug centralize

8.3. Importing mesh 131 MBM Documentation, Release 3.1.f

132 Chapter 8. Table mesh CHAPTER 9

Table meshDebug

The table meshDebug is used to build, debug and save to binary file any format supported by the engine. The idea of this object, is to construct any object available in the engine or import an object from the well know Wavefront for example. The table meshDebug is not a renderizable object, than, there is no common methods inherited. The table meshDebug support the following types from engine:

Types Expected file extension mesh msh sprite spt font fnt texture png jpeg etc shape - particle ptl tile tile

9.1 Primitive options

Primitive determines how consecutive vertices are organized into primitives (triangles), and determines the type of primitive that is used at the beginning of the graphics pipeline.

Follow some explanation of the main options for primitives used in the engine.

9.1.1 mode draw

The mode draw is the way to specific triangle primitives. It is based on different interpretations of the vertex stream.

133 MBM Documentation, Release 3.1.f

Next the table explaining the interpretation of each of them:

134 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Mode Explanation TRIANGLES Given the vertices, vertices 1, 2, and 3 form a triangle, vertices 4, 5, and 6 form a triangle, and so on.

TRIANGLE_STRIP Given the vertices, Every group of 3 adjacent vertices forms a triangle.

TRIANGLE_FAN Given the vertices, The first vertex is always held fixed. From there on, every group of 2 adjacent vertices form a triangle with the first. you get a list of triangles like so: (0, 1, 2) (0, 2, 3), (0, 3, 4), etc

LINES Given the vertices, vertices 1 and 2 form a line, vertices 3 and 4 form a lines and so on.

9.1. Primitive options 135

LINE_LOOP Given the vertices, vertices 1 and 2 form a line, vertices 3, 4, and 5 form a more three lines and the last vertex will connect to the first vertex.

LINE_STRIP Given the vertices, Every group of 2 adjacent vertices forms a line.

POINTS Given the vertices, each vertex will be a point MBM Documentation, Release 3.1.f

Important: The default mode draw for the engine is TRIANGLES. It is only possible to change the mode draw through meshDebug setModeDraw method.

9.1.2 cull face

Triangle primitives after all transformation steps have a particular facing. This is defined by the order of the three vertices that make up the triangle, as well as their apparent order on-screen. Triangles can be discarded based on their apparent facing, a process known as face culling.

Next the table the engine option:

Types Comment FRONT BACK Default for the engine. FRONT_AND_BACK Will draw both sides.

9.1.3 front face direction

Triangle primitives are drawing following the direction clockwise or counter-clockwise.

The table shows the directions:

136 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Types Comment CW Default for the engine.

CCW

9.2 static methods

9.2.1 meshDebug getInfo getInfo(string file_name) Parameters string – file_name to be save.

9.2. static methods 137 MBM Documentation, Release 3.1.f

Returns table - result. Example: local infoTable= meshDebug:getInfo('crate.msh') if infoTable then print('info','The table has the following information:') for k, v in pairs(infoTable) do if type(v) =='table' then for k2, v2 in pairs(v) do print(k, k2, v2) end else print( k, v) end end end

Figure 9.1: Possible output.

Note: This method does not need a instance of meshDebug. It is static. The types are described at this table.

9.2.2 meshDebug getType getType(string file_name) Parameters string – file_name of mesh.

138 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Returns string - will be one of option from table type of mesh. Example: local type= meshDebug:getType('crate.msh') print('info','type of crate.msh',type) --possible output: --type of crate.msh mesh

Note: This method does not need a instance of meshDebug. It is static. The types are described at this table.

9.2.3 meshDebug getExt getExt(string file_name) Given an string it will return the extension. Will look for the last . in the string and return the string after that.

Parameters string – file_name of mesh. Returns string - extension.

Example: local ext= meshDebug:getType('crate.msh') print('expected msh:',ext) --output: --expected msh:msh

Note: This method does not need a instance of meshDebug. It is static.

9.3 meshDebug methods

9.3.1 meshDebug new new Create a new instance of a meshDebug . Returns meshDebug table. Example: tMyMesh= meshDebug:new()

9.3. meshDebug methods 139 MBM Documentation, Release 3.1.f

9.3.2 meshDebug load load(string file_name) Parameters string – file_name to be loaded. Returns boolean - result. Example: tMyMesh= meshDebug:new() if tMyMesh:load("particle.ptl") then print("Success ...") else print("Failed to load mesh...") end

Note: The load method will search in all known path. You can add a path to search by the method addPath. The types are described at this table. load(renderizable mesh) Parameters renderizable – mesh to be loaded from memory. Returns boolean - result. Example: tMyMesh= meshDebug:new() tSprite= sprite:new() if tSprite:load('mike.spt') then if tMyMesh:load(tSprite) then print("Success loaded sprite from memory...") else print("Failed to load mesh...") end else print("Failed to load sprite...") end

Important: The USE_EDITOR_FEATURES flag must be enabled to this method work.

9.3.3 meshDebug save save(string file_name) Parameters string – file_name to be save. Returns boolean - result. Example:

140 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

tMyMesh= meshDebug:new() if tMyMesh:load("mario.spt") then --do something (modify vertex etc) if tMyMesh:save("mario2.spt") then print("Success ...") else print("Failed to save file") end else print("Failed to load mesh...") end

Note: The types are described at this table.

9.3.4 meshDebug setType setType(string new_type) Modify or set the internal type of mesh.

Parameters string – could be one of option from table type of mesh. Returns boolean - result.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then print('my type:', tMesh:getType()) tMesh:setType('sprite') print('my new type:', tMesh:getType()) end

Note: The types are described at this table.

9.3.5 meshDebug animation addAnim(string name, number initialFrame, number finalFrame, number timeBetweenFrame, number typeAn- imation) Add a new animation. Parameters • string – name of animation (new). • number – index initial frame one based. • number – index final frame one based. • number – time between frames. • number – type animation (see type of animation).

9.3. meshDebug methods 141 MBM Documentation, Release 3.1.f

Returns number - Index animation added one based. See animation animation for more detail. Example getting an animation: tMyMeshDebug= meshDebug:new() if tMyMeshDebug:load('crate.msh') then local animation_name='default' local initialFrame=1 local finalFrame= 10 local timeBetweenFrame= 0.3 local typeAnimation= mbm.GROWING_LOOP

local index= tMyMeshDebug:addAnim(animation_name,initialFrame,finalFrame,

˓→timeBetweenFrame,typeAnimation) print('animation added number:',index) end

Note: Note that this method differs from addAnim inherited from renderizable because it is not a renderizable. If the initial frame or final frame is out of range the function will fail. getAnim(number index_animation) Get detail of animation.

Parameters number – index_animation from 1 to max number of animation. Returns string, number, number, number, number - Animation name,initial frame,final frame, time between frame, type of animation.

See animation animation for more detail. Example getting an animation: tMyMeshDebug= meshDebug:new() if tMyMeshDebug:load('crate.msh') then local animation,initialFrame,finalFrame, timeBetweenFrame, typeAnimation=

˓→tMyMeshDebug:getAnim(1) print('animation :',animation) print('initialFrame :',initialFrame) print('finalFrame :',finalFrame) print('timeBetweenFrame:',timeBetweenFrame) print('typeAnimation :',typeAnimation) end

Note: Note that this method differs from getAnim inherited from renderizable because it is not a renderizable.

Note: Note that this method differs from getAnim inherited from renderizable because it is not a renderizable. updateAnim(number index, string name, number initialFrame, number finalFrame, number timeBetween- Frame, number typeAnimation) Update an existent animation.

142 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Figure 9.2: Possible output.

Parameters • number – index animation one based. • string – name of animation (new). • number – index initial frame one based. • number – index final frame one based. • number – time between frames. • number – type animation (see type of animation). Example: tMesh= meshDebug:new() if tMesh:load('Mech.msh') then tMesh:updateAnim(1,'stand',1,5,0.33,mbm.GROWING_LOOP) end copyAnimationsFromMesh(table renderizable) Will copy each animation and shader detail from mesh passed as parameter. The mesh passed as parameter must be loaded in memory to work.

Parameters renderizable – mesh to copy animation and shader. Returns boolean - result.

Example: tMesh= mesh:new() if tMesh:load('crate.msh') then tMyMeshDebug= meshDebug:new() local animation,initialFrame,finalFrame, timeBetweenFrame, typeAnimation=

˓→tMyMeshDebug:getAnim(1) print('Before copy animation from crate.msh, animation :',animation) print('Before copy animation from crate.msh, initialFrame :',initialFrame) print('Before copy animation from crate.msh, finalFrame :',finalFrame) print('Before copy animation from crate.msh, timeBetweenFrame:',timeBetweenFrame) print('Before copy animation from crate.msh, typeAnimation :',typeAnimation)

if tMyMeshDebug:copyAnimationsFromMesh(tMesh) then animation,initialFrame,finalFrame, timeBetweenFrame, typeAnimation=

˓→tMyMeshDebug:getAnim(1) print('green','Now meshDebug has the same animation details as tMesh') (continues on next page)

9.3. meshDebug methods 143 MBM Documentation, Release 3.1.f

(continued from previous page) print('Before copy animation from crate.msh, animation :',animation) print('After copy animation from crate.msh, initialFrame :',initialFrame) print('After copy animation from crate.msh, finalFrame :',finalFrame) print('After copy animation from crate.msh, timeBetweenFrame:',

˓→timeBetweenFrame) print('After copy animation from crate.msh, typeAnimation :',typeAnimation) end end

Figure 9.3: Possible output.

9.3.6 meshDebug mode draw setModeDraw(string mode) Modify the mode of draw.

Parameters string – mode could be one of option from table modeDraw.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then print('Mode draw before:', tMesh:getModeDraw()) tMesh:setModeDraw('TRIANGLE_FAN') print('Mode draw after:', tMesh:getModeDraw()) end

getModeDraw(string mode) Retrieve the mode of draw.

Returns mode will be one of option from table modeDraw.

144 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then print('Mode draw before:', tMesh:getModeDraw()) tMesh:setModeDraw('TRIANGLE_FAN') print('Mode draw after:', tMesh:getModeDraw()) end

Figure 9.4: mode draw

9.3.7 meshDebug Cull face setModeCullFace(string mode) Modify the mode cullFace face.

Parameters string – mode could be one of option from table cullFace.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then print('Mode cull face before:', tMesh:getModeCullFace()) tMesh:setModeCullFace('BACK') print('Mode cull face after:', tMesh:getModeCullFace()) end getModeCullFace(string mode) Modify the mode cullFace face.

Returns mode will be one of option from table cullFace.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then print('Mode cull face before:', tMesh:getModeCullFace()) tMesh:setModeCullFace('BACK') print('Mode cull face after:', tMesh:getModeCullFace()) end

9.3.8 meshDebug front face setModeFrontFace(string mode) Modify the mode front face.

9.3. meshDebug methods 145 MBM Documentation, Release 3.1.f

Parameters string – mode could be one of option from table front face.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then print('Mode front face before:', tMesh:getModeFrontFace()) tMesh:setModeFrontFace('CW') print('Mode front face after:', tMesh:getModeFrontFace()) end getModeFrontFace(string mode) Retrieve the mode front face.

Returns mode will be one of option from table front face.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then print('Mode front face before:', tMesh:getModeFrontFace()) tMesh:setModeFrontFace('CW') print('Mode front face after:', tMesh:getModeFrontFace()) end

9.3.9 meshDebug frame getTotalFrame Retrieve the total frame of mesh.

Returns number total of frame.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then local total_frame= tMesh:getTotalFrame() print('the mesh has' , total_frame,' frames') end

9.3.10 meshDebug subset getTotalSubset(number frame) Retrieve the total subset given a frame.

Parameters number – frame . Returns number total of subset in the indicated frame.

Example:

146 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

tMesh= meshDebug:new() if tMesh:load('crate.msh') then

local total_subset= tMesh:getTotalSubset(1) print('the mesh has' , total_subset,' subset at frame 1') end

9.3.11 meshDebug vertex addVertex(number frame, number subset) Add a single vertex given frame and subset.

Parameters • number – frame • number – subset Returns boolean result of operation.

Example: tMesh= meshDebug:new() local result= tMesh:addVertex(1,1) addVertex(number frame, number subset, number total_vertex) Add vertex given frame, subset and the total of vertex.

Parameters • number – frame • number – subset • number – total vertex to be added Returns boolean result of operation.

Example: tMesh= meshDebug:new() local total_vertex=5 local result= tMesh:addVertex(1,1,total_vertex) addVertex(number frame, number subset, table vertex) Add a vertex given frame, subset and the vertex itself in a table.

Parameters • number – frame • number – subset • table – vertex to be added {x,y,z,nx,ny,nz,u,v} Returns boolean result of operation.

9.3. meshDebug methods 147 MBM Documentation, Release 3.1.f

Example: tMesh= meshDebug:new() local vertex= {x=0,y= 10,z=1,nx=0,ny=0 ,nz=1,u=0 ,v=1} local result= tMesh:addVertex(1,1,vertex) addVertex(number frame, number subset, table vertex_array) Add an array of vertex given frame, subset and the vertex array in a table.

Parameters • number – frame • number – subset • table – vertex array to be added {{x,y,z,nx,ny,nz,u,v},{x,y,z,nx,ny,nz, u,v}, ... Returns boolean result of operation.

Example: tMesh= meshDebug:new() local vertex= {{x=0,y= 10,z=1,nx=0,ny=0 ,nz=1,u=0 ,v=1}, {x=1,y=0,

˓→z=1,nx=0,ny=0 ,nz=1,u= 0.5 ,v= 0.5}} local result= tMesh:addVertex(1,1,vertex) getTotalVertex(number frame, number subset) Retrieve the total vertex given frame and subset.

Parameters • number – frame • number – subset Returns number total of vertex in the indicated frame from subset.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then

local total_vertex= tMesh:getTotalVertex(1,1) print('the mesh has' , total_vertex,' vertex in the subset (1) at frame (1)') end getVertex(number * index_frame, number * index_subset, number * index_vertex, number * max_vertex_return) Get one or more vertices.

Parameters • number – index_frame from 1 to max number of frame (use getTotalFrame) (default is 1) • number – index_subset from 1 to max number of subset (use getTotalSubset) (default is 1) • number – index_vertex from 1 to max number of vertex (use getTotalVertex) (default is 1)

148 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

• number – max_vertex_return from 1 to max number of vertex (use getTotalVertex) (de- fault is 1) Returns single table or multiples table filled with the vertices.

The Table will have x,y,z coordinates, u,v map to texture and nx,ny,nz representing the normal. Example getting a single vertex: tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local vertex= tMesh:getVertex() -- will retrieve 1 because the default value (1

˓→for total vertex, so one single table) print('x:', vertex.x) print('y:', vertex.y) print('z:', vertex.z) print('u:', vertex.u) print('v:', vertex.v) print('nx:', vertex.nx) print('ny:', vertex.ny) print('nz:', vertex.nz) end

Figure 9.5: Possible output

Example getting a specific single vertex: tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local index_frame=1 local index_subset=1 local index_vertex= 10 --our specific vertex

local vertex= tMesh:getVertex(index_frame,index_subset,index_vertex) print('x:', vertex.x) print('y:', vertex.y) print('z:', vertex.z) print('u:', vertex.u) print('v:', vertex.v) print('nx:', vertex.nx) print('ny:', vertex.ny) print('nz:', vertex.nz) end

Example getting a designed amount of vertex:

9.3. meshDebug methods 149 MBM Documentation, Release 3.1.f

Figure 9.6: Possible output

tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local index_frame=1 local index_subset=1 local index_vertex= 10 --our specific vertex local total_vertex=3 -- we want 3 vertices --(you can get them all , just pass a number very high, like 9E9)

local vertices= tMesh:getVertex(index_frame,index_subset,index_vertex,total_

˓→vertex) for i=1,#vertices do local vertex= vertices[1] print('\nVertex number:',i ) print('x:', vertex.x) print('y:', vertex.y) print('z:', vertex.z) print('u:', vertex.u) print('v:', vertex.v) print('nx:', vertex.nx) print('ny:', vertex.ny) print('nz:', vertex.nz) end end setVertex(number index_frame, number index_subset, number index_vertex, number max_vertex_return, table vertex) Set one or more vertices.

Parameters • number – index_frame from 1 to max number of frame (use getTotalFrame) • number – index_subset from 1 to max number of subset (use getTotalSubset) • number – index_vertex from 1 to max number of vertex (use getTotalVertex) • number – max_vertex_return from 1 to max number of vertex (use getTotalVertex) • table – vertex to be set. the table can be unique or array.

The Table could have x,y,z coordinates, u,v map to texture and nx,ny,nz representing the normal. Values

150 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Figure 9.7: Possible output

9.3. meshDebug methods 151 MBM Documentation, Release 3.1.f

not set will not be changed. Example setting a single vertex: function printVertex(vertex) print('\n') print('x:', vertex.x) print('y:', vertex.y) print('z:', vertex.z) print('u:', vertex.u) print('v:', vertex.v) print('nx:', vertex.nx) print('ny:', vertex.ny) print('nz:', vertex.nz) end tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local index_frame=1 local index_subset=1 local index_vertex= 10 --our specific vertex

local vertex= tMesh:getVertex(index_frame,index_subset,index_vertex)

printVertex(vertex)

vertex.x=0 vertex.y=1 vertex.z=2 vertex.nx= 10 vertex.ny= 11 vertex.nz= 12 vertex.u= nil vertex.v= nil --we will not modify u and v

tMesh:setVertex(index_frame,index_subset,index_vertex,vertex)

vertex= tMesh:getVertex(index_frame,index_subset,index_vertex) printVertex(vertex) end

Example setting two vertices: function printVertex(vertex) print('\n') print('x:', vertex.x) print('y:', vertex.y) print('z:', vertex.z) print('u:', vertex.u) print('v:', vertex.v) print('nx:', vertex.nx) print('ny:', vertex.ny) print('nz:', vertex.nz) end tMesh= meshDebug:new() (continues on next page)

152 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Figure 9.8: Possible output

9.3. meshDebug methods 153 MBM Documentation, Release 3.1.f

(continued from previous page) if tMesh:load('Mech.msh') then local index_frame=1 local index_subset=1 local index_vertex= 10 --our specific vertex

local vertex= tMesh:getVertex(index_frame,index_subset,index_vertex)

printVertex(vertex)

vertex.x=3 vertex.y=2 vertex.z=1 vertex.nx= 1.10 vertex.ny= 1.11 vertex.nz= 1.12 vertex.u= nil vertex.v= nil --we will not modify u and v tVertices={[1]= vertex, [2]= vertex} --we instruct to change itself and the

˓→next one

tMesh:setVertex(index_frame,index_subset,index_vertex,tVertices)

vertex= tMesh:getVertex(index_frame,index_subset,index_vertex+1) -- we will get

˓→the next vertex

printVertex(vertex) end

9.3.12 meshDebug index buffer getTotalIndex(number frame, number subset) Retrieve the total index buffer given frame and subset.

Parameters • number – frame • number – subset Returns number total of index buffer in the indicated frame from subset.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then

local index_buffer= tMesh:getTotalIndex(1,1) print('the mesh has' , index_buffer,' index buffer in the subset (1) at frame

˓→(1)') end isIndexBuffer

154 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Figure 9.9: Possible output

9.3. meshDebug methods 155 MBM Documentation, Release 3.1.f

Verify if is indexed buffer.

Returns boolean result indicating if is indexed buffer.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then

local bIndexed= tMesh:isIndexBuffer() print('the mesh is indexed buffer:', tostring(bIndexed)) end getIndex(number frame, number subset) Retrieve a index buffer given frame and subset.

Parameters • number – frame • number – subset Returns table result of operation.

Example: tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local index_frame=1 local index_subset=1

local indexBuffer= tMesh:getIndex(index_frame,index_subset) if indexBuffer then --has index buffer for i=1,#indexBuffer do print(indexBuffer[i]) end else print('Object hs no index buffer!') end end addIndex(number frame, number subset, table index_array) Add index buffer given frame and subset.

Parameters • number – frame • number – subset • table – index array (one based) Returns boolean result of operation.

Follow an example how to add index buffer and how to save a mesh to a binary file:

156 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Figure 9.10: Dummy index buffer

9.3. meshDebug methods 157 MBM Documentation, Release 3.1.f

1 mbm.setColor(1,1,1) --set background color to white

2

3 function createCubeFace()

4

5 local tCube= { {x=-50,y=-50,z=0},

6 {x=-50,y=50,z=0},

7 {x=50,y=-50,z=0},

8 {x=50,y=50,z=0}}

9 local tIndex={1,2,3,3,2,4}

10 local sTextureFileName='crate.png'

11

12 return tCube, tIndex, sTextureFileName

13 end

14

15 function saveMeshToBinaryFile(fileName,tVertex,tIndex,sTexture)

16

17 --meshDebug is used to create dynamically mesh in the engine.

18 --For mesh it has to have at least one frame to be able to

˓→generate the mesh

19 local stride=3 --stride only can be 3 or 2. it means (x,y,

˓→z) or (x,y)

20 local tMesh= meshDebug:new() --new mesh debug to store

˓→the information about our mesh

21 local nFrame= tMesh:addFrame(stride) -- Add one frame with

˓→stride 3 (x,y,z)

22 local indexFrame= nFrame --(meshDebug uses 1 based index)

23 local indexSubset=1 --first subset (1 based index)

24

25

26 --To add vertex, first we need to add a subset

27 local nSubset= tMesh:addSubSet(indexFrame) --add one subset

˓→for the first frame

28

29 --we are adding vertex to frame (next)

30 --this vertex list has to have at least 3 vertex (one triangle)

˓→to be valid

31 -- The table expected is : {{x,y,z},{x,y,z},{x,y,z}, ...}

32 if not tMesh:addVertex(indexFrame,indexSubset,tVertex) then

33 print("Error on add vertex buffer")

34 return false

35 end

36

37 if not tMesh:addIndex(indexFrame,indexSubset,tIndex) then

38 print("Error on add index buffer")

39 return false

40 end

41

42 --apply the texture to frame / subset

43 if not tMesh:setTexture(indexFrame,indexSubset,sTexture) then

44 print("Error on set texture!")

45 return false

46 end

47

48 tMesh:setType('mesh') -- set it to mesh type

49

50 local calcNormal,calcUv= true,true --Instruct to calculate

˓→normal and UV

(continues on next page)

158 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

(continued from previous page)

51 if tMesh:save(fileName,calcNormal,calcUv) then

52 print("Mesh created successfully")

53 return true

54 else

55 print("Failed to create Mesh!")

56 return false

57 end

58

59 end

60

61

62 function onInitScene()

63

64 tMesh= mesh:new('3D') -- our object which will load from binary

˓→file

65

66 local sFileNameMesh='crate.msh'

67

68 local tCubeVertex, tCubeIndex, sCubeTextureFileName=

˓→createCubeFace()--create our cube face

69

70 if saveMeshToBinaryFile(sFileNameMesh,tCubeVertex, tCubeIndex,

˓→sCubeTextureFileName) then

71 tMesh:load(sFileNameMesh) --all coordinate already in place

72 else

73 print('Failed to create'.. sFileNameMesh)

74 mbm.quit()

75 end

76

77

78 --set up camera

79 camera3d= mbm.getCamera('3D')

80 camera3d:setPos(0,0,-500)

81 camera3d:setFocus(0,0,0)

82

83 --need to rotate our object

84 tMouse= {x=0,y=0,clicked= false}

85 end

86

87 function onTouchDown(key,x,y)

88 tMouse.clicked= true

89 tMouse.x=x

90 tMouse.y=y

91 end

92

93 function onTouchMove(key,x,y)

94 if tMouse.clicked then

95 local diff_X= tMouse.x-x

96 local diff_Y= tMouse.y-y

97 tMouse.x=x

98 tMouse.y=y

99

100 --simple rotation based on mouse

101 tMesh.ay= tMesh.ay+ math.rad(diff_X)

102 tMesh.ax= tMesh.ax+ math.rad(diff_Y)

103

104 end (continues on next page)

9.3. meshDebug methods 159 MBM Documentation, Release 3.1.f

(continued from previous page)

105 end

106

107 function onTouchUp(key,x,y)

108 tMouse.clicked= false

109 end

download.

Figure 9.11: Adding index buffer

9.3.13 meshDebug texture getTexture(number frame, number subset) Get the current texture name given frame and subset. Parameters • number – frame • number – subset Returns string - file name from texture. Example:

tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local index_frame=1 local index_subset=1

local texture= tMesh:getTexture(index_frame,index_subset) if texture then --has texture print('texture:',texture) else print('Object has no texture!') end end

Figure 9.12: Get the texture name from meshDebug

setTexture(number frame, number subset, string texture) Set a new texture given frame, subset and texture name. Parameters • number – frame • number – subset • string – texture name or nil to unset. Returns boolean - result from meshDebug. Example:

160 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local index_frame=1 local index_subset=1 local texture='mike.png'

print('texture name current:',tMesh:getTexture(index_frame,index_subset)) local bSuccess= tMesh:setTexture(index_frame,index_subset,texture) if bSuccess then print('texture changed successfully:',tMesh:getTexture(index_frame,index_

˓→subset)) else print('Failed to set the new texture!') end end

Figure 9.13: Setting texture to meshDebug

Note: Note that meshDebug will not check if the texture exists or not!

9.3.14 meshDebug stride setStride(number stride, number * frame) Set a specific stride to specific frame or all frames. Parameters • number – stride 2 x, y or 3 x, y, z • number – frame 0 for all frames or specific frame one based index. Example: tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local stride=3 -- x,y,z local frame=0 tMesh:setStride(stride,frame) end

9.3.15 meshDebug normal enableNormal(boolean enable) Enable or disable normal to be saved in the mesh Parameters boolean – value true or false Example:

9.3. meshDebug methods 161 MBM Documentation, Release 3.1.f

tMesh= meshDebug:new() if tMesh:load('Mech.msh') then tMesh:enableNormal(true) end

9.3.16 meshDebug UV enableUv(boolean enable) Enable or disable uv to be saved in the mesh Parameters boolean – value true or false Example: tMesh= meshDebug:new() if tMesh:load('Mech.msh') then tMesh:enableUv(true) end

9.3.17 meshDebug Physics getPhysics Return an array of physics. Returns table - Physics. Example: function printTable(space, tTbale) for k, v in pairs(tTbale) do if k =='type' then -- Do nothing ... we already have printed type elseif type(v) =='table' then if string.len(space)>0 then print(space,k,v) else print(k,v) end printTable(space..' \t', v) else if string.len(space)>0 then print(space, k, v) else print(k, v) end end end end tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local tPhysics= tMesh:getPhysics() for i=1,#tPhysics do local tPhysic= tPhysics[i] print('physic index['.. tostring(i)..'] type:',tPhysic.type) (continues on next page)

162 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

(continued from previous page) printTable('', tPhysic) end end

Figure 9.14: Possible output for get physics setPhysics(table tPhysics) Set physics from a table. Parameters table – of physics. The following table describe how should be the table of physics:

9.3. meshDebug methods 163 MBM Documentation, Release 3.1.f

type / sub table values name information information

cube center x, y, z dim x, y, z

triangle a x, y, z b x, y, z c x, y, z

sphere center x, y, z ray

complex a x, y, z b x, y, z c x, y, z d x, y, z e x, y, z f x, y, z g x, y, z h x, y, z

Example setting complex table physic: tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local tComplex={ type='complex', a= {x=1, y=1, z=1}, b= {x=2, y=2, z=2}, c= {x=3, y=3, z=3}, d= {x=4, y=4, z=4}, e= {x=5, y=5, z=5}, f= {x=6, y=6, z=6}, g= {x=7, y=7, z=7}, h= {x=8, y=8, z=8}}

tMesh:setPhysics(tComplex)

local tPhysics= tMesh:getPhysics() local tPhysic= tPhysics[1] print(tPhysic.type) print('a',tPhysic.a.x,tPhysic.a.y,tPhysic.a.z) print('b',tPhysic.b.x,tPhysic.b.y,tPhysic.b.z) print('c',tPhysic.c.x,tPhysic.c.y,tPhysic.c.z) (continues on next page)

164 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

(continued from previous page) print('d',tPhysic.d.x,tPhysic.d.y,tPhysic.d.z) print('e',tPhysic.e.x,tPhysic.e.y,tPhysic.e.z) print('f',tPhysic.f.x,tPhysic.f.y,tPhysic.f.z) print('g',tPhysic.g.x,tPhysic.g.y,tPhysic.g.z) print('h',tPhysic.h.x,tPhysic.h.y,tPhysic.h.z) end

Figure 9.15: Output for complex table physic

Example setting multiple table physics: function createTableCubePhysics() local tCube={ type='cube', center= {x= 0.1, y= 0.2, z= 0.3}, half= {x= 5.0, y= 6.0, z= 7.0}} return tCube end function createTableTrianglePhysics() local tTriangle={ type='triangle', a= {x=-1, y=-1, z= 0.1}, b= {x=1, y=1, z= 0.1}, c= {x=1, y=-1, z= 0.1}} return tTriangle end function createTableSpherePhysics() local tSphere={ type='sphere', center= {x=-0.3, y=-0.1, z= 0.1}, ray= 5.56} return tSphere end function createTableComplexPhysics() local tComplex={ type='complex', a= {x=1, y=1, z=1}, b= {x=2, y=2, z=2}, c= {x=3, y=3, z=3}, d= {x=4, y=4, z=4}, (continues on next page)

9.3. meshDebug methods 165 MBM Documentation, Release 3.1.f

(continued from previous page) e= {x=5, y=5, z=5}, f= {x=6, y=6, z=6}, g= {x=7, y=7, z=7}, h= {x=8, y=8, z=8}} return tComplex end function printPhysics(tMesh) local tPhysics= tMesh:getPhysics() print('Total physics:',#tPhysics) for i=1,#tPhysics do local tPhysic= tPhysics[i] print('\n') print('type:',tPhysic.type) if tPhysic.type =='cube' then print('center',tPhysic.center.x,tPhysic.center.y,tPhysic.center.z) print('half',tPhysic.half.x,tPhysic.half.y,tPhysic.half.z) elseif tPhysic.type =='triangle' then print('a',tPhysic.a.x,tPhysic.a.y,tPhysic.a.z) print('b',tPhysic.b.x,tPhysic.b.y,tPhysic.b.z) print('c',tPhysic.c.x,tPhysic.c.y,tPhysic.c.z) elseif tPhysic.type =='sphere' then print('center',tPhysic.center.x,tPhysic.center.y,tPhysic.center.z) print('ray',tPhysic.ray) elseif tPhysic.type =='complex' then print('a',tPhysic.a.x,tPhysic.a.y,tPhysic.a.z) print('b',tPhysic.b.x,tPhysic.b.y,tPhysic.b.z) print('c',tPhysic.c.x,tPhysic.c.y,tPhysic.c.z) print('d',tPhysic.d.x,tPhysic.d.y,tPhysic.d.z) print('e',tPhysic.e.x,tPhysic.e.y,tPhysic.e.z) print('f',tPhysic.f.x,tPhysic.f.y,tPhysic.f.z) print('g',tPhysic.g.x,tPhysic.g.y,tPhysic.g.z) print('h',tPhysic.h.x,tPhysic.h.y,tPhysic.h.z) else print('ERR','type physics unknown') end end end tMesh= meshDebug:new() if tMesh:load('Mech.msh') then local tCube= createTableCubePhysics() local tTriangle= createTableTrianglePhysics() local tSphere= createTableSpherePhysics() local tComplex= createTableComplexPhysics()

local tPhysics={[1]= tSphere, [2]= tCube, [3]= tComplex, [4]= tTriangle }

tMesh:setPhysics(tPhysics) printPhysics(tMesh) end

9.3.18 meshDebug centralize centralize(number * frame, number * subset)

166 Chapter 9. Table meshDebug MBM Documentation, Release 3.1.f

Figure 9.16: Output for multiples physic

9.3. meshDebug methods 167 MBM Documentation, Release 3.1.f

Centralize a specific frame/subset or all of them (do not supply the arguments)

Parameters • number – frame from 1 to total of frames. • number – subset from 1 to total of subset.

Example: tMesh= meshDebug:new() if tMesh:load('crate.msh') then tMesh:centralize() -- centralize all of them end

Table of Contents

• Table particle – particle methods

* particle new * particle load * particle add * particle Offset * particle Direction * particle Speed * particle Color * particle LifeTime * particle Size * particle Stage * particle Arise * particle Invert color * particle Total * particle getTexture – particle attributes – Creating particle programmatically

* particle operator * particle fragment shader * particle vertex shader – Saving particle to a binary file

168 Chapter 9. Table meshDebug CHAPTER 10

Table particle

A table particle inherit from renderizable and implement all methods as usual. A particle has a ‘stage’ which represent the animation. Each stage might have its own behavior. Also each stage has a shader table by default which can be accessed by getShader method. Particles have a peculiarity state of being born, living and dying and then resurrecting (or not). This is well known in all generator of particles and on this engine could not be different. There are several combinations that provide a set of options for reach this.

10.1 particle methods

10.1.1 particle new new(string * world, number * x, number * y, number * z) Create a new instance of a particle passing the world desired (detail) and position. Parameters • string – world can be 2ds, 2dw or 3d. • number – x position (optional). • number – y position (optional). • number – z position (optional). Returns particle table. Example: tParticle= particle:new('2dw') --note that particle inherits from renderizable

169 MBM Documentation, Release 3.1.f

10.1.2 particle load load(string file_name, number * total_particle, string * shader_operator, string * aditional_code_shader) Load a particle from file (expected .plt extension) any of images supported types. Parameters • string – file name can be a texture directly or an binary file .ptl • number – total_particle initial (optional). • string – shader operator can be +, -, /, *, (optional). • string – additional code initial (optional). Returns boolean - result. Example: tParticle= particle:new('2d') if tParticle:load('particle.ptl',50,'*') then print('Successfully loaded particle:','particle.ptl') else print('Failed to load particle:','particle.ptl') end

Note: The load method will search in all known path. You can add a path to search by the method addPath.

10.1.3 particle add add(number total_particle, boolean * force_now) Add more particle to a particle system. Parameters • number – total_particle to be added. • boolean – force now means that all particle will appear instantaneously (optional). Returns boolean - result. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:add(1000) --add 1000 particles else print('Failed to load particle:','particle.ptl') end

10.1.4 particle Offset setMinOffset(number stage, number * x, number * y, number * z) Change the min offset from a particle system.

170 Chapter 10. Table particle MBM Documentation, Release 3.1.f

Parameters • number – stage to be modified. • number – x value (optional). • number – y value (optional). • number – z value (optional). Example: tParticle= particle:new('2dw') local stage=1 --we only have one stage for this particle if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMinOffset(stage,-55,-150,0) else print('Failed to load particle:','particle.ptl') end setMinOffset(number stage, vec3 minOffset) Change the min offset from a particle system. Parameters • number – stage to be modified. • number – minOffset value as vec3. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local minOffset= vec3:new(-45,-100,0) tParticle:setMinOffset(stage,minOffset) else print('Failed to load particle:','particle.ptl') end getMinOffset(number stage) Get the min offset from a particle system. Parameters number – stage to retrieve. Returns number, number, number - x, y and z min offset. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local x,y,z= tParticle:getMinOffset(stage) print('Current min offset:',x,y,z) else print('Failed to load particle:','particle.ptl') end setMaxOffset(number stage, number * x, number * y, number * z) Change the max offset from a particle system.

10.1. particle methods 171 MBM Documentation, Release 3.1.f

Parameters • number – stage to be modified. • number – x value (optional). • number – y value (optional). • number – z value (optional). Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMaxOffset(stage,-55,-150,0) else print('Failed to load particle:','particle.ptl') end setMaxOffset(number stage, vec3 maxOffset) Change the max offset from a particle system. Parameters • number – stage to be modified. • number – maxOffset value as vec3. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local maxOffset= vec3:new(-35,-120,0) tParticle:setMaxOffset(stage,maxOffset) else print('Failed to load particle:','particle.ptl') end getMaxOffset(number stage) Get the max offset from a particle system. Parameters number – stage to retrieve. Returns number, number, number - x, y and z min offset. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local x,y,z= tParticle:getMaxOffset(stage) print('Current max offset:',x,y,z) else print('Failed to load particle:','particle.ptl') end

172 Chapter 10. Table particle MBM Documentation, Release 3.1.f

10.1.5 particle Direction setMinDirection(number stage, number * x, number * y, number * z) Change the min direction from a particle system. Parameters • number – stage to be modified. • number – x value (optional). • number – y value (optional). • number – z value (optional). Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMinDirection(stage,-55,-150,0) else print('Failed to load particle:','particle.ptl') end setMinDirection(number stage, vec3 minDirection) Change the min direction from a particle system. Parameters • number – stage to be modified. • number – minDirection value as vec3. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local minDirection= vec3:new(-54,-154,0) tParticle:setMinDirection(stage,minDirection) else print('Failed to load particle:','particle.ptl') end getMinDirection(number stage) Get the min direction from a particle system. Parameters number – stage to retrieve. Returns number, number, number - x, y and z min direction. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local x,y,z= tParticle:getMinDirection(stage) print('Current min direction:',x,y,z) (continues on next page)

10.1. particle methods 173 MBM Documentation, Release 3.1.f

(continued from previous page) else print('Failed to load particle:','particle.ptl') end setMaxDirection(number stage, number * x, number * y, number * z) Change the max direction from a particle system. Parameters • number – stage to be modified. • number – x value (optional). • number – y value (optional). • number – z value (optional). Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMaxDirection(stage,-55,-150,0) else print('Failed to load particle:','particle.ptl') end setMaxDirection(number stage, vec3 maxDirection) Change the max direction from a particle system. Parameters • number – stage to be modified. • number – vec3 value as vec3. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local maxDirection= vec3:new(-55,-150,0) tParticle:setMaxDirection(stage,maxDirection) else print('Failed to load particle:','particle.ptl') end getMaxDirection(number stage) Get the max direction from a particle system. Parameters number – stage to retrieve. Returns number, number, number - x, y and z min direction. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then (continues on next page)

174 Chapter 10. Table particle MBM Documentation, Release 3.1.f

(continued from previous page) print('Successfully loaded particle:','particle.ptl') local x,y,z= tParticle:getMaxDirection(stage) print('Current max direction:',x,y,z) else print('Failed to load particle:','particle.ptl') end

10.1.6 particle Speed setMinSpeed(number stage, number min_speed) Change the min speed from a particle system. Parameters • number – stage to be modified. • number – min_speed value. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMinSpeed(stage,500) else print('Failed to load particle:','particle.ptl') end getMinSpeed(number stage) Get the min speed from a particle system. Parameters number – stage to retrieve. Returns number - min speed. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local min_speed= tParticle:getMinSpeed(stage) print('Current min speed:',min_speed) else print('Failed to load particle:','particle.ptl') end setMaxSpeed(number stage, number max_speed) Change the max speed from a particle system. Parameters • number – stage to be modified. • number – max_speed value. Example:

10.1. particle methods 175 MBM Documentation, Release 3.1.f

local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMaxSpeed(stage,150) else print('Failed to load particle:','particle.ptl') end getMaxSpeed(number stage) Get the max speed from a particle system. Parameters number – stage to retrieve. Returns number - max speed. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local max_speed= tParticle:getMaxSpeed(stage) print('Current max speed:',max_speed) else print('Failed to load particle:','particle.ptl') end

10.1.7 particle Color setMinColor(number stage, number * r, number * g, number * b) Change the min color from a particle system. Parameters • number – stage to be modified. • number – r value • number – g value • number – b value Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMinColor(stage,0,0.5,0) else print('Failed to load particle:','particle.ptl') end setMinColor(number stage, vec3 minColor) Change the min color from a particle system. Parameters • number – stage to be modified.

176 Chapter 10. Table particle MBM Documentation, Release 3.1.f

• number – minColor value as vec3. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local minColor= vec3:new(1,1,0.8) tParticle:setMinColor(stage,minColor) else print('Failed to load particle:','particle.ptl') end getMinColor(number stage) Get the min color from a particle system. Parameters number – stage to retrieve. Returns number, number, number - r, g and b min color. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local r,g,b= tParticle:getMinColor(stage) print('Current min color:',r,g,b) else print('Failed to load particle:','particle.ptl') end setMaxColor(number stage, number * r, number * g, number * b) Change the max color from a particle system. Parameters • number – stage to be modified. • number – r value • number – g value • number – b value Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMaxColor(stage,1,1,1) else print('Failed to load particle:','particle.ptl') end setMaxColor(number stage, vec3 maxColor) Change the max color from a particle system. Parameters • number – stage to be modified.

10.1. particle methods 177 MBM Documentation, Release 3.1.f

• number – maxColor value as vec3. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local maxColor= vec3:new(1,1,1) tParticle:setMaxColor(stage,maxColor) else print('Failed to load particle:','particle.ptl') end getMaxColor(number stage) Get the max color from a particle system. Parameters number – stage to retrieve. Returns number, number, number - r, g and b min color. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local r,g,b= tParticle:getMaxColor(stage) print('Current max color:',r,g,b) else print('Failed to load particle:','particle.ptl') end

10.1.8 particle LifeTime setMinLifeTime(number stage, number * time) Change the min time from a particle system. Parameters • number – stage to be modified. • number – min time of life in seconds for each new particle. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMinLifeTime(stage,6.5) else print('Failed to load particle:','particle.ptl') end getMinLifeTime(number stage) Get the min time from a particle system. Parameters number – stage to retrieve.

178 Chapter 10. Table particle MBM Documentation, Release 3.1.f

Returns number - min time of life in seconds. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local minTime= tParticle:getMinLifeTime(stage) print('Current min time:',minTime) else print('Failed to load particle:','particle.ptl') end setMaxLifeTime(number stage, number * time) Change the max time from a particle system. Parameters • number – stage to be modified. • number – max time of life in seconds. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMaxLifeTime(stage,5.5) else print('Failed to load particle:','particle.ptl') end getMaxLifeTime(number stage) Get the max life time from a particle system. Parameters number – stage to retrieve. Returns number, max time of life in seconds. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local maxLifeTime= tParticle:getMaxLifeTime(stage) print('Current max time:',maxLifeTime) else print('Failed to load particle:','particle.ptl') end

10.1.9 particle Size setMinSize(number stage, number * size) Change the min size from a particle system. Parameters

10.1. particle methods 179 MBM Documentation, Release 3.1.f

• number – stage to be modified. • number – min size of the particle. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMinSize(stage,1) else print('Failed to load particle:','particle.ptl') end getMinSize(number stage) Get the min size from a particle system. Parameters number – stage to retrieve. Returns number - min size of the particle. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local minSize= tParticle:getMinSize(stage) print('Current min size:',minSize) else print('Failed to load particle:','particle.ptl') end setMaxSize(number stage, number size) Change the max size from a particle system. Parameters • number – stage to be modified. • number – max size of the particle. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setMaxSize(stage,15.5) else print('Failed to load particle:','particle.ptl') end getMaxSize(number stage) Get the max life size from a particle system. Parameters number – stage to retrieve. Returns number, max size of the particle. Example:

180 Chapter 10. Table particle MBM Documentation, Release 3.1.f

local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local maxSize= tParticle:getMaxSize(stage) print('Current max size:',maxSize) else print('Failed to load particle:','particle.ptl') end

10.1.10 particle Stage getStage Get the current stage from particle system. Returns number - stage current. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local stage= tParticle:getStage() print('Current stage:',stage) else print('Failed to load particle:','particle.ptl') end getTotalStage Get the total stage from particle system. Returns number - total stage. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local iTotalStage= tParticle:getTotalStage() print('Total stage:',iTotalStage) else print('Failed to load particle:','particle.ptl') end setStage(number stage) Set the current stage to a particle system. Parameters number – stage to be set. Example: local stage=1 tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setStage(stage) else (continues on next page)

10.1. particle methods 181 MBM Documentation, Release 3.1.f

(continued from previous page) print('Failed to load particle:','particle.ptl') end addStage Add a stage for a particle system. Returns number - index stage added (1 based). Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local stage= tParticle:addStage() print('Stage added at:',stage) else print('Failed to load particle:','particle.ptl') end setStageTime(number stage, number time) Set time for the stage in a particle system. Parameters • number – stage to be set. • number – time in seconds to change the stage. Example: local stage=1 tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then tParticle:setStageTime(stage,2) --2 seconds to change to next stage else print('Failed to load particle:','particle.ptl') end getStageTime(number stage, number time) Set time for the stage in a particle system. Parameters number – stage to be set. Returns number - time from stage. Example: local stage=1 tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then local iTime= tParticle:getStageTime(stage) print('Time in the stage:'.. iTime) else print('Failed to load particle:','particle.ptl') end

10.1.11 particle Arise

Arise time is the time to show up since the particle system starts.

182 Chapter 10. Table particle MBM Documentation, Release 3.1.f

For example, if is added 50 particle and the time is one second, then all 50 particle should be appear in the max one second. setAriseTime(number stage, number time) Set the current arise time to a particle system. Parameters • number – stage to be set. • number – arise time to be set. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') tParticle:setAriseTime(stage,0.88) else print('Failed to load particle:','particle.ptl') end getAriseTime(number stage) Get the current arise time from particle system. Parameters number – stage to be get. Returns number - arise time from particle. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local ariseTime= tParticle:getAriseTime(stage) print('Current arise time:',ariseTime) else print('Failed to load particle:','particle.ptl') end

10.1.12 particle Invert color setInvertedColor(number stage, boolean r, boolean g, boolean b, boolean a) Set individual inverted color to the current stage on a particle system. Parameters • number – stage to be set. • number – red color to be set. • number – green color to be set. • number – blue color to be set. • number – alpha color to be set. Example:

10.1. particle methods 183 MBM Documentation, Release 3.1.f

local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then tParticle:setInvertedColor(stage,true,false,true,false) else print('Failed to load particle:','particle.ptl') end getInvertedColor(number stage) Get the current arise time from particle system. Parameters number – stage to be get. Returns boolean, boolean, boolean, boolean - r, g, b, a indicating if is inverted. Example: local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local ir,ig,ib,ia= tParticle:getInvertedColor(stage) print(string .format('Inverted color R:%s, G:%s, B:%s, A:%s:',ir,ig,ib,ia)) else print('Failed to load particle:','particle.ptl') end

10.1.13 particle Total getTotalAlive Retrieve the total of particles alive. Returns number - total particle alive from system. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local total= tParticle:getTotalAlive() print('Total particles alive in the system:',total) else print('Failed to load particle:','particle.ptl') end getTotalParticle Get the total particle capacity from particle system. Returns number - total particle (dead + alive from system). Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local total= tParticle:getTotalParticle() print('Total particles in the system:',total) else (continues on next page)

184 Chapter 10. Table particle MBM Documentation, Release 3.1.f

(continued from previous page) print('Failed to load particle:','particle.ptl') end getTotalParticle(number stage) Get the total particle available per stage from particle system. Parameters number – stage to be get. Returns number - total particle available to the stage indicated. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local stage=1 local total= tParticle:getTotalParticle(stage) print('Total particles in from stage selected:',total) else print('Failed to load particle:','particle.ptl') end setTotalParticle(number stage, number total) Set the total particle available per stage to particle system. Parameters • number – stage to be set. • number – total particle to the selected stage. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local stage=1 tParticle:setTotalParticle(stage,100) else print('Failed to load particle:','particle.ptl') end

10.1.14 particle getTexture getTexture Get the current texture from particle system. Returns string - file name from texture. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then print('Successfully loaded particle:','particle.ptl') local texture_file_name= tParticle:getTexture() print('Current texture used at particle:',texture_file_name) else (continues on next page)

10.1. particle methods 185 MBM Documentation, Release 3.1.f

(continued from previous page) print('Failed to loaded particle:','particle.ptl') end

10.2 particle attributes alpha [read / write] Enable or disable the alpha flag for a particle from current stage. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then tParticle.alpha= false print('alpha:',tParticle.alpha) else print('Failed to load particle:','particle.ptl') end revive [read / write] Enable or disable the revive flag for a particle from current stage. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then tParticle.revive= false print('revive:',tParticle.revive) else print('Failed to load particle:','particle.ptl') end grow [read / write] Enable or disable the grow flag for a particle from current stage. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then tParticle.grow= false print('grow:',tParticle.grow) else print('Failed to load particle:','particle.ptl') end segmented [read / write] Enable or disable the segmented flag for a particle from current stage. Example: tParticle= particle:new('2dw') if tParticle:load('particle.ptl',70,'*') then tParticle.segmented= false print('segmented:',tParticle.segmented) else print('Failed to load particle:','particle.ptl') end

186 Chapter 10. Table particle MBM Documentation, Release 3.1.f

10.3 Creating particle programmatically

Follow some examples how to create particles programmatically. For the first example, we will use a solid texture in red color. mbm.setColor(0,0,0) --set background color to black tParticle= particle:new('2dw') tParticle:load('#FFFF0000') --red solid texture (alpha 1 red 1, green 0 blue) tParticle:add(50)

Figure 10.1: Simple particle with solid color red as texture.

Now, we will use the follow texture:

download particle_flame.png Particle using texture: mbm.setColor(0,0,0) --set background color to black tParticle= particle:new('2dw') tParticle:load('particle_flame.png') tParticle:add(50)

Figure 10.2: Simple particle using texture.

Particle using texture and changing the direction and speed: mbm.setColor(0,0,0) --set background color to black local stage=1 --we only have one stage for this particle tParticle= particle:new('2dw') tParticle:load('particle_flame.png') tParticle:setMinDirection(stage,-0.2,1,0) (continues on next page)

10.3. Creating particle programmatically 187 MBM Documentation, Release 3.1.f

(continued from previous page) tParticle:setMaxDirection(stage,0.2,1,0) tParticle:setMinSpeed(stage,10) tParticle:setMaxSpeed(stage,1000) tParticle:add(1000)

Figure 10.3: Changing the direction, speed and amount of particle.

Particle with 2 stages: mbm.setColor(0,0,0) --set background color to black local stage_1=1

--Set up for the first stage tParticle:add(500) --500 particle for the first stage tParticle:setMinSpeed(stage_1,10) tParticle:setMaxSpeed(stage_1,1000) tParticle:setMinLifeTime(stage_1,1)--at least one second for the life of particle tParticle:setStageTime(stage_1,1)--one second of duration for the first stage

--Set up for the second stage local stage_2= tParticle:addStage() tParticle:setMinDirection(stage_2,-0.2,1,0) tParticle:setMaxDirection(stage_2,0.2,1,0) tParticle:setMinSpeed(stage_2,10) tParticle:setMaxSpeed(stage_2,1000) tParticle:add(1000)--500 particle for the second stage tParticle:restartAnim()--restart the animation since we have modified it

Figure 10.4: Particle with two stages

10.3.1 particle operator

Particle with different operator in the shader: mbm.setColor(0,0,0) --set background color to black local stage=1 --we only have one stage for this particle local total_particle= 300 local operator={'+','-','/',' *'} local x={-300,-150,0, 150}

(continues on next page)

188 Chapter 10. Table particle MBM Documentation, Release 3.1.f

(continued from previous page) tParticleArray={} -- just to store 4 particle table for i=1,#operator do local tParticle= particle:new('2dw',x[i])

print('operator:',operator[i] )

tParticle:load('particle_flame.png',0,operator[i])

tParticle:setMinDirection(stage,-0.2,1,0) tParticle:setMaxDirection(stage,0.2,1,0)

tParticle:setMinSpeed(stage,10) tParticle:setMaxSpeed(stage,1000)

tParticle:add(total_particle)

table.insert(tParticleArray,tParticle) end

Figure 10.5: Four operator, +, -, /, *

10.3.2 particle fragment shader

The fragment shader (pixel shader) for particle is created in the moment of load. See how the options affect the shader: precision mediump float; uniform vec4 color; uniform float enableAlphaFromColor; varying vec2 vTexCoord; uniform sampler2D sample0; void main() { vec4 texColor; vec4 outColor; texColor= texture2D( sample0, vTexCoord ); if(enableAlphaFromColor> 0.5) outColor.a= color.a; else outColor.a= texColor.a;

//The operator is used in the next line. the default if '*' outColor.rgb= color.rgb * texColor.rgb;

// //this line is the aditional code if supplied. //

gl_FragColor= outColor; }

10.3. Creating particle programmatically 189 MBM Documentation, Release 3.1.f

10.3.3 particle vertex shader

The vertex shader used for the particle is: attribute vec4 aPosition; attribute vec2 aTextCoord; uniform mat4 mvpMatrix; varying vec2 vTexCoord; void main() { gl_Position= mvpMatrix * aPosition; vTexCoord= aTextCoord; }

10.4 Saving particle to a binary file

It is possible to save any mesh with help of meshDebug. For that it is necessary to prepare the meshDebug based on our renderizable. • First, we have to create a temporary particle and set the values that we expect to have. • Then we create a meshDebug, add at least one frame and set it to particle type. • Next, we copy the animations and shaders effect using the function copyAnimationsFromMesh. • Finally we just need specify the file name to save through the function save,. Follow the example how to save a particle to a binary file:

1 mbm.setColor(0,0,0) --set background color to black

2

3 function createParticle()

4

5 local tParticle= particle:new('2dw')

6 tParticle:load('particle_flame.png')

7

8 local stage_1=1

9

10 --Set up for the first stage

11 tParticle:add(500) --500 particle for the first stage

12

13 tParticle:setMinSpeed(stage_1,10,10,0)

14 tParticle:setMaxSpeed(stage_1,1000,1000,0)

15

16 tParticle:setMinLifeTime(stage_1,1)--minimun alive for one second

17 tParticle:setMaxLifeTime(stage_1,2)--maximun alive for two seconds

18

19 tParticle:setStageTime(stage_1,1)--One second of duration

20

21 --Set up for the second stage

22 local stage_2= tParticle:addStage()

23

24 tParticle:setMinDirection(stage_2,-0.2,1,0)

25 tParticle:setMaxDirection(stage_2,0.2,1,0)

26

27 tParticle:setMinSpeed(stage_2,10,10,0)

28 tParticle:setMaxSpeed(stage_2,1000,1000,0) (continues on next page)

190 Chapter 10. Table particle MBM Documentation, Release 3.1.f

(continued from previous page)

29

30 tParticle:add(1000)--500 particle for the second stage

31

32 tParticle:restartAnim()--restart the animation since we have modified it

33 return tParticle

34 end

35

36 function saveParticleToFile(fileName,tParticle)

37

38 --meshDebug is used to create dynamically the mesh in the engine.

39 --For particle it has to have at least one frame to be able to generate

˓→the mesh

40 local stride=2 --stride only can be 3 or 2. it means (x,y,z) or (x,

˓→y)

41 local tMesh= meshDebug:new() --new mesh debug to store the

˓→information about our particle

42 local nFrame= tMesh:addFrame(stride) -- Add one frame with stride 2

˓→(x,y)

43 local indexFrame= nFrame --(meshDebug uses 1 based index)

44 local indexSubset=1 --first subset

45 local totalVertex=3 --minimun 3 to build one triangle (otherwise the

˓→internal check of meshDebug will fail)

46

47 --To add vertex, first we need to add a subset

48 local nSubset= tMesh:addSubSet(indexFrame) --add one subset for the

˓→first frame

49

50 --we have to add one frame to set the texture and be able to save the mesh

51 --this frame has to have at least 3 vertex (one triangle)

52 if not tMesh:addVertex(indexFrame,indexSubset,totalVertex) then

53 print("Error on add vertex")

54 return false

55 end

56

57 --apply the texture from particle

58 if not tMesh:setTexture(indexFrame,indexSubset,tParticle:getTexture())

˓→then

59 print("Error on set texture")

60 return false

61 end

62

63 tMesh:setType('particle') -- set it to particle type

64

65 if tMesh:copyAnimationsFromMesh(tParticle) then --copy animations and

˓→shaders, include stages.

66 local calcNormal,calcUv= false,false --dont wanna normal (neither

˓→recalc it) and recalc UV at all

67 if tMesh:save(fileName,calcNormal,calcUv) then

68 print("Particle created successfully")

69 return true

70 else

71 print("Failed to create particle!")

72 return false

73 end

74 else

75 print("Failed to copy animations - stages, shaders...")

76 return false (continues on next page)

10.4. Saving particle to a binary file 191 MBM Documentation, Release 3.1.f

(continued from previous page)

77 end

78 end

79

80

81 local tParticle= createParticle()

82

83 if saveParticleToFile('particle.ptl',tParticle) then

84 tParticleFromFile= particle:new('2dw')

85 tParticleFromFile:load('particle.ptl') --all behavior already in place

86 end

87

88 tParticle:destroy()

download.

Table of Contents

• Table render2texture – render2texture methods

* render2texture new * render2texture create * render2texture enableFrame * render2texture getCamera * render2texture add * render2texture remove * render2texture clear * render2texture release * render2texture setColor * render2texture save

192 Chapter 10. Table particle CHAPTER 11

Table render2texture

A table render2texture create a dynamic texture, inherit from renderizable and normally have one animation. Also the animation has a shader table by default which can be accessed by getShader method. A dynamic texture can be interpreted as a personal view and can be applied to any component through setTexture. Also can be rendered in a single frame using the method enableFrame as true (default).

11.1 render2texture methods

11.1.1 render2texture new new(string * world, number * x, number * y, number * z) Create a new instance of a render2texture passing the world desired (detail) and position. Parameters • string – world can be 2ds, 2dw or 3d. • number – x position (optional). • number – y position (optional). • number – z position (optional). Returns render2texture table. Example:

tRender= render2texture:new('2dw') --note that render2texture inherits from

˓→renderizable

11.1.2 render2texture create

create(number * width, number * height, boolean * alpha, string * nickName)

193 MBM Documentation, Release 3.1.f

Create a dynamic texture properly. • Width is the texture’s width and should not be major than native width. if it is then the native width will be used. • Height is the texture’s height and should not be major than native height. if it is then the native height will be used. • Alpha indicate if the texture will have alpha channel. • NickName is the texture name. It generate automatically if not supplied.

Parameters • number – width texture (optional). • number – height texture (optional). • boolean – alpha channel (optional). • string – nick name from texture generated. Returns boolean - result, string - texture name, number - texture id

Example: tRender= render2texture:new('2dw') --note that render2texture inherits from

˓→renderizable local ret, nickname, id= tRender:create() if ret then print('Dynamic texture created successfully') tRender:enableFrame(true) -- we are enabling render to frame to show our texture tex= texture:new('2dw') tex:load('#0000ff') --Blue texture tex:setSize(500,500) -- resize the frame tRender:add(tex) else print('Failed to create a dynamic texture') end

Following other example doing the opposite way. Setting the background color and applying it to the texture object: tRender= render2texture:new('2dw') --note that render2texture inherits from

˓→renderizable local ret, nickname, id= tRender:create() if ret then print('Dynamic texture created successfully') tRender:enableFrame(false) -- we are disabling render to frame tex= texture:new('2dw') tex:load('#0000ff') --Blue texture tex:setSize(500,500) -- resize the frame tRender:setColor(1,0,0) -- set the background color of render2texture to red tex:setTexture(nickname) -- will render the dynamic texture instead of blue

˓→because we just set

--however anytime that we change background color of render2texture will be

˓→applied to the texture --we will do it in the timer following tTimer= timer:new( function (self) local r= math.random(0,1) (continues on next page)

194 Chapter 11. Table render2texture MBM Documentation, Release 3.1.f

Figure 11.1: Texture object being renderized in the render2texture object

11.1. render2texture methods 195 MBM Documentation, Release 3.1.f

(continued from previous page) local g= math.random(0,1) local b= math.random(0,1)

tRender:setColor(r,g,b) end, 0.2 ) else print('Failed to create a dynamic texture') end

Figure 11.2: render2texture being used as dynamic texture.

11.1.3 render2texture enableFrame enableFrame(boolean enable) Enable the render2texture to render in a frame. The frame will have the same size as the texture. The frame is initially enabled. Parameters boolean – enable render the frame. Example: myMesh= mesh:new('2dw') -- create a object as 2d if myMesh:load('crate.msh') then tRender= render2texture:new('2dw') local ret, nickname, id= tRender:create(300,250) --similar to ratio current if ret then print('Dynamic texture created successfully') tRender:enableFrame(true) -- enable render to frame to show our object inside

˓→the frame tRender:setColor(0,1,0) --green color tRender:add(myMesh) -- add the object to our dynamic texture

else print('Failed to create a dynamic texture') end else print('Failed to load crate.msh') end

11.1.4 render2texture getCamera getCamera(string * world) Get a camera which gives you the control to the scene in the dynamic texture. See camera for more information. Parameters string – world can be '2d' or '3d'. default is '2d'. Returns camera table reference. Example:

196 Chapter 11. Table render2texture MBM Documentation, Release 3.1.f

Figure 11.3: adding object to render2texture

myMesh= mesh:new('3d') -- create a object as 3d if myMesh:load('crate.msh') then tRender= render2texture:new('2dw') local ret, nickname, id= tRender:create(300,250) --similar to ration current if ret then print('Dynamic texture created successfully') tRender:enableFrame(true) -- enable render to frame to show our any object

˓→inside the frame tRender:setColor(0,1,0) --green color tRender:add(myMesh) -- add the object to our dynamic texture camera3d= tRender:getCamera('3d') camera3d:setPos(0,0,-500)

--using a timer to do a random movement using the camera tTimer= timer:new( function (self) local p= camera3d:getPos() p.x= p.x+ 10 p.y= p.y+ 20 p.z= p.z- 1.5

if p.x> 300 then p.x=-300 end if p.y> 600 then p.y=-600 end if p.z> 500 then p.z=-500 end (continues on next page)

11.1. render2texture methods 197 MBM Documentation, Release 3.1.f

(continued from previous page) end, 0.02 ) else print('Failed to create a dynamic texture') end else print('Failed to load crate.msh') end

Figure 11.4: Accessing the camera from render_2_texture object

Important: The camera method is supposed to be a normal camera but not all methods are implemented. TODO :)

11.1.5 render2texture add add(renderizable mesh) Add a renderizable to render in the dynamic texture. Parameters renderizable – mesh to render in the frame. Example: myMesh= mesh:new('2dw') -- create a object as 2d if myMesh:load('crate.msh') then tRender= render2texture:new('2dw') local ret, nickname, id= tRender:create(300,250) --similar to ratio current if ret then print('Dynamic texture created successfully') tRender:enableFrame(true) -- enable render to frame to show our object inside

˓→the frame tRender:setColor(0,1,0) --green color tRender:add(myMesh) -- add the object to our dynamic texture else print('Failed to create a dynamic texture') end else print('Failed to load crate.msh') end

11.1.6 render2texture remove remove(renderizable mesh) Remove a renderizable from render 2 texture list. Parameters renderizable – mesh to remove from list. Returns boolean found - it was found to be removed?.

198 Chapter 11. Table render2texture MBM Documentation, Release 3.1.f

11.1.7 render2texture clear

clear Remove all renderizable from render 2 texture list.

11.1.8 render2texture release

release Remove all renderizable from render 2 texture list and destroy the dynamic texture created. The method create might be used again.

11.1.9 render2texture setColor

Change the background color of dynamic texture. setColor(number r, number g, number b, number a) Parameters • number – r red color, range 0 to 1. • number – g green color, range 0 to 1. • number – b blue color, range 0 to 1. • number – a alpha color, range 0 to 1.

11.1.10 render2texture save save(string file_name, number * x, number * y, number * w, number * h)

Save the texture as png file. If not supplied x and y will be zero. If not supplied w and h will be the size of the back buffer.

Parameters • string – file name of texture to be saved. • number – x origin to rect the texture. • number – y origin to rect the texture. • number – width of texture to be saved. • number – height of texture to be saved. Returns boolean result of operation.

Example:

myMesh= mesh:new('2dw') -- create a object as 2d if myMesh:load('crate.msh') then tRender= render2texture:new('2dw') local ret, nickname, id= tRender:create(300,250) --similar to ratio current if ret then (continues on next page)

11.1. render2texture methods 199 MBM Documentation, Release 3.1.f

(continued from previous page) print('Dynamic texture created successfully') tRender:enableFrame(true) -- enable render to frame to show our object inside

˓→the frame tRender:setColor(0,1,0) --green color tRender:add(myMesh) -- add the object to our dynamic texture else print('Failed to create a dynamic texture') end else print('Failed to load crate.msh') end times_render=0 function loop(delta) if times_render ==1 then --we wait for the first render otherwise the texture

˓→will be empty if tRender:save('my_dynamic_texture.png') then print('Texture saved successfully ...') else print('Failed to save texture') end end times_render= times_render+1 end

Important: If the texture was never render, then when you save it will be just empty texture. That is why we wait for the first cycle of render to save the texture.

Table of Contents

• Table renderizable – Renderizable methods

* Renderizable setPos * Renderizable getPos * Renderizable setScale * Renderizable getScale * Renderizable setAngle * Renderizable getAngle * Renderizable move * Renderizable isOver * Renderizable collide * Renderizable rotate * Renderizable getSize

200 Chapter 11. Table render2texture MBM Documentation, Release 3.1.f

* Renderizable getAABB * Renderizable isOnScreen * Renderizable isLoaded * Renderizable onEndFx * Renderizable forceEndAnimFx * Renderizable getTotalFrame * Renderizable destroy – Blending

* Blending setBlend * Blending getBlend * Blend Operation – Animation

* Animation setAnim * Animation getAnim * Animation setTypeAnim * Animation restartAnim * Animation onEndAnim * Animation isEndedAnim * Animation getIndexFrame * Animation setTexture * Animation getTotalAnim * Animation addAnim * Animation getShader – Physics – Renderizable attributes – User data acknowledgment

11.1. render2texture methods 201 MBM Documentation, Release 3.1.f

202 Chapter 11. Table render2texture CHAPTER 12

Table renderizable

Table renderizable is a base class for all object that are ‘renderizable’ in the engine. All table which inherit from renderizable will have these commons methods and attributes in this section.

12.1 Renderizable methods

12.1.1 Renderizable setPos setPos(number x, number * y, number * z) Set new values to renderizable’s position passing three number arguments (x, y and z). Parameters • number – x value. • number – y value (optional). • number – z value (optional). Example: tTexture= texture:new('2dw') tTexture:setPos(200,500,-1) setPos(vec3 position) Set new values to renderizable’s position passing a vec3. Parameters vec3 – position. Example: tSprite= sprite:new('3d') v= vec3:new(200,500,500) tSprite:setPos(v) -- z is set to 500 because tSprite is 3d otherwise would not be set.

203 MBM Documentation, Release 3.1.f

Note: If the renderizable is 2d then z position is not set. You have to force if you want. The reason behind this is because the method accepts another objects that can be renderizable as a parameter and, most of the time, in the 2D game, z would be wrong. Example: tSprite= sprite:new('3d') tSprite.z=5 -- or v= vec3:new(200,500,500) tSprite:setPos(v.x,v.y,v.z) print(tostring(tSprite:getPos())) -- x:200 y:500 z:500 setPos(renderizable obj) Set new values to renderizable’s position passing other renderizable. Parameters renderizable – render object. Example: tSprite= sprite:new('2ds',0,0,-2) tTexture= texture:new('3d') tTexture:setPos(200,500,-1) tSprite:setPos(tTexture) --set position tSprite same as tTexture. z continues -2

˓→because tSprite is 2d print(tostring(tSprite:getPos())) -- x:200 y:500 z:-2

Note: If the renderizable is 2d then z position is not set. You have to force if you want. The reason behind this is because the method accepts another objects that can be renderizable as a parameter and, most of the time, in the 2D game, z would be wrong. Example: tSprite= sprite:new('3d') tSprite.z=5 -- or v= vec3:new(200,500,600) tSprite:setPos(v.x,v.y,v.z) print(tostring(tSprite:getPos())) -- x:200 y:500 z:600

12.1.2 Renderizable getPos getPos Get a vec3 position from renderizable. Returns vec3 - renderizable’s position. Example:

204 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

tTexture= texture:new('3d') local position= tTexture:getPos() position:set(220,100,1)

12.1.3 Renderizable setScale setScale(number sx, number * sy, number * sz) Set new values to renderizable’s scale passing three number arguments (sx, sy and sz). Parameters • number – sx value. • number – sy value (optional). • number – sz value (optional). Example: tMesh= mesh:new('3d') tMesh:setScale(2,2,2) setScale(vec3 scale) Set new values to renderizable’s scale passing a vec3. Parameters number – vec3 scale. Example: tSprite= sprite:new('3d') v= vec3:new(1.5,1.5,1.5) tSprite:setScale(v)

12.1.4 Renderizable getScale getScale Get a vec3 scale from renderizable. Returns vec3 - renderizable’s scale. Example: tTexture= texture:new('3d') local scale_texture= tTexture:getScale() scale_texture:set(3,3,1)

12.1.5 Renderizable setAngle setAngle(number x, number * y, number * z) Set new values to renderizable’s angle passing three number arguments (x, y and z). Parameters • number – x value. • number – y value (optional).

12.1. Renderizable methods 205 MBM Documentation, Release 3.1.f

• number – z value (optional). Example: tTexture= texture:new('2dw') tTexture:setAngle(0,0,math.rad(180))--180 degree on z axis setAngle(renderizable render) Set new values to renderizable’s angle passing a renderizable.

Parameters renderizable – render to set values from angle.

Example: local tTexture= texture:new('3D') tTexture:setAngle(math.rad(90),0,math.rad(120)) tSprite= sprite:new('3d') tSprite:setAngle(tTexture)

Note: If the renderizable is 2d then only az angle is set. You have to force the other angles if desired. The reason behind this is because the method accepts another objects that can be renderizable as a parameter and, most of the time, in the 2D game, the z angle would be the only one desired. Example: local tSprite= sprite:new('2DW') local tTexture= texture:new('3D') tTexture:setAngle(6,7,8) tSprite.ax=6 -- or tSprite:setAngle(tTexture.ax,tTexture.ay,tTexture.az) print(tostring(tSprite:getAngle()))-- x:6 y:7 z:8 tTexture:setAngle(1,2,3) tSprite:setAngle(tTexture) --will set only az because tSprite is 2d print(tostring(tSprite:getAngle()))-- x:6 y:7 z:3

12.1.6 Renderizable getAngle getAngle Get a vec3 angle from renderizable. Returns vec3 - renderizable’s angle. Example: tTexture= texture:new('3d') local angle_texture= tTexture:getAngle() angle_texture:set(math.rad(90),math.rad(120),math.rad(180))

206 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

12.1.7 Renderizable move

move(number x, number * y, number * z) Move x, y and z units frames by seconds. This method consider the FPS. Parameters • number – x position. • number – y position (optional). • number – z position (optional). Example:

local tTexture= texture:new('3D') tTexture:move(10,20,30)

--this is equivalent function loop(delta) tTexture.x= tTexture.x+ (delta * 10) tTexture.y= tTexture.y+ (delta * 20) tTexture.z= tTexture.z+ (delta * 30) end

12.1.8 Renderizable isOver

isOver(number x, number y, number * z) Check if the point (x,y) or (x,y,z) for 3D is over the bounding box of renderizable. Parameters • number – x position. • number – y position. • number – z position (optional). Returns boolean - result if point is over bounding box of renderizable. Example:

local tShape= shape:new('2DW') tShape:create('rectangle',100,100) tShape:setPos(10,20)

function onTouchDown(key,x,y)

if tShape:isOver(x,y) then print('Is over my shape.',x,y) end end

Attention: Is expected x,y in 2d screen coordinates.

12.1. Renderizable methods 207 MBM Documentation, Release 3.1.f

12.1.9 Renderizable collide collide(renderizable other, boolean * useAABB) Check if two renderizable collide. Parameters • renderizable – render to check the collision. • boolean – useAABB consider the object rotation (optional). Returns boolean - result if the renderizable is colliding. Example:

local mytex_a= texture:new('2DW') mytex_a:setPos(10,20) mytex_a:load('#ff000000') mytex_a:setSize(100,100)

local mytex_b= texture:new('2DW') mytex_b:setPos(15,25) mytex_b:load('#ffff0000') mytex_b:setSize(100,100) if mytex_a:collide(mytex_b) then print('Collision (without AABB): true') else print('Collision (without AABB): false') end mytex_a.az= math.rad(90) --rotate the texture mytex_b.az= math.rad(-45) --rotate the texture if mytex_a:collide(mytex_b,true) then print('Collision (using AABB): true') else print('Collision (using AABB): false') end collide(number x, number y, number * z) Check if the point (x,y) or (x,y,z) for 3D is over the bounding box of renderizable. Parameters • number – x in 2ds coordinate. • number – y in 2ds coordinate. • number – z in 2ds coordinate (for 3d objects). Returns boolean - result if the renderizable is colliding. Example: local mytex_a= texture:new('2DW') mytex_a:setPos(10,20) mytex_a:load('#ff000000') mytex_a:setSize(100,100) function onTouchDown(key,x,y) if mytex_a:collide(x,x) then (continues on next page)

208 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

(continued from previous page) print('it collides') end end

12.1.10 Renderizable rotate rotate(string angle, number radian) Rotate a renderizable considering the FPS making it smooth. Parameters • string – angle x, y or z. • number – radian to be rotated per seconds. Example: local mytex_a= texture:new('2DW') mytex_a:setPos(10,20) mytex_a:load('#ff000000') mytex_a:setSize(100,100) function loop(delta) mytex_a:rotate('z',math.rad(360)) -- one complete turn per second end

12.1.11 Renderizable getSize getSize(boolean * consider_scale) Get the size of renderizable NOT considering the rotation. It considers the scale. Parameters boolean – consider_scale default is true if not supplied. Returns number width, number height, number depth *- dimension of renderizable. Example: local tTexture= texture:new('2DW') tTexture:load('#ff000000') tTexture:setSize(100,100) local width,height= tTexture:getSize() print(width,height) local tMesh= mesh:new('3D') tMesh:load('some_file') local width,height,depth= tTexture:getSize() print(width,height,depth)

Note: Only if the renderizable is 3D there will be a depth value.

12.1. Renderizable methods 209 MBM Documentation, Release 3.1.f

12.1.12 Renderizable getAABB getAABB(boolean * recalculate) Get the size of renderizable considering the rotation. It considers the scale. Parameters boolean – recalculate is only need after resize the scale. Returns number width, number height, number depth* - dimension of renderizable. Example: local tTexture= texture:new('2DW') tTexture:load('#ff000000') tTexture:setSize(100,100) local width,height= tTexture:getSize() print(width,height) local tMesh= mesh:new('3D') tMesh:load('some_file') local width,height,depth= tTexture:getSize() print(width,height,depth)

Note: Only if the renderizable is 3D there will be a depth value.

12.1.13 Renderizable isOnScreen isOnScreen Check if the renderizable is on screen. Returns boolean - true if the renderizable is on screen. Example: local tSprite= sprite:new('2DW',500,800) tSprite:load('tSprite.spt') function loop(delta) if tSprite:isOnScreen() then print('Sprite on screen: True') else print('Sprite on screen: False') end end

Attention: If you set the property visible as true and check the isOnScreen method next (same step), the result always will be true even if the object is not on screen. This happens because it has to wait for at least one loop to the engine update the objects that are on screen.

Here a example of a false positive logic as explained before: Note the highlighted lines bellow demonstrating the logic error.

210 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

1 local tSprite= sprite:new('2DW',500,800)

2 tSprite:load('tSprite.spt')

3

4 function loop(delta)

5 tSprite.x=-99999999 -- far far away from screen (isOnScreen should return false)

6 tSprite.visible= true --force to be on screen

7

8 -- tSprite:isOnScreen() is always true because the

9 -- tSprite.visible it was set to true in the same step.

10 -- next loop should be false (if not set again the visible property)

11 if tSprite:isOnScreen() then

12 print('Sprite on screen: True')

13 else

14 print('Sprite on screen: False')

15 end

16 end

12.1.14 Renderizable isLoaded

isLoaded Check if the renderizable is loaded. Returns boolean - true if the renderizable is loaded. Example:

local tSprite= sprite:new('2DW',500,800) tSprite:load('tSprite.spt')

if tSprite:isLoaded() then print('Sprite is loaded') else print('Sprite is not loaded') end

12.1.15 Renderizable onEndFx

Set a renderizable’s shader effect callback. The callback must have the following signature:

function callBack(renderizable self,string shader_fileName)

Note: Some shader effect may never end because it is flagged as loop. See animation table animation table.

onEndFx(string) Set a renderizable’s shader effect callback passing a string name from a function defined somewhere. Parameters string – function name callback. Example:

12.1. Renderizable methods 211 MBM Documentation, Release 3.1.f

--example callback function fFxCallBack(self,shader_fileName) if shader_fileName =='bloom.ps' then self:setAnim('destroy') end end local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:onEndFx('fFxCallBack') tSprite:setAnim('fall') onEndFx(function) Set a renderizable’s shader effect callback passing a function. Parameters function – callback. Example:

--example callback function fFxCallBack(self,shader_fileName) if shader_fileName =='bloom.ps' then self:setAnim('destroy') end end local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:onEndFx(fFxCallBack)--named function local otherSprite= sprite:new('2DW') otherSprite:load('tSprite.spt') otherSprite:onEndFx( function (self,shader_fileName) --anonymous function if shader_fileName =='bloom.ps' then self:setAnim('destroy') end end )

12.1.16 Renderizable forceEndAnimFx forceEndAnimFx(boolean bEndAnim, boolean bEndFx) Force to end an animation and / or shader effect from a renderizable. Parameters • boolean – end animation. • boolean – end effect shader. Example:

--example callback function fFxCallBack(self,shader_fileName) if shader_fileName =='bloom.ps' then self:setAnim('destroy') (continues on next page)

212 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

(continued from previous page) end end

--example callback function myCallBackSprite(self,nameAnimation) if nameAnimation =='fall' then self:setAnim('destroy') end end local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:onEndAnim(myCallBackSprite)--named function tSprite:onEndFx(fFxCallBack)--named function tSprite:forceEndAnimFx(true,true) --force and both (animation and fx) and do a

˓→callback to functions.

12.1.17 Renderizable getTotalFrame getTotalFrame Retrieve the total frame from a renderizable independent of animation. Returns number - total frame from renderizable. Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') local iTotal= tSprite:getTotalFrame()

12.1.18 Renderizable destroy destroy Force to destroy an object renderizable. Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:destroy() -- can not be used anymore tSprite= nil -- so set to nil be be collected ASAP

Note: When an object destroyed it does not means that will be collected immediately. To force that you can call collectgarbage from LUA API.

12.2 Blending

Blend state or Blending is the stage of OpenGL rendering pipeline that takes the fragment color outputs from the Fragment Shader and combines them with the colors in the color buffers that these outputs map to.

12.2. Blending 213 MBM Documentation, Release 3.1.f

Blending parameters can allow the source and destination colors for each output to be combined in various ways. The color S is the source color; the color D is the destination color; the color O is the output color that is written to the buffer. The S, D, and so forth represent all of the components of that color. Srgb represents only the RGB components of the source color. Da represents the alpha component of the destination color. You can learn more at wiki Blending. Blend operation can also be accessed by shader blend state methods.

Function Explanation ADD The source and destination colors are added to each other. O = sS + dD. The s and d are blending parameters that are multiplied into each of S and D before the addition.

SUBTRACT Subtracts the destination from the source. O = sS - dD. The source and dest are multiplied by blending parameters.

REVERSE_SUBTRACT Subtracts the source from the destination. O = dD - sS. The source and dest are multiplied by blending parameters.

MIN The output color is the component-wise minimum value of the source and dest colors. So performing GL_MIN in the RGB equation means that Or = min(Sr, Dr), Og = min(Sg, Dg), and so forth. The parameters s and d are ignored for this equation.

MAX The output color is the component-wise maximum value of the source and dest colors. The parameters s and d are ignored for this equation.

214 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

Following the constant table for blend state used by this engine:

Blend State Constant Name String Name DISABLE disable ZERO zero ONE one SRC_COLOR src_color INV_SRC_COLOR inv_src_color SRC_ALPHA src_alpha INV_SRC_ALPHA inv_src_alpha DEST_ALPHA dest_alpha INV_DEST_ALPHA inv_dest_alpha DEST_COLOR dest_color INV_DEST_COLOR inv_dest_color

Following the constant table for blend operation used by this engine:

Blend Operation Constant Name String Name ADD ADD SUBTRACT SUBTRACT REVERSE_SUBTRACT REVERSE_SUBTRACT MIN MIN MAX MAX

12.2.1 Blending setBlend setBlend(string name) Set the blend state to a renderizable. Parameters string – name regard the blend state. Example: local tShape= shape:new('2DW') tShape:create('circle') tShape:setBlend('inv_src_color') -- same as mbm.INV_SRC_COLOR local nameBlend, constantBlend= tShape:getBlend() print(nameBlend) -- inv_src_color if constantBlend == mbm.INV_SRC_COLOR then print('expected constant: INV_SRC_COLOR') end

Figure 12.1: setting blend by string name setBlend(number constant) Set the blend state to a renderizable.

12.2. Blending 215 MBM Documentation, Release 3.1.f

Parameters number – index regard the blend state. Example: local tShape= shape:new('2DW') tShape:create('circle') tShape:setBlend(mbm.DEST_ALPHA) -- same as 'dest_alpha' local nameBlend, constantBlend= tShape:getBlend() print(nameBlend) -- dest_alpha if constantBlend == mbm.DEST_ALPHA then print('expected constant: DEST_ALPHA') end

Figure 12.2: setting blend by string name

12.2.2 Blending getBlend getBlend Get the blend state from a renderizable. Returns string name, number index - blend state of renderizable. Example: local tShape= shape:new('2DW') tShape:create('circle') local nameBlend, constantBlend= tShape:getBlend() print(nameBlend) -- DISABLE if constantBlend == mbm.DISABLE then print('expected constant: DISABLE') end

Figure 12.3: getting blend

12.2.3 Blend Operation

Blend operation is part of shader. See shader blend operation.

12.3 Animation

All inheritable table from renderizable might have one or more animation.

216 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

An animation is basically a change of frames regularly. An can be added through the method addAnim. Each animation has its own shader.

An animation changes the frame regularly according to this table:

12.3. Animation 217 MBM Documentation, Release 3.1.f

Animation Explanation callback end Name of animation ?

PAUSED false The animation is paused

GROWING true Increment the frames till the final frame. Stop animation in the final frame.

GROWING_LOOP false Increment the frames till the final frame. repeat when reach the final frame.

DECREASING true Decrement the frames till the initial frame. Stop animation in the initial frame.

DECREASING_LOOP false Decrement the frames till the initial frame. repeat when reach the initial frame.

RECURSIVE true Increment the frames till the final frame. Decrement the frames till the initial frame. Stop animation in the initial frame.

RECURSIVE_LOOP true Increment the frames till the final frame. Decrement the frames till the initial frame. repeat when reach the initial frame.

218 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

All member are constant and can be accessible through mbm table.

Example:

tShape= shape:new('2dw') tShape:create('Circle')

--Added an animation type GROWING tShape:addAnim('rolling', mbm.GROWING)

local tShader= tShape:getShader()

if tShader:load(nil,'scale.vs',1,0,2.0,0) then --Added an animation type GROWING_LOOP to shader tShader:setVStype(mbm.GROWING_LOOP) end

local nameAnim, indexAnim= tShape:getAnim() print(nameAnim, indexAnim) -- 'rolling', 2

12.3.1 Animation setAnim

setAnim(string name) Set the animation to a renderizable. Parameters string – name of animation. Example:

local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:setAnim('walk')

setAnim(number index) Set the animation to a renderizable. Parameters number – index of animation (one based index). Example:

local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:setAnim(1) --first animation

12.3.2 Animation getAnim

getAnim(number * index_anim) Get the name and index (1 based) of the animation from a renderizable. Parameters number – index of animation (one based index). If not supplied get the current. Returns string name, number index (1 based) - animation of renderizable. Example:

12.3. Animation 219 MBM Documentation, Release 3.1.f

local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') local nameAnim, indexAnim= tSprite:getAnim() print(nameAnim, indexAnim) -- 'walk 0' for current animation 1

12.3.3 Animation setTypeAnim setTypeAnim(number type_animation) Set a new type to animation. Parameters number – type of animation. Returns number old_type - type of animation. Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') local iOldTypeAnimation= tSprite:setTypeAnim(mbm.PAUSED) -- pause the current

˓→animation tSprite:setTypeAnim(iOldTypeAnimation) -- set animation type defined previously

12.3.4 Animation restartAnim

Restart an renderizable’s animation. Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:restartAnim()

12.3.5 Animation onEndAnim

Set a renderizable’s animation callback. The callback must have the following signature: function callBack(renderizable self,string name_animation)

Note: Some animation may never end because it is flagged as loop. See animation table animation table. onEndAnim(string) Set a renderizable’s animation callback passing a string name from a function defined somewhere. Parameters string – function name callback. Example:

220 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

--example function myCallBackSprite(self,nameAnimation) if nameAnimation =='fall' then self:setAnim('destroy') end end local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:onEndAnim('myCallBackSprite') tSprite:setAnim('fall') local otherSprite= sprite:new('2DW') otherSprite:load('tSprite.spt') otherSprite:onEndAnim('myCallBackSprite') otherSprite:setAnim('fall') onEndAnim(function) Set a renderizable’s animation callback passing a function. Parameters function – callback. Example:

--example function myCallBackSprite(self,nameAnimation) if nameAnimation =='fall' then self:setAnim('destroy') end end local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:onEndAnim(myCallBackSprite)--named function tSprite:setAnim('fall') local otherSprite= sprite:new('2DW') otherSprite:load('tSprite.spt') otherSprite:onEndAnim( function (self,nameAnimation) --anonymous function if nameAnimation =='fall' then self:setAnim('destroy') end end ) otherSprite:setAnim('fall')

12.3.6 Animation isEndedAnim isEndedAnim Check if the animation from a renderizable has ended the animation. Returns boolean - true if animation has ended. Example:

12.3. Animation 221 MBM Documentation, Release 3.1.f

local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') function loop(delta) if tSprite:isEndedAnim() then print('Animation has ended') tSprite:restartAnim() end end

12.3.7 Animation getIndexFrame getIndexFrame Return which index frame is currently to the renderizable (1 based). Returns number - index of frame from current renderizable. Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') function loop(delta) if tSprite:getIndexFrame() ==2 then print('reach index 2 from animation') tSprite:restartAnim() end end

12.3.8 Animation setTexture setTexture(string file_name_texture, boolean* alpha, number* stage) Set a new texture for a renderizable. It considers the current animation. Parameters • string – file name texture to be set to current animation. • boolean – alpha apply alpha if texture not loaded before. Default is true. • number – stage to apply. (1 or 2). Default is 1. Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:setTexture('mario.png',true,1)

Note: • Stage 1 means apply the texture for the current animation – Each animation hold the texture for stage 1. • Stage 2 means apply the texture for the current shader. – If the current shader does not use the texture stage 2, nothing happens.

222 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

setTexture(number red, number green, number blue, number * alpha) Set a new solid texture for a renderizable. It considers the current animation. Parameters • number – red color (0-1). • number – green color (0-1). • number – blue color (0-1). • number – alpha color (0-1) (optional, default 1). Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:setTexture(1,0,0) --Apply a solid (red color) to the sprite setColor(number red, number green, number blue, number * alpha) Set a new solid texture for a renderizable. It considers the current animation. Parameters • number – red color (0-1). • number – green color (0-1). • number – blue color (0-1). • number – alpha color (0-1) (optional, default 1). Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') tSprite:setColor(1,0,0) --Apply a solid (red color) to the sprite (same as setTexture)

12.3.9 Animation getTotalAnim getTotalAnim Retrieve the total animation from a renderizable. Returns number - total animation for the renderizable. Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') local iTotal= tSprite:getTotalAnim()

12.3.10 Animation addAnim addAnim(string* name, number* type, number* start_frame, number* final_Frame, number * interval) Create a new animation to a renderizable based on animation table. Parameters • string – name of animation.

12.3. Animation 223 MBM Documentation, Release 3.1.f

• number – type of animation (see animation table index type). • number – start frame of animation. • number – final frame of animation. • number – interval between frames of animation. Returns string name, number index (1 based) - animation of renderizable created. Example: local tSprite= sprite:new('2DW') tSprite:load('sprite.spt') tSprite:addAnim('walk',mbm.GROWING_LOOP,1,5,0.2)

12.3.11 Animation getShader getShader Retrieve the shader used by renderizable for the current animation. Returns shader - from renderizable. Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') local shader= tSprite:getShader()

12.4 Physics

It is possible to retrieve the physics information applied to renderizable however it is not possible to change in the mesh. You only can change the info retrieved. getPhysics Returns table - array with each physics applied to this renderizable. Example: local tSprite= sprite:new('2DW') tSprite:load('tSprite.spt') local tInfoPhysics= tSprite:getPhysics() for i=1,#tInfoPhysics do print(tInfoPhysics[i].type) if tInfoPhysics[i].type =='cube' then print('center x:',tInfoPhysics[i].x) print('center y:',tInfoPhysics[i].y) print('center z:',tInfoPhysics[i].z) print('width:', tInfoPhysics[i].width) print('height:', tInfoPhysics[i].height) print('depth:', tInfoPhysics[i].depth) elseif tInfoPhysics[i].type =='sphere' then print('center x:',tInfoPhysics[i].x) print('center y:',tInfoPhysics[i].y) print('center z:',tInfoPhysics[i].z) print('ray:', tInfoPhysics[i].ray) (continues on next page)

224 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

(continued from previous page) elseif tInfoPhysics[i].type =='triangle' then print('a x:',tInfoPhysics[i].a.x) print('a y:',tInfoPhysics[i].a.y) print('a z:',tInfoPhysics[i].a.z) print('b x:',tInfoPhysics[i].b.x) print('b y:',tInfoPhysics[i].b.y) print('b z:',tInfoPhysics[i].b.z) print('c x:',tInfoPhysics[i].c.x) print('c y:',tInfoPhysics[i].c.y) print('c z:',tInfoPhysics[i].c.z) elseif tInfoPhysics[i].type =='complex' then print('a x:',tInfoPhysics[i].a.x) print('a y:',tInfoPhysics[i].a.y) print('a z:',tInfoPhysics[i].a.z) print('b x:',tInfoPhysics[i].b.x) print('b y:',tInfoPhysics[i].b.y) print('b z:',tInfoPhysics[i].b.z) print('c x:',tInfoPhysics[i].c.x) print('c y:',tInfoPhysics[i].c.y) print('c z:',tInfoPhysics[i].c.z) print('d x:',tInfoPhysics[i].d.x) print('d y:',tInfoPhysics[i].d.y) print('d z:',tInfoPhysics[i].d.z) print('e x:',tInfoPhysics[i].e.x) print('e y:',tInfoPhysics[i].e.y) print('e z:',tInfoPhysics[i].e.z) print('f x:',tInfoPhysics[i].f.x) print('f y:',tInfoPhysics[i].f.y) print('f z:',tInfoPhysics[i].f.z) print('g x:',tInfoPhysics[i].g.x) print('g y:',tInfoPhysics[i].g.y) print('g z:',tInfoPhysics[i].g.z) print('h x:',tInfoPhysics[i].h.x) print('h y:',tInfoPhysics[i].h.y) print('h z:',tInfoPhysics[i].h.z) end end

12.5 Renderizable attributes x, y, z [read / write] Access the position x, y and z member from renderizable. Example: local tSprite= sprite:new('2DW') tSprite.x= 100 tSprite.y= 200 tSprite.z=-1 print(tSprite.x,tSprite.y,tSprite.z) -- 100 200 -1 sx, sy, sz [read / write] Access the scale sx, sy and sz member from renderizable.

12.5. Renderizable attributes 225 MBM Documentation, Release 3.1.f

Example: local tSprite= sprite:new('2DW') tSprite.sx= 0.8 tSprite.sy= 0.8 tSprite.sz=1 print(tSprite.sx,tSprite.sy,tSprite.sz) -- 0.8 0.8 1 ax, ay, az [read / write] Access the angle ax, ay and az member from renderizable. Example: local tSprite= sprite:new('2DW') tSprite.ax= math.rad(180) tSprite.ay= math.rad(90) tSprite.az= math.rad(45) print(math.deg(tSprite.ax),math.deg(tSprite.ay),math.deg(tSprite.az)) -- 180 90 45

Note: The angle is radian. visible [read / write] Enable or disable the renderizable to be rendered. Example: local tSprite= sprite:new('2DW') tSprite.visible= false --turn invisible the object

Attention: If you set the property visible as true and check the isOnScreen method next (same step), the result always will be true even if the object is not on screen. This happens because it has to wait for at least one loop to the engine update the objects that are on screen. More information at isOnScreen explanation. alwaysRender [read / write] Force always render the renderizable even if is not at the screen. Example: local tSprite= sprite:new('2DW') tSprite.alwaysRender= true -- always will be renderized

'variable' [read / write] Create a variable read/write to renderizable. The type allowed is number, string, boolean, table and function. Example: local tSprite= sprite:new('2DW') function myPrint(self,message) print('message:', message or '') (continues on next page)

226 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

(continued from previous page) end

tSprite.myFloat= 3.151413 tSprite.myInt=9 tSprite.myString='Hi there!' tSprite.myTable= {msg='Hi there!'} tSprite.myFunction= myPrint print('Accessing the variables myFloat:',tSprite.myFloat) print('Accessing the variables myInt:',tSprite.myInt) print('Accessing the variables myString:',tSprite.myString) print('Accessing the variables myTable:',tSprite.myTable.msg) tSprite:myPrint('Hello!')

12.6 User data acknowledgment

This table uses the first index to store the userdata C++ class internally. So, if you want to store some values to the table you must use from the second element as exampled bellow:

Listing 12.1: You can do this:

1 tTexture= texture:new('2ds')

2 tTexture:setPos(12,5)

3

4 tTexture[2]='some value var'

5

6 print(tTexture[2]) -- 'some value var'

Error: It is important to understand that as all tables used in this engine, this table uses the first index to store the userdata pointing to the C++ class internally. There is no mechanism to prevent to access the first index from renderizable. If you overload the userdata, probably the program will crash.

Listing 12.2: Do not do this:

1 tTexture= texture:new('2dw')

2 tTexture:setPos(100,300,-1)

3

4 print(tTexture[1]) -- read, okay will print userdata: 0x55957888a6a8 for example

5

6 tTexture[1]=2 -- Error, this will do your program crash!

Table of Contents

• Table shader – shader methods

* shader load * shader setPS

12.6. User data acknowledgment 227 MBM Documentation, Release 3.1.f

· shader setPS · shader setPSmin · shader setPSmax · shader setPSall · shader setPStime · shader setPStype

* shader setVS · shader setVS · shader setVSmin · shader setVSmax · shader setVSall · shader setVStime · shader setVStype

* shader getPS · shader getPS · shader getPSmin · shader getPSmax · shader getPStime · shader getPStype

* shader getVS · shader getVS · shader getVSmin · shader getVSmax · shader getVStime · shader getVStype

* shader util · shader getNames · shader getCode · shader getVars · shader getTextureStage2

* shader setBlendOp * shader getBlendOp – pixel shader

* bands * blend

228 Chapter 12. Table renderizable MBM Documentation, Release 3.1.f

* bloom * blur directional * blur zoom * bright extract * brightness * color it * color keying * color tone * edge gradient magnitude * embossed * explosion gaussian * fade radial * fade ripple * fade saturate * fade twist grid * fade twist * fade wave * fade * font * frosty out line * glass tile * invert color * luminance * magnifying glass * multi textura * night vision blur * night vision * old movie * out of bounds * pinch mouse * pinch * poisson * ripple * saturate * sharpen

12.6. User data acknowledgment 229 MBM Documentation, Release 3.1.f

* sketch * smooth magnify * spiral * texture map * tiled map * tone mapping * toon * transparent * wave – vertex shader

* scale * simple texture

230 Chapter 12. Table renderizable CHAPTER 13

Table shader

A table shader is responsible for the effect shader in the renderizable table. Each animation has an effect shader which can be modified by the shader methods and also it has its own animation. Use getShader to retrieve a shader table. Use getShaderList to get shader information. All shader code are described at shader code.

13.1 shader methods

13.1.1 shader load load(string pixelFileName, string vertexFileName, *number typeAnimPs, *number timeAnimPs, *number ty- peAnimVs, *number timeAnimVs) Load a new shader supplying arguments needed. Parameters • string – pixelFileName must exists or can be nil. • string – vertexFileName can be nil (optional) . • number – typeAnimPs Type animation constant for pixel shader. (optional, default is GROWING), see type of animation • number – timeAnimPs Animation time for pixel shader. (optional, default is 0.0). • number – typeAnimVs Type animation constant for vertex shader. (optional, default is GROWING), see type of animation • number – timeAnimVs Animation time for vertex shader. (optional, default is 0.0). Returns boolean - result Example

231 MBM Documentation, Release 3.1.f

myMesh1= mesh:new('2dw',-100) -- create one object as 2d in the left (x:-100) myMesh2= mesh:new('2dw', 100) -- create second object as 2d in the right (x:100) if myMesh1:load('crate.msh') then print("crate 1 successfully loaded") else print('Failed to load crate.msh (1)') end if myMesh2:load('crate.msh') then print("crate 2 successfully loaded ... let's apply a shader to it") local tShader= myMesh2:getShader() if tShader:load('brightness.ps',nil,mbm.GROWING,1.0,mbm.GROWING_LOOP,2.0) then print('Successfully loaded shader') else print('Failed to load shader ...') end else print('Failed to load crate.msh (2)') end

Figure 13.1: Applying shader and compare to an object without shader download crate.msh download crate.png

Note: The load method will search in all known path. You can add a path to search by the method addPath. Note all arguments can be nil if not applicable.

13.1.2 shader setPS shader setPS setPS(string name, number value_1, ...) Set new value to a variable ‘current’ into pixel shader passing the variable name and values (one or more, depends on type).

Parameters

232 Chapter 13. Table shader MBM Documentation, Release 3.1.f

• string – name variable. • number – value of variable (can be one or more, depends on shader variable).

Example: mbm.setColor(0,0,0) --background black myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color it.ps',nil,mbm.PAUSED,1.0,mbm.PAUSED,0.0) then local r,g,b=0,1,0 --rgb green color tShader:setPS('color',r,g,b) --set green color to current shader else print('Failed to load shader ...') end else print('Failed to load crate.msh') end

Figure 13.2: Change the current value from a variable in the current shader download crate.msh download crate.png shader setPSmin setPSmin(string name, number value_1, ...) Set the minimum value to a variable into pixel shader passing the variable name and values (one or more, depends on type).

Parameters • string – name variable. • number – value of variable (can be one or more, depends on shader variable).

Example: myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color it.ps',nil,mbm.GROWING_LOOP,0.5,mbm.PAUSED,0.0) then local min_r,min_g,min_b=0,0,0 --rgb black color local max_r,max_g,max_b=1,0,0 --rgb red color tShader:setPSmin('color',min_r,min_g,min_b) --set black color as min color (continues on next page)

13.1. shader methods 233 MBM Documentation, Release 3.1.f

(continued from previous page) tShader:setPSmax('color',max_r,max_g,max_b) --set red color as max color else print('Failed to load shader ...') end else print('Failed to load crate.msh') end

Figure 13.3: Change the min value from a variable in the current shader download crate.msh download crate.png shader setPSmax setPSmax(string name, number value_1, ...) Set the maximum value to a variable into pixel shader passing the variable name and values (one or more, depends on type).

Parameters • string – name variable. • number – value of variable (can be one or more, depends on shader variable).

Example: myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color it.ps',nil,mbm.GROWING_LOOP,0.5,mbm.PAUSED,0.0) then local min_r,min_g,min_b=0,0,0 --rgb black color local max_r,max_g,max_b=1,1,1 --rgb white color tShader:setPSmin('color',min_r,min_g,min_b) --set black color as min color tShader:setPSmax('color',max_r,max_g,max_b) --set white color as max color else print('Failed to load shader ...') end else print('Failed to load crate.msh') end

Figure 13.4: Change the max value from a variable in the current shader download crate.msh download crate.png shader setPSall setPSall(string name, number value_1, ...) Set all values (minimum, maximum and current) to a variable into pixel shader passing the variable name and values (one or more, depends on type).

234 Chapter 13. Table shader MBM Documentation, Release 3.1.f

Parameters • string – name variable. • number – value of variable (can be one or more, depends on shader variable).

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('brightness.ps',nil,mbm.GROWING,0.0,mbm.PAUSED,0.0) then local contrast_value=2 local brightness_value= 0.7 tShader:setPSall('contrast',contrast_value) --set all min, max and current

˓→to contrast_value tShader:setPSall('brightness',brightness_value) --set all min, max and current

˓→to brightness_value else print('Failed to load shader ...') end else print('Failed to load crate.msh') end

Figure 13.5: Change the min/max and current value from a variable in the current shader download crate.msh download crate.png

shader setPStime setPStime(number seconds) Change the time (duration) for the current shader.

Parameters number – time in seconds.

Example: mbm.setColor(1,1,1) -- background white myMesh1= mesh:new('2dw',-100) --left if myMesh1:load('crate.msh') then local tShader= myMesh1:getShader() if tShader:load('brightness.ps',nil,mbm.RECURSIVE_LOOP,1.0,mbm.PAUSED,0.0) then tShader:setPStime(3) --set to 3 second else (continues on next page)

13.1. shader methods 235 MBM Documentation, Release 3.1.f

(continued from previous page) print('Failed to load shader ...') end else print('Failed to load crate.msh') end myMesh2= mesh:new('2dw',100) --right if myMesh2:load('crate.msh') then local tShader= myMesh2:getShader() if tShader:load('brightness.ps',nil,mbm.RECURSIVE_LOOP,1.0,mbm.PAUSED,0.0) then tShader:setPStime(0.5) --set to 0.5 second else print('Failed to load shader ...') end else print('Failed to load crate.msh') end

Figure 13.6: Change the time of effect in the shader download crate.msh download crate.png

shader setPStype setPStype(number type) Change the type of animation for the current shader.

Parameters number – type of animation.

Example: mbm.setColor(1,1,1) -- background white myMesh1= mesh:new('2dw',-100) --left if myMesh1:load('crate.msh') then local tShader= myMesh1:getShader() if tShader:load('brightness.ps',nil,mbm.RECURSIVE_LOOP,1.0,mbm.PAUSED,0.0) then tShader:setPStype(mbm.GROWING_LOOP) --set type to GROWING_LOOP else print('Failed to load shader ...') end else print('Failed to load crate.msh') end myMesh2= mesh:new('2dw',100) --right if myMesh2:load('crate.msh') then local tShader= myMesh2:getShader() if tShader:load('brightness.ps',nil,mbm.RECURSIVE_LOOP,1.0,mbm.PAUSED,0.0) then tShader:setPStype(mbm.DECREASING_LOOP) --set type to DECREASING_LOOP else print('Failed to load shader ...') end else (continues on next page)

236 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) print('Failed to load crate.msh') end

Figure 13.7: Change the type of effect in the shader download crate.msh download crate.png

13.1.3 shader setVS shader setVS setVS(string name, number value_1, ...) Set new value to a variable into vertex shader passing the variable name and values (one or more, depends on type).

Parameters • string – name variable. • number – value of variable (can be one or more, depends on shader variable).

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load(nil,'scale.vs',mbm.PAUSED,0.0,mbm.PAUSED,0.0) then local sx,sy,sz=2,1,1 --stretch on x axis tShader:setVS('scale',sx,sy,sz) --set the current scale else print('Failed to load shader ...') end else print('Failed to load crate.msh (1)') end

Figure 13.8: Set a value to a variable into a vertex shader download crate.msh download crate.png shader setVSmin setVSmin(string name, number value_1, ...)

13.1. shader methods 237 MBM Documentation, Release 3.1.f

Set the minimum value to a variable into vertex shader passing the variable name and values (one or more, depends on type).

Parameters • string – name variable. • number – value of variable (can be one or more, depends on shader variable).

Example: myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load(nil,'scale.vs',mbm.PAUSED,0.0,mbm.RECURSIVE_LOOP,1.0) then local min_x,min_y,min_z=1,1,1 local max_x,max_y,max_z=2,2,2 tShader:setVSmin('scale',min_x,min_y,min_z) --set min scale tShader:setVSmax('scale',max_x,max_y,max_z) --set max scale else print('Failed to load shader ...') end else print('Failed to load crate.msh (1)') end

Figure 13.9: Applying min value to vertex shader download crate.msh download crate.png shader setVSmax setVSmax(string name, number value_1, ...) Set the maximum value to a variable into vertex shader passing the variable name and values (one or more, depends on type).

Parameters • string – name variable. • number – value of variable (can be one or more, depends on shader variable).

Example:

*Example:* myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load(nil,'scale.vs',mbm.PAUSED,0.0,mbm.RECURSIVE_LOOP,1.0) then local min_x,min_y,min_z=1,1,1 local max_x,max_y,max_z=2,2,2 tShader:setVSmin('scale',min_x,min_y,min_z) --set min scale tShader:setVSmax('scale',max_x,max_y,max_z) --set max scale else (continues on next page)

238 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) print('Failed to load shader ...') end else print('Failed to load crate.msh (1)') end

Figure 13.10: Applying max value to vertex shader download crate.msh download crate.png shader setVSall setVSall(string name, number value_1, ...) Set all values (minimum, maximum and current) to a variable into vertex shader passing the variable name and values (one or more, depends on type).

Parameters • string – name variable. • number – value of variable (can be one or more, depends on shader variable).

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load(nil,'scale.vs',mbm.GROWING,0.0,mbm.PAUSED,0.0) then local sx,sy,sz=2,0.5,1 --stretch on x axis and shrink it in the y axis tShader:setVSall('scale',sx,sy,sz) --set the current scale else print('Failed to load shader ...') end else print('Failed to load crate.msh (1)') end

Figure 13.11: Set all values (min, max and current) to a variable into a vertex shader download crate.msh download crate.png

shader setVStime setVStime(number seconds)

13.1. shader methods 239 MBM Documentation, Release 3.1.f

Change the time (duration) for the current shader.

Parameters number – time in seconds.

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load(nil,'scale.vs',mbm.PAUSED,0.0,mbm.RECURSIVE_LOOP,1.0) then local min_x,min_y,min_z=1,1,1 local max_x,max_y,max_z=2,2,2 tShader:setVSmin('scale',min_x,min_y,min_z) tShader:setVSmax('scale',max_x,max_y,max_z) tShader:setVStime(0.2) else print('Failed to load shader ...') end else print('Failed to load crate.msh (1)') end

Figure 13.12: change the time of vertex shader effect download crate.msh download crate.png

shader setVStype setVStype(number type) Change the type of animation for the current shader.

Parameters number – type of animation.

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load(nil,'scale.vs',mbm.PAUSED,0.0,mbm.RECURSIVE_LOOP,1.0) then local min_x,min_y,min_z=1,1,1 local max_x,max_y,max_z=2,2,2 tShader:setVSmin('scale',min_x,min_y,min_z) tShader:setVSmax('scale',max_x,max_y,max_z) tShader:getVS(0.2) tShader:setVStype(mbm.GROWING_LOOP) else print('Failed to load shader ...') end else print('Failed to load crate.msh (1)') end

240 Chapter 13. Table shader MBM Documentation, Release 3.1.f

Figure 13.13: change the time of vertex shader effect download crate.msh download crate.png

13.1.4 shader getPS shader getPS getPS(string name) Get the current variable’s value from pixel shader passing the variable name.

Parameters string – name of variable. Returns number value of variable (one or more value, depends on type of variable).

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color tone.ps',nil,mbm.GROWING,0.0,mbm.PAUSED,0.0) then local desaturation= tShader:getPS('desaturation') local toned= tShader:getPS('toned')

local lightColor_r,lightColor_g,lightColor_b,lightColor_a= tShader:getPS(

˓→'lightColor') local darkColor_r,darkColor_g,darkColor_b,darkColor_a= tShader:getPS(

˓→'darkColor')

print('desaturation',desaturation) print('toned', toned) print('lightColor',lightColor_r,lightColor_g,lightColor_b,lightColor_a) print('darkColor',darkColor_r, darkColor_g, darkColor_b, darkColor_a )

else print('Failed to load shader ...') end else print('Failed to load crate.msh') end shader getPSmin getPSmin(string name) Get the minimum variable’s value from pixel shader passing the variable name.

Parameters string – name of variable. Returns number value of variable (one or more value, depends on type of variable).

Example:

13.1. shader methods 241 MBM Documentation, Release 3.1.f

Figure 13.14: getting value of variable in pixel shader download crate.msh download crate.png

mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color tone.ps',nil,mbm.GROWING,0.0,mbm.PAUSED,0.0) then local desaturation= tShader:getPSmin('desaturation') local toned= tShader:getPSmin('toned')

local lightColor_r,lightColor_g,lightColor_b,lightColor_a= tShader:getPSmin(

˓→'lightColor') local darkColor_r,darkColor_g,darkColor_b,darkColor_a= tShader:getPSmin(

˓→'darkColor')

print('min desaturation',desaturation) print('min toned', toned) print('min lightColor',lightColor_r,lightColor_g,lightColor_b,lightColor_a) print('min darkColor',darkColor_r, darkColor_g, darkColor_b, darkColor_a )

else print('Failed to load shader ...') end else print('Failed to load crate.msh') end shader getPSmax getPSmax(string name) Get the maximum variable’s value from pixel shader passing the variable name. Parameters string – name of variable.

242 Chapter 13. Table shader MBM Documentation, Release 3.1.f

Figure 13.15: getting minimum value of variable in pixel shader download crate.msh download crate.png

Returns number value of variable (one or more value, depends on type of variable). Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color tone.ps',nil,mbm.GROWING,0.0,mbm.PAUSED,0.0) then local desaturation= tShader:getPSmax('desaturation') local toned= tShader:getPSmax('toned')

local lightColor_r,lightColor_g,lightColor_b,lightColor_a= tShader:getPSmax(

˓→'lightColor') local darkColor_r,darkColor_g,darkColor_b,darkColor_a= tShader:getPSmax(

˓→'darkColor')

print('max desaturation',desaturation) print('max toned', toned) print('max lightColor',lightColor_r,lightColor_g,lightColor_b,lightColor_a) print('max darkColor',darkColor_r, darkColor_g, darkColor_b, darkColor_a )

else print('Failed to load shader ...') end else print('Failed to load crate.msh') end

13.1. shader methods 243 MBM Documentation, Release 3.1.f

Figure 13.16: getting maximum value of variable in pixel shader download crate.msh download crate.png shader getPStime getPStime Get the time effect from pixel shader passing the variable name.

Returns number time in seconds of the effect.

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color tone.ps',nil,mbm.GROWING,0.0,mbm.PAUSED,0.0) then local my_mtime= tShader:getPStime() print('time',my_mtime) else print('Failed to load shader ...') end else print('Failed to load crate.msh') end shader getPStype getPStype Get the type animation from pixel shader passing the variable name.

Returns literal type of animation as string, type as number.

244 Chapter 13. Table shader MBM Documentation, Release 3.1.f

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color tone.ps',nil,mbm.GROWING,0.0,mbm.PAUSED,0.0) then local sType,iType= tShader:getPStype() print('type as string :'.. sType,'type as integer:', iType) --output: type as string :GROWING type as integer: 1 else print('Failed to load shader ...') end else print('Failed to load crate.msh') end

13.1.5 shader getVS shader getVS getVS(string name) Get the current variable’s value from vertex shader passing the variable name.

Parameters string – name of variable. Returns number value of variable (one or more value, depends on type of variable).

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color tone.ps','scale.vs',mbm.GROWING,0.0,mbm.PAUSED,0.0) then tShader:setVS('scale',2,2,2) local xScale,yScale,zScale= tShader:getVS('scale') print('The current value of scale is:',xScale,yScale,zScale) else print('Failed to load shader ...') end else print('Failed to load crate.msh') end shader getVSmin getVSmin(string name) Get the minimum variable’s value from vertex shader passing the variable name.

Parameters string – name of variable. Returns number value of variable (one or more value, depends on type of variable).

13.1. shader methods 245 MBM Documentation, Release 3.1.f

Figure 13.17: getting the value of variable from vertex shader download crate.msh download crate.png

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load('color tone.ps','scale.vs',mbm.GROWING,0.0,mbm.PAUSED,0.0) then tShader:setVS('scale',2,2,2) local x_min,y_min,z_min= tShader:getVSmin('scale') print('The minimum value of scale is:',x_min,y_min,z_min) else print('Failed to load shader ...') end else print('Failed to load crate.msh') end shader getVSmax getVSmax(string name) Get the maximum variable’s value from vertex shader passing the variable name. Parameters string – name of variable. Returns number value of variable (one or more value, depends on type of variable). Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() (continues on next page)

246 Chapter 13. Table shader MBM Documentation, Release 3.1.f

Figure 13.18: getting the minimum value of variable from vertex shader download crate.msh download crate.png

(continued from previous page) if tShader:load('color tone.ps','scale.vs',mbm.GROWING,0.0,mbm.PAUSED,0.0) then tShader:setVS('scale',2,2,2) local x_max,y_max,z_max= tShader:getVSmax('scale') print('The maximum value of scale is:',x_max,y_max,z_max) else print('Failed to load shader ...') end else print('Failed to load crate.msh') end

Figure 13.19: getting the maximum value of variable from vertex shader download crate.msh download crate.png

13.1. shader methods 247 MBM Documentation, Release 3.1.f shader getVStime getVStime Get the time effect from vertex shader passing the variable name.

Returns number time in seconds of the effect.

Example: myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load(nil,'scale.vs',mbm.PAUSED,0.0,mbm.GROWING,0.0) then local i_time= tShader:getVStime() print('time:',i_time) else print('Failed to load shader ...') end else print('Failed to load crate.msh') end shader getVStype getVStype Get the type animation from vertex shader passing the variable name.

Returns literal type of animation as string, type as number.

Example: mbm.setColor(1,1,1) -- background white myMesh= mesh:new('2dw') if myMesh:load('crate.msh') then local tShader= myMesh:getShader() if tShader:load(nil,'scale.vs',mbm.PAUSED,0.0,mbm.GROWING,0.0) then local sType,iType= tShader:getVStype() print('type as string :'.. sType,'type as integer:', iType) --output: type as string :GROWING type as integer: 1 else print('Failed to load shader ...') end else print('Failed to load crate.msh') end

13.1.6 shader util

The following methods are useful mostly for editors.

248 Chapter 13. Table shader MBM Documentation, Release 3.1.f

shader getNames

getNames Retrieve the names (pixel and vertex) from current shader.

Returns string pixel shader name, string vertex shader name (might return nil) shader getCode getCode Retrieve the code (pixel and vertex) from current shader.

Returns string pixel shader code, string vertex shader code (might return nil) shader getVars getVars Retrieve an array of table with information (pixel and vertex) from current shader for each variable.

Returns table pixel shader variables, table vertex shader variables

The table will have the following structure:

Field Expected as Detail type name string variable name type number {[1] = value} vec2 {[1] = x,[2] = y} vec3 {[1] = x,[2] = y, [3] value rgb = z} rgba {[1] = r,[2] = g, [3] = b} min {[1] = r,[2] = g, [3] = b, [4] = a} max

Example:

{[1]= { name='color', type='rgb', value={[1]= r, [2]= g, [3]= b}, min={[1]= r, [2]= g, [3]= b}, max={[1]= r, [2]= g, [3]= b} }, [2]= {...} }

shader getTextureStage2

getTextureStage2 Retrieve the current texture applied to stage 2 (if there is) (might return nil)

Returns string texture file name

13.1. shader methods 249 MBM Documentation, Release 3.1.f

13.1.7 shader setBlendOp

Blend state or Blending is the stage of OpenGL rendering pipeline that takes the fragment color outputs from the Fragment Shader and combines them with the colors in the color buffers that these outputs map to. Blending parameters can allow the source and destination colors for each output to be combined in various ways. The color S is the source color; the color D is the destination color; the color O is the output color that is written to the buffer. The S, D, and so forth represent all of the components of that color. Srgb represents only the RGB components of the source color. Da represents the alpha component of the destination color. You can learn more at wiki Blending.

250 Chapter 13. Table shader MBM Documentation, Release 3.1.f

Function Explanation ADD The source and destination colors are added to each other. O = sS + dD. The s and d are blending parameters that are multiplied into each of S and D before the addition.

SUBTRACT Subtracts the destination from the source. O = sS - dD. The source and dest are multiplied by blending parameters.

REVERSE_SUBTRACT Subtracts the source from the destination. O = dD - sS. The source and dest are multiplied by blending parameters.

MIN The output color is the component-wise minimum value of the source and dest colors. So performing GL_MIN in the RGB equation means that Or = min(Sr, Dr), Og = min(Sg, Dg), and so forth. The parameters s and d are ignored for this equation.

MAX The output color is the component-wise maximum value of the source and dest colors. The parameters s and d are ignored for this equation.

Blend operation is also described at blend state topic. setBlendOp(string name) Set the blend operation to a renderizable. Parameters string – name regard the :blend operation. Example: local tShape= shape:new('2DW') tShape:create('circle') local tShader= tShape:getShader() tShader:setBlendOp('MIN') setBlendOp(number constant)

13.1. shader methods 251 MBM Documentation, Release 3.1.f

Set the blend operation to a renderizable. Parameters string – name regard the :blend operation. Example: local tShape= shape:new('2DW') tShape:create('circle') local tShader= tShape:getShader() tShader:setBlendOp(mbm.MAX)

13.1.8 shader getBlendOp getBlendOp Get the blend operation from a renderizable. Returns string name - blend operation of renderizable. Example: local tShape= shape:new('2DW') tShape:create('circle') local tShader= tShape:getShader() print(tShader:getBlendOp()) -- expected 'ADD'

13.2 pixel shader

Bellow all embedded pixel shader available for the engine:

13.2.1 bands

name bands.ps variable bandIntensity min 0.001 max 0.56 default 0.56 variable bandDensity min 0 max 150 default 65 shader code precision mediump float; uniform float bandDensity; uniform float bandIntensity; uniform sampler2D sample0; varying vec2 vTexCoord; (continues on next page)

252 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) vec4 xlat_main(in vec4 color) { color.xyz+= (tan((vTexCoord.x * bandDensity)) * bandIntensity); return color; } void main() { vec4 color; color= texture2D(sample0, vTexCoord); gl_FragColor= xlat_main(color); }

13.2.2 blend

name blend.ps variable junctionRemove min 0, 0, 0, 0 max 1, 1, 1, 1 default 0.2, 0.2, 0.2, 0 variable colorAdd min 0, 0, 0 max 1, 1, 1 default 1, 0, 0 variable invertSample min 0 max 1 default 0 variable disableSample1 min 0 max 1 default 0 shader code precision mediump float; uniform vec3 colorAdd; uniform vec4 junctionRemove; uniform sampler2D sample0; uniform sampler2D sample1; uniform float invertSample; uniform float disableSample1; varying vec2 vTexCoord;

(continues on next page)

13.2. pixel shader 253 MBM Documentation, Release 3.1.f

(continued from previous page) void main() { vec4 c0; vec4 c1; vec4 original; vec4 outColor;

if (invertSample> 0.5) { c0= texture2D(sample1, vTexCoord.xy); //sample1 precisa ter alpha c1= texture2D(sample0, vTexCoord.xy); //sample0 nao precisa ter alpha } else { c0= texture2D(sample0, vTexCoord.xy); //sample0 nao precisa ter alpha c1= texture2D(sample1, vTexCoord.xy); //sample1 precisa ter alpha } if(disableSample1> 0.5) { c0.rgb+= colorAdd; gl_FragColor= c0; } else { c1-= junctionRemove; original= c0; outColor.w= c0.w ; c1.xyz= (c1.xyz * c0.w ); outColor.xyz= ((c0.xyz * (1.0- c1.w ))+ c1.xyz ); outColor= mix( original, outColor, vec4( c1.w )); outColor.xyz+= colorAdd; gl_FragColor= outColor; } }

13.2.3 bloom

name bloom.ps variable BloomIntensity min 0 max 2 default 1 variable BaseIntensity min 0 max 2 default 0.5 variable BaseSaturation min 0 max 2

254 Chapter 13. Table shader MBM Documentation, Release 3.1.f

default 0.5 variable BloomSaturation min 0 max 2 default 1 shader code precision mediump float; uniform float BaseIntensity; uniform float BaseSaturation; uniform float BloomIntensity; uniform float BloomSaturation; uniform sampler2D sample0; varying vec2 vTexCoord; float xlat_lib_saturate(float x) { return clamp(x, 0.0, 1.0); } vec2 xlat_lib_saturate(vec2 x) { return clamp(x, 0.0, 1.0); } vec3 xlat_lib_saturate(vec3 x) { return clamp(x, 0.0, 1.0); } vec4 xlat_lib_saturate(vec4 x) { return clamp(x, 0.0, 1.0); } mat2 xlat_lib_saturate(mat2 m) { return mat2(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0)); } mat3 xlat_lib_saturate(mat3 m) { return mat3(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0)); } mat4 xlat_lib_saturate(mat4 m) { return mat4(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0),

˓→clamp(m[3], 0.0, 1.0)); } vec3 AdjustSaturation(in vec3 color, in float saturation) { float grey; (continues on next page)

13.2. pixel shader 255 MBM Documentation, Release 3.1.f

(continued from previous page) grey= dot(color, vec3(0.3, 0.59, 0.11)); return vec3(mix(grey, float(color.xyz), saturation)); } vec4 xlat_main(in vec4 color) { float BloomThreshold= 0.250000; vec3 base; vec3 bloom;

base= (color.xyz/ color.w); bloom= xlat_lib_saturate(((base- BloomThreshold)/(1.00000- BloomThreshold))); bloom= (AdjustSaturation(bloom, BloomSaturation) * BloomIntensity); base= (AdjustSaturation(base, BaseSaturation) * BaseIntensity); base *=(1.00000- xlat_lib_saturate(bloom)); return vec4(((base+ bloom) * color.w), color.w); } void main() { vec4 color; color= texture2D(sample0, vTexCoord); if(color.a == 0.0) discard; else gl_FragColor= xlat_main(color); }

13.2.4 blur directional

name blur directional.ps variable blurAmount min 0 max 0.01 default 0 variable angle min 0 max 360 default 0 shader code precision mediump float; uniform float angle; uniform float blurAmount; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv,vec4 color) (continues on next page)

256 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) { vec4 c; float rad; float xOffset; float yOffset; int i=0; c= vec4(0.0); rad= (angle * 0.0174533); xOffset= cos(rad); yOffset= sin(rad); for (; (i< 16); (++i)) { uv.x= (uv.x- (blurAmount * xOffset)); uv.y= (uv.y- (blurAmount * yOffset)); c+= texture2D(sample0, uv); } c/= 16.0000; return c; } void main() { vec4 color= texture2D(sample0, vTexCoord); gl_FragColor= xlat_main(vTexCoord,color); }

13.2.5 blur zoom

name blur zoom.ps variable center min 0, 0 max 1, 1 default 0.62, 0.67 variable blurAmount min 0 max 2 default 0.2 shader code precision mediump float; uniform float blurAmount; uniform vec2 center; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv) { vec4 color; (continues on next page)

13.2. pixel shader 257 MBM Documentation, Release 3.1.f

(continued from previous page) vec4 c; int i=0; float scale;

c= vec4(0.000000); uv-= center; for (; (i< 15); (++i)) { scale=(1.00000+ (blurAmount * (float(i)/ 14.0000))); c+= texture2D(sample0, ((uv * scale)+ center)); } c/= 15.0000; return c; } void main() { vec4 color= texture2D(sample0, vTexCoord); gl_FragColor= xlat_main(vTexCoord); }

13.2.6 bright extract

name bright extract.ps variable threshold min 0 max 1 default 0.5 shader code precision mediump float; uniform sampler2D sample0; uniform float threshold; varying vec2 vTexCoord; float xlat_lib_saturate(float x) { return clamp(x, 0.0, 1.0); } vec2 xlat_lib_saturate(vec2 x) { return clamp(x, 0.0, 1.0); } vec3 xlat_lib_saturate(vec3 x) { return clamp(x, 0.0, 1.0); } vec4 xlat_lib_saturate(vec4 x) (continues on next page)

258 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) { return clamp(x, 0.0, 1.0); } mat2 xlat_lib_saturate(mat2 m) { return mat2(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0)); } mat3 xlat_lib_saturate(mat3 m) { return mat3(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0)); } mat4 xlat_lib_saturate(mat4 m) { return mat4(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0),

˓→clamp(m[3], 0.0, 1.0)); } vec4 xlat_main(in vec2 uv) { vec4 originalColor; vec3 rgb;

originalColor= texture2D(sample0, uv); rgb= (originalColor.xyz/ originalColor.w); rgb= xlat_lib_saturate(((rgb- threshold)/(1.00000- threshold))); return vec4((rgb * originalColor.w), originalColor.w); } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.2.7 brightness

name brightness.ps variable contrast min 0 max 2 default 1.5 variable brightness min 0 max 1 default 0.5 shader code

13.2. pixel shader 259 MBM Documentation, Release 3.1.f

precision mediump float; uniform float brightness; uniform float contrast; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv,in vec4 pixelColor) { pixelColor.xyz/= pixelColor.w; pixelColor.xyz= (((pixelColor.xyz- 0.500000) * max(contrast, 0.000000))+ 0. ˓→500000); pixelColor.xyz+= brightness; pixelColor.xyz *= pixelColor.w; return pixelColor; } void main() { vec4 color= texture2D(sample0, vTexCoord); if (color.a == 0.0) discard; else gl_FragColor= xlat_main(vTexCoord,color); }

13.2.8 color it

name color it.ps variable color min 0, 0, 0 max 1, 1, 1 default 1, 0, 0 variable enable min 0 max 1 default 1 shader code precision mediump float; uniform sampler2D sample0; uniform vec3 color; uniform float enable; varying vec2 vTexCoord; void main() { vec4 c= texture2D( sample0, vTexCoord.xy ); if(enable> 0.5) gl_FragColor= vec4(color.r,color.g,color.b,c.a); else (continues on next page)

260 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) gl_FragColor= c; }

13.2.9 color keying

name color keying.ps variable colorDst min 0.1, 0.2, 0.3, 0 max 1, 1, 1, 1 default 1, 0.2, 1, 1 variable granThen min 0 max 1 default 1 variable colorSrc min 0.0392157, 0.0784314, 0.117647, 1 max 0.490196, 0.501961, 0.980392, 1 default 0.490196, 0.501961, 0.196078, 1 variable tolerance min 0 max 1 default 0.3 shader code precision mediump float; uniform vec4 colorDst; uniform vec4 colorSrc; uniform float granThen; uniform sampler2D sample0; uniform float tolerance; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv, vec4 color) {

if ((granThen> 0.500000)) { if (all(lessThan(abs((color.xyz- colorSrc.xyz)), vec3(tolerance)))) { color.xyzw= colorDst; } } else (continues on next page)

13.2. pixel shader 261 MBM Documentation, Release 3.1.f

(continued from previous page) { if (all(greaterThan(abs((color.xyz- colorSrc.xyz)), vec3(tolerance)))) { color.xyzw= colorDst; } } return color; } void main() { vec4 color; color= texture2D(sample0, vTexCoord); if ((color.w == 0.0)) discard; else gl_FragColor= xlat_main(vTexCoord, color); }

13.2.10 color tone

name color tone.ps variable desaturation min 0 max 1 default 0.5 variable lightColor min 0, 0, 0, 0 max 1, 1, 1, 1 default 1, 1, 1, 1 variable toned min 0 max 1 default 0.5 variable darkColor min 0, 0, 0, 0 max 1, 1, 1, 1 default 1, 1, 0, 0.7 shader code precision mediump float; uniform vec4 darkColor; uniform float desaturation; uniform vec4 lightColor; (continues on next page)

262 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) uniform sampler2D sample0; uniform float toned; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv,in vec4 color) { vec3 scnColor; float gray; vec3 muted; vec3 middle;

color= texture2D(sample0, uv); scnColor=( vec3(lightColor) * (color.xyz/ color.w)); gray= dot( vec3(0.300000, 0.590000, 0.110000), scnColor); muted= mix(scnColor, vec3(vec3(gray)), vec3(desaturation)); middle= vec3(mix(darkColor, lightColor, vec4(gray))); scnColor= mix(muted, middle, vec3(toned)); return vec4((scnColor * color.w), color.w); } void main() { vec4 color= texture2D(sample0, vTexCoord); if (color.a == 0.0) discard; else gl_FragColor= xlat_main(vTexCoord,color); }

13.2.11 edge gradient magnitude

name edge gradient magnitude.ps variable imageSize min 0, 0 max 1024, 1024 default 256, 256 variable tolerance min 0 max 1 default 0 shader code precision mediump float; uniform vec2 imageSize; uniform sampler2D sample0; uniform float tolerance; varying vec2 vTexCoord; vec4 xlat_main( in vec2 uv) { (continues on next page)

13.2. pixel shader 263 MBM Documentation, Release 3.1.f

(continued from previous page) vec2 offsetTexture; vec2 pixel_Right; vec2 pixel_Left; vec2 pixel_Top; vec2 pixel_Bottom; vec2 gradient; float a;

offsetTexture=(1.00000/ imageSize); pixel_Right= (uv.xy+ vec2( offsetTexture.x , 0.000000)); pixel_Left= (uv.xy+ vec2((-offsetTexture.x ), 0.000000)); pixel_Top= (uv.xy+ vec2( 0.000000, offsetTexture.y )); pixel_Bottom= (uv.xy+ vec2( 0.000000,(-offsetTexture.y ))); gradient= vec2( length( (texture2D( sample0, pixel_Right).xyz- texture2D(

˓→sample0, pixel_Left).xyz ) ), length( (texture2D( sample0, pixel_Top).xyz-

˓→texture2D( sample0, pixel_Bottom).xyz ) )); a= length( gradient ); return vec4( a, a, a, 1.00000); } void main() { float a= texture2D(sample0, vTexCoord).a; if (a == 0.0) discard; else { vec4 color= xlat_main(vTexCoord); if(color.r <= tolerance&& color.g <= tolerance&& color.b <= tolerance) discard; else gl_FragColor= xlat_main(vTexCoord); }}

13.2.12 embossed

name embossed.ps variable width min 0 max 0.1 default 0.0023 variable amount min 0 max 1 default 0.5 shader code precision mediump float;

(continues on next page)

264 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) uniform float amount; uniform sampler2D sample0; uniform float width; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv) { vec4 outC= vec4(0.500000, 0.500000, 0.500000, 1.00000); outC-= (texture2D(sample0, (uv- width)) * amount); outC+= (texture2D(sample0, (uv+ width)) * amount); outC.xyz= vec3((((outC.x+ outC.y)+ outC.z)/ 3.00000)); return outC; } void main() { vec4 color; color= texture2D(sample0, vTexCoord); if (color.a == 0.0) discard; else gl_FragColor= xlat_main(vTexCoord); }

13.2.13 explosion gaussian

name explosion gaussian.ps variable sigma min -2 max 2 default 0.15 variable color min 0, 0, 0 max 1, 1, 1 default 1, 1, 1 variable center min -1, -1 max 1.5, 1.5 default 0.5, 0.5 shader code precision mediump float; uniform sampler2D sample0; uniform vec2 center; uniform vec3 color; uniform float sigma; varying vec2 vTexCoord; (continues on next page)

13.2. pixel shader 265 MBM Documentation, Release 3.1.f

(continued from previous page) vec4 xlat_main( in vec2 uv ) { float alpha; float PI= 3.14152; float s; float q; float a;

s=(2.0 * pow( sigma, 2.0)); q=(1.0/ (PI * s)); a= (q * exp( ((-(pow( (uv.x- center.x), 2.0)+ pow( (uv.y- center.y), 2.0)) ˓→)/ s) )); alpha= texture2D(sample0, uv.xy).a; return vec4( a * color.r, a * color.g, a * color.b, alpha); } void main() { gl_FragColor= xlat_main( vTexCoord); }

13.2.14 fade radial

name fade radial.ps variable progress min 0 max 100 default 30 shader code precision mediump float; uniform float progress; uniform sampler2D sample0; uniform sampler2D sample1; varying vec2 vTexCoord; vec4 RadialBlur(in vec4 color, in float progress, in vec2 uv) { vec2 center= vec2(0.500000, 0.500000); vec2 toUV; vec2 normToUV; vec4 c1= vec4(0.000000, 0.000000, 0.000000, 0.000000); float s; int i=0;

toUV= (uv- center); normToUV= toUV; s= (progress * 0.0200000); for (; (i< 24); (++i)) (continues on next page)

266 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) { c1+= texture2D(sample1, (uv- ((normToUV * s) * float(i)))); } c1/= 24.0000; return mix(c1, color, vec4(progress)); } vec4 xlat_main(in vec2 uv) { vec4 color;

color= texture2D(sample0, uv); if ((color.w == 0.000000)) { return color; } return RadialBlur(color, (progress/ 100.000), uv); } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.2.15 fade ripple

name fade ripple.ps variable progress min 0 max 100 default 30 shader code precision mediump float; uniform float progress; uniform sampler2D sample0; uniform sampler2D sample1; varying vec2 vTexCoord; vec4 Ripple(in float progress, in vec2 uv) { float frequency= 20.0000; float speed= 10.0000; float amplitude= 0.0500000; vec2 center= vec2(0.500000, 0.500000); vec2 toUV; float distanceFromCenter; vec2 normToUV; float wave; float offset1; float offset2; (continues on next page)

13.2. pixel shader 267 MBM Documentation, Release 3.1.f

(continued from previous page) vec2 newUV1; vec2 newUV2; vec4 c1; vec4 c2;

toUV= (uv- center); distanceFromCenter= length(toUV); normToUV= (toUV/ distanceFromCenter); wave= cos(((frequency * distanceFromCenter)- (speed * progress))); offset1= ((progress * wave) * amplitude); offset2= (((1.00000- progress) * wave) * amplitude); newUV1= (center+ (normToUV * (distanceFromCenter+ offset1))); newUV2= (center+ (normToUV * (distanceFromCenter+ offset2))); c1= texture2D(sample1, newUV1); c2= texture2D(sample0, newUV2); return mix(c1, c2, vec4(progress)); } void main() { vec4 color;

color= texture2D(sample0, vTexCoord); gl_FragColor= Ripple((progress/ 100.000), vTexCoord); }

13.2.16 fade saturate

name fade saturate.ps variable progress min 0 max 100 default 30 shader code precision mediump float; uniform float progress; uniform sampler2D sample0; uniform sampler2D sample1; varying vec2 vTexCoord; vec4 xlat_lib_saturate(vec4 x) { return clamp(x, 0.0, 1.0); } vec4 Saturate(in vec2 uv, in float progress, in vec4 c2) { vec4 c1; float new_progress;

c1= texture2D(sample1, uv); (continues on next page)

268 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) c1= xlat_lib_saturate((c1 * ((2.00000 * progress)+ 1.00000))); if ((progress> 0.800000)) { new_progress= ((progress- 0.800000) * 5.00000); return mix(c1, c2, vec4(new_progress)); } else { return c1; } } void main() { vec4 color; color= texture2D(sample0, vTexCoord); gl_FragColor= Saturate(vTexCoord, (progress/ 100.000), color);

}

13.2.17 fade twist grid

name fade twist grid.ps variable twistAmount min -70 max 70 default 30 variable progress min 0 max 100 default 30 shader code precision mediump float; uniform sampler2D sample0; uniform sampler2D sample1; uniform float progress; uniform float twistAmount; varying vec2 vTexCoord; void xlat_lib_sincos(float x, out float s, out float c) { s= sin(x); c= cos(x); } vec4 SwirlGrid(in vec2 uv, in float progress, in vec4 color) { (continues on next page)

13.2. pixel shader 269 MBM Documentation, Release 3.1.f

(continued from previous page) float cellsize= 0.100000; vec2 cell; vec2 oddeven; float cellTwistAmount; vec2 newUV; vec2 center= vec2(0.500000, 0.500000); vec2 toUV; float distanceFromCenter; vec2 normToUV; float angle; vec2 newUV2; vec4 c1;

cell= floor((uv * 10.0000)); oddeven= mod(cell, vec2(2.00000)); cellTwistAmount= twistAmount; if ((oddeven.x< 1.00000)) { cellTwistAmount *=-1.00000; } if ((oddeven.y< 1.00000)) { cellTwistAmount *=-1.00000; } newUV= fract((uv * 10.0000)); toUV= (newUV- center); distanceFromCenter= length(toUV); normToUV= (toUV/ distanceFromCenter); angle= atan(normToUV.y, normToUV.x); angle+= (((distanceFromCenter * distanceFromCenter) * cellTwistAmount) * ˓→progress); xlat_lib_sincos(angle, newUV2.y, newUV2.x); newUV2 *= distanceFromCenter; newUV2+= center; newUV2 *= cellsize; newUV2+= (cell * cellsize); c1= texture2D(sample1, newUV2); return mix(c1, color, vec4(progress)); } void main() { vec4 color; color= texture2D(sample0, vTexCoord); gl_FragColor= SwirlGrid(vTexCoord, (progress/ 100.000), color); }

13.2.18 fade twist

name fade twist.ps variable twistAmount min -70 max 70

270 Chapter 13. Table shader MBM Documentation, Release 3.1.f

default 30 variable progress min 0 max 100 default 30 shader code precision mediump float; uniform float progress; uniform sampler2D sample0; uniform sampler2D sample1; uniform float twistAmount; varying vec2 vTexCoord; void xlat_lib_sincos(float x, out float s, out float c) { s= sin(x); c= cos(x); } vec2 xlat_lib_saturate(vec2 x) { return clamp(x, 0.0, 1.0); } vec4 SampleWithBorder(in vec4 border, in sampler2D tex, in vec2 uv) {

if (any(bvec2((xlat_lib_saturate(uv)- uv)))) { return border; } else { return texture2D(tex, uv); } } vec4 Swirl(in vec2 uv, in float progress, in vec4 color) { vec2 center= vec2(0.500000, 0.500000); vec2 toUV; float distanceFromCenter; vec2 normToUV; float angle; vec2 newUV; vec4 c1;

toUV= (uv- center); distanceFromCenter= length(toUV); normToUV= (toUV/ distanceFromCenter); angle= atan(normToUV.y, normToUV.x); angle+= (((distanceFromCenter * distanceFromCenter) * twistAmount) * progress); xlat_lib_sincos(angle, newUV.y, newUV.x); newUV *= distanceFromCenter; (continues on next page)

13.2. pixel shader 271 MBM Documentation, Release 3.1.f

(continued from previous page) newUV+= center; c1= SampleWithBorder( vec4(0.000000, 0.000000, 0.000000, 0.000000), sample1,

˓→newUV); return mix(c1, color, vec4(progress)); } void main() { vec4 color; color= texture2D(sample0, vTexCoord); gl_FragColor= Swirl(vTexCoord, (progress/ 100.000), color); }

13.2.19 fade wave

name fade wave.ps variable progress min 0 max 100 default 30 shader code precision mediump float; uniform float progress; uniform sampler2D sample0; uniform sampler2D sample1; varying vec2 vTexCoord; vec2 xlat_lib_saturate(vec2 x) { return clamp(x, 0.0, 1.0); } vec4 SampleWithBorder(in vec4 border, in sampler2D tex, in vec2 uv) {

if (any(bvec2((xlat_lib_saturate(uv)- uv)))) { return border; } else { return texture2D(tex, uv); } } vec4 Wave(in vec2 uv, in float progress, in vec4 color) { float mag= 0.100000; float phase= 14.0000; (continues on next page)

272 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) float freq= 20.0000; vec2 newUV; vec4 c1;

newUV= (uv+ vec2(((mag * progress) * sin(((freq * uv.y)+ (phase * progress)))), ˓→0.000000)); c1= SampleWithBorder( vec4(0.000000), sample1, newUV); return mix(c1, color, vec4(progress)); } void main() { vec4 color; color= texture2D(sample0, vTexCoord); gl_FragColor= Wave(vTexCoord, (progress/ 100.000), color); }

13.2.20 fade

name fade.ps variable progress min 0 max 100 default 30 shader code precision mediump float; uniform float progress; uniform sampler2D sample0; uniform sampler2D sample1; varying vec2 vTexCoord; vec4 fade(vec4 c2) { vec4 c1= texture2D(sample1, vTexCoord); return mix(c1, c2, vec4(progress/100.0)); } void main() { vec4 color0= texture2D(sample0, vTexCoord); gl_FragColor= fade(color0); }

13.2.21 font

name font.ps variable colorFont

13.2. pixel shader 273 MBM Documentation, Release 3.1.f

min 0, 0, 0 max 1, 1, 1 default 1, 1, 1 shader code precision mediump float; uniform sampler2D sample0; uniform vec3 colorFont; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv) { vec4 color;

color= texture2D(sample0, uv); vec3 c2= vec3(1.0- colorFont.r,1.0- colorFont.g,1.0- colorFont.b); color.rgb-= c2; return color; } void main() { vec4 xlat_retVal; xlat_retVal= xlat_main(vTexCoord); gl_FragColor= vec4(xlat_retVal); }

13.2.22 frosty out line

name frosty out line.ps variable height min 0 max 500 default 300 variable width min 0 max 650 default 300 shader code precision mediump float; uniform float height; uniform sampler2D sample0; uniform float width; varying vec2 vTexCoord; vec4 xlat_main(in vec2 middle) { (continues on next page)

274 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) vec2 topLeft; vec2 top; vec2 topRight; vec2 left; vec2 right; vec2 bottomLeft; vec2 bottom; vec2 bottomRight; vec4 m; vec4 tl; vec4 l; vec4 bl; vec4 t; vec4 b; vec4 tr; vec4 r; vec4 br; vec4 color; vec4 color2; float avg;

topLeft.x= (middle.x-(1.00000/ width)); topLeft.y= (middle.y-(1.00000/ height)); top.x= middle.x; top.y= (middle.y-(1.00000/ height)); topRight.x= (middle.x+(1.00000/ width)); topRight.y= (middle.y-(1.00000/ height)); left.x= (middle.x-(1.00000/ width)); left.y= middle.y; right.x= (middle.x+(1.00000/ width)); right.y= middle.y; bottomLeft.x= (middle.x-(1.00000/ width)); bottomLeft.y= (middle.y+(1.00000/ height)); bottom.x= middle.x; bottom.y= (middle.y+(1.00000/ height)); bottomRight.x= (middle.x+(1.00000/ width)); bottomRight.y= (middle.y+(1.00000/ height)); m= texture2D(sample0, middle); tl= texture2D(sample0, topLeft); l= texture2D(sample0, left); bl= texture2D(sample0, bottomLeft); t= texture2D(sample0, top); b= texture2D(sample0, bottom); tr= texture2D(sample0, topRight); r= texture2D(sample0, right); br= texture2D(sample0, bottomRight); color= (((((-tl)- t)- tr)+ (((-l)+(8.00000 * m))- r))+ (((-bl)- b)- br)); color2= texture2D(sample0, middle); avg= ((color.x+ color.y)+ color.z); avg/= 3.00000; color.xyz= vec3(avg); color.w= 1.00000; return (color2+ color); } void main() { (continues on next page)

13.2. pixel shader 275 MBM Documentation, Release 3.1.f

(continued from previous page) vec4 color; color= texture2D(sample0, vTexCoord); if(color.a == 0.0) discard; else gl_FragColor= xlat_main(vTexCoord); }

13.2.23 glass tile

name glass tile.ps variable bevelWidth min 1 max 10 default 10 variable offset min 0 max 3 default 3 variable groutColor min 0, 0, 0, 0 max 1, 1, 1, 1 default 0, 0, 0, 0 variable tiles min 0 max 20 default 5 shader code precision mediump float; uniform float bevelWidth; uniform vec4 groutColor; uniform float offset; uniform sampler2D sample0; uniform float tiles; varying vec2 vTexCoord; void main() { float a= texture2D(sample0, vTexCoord).a; if(a == 0.0&& groutColor.a == 0.0) discard; else { (continues on next page)

276 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) vec2 newUV1; vec4 c1; newUV1.xy= (vTexCoord.xy+ (tan((((tiles * 2.50000) * vTexCoord.xy)+ ˓→offset)) * (bevelWidth/ 100.000))); c1= texture2D(sample0, newUV1); if(c1.a == 0.0&& groutColor.a == 0.0) discard; else { if (((((newUV1.x< 0.000000) || (newUV1.x> 1.00000)) || (newUV1.y< 0.

˓→000000)) || (newUV1.y> 1.00000))) { c1= groutColor; } if(c1.a == 0.0&& groutColor.a == 0.0) discard; else { gl_FragColor= c1; } } } }

13.2.24 invert color

name invert color.ps shader code precision mediump float; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv) { vec4 color; vec4 invertedColor;

color= texture2D(sample0, uv); invertedColor= vec4((color.w- color.xyz), color.w); return invertedColor; } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.2.25 luminance

name luminance.ps variable color min 0, 0, 0, 0

13.2. pixel shader 277 MBM Documentation, Release 3.1.f

max 1, 1, 1, 1 default 0.5, 0.5, 0.5, 0.5 shader code precision mediump float; uniform vec4 color; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main( in vec2 uv ) { vec4 texColor; float luminance; vec4 xlat_var_output; vec4 white= vec4( 1.00000, 1.00000, 1.00000, 1.00000);

texColor= texture2D( sample0, uv); luminance= dot( texColor, vec4( 0.212600, 0.715200, 0.0722000, 0.000000)); xlat_var_output= vec4( 0.000000); if ( (luminance< 0.500000) ){ xlat_var_output=((2.00000 * texColor) * color); } else{ xlat_var_output= (white-((2.00000 * (white- texColor)) * (white- ˓→color))); } xlat_var_output.w= (texColor.w * color.w ); return xlat_var_output; } void main() { gl_FragColor= xlat_main( vTexCoord); }

13.2.26 magnifying glass

name magnifying glass.ps variable center min 0, 0 max 1, 1 default 0.5, 0.5 variable magnification min 0 max 5 default 2 variable aspectRatio min 0.5 max 2

278 Chapter 13. Table shader MBM Documentation, Release 3.1.f

default 0.94 variable radius min 0 max 1 default 0.25 shader code precision mediump float; uniform float aspectRatio; uniform vec2 center; uniform float magnification; uniform float radius; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv) { vec2 centerToPixel; float dist; vec2 samplePoint;

centerToPixel= (uv- center); dist= length((centerToPixel/ vec2(1.00000, aspectRatio))); samplePoint= uv; if ((dist< radius)) { samplePoint= (center+ (centerToPixel/ magnification)); } return texture2D(sample0, samplePoint); } void main() { vec4 color; color= texture2D(sample0, vTexCoord); if (color.a == 0.0) discard; else gl_FragColor= xlat_main(vTexCoord); }

13.2.27 multi textura

name multi textura.ps variable gamma min 0 max 100 default 2 shader code

13.2. pixel shader 279 MBM Documentation, Release 3.1.f

precision mediump float; varying vec2 vTexCoord; uniform float gamma; uniform sampler2D sample0; uniform sampler2D sample1; vec4 xlat_lib_saturate( vec4 x) { return clamp( x, 0.0, 1.0); } void main() { vec4 color1; vec4 color2; vec4 blendColor; color1= texture2D( sample0, vTexCoord.xy ); color2= texture2D( sample1, vTexCoord.xy ); blendColor= ((color1 * color2) * gamma); blendColor= xlat_lib_saturate( blendColor ); gl_FragColor= blendColor; }

13.2.28 night vision blur

name night vision blur.ps variable contrast min 1e-05 max 10 default 6.8 variable brightness min 1e-05 max 100 default 10 shader code precision mediump float; uniform float brightness; uniform float contrast; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main(in vec4 pixelColor) { vec4 color0; color0= pixelColor; pixelColor= vec4((((0.299000 * pixelColor.x)+(0.587000 * pixelColor.y))+(0. ˓→184000 * pixelColor.z))); (continues on next page)

280 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) pixelColor.xyz/= pixelColor.w; pixelColor.xyz= (((pixelColor.xyz- 0.500000) * max(contrast, 0.000000))+ 0. ˓→500000); pixelColor.y+= brightness; pixelColor.xyz *= pixelColor.w; return ((pixelColor * color0) * 0.250000); } void main() { vec4 color; color= texture2D(sample0, vTexCoord); if(color.a == 0.0) discard; else gl_FragColor= xlat_main(color); }

13.2.29 night vision

name night vision.ps variable fInverseViewportHeight min 1e-05 max 1 default 1 variable fInverseViewportWidth min 1e-05 max 1 default 1 shader code precision mediump float; uniform float fInverseViewportHeight; uniform float fInverseViewportWidth; uniform sampler2D sample0; varying vec2 vTexCoord; void main() { vec4 col; vec4 color0;

col= texture2D(sample0, vTexCoord);

color0= col; col+=(0.0625000 * texture2D(sample0, (vTexCoord+ vec2((-1.00000 * ˓→fInverseViewportWidth), (-1.00000 * fInverseViewportHeight))))); col+=(0.0625000 * texture2D(sample0, (vTexCoord+ vec2((-1.00000 * ˓→fInverseViewportWidth), (1.00000 * fInverseViewportHeight))))); (continues on next page)

13.2. pixel shader 281 MBM Documentation, Release 3.1.f

(continued from previous page) col+=(0.0625000 * texture2D(sample0, (vTexCoord+ vec2((1.00000 * ˓→fInverseViewportWidth), (-1.00000 * fInverseViewportHeight))))); col+=(0.0625000 * texture2D(sample0, (vTexCoord+ vec2((1.00000 * ˓→fInverseViewportWidth), (1.00000 * fInverseViewportHeight))))); col+=(0.125000 * texture2D(sample0, (vTexCoord+ vec2((-1.00000 * ˓→fInverseViewportWidth), (0.000000 * fInverseViewportHeight))))); col+=(0.125000 * texture2D(sample0, (vTexCoord+ vec2((1.00000 * ˓→fInverseViewportWidth), (0.000000 * fInverseViewportHeight))))); col+=(0.125000 * texture2D(sample0, (vTexCoord+ vec2((0.000000 * ˓→fInverseViewportWidth), (-1.00000 * fInverseViewportHeight))))); col+=(0.125000 * texture2D(sample0, (vTexCoord+ vec2((0.000000 * ˓→fInverseViewportWidth), (1.00000 * fInverseViewportHeight))))); col+=(0.250000 * texture2D(sample0, (vTexCoord+ vec2((0.000000 * ˓→fInverseViewportWidth), (0.000000 * fInverseViewportHeight))))); col= vec4((((0.299000 * col.x)+(0.587000 * col.y))+(0.184000 * col.z))); col= vec4(col.xxx, col.w); col.y *= 3.00000; col= ((col * color0) * 0.500000); gl_FragColor= col; }

13.2.30 old movie

name old movie.ps variable noiseAmount min 1e-05 max 1 default 0.0001 variable scratchAmount min 1e-05 max 0.1 default 0.044 variable frame min 0 max 2 default 1 shader code precision mediump float; uniform float frame; uniform float noiseAmount; uniform sampler2D sample0; uniform float scratchAmount; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv,in vec4 color) { (continues on next page)

282 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) float ScratchAmountInv; vec2 sc; float scratch; vec2 rCoord; vec3 rand; float gray; vec2 dist;

ScratchAmountInv=(1.00000/ scratchAmount); sc= (frame * vec2(0.00100000, 0.400000)); sc.x= fract((uv.x+ sc.x)); scratch= sc.x; scratch=((2.00000 * scratch) * ScratchAmountInv); scratch=(1.00000- abs((1.00000- scratch))); scratch= max(0.000000, scratch); color.xyz+= vec3(scratch); rCoord= (uv * 0.330000); rand= vec3(texture2D(sample0, rCoord)); if ((noiseAmount> rand.x)) { color.xyz= vec3((0.100000+ (rand.z * 0.400000))); } gray= dot(color, vec4(0.300000, 0.590000, 0.110000, 0.000000)); color= vec4((gray * vec3(0.900000, 0.800000, 0.600000)), 1.00000); dist=(0.500000- uv); color.xyz *=((0.400000- dot(dist, dist)) * 2.80000); return color; } void main() { vec4 color; color= texture2D(sample0, vTexCoord); if(color.a == 0.0) discard; else gl_FragColor= xlat_main(vTexCoord,color); }

13.2.31 out of bounds

name out of bounds.ps variable color min 0, 0, 0 max 1, 1, 1 default 1, 0, 0 shader code precision mediump float; uniform sampler2D sample0; (continues on next page)

13.2. pixel shader 283 MBM Documentation, Release 3.1.f

(continued from previous page) uniform vec3 color; varying vec2 vTexCoord; void main() { vec4 colorRet= texture2D( sample0, vTexCoord.xy ); if(vTexCoord.x< 0.0 || vTexCoord.x> 1.0 || vTexCoord.y< 0.0 || vTexCoord.y> 1.

˓→0) colorRet.rgb *= color.rgb; gl_FragColor= colorRet; }

13.2.32 pinch mouse

name pinch mouse.ps variable strength min 0 max 2 default 1 variable center min 0, 0 max 794, 678 default 0.5, 0.5 variable aspectRatio min 0.5 max 2 default 1 variable radius min 0 max 1 default 0.25 shader code precision mediump float; uniform float aspectRatio; uniform vec2 center; uniform float radius; uniform sampler2D sample0; uniform float strength; varying vec2 vTexCoord; float xlat_lib_saturate(float x) { return clamp(x, 0.0, 1.0); } (continues on next page)

284 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) vec2 xlat_lib_saturate(vec2 x) { return clamp(x, 0.0, 1.0); } vec3 xlat_lib_saturate(vec3 x) { return clamp(x, 0.0, 1.0); } vec4 xlat_lib_saturate(vec4 x) { return clamp(x, 0.0, 1.0); } mat2 xlat_lib_saturate(mat2 m) { return mat2(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0)); } mat3 xlat_lib_saturate(mat3 m) { return mat3(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0)); } mat4 xlat_lib_saturate(mat4 m) { return mat4(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0),

˓→clamp(m[3], 0.0, 1.0)); } vec4 xlat_main(in vec2 uv) { vec2 newCenter; vec2 dir; vec2 scaledDir; float dist; float range; vec2 samplePoint;

newCenter.x=(1.00000- (center.x/ 794.000)); newCenter.y=(1.00000- (center.y/ 678.000)); dir= (newCenter- uv); scaledDir= dir; scaledDir.y/= aspectRatio; dist= length(scaledDir); range= xlat_lib_saturate((1.00000- (dist/ (abs(((-sin((radius * 8.00000))) * ˓→radius))+ 1.00000e-008)))); samplePoint= (uv+ ((dir * range) * strength)); return texture2D(sample0, samplePoint); } void main() { gl_FragColor= xlat_main(vTexCoord); (continues on next page)

13.2. pixel shader 285 MBM Documentation, Release 3.1.f

(continued from previous page) }

13.2.33 pinch

name pinch.ps variable strength min 0 max 2 default 1 variable center min 0, 0 max 1, 1 default 0.5, 0.5 variable aspectRatio min 0.5 max 2 default 1 variable radius min 0 max 1 default 0.25 shader code precision mediump float; uniform float aspectRatio; uniform vec2 center; uniform float radius; uniform sampler2D sample0; uniform float strength; varying vec2 vTexCoord; float xlat_lib_saturate(float x) { return clamp(x, 0.0, 1.0); } vec2 xlat_lib_saturate(vec2 x) { return clamp(x, 0.0, 1.0); } vec3 xlat_lib_saturate(vec3 x) { return clamp(x, 0.0, 1.0); (continues on next page)

286 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) } vec4 xlat_lib_saturate(vec4 x) { return clamp(x, 0.0, 1.0); } mat2 xlat_lib_saturate(mat2 m) { return mat2(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0)); } mat3 xlat_lib_saturate(mat3 m) { return mat3(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0)); } mat4 xlat_lib_saturate(mat4 m) { return mat4(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0),

˓→clamp(m[3], 0.0, 1.0)); } vec4 xlat_main(in vec2 uv) { vec2 dir; vec2 scaledDir; float dist; float range; vec2 samplePoint;

dir= (center- uv); scaledDir= dir; scaledDir.y/= aspectRatio; dist= length(scaledDir); range= xlat_lib_saturate((1.00000- (dist/ (abs(((-sin((radius * 8.00000))) * ˓→radius))+ 1.00000e-008)))); samplePoint= (uv+ ((dir * range) * strength)); return texture2D(sample0, samplePoint); } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.2.34 poisson

name poisson.ps variable poisson min 1 max 10

13.2. pixel shader 287 MBM Documentation, Release 3.1.f

default 3 variable inputSize min 1, 1 max 300, 300 default 100, 100 shader code precision mediump float; uniform vec2 inputSize; uniform float poisson; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv) { vec4 cOut; vec2 coord;

cOut= texture2D(sample0, uv); coord= (uv.xy+(( vec2(-0.326212,-0.405810)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(-0.840144,-0.07358)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(-0.695914, 0.457137)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(-0.203345, 0.620716)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(0.96234,-0.194983)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(0.473434,-0.480026)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(0.519456, 0.767022)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(0.185461,-0.893124)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(0.507431, 0.064425)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(0.89642, 0.412458)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(-0.32194,-0.932615)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

coord= (uv.xy+(( vec2(-0.791559,-0.59771)/ inputSize) * poisson)); cOut+= texture2D(sample0, coord);

(continues on next page)

288 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) return (cOut/ 13.0000); } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.2.35 ripple

name ripple.ps variable center min 0, 0 max 1, 1 default 0.5, 0.5 variable aspectRatio min 0.5 max 2 default 1.34 variable phase min -20 max 20 default 0 variable frequency min 0 max 100 default 70 variable amplitude min 0 max 1 default 0.1 shader code precision mediump float; uniform float amplitude; uniform float aspectRatio; uniform vec2 center; uniform float frequency; uniform float phase; uniform sampler2D sample0; varying vec2 vTexCoord; (continues on next page)

13.2. pixel shader 289 MBM Documentation, Release 3.1.f

(continued from previous page) void xlat_lib_sincos(float x, out float s, out float c) { s= sin(x); c= cos(x); } void xlat_lib_sincos(vec2 x, out vec2 s, out vec2 c) { s= sin(x); c= cos(x); } void xlat_lib_sincos(vec3 x, out vec3 s, out vec3 c) { s= sin(x); c= cos(x); } void xlat_lib_sincos(vec4 x, out vec4 s, out vec4 c) { s= sin(x); c= cos(x); } void xlat_lib_sincos(mat2 x, out mat2 s, out mat2 c) { s= mat2(sin(x[0]), sin(x[1])); c= mat2(cos(x[0]), cos(x[1])); } void xlat_lib_sincos(mat3 x, out mat3 s, out mat3 c) { s= mat3(sin(x[0]), sin(x[1]), sin(x[2])); c= mat3(cos(x[0]), cos(x[1]), cos(x[2])); } void xlat_lib_sincos(mat4 x, out mat4 s, out mat4 c) { s= mat4(sin(x[0]), sin(x[1]), sin(x[2]), sin(x[3])); c= mat4(cos(x[0]), cos(x[1]), cos(x[2]), cos(x[3])); } float xlat_lib_saturate(float x) { return clamp(x, 0.0, 1.0); } vec2 xlat_lib_saturate(vec2 x) { return clamp(x, 0.0, 1.0); } vec3 xlat_lib_saturate(vec3 x) { return clamp(x, 0.0, 1.0); } (continues on next page)

290 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) vec4 xlat_lib_saturate(vec4 x) { return clamp(x, 0.0, 1.0); } mat2 xlat_lib_saturate(mat2 m) { return mat2(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0)); } mat3 xlat_lib_saturate(mat3 m) { return mat3(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0)); } mat4 xlat_lib_saturate(mat4 m) { return mat4(clamp(m[0], 0.0, 1.0), clamp(m[1], 0.0, 1.0), clamp(m[2], 0.0, 1.0),

˓→clamp(m[3], 0.0, 1.0)); } vec4 xlat_main(in vec2 uv) { vec2 dir; float dist; vec2 wave; float falloff; vec2 samplePoint; vec4 color; float lighting;

dir= (uv- center); dir.y/= aspectRatio; dist= length(dir); dir/= dist; dir.y *= aspectRatio; xlat_lib_sincos(((frequency * dist)+ phase), wave.x, wave.y); falloff= xlat_lib_saturate((1.00000- dist)); falloff *= falloff; dist+= ((amplitude * wave.x) * falloff); samplePoint= (center+ (dist * dir)); color= texture2D(sample0, samplePoint); lighting=(1.00000- ((amplitude * 0.200000) * (1.00000- xlat_lib_saturate((wave. ˓→y * falloff))))); color.xyz *= lighting; return color; } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.2. pixel shader 291 MBM Documentation, Release 3.1.f

13.2.36 saturate

name saturate.ps variable color min 0, 0, 0 max 1, 1, 1 default 1, 1, 1 shader code precision mediump float; uniform vec3 color; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main( in vec2 uv ) { vec4 c1; c1= texture2D( sample0, uv.xy ); c1.xyz *= color.xyz ; return c1; } void main() { gl_FragColor= xlat_main( vTexCoord); }

13.2.37 sharpen

name sharpen.ps variable inputSize min 1, 1 max 1000, 1000 default 800, 600 variable amount min 0 max 2 default 1 shader code precision mediump float; uniform float amount; uniform vec2 inputSize; uniform sampler2D sample0; varying vec2 vTexCoord;

(continues on next page)

292 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) void main() { vec2 offset; vec4 color;

offset=(1.00000/ inputSize); color= texture2D(sample0, vTexCoord); color.xyz+= vec3((texture2D(sample0, (vTexCoord- offset)) * amount)); color.xyz-= vec3((texture2D(sample0, (vTexCoord+ offset)) * amount)); gl_FragColor= color; }

13.2.38 sketch

name sketch.ps variable brushSize min 0.0006 max 1 default 0.003 shader code precision mediump float; uniform sampler2D Image; uniform float brushSize; varying vec2 vTexCoord; const vec2 sample1= vec2(0.000000,-1.00000); const vec2 sample2= vec2(-1.00000, 0.000000); const vec2 sample3= vec2(1.00000, 0.000000); const vec2 sample4= vec2(0.000000, 1.00000); vec4 xlat_main(in vec2 texCoord) { vec4 color; vec4 laplace; vec4 complement; float gray; float gray_1;

color= texture2D(Image, texCoord); laplace=(-4.00000 * color);

laplace+= texture2D(Image, (texCoord+ (brushSize * sample1))); laplace.x= float(laplace.xyz); laplace.y= float(laplace.xyz); laplace.z= float(laplace.xyz);

laplace+= texture2D(Image, (texCoord+ (brushSize * sample2))); laplace.x= float(laplace.xyz); laplace.y= float(laplace.xyz); laplace.z= float(laplace.xyz); (continues on next page)

13.2. pixel shader 293 MBM Documentation, Release 3.1.f

(continued from previous page)

laplace+= texture2D(Image, (texCoord+ (brushSize * sample3))); laplace.x= float(laplace.xyz); laplace.y= float(laplace.xyz); laplace.z= float(laplace.xyz);

laplace+= texture2D(Image, (texCoord+ (brushSize * sample2))); laplace.x= float(laplace.xyz); laplace.y= float(laplace.xyz); laplace.z= float(laplace.xyz);

laplace=(1.00000/ laplace); complement.xyz=(1.00000- laplace.xyz); complement.w= color.w; if ((complement.x> 1.00000)) { gray= (((complement.x * 0.300000)+ (complement.y * 0.590000))+ (complement. ˓→z * 0.110000)); complement.x= gray; complement.y= gray; complement.z= gray; return complement; } else { gray_1= (((color.x * 0.300000)+ (color.y * 0.590000))+ (color.z * 0. ˓→110000)); color.x= gray_1; color.y= gray_1; color.z= gray_1; return color; } } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.2.39 smooth magnify

name smooth magnify.ps variable center min 0, 0 max 1, 1 default 0.5, 0.5 variable aspectRatio min 0.5 max 2 default 1.4

294 Chapter 13. Table shader MBM Documentation, Release 3.1.f

variable innerRadius min 0 max 1 default 0.2 variable magnification min 0 max 5 default 2 variable outerRadius min 0 max 1 default 0.4 shader code precision mediump float; uniform float aspectRatio; uniform vec2 center; uniform float innerRadius; uniform float magnification; uniform float outerRadius; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv) { vec2 centerToPixel; float dist; float ratio; vec2 samplePoint;

centerToPixel= (uv- center); dist= length((centerToPixel/ vec2(1.00000, aspectRatio))); ratio= smoothstep(innerRadius, max(innerRadius, outerRadius), dist); samplePoint= mix((center+ (centerToPixel/ magnification)), uv, vec2(ratio)); return texture2D(sample0, samplePoint); } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.2.40 spiral

name spiral.ps variable center min 0, 0

13.2. pixel shader 295 MBM Documentation, Release 3.1.f

max 1, 1 default 0.5, 0.5 variable aspectRatio min 0.5 max 2 default 1.4 variable spiralStrength min 0 max 20 default 10 shader code precision mediump float; uniform float aspectRatio; uniform vec2 center; uniform sampler2D sample0; uniform float spiralStrength; varying vec2 vTexCoord; void xlat_lib_sincos(float x, out float s, out float c) { s= sin(x); c= cos(x); } void xlat_lib_sincos(vec2 x, out vec2 s, out vec2 c) { s= sin(x); c= cos(x); } void xlat_lib_sincos(vec3 x, out vec3 s, out vec3 c) { s= sin(x); c= cos(x); } void xlat_lib_sincos(vec4 x, out vec4 s, out vec4 c) { s= sin(x); c= cos(x); } void xlat_lib_sincos(mat2 x, out mat2 s, out mat2 c) { s= mat2(sin(x[0]), sin(x[1])); c= mat2(cos(x[0]), cos(x[1])); } void xlat_lib_sincos(mat3 x, out mat3 s, out mat3 c) { s= mat3(sin(x[0]), sin(x[1]), sin(x[2])); (continues on next page)

296 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) c= mat3(cos(x[0]), cos(x[1]), cos(x[2])); } void xlat_lib_sincos(mat4 x, out mat4 s, out mat4 c) { s= mat4(sin(x[0]), sin(x[1]), sin(x[2]), sin(x[3])); c= mat4(cos(x[0]), cos(x[1]), cos(x[2]), cos(x[3])); } vec4 xlat_main(in vec2 uv) { vec2 dir; float dist; float angle; float newAngle; vec2 newDir; vec2 samplePoint; bool isValid;

dir= (uv- center); dir.y/= aspectRatio; dist= length(dir); angle= atan(dir.y, dir.x); newAngle= (angle+ (spiralStrength * dist)); xlat_lib_sincos(newAngle, newDir.y, newDir.x); newDir.y *= aspectRatio; samplePoint= (center+ (newDir * dist)); if ((all(greaterThanEqual(samplePoint, vec2(0.000000)))&&

˓→all(lessThanEqual(samplePoint, vec2(1.00000))))) { isValid= true; } else { isValid= false; } return (isValid)? (texture2D(sample0, samplePoint)):( vec4(0.000000, 0.000000, 0.

˓→000000, 0.000000)); } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.2.41 texture map

name texture map.ps variable horizontalSize min 0 max 5 default 1

13.2. pixel shader 297 MBM Documentation, Release 3.1.f

variable verticalOffset min 0 max 1 default 0 variable horizontalOffset min 0 max 1 default 0 variable strength min 0 max 1 default 0.3 variable verticalSize min 0 max 5 default 1 shader code precision mediump float; uniform float horizontalOffset; uniform float horizontalSize; uniform sampler2D sample0; uniform sampler2D sample1; uniform float strength; uniform float verticalOffset; uniform float verticalSize; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv) { float horzOffset; float vOffset; vec2 offset; vec4 c1;

horzOffset= fract(((uv.x/ horizontalSize)+ min(1.00000, horizontalOffset))); vOffset= fract(((uv.y/ verticalSize)+ min(1.00000, verticalOffset))); offset= ((texture2D(sample1, vec2(horzOffset, vOffset)).xy * strength)- ˓→(strength/ 8.00000)); c1= texture2D(sample0, fract((uv+ offset))); return c1; } void main() { vec4 color; color= texture2D(sample0, vTexCoord); (continues on next page)

298 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) gl_FragColor= xlat_main(vTexCoord); }

13.2.42 tiled map

name tiled map.ps variable alpha min 0 max 1 default 0 variable tolerance min 0 max 1 default 0.3 variable granThen min 0 max 1 default 1 variable colorSrc min 0, 0, 0 max 1, 1, 1 default 1, 0, 1 variable enableColorKeying min 0 max 1 default 0 shader code precision mediump float; uniform float enableColorKeying; uniform float granThen; uniform float alpha; uniform float tolerance; uniform vec3 colorSrc; uniform sampler2D sample0; varying vec2 vTexCoord; void main() { (continues on next page)

13.2. pixel shader 299 MBM Documentation, Release 3.1.f

(continued from previous page) vec4 color= texture2D(sample0, vTexCoord); color.a-= alpha; if (color.a <= 0.0) { discard; } else if (enableColorKeying> 0.5) { if (granThen> 0.5) { if (all(lessThan(abs((color.xyz- colorSrc.xyz)), vec3(tolerance)))) { discard; } else { gl_FragColor= color; } } else { if (all(greaterThan(abs((color.xyz- colorSrc.xyz)), vec3(tolerance)))) { discard; } else { gl_FragColor= color; } } } else { gl_FragColor= color; } }

13.2.43 tone mapping

name tone mapping.ps variable fogColor min 0, 0, 0, 0 max 1, 1, 1, 1 default 1, 1, 1, 1 variable gamma min 0.5 max 2 default 0.63 variable vignetteCenter

300 Chapter 13. Table shader MBM Documentation, Release 3.1.f

min 0, 0 max 1, 1 default 0.5, 0.5 variable blueShift min 0 max 10 default 10 variable vignetteAmount min -1 max 1 default 0 variable defog min 0 max 1 default 0.4 variable exposure min -1 max 1 default -0.2 variable vignetteRadius min 0 max 1 default 0.5 shader code precision mediump float; uniform float blueShift; uniform float defog; uniform float exposure; uniform vec4 fogColor; uniform float gamma; uniform sampler2D sample0; uniform float vignetteAmount; uniform vec2 vignetteCenter; uniform float vignetteRadius; varying vec2 vTexCoord; vec4 xlat_main(in vec2 uv, in vec4 c) { vec2 tc; float v; vec3 d; (continues on next page)

13.2. pixel shader 301 MBM Documentation, Release 3.1.f

(continued from previous page)

c.xyz= vec3(max(0.000000, float((c.xyz- (defog * fogColor.xyz))))); c.xyz *= pow(2.00000, exposure); c.xyz= pow(c.xyz, vec3(gamma)); tc= (uv- vignetteCenter); v= (length(tc)/ vignetteRadius); c.xyz+= (pow(v, 4.00000) * vignetteAmount); d= (c.xyz * vec3(1.05000, 0.970000, 1.27000)); c.xyz= mix(c.xyz, d, vec3(blueShift)); return c; } void main() { vec4 color; color= texture2D(sample0, vTexCoord); gl_FragColor= xlat_main(vTexCoord,color); }

13.2.44 toon

name toon.ps variable levels min 0 max 15 default 5 shader code precision mediump float; uniform float levels; uniform sampler2D sample0; varying vec2 vTexCoord; vec4 xlat_main(in vec4 color) { int result;

color.xyz/= color.w; result= int(floor(levels)); color.xyz *= float(result); color.xyz= floor(color.xyz); color.xyz/= float(result); color.xyz *= color.w; return color; } void main() { vec4 color; color= texture2D(sample0, vTexCoord); if(color.a == 0.0) (continues on next page)

302 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) discard; else gl_FragColor= xlat_main(color); }

13.2.45 transparent

name transparent.ps variable alpha min 0 max 1 default 0.7 shader code precision mediump float; uniform float alpha; uniform sampler2D sample0; varying vec2 vTexCoord; void main() { vec4 color; color= texture2D( sample0, vTexCoord); color.a-= alpha; gl_FragColor= color; }

13.2.46 wave

name wave.ps variable effectTime min 0 max 10 default 0 variable sizeWave min -50 max 100 default 10 shader code precision mediump float; uniform sampler2D sample0; uniform float effectTime; uniform float sizeWave; varying vec2 vTexCoord; (continues on next page)

13.2. pixel shader 303 MBM Documentation, Release 3.1.f

(continued from previous page) float dist(in float a, in float b, in float c, in float d) { return sqrt((((a- c) * (a- c))+ ((b- d) * (b- d)))); } vec4 xlat_main(in vec2 uv) { vec4 Color; float f;

Color= vec4(0.000000); f= ((sin((dist((uv.x+ effectTime), uv.y, 0.128000, 0.128000) * sizeWave))+ ˓→sin((dist(uv.x, uv.y, 0.640000, 0.640000) * sizeWave)))+ sin((dist(uv.x, (uv.y+ ˓→(effectTime/ 7.00000)), 0.192000, 0.640000) * sizeWave))); uv.xy= (uv.xy+ (f/ sizeWave)); Color= texture2D(sample0, uv.xy); return Color; } void main() { gl_FragColor= xlat_main(vTexCoord); }

13.3 vertex shader

Bellow all embedded vertex shader available for the engine:

13.3.1 scale

name scale.vs variable scale min 0, 0, 0 max 10, 10, 10 default 1, 1, 1 shader code precision highp float; uniform mat4 mvpMatrix; uniform vec3 scale; attribute vec4 aPosition; attribute vec4 aNormal; attribute vec2 aTextCoord; varying vec2 vTexCoord; struct VS_OUTPUT { vec4 pos; vec2 uv; (continues on next page)

304 Chapter 13. Table shader MBM Documentation, Release 3.1.f

(continued from previous page) };

VS_OUTPUT xlat_main(in vec4 pos, in vec4 nor, in vec2 uv) { VS_OUTPUT ret;

pos.x *= scale.x; pos.y *= scale.y; pos.z *= scale.z; ret.pos= (mvpMatrix * pos); ret.uv= uv; return ret; } void main() { VS_OUTPUT ret; ret= xlat_main(aPosition, aNormal, aTextCoord); vTexCoord= ret.uv; gl_Position= vec4(ret.pos); }

13.3.2 simple texture

name simple texture.vs shader code precision highp float; uniform mat4 mvpMatrix; attribute vec4 aPosition; attribute vec4 aNormal; attribute vec2 aTextCoord; varying vec4 vPosition; varying vec4 vNormal; varying vec2 vTexCoord; void main() { vPosition= aPosition; vNormal= aNormal; vTexCoord= aTextCoord; gl_Position= (mvpMatrix * aPosition); }

Table of Contents

• Table shape – shape methods

* shape new * shape create

13.3. vertex shader 305 MBM Documentation, Release 3.1.f

* shape createIndexed * shape createDynamicIndexed * setColor * onRender

306 Chapter 13. Table shader CHAPTER 14

Table shape

A table shape inherit from renderizable and implement all methods as usual. Also each animation has a shader table by default which can be accessed by getShader method. The main functionality of shape is to easily create a shape of circle, triangle or rectangle. Also is possible to create a free shape using the methods create and createIndexed. The table shape is also capable to render in real time using the method onRender. To do that the frame must be created as dynamic mode option.

Note: The shape is not capable to store runtime information. On lost device, the shape will lost its information, so, it must be reloaded on method onRestore. Also is lost its texture and callback for onEndAnim and onEndFx.

14.1 shape methods

14.1.1 shape new new(string * world, number * x, number * y, number * z) Create a new instance of a shape passing the world desired (detail) and position. Parameters • string – world can be 2ds, 2dw or 3d. • number – x position (optional). • number – y position (optional). • number – z position (optional). Returns shape table.

307 MBM Documentation, Release 3.1.f

Example: tShape= shape:new('2dw')

14.1.2 shape create create(string type, number width, number * height, number * triangles, boolean * dynamic_buffer, string * nick_name) Create a shape in runtime choosing among the pre defined option available. The onRender callback can be used if dynamic_buffer is true. Parameters • string – type pre defined. circle, rectangle or triangle. • number – width of shape. • number – height of shape. • number – triangles - default values circle: 18 - rectangle: 2, triangle: 1. • boolean – dynamic buffer option to render in runtime the shape using onRender method (optional). • string – nick name of shape (optional). Returns string - nick_name Example: tShapeCircle= shape:new('2dw',-100) tShapeRectangle= shape:new('2dw',0) tShapeTriangle= shape:new('2dw', 100) local nickNameCircle= tShapeCircle:create('circle',100,100) local nickNameRectangle= tShapeRectangle:create('rectangle',100,100) local nickNameTriangle= tShapeTriangle:create('triangle',100,100) if nickNameCircle then print('Circle'.. nickNameCircle..' successfully created!') else print('Failed to create a circle') end if nickNameRectangle then print('Rectangle'.. nickNameRectangle..' successfully created!') else print('Failed to create a rectangle') end if nickNameTriangle then print('Triangle'.. nickNameTriangle..' successfully created!') else print('Failed to create a triangle') end

As is known, a shape is based on triangles and, to build a circle is not different. If is necessary to have a huge detail on circle, is recommended to create it using shader.

308 Chapter 14. Table shape MBM Documentation, Release 3.1.f

Figure 14.1: Three shapes created as result.

Example creating circle with different number of triangles tShapeCircle_4= shape:new('2dw',-200) tShapeCircle_8= shape:new('2dw',0) tShapeCircle_18= shape:new('2dw', 200) local nickNameCircle_4= tShapeCircle_4:create ('circle',200,200,4) local nickNameCircle_8= tShapeCircle_8:create ('circle',200,200,8) local nickNameCircle_18= tShapeCircle_18:create('circle',200,200, 18) if nickNameCircle_4 then print('Circle'.. nickNameCircle_4..' with 4 triangle successfully created!') else print('Failed to create a circle') end if nickNameCircle_8 then print('Circle'.. nickNameCircle_8..' with 8 triangle successfully created!') else print('Failed to create a circle') end if nickNameCircle_18 then print('Circle'.. nickNameCircle_18..' with 18 triangle successfully created!') else print('Failed to create a circle') end create(table vertex, table* uv, table* normal, string * nick_name, string * mode_draw, string * mode_cull_face, string * mode_front_face_direction) Create a shape in runtime supplying native coordinates. Parameters • table – vertex coordinates x,y or x,y,z. • table – uv coordinates u,v (optional). • table – normal coordinates x,y,z (optional). • string – nick name of shape (optional). • string – mode draw of shape (optional). see mode draw.

14.1. shape methods 309 MBM Documentation, Release 3.1.f

Figure 14.2: Three circle created as result with different number of triangles. Although the first seems to be a square, it is a circle but with a minimum of triangles needed.

• string – mode cull face of shape (optional). see cull face. • string – mode front face direction of shape (optional). see front face direction. Returns string - nick_name Example:

-- Example: 2d tShape= shape:new('2dw')

--lets´ draw a square of 400x400 -- First Triangle Second Triangle local tVertex={-200,-200,-200,200, 200,-200, 200,-200,-200,200, 200,200}

˓→-- (x,y) coordinates local tUv={0,1,0,0,1,1,1,1,0,0,1,0} local tNormal= nil --let the normal be calculated automatically if tShape:create(tVertex,tUv,tNormal,'my-shape-nick-name') then print('Shape successfully created!') else print('Failed to create a shape') end

Figure 14.3: An square shape without texture as result

-- Example: 3d tShape= shape:new('3d',0,0,500)

(continues on next page)

310 Chapter 14. Table shape MBM Documentation, Release 3.1.f

(continued from previous page) --lets´ draw a square of 400x400x0 -- First Triangle Second Triangle local tVertex={-200,-200,0,-200,200,0, 200,-200,0, 200,-200,0,-200,200,0,

˓→ 200,200,0} -- (x,y) coordinates local tUv={0,1,0,0,1,1,1,1,0,0,1,0} local tNormal= nil --let the normal be calculated automatically if tShape:create(tVertex,tUv,tNormal,'my-shape-nick-name','TRIANGLES','BACK','CW')

˓→then print('Shape successfully created!') else print('Failed to create a shape') end

14.1.3 shape createIndexed createIndexed(table vertex, table index, table* uv, table* normal, string * nick_name, string * mode_draw, string * mode_cull_face, string * mode_front_face_direction) Create a shape in runtime supplying indexed native coordinates. Parameters • table – vertex coordinates x,y or x,y,z. • table – index array referent to vertex (one based). • table – uv coordinates u,v (optional). • table – normal coordinates x,y,z (optional). • string – nick name of shape (optional). • string – mode draw of shape (optional). see mode draw. • string – mode cull face of shape (optional). see cull face. • string – mode front face direction of shape (optional). see front face direction. Returns string - nick_name Example: 2d tShape= shape:new('2dw') --lets´ draw a square of 400x400 -- 1 2 3 4 local tVertex={-200,-200,-200,200, 200,-200, 200,200} -- (x,y) coordinates local tUv={0,1,0,0,1,1,1,0} local tIndex={1,2,3,3,2,4} -- one based local tNormal= nil --let the normal be calculated automatically if tShape:createIndexed(tVertex,tIndex,tUv,tNormal,'my-shape-nick-name','TRIANGLES',

˓→'BACK','CW') then print('Shape successfully created!') else print('Failed to create a shape') end

14.1. shape methods 311 MBM Documentation, Release 3.1.f

Figure 14.4: Rendering using triangle list, Clockwise and CullFace mode back (default of the engine).

312 Chapter 14. Table shape MBM Documentation, Release 3.1.f

14.1.4 shape createDynamicIndexed createDynamicIndexed(table vertex, table index, table* uv, table* normal, string * nick_name, string * mode_draw, string * mode_cull_face, string * mode_front_face_direction) Create a dynamic shape in runtime supplying indexed native coordinates. The onRender callback can be used after creating with this method. Parameters • table – vertex coordinates x,y or x,y,z. • table – index array referent to vertex (one based). • table – uv coordinates u,v (optional). • table – normal coordinates x,y,z (optional). • string – nick name of shape (optional). • string – mode draw of shape (optional). see mode draw. • string – mode cull face of shape (optional). see cull face. • string – mode front face direction of shape (optional). see front face direction. Returns string - nick_name Example: 2d tShape= shape:new('2dw') --lets´ draw a square of 400x400 -- 1 2 3 4 local tVertex={-200,-200,-200,200, 200,-200, 200,200} -- (x,y) coordinates local tUv={0,1,0,0,1,1,1,0} local tIndex={1,2,3,3,2,4} -- one based local tNormal= nil --let the normal be calculated automatically if tShape:createDynamicIndexed(tVertex,tIndex,tUv,tNormal,'my-shape-nick-name',

˓→'TRIANGLES','BACK','CW') then print('Shape successfully created!') else print('Failed to create a shape') end

14.1.5 setColor setColor(number red, number green, number blue, number * alpha) Set a solid color as texture. Parameters • number – red color. Values between 0.0 and 1.0 • number – green color. Values between 0.0 and 1.0 • number – blue color. Values between 0.0 and 1.0 • number – alpha color. Values between 0.0 and 1.0 Returns boolean - successfully applied.

14.1. shape methods 313 MBM Documentation, Release 3.1.f

Example: tShape= shape:new('2dw') tShape:create('RECTANGLE',100,100) local r,g,b, a= 1.0, 0.0, 0.0, 1.0 local ret= tShape:setColor(r,g,b,a)

Figure 14.5: Setting red color for the shape

14.1.6 onRender onRender(tShape, vertex, normal, uv, index_read_only) Shape is capable to render in run time if created with the option dynamic mode as mentioned at shape:create . The data from callback are organized in x, y, z for vertex, nx, ny, nz for normal and u, v for texture coordinates. Also each table has a property name to identify when return from render callback. The first argument is the shape itself following from vertex table, normal table, uv table and index_buffer. The index buffer is read only and one based. Do not need to return it.

Note: Passing nil to method onRender the callback is cancelled.

Parameters • table – shape instance of shape. • table – [x, y, x] vertex table. • table – [nx, ny, nz] normal table. • table – [u, v] texture coordinates. • table – [] array index buffer read only. (one based) Returns table vertex, table normal, table uv - if nil is returned the callback is cancelled. Not all arguments are necessary, just the one edited.

314 Chapter 14. Table shape MBM Documentation, Release 3.1.f

Example how to access all members from callback: mbm.setColor(0.7,0.7,0.7) --set background color to gray local numberTriangle=1 local isDynamic= true tShape= shape:new('2dw') nickName= tShape:create('Triangle',1000,1000,numberTriangle,isDynamic) print('Shape Nick Name:'.. nickName) function onRender(tShape,vertex,normal,uv,index_read_only)

print("------") print(" table (".. vertex.name..')') for i=1,#vertex do print('x:'.. vertex[i].x..' y:'.. vertex[i].y..' z:'.. vertex[i].z) end

print(" table (".. normal.name..')') for i=1,#normal do print('nx:'.. normal[i].nx..' ny:'.. normal[i].ny..' nz:'.. normal[i].nz) end

print(" table (".. uv.name..')') for i=1,#uv do print('u:'.. uv[i].u..' v:'.. uv[i].v ) end

print("------")

-- if does not return or return nil the callback is cancelled return vertex,normal,uv --is possible to choose what return because of the name in the table which

˓→identify it -- example: -- return uv, vertex -- -- if return nil or does not return the callback is cancelled -- example -- return nil end

--set the callback tShape:onRender(onRender)

Warning: If return nil or does not return, the callback is cancelled for onRender.

Table of Contents

• Table sprite – sprite methods

* sprite new

14.1. shape methods 315 MBM Documentation, Release 3.1.f

Figure 14.6: The output should be like this.

* sprite load – Creating a sprite programmatically

* Sprite to a binary file * Sprite animated to a binary file

316 Chapter 14. Table shape CHAPTER 15

Table sprite

A table sprite inherit from renderizable and implement all methods as usual.. Each animation on sprite has an initial frame and final frame which represent its cycle. Also each animation has a shader table by default which can be accessed by getShader method.

15.1 sprite methods

15.1.1 sprite new new(string * world, number * x, number * y, number * z) Create a new instance of a sprite passing the world desired (detail) and position. Parameters • string – world can be 2ds, 2dw or 3d. • number – x position (optional). • number – y position (optional). • number – z position (optional). Returns sprite table. Example: tSpt= sprite:new('2dw') --note that sprite inherits from renderizable

15.1.2 sprite load load(string file_name) Load a sprite from file (expected .spt extension). Parameters string – file name from file.

317 MBM Documentation, Release 3.1.f

Example: tSprite= sprite:new('3d') if tSprite:load('mario.spt') then print('Successfully loaded sprite:','mario.spt') else print('Failed to loaded sprite:','mario.spt') end

Note: The load method will search in all known path. You can add a path to search by the method addPath.

15.2 Creating a sprite programmatically

Here an example how to create an sprite programmatically using the engine to do that. It is possible to save any mesh with help of meshDebug. For that it is necessary to prepare the meshDebug based on our renderizable. • First, we have to create coordinates of vertex buffer. • We also need to create index buffer (1 index based) for the vertex. • Then we create a meshDebug which will store all the information. • The UV and normal coordinates are not mandatory. For this example we will not fill it. • Next we create a frame informing the stride (for sprite will be 2) and add a new subset. • One frame can have one or more subsets. Each subset has its own texture. • Next we add the vertex buffer and index buffer. • The vertex buffer can have normal buffer (optional) and texture coordinates (optional). • Next we set the sprite type (others types are mesh, particle, font, . . . ). • Finally we just need to specify the file name to save through the function save.

15.2.1 Sprite to a binary file

For the first example we will use the following texture: download. Follow the first example how to save a sprite to a binary file:

1 mbm.setColor(1,1,1) --set background color to white

2

3 function createFace()

4

5 local tFace= { {x=-50, y=-50},

6 {x=-50, y= 50},

7 {x= 50, y=-50},

8 {x= 50, y= 50}} (continues on next page)

318 Chapter 15. Table sprite MBM Documentation, Release 3.1.f

Figure 15.1: smile.png

(continued from previous page)

9 local tIndex={1,2,3,3,2,4}

10 local sTextureFileName='HB_smile.png'

11

12 return tFace, tIndex, sTextureFileName

13 end

14

15 function saveMeshToBinaryFile(fileName,tVertex,tIndex,sTexture)

16

17 --meshDebug is used to create dynamically mesh in the engine.

18 --For sprite it has to have at least one frame to be able to generate

˓→the sprite

19 local stride=2 --stride only can be 3 or 2. it means (x,y,z) or

˓→(x,y)

20 local tMesh= meshDebug:new() --new mesh debug to store the

˓→information about our sprite

21 local nFrame= tMesh:addFrame(stride) -- Add one frame with stride

˓→2 (x,y)

22 local indexFrame= nFrame --(meshDebug uses 1 based index)

23 local indexSubset=1 --first subset (1 based index)

24

25

26 --To add vertex, first we need to add a subset

27 local nSubset= tMesh:addSubSet(indexFrame) --add one subset for the

˓→first frame

28

29 --we are adding vertex to frame (next)

30 --this vertex list has to have at least 3 vertex (one triangle) to be

˓→valid

31 -- The table expected is : {{x,y},{x,y},{x,y}, ...}

32 if not tMesh:addVertex(indexFrame,indexSubset,tVertex) then

33 print("Error on add vertex buffer")

34 return false

35 end

36

37 if not tMesh:addIndex(indexFrame,indexSubset,tIndex) then

38 print("Error on add index buffer")

39 return false

40 end

41 (continues on next page)

15.2. Creating a sprite programmatically 319 MBM Documentation, Release 3.1.f

(continued from previous page)

42 --apply the texture to frame / subset

43 if not tMesh:setTexture(indexFrame,indexSubset,sTexture) then

44 print("Error on set texture!")

45 return false

46 end

47

48 tMesh:setType('sprite') -- set it to sprite type

49

50 local calcNormal,calcUv= false,true --Instruct to do not calculate

˓→normal but calcule UV

51 if tMesh:save(fileName,calcNormal,calcUv) then

52 print("Sprite created successfully")

53 return true

54 else

55 print("Failed to create sprite!")

56 return false

57 end

58

59 end

60

61

62 function onInitScene()

63

64 tSprite= sprite:new('2DW') -- our object which will load from binary file

65

66 local sFileNameSprite='smile.spt'

67

68 local tFaceVertex, tFaceIndex, sTextureFileName= createFace() --create

˓→our face

69

70 if saveMeshToBinaryFile(sFileNameSprite,tFaceVertex, tFaceIndex,

˓→sTextureFileName) then

71 tSprite:load(sFileNameSprite) --all coordinate already in place

72 else

73 print('Failed to create'.. sFileNameSprite)

74 mbm.quit()

75 end

76

77 end

download.

Figure 15.2: Example 1 creating sprite

Follow other example how to save a sprite to a binary file setting uv coordinates:

320 Chapter 15. Table sprite MBM Documentation, Release 3.1.f

1 mbm.setColor(1,1,1) --set background color to white

2

3 function createFaceUv()

4

5 local tFace= { {x=-50, y=-50, u=0, v=1},

6 {x=-50, y= 50, u=0, v=0},

7 {x= 50, y=-50, u=1, v=1},

8 {x= 50, y= 50, u=1, v=0}}

9 local tIndex={1,2,3,3,2,4}

10 local sTextureFileName='HB_smile.png'

11

12 return tFace, tIndex, sTextureFileName

13 end

14

15 function saveMeshToBinaryFile(fileName,tVertex,tIndex,sTexture)

16

17 --meshDebug is used to create dynamically mesh in the engine.

18 --For sprite it has to have at least one frame to be able to generate

˓→the sprite

19 local stride=2 --stride only can be 3 or 2. it means (x,y,z) or

˓→(x,y)

20 local tMesh= meshDebug:new() --new mesh debug to store the

˓→information about our sprite

21 local nFrame= tMesh:addFrame(stride) -- Add one frame with stride

˓→2 (x,y)

22 local indexFrame= nFrame --(meshDebug uses 1 based index)

23 local indexSubset=1 --first subset (1 based index)

24

25

26 --To add vertex, first we need to add a subset

27 local nSubset= tMesh:addSubSet(indexFrame) --add one subset for the

˓→first frame

28

29 --we are adding vertex to frame (next)

30 --this vertex list has to have at least 3 vertex (one triangle) to be

˓→valid

31 -- The table expected is : {{x,y},{x,y},{x,y}, ...}

32 if not tMesh:addVertex(indexFrame,indexSubset,tVertex) then

33 print("Error on add vertex buffer")

34 return false

35 end

36

37 if not tMesh:addIndex(indexFrame,indexSubset,tIndex) then

38 print("Error on add index buffer")

39 return false

40 end

41

42 --apply the texture to frame / subset

43 if not tMesh:setTexture(indexFrame,indexSubset,sTexture) then

44 print("Error on set texture!")

45 return false

46 end

47

48 tMesh:setType('sprite') -- set it to sprite type

49

50 local calcNormal,calcUv= false,false --Instruct to do not calculate

˓→normal and UV

(continues on next page)

15.2. Creating a sprite programmatically 321 MBM Documentation, Release 3.1.f

(continued from previous page)

51 if tMesh:save(fileName,calcNormal,calcUv) then

52 print("Sprite created successfully")

53 return true

54 else

55 print("Failed to create sprite!")

56 return false

57 end

58

59 end

60

61

62 function onInitScene()

63

64 tSprite= sprite:new('2DW') -- our object which will load from binary file

65

66 local sFileNameSprite='smile.spt'

67

68 local tFaceVertex, tFaceIndex, sTextureFileName= createFaceUv() --create

˓→our face and uv coordinates

69

70 if saveMeshToBinaryFile(sFileNameSprite,tFaceVertex, tFaceIndex,

˓→sTextureFileName) then

71 tSprite:load(sFileNameSprite) --all coordinate already in place

72 else

73 print('Failed to create'.. sFileNameSprite)

74 mbm.quit()

75 end

76

77 end

download.

Figure 15.3: Example 2 setting uv to create a sprite

Follow other example how to save a sprite to a binary file setting uv coordinates upside down:

1 mbm.setColor(1,1,1) --set background color to white

2

3 function createFaceUvUpSideDown()

4

5 local tFace= { {x=-50, y=-50, u=0, v=0},

6 {x=-50, y= 50, u=0, v=1},

7 {x= 50, y=-50, u=1, v=0},

8 {x= 50, y= 50, u=1, v=1}} (continues on next page)

322 Chapter 15. Table sprite MBM Documentation, Release 3.1.f

(continued from previous page)

9 local tIndex={1,2,3,3,2,4}

10 local sTextureFileName='HB_smile.png'

11

12 return tFace, tIndex, sTextureFileName

13 end

14

15 function saveMeshToBinaryFile(fileName,tVertex,tIndex,sTexture)

16

17 --meshDebug is used to create dynamically mesh in the engine.

18 --For sprite it has to have at least one frame to be able to generate

˓→the sprite

19 local stride=2 --stride only can be 3 or 2. it means (x,y,z) or

˓→(x,y)

20 local tMesh= meshDebug:new() --new mesh debug to store the

˓→information about our sprite

21 local nFrame= tMesh:addFrame(stride) -- Add one frame with stride

˓→2 (x,y)

22 local indexFrame= nFrame --(meshDebug uses 1 based index)

23 local indexSubset=1 --first subset (1 based index)

24

25

26 --To add vertex, first we need to add a subset

27 local nSubset= tMesh:addSubSet(indexFrame) --add one subset for the

˓→first frame

28

29 --we are adding vertex to frame (next)

30 --this vertex list has to have at least 3 vertex (one triangle) to be

˓→valid

31 -- The table expected is : {{x,y},{x,y},{x,y}, ...}

32 if not tMesh:addVertex(indexFrame,indexSubset,tVertex) then

33 print("Error on add vertex buffer")

34 return false

35 end

36

37 if not tMesh:addIndex(indexFrame,indexSubset,tIndex) then

38 print("Error on add index buffer")

39 return false

40 end

41

42 --apply the texture to frame / subset

43 if not tMesh:setTexture(indexFrame,indexSubset,sTexture) then

44 print("Error on set texture!")

45 return false

46 end

47

48 tMesh:setType('sprite') -- set it to sprite type

49

50 local calcNormal,calcUv= false,false --Instruct to do not calculate

˓→normal and UV

51 if tMesh:save(fileName,calcNormal,calcUv) then

52 print("Sprite created successfully")

53 return true

54 else

55 print("Failed to create sprite!")

56 return false

57 end

58 (continues on next page)

15.2. Creating a sprite programmatically 323 MBM Documentation, Release 3.1.f

(continued from previous page)

59 end

60

61

62 function onInitScene()

63

64 tSprite= sprite:new('2DW') -- our object which will load from binary file

65

66 local sFileNameSprite='smile.spt'

67

68 local tFaceVertex, tFaceIndex, sTextureFileName=

˓→createFaceUvUpSideDown()--create our face upside down

69

70 if saveMeshToBinaryFile(sFileNameSprite,tFaceVertex, tFaceIndex,

˓→sTextureFileName) then

71 tSprite:load(sFileNameSprite) --all coordinate already in place

72 else

73 print('Failed to create'.. sFileNameSprite)

74 mbm.quit()

75 end

76

77 end

download.

Figure 15.4: Example 3 setting uv upside down to create a sprite

15.2.2 Sprite animated to a binary file

Next one example how to create animated sprite. We will use four different image for this example:

Figure 15.5: smile download HB_smile.png download HB_sad.png

324 Chapter 15. Table sprite MBM Documentation, Release 3.1.f

Figure 15.6: sad

Figure 15.7: neutral download HB_neutral.png download HB_dead.png

1 mbm.setColor(1,1,1) --set background color to white

2

3 function createOneFrame(sTexture)

4

5 local tVertex= { {x=-50, y=-50, u=0, v=1},

6 {x=-50, y= 50, u=0, v=0},

7 {x= 50, y=-50, u=1, v=1},

8 {x= 50, y= 50, u=1, v=0}}

9 local tIndex={1,2,3,3,2,4}

10

11 return {tVertex= tVertex, tIndex= tIndex, sTexture= sTexture }

12 end

13

14 function saveMeshToBinaryFile(fileName,tFrames)

15

16 --meshDebug is used to create dynamically mesh in the engine.

17 --For sprite it has to have at least one frame to be able to generate

˓→the sprite

18 local stride=2 --stride only can be 3 or 2. it means (x,y,z) or

˓→(x,y)

19 local tMesh= meshDebug:new() --new mesh debug to store the

˓→information about our sprite

20

21 --First we must add the frames

22 for i=1,#tFrames do

23 local tFrame= tFrames[i]

24 local indexFrame= tMesh:addFrame(stride) -- Add one frame with

˓→stride 2 (x,y)

25 --To add vertex, first we need to add a subset

26 local indexSubset= tMesh:addSubSet(indexFrame) --add one subset for

˓→the first frame

27 --we are adding vertex to frame (next)

28 --this vertex list has to have at least 3 vertex (one triangle) to ˓→be valid (continues on next page)

Figure 15.8: dead

15.2. Creating a sprite programmatically 325 MBM Documentation, Release 3.1.f

(continued from previous page)

29 -- The table expected is : {{x,y},{x,y},{x,y}, ...}

30 if not tMesh:addVertex(indexFrame,indexSubset,tFrame.tVertex) then

31 print("Error on add vertex buffer")

32 return false

33 end

34 end

35

36 --Then we add the index buffer

37 for indexFrame=1,#tFrames do

38 local tFrame= tFrames[indexFrame]

39 local indexSubset=1

40 if not tMesh:addIndex(indexFrame,indexSubset,tFrame.tIndex) then

41 print("Error on add index buffer")

42 return false

43 end

44 --apply the texture to frame / subset

45 if not tMesh:setTexture(indexFrame,indexSubset,tFrame.sTexture) then

46 print("Error on set texture!")

47 return false

48 end

49 end

50

51 tMesh:setType('sprite') -- set it to sprite type

52

53 --animation

54 local animation_name='first_animation'

55 local initialFrame=1

56 local finalFrame=4

57 local timeBetweenFrame= 0.3

58 local typeAnimation= mbm.GROWING_LOOP

59

60 local index= tMesh:addAnim(animation_name,initialFrame,finalFrame,

˓→timeBetweenFrame,typeAnimation)

61 print('Animation :', index)

62

63

64 local calcNormal,calcUv= false,false --Instruct to do not calculate

˓→normal and UV

65 if tMesh:save(fileName,calcNormal,calcUv) then

66 print("Sprite created successfully")

67 return true

68 else

69 print("Failed to create sprite!")

70 return false

71 end

72

73 end

74

75

76 function onInitScene()

77

78 tSprite= sprite:new('2DW') -- our object which will load from binary file

79

80 local sFileNameSprite='smile.spt'

81

82 local tFrames={

83 [1]= createOneFrame('HB_smile.png'), (continues on next page)

326 Chapter 15. Table sprite MBM Documentation, Release 3.1.f

(continued from previous page)

84 [2]= createOneFrame('HB_sad.png'),

85 [3]= createOneFrame('HB_neutral.png'),

86 [4]= createOneFrame('HB_dead.png')

87 }

88

89 if saveMeshToBinaryFile(sFileNameSprite,tFrames) then

90 tSprite:load(sFileNameSprite) --all coordinate already in place

91 else

92 print('Failed to create'.. sFileNameSprite)

93 mbm.quit()

94 end

95

96 end

download

Figure 15.9: Example how to create animated sprite using different images.

Next example we will use a unique image with 9 animations inside:

Figure 15.10: Bird download Bird.png

1 mbm.setColor(1,1,1) --set background color to white

2

3 function addBirdFrame(x,y)

4

5 local sTexture='Bird.png'

6 local w_size_texture, h_size_texture= 512, 512 -- we know the size of

˓→texture 7 local pw= 1.0/ w_size_texture * (w_size_texture/3) --we calculate the ˓→3 birds in the x 8 local ph= 1.0/ h_size_texture * (h_size_texture/3) --we calculate the ˓→3 birds in the y (continues on next page)

15.2. Creating a sprite programmatically 327 MBM Documentation, Release 3.1.f

(continued from previous page)

9 10 local tVertex= { {x=-50, y=-50, u= (x-1) * pw, v= (y ) * ph}, 11 {x=-50, y= 50, u= (x-1) * pw, v= (y-1) * ph}, 12 {x= 50, y=-50, u= (x ) * pw, v= (y ) * ph}, 13 {x= 50, y= 50, u= (x ) * pw, v= (y-1) * ph}} 14 local tIndex={1,2,3,3,2,4}

15

16 return {tVertex= tVertex, tIndex= tIndex, sTexture= sTexture }

17 end

18

19 function saveMeshToBinaryFile(fileName,tFrames)

20

21 --meshDebug is used to create dynamically mesh in the engine.

22 --For sprite it has to have at least one frame to be able to generate

˓→the sprite

23 local stride=2 --stride only can be 3 or 2. it means (x,y,z) or

˓→(x,y)

24 local tMesh= meshDebug:new() --new mesh debug to store the

˓→information about our sprite

25

26 --First we must add the frames

27 for i=1,#tFrames do

28 local tFrame= tFrames[i]

29 local indexFrame= tMesh:addFrame(stride) -- Add one frame with

˓→stride 2 (x,y)

30 --To add vertex, first we need to add a subset

31 local indexSubset= tMesh:addSubSet(indexFrame) --add one subset for

˓→the first frame

32 --we are adding vertex to frame (next)

33 --this vertex list has to have at least 3 vertex (one triangle) to

˓→be valid

34 -- The table expected is : {{x,y},{x,y},{x,y}, ...}

35 if not tMesh:addVertex(indexFrame,indexSubset,tFrame.tVertex) then

36 print("Error on add vertex buffer")

37 return false

38 end

39 end

40

41 --Then we add the index buffer

42 for indexFrame=1,#tFrames do

43 local tFrame= tFrames[indexFrame]

44 local indexSubset=1

45 if not tMesh:addIndex(indexFrame,indexSubset,tFrame.tIndex) then

46 print("Error on add index buffer")

47 return false

48 end

49 --apply the texture to frame / subset

50 if not tMesh:setTexture(indexFrame,indexSubset,tFrame.sTexture) then

51 print("Error on set texture!")

52 return false

53 end

54 end

55

56 tMesh:setType('sprite') -- set it to sprite type

57

58 --animation

59 local animation_name='bird flying' (continues on next page)

328 Chapter 15. Table sprite MBM Documentation, Release 3.1.f

(continued from previous page)

60 local initialFrame=1

61 local finalFrame=#tFrames

62 local timeBetweenFrame= 0.2

63 local typeAnimation= mbm.GROWING_LOOP

64

65 local index= tMesh:addAnim(animation_name,initialFrame,finalFrame,

˓→timeBetweenFrame,typeAnimation)

66 print('Animation :', index)

67

68

69 local calcNormal,calcUv= false,false --Instruct to do not calculate

˓→normal and UV

70 if tMesh:save(fileName,calcNormal,calcUv) then

71 print("Sprite created successfully")

72 return true

73 else

74 print("Failed to create sprite!")

75 return false

76 end

77

78 end

79

80

81 function onInitScene()

82

83 tSprite= sprite:new('2DW') -- our object which will load from binary file

84

85 local sFileNameSprite='Bird.spt'

86

87 local tFrames={

88 [1]= addBirdFrame(1,1),

89 [2]= addBirdFrame(1,2),

90 [3]= addBirdFrame(1,3),

91

92 [4]= addBirdFrame(2,1),

93 [5]= addBirdFrame(2,2),

94 [6]= addBirdFrame(2,3),

95

96 [7]= addBirdFrame(3,1),

97 [8]= addBirdFrame(3,2),

98 [9]= addBirdFrame(3,3),

99 }

100

101 if saveMeshToBinaryFile(sFileNameSprite,tFrames) then

102 tSprite:load(sFileNameSprite) --all coordinate already in place

103 else

104 print('Failed to create'.. sFileNameSprite)

105 mbm.quit()

106 end

107

108 end download

Figure 15.11: Example how to create animated sprite using unique image and different coordinates by frame.

15.2. Creating a sprite programmatically 329 MBM Documentation, Release 3.1.f

Table of Contents

• Table text – text methods

* text getSize * text getSizeText * text setWildCard – text attributes – Creating a text programmatically

330 Chapter 15. Table sprite CHAPTER 16

Table text

A table text inherit from renderizable and implement all methods as usual. A text is created by a font using the method addText. An animation has a shader table by default which can be accessed by getShader method. Also an animation for text does not change the frame (there is no this concept on text), and instead of this, change how is drew the text on screen. A text can have more than one animation simultaneous (use setWildCard to do it).

16.1 text methods

16.1.1 text getSize

getSize(boolean* forceCalc) Get the size of text, Do NOT consider the rotation. It considers the scale. Returns number width, number height - dimension of text. Example:

tArial15= font:new('Arial15.fnt') -- load a file previously created by the engine. tText= tArial15:add('Some text here','2dw') local width, height= tText:getSize() print(width,height) local width, height= tText:getSize( true) -- force recalculate print(width,height)

Note: Only if the text is 3D there will be a depth value.

getSize(string other_text) Get the size of the string sent as text, Do NOT consider the rotation. It considers the scale. Parameters string – text to be calculated.

331 MBM Documentation, Release 3.1.f

Returns number width, number height - dimension of text. Example:

tArial15= font:new('Arial15.fnt') -- load a file previously created by the engine. tText= tArial15:add('Some text here','2dw') local width, height= tText:getSize('Other text \nHere is a new line!') print(width,height)

Note: Only if the text is 3D there will be a depth value.

16.1.2 text getSizeText

getSizeText(text other_text) Get the size of text NOT considering the rotation. It considers the scale. Parameters string – text to be calculated. Returns number width, number height - dimension of text. Example:

tArial15= font:new('Arial15.fnt') -- load a file previously created by the engine. tText= tArial15:add('Some text here','2dw') local width, height= tText:getSizeText('Other other text \nHere is a new line!') print(width,height)

Note: Only if the text is 3D there will be a depth value.

16.1.3 text setWildCard

setWildCard(string wildCard) Set the wildCard to change the animations in the same text. Parameters string – wildCard any character. Example:

tArial15= font:new('Arial15.fnt') -- load a file previously created by the engine. tText= tArial15:add('Hello world','2dw') tText:setWildCard('#') tText.text='#1#Hello #2#World!' --new text with wild-card.

Note: In the example we are expecting the text has at least two animation. #1# is the number for animation ‘one’. #2# is the number for animation ‘two’.

332 Chapter 16. Table text MBM Documentation, Release 3.1.f

16.2 text attributes

text [read / write] Access the text member for read / write. Example:

tArial15= font:new('Arial15.fnt') -- load a file previously created by the engine. tText= tArial15:add('Hello world','2dw') print(tText.text) -- Hello world tText.text='Welcome to my example!' --new text with print(tText.text) -- Welcome to my example!

align [read / write] Access the align from text member for read / write. The default is aligned to left. The valid values are: left, right and center. Example:

tArial15= font:new('Arial15.fnt') -- load a file previously created by the engine. tText= tArial15:add('Hello world aligned! \nNew line','2dw') print(tText.align) -- left tText.align='center'

16.3 Creating a text programmatically

To create a text programmatically you need create a font. An example can be found here.

Table of Contents

• Table texture – texture methods

* texture new * texture load * texture setSize – Creating a texture programmatically

16.2. text attributes 333 MBM Documentation, Release 3.1.f

334 Chapter 16. Table text CHAPTER 17

Table texture

A table texture inherit from renderizable and normally have one animation. Also the animation has a shader table by default which can be accessed by getShader method.

17.1 texture methods

17.1.1 texture new new(string * world, number * x, number * y, number * z) Create a new instance of a texture passing the world desired (detail) and position. Parameters • string – world can be 2ds, 2dw or 3d. • number – x position (optional). • number – y position (optional). • number – z position (optional). Returns texture table. Example: tTex= texture:new('2dw') --note that texture inherits from renderizable tTex:setPos(100,100,-1)

17.1.2 texture load load(string file_name, number * width, number * height) Load a texture from file at any format listed at images supported types. The number width and height (optional) are the frame size.

335 MBM Documentation, Release 3.1.f

Parameters • string – file name from texture. • number – width frame (optional). • number – height frame (optional). • boolean – alpha force to use or not (default is true)(optional). Returns boolean result. Example: tTexture= texture:new('2ds') if tTexture:load('mario.png') then print('Successfully loaded texture:','mario.png') else print('Failed to loaded texture:','mario.png') end

Note: The load method will search in all known path. You can add a path to search by the method addPath.

17.1.3 texture setSize setSize(number width, number height) Resize the frame size from texture. Parameters • number – width from frame. • number – height from frame. Example: tTex= texture:new('2dw') --note that texture inherits from renderizable tTex:setPos(100,100,-1) tTex:setSize(50,50)

Note: Always the image will adapt to the frame size.

17.2 Creating a texture programmatically

Here an example how to create a texture programmatically using the engine to do that. Please check the page creating texture

Table of Contents

336 Chapter 17. Table texture MBM Documentation, Release 3.1.f

• Table tile – tile map definitions

* Brick ID * Tile ID in the map – tile methods

* tile new * tile load * tile setLayerVisible * tile getTotalLayer * tile getTypeMap * tile getTileID * tile disableTile * tile enableTile * tile getPositionsFromBrickID * tile getPositionFromTileID * tile getNearPosition * tile setTileID * tile getTileID * tile getTileSize * tile getMapSize * tile getProperties * tile getObjects * tile getPhysicsBrick * tile createTileObject * tile setLayerZ * tile getLayerZ – tile object

* tile setBrickID

17.2. Creating a texture programmatically 337 MBM Documentation, Release 3.1.f

338 Chapter 17. Table texture CHAPTER 18

Table tile

A table tile inherit from renderizable and implement all methods as usual. Also the animation has a shader table by default which can be accessed by getShader method. A tile is created using the tile map editor

18.1 tile map definitions

There are some definitions that are important to understand. Brick ID and Tile ID.

18.1.1 Brick ID

Brick ID is a unique identifier for each brick. In the editor the brick ID is just a number of itself:

18.1.2 Tile ID in the map

This is how tile are organized in the map. • It is called ‘tile’ when the brick it is in the map. • The total of tile is count width tile x count height tile. • The first tile is the ID 1, and the last one depends on map size. • If we have for example 20x10 tiles we will have 200 tiles in total. 200th is the last one. • Zero means no tile . • See the figure to understand better:

339 MBM Documentation, Release 3.1.f

Figure 18.1: Brick ID on editor

340 Chapter 18. Table tile MBM Documentation, Release 3.1.f

Figure 18.2: 20x10 tiles = 200 tiles.

18.2 tile methods

18.2.1 tile new new(string * world, number * x, number * y, number * z) Create a new instance of a tile passing the world desired (detail) and position. Parameters • string – world can be 2ds, 2dw or 3d. • number – x position (optional). • number – y position (optional). • number – z position (optional). Returns tile table. Example: tTile= tile:new('2dw')

18.2.2 tile load load(string file_name) Load a tile from file (expected .tile extension). Parameters string – file name from file. Example:

18.2. tile methods 341 MBM Documentation, Release 3.1.f

tTile= tile:new('2dW') if tTile:load('my_map.tile') then print('Successfully loaded tile map:','my_map.tile') else print('Failed to loaded tile map:','my_map.tile') end

Note: The load method will search in all known path. You can add a path to search by the method addPath.

18.2.3 tile setLayerVisible setLayerVisible(number layer, boolean value) Turn a layer visible or not indicating the number of it (one based). Parameters • number – layer 1 to total of layer. • boolean – visible true or false. Example: tTile= tile:new('2dW') if tTile:load('my_map.tile') then tTile:setLayerVisible(1,false) else print('Failed to loaded tile map:','my_map.tile') end

Note: Initially all layers are visible.

18.2.4 tile getTotalLayer getTotalLayer Retrieve the total of layer from tile map. Returns number - total of layer. Example: tTile= tile:new('2dW') if tTile:load('my_map.tile') then print('Total layer:',tTile:getTotalLayer()) else print('Failed to loaded tile map:','my_map.tile') end

342 Chapter 18. Table tile MBM Documentation, Release 3.1.f

18.2.5 tile getTypeMap getTypeMap Retrieve the type of the tile map (isometric, orthogonal, hexagonal) Returns string - type of tile map. Example: tTile= tile:new('2dW') if tTile:load('my_map.tile') then print('Type Tile Map:',tTile:getTypeMap()) else print('Failed to loaded tile map:','my_map.tile') end

18.2.6 tile getTileID getTileID(number x, number y, number layer) Retrieve the tile ID in the map given x, y in 2d screen coordinate and the layer number. Parameters • number – x coordinate in 2d screen. • number – y coordinate in 2d screen. • number – layer 1 to total of layer. Returns number - ID of tile on tile map (1 to total of tile on map). Example: tTile= tile:new('2dW') tTile:load('my_map.tile') function onTouchMove(key,x,y) local layer=1 local ID= tTile:getTileID(x,y,layer) print('Tile ID:', ID) end

18.2.7 tile disableTile disableTile(number x, number y, number * layer) Disable rendering of tile, given the position x, y of the tile on the map in 2d screen coordinate, and the layer number. Parameters • number – x coordinate in 2d screen. • number – y coordinate in 2d screen. • number – layer 1 to total of layer. (Optional) Returns number - position of tile on tile map. (Zero means not found at x, y coordinate). Example:

18.2. tile methods 343 MBM Documentation, Release 3.1.f

tTile= tile:new('2dW') tTile:load('my_map.tile') function onTouchDown(key,x,y) local ID= tTile:disableTile(x,y) if ID ~=0 then print('Tile disabled ID',ID) end end

Note: See tile ID to understand better how tile ID works. If -1 is supplied to layer, it will disable each tile for each layer at position.

18.2.8 tile enableTile enableTile(number x, number y, number * layer) Enable rendering of tile, given the position x, y of the tile on the map in 2d screen coordinate, and the layer number. Parameters • number – x coordinate in 2d screen. • number – y coordinate in 2d screen. • number – layer 1 to total of layer. (Optional) Returns number - position of tile on tile map. (Zero means not found at x, y coordinate). Example: tTile= tile:new('2dW') tTile:load('my_map.tile') function onTouchDown(key,x,y) local ID= tTile:enableTile(x,y) if ID ~=0 then print('Tile Enabled ID',ID) end end

Note: See tile ID to understand better how tile ID works. If -1 is supplied to layer, it will enable each tile for each layer at position.

18.2.9 tile getPositionsFromBrickID getPositionsFromBrickID(number idBrick, number layer) Return a table of x, y positions, and layer of one or more tiles found on the map, according to the brick ID and the number of layer (can be omitted).

344 Chapter 18. Table tile MBM Documentation, Release 3.1.f

Parameters • number – brick id. • number – layer (one based). Returns table - { x, y, layer}, { x, y, layer}, ...}. Example: tTile= tile:new('2dW') tTile:load('my_map.tile') local brickID= 32 -- according to bricks local tPos= tTile:getPositionsFromBrickID(brickID) for i=1,#tPos do print(i,tPos[i].x,tPos[i].y,tPos[i],tPos[i].layer) end

Note: If -1 is supplied to layer, it will retrieve each tile found for each layer. Note that brick ID id is different of tile ID.

18.2.10 tile getPositionFromTileID getPositionFromTileID(number tileID) Return the x, y tile position given the tile ID on map. Parameters number – tile id. Returns number - x, number - y Example: tTile= tile:new('2dW') tTile:load('my_map.tile') local tileID= 32 local x,y= tTile:getPositionFromTileID(tileID) print('Center of tile 32:',x,y)

18.2.11 tile getNearPosition getNearPosition(number x, number y, number layer) Return the near x, y tile position given x,y and layer. Parameters • number – x position. • number – y position. • number – layer (one based) (if not supplied will get the first one). Returns number - x, number - y Example:

18.2. tile methods 345 MBM Documentation, Release 3.1.f

tTile= tile:new('2dW') tTile:load('my_map.tile') local x,y= 10, 10 local x,y= tTile:getNearPosition(x,y)

18.2.12 tile setTileID setTileID(number x, number y, number brickID, number layer) Set a tile to render a brick given the brick ID at x, y position, and layer. Parameters • number – x position. • number – y position. • number – brick ID. • number – layer (one based). Returns boolean - result of operation. Example: tTile= tile:new('2dW') tTile:load('my_map.tile') function onTouchDown(key,x,y) local brickID=1 local layer=1 tTile:setTileID(x,y,brickID,layer) end

Note: Note that brick ID id is different of tile ID.

18.2.13 tile getTileID getTileID(number x, number y, number brickID, number layer) Retrieve the tile ID and brick ID (if there is one set) given x, y position, and layer. Parameters • number – x position. • number – y position. • number – layer (one based). Returns number - tile ID, number - brick ID. Example:

346 Chapter 18. Table tile MBM Documentation, Release 3.1.f

tTile= tile:new('2dW') tTile:load('my_map.tile') function onTouchDown(key,x,y) local layer=1 local tileID, brickID= tTile:getTileID(x,y,layer) print('tileID', tileID,'brickID', brickID) end

18.2.14 tile getTileSize getTileSize Retrieve the default tile size considering the scale. Returns number - width, number - height. Example: tTile= tile:new('2dW') tTile:load('my_map.tile') local width,height= tTile:getTileSize() print('default size of tile:',width,height)

18.2.15 tile getMapSize getMapSize Retrieve the map size considering the scale. Returns number - width, number - height. Example: tTile= tile:new('2dW') tTile:load('my_map.tile') local width,height= tTile:getMapSize() print('Map size:',width,height)

18.2.16 tile getProperties getProperties(table * filter) Retrieve a array of a table with properties according to the filter. Parameters table – filter {name,owner,type,ID} (might be omitted). Returns table - {{name,value,owner,type}, ...} Example: tTile= tile:new('2dW') tTile:load('my_map.tile') local tProperties= tTile:getProperties({owner='layer', type='string'}) (continues on next page)

18.2. tile methods 347 MBM Documentation, Release 3.1.f

(continued from previous page) for i=1,#tProperties do local tProperty= tProperties[i] print(tProperty.name,tProperty.value,tProperty.owner,tProperty.type) end

Note: The filter is optional and when present, one or more fields might be used.

18.2.17 tile getObjects getObjects(table * filter) Retrieve a array of a table with objects according to the filter. Parameters table – filter {name,type,ID} (might be omitted). Returns table - {{name,type, ...}, ...} Example: tTile= tile:new('2dW') tTile:load('my_map.tile') local tRectangles= tTile:getObjects({type='rectangle'}) for i=1,#tRectangles do local tObject= tRectangles[i] print(tObject.type,tObject.name,tObject.x,tObject.y,tObject.width,tObject.height) end local tCircles= tTile:getObjects({type='circle'}) for i=1,#tCircles do local tObject= tCircles[i] print(tObject.type,tObject.name,tObject.x,tObject.y,tObject.ray) end local tTriangles= tTile:getObjects({type='triangle'}) for i=1,#tTriangles do local tObject= tTriangles[i] print(tObject.type,tObject.name,tObject.p1.x,tObject.p1.y, tObject.p2.x,tObject.p2.

˓→y, tObject.p3.x,tObject.p3.y) end local tPoints= tTile:getObjects({type='point'}) for i=1,#tPoints do local tObject= tPoints[i] print(tObject.type,tObject.name,tObject.x,tObject.y) end local tPoints= tTile:getObjects({type='line'}) for i=1,#tPoints do local tObject= tPoints[i] print(''.. tObject.type,tObject.name) for j=1,#tObject.points do local point= tObject.points[j] print(point.x,point.y) (continues on next page)

348 Chapter 18. Table tile MBM Documentation, Release 3.1.f

(continued from previous page) end end

Note: The filter is optional and when present, one or more fields might be used. The table has different fields according to type. See table bellow: Object might have repeated names.

Expected object types:

Type Fields rectangle x y width height circle x y ray triangle p1 = {x,y} p2 = {x,y} p1 = {x,y} point x y line points = {[1] = {x,y}, [2] = {x,y}, ...}

18.2.18 tile getPhysicsBrick getPhysicsBrick(number brickID) Retrieve a array of a table with physics from brick as defined in the editor. Parameters number – brickID Returns table - {{name,type, ...}, ...} Example: tTile= tile:new('2dW') tTile:load('my_map.tile') local brickID= 47 local tPhysics= tTile:getPhysicsBrick(brickID) for i=1,#tPhysics do local tObject= tPhysics[i] print(tObject.type,tObject.name,tObject.x,tObject.y) end

Note: A physic table might be the same table as object table for rectangle, circle and triangle.

18.2. tile methods 349 MBM Documentation, Release 3.1.f

18.2.19 tile createTileObject createTileObject(number tileID, number layer) Create a independent Tile Object from an existent tile ID given the layer. The Tile Object will no long be controlled by tile map, however, if the tile map is destroyed, it is also destroyed. This Tile Object is inherited from renderizable. Parameters • number – tileID • number – layer Returns table - renderizable Example: tTile= tile:new('2dW') tTile:load('my_map.tile') local tileID= 144 local layer=2 tSaw= tTile:createTileObject(tileID,layer) function loop(delta) tSaw.az= tSaw.az+ math.rad(50) end

Figure 18.3: Using tile object as normal renderizable after building it.

18.2.20 tile setLayerZ setLayerZ(number layer, number z) Set z position of layer. Parameters • number – layer (one based). • number – z position. Example: tTile= tile:new('2dW') tTile:load('my_map.tile') local layer, z=1, 0.5 tTile:setLayerZ(layer,z)

18.2.21 tile getLayerZ getLayerZ(number layer) Get z position from layer. Parameters number – layer (one based). Returns number - z position of layer

350 Chapter 18. Table tile MBM Documentation, Release 3.1.f

Example:

tTile= tile:new('2dW') tTile:load('my_map.tile') local layer=1 local z= tTile:getLayerZ(layer)

18.3 tile object

Tile Object is an independent object with its physics and own control of render. It inherits from renderiz- able. Although it is independent, if the tile map is destroyed, it is also destroyed.

18.3.1 tile setBrickID setBrickID(number brickID) Set a new Brick ID based on existent in tile map. Parameters number – brick id. Example:

tTile= tile:new('2dW') tTile:load('my_map.tile')

local tileID= 144 local layer=2 tSaw= tTile:createTileObject(tileID,layer)

local brickID= 25 tSaw:setBrickID(brickID)

function loop(delta) tSaw.az= tSaw.az+ math.rad(50) end

Figure 18.4: Changing the brick ID from Tile Object

Table of Contents

• Table timer – timer callback signature – timer methods

* timer new * timer start – timer attributes – User data acknowledgment

18.3. tile object 351 MBM Documentation, Release 3.1.f

352 Chapter 18. Table tile CHAPTER 19

Table timer

The table timer calls a function (callback) in a specific interval of time.

19.1 timer callback signature

The following signature must be implemented to be used in a timer callback: function onTimeOut(self) -- self is the timer table end

19.2 timer methods

19.2.1 timer new new(function callback_timer, number time) Create a new instance of a timer passing the function callback and the interval of time to be called. Parameters • string – callback_timer to the real function in lua. • number – interval in seconds to call the callback. Returns timer table. Example:

--important the function be defined before register the callback function on2Seconds(self) print('2 seconds has been passed...') end (continues on next page)

353 MBM Documentation, Release 3.1.f

(continued from previous page) tTimer= timer:new(on2Seconds,2)

Also the function might be anonymous: tTimer= timer:new( function (self) print('2 seconds has been passed...') end,2) new(string callback_timer, number time) Create a new instance of a timer passing the function callback as string and the interval of time to be called. Parameters • string – callback_timer string to real function in lua. • number – interval in seconds to call the callback. Returns timer table. Example:

--important the function be defined before register the callback function on2Seconds(self) print('2 seconds has been passed...') end tTimer= timer:new('on2Seconds',2)

19.2.2 timer start start Start the timer. If the timer was stopped using stop function, the timer will begin from zero. If the timer was paused using pause function, the timer will take account the time passed before. Example: tTimer= timer:new( function (self) print('2 seconds has been passed...') end,2) tTimer:start() stop Start the timer. Stop the timer callback and the internal timer. Example: tTimer= timer:new( function (self) print('I will be never called...') end,2) tTimer:stop() pause Pause the timer. Pause the timer callback. This method does not zero the internal timer. Next time the timer start, it will take account the time elapsed. Example:

354 Chapter 19. Table timer MBM Documentation, Release 3.1.f

tTimer= timer:new( function (self) print('2 seconds has been passed..') end,2) tTimer:pause() restart Restart the timer. If it was paused or stopped it will start again. The internal timer will be set to zero. Example: tTimer= timer:new( function (self) print('2 seconds has been passed..') end,2) tTimer:restart() isRunning Check if the timer is running or not. Returns boolean running - true is is running, false if is not. If it was paused or stopped it will return false. Example: tTimer= timer:new( function (self) print('2 seconds has been passed..') end,2) print('Timer is running:', tTimer:isRunning()) set(number interval) Change the interval of timer callback Parameters number – internal of callback timer. Example: tTimer= timer:new( function (self) print('3 seconds has been passed..') end,2) tTimer:set(3) get Retrieve the interval of the timer callback Returns number interval - the interval of timer callback. Example: tTimer= timer:new( function (self) print('2 seconds has been passed..') end,2) print('Timer to callback:', tTimer:get()) elapsed Retrieve the time elapsed since the last callback. Returns number elapsed - the elapsed timer. Example: tTimer= timer:new( function (self) print('Timer elapsed:', tTimer:elapsed()) --always 0 end,2) function loop(delta) print('Timer elapsed:', tTimer:elapsed()) -- here is possible to the timer elapsed end

19.2. timer methods 355 MBM Documentation, Release 3.1.f times Retrieve how much times the callback has been called since the last start. Returns number times - how much times the callback has been called. Example: tTimer= timer:new( function (self) print('Time number :', tTimer:times()) end,2) setCallBack(string callback_function_name) Change the callback of timer passing the callback as string. Parameters string – name of new callback timer. Example: tTimer= timer:new( function (self) print('2 seconds has been passed..') end,2) function onTimer(self) print('New callback in action') end tTimer:setCallBack('onTimer') setCallBack(function callback_function) Change the callback of timer passing as argument. Parameters function – callback of new callback timer. Example: tTimer= timer:new( function (self) print('2 seconds has been passed..') end,2) function onTimer(self) print('New callback in action') end tTimer:setCallBack(onTimer)

-- or as anonymous tTimer:setCallBack( function(self) print('New anonymous callback in action') end) destroy Destroy a timer. Example: tTimer= timer:new( function (self) print('I will never be called') end,2) tTimer:destroy() tTimer= nil

356 Chapter 19. Table timer MBM Documentation, Release 3.1.f

19.3 timer attributes

There is no attribute for timer table. So it is possible to add any tipe of attribute like number, boolean, string, table or function. Example:

tTimer= timer:new( function (self) print('2 seconds has been passed..') end,2) tTimer.x= 100 tTimer.y= 200

print(tTimer.x,tTimer.y) -- 100 200

19.4 User data acknowledgment

This table uses the first index to store the userdata C++ class internally, however, for timer, is allowed to write / read to / from index.

Error: It is important to understand that as all tables used in this engine, this table uses the first index to store the userdata pointing to the C++ class internally. There is no mechanism to prevent to access the first index from timer. If you overload the userdata, probably the program will crash.

Listing 19.1: Do not do this:

1 tTimer= timer:new( function (self) print('2 seconds has been passed..') end,2)

2 tTimer.x=0

3

4 print(tTimer[1]) -- read, okay will print userdata: 0x44958588a6a8 for example

5

6 tTimer[1]=5 -- Error, not allowed for this table. program will crash!

Table of Contents

• Table vec2 – vec2 methods

* vec2 new * vec2 get * vec2 set * vec2 add * vec2 sub * vec2 mul * vec2 div * vec2 length

19.3. timer attributes 357 MBM Documentation, Release 3.1.f

* vec2 azimuth * vec2 move * vec2 dot * vec2 lerp * vec2 normalize – vec2 attributes – User data acknowledgment

358 Chapter 19. Table timer CHAPTER 20

Table vec2

Table vec2 is a vector 2d (x,y) class for the most known operations using vector.

20.1 vec2 methods

20.1.1 vec2 new new Create a new instance of vec2 with no argument. Returns vec2 table. Example: local v= vec2:new() print(v.x,v.y) -- 0,0 new(number x, number * y) Create a new instance of vec2 passing two arguments.

Parameters • number – x value. • number – y value (optional). Returns vec2 table.

Example: local v= vec2:new(15,66) print(v.x,v.y) -- 15,66

(continues on next page)

359 MBM Documentation, Release 3.1.f

(continued from previous page) v= vec2:new(15) print(v.x,v.y) -- 15,0 new(vec2 other) Create a new instance of vec2 passing other vec2 as parameter.

Parameters vec2 – other to copy values. Returns vec2 table.

Example: local v1= vec2:new(15,66) print(v1.x,v1.y) -- 15,66 local v2= vec2:new(v1) print(v2.x,v2.y) -- 15,66 new(vec3 other) Create a new instance of vec2 passing other vec3 as parameter.

Parameters vec3 – other to copy values (x and y). Returns vec2 table.

Example: local v1= vec3:new(1,2,3) print(v1.x,v1.y,v1.z) -- 1,2,3 local v2= vec2:new(v1) print(v2.x,v2.y) -- 1,2 new(renderizable render) Create a new instance of vec2 passing a renderizable as parameter.

Parameters renderizable – render to copy values from position. Returns vec2 table.

Example: local tTexture= texture:new('2dw') tTexture:setPos(88,99) local v2= vec2:new(tTexture) print(v2.x,v2.y) -- 88,99

20.1.2 vec2 get get Retrieve the values x and y from vec2.

360 Chapter 20. Table vec2 MBM Documentation, Release 3.1.f

Returns number x, number y

Example: local v2= vec2:new(415,669) local x,y= v2:get() print(x,y) -- 415,669

20.1.3 vec2 set set(number x, number y) Set new values to vec2 passing two number arguments (x and y).

Parameters • number – x value. • number – y value (optional).

Example: local v= vec2:new(15,66) v:set(88,74) print(v:get()) -- 88,74 v:set(15) -- Note only x change print(v:get()) -- 15,74 set(vec2 other) Set new values to vec2 passing other vec2 as parameter.

Parameters vec2 – other to set values.

Example: local v1= vec2:new(15,66) local v2= vec2:new() print(v1) -- x:15 y:66 print(v2) -- x:0 y:0 v2:set(v1) print(v2) -- x:15 y:66 set(vec3 other) Set new values to vec2 passing other vec3 as parameter.

Parameters vec3 – other to set values (x and y).

Example: local v1= vec3:new(44,55,33) local v2= vec2:new() print(v1:get()) -- 44,55,33 print(v2:get()) -- 0,0 (continues on next page)

20.1. vec2 methods 361 MBM Documentation, Release 3.1.f

(continued from previous page) v2:set(v1) print(v2) -- x:44 y:55 set(renderizable render) Set new values to vec2 passing a renderizable as parameter.

Parameters renderizable – render to set values from position.

Example: local tTexture= texture:new('2dw') tTexture:setPos(12,15) local v2= vec2:new() v2:set(tTexture) print(v2) --x:12 y:15

20.1.4 vec2 add add(number x, number y) Add values to vec2 passing two number arguments (x and y).

Parameters • number – x value. • number – y value (optional).

Example: local v= vec2:new(15,66) v:add(88,74) print(v:get()) -- 103,140 v:add(15) -- Note.: 103 + 15 and 140 + 15 print(v:get()) -- 118,155 add(vec2 other) Add values to vec2 passing other vec2 as parameter.

Parameters vec2 – other to add values.

Example: local v1= vec2:new(15,66) local v2= vec2:new(1,2) print(v1) -- x:15 y:66 print(v2) -- x:1 y:2 v2:add(v1) print(v2) -- x:16 y:68

362 Chapter 20. Table vec2 MBM Documentation, Release 3.1.f add(vec3 other) Add values to vec2 passing other vec3 as parameter.

Parameters vec3 – other to add values (x and y).

Example: local v1= vec3:new(44,55,33) local v2= vec2:new(5,8) print(v1:get()) -- 44,55,33 print(v2:get()) -- 5,8 v2:add(v1) print(v2) -- x:49 y:63 add(renderizable render) Add values to vec2 passing a renderizable as parameter.

Parameters renderizable – render to add values from position.

Example: local tTexture= texture:new('2dw') tTexture:setPos(12,15) local v2= vec2:new(5,5) v2:add(tTexture) print(v2) --x:17 y:20

20.1.5 vec2 sub sub(number x, number y) Subtract values in the vec2 passing two number arguments (x and y).

Parameters • number – x value. • number – y value (optional).

Example: local v= vec2:new(150,660) v:sub(88,74) print(v:get()) -- 62 586 v:sub(15) --note.: 62 - 15, 586 - 15 print(v:get()) -- 47 571 sub(vec2 other) Subtract values in the vec2 passing other vec2 as parameter.

Parameters vec2 – other to subtract values.

20.1. vec2 methods 363 MBM Documentation, Release 3.1.f

Example: local v1= vec2:new(15,66) local v2= vec2:new(1,2) print(v1) -- x:15 y:66 print(v2) -- x:1 y:2 v2:sub(v1) print(v2) -- x:-14 y:-64 sub(vec3 other) Subtract values in the vec2 passing other vec3 as parameter.

Parameters vec3 – other to subtract values (x and y).

Example: local v1= vec3:new(44,55,33) local v2= vec2:new(5,8) print(v1:get()) -- 44,55,33 print(v2:get()) -- 5,8 v2:sub(v1) print(v2) -- x:-39 y:-47 sub(renderizable render) Subtract values in the vec2 passing a renderizable as parameter.

Parameters renderizable – render to subtract values from position.

Example: local spt= sprite:new('2dw') spt:setPos(12,15) local v2= vec2:new(5,5) v2:sub(spt) print(v2) -- x:-7 y:-10

20.1.6 vec2 mul mul(number x, number y) Multiply (scalar) values to vec2 passing two number arguments (x and y).

Parameters • number – x value. • number – y value (optional).

Example:

364 Chapter 20. Table vec2 MBM Documentation, Release 3.1.f

local v= vec2:new(2,3) v:mul(5,2) print(v:get()) -- 10 6 v:mul(2) -- Note.: 10 * 2 and 6 * 2 print(v:get()) -- 20 12 mul(vec2 other) Multiply (scalar) values to vec2 passing other vec2 as parameter.

Parameters vec2 – other to multiply values.

Example: local v1= vec2:new(2,3) local v2= vec2:new(3,4) print(v1) -- x:2 y:3 print(v2) -- x:3 y:4 v2:mul(v1) print(v2) -- 6 12 mul(vec3 other) Multiply (scalar) values by vec2 passing other vec3 as parameter.

Parameters vec3 – other to multiply values (x and y).

Example: local v1= vec3:new(2,3,4) local v2= vec2:new(2,1.5) print(v1:get()) -- 2,3,4 print(v2:get()) -- 2,1.5 v2:mul(v1) print(v2) -- 4, 4.5 mul(renderizable render) Multiply (scalar) values by vec2 passing a renderizable as parameter.

Parameters renderizable – render to multiply values by position.

Example: local spt= sprite:new('2dw') spt:setPos(2.2,3.3) local v2= vec2:new(3,4) v2:mul(spt) print(v2) -- x:6.6 y:13.2

20.1. vec2 methods 365 MBM Documentation, Release 3.1.f

20.1.7 vec2 div

Note: Any number divided by zero is an error however the engine set the result to 0. div(number x, number y) Divide values by vec2 passing two number arguments (x and y).

Parameters • number – x value. • number – y value (optional).

Example: local v= vec2:new(2,3) v:div(2,1.5) print(v:get()) -- 1 2 v:div(2) -- Note.: 1 / 2 and 2 / 2 print(v:get()) -- 0.5 1 v:div(0) -- Note.: 0.5 / 0 and 1 / 0 not throw an exception and the result is set to 0 print(v) -- x:0 y:0 div(vec2 other) Divide values by vec2 passing other vec2 as parameter.

Parameters vec2 – other to divide values.

Example: local v1= vec2:new(20,30) local v2= vec2:new(2,4) print(v1) -- x:20 y:30 print(v2) -- x:2 y:4 v1:div(v2) print(v1) -- x:10 y:7.5 v2.y=0 v1:div(v2) print(v1) -- x:5 y:0 v1:set(10,20) v2:set(0,10) v1:div(v2)-- Note.: 10 / 0 not throw an exception and the result is set to 0 print(v1) -- x:0 y:2 div(vec3 other) Divide values by vec2 passing other vec3 as parameter.

Parameters vec3 – other to divide values by (x and y).

366 Chapter 20. Table vec2 MBM Documentation, Release 3.1.f

Example: local v1= vec3:new(2,3,4) local v2= vec2:new(2,1.5) print(v1:get()) -- 2,3,4 print(v2:get()) -- 2,1.5 v2:div(v1) print(v2) -- x:1 y:0.5 div(renderizable render) Divide values by vec2 passing a renderizable as parameter.

Parameters renderizable – render to divide values by position.

Example: local spt= sprite:new('2dw') spt:setPos(2,50) local v2= vec2:new(200,300) v2:div(spt) print(v2) -- x:100 y:6

20.1.8 vec2 length

The formula to length is: √︀(푥 * 푥) + (푦 * 푦) length Get the length from vec2. Same as len attribute. Returns number - length of vector. Example: local v= vec2:new(100,300) print(v:length()) -- 316.2278

20.1.9 vec2 azimuth azimuth Get the azimuth from vec2. Returns number - azimuth of vector (radian). Example: local v= vec2:new(1,0) print(math.deg(v:azimuth())) -- 90 azimuth(vec2 v2) Get the azimuth between two vec2. Returns number - azimuth between two vectors (radian).

20.1. vec2 methods 367 MBM Documentation, Release 3.1.f

Example: local v1= vec2:new(1,0) local v2= vec2:new(0,1) print(math.deg(v1:azimuth(v2))) -- 135

20.1.10 vec2 move move(number x, number * y) Move x and y units frames by seconds. This method consider the FPS. Parameters • number – x position. • number – y position (optional). Example: local v= vec2:new(5,55) v:move(100,50)

--this is equivalent function loop(delta) v.x= v.x+ (delta * 100) v.y= v.y+ (delta * 50) end

20.1.11 vec2 dot

A dot product is an algebraic operation that takes two equal-length sequences of numbers and returns a single number. Learn more at wiki dot product. The formula to vec2 dot is: (푥 * 푥) + (푦 * 푦) dot(vec2 b) Calculate a dot product value to vec2 passing other vec2 as parameter. Parameters vec2 – parameter. Returns number dot calculated. Example: a= vec2:new(3,4) --x = 3 y = 4 b= vec2:new(10,25) --x = 10 y = 25 local dot_result= a:dot(b) --3 * 10 + 4 * 25 = 130 print(dot_result) -- 130 dot(vec2 a, vec2 b) Calculate a dot product value to vec2 between a and b vec2 as parameter.

Parameters

368 Chapter 20. Table vec2 MBM Documentation, Release 3.1.f

• vec2 – a a parameter. • vec2 – b b parameter. Returns number dot calculated.

Example:

a= vec2:new(3,4) --x = 3 y = 4 b= vec2:new(10,25) --x = 10 y = 25 c= vec2:new(1,2) --x = 1 y = 2 local dot_result= c:dot(a,b) --3 * 10 + 4 * 25 = 130 print(dot_result) -- 130

20.1.12 vec2 lerp

Linear interpolation is a method of curve fitting using linear polynomials to construct new data points within the range of a discrete set of known data points. Learn more at wiki linear interpolation. The formula to vec2 lerp is:

푣 = (1 − 푠) * (푣1) + 푠 * (푣2) lerp(vec2 a, vec2 b, number s) Calculate a linear interpolation between two vec2. Store the result on itself.

Parameters • vec2 – a a parameter. • vec2 – b b parameter. • number – s parameter.

Example:

local a= vec2:new(20,30) local b= vec2:new(10,15) local c= vec2:new() --x = 0 y = 0 c:lerp(a,b,0.5) --Keep the result on 'c' vector print(c) --x:15 y:22.5

20.1.13 vec2 normalize

A normal vector is a vector that is perpendicular to a given object. Learn more at wiki Normal (geometry) and wiki Unit vector (geometry). The formula to vec2 normal is:

ˆ 푈 푈 = |푈|

where |u| is the length of u. normalize

20.1. vec2 methods 369 MBM Documentation, Release 3.1.f

Normalize a vec2. Store the result on itself. Example: local a= vec2:new(500,100) a:normalize() print(a) -- x:0.9805807 y:0.1961161 normalize(vec2 out) Normalize a vec2 and store the result in the vec2 out.

Parameters vec2 – out as parameter.

Example: local a= vec2:new(500,100) local b= vec2:new() a:normalize(b) print(a) -- x:500 y:100 print(b) -- x:0.9805807 y:0.1961161

20.2 vec2 attributes x, y [read / write] Access the position x and y member from vec2. Example: local v= vec2:new() v.x= 100 v.y= 200 print(v) -- x:100 y:200 len [ read only ]

Call len method as member from vec2 for read only. Same as length Example: local v= vec2:new() v.x= 100 v.y= 200 print(v.len) -- 223.6068

20.3 User data acknowledgment

This table uses the first index to store the userdata C++ class internally, and is not allowed for vec2 to write / read to index.

370 Chapter 20. Table vec2 MBM Documentation, Release 3.1.f

Listing 20.1: Do not do this:

1 v= vec2:new()

2 v:set(10,10)

3

4 print(v[1]) -- read, okay will print userdata: 0x44958588a6a8 for example

5

6 v[1]=5 -- Error, not allowed for this table. program will crash!

Table of Contents

• Table vec3 – vec3 methods

* vec3 new * vec3 get * vec3 set * vec3 add * vec3 sub * vec3 mul * vec3 div * vec3 length * vec3 move * vec3 dot * vec3 lerp * vec3 normalize * vec3 cross – vec3 attributes – User data acknowledgment

20.3. User data acknowledgment 371 MBM Documentation, Release 3.1.f

372 Chapter 20. Table vec2 CHAPTER 21

Table vec3

Table vec3 is a vector 3d (x,y,z) class for the most known operations using vector.

21.1 vec3 methods

21.1.1 vec3 new new Create a new instance of vec3 with no argument. Returns vec3 table. Example: local v= vec3:new() print(v.x,v.y,v.z) -- 0,0,0 new(number x, number * y, number * z) Create a new instance of vec3 passing three arguments.

Parameters • number – x value. • number – y value (optional). • number – z value (optional). Returns vec3 table.

Example:

373 MBM Documentation, Release 3.1.f

local v= vec3:new(15,66,88) print(v.x,v.y,v.z) -- 15,66,88 v= vec3:new(15) print(v.x,v.y,v.z) -- 15,0,0 new(vec3 other) Create a new instance of vec3 passing other vec3 as parameter.

Parameters vec3 – other to copy values (x, y and z). Returns vec3 table.

Example: local v1= vec3:new(1,2,3) print(v1.x,v1.y,v1.z) -- 1,2,3 local v2= vec3:new(v1) print(v2.x,v2.y,v2.z) -- 1,2,3 new(renderizable render) Create a new instance of vec3 passing a renderizable as parameter.

Parameters renderizable – render to copy values from position. Returns vec3 table.

Example: local tTexture= texture:new('3D') tTexture:setPos(88,99,101) local v2= vec3:new(tTexture) print(v2.x,v2.y,v2.z) -- 88,99,101

21.1.2 vec3 get get Retrieve the values x, y and z from vec3.

Returns number x, number y, number z

Example: local v= vec3:new(415,669,222) local x,y,z= v:get() print(x,y) -- 415,669,222

374 Chapter 21. Table vec3 MBM Documentation, Release 3.1.f

21.1.3 vec3 set set(number x, number y, number z) Set new values to vec3 passing three number arguments (x, y and z).

Parameters • number – x value. • number – y value (optional). • number – z value (optional).

Example: local v= vec3:new(15,66,33) v:set(88,74,55) print(v:get()) -- 88,74,55 v:set(15) -- Note only x change print(v:get()) -- 15,74,55 set(vec3 other) Set new values to vec3 passing other vec3 as parameter.

Parameters vec3 – other to set values.

Example: local v1= vec3:new(15,66,99) local v2= vec3:new() print(v1) -- x:15 y:66 z:99 print(v2) -- x:0 y:0 z:0 v2:set(v1) print(v2) -- x:15 y:66 z:99 set(renderizable render) Set new values to vec3 passing a renderizable as parameter.

Parameters renderizable – render to set values from position.

Example: local tTexture= texture:new('3D') tTexture:setPos(12,15,75) local v2= vec3:new() v2:set(tTexture) print(v2) --x:12 y:15 z:75

21.1.4 vec3 add add(number x, number y, number z)

21.1. vec3 methods 375 MBM Documentation, Release 3.1.f

Add values to vec3 passing three number arguments (x, y and z).

Parameters • number – x value. • number – y value (optional). • number – z value (optional).

Example: local v= vec3:new(15,66,33) v:add(88,74,2) print(v:get()) -- 103,140, 35 v:add(15) -- Note.: 103 + 15, 140 + 15 and 35 + 15 print(v:get()) -- 118,155,50 add(vec3 other) Add values to vec3 passing other vec3 as parameter.

Parameters vec3 – other to add values.

Example: local v1= vec3:new(15,66,12) local v2= vec3:new(1,2,3) print(v1) -- x:15 y:66 z:12 print(v2) -- x:1 y:2 z:3 v2:add(v1) print(v2) -- x:16 y:68 z:15 add(renderizable render) Add values to vec3 passing a renderizable as parameter.

Parameters renderizable – render to add values from position.

Example: local tTexture= texture:new('3D') tTexture:setPos(12,15,22) local v2= vec3:new(5,5,5) v2:add(tTexture) print(v2) --x:17 y:20 z:27

21.1.5 vec3 sub sub(number x, number y, number z) Subtract values in the vec3 passing three number arguments (x, y and z).

Parameters

376 Chapter 21. Table vec3 MBM Documentation, Release 3.1.f

• number – x value. • number – y value (optional). • number – z value (optional).

Example: local v= vec3:new(150,660,1) v:sub(88,74,1) print(v:get()) -- 62 586 0 v:sub(15) --note.: 62 - 15, 586 - 15, 0 - 15 print(v:get()) -- 47 571 -15 sub(vec3 other) Subtract values in the vec3 passing other vec3 as parameter.

Parameters vec3 – other to subtract values.

Example: local v1= vec3:new(15,66,99) local v2= vec3:new(1,2,3) print(v1) -- x:15 y:66 z:99 print(v2) -- x:1 y:2 z:3 v2:sub(v1) print(v2) -- x:-14 y:-64 z:-96 sub(renderizable render) Subtract values in the vec3 passing a renderizable as parameter.

Parameters renderizable – render to subtract values from position.

Example: local spt= sprite:new('3D') spt:setPos(12,15,10) local v2= vec3:new(5,5,5) v2:sub(spt) print(v2) -- x:-7 y:-10 z:-5

21.1.6 vec3 mul mul(number x, number y, number z) Multiply (scalar) values to vec3 passing three number arguments (x, y and z).

Parameters • number – x value. • number – y value (optional). • number – z value (optional).

21.1. vec3 methods 377 MBM Documentation, Release 3.1.f

Example:

local v= vec3:new(2,3,1.5) v:mul(5,2,3) print(v:get()) -- 10 6 4.5

v:mul(2) -- Note.: 10 * 2, 6 * 2, 4.5 * 2 print(v:get()) -- 20 12 9

mul(vec3 other) Multiply (scalar) values to vec3 passing other vec3 as parameter.

Parameters vec3 – other to multiply values.

Example:

local v1= vec3:new(2,3,1) local v2= vec3:new(3,4,2) print(v1) -- x:2 y:3 z:1 print(v2) -- x:3 y:4 z:2

v2:mul(v1) print(v2) -- 6 12 2

mul(renderizable render) Multiply (scalar) values by vec3 passing a renderizable as parameter.

Parameters renderizable – render to multiply values by position.

Example:

local spt= sprite:new('3d') spt:setPos(2.2,3.3,4.4)

local v2= vec3:new(3,4,2) v2:mul(spt) print(v2) -- x:6.6 y:13.2 z:8.8

21.1.7 vec3 div

Note: Any number divided by zero is an error and the engine set the result to 0.

div(number x, number y) Divide values by vec3 passing three number arguments (x, y and z).

Parameters • number – x value. • number – y value (optional). • number – z value (optional).

378 Chapter 21. Table vec3 MBM Documentation, Release 3.1.f

Example: local v= vec3:new(2,3,4) v:div(2,1.5,0.5) print(v:get()) -- 1 2 8 v:div(2) -- Note.: 1 / 2, 2 / 2 and 8 / 2 print(v:get()) -- 0.5 1 4 v:div(0) -- Note.: 0.5 / 0, 1 / 0 and 4 / 0 not throw an exception and the result is

˓→set to 0 print(v) -- x:0 y:0 z:0 div(vec3 other) Divide values by vec3 passing other vec3 as parameter.

Parameters vec3 – other to divide values.

Example: local v1= vec3:new(20,30,40) local v2= vec3:new(2,4,5) print(v1) -- x:20 y:30 z:40 print(v2) -- x:2 y:4 z:5 v1:div(v2) print(v1) -- x:10 y:7.5 z:8 v2.y=0 v1:div(v2) print(v1) -- x:5 y:0 z:1.6 v1:set(10,20,30) v2:set(0,10,20) v1:div(v2)-- Note.: 10 / 0 not throw an exception however the result is set to 0 print(v1) -- x:0 y:2 z:1.5 div(renderizable render) Divide values by vec3 passing a renderizable as parameter.

Parameters renderizable – render to divide values by position.

Example: local spt= sprite:new('3d') spt:setPos(2,50,75) local v2= vec3:new(200,300,400) v2:div(spt) print(v2) -- x:100 y:6 z:5.333333

21.1.8 vec3 length

The formula to length is:

21.1. vec3 methods 379 MBM Documentation, Release 3.1.f

√︀(푥 * 푥) + (푦 * 푦) + (푧 * 푧) length Get the length from vec3. Same as len attribute. Returns number length of vector. Example:

local v= vec3:new(100,300,500) print(v:length()) -- 591.608

21.1.9 vec3 move

move(number x, number * y, number * z) Move x, y and z units frames by seconds. This method consider the FPS. Parameters • number – x position. • number – y position (optional). • number – z position (optional). Example:

local v= vec3:new(5,55,33) v:move(100,50,40)

--this is equivalent function loop(delta) v.x= v.x+ (delta * 100) v.y= v.y+ (delta * 50) v.z= v.z+ (delta * 40) end

21.1.10 vec3 dot

A dot product is an algebraic operation that takes two equal-length sequences of numbers and returns a single number. Learn more at wiki dot product. The formula to vec3 dot is: (푥 * 푥) + (푦 * 푦) + (푧 * 푧) dot(vec3 b) Calculate a dot product value to vec3 passing other vec3 as parameter. Parameters vec3 – parameter. Returns number dot calculated. Example:

a= vec3:new(3,4,5) --x = 3 y = 4 z = 5 b= vec3:new(10,25,15) --x = 10 y = 25 z = 15 local dot_result= a:dot(b) --3 * 10 + 4 * 25 + 5 * 15 = 205 (continues on next page)

380 Chapter 21. Table vec3 MBM Documentation, Release 3.1.f

(continued from previous page)

print(dot_result) -- 205

dot(vec3 a, vec3 b) Calculate a dot product value to vec3 between a and b vec3 as parameter.

Parameters • vec3 – a a parameter. • vec3 – b b parameter. Returns number dot calculated.

Example:

a= vec3:new(3,4,5) --x = 3 y = 4 z = 5 b= vec3:new(10,25,15) --x = 10 y = 25 z = 15 c= vec3:new(1,2,3) --x = 1 y = 2 z = 3 local dot_result= c:dot(a,b) --3 * 10 + 4 * 25 + 5 * 15 = 205

print(dot_result) -- 205

21.1.11 vec3 lerp

Linear interpolation is a method of curve fitting using linear polynomials to construct new data points within the range of a discrete set of known data points. Learn more at wiki linear interpolation. The formula to vec3 lerp is:

푣 = (1 − 푠) * (푣1) + 푠 * (푣2) lerp(vec3 a, vec3 b, number s) Calculate a linear interpolation between two vec3. Store the result on itself.

Parameters • vec3 – a a parameter. • vec3 – b b parameter. • number – s parameter.

Example:

local a= vec3:new(20,30,40) local b= vec3:new(10,15,20) local c= vec3:new() --x = 0 y = 0 z = 0 c:lerp(a,b,0.5) --Keep the result on 'c' vector print(c) --x:15 y:22.5 z:30

21.1. vec3 methods 381 MBM Documentation, Release 3.1.f

21.1.12 vec3 normalize

A normal vector is a vector that is perpendicular to a given object. Learn more at wiki Normal (geometry) and wiki Unit vector (geometry). The formula to vec3 normal is:

ˆ 푈 푈 = |푈|

where |u| is the length of u. normalize Normalize a vec3. Store the result on itself. Example: local a= vec3:new(500,100,200) a:normalize() print(a) -- x:0.9128709 y:0.1825742 z:0.3651484 normalize(vec3 out) Normalize a vec3 and store the result in the vec3 out.

Parameters vec3 – out as parameter.

Example: local a= vec3:new(500,100,200) local b= vec3:new() a:normalize(b) print(a) -- x:500 y:100 z:200 print(b) -- x:0.9128709 y:0.1825742 z:0.3651484

21.1.13 vec3 cross

A cross vector between a and b is the cross product a x b vector that is perpendicular to both and thus normal to the plane containing them. Learn more at wiki Cross product.

The formula to vec3 cross is:

푎x푏 = |푎||푏| sin 휃푛

Where 휃 is the angle between a and b in the plane containing them (hence, it is between 0° and 180°), |a| and |b| are the magnitudes of vectors a and b, and n is a unit vector perpendicular to the plane containing a and b in the direction given by the right-hand rule. If the vectors a and b are parallel (i.e., the angle 휃 between them is either 0° or 180°), by the above formula, the cross product of a and b is a zero vector. cross(vec3 a, vec3 b) Parameters • vec3 – a as parameter.

382 Chapter 21. Table vec3 MBM Documentation, Release 3.1.f

• vec3 – b as parameter. Example:

local a= vec3:new(1,1,0) local b= vec3:new(0,1,1) local c= vec3:new() c:cross(a,b) print(c) -- x:1 y:-1 z:1

21.2 vec3 attributes

x, y, z [read / write] Access the position x , y and z member from vec3. Example:

local v= vec3:new() v.x= 100 v.y= 200 v.z= 300

print(v.x,v.y,v.z) -- 100 200 300

len [ read only ]

Call len method as member from vec3 for read only. Same as length Example:

local v= vec3:new() v.x= 100 v.y= 200 v.z= 300

print(v.len) -- 374.1657

21.3 User data acknowledgment

This table uses the first index to store the userdata C++ class internally, and is not allowed for vec3 to write / read to index.

Listing 21.1: Do not do this:

1 v= vec3:new()

2 v:set(10,10,10)

3

4 print(v[1]) -- read, okay will print userdata: 0x44958588a6a8 for example

5

6 v[1]=5 -- Error, not allowed for this table. program will crash!

21.2. vec3 attributes 383 MBM Documentation, Release 3.1.f

Table of Contents

• Table audio – audio Methods

* audio new * audio play * audio pause * audio stop * audio volume * audio pitch * audio pan * audio pan * audio reset * audio len * audio setPosition * audio pan * audio persistent * audio destroy * audio onEnd

384 Chapter 21. Table vec3 CHAPTER 22

Table audio

Audio is an attempt to embed audio for multiple platform using the same interface in Lua by the engine. Unfortunately, this is still time consuming and not every platform is easy to handle with a common built-in music library. The main focus of the engine is graphics, so, for now, there are missing platform for audios. For Windows it is used Audiere. For Android it is used native audio.

Important: For Android only add audio in the asset folder. If you try to read audio from external device such as SD card, it has to modify the Java code for that.

22.1 audio Methods

22.1.1 audio new new(string file_name, boolean * in_memory, boolean * play, boolean * loop) Create a new instance of a audio. Parameters • string – file name of sound. • boolean – in memory , default is false. • boolean – play to play immediately, default is false. • boolean – loop to keep in loop, default is false. Returns audio table.

385 MBM Documentation, Release 3.1.f

22.1.2 audio play

play(boolean * loop) Parameters boolean – loop to keep in loop, default is false. Returns boolean result isPlaying Returns boolean result

22.1.3 audio pause

pause Returns boolean result isPaused Returns boolean result

22.1.4 audio stop

stop Returns boolean result

22.1.5 audio volume

setVolume(number volume) Parameters number – volume of sound (usually 0 to 1). Returns boolean result getVolume Returns number volume

22.1.6 audio pitch

setPitch(number pitch) Parameters number – pitch of sound. Returns boolean result getPitch Returns number pitch

386 Chapter 22. Table audio MBM Documentation, Release 3.1.f

22.1.7 audio pan

setPan(number pan) Parameters number – pan of sound. Returns boolean result getPan Returns number pan

22.1.8 audio pan

setPan(number pan) Parameters number – pan of sound. Returns boolean result getPan Returns number pan

22.1.9 audio reset

reset Returns boolean result

22.1.10 audio len

getLen Returns number length of sound.

22.1.11 audio setPosition setPan(number position) Parameters number – position of sound as integer. Returns boolean result

22.1.12 audio pan

setPan(number pan) Parameters number – pan of sound. Returns boolean result getName Returns string name of sound.

22.1. audio Methods 387 MBM Documentation, Release 3.1.f

22.1.13 audio persistent setPersistent(boolean persistent) Parameters boolean – persistent. isPersistent Returns boolean persistent.

22.1.14 audio destroy destroy

22.1.15 audio onEnd onEnd(function callback) Parameters function – callback.

function onEndStream(audio tAudio,string name)

end

Table of Contents

• Editors – File Format – Sprite Maker

* First Steps With Sprite Maker Editor – Font Maker

* First Steps With Font Maker Editor – Particle Editor

* First Steps With Particle Editor – Physic Editor – Shader Editor

* First Steps With Shader Editor – Scene Editor

* First Steps With Scene Editor – Asset Packager

* First Steps With Packager – Tile Map Editor

* First Steps With Tile Map Editor – Texture Packer Editor

388 Chapter 22. Table audio CHAPTER 23

Editors

MBM has some LUA based editors. This page intent to show each of them and its main functionality. Those editor is meant to facilitate to build games/application. We are talking about sprite, mesh, particle, font/text, shader, etc. . .

23.1 File Format

All editors can save the current edit status, however, the main objective is to create a final binary file that the engine is able to read in the optimized way. Here the expected format for each editor:

Editor Editor Format Binary Format Type mesh Sprite Maker .sprite .spt sprite Font Maker .ttf .fnt font Particle Maker .particle .ptl particle

23.2 Sprite Maker

Sprite Maker meant to make animations based on image(s). One sprite might have one or more images, one or more animations, one or more frames. The animations are based on frames interpolation and also might be repeated (you might want to make some effect on it). The application is written in LUA script and the file name is sprite_maker.lua. It is dependent on ImGui Plugin and EDITOR_FEATURES flag of compilation in the engine.

389 MBM Documentation, Release 3.1.f

23.2.1 First Steps With Sprite Maker Editor

For this example it will be used those six images:

Open Sprite Maker indicating the script and typing the desired width and height: $ mini-mbm sprite_maker.lua -w 1280 -h 800 --nosplash

Note: You might need to specify the whole path if it is not in your environment.

From menu insert image and choose All images needed: From menu in Image(s) Selector select All Images: From menu in Add Frame click in Add all and one frame for each image will be added: From menu Animations click in Edit Animations and choose the frames, type, interval and time between frames: Also it is possible to create frame from sprite sheet. This allows to crop a lot of frames from one image: Now a sprite could be loaded using sprite.

23.3 Font Maker

Font Maker or should be better called Font Parser, is a way to create font from truetype font. It is a simple editor which import and parse truetype font and allow to make some desired animations and then, save as binary file to be used in the engine. The application is written in LUA script and the file name is font_maker.lua. It is dependent on ImGui Plugin and EDITOR_FEATURES flag of compilation in the engine.

390 Chapter 23. Editors MBM Documentation, Release 3.1.f

23.3. Font Maker 391 MBM Documentation, Release 3.1.f

392 Chapter 23. Editors MBM Documentation, Release 3.1.f

23.3. Font Maker 393 MBM Documentation, Release 3.1.f

394 Chapter 23. Editors MBM Documentation, Release 3.1.f

23.3.1 First Steps With Font Maker Editor

For this example it will be used the Carlito-Regular truetype font. download Carlito-Regular.ttf From command line type: $ mini-mbm --scene font_maker.lua -w 1280 -h 800 --nosplash

Note: You might need to specify the whole path if it is not in your environment.

From menu, choose the desired height of font (default is 50) and click in Load Font: Change/add animation, change positions, space, size, colors as desired and click in Save Binary Font:

Note: For each font size, a png file will be created. The png is the image itself as a sprite sheet and the binary file contains the information (animation, shaders, position etc.) to be used in the engine. These two files are required.

download Carlito-Regular-50.png. Now a font could be loaded using font.

23.4 Particle Editor

Particle Editor is a editor to create particle behavior. One particle might have one image (texture) and one or more stage(s) (like animations but with extra control). The shader is specific for particle (see shader particle detail ). The application is written in LUA script and the file name is particle_editor.lua. It is dependent on ImGui Plugin and EDITOR_FEATURES flag of compilation in the engine.

23.4. Particle Editor 395 MBM Documentation, Release 3.1.f

23.4.1 First Steps With Particle Editor

For this example, we will use the folowing texture: download particle_flame.png From command line type: $ mini-mbm --scene particle_editor.lua -w 800 -h 600 --nosplash

Note: You might need to specify the whole path if it is not in your environment.

From menu, choose the File select New Particle From menu, choose the Image select Add Image and set particle_flame.png. Change the Number of particle, Direction and other options from Particle Options as desired. From menu, choose the File select Save Particle and select the file name. Now a particle could be loaded using particle.

23.5 Physic Editor

Physic Editor is a simple editor to be able to edit physics of sprite or mesh. The editor is dependent on ImGui Plugin and EDITOR_FEATURES flag of compilation in the engine. This editor is TODO for 3D objects: Simple load a sprite or mesh and edit, then save it. To run it from command line type: $ mini-mbm --scene physic_editor.lua -w 800 -h 600 --nosplash

396 Chapter 23. Editors MBM Documentation, Release 3.1.f

Figure 23.1: Carlito-Regular png generated

23.5. Physic Editor 397 MBM Documentation, Release 3.1.f

398 Chapter 23. Editors MBM Documentation, Release 3.1.f

23.6 Shader Editor

Shader Editor is a editor to change/add shader effect. Also is possible to add or change animation . This editor support all binaries types of mesh created by the engine. The application is written in LUA script and the file name is shader_editor.lua. It is dependent on ImGui Plugin and EDITOR_FEATURES flag of compilation in the engine.

23.6.1 First Steps With Shader Editor

For this example, create a sprite using sprite maker with the folowing texture:

23.6. Shader Editor 399 MBM Documentation, Release 3.1.f download crate.png From command line type: $ mini-mbm --scene shader_editor.lua -w 800 -h 600 --nosplash

Note: You might need to specify the whole path if it is not in your environment.

From menu, choose the File select Open Mesh and select the sprite created. From menu Shader Options select Pixel Shader -> bloom.ps and change the type for RECURSIVE_LOOP. Change others parameters as desired. From menu, choose the File select Save Mesh and select the file name. Now the mesh will have the shader configured in the binary file. Whenever be load, automatically will be set the shader with the configurations set in the editor.

23.7 Scene Editor

The Scene Editor is a simple 2D editor, meant to create scene in visual mode. This editor support all binaries types of mesh created by the engine.

400 Chapter 23. Editors MBM Documentation, Release 3.1.f

23.7. Scene Editor 401 MBM Documentation, Release 3.1.f

The application is written in LUA script and the file name is scene_editor2d.lua. It is dependent on ImGui Plugin, Box 2d and EDITOR_FEATURES flag of compilation in the engine.

23.7.1 First Steps With Scene Editor

For this example, create a sprite using sprite maker with the folowing texture:

download crate.png Then, after that, from command line type: $ mini-mbm --scene scene_editor2d.lua -w 800 -h 600 --nosplash

Note: You might need to specify the whole path if it is not in your environment.

From menu, choose the Mesh select Added Mesh and select the sprite created. Edit the position, scale, rotation or physics as you wish. . . From menu File select Save Scene -> my_scene.lua. Now you have the scene with all mesh(es) added. You can use the scene as point of start and do the necessary logic for your game. Here an example using the scene: tScene= require"my_scene" function onInitScene() mbm.setColor(1,1,1) tScene:load() end function onTouchDown(key,x,y) -- we are sure that box.spt exists in the file my_scene.lua local tMesh= tScene:addMesh('box.spt') tMesh.x, tMesh.y= mbm.to2dw(x,y) end function loop(delta) -- your logic here end

402 Chapter 23. Editors MBM Documentation, Release 3.1.f

23.7. Scene Editor 403 MBM Documentation, Release 3.1.f

404 Chapter 23. Editors MBM Documentation, Release 3.1.f

23.7. Scene Editor 405 MBM Documentation, Release 3.1.f

• Remarks – It was added only one sprite using the editor. – Therefore, when tScene:load() is called, only one sprite is added to the scene. – The others sprites are dynamic added as you can see in the code. – Besides the tMesh is local, the scene will hold the instance in the table tScene.tMeshesLoaded. That is why the object is not destroyed by gc from LUA. – When is added an object using tScene:addMesh, all configuration (position, scale, etc) are applied to the object added.

23.8 Asset Packager

The Asset Packager create asset from any type of files like image file, script file, music file, etc. The idea is to be able to make your assets in one unique file as mentioned before. Some people or company want to make the assets not so easy to access for many reasons. This editor might help on that. The application is written in LUA script and the file name is asset_packager.lua. It is dependent on ImGui Plugin and SQLite module.

23.8.1 First Steps With Packager

From command line type: $ mini-mbm --scene asset_packager.lua -w 800 -h 600 --nosplash

Note: You might need to specify the whole path if it is not in your environment.

From menu File select New Asset (from folder) and add it. Then from menu File select Save asset (to Database) and it is done! You can find more information about how to use your asset at SQLite module topic.

23.9 Tile Map Editor

Tile Map Editor is a 2D level editor meant to help you develop the content of your game by little bricks (tiles). One tile can be easily mapped through the world (in the size that you need) forming a 2D map. It is possible create layers and add some information as physics or objects/paths. The final map is an unique file + images ready to be used in the engine. The editor is dependent on ImGui Plugin and EDITOR_FEATURES flag of compilation in the engine.

406 Chapter 23. Editors MBM Documentation, Release 3.1.f

23.9. Tile Map Editor 407 MBM Documentation, Release 3.1.f

23.9.1 First Steps With Tile Map Editor

For this example it will be used a tileset from kenney: Open Tile Map indicating the script and typing the desired width and height: $ mini-mbm tilemap_editor.lua -w 1280 -h 800 --nosplash

Note: You might need to specify the whole path if it is not in your environment.

From Tile Map Options menu, click at Load Image(s) and select the tileset. Adjust the size of tile. In this example the tile size is 64x64 Pixel with no margin/ space.

Click in create button and got to the layer tab. Create a new layer and select the bricks (tiles) to make a layer like this:

408 Chapter 23. Editors MBM Documentation, Release 3.1.f

Then, create a new layer and try to do something like this:

The final result should be something like this: Save it and now the tilemap could be loaded using tile.

23.10 Texture Packer Editor

Texture Packer Editor is a 2D level editor meant to merge textures in a single file (sprite sheet) The editor is dependent on ImGui Plugin and EDITOR_FEATURES flag of compilation in the engine. This is a simple editor and the following image shows the editor making a single texture from severals images:

23.10. Texture Packer Editor 409 MBM Documentation, Release 3.1.f

410 Chapter 23. Editors MBM Documentation, Release 3.1.f

After that you just have to specify the file name to save the final image.

Table of Contents

• Modules – What is a Module?

* Creating and using Modules – Parsing OBJ wavefront

23.10. Texture Packer Editor 411 MBM Documentation, Release 3.1.f

412 Chapter 23. Editors CHAPTER 24

Modules

This section has a lot of modules available and where I hope would be useful for you! Even if you are learning LUA this is a interesting topic. Have fun!

24.1 What is a Module?

Module is like a library that can be loaded using require and has a single global name containing a table. All functions and variables are wrapped in to a table which acts as a namespace. Also, a well behaved module has necessary provisions to return this table on require. Module can be an .lua , .Dll or .so extension. A module can be an external extension for the project or not. For example, we can consider to build a module that will use some resources from this engine like a vec3, particle system, blend operation , etc. In another words, a modules can be an extension about what we have. The next topics will present some modules available.

24.1.1 Creating and using Modules

The way for LUA 5.2 create module is described bellow: First, we will create a file mymodule.lua with the following content:

local mymodule={}

function mymodule.foo() print("Hello World from module!") (continues on next page)

413 MBM Documentation, Release 3.1.f

(continued from previous page) end return mymodule

This is the basic concept of modules. Now to use this new module in the interactive interpreter: mymodule= require"mymodule" mymodule.foo() -- Hello World from module!

For more information you can consult ModulesTutorial.

24.2 Parsing OBJ wavefront

Next we will demonstrate how to import from OBJ format using a modules written in LUA. OBJ (or .OBJ) is a geometry definition file format first developed by Wavefront Technologies for its Advanced Visualizer animation package. The file format is open and has been adopted by other 3D graphics application vendors. The parser implemented here might NOT be the fully implementation but at least for this example works. To do that we will use the following module: OBJ_parser.lua You can download OBJ_parser.lua here. The following program will use the OBJ_parser.lua to parse an OBJ format and generate a mesh my_mesh.msh:

--import our module OBJ parser OBJ_parser= require"OBJ_parser"

--gray color background mbm.setColor(0.5,0.5,0.5)

function saveFrameToMeshFile(fileName,tFrame,bCentralize)

--meshDebug is used to create dynamically mesh in the engine. --For mesh it has to have at least one frame to be able to generate the

˓→mesh local stride=3 --stride only can be 3 or 2. it means (x,y,z) or

˓→(x,y) local tMesh= meshDebug:new() --new mesh debug to store the

˓→information about our mesh local indexFrame= tMesh:addFrame(stride) -- Add one frame with stride

˓→3 (x,y,z)

local has_normal= OBJ_parser:has_normal(tFrame) local has_texture= OBJ_parser:has_texture(tFrame)

print('Total subset:',#tFrame) print('Normal :',tostring(has_normal)) print('Uv :',tostring(has_texture))

-- Add vertex buffer first for i=1,#tFrame do (continues on next page)

414 Chapter 24. Modules MBM Documentation, Release 3.1.f

(continued from previous page) local tSubset= tFrame[i]

--add each subset on frame local indexSubset= tMesh:addSubSet(indexFrame) --add one subset

˓→for the first frame

-- The table expected is : {{x,y,z,u,v,nx,ny,nz},{x,y,z,u,v,nx,ny,nz}

˓→,{x,y,z,u,v,nx,ny,nz}, ...} if not tMesh:addVertex(indexFrame,indexSubset,tSubset.tVertex) then print("Error on add vertex buffer") return false end end

--Now we add index buffer and apply the texture for indexSubset=1,#tFrame do local tSubset= tFrame[indexSubset] if not tMesh:addIndex(indexFrame,indexSubset,tSubset.tIndex) then print("Error on add index buffer") return false end

--get texture (among the choices in the material) local sTexture= OBJ_parser:get_texture_from_material(tSubset.

˓→tMaterial)

--apply the texture to frame / subset if not tMesh:setTexture(indexFrame,indexSubset,sTexture) then print("Error on set texture!") return false end end

tMesh:setType('mesh') -- set it to mesh type

--Advanced options (draw mode). we do not need to set it, but it is

˓→available --tMesh:setModeDraw('TRIANGLES') -- TRIANGLES (default), TRIANGLE_STRIP,

˓→TRIANGLE_FAN, LINES, LINE_LOOP, LINE_STRIP, POINTS --tMesh:setModeCullFace('FRONT') -- FRONT (default), BACK, FRONT_AND_

˓→BACK --tMesh:setModeFrontFace('CCW') -- CCW (default), CW,

if bCentralize then print('centralizing mesh...') tMesh:centralize() --centralize all subsets before save end

if tMesh:save(fileName,not has_normal,not has_texture) then print("Mesh created successfully") return true else print("Failed to create Mesh!") return false end

(continues on next page)

24.2. Parsing OBJ wavefront 415 MBM Documentation, Release 3.1.f

(continued from previous page) end

function onInitScene()

tMesh= mesh:new('3D') -- our object which will load from binary file local bCentralize= true

local sFileNameMesh='Mech.msh' --output file (msh for mesh 3D) local sFileNameOBJ='Mech.obj' --input OBJ file

local bResult , tFrame= OBJ_parser:parse_file(sFileNameOBJ)

if bResult and saveFrameToMeshFile(sFileNameMesh,tFrame,bCentralize) then tMesh:load(sFileNameMesh) --all coordinate already in place end

--set up camera camera3d= mbm.getCamera('3D') camera3d:setPos(0,0,-500) camera3d:setFocus(0,0,0)

--needed to rotate our object tMouse= {x=0,y=0,clicked= false} end

function onTouchDown(key,x,y) tMouse.clicked= true tMouse.x=x tMouse.y=y end

function onTouchMove(key,x,y) if tMouse.clicked then local diff_X= tMouse.x-x local diff_Y= tMouse.y-y tMouse.x=x tMouse.y=y

--simple rotation based on mouse tMesh.ay= tMesh.ay+ math.rad(diff_X) tMesh.ax= tMesh.ax+ math.rad(diff_Y)

end end

function onTouchUp(key,x,y) tMouse.clicked= false end

function onTouchZoom(zoom) --Zoom the 3D object tMesh.sx= tMesh.sx+(0.2 * zoom) if tMesh.sx <= 0.2 then tMesh.sx= 0.2 end (continues on next page)

416 Chapter 24. Modules MBM Documentation, Release 3.1.f

(continued from previous page) tMesh.sy= tMesh.sx tMesh.sz= tMesh.sx end download.

Figure 24.1: Mesh 3D from OBJ

download OBJ. download material. download texture.

Table of Contents

• Module box2d – box2d Methods

* box2d new * box2d contact listener * box2d gravity * box2d iterations * box2d manifold * box2d world manifold * box2d multiply * box2d scale * box2d pause * box2d ray cast * box2d start * box2d queryAABB – box2d Body

* Bullet body * Character body * Damping options body * Density option body * Destroy body * Dynamic body * Filter options body * Force options body * Friction options body * Gravity options body * Inertia options body

24.2. Parsing OBJ wavefront 417 MBM Documentation, Release 3.1.f

* Mass options body * Kinematic body * Position options body * Restitution options body * Rotation options body * Sleep options body * State options body * Static body * Test point on body * Torque options body * Transform options body * Type options body * Velocity options body – box2d Joint

* Joints definition · Distance joint · Friction joint · Gear joint · Motor joint · Mouse joint · Prismatic joint · Pulley joint · Revolute joint · Rope joint · Weld joint · Wheel joint

* Creating joint · Distance joint · Friction joint · Gear joint · Motor joint · Mouse joint · Prismatic joint · Pulley joint · Revolute joint

418 Chapter 24. Modules MBM Documentation, Release 3.1.f

· Rope joint · Weld joint · Wheel joint

* Joint methods * Active options * Angular offset options * Anchor options * Correction factor options * Damping ratio options * Destroy joint * Force options * Frequency options * Get joint * Length options * Limit options * Linear offset options * Motor options * Reaction options * Target options

24.2. Parsing OBJ wavefront 419 MBM Documentation, Release 3.1.f

420 Chapter 24. Modules CHAPTER 25

Module box2d

Box 2D physics is an open source C++ engine for simulating rigid bodies in 2D. The library Box 2D is available as a plugin/module. The version and status of box2d can be found here.

Note: NOT all methods from Box 2D are wrapped. The most complicated methods have examples. It is desired to have more examples and methods wrapped, but for now, we consider it stable, faithful (to box2d) and good enough to develop a game. If you need some method which is not wrapped you could make a pull request for it.

Important: Box 2D works in units and to be able to do a right adaptation, the engine uses a scale factor. Always use function from box2d when related to position (locations). E.g: Prefer to use box2d:getPosition instead of the position of renderizable:getPosition. When transforming from 2d world to box2d consider box2d scale Example:

function onTouchDown(key,x,y) local box2d_scale= tPhysic:getScale() x,y= mbm.to2dw(x,y) x,y=x/ box2d_scale, y/ box2d_scale -- box2d x,y world can be used now. end

421 MBM Documentation, Release 3.1.f

25.1 box2d Methods

25.1.1 box2d new new(number * gravity_x, number * gravity_y number * scale_box_2d, number * velocityIterations, number * positionIterations, number * multiplyStep) Create a new instance of a box2d. Parameters • number – gravity in the axis x, default is 0.0. • number – gravity in the axis y, default is -90.8. • number – scale to apply in the world default is 10. • number – velocity iterations default is 10. • number – position iterations default is 3. • number – multiply step default is 1. Returns box2d table. Example:

require"box2d" local gravity_x=0 local gravity_y=-90.8 local scale_box_2d= 10 local velocityIterations= 10 local positionIterations=3 local multiplyStep=1

tPhysic= box2d:new(gravity_x,gravity_y,scale_box_2d,velocityIterations,

˓→positionIterations,multiplyStep) print('Gravity :', tPhysic:getGravity()) print('Scale :', tPhysic:getScale()) print('Velocity iteration :', tPhysic:getVelocityIterations()) print('Position iteration :', tPhysic:getPositionIterations()) print('Multiply step :', tPhysic:getMultiply())

Figure 25.1: Creating box2d instance Other example:

require"box2d" tPhysic= box2d:new() --no arguments needed (same as before) print('Gravity :', tPhysic:getGravity()) print('Scale :', tPhysic:getScale()) (continues on next page)

422 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) print('Velocity iteration :', tPhysic:getVelocityIterations()) print('Position iteration :', tPhysic:getPositionIterations()) print('Multiply step :', tPhysic:getMultiply())

Figure 25.2: Creating box2d instance without arguments

25.1.2 box2d contact listener

When bodies move around in the physics scene and bounce off each other, Box 2D will handle all the necessary collision detection and response so you don’t need to worry about that. But the whole point of making a physics game is that occasionally something should happen in the game as a result of some of the bodies hitting each other eg. when the player touches a monster he should die, or a ball bouncing on the ground should make a sound etc. A way to get this information back from the physics engine is using this abstracted contact listener im- plemented by the engine. There are four callbacks to handle collision detection in Box 2D and the engine implemented them all (abstracted way). BeginContact Called when two fixtures begin to touch. It has the following signature:

function onBeginContact(tMesh_a, tMesh_b)

end

EndContact Called when two fixtures cease to touch. It has the following signature:

function onEndContact(tMesh_a, tMesh_b)

end

PreSolve Called several times per step. Is called after a contact is updated. It has the following signature:

function onPreSolve(tMesh_a, tMesh_b, tManifold)

end

Note: This is called only for awake bodies. This is called even when the number of contact points is zero. This is not called for sensors.

25.1. box2d Methods 423 MBM Documentation, Release 3.1.f

If you set the number of contact points to zero, you will not get an EndContact callback. However, you may get a BeginContact callback the next step.

Note: b2Manifold from Box 2D has more member in the structure then this. The engine omit them.

See manifold table for more information. PostSolve Called several times per step. This lets you inspect a contact after the solver is finished. This is useful for inspecting impulses. It has the following signature:

function onPostSolve(tMesh_a, tMesh_b, tImpulse)

end

Note: This is only called for contacts that are touching, solid, and awake.

The b2ContactImpulse used by the engine has the following members:

tImpulse= { count=0, normalImpulses={[1]=0,[2]=0}, tangentImpulses={[1]=0,[2]=0}} setContactListener(function onBeginContact, function onEndContact, function onPreSolve, function onPostSolve) Parameters • function – onBeginContact callback (may be nil). • function – onEndContact callback (may be nil). • function – onPreSolve callback (may be nil). • function – onPostSolve callback (may be nil). Example: require"box2d" function print_manifold(tManifold) print('type:',tManifold.type) print('pointCount:',tManifold.pointCount) print('localNormal.x:',tManifold.localNormal.x) print('localNormal.x:',tManifold.localNormal.y) print('localPoint.x:',tManifold.localPoint.x) print('localPoint.x:',tManifold.localPoint.y)

for i=1,#tManifold.points do print('point:',i) print('\tlocalPoint.x:',tManifold.points[1].localPoint.x) print('\tlocalPoint.y:',tManifold.points[1].localPoint.y) print('\tnormalImpulse:',tManifold.points[1].normalImpulse) print('\ttangentImpulse:',tManifold.points[1].tangentImpulse) end print('\n') (continues on next page)

424 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) end

-- Callbacks function onBeginContact(tMesh_a, tMesh_b) print('\n') print('Begin contact:') print('Collision:',tMesh_a.name,tMesh_b.name) end function onEndContact(tMesh_a, tMesh_b) print('\n') print('End contact:') print('Collision:',tMesh_a.name,tMesh_b.name) end function onPreSolve(tMesh_a, tMesh_b, tManifold) print('\n') print('onPreSolve:') print('Collision:',tMesh_a.name,tMesh_b.name) print_manifold(tManifold) end function onPostSolve(tMesh_a, tMesh_b, tImpulse) print('\n') print('Impulse:') print('Impulse.count:', tImpulse.count) print('Impulse.normalImpulses[1]:', tImpulse.normalImpulses[1]) print('Impulse.normalImpulses[2]:', tImpulse.normalImpulses[2]) print('Impulse.tangentImpulses[1]:', tImpulse.tangentImpulses[1]) print('Impulse.tangentImpulses[2]:', tImpulse.tangentImpulses[2]) end -- End callbacks mbm.setColor(1,1,1) --set background color to white tPhysic= box2d:new() tShapeQuad= shape:new('2dw',-10, 500) tShapeCircle= shape:new('2dw',50, 300) tShapeGround= shape:new('2dw',0,-50) tShapeBigCircle= shape:new('2dw',200,800) tShapeQuad.name='rectangle' tShapeCircle.name='circle' tShapeBigCircle.name='big circle' tShapeGround.name='ground' tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapeBigCircle:create('circle',200,200) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addDynamicBody(tShapeBigCircle) tPhysic:addStaticBody(tShapeGround)

(continues on next page)

25.1. box2d Methods 425 MBM Documentation, Release 3.1.f

(continued from previous page) tPhysic:setContactListener(onBeginContact,onEndContact,onPreSolve,onPostSolve) camera= mbm.getCamera('2d') camera.y= 300

Figure 25.3: Example setContactListener box2d

25.1.3 box2d gravity getGravity Return gravity used by box2d. Returns number gravity x, number gravity y - of box2d. Example:

require"box2d" tPhysic= box2d:new() print('Gravity :', tPhysic:getGravity()) setGravity(number gravity_x, number gravity_y) Set a new gravity to box2d. Parameters • number – gravity in the axis x. • number – gravity in the axis y. Example:

require"box2d" tPhysic= box2d:new() tPhysic:setGravity(-3,95.8)

25.1.4 box2d iterations getVelocityIterations Return the velocity iterations used by box2d. Returns number velocity iterations - of box2d. Example:

require"box2d" tPhysic= box2d:new() print('Velocity iteration :', tPhysic:getVelocityIterations()) getPositionIterations Return the position iterations used by box2d. Returns number position iterations - of box2d. Example:

426 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

require"box2d" tPhysic= box2d:new() print('Velocity iteration :', tPhysic:getPositionIterations())

25.1.5 box2d manifold

A manifold table has the following structure: tManifold={ type='circles' or 'face_a' or 'face_b', pointCount=0, localNormal= {x=0, y=0}, localPoint= {x=0, y=0}, points={ [1]={ localPoint= {x=0, y=0}, normalImpulse=0, tangentImpulse=0 }, [2]={ localPoint= {x=0, y=0}, normalImpulse=0, tangentImpulse=0 }, } getManifolds(tBody, boolean * checkIsTouching, boolean * checkIsEnabled) param renderizable body. param boolean checkIsTouching instruct to check b2Contact::IsTouching() from Box2d (default if false). param boolean checkIsEnabled instruct to check b2Contact::IsEnabled() from Box2d (default if false). return table - manifold array. Example:

--this is not a real example function print_manifold(tManifold) print('type:', tManifold.type) print('pointCount:', tManifold.pointCount) print('localNormal.x:', tManifold.localNormal.x) print('localNormal.x:', tManifold.localNormal.y) print('localPoint.x:', tManifold.localPoint.x) print('localPoint.x:', tManifold.localPoint.y)

for i=1,#tManifold.points do print('point:', i) print('\tlocalPoint.x:', tManifold.points[1].localPoint.x) print('\tlocalPoint.y:', tManifold.points[1].localPoint.y) print('\tnormalImpulse:', tManifold.points[1].normalImpulse) print('\ttangentImpulse:', tManifold.points[1].tangentImpulse) end print('\n') (continues on next page)

25.1. box2d Methods 427 MBM Documentation, Release 3.1.f

(continued from previous page) end

--when is colliding otherwise will not have manifold. local tManifolds= tPhysic:getManifolds(tMesh_a) for i=1,#tManifolds do print('\n') print('Manifold index:',i) print_manifold(tManifolds[i]) end setManifolds(tManifolds) param table manifolds previously got using getManifolds method. Example: require"box2d" -- Callbacks function onPreSolve(tMesh_a, tMesh_b, tManifold) local tManifolds= tPhysic:getManifolds(tMesh_a) for i=1,#tManifolds do print('tManifold index', i) -- change something in the manifold end

tPhysic:setManifolds(tMesh_a,tManifolds) end

-- End callbacks mbm.setColor(1,1,1) --set background color to white tPhysic= box2d:new() tShapeQuad= shape:new('2dw',-10, 500) tShapeCircle= shape:new('2dw',50, 300) tShapeGround= shape:new('2dw',0,-50) tShapeBigCircle= shape:new('2dw',200,800) tShapeQuad.name='rectangle' tShapeCircle.name='circle' tShapeBigCircle.name='big circle' tShapeGround.name='ground' tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapeBigCircle:create('circle',200,200) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addDynamicBody(tShapeBigCircle) tPhysic:addStaticBody(tShapeGround) tPhysic:setContactListener(nil,nil,onPreSolve,nil)

428 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

25.1. box2d Methods 429

Figure 25.4: Example of output printing manifold structure. MBM Documentation, Release 3.1.f

Important: Do not modify the manifold unless you understand the internals of Box2D.

25.1.6 box2d world manifold

A manifold world table has the following structure: tWorldManifold= { normal= {x=0, y=0}, separations=[1]=0,[2]=0, points={[1]= {x=0, y=0}, [2]= {x=0, y=0}} getWorldManifold(tBody) param renderizable body. return table - world manifold array. Example: require"box2d" function print_manifold_world(tWorldManifold) print('normal.x:',tWorldManifold.normal.x) print('normal.x:',tWorldManifold.normal.y) print('separations[1]:',tWorldManifold.separations[1]) print('separations[2]:',tWorldManifold.separations[2])

for i=1,#tWorldManifold.points do print('point:',i) print('\tx:',tWorldManifold.points[1].x) print('\ty:',tWorldManifold.points[1].y) end print('\n') end

-- Callbacks function onPreSolve(tMesh_a, tMesh_b, tManifold) local tWorldManifolds= tPhysic:getWorldManifolds(tMesh_a) for i=1,#tWorldManifolds do print('WorldManifold index', i) print_manifold_world(tWorldManifolds[i]) end end

-- End callbacks mbm.setColor(1,1,1) --set background color to white tPhysic= box2d:new() tShapeQuad= shape:new('2dw',-10, 500) tShapeCircle= shape:new('2dw',50, 300) tShapeGround= shape:new('2dw',0,-50) tShapeBigCircle= shape:new('2dw',200,800) tShapeQuad.name='rectangle' tShapeCircle.name='circle' tShapeBigCircle.name='big circle' (continues on next page)

430 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) tShapeGround.name='ground' tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapeBigCircle:create('circle',200,200) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addDynamicBody(tShapeBigCircle) tPhysic:addStaticBody(tShapeGround) tPhysic:setContactListener(nil,nil,onPreSolve,nil) camera= mbm.getCamera('2d') camera.y= 300

Figure 25.5: Example of accessing world manifold

25.1.7 box2d multiply

Box 2D has a internal function which is called every step. This function is b2World::Step. The first argument is delta regarding the amount of time to simulate, this should not vary. The multiply parameter manipulates it doing literally a multiplication. See how the engine does:

world->Step(delta * multiplyStep, velocityIterations, positionIterations); getMultiply Return the multiply step used by box2d. Returns number multiply step - of box2d. Example:

require"box2d" tPhysic= box2d:new() print('Multiply step :', tPhysic:getMultiply()) setMultiply(number multiply_step) Set a new multiply step to box2d. Parameters number – multiply step to the box2d, default is 1.0. Example:

require"box2d" tPhysic= box2d:new() tPhysic:setMultiply(2)

25.1. box2d Methods 431 MBM Documentation, Release 3.1.f

25.1.8 box2d scale

The engine provide an internal scale to be able to adapt to any size of objects. The default value is 10. Here what the engine does internally to get values: for(auto mesh : box_2d->all_meshes) { auto body= mesh->body; if(body->typePhysics!= b2_staticBody) { const b2Vec2 pos= body->GetPosition(); mesh->position.x= pos.x * box_2d->scale; mesh->position.y= pos.y * box_2d->scale; mesh->angle.z= body->GetAngle(); } }

Here what the engine does internally to set values: auto body= mesh->body; const float scalePercentage= 1.0f/ box_2d->scale; const b2Vec2 position(mesh->position.x * scalePercentage, mesh->position.y * ˓→scalePercentage); body->SetTransform(position,mesh->angle.z); body->SetAwake(true);

Note: Setting scale to 1 makes the original behavior from box2d. It means that if you suspect that this scale is interfering in yours result then just set it to 1. getScale Return the scale used by box2d. Returns number scale - of box2d. Example:

require"box2d" tPhysic= box2d:new() print('Scale :', tPhysic:getScale()) setScale(number scale) Set a new scale to box2d. Parameters number – scale to the box2d. Example:

require"box2d" tPhysic= box2d:new() tPhysic:setScale(20)

432 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

25.1.9 box2d pause

pause Pause the simulation of box2d. Example:

require"box2d" tPhysic= box2d:new() tPhysic:pause()

25.1.10 box2d ray cast

Ray casting is often used to find out what objects are in a certain part of the world. A ray is just a straight line, and you can use a function provided by box2d to check if the line crosses a body. You can also find out what the normal is at the point the line hits the body. The points x_start, y_start and x_end, y_end are used to define a start, end and direction for the ray, and the max fraction specifies how far along the ray should be checked for an intersection. The following image may make this clearer.

Remark about fraction: A fraction of 0 means the start of line, fraction of 1 means the end of line and in this figure, the fraction of 2 would intersect the shape. A ray cast have the following signature:

function onRayCast(tMesh,x,y,nx,ny,fraction)

return fraction -- Zero means to end the ray cast end

Note: If you return 0 the ray cast is ended by box2d

rayCast(number x_start, number y_start, number x_end, number y_end, function onRayCastCallBack) Parameters

25.1. box2d Methods 433 MBM Documentation, Release 3.1.f

• number – x start point of the ray-cast. • number – y start point of the ray-cast. • number – x end point of the ray-cast. • number – y end point of the ray-cast. • function – call back function ray-cast. Example: require"box2d" --Ray cast callback function onRayCast(tMesh,x,y,nx,ny,fraction)

message= string.format('Crossed line: %s, at x:%g y:%g normal nx:%g ny:%g

˓→fraction:%g',tMesh.name,x,y,nx,ny,fraction) print(message) tMesh:setColor(0.7,0,0)

tShapePoint:setPos(x,y) tShapePoint.visible= true

return fraction --if you return 0 it means end of ray-cast end mbm.setColor(1,1,1) --set background color to white local gravity_x=0 local gravity_y=-9.8 --very slow to be able to see tPhysic= box2d:new(gravity_x,gravity_y) line_start= {x=-300, y= 200} line_end= {x= 300, y= 50} tLine= line:new('2dw') tLine:add({line_start.x,line_start.y,line_end.x,line_end.y}) tLine:setColor(0,0,1) -- Blue color tShapeQuad= shape:new('2dw',-20, 500) tShapeCircle= shape:new('2dw',50, 300) tShapeGround= shape:new('2dw',0,-50) tShapePoint= shape:new('2dw') tShapeQuad.name='rectangle' tShapeCircle.name='circle' tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapePoint:create('circle',20,20) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addStaticBody(tShapeGround) function loop(delta,fps) (continues on next page)

434 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) tShapeQuad:setColor(0.7,0,0.7) --reset the shape's color tShapeCircle:setColor(0.7,0,0.7) --reset the shape's color tShapePoint.visible= false local scale= tPhysic:getScale() local pStart= {x= line_start.x/ scale, y= line_start.y/ scale} local pEnd= {x= line_end.x/ scale, y= line_end.y/ scale}

tPhysic:rayCast(pStart.x,pStart.y,pEnd.x,pEnd.y,onRayCast) end

Figure 25.6: Performing ray cast box2d

25.1.11 box2d start start Start or resume the simulation of box2d. Example:

require"box2d" tPhysic= box2d:new() tPhysic:start() --resume the simulation

25.1.12 box2d queryAABB queryAABB(number lowerBound_x, number lowerBound_y, number upperBound_x, number upperBound_y, function onQueryAABBBox2d) Perform a AABB algorithm collision for all objects given the bound. It considers box2d scale. The callback is called in case of collision. It has to have the following signature: function onQueryAABBBox2d(tMesh) end

Example:

require"box2d" mbm.setColor(1,1,1) --set background color to white

function onQueryAABBBox2d(tMesh) print('Collide with:',tMesh.name) if tMesh.name =='circle' then tLine:setColor(1,0,0) -- red for circle elseif tMesh.name =='rectangle' then tLine:setColor(0,0,1) --blue for rectangle end end

(continues on next page)

25.1. box2d Methods 435 MBM Documentation, Release 3.1.f

(continued from previous page) local gravity_x=0 local gravity_y=-9.8 --very slow to be able to see

tPhysic= box2d:new(gravity_x,gravity_y) local lowerBound= {x=0, y=0} local upperBound= {x= 100, y= 100}

tLine= line:new('2dw') tLine:add( {lowerBound.x,lowerBound.y, lowerBound.x,upperBound.y, upperBound.x,upperBound.y, upperBound.x,lowerBound.y, lowerBound.x,lowerBound.y})

tLine:setColor(1,1,1) --white color means no colision

tShapeQuad= shape:new('2dw',-20, 500) tShapeCircle= shape:new('2dw',50, 300) tShapeGround= shape:new('2dw',0,-50)

tShapeQuad.name='rectangle' tShapeCircle.name='circle'

tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100)

tShapeGround:create('rectangle',500,20)

tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addStaticBody(tShapeGround)

function loop(delta) tPhysic:queryAABB(lowerBound.x,lowerBound.y,upperBound.x,upperBound.y,

˓→onQueryAABBBox2d) end

Figure 25.7: Performing query AABB colision

25.2 box2d Body

Bodies are the fundamental objects in the physics scene, but they are not what you actually see bouncing around and colliding with each other. Body represent the actual physics and for this engine, is a kind of glue beteween the actual body and any renderizable. You can think of a body as the properties of an object that you cannot see (draw) or touch (collide with) but the engine will copy the position and angle to the current object. The main properties of bodies for box2d are: Mass • how heavy it is

436 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

Velocity • how fast and which direction it’s moving Rotational inertia • how much effort it takes to start or stop spinning Angular velocity • how fast and which way it’s rotating Location • where it is. This is the position of object (x,y) Angle • which way it is facing. This is the angle az of object There are three types of body available for box2d: static, dynamic and kinematic. The engine implement them all. Any renderizable object can be added to box2d to be simulated with its physics properties, however, it makes sense for 2D objects. The body is based on physics properties which can be modified through setPhysics from meshDebug object.

25.2.1 Bullet body setBullet(tBody, boolean value) Should this body be treated like a bullet for continuous collision detection? Parameters • renderizable – body. • boolean – value. Example: tPhysic:setBullet(tBody,true)

25.2.2 Character body

A Character body is a dynamic body but using fixed rotation and do not allowing to sleep. Let’s see an example: require"box2d" mbm.setColor(1,1,1) --set background color to white local gravity_x=0 local gravity_y=-9.8 --very slow to be able to see tPhysic= box2d:new(gravity_x,gravity_y) tShapeQuad= shape:new('2dw',-310, 50) tShapeCircle= shape:new('2dw',0, 300) tShapeTriangle= shape:new('2dw', 50, 500)

(continues on next page)

25.2. box2d Body 437 MBM Documentation, Release 3.1.f

(continued from previous page) tShapeGround= shape:new('2dw',0,-50) tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapeTriangle:create('triangle',100) tShapeGround:create('rectangle',1000,20) local density, friction, restitution=1, 10, 0.8 -- restitution 0.1 -> 0.8 (super) tPhysic:addDynamicBody(tShapeCircle,density, friction, restitution) tPhysic:addKinematicBody(tShapeQuad) tPhysic:setLinearVelocity(tShapeQuad,2,0) -- move right 2 unit per second tPhysic:addDynamicBody(tShapeTriangle) tPhysic:setFixedRotation(tShapeTriangle,true) tPhysic:setSleepingAllowed(tShapeTriangle,false) tPhysic:addStaticBody(tShapeGround)

Figure 25.8: Creating character body

25.2.3 Damping options body setAngularDamping(tBody, number angular_damping) Parameters • renderizable – body. • number – angular damping. Example: tPhysic:setAngularDamping(tBody,15)

25.2.4 Density option body setDensity(tBody, number density, boolean * reset_mass) Set the density of all fixtures in the body. The optional flag reset_mass instruct to call b2Body::ResetMassData to update the body’s mass. Parameters • renderizable – body. • number – density. • boolean – reset mass flag, default is true. Example: tPhysic:setDensity(tBody,10,true)

438 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

25.2.5 Destroy body destroyBody(tBody) Parameters renderizable – body. Example: tPhysic:destroyBody(tBody)

Note: The engine will destroy the body in the next cycle.

25.2.6 Dynamic body

Dynamic body can move, spin and also be influenced by the gravity. addDynamicBody(renderizable mesh, number * density, number * friction, number * restitution, number * reduceX, number * reduceY, boolean * isSensor, boolean * isBullet) Create a new instance of a dynamic body. Parameters • renderizable – any type of mesh previouslly loaded according. • number – density default is 1.0. • number – friction default is 10.0. • number – restitution default is 0.1. • number – scale of reduction on x axis. default is 1.0 (real size). • number – scale of reduction on y axis. default is 1.0 (real size). • boolean – sensor flag (true or false) default is false. • boolean – bullet flag (true or false) default is false. Returns body table. For this example let’s create differents types of dynamic bodies:

require"box2d" mbm.setColor(1,1,1)

local gravity_x=0 local gravity_y=-9.8 --very slow to be able to see

tPhysic= box2d:new(gravity_x,gravity_y)

tShapeQuad= shape:new('2dw',-100, 720) tShapeCircle= shape:new('2dw',0, 500) tShapeTriangle= shape:new('2dw', 50, 300)

tShapeGround= shape:new('2dw',0,-50)

tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapeTriangle:create('triangle',100) (continues on next page)

25.2. box2d Body 439 MBM Documentation, Release 3.1.f

(continued from previous page)

tShapeGround:create('rectangle',1000,20)

local density, friction, restitution=1, 10, 0.8 -- restitution 0.1 -> 0.8 (super) tPhysic:addDynamicBody(tShapeCircle,density, friction, restitution)

density= 10 tPhysic:addDynamicBody(tShapeQuad,density) --heavy

tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround)

Figure 25.9: Creating three dynamic bodies

25.2.7 Filter options body setEnable(tBody, boolean value) Disable or enable a body changing internally the flag maskBits for each fixture in the body.

Parameters • renderizable – body. • boolean – value.

Example: require"box2d" mbm.setColor(1,1,1) local gravity_x=0 local gravity_y=-9.8 --very slow to be able to see tPhysic= box2d:new(gravity_x,gravity_y) tShapeQuad= shape:new('2dw',-100, 300) tShapeCircle= shape:new('2dw',0, 200) tShapeTriangle= shape:new('2dw', 50, 100) tShapeGround= shape:new('2dw',0,-50) tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapeTriangle:create('triangle',100) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addDynamicBody(tShapeQuad) --heavy tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround) (continues on next page)

440 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page)

tPhysic:setEnable(tShapeCircle,false)

Figure 25.10: Enable/disable box2d body

Internally it will change all fixture mask bits as is showing bellow:

const uint16 maskBits= enable? 0xFFFF:0; b2Fixture* fixtureList= body->GetFixtureList(); while (fixtureList) { b2Filter oldFilter(fixtureList->GetFilterData()); oldFilter.maskBits= maskBits; fixtureList->SetFilterData(oldFilter); fixtureList= fixtureList->GetNext(); }

setFilter(tBody * body, b2Filter filter) Set the contact filtering data. If body is not supplied it will set the filter for all bodies. The default values are 0x0001 for categoryBits and 0xFFFF for maskBits, or in other words every fixture says: ‘I am a thing and I will collide with every other thing,’ Parameters • renderizable – body (optional). • b2Filter – filter box2d. The filter shall have this members (default values):

tFilter= { categoryBits= 0x0001, -- I am (16 bits) maskBits= 0xFFFF, -- Collide with (16 bits) groupIndex=0} -- Group collision (override collision). (16 bits)

categoryBits The collision category bits. Normally you would just set one bit. maskBits The collision mask bits. This states the categories that this shape would accept for collision. groupIndex Collision groups allow a certain group of objects to never collide (negative) or always collide (positive). Zero means no collision group. Non-zero group filtering always wins against the mask bits. Example:

require"box2d" mbm.setColor(1,1,1)

local gravity_x=0 local gravity_y=-9.8 --very slow to be able to see

tPhysic= box2d:new(gravity_x,gravity_y)

(continues on next page)

25.2. box2d Body 441 MBM Documentation, Release 3.1.f

(continued from previous page) tFilterA= { categoryBits=1, -- I am A (0000-0001) maskBits= 132, -- Collide with C,D (1000-0100) groupIndex=0} -- Override collision tFilterB= { categoryBits=2, -- I am B (0000-0010) maskBits= 128, -- Collide with D (1000-0000) groupIndex=0} -- Override collision tFilterC= { categoryBits=4, -- I am C (0000-0100) maskBits= 129, -- Collide with A,D (1000-0001) groupIndex=0} -- Override collision tFilterD= { categoryBits= 128, -- I am D (1000-0000) maskBits= 255, -- Collide with all (1111-1111) groupIndex=0} -- Override collision tShapeQuad= shape:new('2dw',-20, 300) tShapeCircle= shape:new('2dw',0, 200) tShapeTriangle= shape:new('2dw', 50, 100) tShapeGround= shape:new('2dw',0,-50) tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapeTriangle:create('triangle',100) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround) tPhysic:setFilter(tShapeQuad, tFilterA) tPhysic:setFilter(tShapeCircle, tFilterB) tPhysic:setFilter(tShapeTriangle, tFilterC) tPhysic:setFilter(tShapeGround, tFilterD)

Figure 25.11: box2d setFilter

25.2.8 Force options body applyForce(tBody, number fx, number fy, number * wx, number *wy) Apply a gradual force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the angular velocity. This function always wake up the body. Parameters • renderizable – body. • number – fx force world, usually in Newtons (N).

442 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

• number – fy force world, usually in Newtons (N). • number – wx point the world position of the point of application. • number – wy point the world position of the point of application. Example: require"box2d" tPhysic= box2d:new() tPhysic:setScale(10) tShapeQuad= shape:new('2dw',-310, 50) tShapeCircle= shape:new('2dw',0, 300) tShapeGround= shape:new('2dw',0,-50) tShapeQuad:create('rectangle',40,40) tShapeCircle:create('circle',40,40) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addStaticBody(tShapeGround) function onKeyDown(key) local force= 20000 local wx,wy= tPhysic:getWorldCenter(tShapeQuad) --same effect as

˓→applyForceToCenter if mbm.getKeyCode('up') == key then -- in this example we keep pressing to up tPhysic:applyForce(tShapeQuad,0 ,force, wx, wy) elseif mbm.getKeyCode('left') == key then tPhysic:applyForce(tShapeQuad,-force,0, wx, wy) elseif mbm.getKeyCode('right') == key then -- and in the air right tPhysic:applyForce(tShapeQuad,force,0, wx, wy) end end

Figure 25.12: box2d applying force applyForceToCenter(tBody, number fx, number fy) Apply a force at a world point at the center of mass,

Parameters • renderizable – body. • number – fx force world, usually in Newtons (N). • number – fy force world, usually in Newtons (N).

Example: require"box2d" tPhysic= box2d:new() tPhysic:setScale(10) tShapeQuad= shape:new('2dw',-310, 50) (continues on next page)

25.2. box2d Body 443 MBM Documentation, Release 3.1.f

(continued from previous page) tShapeCircle= shape:new('2dw',0, 300) tShapeGround= shape:new('2dw',0,-50) tShapeQuad:create('rectangle',40,40) tShapeCircle:create('circle',40,40) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addStaticBody(tShapeGround) function onKeyDown(key) local force= 20000 if mbm.getKeyCode('up') == key then tPhysic:applyForceToCenter(tShapeQuad,0 ,force) elseif mbm.getKeyCode('left') == key then tPhysic:applyForceToCenter(tShapeQuad,-force,0) elseif mbm.getKeyCode('right') == key then tPhysic:applyForceToCenter(tShapeQuad,force,0) -- in this example we keep

˓→pressing to right end end

Figure 25.13: box2d applying force to center applyLinearImpulse(tBody, number fx, number fy, number * wx, number *wy) Apply an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of application is not at the center of mass. This wakes up the body.

Parameters • renderizable – body. • number – fx force world, usually in Newtons (N). • number – fy force world, usually in Newtons (N). • number – wx point the world position of the point of application. • number – wy point the world position of the point of application.

Example: require"box2d" tPhysic= box2d:new() tPhysic:setScale(10) tShapeQuad= shape:new('2dw',-310, 50) tShapeCircle= shape:new('2dw',0, 300) tShapeGround= shape:new('2dw',0,-50) tShapeQuad:create('rectangle',40,40) tShapeCircle:create('circle',40,40) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeCircle) (continues on next page)

444 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addStaticBody(tShapeGround) function onKeyDown(key) local force= 2000 local wx,wy= tPhysic:getWorldCenter(tShapeQuad) if mbm.getKeyCode('up') == key then tPhysic:applyLinearImpulse(tShapeQuad,0 ,force, wx, wy) elseif mbm.getKeyCode('left') == key then tPhysic:applyLinearImpulse(tShapeQuad,-force,0, wx, wy) elseif mbm.getKeyCode('right') == key then -- in this example we pressed once to

˓→right tPhysic:applyLinearImpulse(tShapeQuad,force,0, wx, wy) end end

Figure 25.14: box2d applying linear impulse applyLinearImpulseToCenter(tBody, number fx, number fy) Apply an impulse to the center of mass. This immediately modifies the velocity. Parameters • renderizable – body. • number – fx force world, usually in Newtons (N). • number – fy force world, usually in Newtons (N). Example: require"box2d" tPhysic= box2d:new() tPhysic:setScale(10) tShapeQuad= shape:new('2dw',-310, 50) tShapeCircle= shape:new('2dw',0, 300) tShapeGround= shape:new('2dw',0,-50) tShapeQuad:create('rectangle',40,40) tShapeCircle:create('circle',40,40) tShapeGround:create('rectangle',1000,20) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addStaticBody(tShapeGround) function onKeyDown(key) local force= 2000 if mbm.getKeyCode('up') == key then tPhysic:applyLinearImpulseToCenter(tShapeQuad,0 ,force) -- in this example we

˓→pressed once to up elseif mbm.getKeyCode('left') == key then tPhysic:applyLinearImpulseToCenter(tShapeQuad,-force,0) elseif mbm.getKeyCode('right') == key then tPhysic:applyLinearImpulseToCenter(tShapeQuad,force,0) (continues on next page)

25.2. box2d Body 445 MBM Documentation, Release 3.1.f

(continued from previous page) end end

Figure 25.15: box2d applying linear impulse to center applyAngularImpulse(tBody, number angular_impulse, boolean * wake) Apply an angular impulse.

Parameters • renderizable – body. • number – angular impulse in units of kg*m*m/s. • boolean – wake up the body (default is true).

Example: tPhysic:applyAngularImpulse(tBody,50,true)

25.2.9 Friction options body setFriction(tBody, number friction, boolean update_contact_list) Set the coefficient of friction. By default the engine also set the friction on contact list.

Parameters • renderizable – body. • number – friction coefficient. • boolean – update contact list flag (default is true).

Example: tPhysic:setFriction(tBody,5,true)

25.2.10 Gravity options body getGravityScale(tBody) Get the gravity scale of the body. Parameters renderizable – body. Returns number - gravity scale Example: local gravity_scale= tPhysic:getGravityScale(tBody) setGravityScale(tBody, number gravity_scale) Set the gravity scale of the body.

446 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

Parameters • renderizable – body. • number – gravity scale.

Example: tPhysic:setGravity(tBody,2.0)

25.2.11 Inertia options body getInertia(tBody) Get the rotational inertia of the body about the local origin. Parameters renderizable – body. Returns number - The rotational inertia, usually in kg-m^2. Example: local inertia= tPhysic:getInertia(tBody)

25.2.12 Mass options body getMass(tBody) Get the total mass of the body. Parameters renderizable – body. Returns number - the mass, usually in kilograms (kg). Example: local mass= tPhysic:getMass(tBody) setMass(tBody) The mass of the shape, usually in kilograms. Parameters • renderizable – body. • number – mass. Example: tPhysic:setMass(tBody,10)

25.2.13 Kinematic body

A kinematic body is very similar to a static body because, when it collides with a dynamic body it always holds its ground, and forces the dynamic body to retreat out of the way. The difference is that a kinematic body can move. addKinematicBody(renderizable mesh, number * density, number * friction, number * restitution, number * reduceX, number * reduceY, boolean * isSensor) Create a new instance of a kinematic body.

25.2. box2d Body 447 MBM Documentation, Release 3.1.f

Parameters • renderizable – any type of mesh previouslly loaded according. • number – density default is 1.0. • number – friction default is 10.0. • number – restitution default is 0.1. • number – scale of reduction on x axis. default is 1.0 (real size). • number – scale of reduction on y axis. default is 1.0 (real size). • boolean – sensor flag (true or false) default is false. Returns body table. For this example let’s create a kinematic body as a square:

require"box2d" mbm.setColor(1,1,1) --set background color to white

local gravity_x=0 local gravity_y=-9.8 --very slow to be able to see

tPhysic= box2d:new(gravity_x,gravity_y)

tShapeQuad= shape:new('2dw',-310, 50) tShapeCircle= shape:new('2dw',0, 500) tShapeTriangle= shape:new('2dw', 50, 300)

tShapeGround= shape:new('2dw',0,-50)

tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapeTriangle:create('triangle',100)

tShapeGround:create('rectangle',1000,20)

local density, friction, restitution=1, 10, 0.8 -- restitution 0.1 -> 0.8 (super) tPhysic:addDynamicBody(tShapeCircle,density, friction, restitution)

tPhysic:addKinematicBody(tShapeQuad) tPhysic:setLinearVelocity(tShapeQuad,2,0) -- move right 2 unit per second

tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround)

Figure 25.16: Creating kinematic body

25.2.14 Position options body getPosition(tBody) Get the body position NOT considering the box2d scale . Parameters renderizable – body. Returns number x - number - y .

448 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

Example: require"box2d" local x,y= tPhysic:getPosition(tBody) print('raw position :',x,y) print('scaled position:',tBody.x,tBody.y)

-- possible output using scale default (10) -- raw position : -2 7.929474 -- scaled position: -20 79.29475

25.2.15 Restitution options body setRestitution(tBody, number restitution, boolean update_contact_list) Set the coefficient of restitution. By default the engine also set the restitution on contact list. Parameters • renderizable – body. • number – restitution coefficient. • boolean – update contact list flag (default is true). Example: tPhysic:setRestitution(tBody,10,true)

25.2.16 Rotation options body setFixedRotation(tBody, boolean value) Set this body to have fixed rotation. This causes the mass to be reset. Parameters • renderizable – body. • boolean – value. Example: tPhysic:setFixedRotation(tBody,true)

25.2.17 Sleep options body setSleepingAllowed(tBody, boolean value) Disable sleeping on body. If you disable sleeping, the body will be woken. Parameters • renderizable – body. • boolean – value. Example: tPhysic:setSleepingAllowed(tBody,false)

25.2. box2d Body 449 MBM Documentation, Release 3.1.f

25.2.18 State options body isActive(tBody) Get the active state of the body.

Parameters renderizable – body. Returns boolean - is active

Example: local is_active= tPhysic:isActive(tBody) print('Body is active?:', tostring(is_active)) isAwake(tBody) Get the sleeping state of this body. Parameters renderizable – body. Returns boolean - is awake Example: local is_awake= tPhysic:isActive(tBody) print('Body is awake?:', tostring(is_awake)) setActive(tBody, boolean value) Set the active state of the body. An inactive body is not simulated and cannot be collided with or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive body are implicitly inactive. An inactive body is still owned by a b2World object and remains in the body list.

Parameters • renderizable – body. • boolean – value.

Example: tPhysic:setActive(tBody,true) setAwake(tBody, boolean value) Set the sleep state of the body. A sleeping body has very low CPU cost.

Parameters • renderizable – body. • boolean – value.

Example: tPhysic:setAwake(tBody,false)

450 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

25.2.19 Static body when a static body collides with a dynamic body, it always holds its ground, and forces the dynamic body to retreat out of the way. The static body will never move. addStaticBody(renderizable mesh, number * density, number * friction, number * reduceX, number * reduceY, boolean * isSensor) Create a new instance of a static body. Parameters • renderizable – any type of mesh previouslly loaded according. • number – density default is 0.0. • number – friction default is 0.3. • number – scale of reduction on x axis. default is 1.0 (real size). • number – scale of reduction on y axis. default is 1.0 (real size). • boolean – sensor flag (true or false) default is false. Returns body table. For this example let’s create a ground which represent the static body:

require"box2d" mbm.setColor(1,1,1)

local gravity_x=0 local gravity_y=-9.8 --very slow to be able to see

tPhysic= box2d:new(gravity_x,gravity_y)

tShapeQuad= shape:new('2dw',-20, 720) tShapeCircle= shape:new('2dw',100, 500) tShapeTriangle= shape:new('2dw',50, 300)

tShapeGround= shape:new('2dw',0,-50)

tShapeQuad:create('rectangle',100,100) tShapeCircle:create('circle',100,100) tShapeTriangle:create('triangle',100)

tShapeGround:create('rectangle',500,20)

tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround)

Figure 25.17: Creating a static body named tShapeGround

25.2.20 Test point on body testPoint(tBody, number x, number y) Test a point for containment in all fixture from a body.

25.2. box2d Body 451 MBM Documentation, Release 3.1.f

It considers box2d scale. Parameters • renderizable – body. • number – x in world coordinates. • number – y in world coordinates. Returns boolean - hit any fixture Example:

require"box2d" mbm.setColor(1,1,1)

tPhysic= box2d:new() tPhysic:setScale(15)

tShapeQuad= shape:new('2dw',-20,-20) tShapeQuad:create('rectangle', 100,200) tPhysic:addStaticBody(tShapeQuad)

function onTouchMove(key,x,y) x,y= mbm.to2dw(x,y) if tPhysic:testPoint(tShapeQuad,x,y) then tShapeQuad:setColor(0.8,0,0) else tShapeQuad:setColor(0.8,0,0.8) end end

Figure 25.18: testPoint box2d

25.2.21 Torque options body

applyTorque(tBody, number torque, boolean * wake) Apply a torque. This affects the angular velocity without affecting the linear velocity of the center of mass. Parameters • renderizable – body. • number – torque about the z-axis (out of the screen), usually in N-m. • boolean – wake up the body (default is true). Example:

tPhysic:applyTorque(tBody,50,true)

25.2.22 Transform options body

Important: You should consider the box2d scale to everything related to any transform method to real world and vice versa.

452 Chapter 25. Module box2d MBM Documentation, Release 3.1.f setTransform(tBody, number * x, number * y, number * angle) Set a new position of the body’s origin and rotation. Manipulating a body’s transform may cause non-physical behavior but sometimes it is desired. If not supplied any of arguments it will use the own position and angle.

Parameters • number – x position of body. • number – y position of body. • number – angle z of body.

Example: require"box2d" tPhysic= box2d:new() tPhysic:setScale(10) -- setTransform method considers box2d scale. tShapeQuad= shape:new('2dw') tShapeQuad:create('rectangle',100,100) tPhysic:addDynamicBody(tShapeQuad) tShapeQuad:setPos(55,33) -- will not change the position since box2d is in control tShapeQuad.az= math.rad(15) -- tilt 15 degree tPhysic:setTransform(tShapeQuad) -- Now we say to box 2d to use this new position and

˓→z angle -- tPhysic:setTransform(tShapeQuad,55,33,math.rad(15)) --same as above

Important: This method is the only one that considers box2d scale making a automatically calculation for the input. Internally it does the following code: const float scalePercentage= 1.0f/ box2d->scale; const b2Vec2 position(newPosition->x * scalePercentage,newPosition->y * ˓→scalePercentage); body->SetTransform(position,newAngleDegree); getWorldCenter(tBody) Get the world position of the center of mass. Parameters renderizable – body. Returns number x - number - y . Example: require"box2d" tPhysic= box2d:new() tPhysic:setScale(1) tShapeQuad= shape:new('2dw',45,38) --put some place different from origin tShapeQuad:create('rectangle',100,100) (continues on next page)

25.2. box2d Body 453 MBM Documentation, Release 3.1.f

(continued from previous page) tPhysic:addStaticBody(tShapeQuad) local px, py= tPhysic:getWorldCenter(tShapeQuad) tShapePoint= shape:new('2dw') tShapePoint:create('circle',10,10) tShapePoint:setPos(px,py) tShapePoint:setColor(0,0,1) -- our blue point print('px:',px,'py:',py)

Figure 25.19: box2d getWorldCenter method getWorldPoint(tBody, number x, number y) The function getWorldPoint is used to convert a location relative to the body (body coordinates) into world coordinates. Parameters • renderizable – body. • number – x point on the body measured relative the the body’s origin. • number – y point on the body measured relative the the body’s origin. Returns number x - number - y . Example: require"box2d" tPhysic= box2d:new() tPhysic:setScale(1) tShapeQuad= shape:new('2dw',66,99) --put some place different from origin tShapeQuad:create('rectangle',100,100) tShapeQuad.az= math.rad(10) -- tilt 10 degree tPhysic:addStaticBody(tShapeQuad) local x, y= 50,50 -- we know the size local px, py= tPhysic:getWorldPoint(tShapeQuad,x,y) tShapePoint= shape:new('2dw') tShapePoint:create('circle',10,10) tShapePoint:setPos(px,py) (continues on next page)

454 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) tShapePoint:setColor(0,0,1) -- our blue point print('px:',px,'py:',py)

Figure 25.20: box2d getWorldPoint method getWorldVector(tBody, number x, number y) Get the world coordinates of a vector given the local coordinates.

Parameters • renderizable – body. • number – x local fixed in the body. • number – y local fixed in the body. Returns number x - number - y .

Example: require"box2d" tPhysic= box2d:new() tPhysic:setScale(1) tShapeQuad= shape:new('2dw',50,50) tShapeQuad:create('rectangle',100,100) tShapeQuad.az= math.rad(180) -- tilt 180 degree tPhysic:addStaticBody(tShapeQuad) local x, y= 100,100 local px, py= tPhysic:getWorldVector(tShapeQuad,x,y) tShapePoint= shape:new('2dw') tShapePoint:create('circle',10,10) tShapePoint:setPos(px,py) tShapePoint:setColor(0,0,1) -- our blue point print('px:',px,'py:',py)

25.2. box2d Body 455 MBM Documentation, Release 3.1.f

Figure 25.21: box2d getWorldVector method getLocalPoint(tBody) Gets a local point relative to the body’s origin given a world point.

Parameters • renderizable – body. • number – x world coordinates. • number – y world coordinates. Returns number x - number - y corresponding local point relative to the body’s origin.

Example: local x,y= tPhysic:getLocalPoint(tBody,10,5) getLocalCenter(tBody) Get the local position of the center of mass. Parameters renderizable – body. Returns number x - number - y local center. Example: local x,y= tPhysic:getLocalCenter(tBody)

25.2.23 Type options body setType(tBody, string type)

456 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

Set the type of body. This may alter the mass and velocity. Acceptable types are:static, kinematic or dynamic.

Parameters • renderizable – body. • string – type of body.

Example: tPhysic:setType(tBody,'static') getType(tBody) Retrieve the body type. The possible types are:static, kinematic or dynamic. Parameters renderizable – body. Returns string - type Example: local type_body= tPhysic:getType(tBody)

25.2.24 Velocity options body getLinearVelocity(tBody) Get the linear velocity of the center of mass.

Parameters renderizable – body. Returns number x - number - y the linear velocity of the center of mass.

Example: local lx,ly= tPhysic:getLinearVelocity(tBody) getAngularVelocity(tBody) Get the angular velocity. Parameters renderizable – body. Returns number - angular velocity in radians/second. Example: local angular_velocity= tPhysic:getAngularVelocity(tBody) setAngularVelocity(tBody, number omega) Set the angular velocity. Parameters • renderizable – body. • number – omega. the new angular velocity in radians/second. Example:

25.2. box2d Body 457 MBM Documentation, Release 3.1.f

local omega= math.rad(15) tPhysic:setAngularVelocity(tBody,omega) setLinearVelocity(tBody, number x, number y) Set the linear velocity of the center of mass. Parameters • renderizable – body. • number – x. the new linear velocity of the center of mass. • number – y. the new linear velocity of the center of mass. Example: tPhysic:setLinearVelocity(tBody,50,2)

25.3 box2d Joint

Box2D has a lot of joints that can be used to connect two bodies. These joints mostly are to be used to simulate the interaction between objects to form hinges, pistons, ropes, wheels, pulleys, vehicles, chains, etc. Learning how to use joints effectively helps to create a more engaging and interesting scene. The method used to create a joint is defined here. Joint common properties Although each joint has a different behavior, they have some properties in common. Here are the properties which are common to build each joint:

tJoint= { name='my joint name', collideConnected= false, }

Also for some joints you have to need to specify details for the specific type of joint that you are making. This commonly includes an anchor point on each body, limits on the range of movement, and motor settings. Anchor points Typically a point on each body is given as the location around which the bodies must interact. Depending on the joint type, this point will be the center of rotation, the locations to keep a certain distance apart, etc. Joint limits Revolute and prismatic joints can be given limits, which places a restriction on how far the bodies can rotate or slide. Joint motors Revolute, prismatic and line (wheel) joints can be given motor settings, which means that instead of spinning or sliding around freely, the joint acts as if it had it’s own power source. The motor is given a maximum force or torque, and this can be used in combination with a target velocity to spin or slide bodies in relation to each other.

25.3.1 Joints definition

Let’s see the joints available for box2d and its characteristics:

458 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

Distance joint

Distance • A point on each body will be kept at a fixed distance apart. This requires defining an anchor point on both bodies and the non-zero length of the distance joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when saving and loading a game.

Warning: Do not use a zero or short length.

Here the table definition:

tJoint= { name='distance', localAnchorA= {x= 0.0, y= 0.0}, localAnchorB= {x= 0.0, y= 0.0}, length= 1.0, frequencyHz= 0.0, dampingRatio= 0.0, collideConnected= false }

Hint: The engine accept two extras parameters to initialize the joint definition in box2d. (see b2DistanceJointDef::Initialize) These parameters Initialize localAnchorA, localAnchorB and length. You should consider the box2d scale for localAnchorA, localAnchorB, length, anchor1 and anchor2.

The extra parameters for this joint table are:

pos_1= tPhysic:getPosition(mesh_1) -- position from box2d might be

˓→different if is there scale pos_2= tPhysic:getPosition(mesh_2) -- position from box2d might be

˓→different if is there scale tJoint= { anchor1= {x= pos_1.x, y= pos_1.y}, -- default values anchor2= {x= pos_2.y, y= pos_2.y}, -- default values -- others parameters from table definition ... }

Of course if you pass any of localAnchorA, localAnchorB and length it will be overridden.

Friction joint

Friction • Reduces the relative motion between the two bodies. Here the table definition:

25.3. box2d Joint 459 MBM Documentation, Release 3.1.f

tJoint= { name='friction', localAnchorA= {x=0, y=0}, localAnchorB= {x=0, y=0}, maxForce= 0.0, maxTorque= 0.0, collideConnected= false }

Hint: The engine accept one extra parameter to initialize the joint definition in box2d. (see b2FrictionJointDef::Initialize) This parameter Initialize localAnchorA and localAnchorB. You should consider the box2d scale for localAnchorA, localAnchorB, and anchor.

The extra parameter for this joint is described bellow:

tJoint= { anchor= {x=0, y=0}, -- Default value -- others parameters from table definition ... }

Of course if you pass any of localAnchorA or localAnchorB it will be overridden.

Gear joint

Gear • Controls two other joints (revolute or prismatic) so that the movement of one affects the other. This definition requires two existing revolute or prismatic joints (any combination will work). Here the table definition:

tJoint= { name='gear', ratio= 1.0, indexA= absolute_index_joint_A, indexB= absolute_index_joint_B, collideConnected= false }

Note: It is mandatory the body 1 and 2 have joint. The index have preference, in other words, the engine will look first for the absolute index.

460 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

Motor joint

Motor • Controls the relative motion between two bodies. A typical usage is to control the movement of a dynamic body with respect to the ground. Here the table definition:

tJoint= { name='motor', linearOffset={x=0, y=0}, angularOffset= 0.0, maxForce= 1.0, maxTorque= 1.0, correctionFactor= 0.3, collideConnected= false, }

Mouse joint

Mouse • Pulls a point on one body to a location in the world. This requires a world target point, tuning parameters, and the time step. Here the table definition:

tJoint= { name='mouse', target= {x=0, y=0}, maxForce= 0.0, frequencyHz= 5.0, dampingRatio= 0.7, collideConnected= false, }

Note: Mouse joint does not need a second body however to keep the signature, we pass it twice on create joint method.

Prismatic joint

Prismatic • The relative rotation of the two bodies is fixed, and they can slide along an axis. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game. Here the table definition:

25.3. box2d Joint 461 MBM Documentation, Release 3.1.f

tJoint= { name='prismatic', localAnchorA= {x=0, y=0}, localAnchorB= {x=0, y=0}, localAxisA= {x=1, y=0}, -- Must be normalized referenceAngle= 0.0, enableLimit= false, lowerTranslation= 0.0, upperTranslation= 0.0, enableMotor= false, maxMotorForce= 0.0, motorSpeed= 0.0, collideConnected= false, }

Hint: The engine accept two extras parameters to initialize the joint definition in box2d. (see b2PrismaticJointDef::Initialize) These parameters Initialize localAnchorA, localAnchorB and localAxisA. You should consider the box2d scale for localAnchorA, localAnchorB, and anchor.

The extra parameters for this joint table are:

tJoint= { anchor= {x=0, y=0}, -- Default value. It initialize localAnchorA

˓→and localAnchorB axis= {x=0, y=1}, --Default value. It initialize localAxisA.

˓→must be normalized -- others parameters from table definition ... }

Of course if you pass any of localAnchorA, localAnchorB and localAxisA it will be overridden.

Pulley joint

Pulley • A point on each body will be kept within a certain distance from a point in the world. This requires two ground anchors, two dynamic body anchor points, and a pulley ratio. Here the table definition:

tJoint= { name='pulley', groundAnchorA= {x=-1.0, y= 1.0}, groundAnchorB= {x= 1.0, y= 1.0}, localAnchorA= {x=-1.0, y= 0.0}, localAnchorB= {x= 1.0, y= 0.0}, lengthA= 0.0, (continues on next page)

462 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) lengthB= 0.0, ratio= 1.0, collideConnected= true, }

Hint: The engine accept extras parameters to initialize the joint definition in box2d. (see b2PulleyJointDef::Initialize) These parameters Initialize localAnchorA, localAnchorB, groundAnchorA, groundAnchorB, lengthA and lengthB. You should consider the box2d scale for localAnchorA, localAnchorB, groundAnchorA, groundAnchorB, lengthA and lengthB.

The extra parameters for this joint table are:

tJoint= { anchorA= {x= body_a.x, y= body_a.y}, -- default values comes from

˓→body a anchorB= {x= body_b.x, y= body_b.y}, -- default values comes from

˓→body b -- others parameters from table definition ... }

Of course if you pass any of localAnchorA, localAnchorB, groundAnchorA, groundAnchorB, lengthA and lengthB it will be overridden.

The pulley connects two bodies to ground and to each other. As one body goes up, the other goes down. The total length of the pulley rope is conserved according to the initial configuration: lengthA + lengthA == constant. You can supply a ratio that simulates a block and tackle. This causes one side of the pulley to extend faster than the other. At the same time the constraint force is smaller on one side than the other: lengthA + ratio * lengthB == constant

Revolute joint

Revolute • A hinge or pin, where the bodies rotate about a common point. This requires defining an anchor point where the bodies are joined. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body’s origin rather than the center of mass because: 1. you might not know where the center of mass will be. 2. if you add/remove shapes from a body and recompute the mass,the joints will be broken. Here the table definition:

25.3. box2d Joint 463 MBM Documentation, Release 3.1.f

tJoint= { name='revolute', localAnchorA={x= 0.0, y= 0.0}, localAnchorB={x= 0.0, y= 0.0}, referenceAngle= 0.0, lowerAngle= 0.0, upperAngle= 0.0, maxMotorTorque= 0.0, motorSpeed= 0.0, enableLimit= false, enableMotor= false, collideConnected= false, }

Hint: The engine accept one extra parameter to initialize the joint definition in box2d. (see b2RevoluteJointDef::Initialize) This parameter Initialize localAnchorA, localAnchorB and referenceAngle. You should consider the box2d scale for localAnchorA, localAnchorB and anchor.

The extra parameter for this joint is described bellow:

pos_mesh_2= tPhysic:getPosition(mesh_2) tJoint= { anchor= {x= pos_mesh_2.x, y= pos_mesh_2.y}, -- Default value,

˓→position from mesh '2' -- others parameters from table definition ... }

Of course if you pass any of localAnchorA, localAnchorB or referenceAngle it will be overridden.

Rope joint

Rope • A point on each body will be constrained to a maximum distance apart. This requires two body anchor points and a maximum lengths. Here the table definition:

tJoint= { name='rope', localAnchorA={x =-1.0, y= 0.0}, localAnchorB={x= 1.0, y= 0.0}, maxLength= 0.0, collideConnected= false, }

464 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

Warning: The maximum length of the rope must be larger than b2_linearSlop (0.005) or the joint will have no effect.

Weld joint

Weld • Holds the bodies at the same orientation. You need to specify local anchor points where they are attached and the relative body angle. The position of the anchor points is important for computing the reaction torque. Here the table definition: tJoint= { name='weld', localAnchorA={x= 0.0, y= 0.0}, localAnchorB={x= 0.0, y= 0.0}, referenceAngle= 0.0, frequencyHz= 0.0, dampingRatio= 0.0, collideConnected= false, }

Hint: The engine accept one extra parameter to initialize the joint definition in box2d. (see b2WeldJointDef::Initialize) This parameter Initialize localAnchorA, localAnchorB and referenceAngle. You should consider the box2d scale for localAnchorA, localAnchorB, and anchor.

The extra parameter for this joint is described bellow:

pos_mesh_2= tPhysic:getPosition(mesh_2) tJoint= { anchor= {x= pos_mesh_2.x, y= pos_mesh_2.y}, -- Default value,

˓→position from mesh '2' -- others parameters from table definition ... }

Of course if you pass any of localAnchorA, localAnchorB or referenceAngle it will be overridden.

Wheel joint

Wheel • A combination of revolute and prismatic joints, useful for modeling vehicle suspension. (old line joint). This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game.

25.3. box2d Joint 465 MBM Documentation, Release 3.1.f

Here the table definition: tJoint= { name='wheel', localAnchorA={x=0, y=0}, localAnchorB={x=0, y=0}, localAxisA={x=1, y=0}, enableMotor= false, maxMotorTorque= 0.0, motorSpeed= 0.0, frequencyHz= 2.0, dampingRatio= 0.7, collideConnected= false, }

Hint: The engine accept two extras parameters to initialize the joint definition in box2d. (see b2WheelJointDef::Initialize) These parameters Initialize localAnchorA, localAnchorB and localAxisA. You should consider the box2d scale for localAnchorA, localAnchorB, and anchor.

The extra parameters for this joint table are:

tJoint= { anchor= {x=0, y=0}, -- Default value. It initialize localAnchorA

˓→and localAnchorB axis= {x=0, y=1}, --Default value. It initialize localAxisA. -- others parameters from table definition ... }

Of course if you pass any of localAnchorA, localAnchorB and localAxisA it will be overridden.

25.3.2 Creating joint joint(tBody_A, tBody_B, tJoint) The signature is always like this. The first body then the second and the joint table definition. Parameters • renderizable – first body. • renderizable – second body. • table – joint definition. see box2d joint Returns number - index absolute of joint. (zero is error).

Note: The result for this method is a number indicating the absolute index in the engine for this joint. This absolute index can be invalid after destroying joint. To get the joint use getJoint method and prefer to pass the absolute index.

466 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

Distance joint

Next, an example of joint using distance joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tShapeQuad= shape:new('2dw',-200, 720) tShapeCircle1= shape:new('2dw',-100, 400) tShapeCircle2= shape:new('2dw', 100, 400) tShapeTriangle= shape:new('2dw', 50, 300) tShapeGround= shape:new('2dw',0,-50) tShapeWall= shape:new('2dw',300,100) tShapeQuad:create('rectangle',100,100) tShapeCircle1:create('circle',100,100) tShapeCircle2:create('circle',80,80) tShapeTriangle:create('triangle',100) tShapeGround:create('rectangle',1000,20) tShapeWall:create('rectangle',20,200) local density, friction, restitution= 0.5, 10, 1.0 tPhysic:addDynamicBody(tShapeCircle1,density, friction, restitution) tPhysic:addDynamicBody(tShapeCircle2,density, friction, restitution) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround) tPhysic:addStaticBody(tShapeWall) tJoint= { name='distance', localAnchorA= {x= 0.0, y= 0.0}, localAnchorB= {x= 0.0, y= 0.0}, --length: we are omitting the distance let the engine calculate it frequencyHz= 0.0, dampingRatio= 0.0, collideConnected= false } local indexJoint= tPhysic:joint(tShapeCircle1,tShapeCircle2,tJoint)

Figure 25.22: Distance joint

Friction joint

Next, an example of joint using friction joint table.

25.3. box2d Joint 467 MBM Documentation, Release 3.1.f

require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tShapeQuad= shape:new('2dw',-200, 720) tShapeCircle1= shape:new('2dw',-100, 400) tShapeCircle2= shape:new('2dw', 100, 400) tShapeTriangle= shape:new('2dw', 50, 300) tShapeGround= shape:new('2dw',0,-50) tShapeWall= shape:new('2dw',300,100) tShapeQuad:create('rectangle',100,100) tShapeCircle1:create('circle',100,100) tShapeCircle2:create('circle',80,80) tShapeTriangle:create('triangle',100) tShapeGround:create('rectangle',1000,20) tShapeWall:create('rectangle',20,200) local density, friction, restitution= 0.5, 10, 1.0 tPhysic:addDynamicBody(tShapeCircle1,density, friction, restitution) tPhysic:addDynamicBody(tShapeCircle2,density, friction, restitution) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround) tPhysic:addStaticBody(tShapeWall) tJoint= { name='friction', localAnchorA= {x=0, y=0}, localAnchorB= {x=0, y=0}, maxForce= 5000.0, maxTorque= 5000.0, collideConnected= true } local indexJoint= tPhysic:joint(tShapeQuad,tShapeGround,tJoint)

Figure 25.23: Friction joint

Gear joint

Next, an example of joint using gear joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new()

(continues on next page)

468 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) tShapeBoxMain= shape:new('2dw',0, 100) tShapeBoxLeft= shape:new('2dw',-50, 150) tShapeBoxRight= shape:new('2dw',50, 150) tShapeCircle= shape:new('2dw',400, 500) tShapeGround= shape:new('2dw',0,40) tShapeRightWall= shape:new('2dw',450,0) tShapeBoxMain:create('rectangle',100,100) tShapeBoxLeft:create('rectangle',50,50) tShapeBoxRight:create('rectangle',50,50) tShapeCircle:create('circle',100,100) tShapeGround:create('rectangle',1000,20) tShapeRightWall:create('rectangle',20,400) tShapeGround.az= math.rad(2) --tilt a litle bit tPhysic:addDynamicBody(tShapeBoxMain) tPhysic:addDynamicBody(tShapeBoxLeft) tPhysic:addDynamicBody(tShapeBoxRight) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addStaticBody(tShapeGround) tPhysic:addStaticBody(tShapeRightWall) local size_box= {x=0, y=0} size_box.x, size_box.y= tShapeBoxMain:getSize() size_box.x= size_box.x/ tPhysic:getScale() --consider the box2d scale size_box.y= size_box.y/ tPhysic:getScale() --consider the box2d scale local corner_box_left= {x= size_box.x/2,y= size_box.y/2} -- corner of the

˓→box (top,left) local corner_box_right= {x=-size_box.x/2,y= size_box.y/2} -- corner of the

˓→box (top,right) --[[ corner box top left -> *------* <- corner_box top,right | main | | box | |------| ]] tJointLeft= { name='revolute', localAnchorA= corner_box_left, --in the corner of the box A (top,left) localAnchorB= {x=0, y=0}, --in the center of the left box referenceAngle= tShapeBoxLeft.az- tShapeBoxMain.az, lowerAngle= math.rad(-90), -- no effect since enableLimit is false upperAngle= math.rad(45), -- no effect since enableLimit is false maxMotorTorque= 10000.0, motorSpeed= 10.0, enableLimit= false, enableMotor= false, (continues on next page)

25.3. box2d Joint 469 MBM Documentation, Release 3.1.f

(continued from previous page) collideConnected= false, } tJointRight= { name='revolute', localAnchorA= corner_box_right, --in the corner of the box A (top,right) localAnchorB= {x=0, y=0}, --in the center of the rigth box referenceAngle= tShapeBoxLeft.az- tShapeBoxMain.az, lowerAngle= math.rad(-90), -- no effect since enableLimit is false upperAngle= math.rad(45), -- no effect since enableLimit is false maxMotorTorque= 10000.0, motorSpeed= 10.0, enableLimit= false, enableMotor= false, collideConnected= false, } local indexA= tPhysic:joint(tShapeBoxMain,tShapeBoxLeft,tJointLeft) local indexB= tPhysic:joint(tShapeBoxMain,tShapeBoxRight,tJointRight) tJLeft= tPhysic:getJoint(tShapeBoxLeft) tJRight= tPhysic:getJoint(tShapeBoxRight) tJoint= { name='gear', ratio= 1.0, indexA= indexA, indexB= indexB, collideConnected= false } local indexJointGear= tPhysic:joint(tShapeBoxLeft,tShapeBoxRight,tJoint)

Figure 25.24: Gear joint

Motor joint

Next, an example of joint using motor joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tShapeQuad= shape:new('2dw',-200, 520) tShapeCircle1= shape:new('2dw',-80, 400) tShapeCircle2= shape:new('2dw', 100, 400) tShapeTriangle= shape:new('2dw', 50, 300) tShapeGround= shape:new('2dw',0,-300) tShapeRightWall= shape:new('2dw',450,0) tShapeLeftWall= shape:new('2dw',-450,0) (continues on next page)

470 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) tShapeQuad:create('rectangle',100,100) tShapeCircle1:create('circle',200,200,10) --low resolution of the circle tShapeCircle2:create('circle',80,80) tShapeTriangle:create('triangle',100) tShapeGround:create('rectangle',1000,20) tShapeRightWall:create('rectangle',20,400) tShapeLeftWall:create('rectangle',20,400) local density, friction, restitution= 0.5, 10, 1.0 tPhysic:addDynamicBody(tShapeCircle1,density, friction, restitution) tPhysic:addDynamicBody(tShapeCircle2,density, friction, restitution) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround) tPhysic:addStaticBody(tShapeLeftWall) tPhysic:addStaticBody(tShapeRightWall) tJoint= { name='motor', linearOffset={x= 15, y=0}, --relative distance between body 2 and

˓→body 1 angularOffset= math.rad(180.0), --relative angle between body 2 and body

˓→1 maxForce= 100000.0, maxTorque= 10000.0, correctionFactor= 1.3, collideConnected= false, } local indexJoint= tPhysic:joint(tShapeQuad,tShapeCircle1,tJoint)

Figure 25.25: Motor joint

Mouse joint

Next, an example of joint using mouse joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tPhysic:setScale(10) --set our desired scale tShapeQuad= shape:new('2dw',-200, 300) tShapeCircle1= shape:new('2dw',-100, 300) tShapeCircle2= shape:new('2dw', 100, 300) tShapeTriangle= shape:new('2dw', 50, 300)

(continues on next page)

25.3. box2d Joint 471 MBM Documentation, Release 3.1.f

(continued from previous page) tShapeGround= shape:new('2dw',0,-350) tShapeLeftWall= shape:new('2dw',-400,0) tShapeRightWall= shape:new('2dw',400,0) tShapeUpWall= shape:new('2dw',0,350) tShapeQuad:create('rectangle',100,100) tShapeCircle1:create('circle',100,100) tShapeCircle2:create('circle',80,80) tShapeTriangle:create('triangle',100) tShapeGround:create('rectangle',1000,20) tShapeRightWall:create('rectangle',20,700) tShapeLeftWall:create('rectangle',20,700) tShapeUpWall:create('rectangle',1000,20) local density, friction, restitution= 0.5, 10, 1.0 tPhysic:addDynamicBody(tShapeCircle1,density, friction, restitution) tPhysic:addDynamicBody(tShapeCircle2,density, friction, restitution) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround) tPhysic:addStaticBody(tShapeRightWall) tPhysic:addStaticBody(tShapeLeftWall) tPhysic:addStaticBody(tShapeUpWall) tAllDynamicObject={} --store all dynamic objects that we want to apply mouse joint table.insert(tAllDynamicObject,tShapeQuad) table.insert(tAllDynamicObject,tShapeCircle1) table.insert(tAllDynamicObject,tShapeCircle2) table.insert(tAllDynamicObject,tShapeTriangle)

--our mouse joint table tJoint= { name='mouse', target= {x=0,y=0}, -- updated in the moment that we click on object

˓→and keep clicked maxForce=0, -- updated according to mass frequencyHz= 30.0, dampingRatio= 0.7, collideConnected= false, } tMouseJoint= nil --point to mouse joint when created tMeshJoint= nil --point to mesh that we have selected (clicked)

--called onTouchDown and onTouchMove function setTarget(x,y) x , y=x/ tPhysic:getScale(),y/ tPhysic:getScale() -- we have to consider the

˓→scale if tMouseJoint then tMouseJoint:setTarget(x,y) end tJoint.target.x,tJoint.target.y= x,y end (continues on next page)

472 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) function onTouchDown(key,x,y) x,y= mbm.to2dw(x,y) for i=1,#tAllDynamicObject do local tMesh= tAllDynamicObject[i] if tPhysic:testPoint(tMesh,x,y) and tMouseJoint == nil then tJoint.maxForce= 1000 * tPhysic:getMass(tMesh) setTarget(x,y) -- update the target if tPhysic:joint(tMesh,tMesh,tJoint)>0 then tMouseJoint= tPhysic:getJoint(tMesh) tMeshJoint= tAllDynamicObject[i] break end end end end function onTouchMove(key,x,y) if tMouseJoint then x , y= mbm.to2dw(x,y) setTarget(x,y)-- update the target end end function onTouchUp(key,x,y) if tMouseJoint then tPhysic:destroyJoint(tMeshJoint) --no long are holding the object, destroy it tMouseJoint= nil --mark as nil end end

Figure 25.26: Mouse joint

Note: Note that we are considering the box2d scale when we set the target through the method setTarget. Also note that mouse joint take the same body in the first and second argument.

Prismatic joint

Next, an example of joint using prismatic joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tShapeBoxA= shape:new('2dw',-300, 100) tShapeBoxB= shape:new('2dw',-350, 150) tShapeCircle= shape:new('2dw',400, 500)

(continues on next page)

25.3. box2d Joint 473 MBM Documentation, Release 3.1.f

(continued from previous page) tShapeGround= shape:new('2dw',0,40) tShapeRightWall= shape:new('2dw',450,0) tShapeBoxA:create('rectangle',100,100) tShapeBoxB:create('rectangle',50,10) tShapeCircle:create('circle',100,100) tShapeGround:create('rectangle',1000,20) tShapeRightWall:create('rectangle',20,400) tShapeGround.az= math.rad(2) --tilt a litle bit tPhysic:addDynamicBody(tShapeBoxA) tPhysic:addDynamicBody(tShapeBoxB) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addStaticBody(tShapeGround) tPhysic:addStaticBody(tShapeRightWall) local size_box_a= {x=0, y=0} size_box_a.x, size_box_a.y= tShapeBoxA:getSize() size_box_a.x= size_box_a.x/ tPhysic:getScale() --consider the box2d

˓→scale size_box_a.y= size_box_a.y/ tPhysic:getScale() --consider the box2d

˓→scale local corner_box_a= {x= size_box_a.x/2,y=-size_box_a.y/2} -- corner of the

˓→box (bottom, right) local size_box_b= {x=0, y=0} size_box_b.x, size_box_b.y= tShapeBoxB:getSize() size_box_b.x= size_box_b.x/ tPhysic:getScale() --consider the box2d

˓→scale size_box_b.y= size_box_b.y/ tPhysic:getScale() --consider the box2d

˓→scale local corner_box_b= {x=-size_box_b.x/2,y=-size_box_b.y/2} -- corner of the

˓→box (bottom left)

--[[ |------| | | |------| | box A | | | |------* <- corner box a bottom,right | box B | corner box b bottom left -> *------| ]] tJoint= { name='prismatic', localAnchorA= {x= corner_box_a.x, y= corner_box_a.y}, localAnchorB= {x= corner_box_b.x, y= corner_box_b.y}, localAxisA= {x=0, y=1}, -- Direction of elevation (normalized) referenceAngle= 0.0, enableLimit= true, lowerTranslation= 0.0, upperTranslation= size_box_a.y, --How high? same as maximum of first box (continues on next page)

474 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) enableMotor= false, --enable on key up maxMotorForce= 50000.0, motorSpeed= 5.0, collideConnected= false, } local indexJoint= tPhysic:joint(tShapeBoxA,tShapeBoxB,tJoint) tJointPrismatic= tPhysic:getJoint(tShapeBoxA) function onKeyDown(key) if mbm.getKeyCode('up') == key then tJointPrismatic:enableMotor(true) end end function onKeyUp(key) if mbm.getKeyCode('up') == key then tJointPrismatic:enableMotor(false) end end

Figure 25.27: Prismatic joint

Pulley joint

Next, an example of joint using pulley joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tPhysic:setScale(10) tShapeBox1= shape:new('2dw',-200,-80) tShapeBox2= shape:new('2dw', 200,-308) tShapeGround= shape:new('2dw',0,-350) tShapeGround:create('rectangle',1000,20) tShapeBox1:create('rectangle',100,100) tShapeBox2:create('rectangle',50,50) tPhysic:addDynamicBody(tShapeBox1) tPhysic:addDynamicBody(tShapeBox2) tPhysic:addStaticBody(tShapeGround) groundAnchorA= shape:new('2dw',-200,300) groundAnchorB= shape:new('2dw',200,300) groundAnchorA:create('circle',20,20) groundAnchorB:create('circle',20,20) size_box_2_y= select(2,tShapeBox2:getSize()) (continues on next page)

25.3. box2d Joint 475 MBM Documentation, Release 3.1.f

(continued from previous page) half_size_box_2_y= size_box_2_y/2 box_2d_scale= tPhysic:getScale() tJoint= { name='pulley', groundAnchorA= {x= groundAnchorA.x/ box_2d_scale , y= groundAnchorA.y

˓→/ box_2d_scale}, groundAnchorB= {x= groundAnchorB.x/ box_2d_scale , y= groundAnchorB.y

˓→/ box_2d_scale}, localAnchorA= {x= 0.0, y= 0.0}, localAnchorB= {x= 0.0, y= half_size_box_2_y/ box_2d_scale}, lengthA= 100.0/ box_2d_scale, lengthB= 400.0/ box_2d_scale, ratio= 1.0, collideConnected= true, } local indexJoint= tPhysic:joint(tShapeBox1,tShapeBox2,tJoint)

Figure 25.28: Pulley joint

Revolute joint

Next, an example of joint using revolute joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tShapeBoxA= shape:new('2dw',0, 100) tShapeBoxB= shape:new('2dw',50, 150) tShapeCircle= shape:new('2dw',400, 500) tShapeGround= shape:new('2dw',0,40) tShapeRightWall= shape:new('2dw',450,0) tShapeBoxA:create('rectangle',100,100) tShapeBoxB:create('rectangle',50,50) tShapeCircle:create('circle',100,100) tShapeGround:create('rectangle',1000,20) tShapeRightWall:create('rectangle',20,400) tShapeGround.az= math.rad(2) --tilt a litle bit tPhysic:addDynamicBody(tShapeBoxA) tPhysic:addDynamicBody(tShapeBoxB) (continues on next page)

476 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) tPhysic:addDynamicBody(tShapeCircle) tPhysic:addStaticBody(tShapeGround) tPhysic:addStaticBody(tShapeRightWall) local size_box= {x=0, y=0} size_box.x, size_box.y= tShapeBoxA:getSize() size_box.x= size_box.x/ tPhysic:getScale() --consider the box2d scale size_box.y= size_box.y/ tPhysic:getScale() --consider the box2d scale local corner_box= {x= size_box.x/2,y= size_box.y/2} -- corner of the box (top,

˓→right) --[[ |------* <- corner_box top,right | | | box A | |------| ]]

-- If we omit local anchors A and B, the engine will use the second body to calculate

˓→it. tJoint= { name='revolute', localAnchorA= corner_box, --in the corner of the box A (top,right) localAnchorB= {x=0, y=0}, --in the center of the box B referenceAngle= tShapeBoxB.az- tShapeBoxA.az, lowerAngle= math.rad(-90), -- no effect since enableLimit is false upperAngle= math.rad(45), -- no effect since enableLimit is false maxMotorTorque= 10000.0, motorSpeed= 10.0, enableLimit= false, enableMotor= true, collideConnected= false, } local indexJoint= tPhysic:joint(tShapeBoxA,tShapeBoxB,tJoint)

Figure 25.29: Revolute joint

Rope joint

Next, an example of joint using rope joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tShapeQuad= shape:new('2dw',-200, 720) tShapeCircle1= shape:new('2dw',-100, 400) tShapeCircle2= shape:new('2dw', 100, 400) tShapeTriangle= shape:new('2dw', 50, 300) (continues on next page)

25.3. box2d Joint 477 MBM Documentation, Release 3.1.f

(continued from previous page) tShapeGround= shape:new('2dw',0,-50) tShapeWall= shape:new('2dw',300,100) tShapeQuad:create('rectangle',100,100) tShapeCircle1:create('circle',100,100) tShapeCircle2:create('circle',80,80) tShapeTriangle:create('triangle',100) tShapeGround:create('rectangle',1000,20) tShapeWall:create('rectangle',20,200) local density, friction, restitution= 0.5, 10, 1.0 tPhysic:addDynamicBody(tShapeCircle1,density, friction, restitution) tPhysic:addDynamicBody(tShapeCircle2,density, friction, restitution) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround) tPhysic:addStaticBody(tShapeWall) tJoint= { name='rope', localAnchorA={x =-1.0, y= 0.0}, localAnchorB={x= 1.0, y= 0.0}, --maxLength = 0.0, -- let the engine calculate the max length according

˓→to the current position of the bodies collideConnected= false, } local indexJoint= tPhysic:joint(tShapeCircle1,tShapeCircle2,tJoint)

Figure 25.30: Rope joint

Weld joint

Next, an example of joint using weld joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tShapeQuad= shape:new('2dw',-200, 520) tShapeCircle1= shape:new('2dw',-80, 400) tShapeCircle2= shape:new('2dw', 100, 400) tShapeTriangle= shape:new('2dw', 50, 300) tShapeGround= shape:new('2dw',0,-300) tShapeRightWall= shape:new('2dw',450,0) tShapeLeftWall= shape:new('2dw',-450,0) (continues on next page)

478 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) tShapeQuad:create('rectangle',100,100) tShapeCircle1:create('circle',200,200,10) --low resolution of the circle tShapeCircle2:create('circle',80,80) tShapeTriangle:create('triangle',100) tShapeGround:create('rectangle',1000,20) tShapeRightWall:create('rectangle',20,400) tShapeLeftWall:create('rectangle',20,400) local density, friction, restitution= 0.5, 10, 1.0 tPhysic:addDynamicBody(tShapeCircle1,density, friction, restitution) tPhysic:addDynamicBody(tShapeCircle2,density, friction, restitution) tPhysic:addDynamicBody(tShapeQuad) tPhysic:addDynamicBody(tShapeTriangle) tPhysic:addStaticBody(tShapeGround) tPhysic:addStaticBody(tShapeLeftWall) tPhysic:addStaticBody(tShapeRightWall) local world_point_a={x=0, y=0} local world_point_b={x=0, y=0} world_point_a.x, world_point_a.y= tPhysic:getLocalPoint(tShapeQuad,0,0) world_point_b.x, world_point_b.y= tPhysic:getLocalPoint(tShapeCircle1,0,0) tJoint= { name='weld', localAnchorA= world_point_a, -- If we omit local anchors A and B, the

˓→engine will use the second body to calculate it. localAnchorB= world_point_b, -- If we omit local anchors A and B, the

˓→engine will use the second body to calculate it. referenceAngle= tShapeQuad.az- tShapeCircle1.az, --if not supply, it will

˓→get the angle difference like this frequencyHz= 0.0, dampingRatio= 0.0, collideConnected= false, } local indexJoint= tPhysic:joint(tShapeQuad,tShapeCircle1,tJoint)

Figure 25.31: Weld joint

Wheel joint

Next, an example of joint using wheel joint table. require"box2d" mbm.setColor(1,1,1) tPhysic= box2d:new() tPhysic:setScale(10) (continues on next page)

25.3. box2d Joint 479 MBM Documentation, Release 3.1.f

(continued from previous page) tShapCar= shape:new('2dw',0, 50) tShapeWheel1= shape:new('2dw',-50, 25) tShapeWheel2= shape:new('2dw', 50, 25) tShapeGround= shape:new('2dw',0,-25) tShapeGround:create('rectangle',1000,20) tShapCar:create('rectangle',100,50) tShapeWheel1:create('circle',50,50) tShapeWheel2:create('circle',50,50) tPhysic:addDynamicBody(tShapCar) tPhysic:addDynamicBody(tShapeWheel1) tPhysic:addDynamicBody(tShapeWheel2) tPhysic:addStaticBody(tShapeGround)

-- Invert mass. See box2d tutorial the explanation local massCar= tPhysic:getMass(tShapCar) local massWheel= tPhysic:getMass(tShapeWheel1) tPhysic:setMass(tShapeWheel1,massCar * 0.5) tPhysic:setMass(tShapeWheel2,massCar * 0.5) tPhysic:setMass(tShapCar, massWheel * 2) tJoint= { name='wheel', localAnchorA={x=0, y=0}, localAnchorB={x=0, y=0}, localAxisA={x=0, y=1}, enableMotor= true, maxMotorTorque= 8000, motorSpeed= 0.0, frequencyHz= 3.0, dampingRatio= 0.9, collideConnected= false, } v1= vec2:new() v2= vec2:new() box_2d_scale= tPhysic:getScale()

--find the relative local of back wheel v1:set(tShapCar.x,tShapCar.y) v2:set(tShapeWheel1.x,tShapeWheel1.y) v2:sub(v1) v2:div(box_2d_scale) tJoint.localAnchorA.x,tJoint.localAnchorA.y= v2.x,v2.y local indexJoint1= tPhysic:joint(tShapCar,tShapeWheel1,tJoint) tShapCar.tJointWheel1= tPhysic:getJoint(tShapeWheel1)

--find the relative local of front wheel (continues on next page)

480 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

(continued from previous page) v1:set(tShapCar.x,tShapCar.y) v2:set(tShapeWheel2.x,tShapeWheel2.y) v2:sub(v1) v2:div(box_2d_scale) tJoint.localAnchorA.x, tJoint.localAnchorA.y= v2.x,v2.y local indexJoint2= tPhysic:joint(tShapCar,tShapeWheel2,tJoint) tShapCar.tJointWheel2= tPhysic:getJoint(tShapeWheel2) motorSpeed= 500 direction_car=0 function onKeyDown(key) if mbm.getKeyCode('left') == key then direction_car=1 elseif mbm.getKeyCode('right') == key then direction_car=-1 end end function onKeyUp(key) if mbm.getKeyCode('left') == key or mbm.getKeyCode('right') == key then direction_car=0 end end function loop(delta,fpsProp) tShapCar.tJointWheel1:setMotorSpeed(motorSpeed * direction_car) tShapCar.tJointWheel2:setMotorSpeed(motorSpeed * direction_car) end

Figure 25.32: Wheel joint

25.3.3 Joint methods

Note: Not all joint has the same methods, each joint has its particularity.

25.3.4 Active options isActive Available for all joints Check if both bodies are active given the joint. Returns boolean - Both bodies are active? Example: local active= tJoint:isActive() setActive(boolean value)

25.3. box2d Joint 481 MBM Documentation, Release 3.1.f

Available for all joints Set active option for both bodies given the joint.

Parameters boolean – value - Set Active for both bodies

Example:

tJoint:setActive(true)

25.3.5 Angular offset options

getAngularOffset Available for motor. Returns number - angular offset Example:

local angular_offset= tJoint:getAngularOffset()

setAngularOffset(number angular_offset) Available for motor. Parameters number – angular_offset. Example:

local angular_offset= math.rad(10) tJoint:setAngularOffset(angular_offset)

25.3.6 Anchor options

getAnchorA

Available for all joints Get the anchor point on body ‘A’ in world coordinates.

return number x - number - y anchor on body ‘A’ in world coordinates. Example:

local x,y= tJoint:getAnchorA()

getAnchorB

Available for all joints Get the anchor point on body ‘B’ in world coordinates.

return number x - number - y anchor on body ‘B’ in world coordinates. Example:

482 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

local x,y= tJoint:getAnchorB()

25.3.7 Correction factor options getCorrectionFactor Available for motor. Returns number - correction factor in range [0,1] Example: local correction= tJoint:getCorrectionFactor() setCorrectionFactor(table joint, number correction_factor) Available for motor Parameters number – correction factor in range [0,1] Example: local correction_factor= 0.5 tJoint:setCorrectionFactor(correction_factor)

25.3.8 Damping ratio options getDampingRatio Available for distance , gear , wheel, weld . Returns number - Damping ratio Example: local damping_ratio= tJoint:getDampingRatio() setDampingRatio(number damping_ratio) Available for distance , gear , wheel, weld . Parameters number – damping ratio. Example: local damping_ratio=2 tJoint:setDampingRatio(damping_ratio)

25.3.9 Destroy joint destroyJoint(tBody) Parameters renderizable – body. Example: tPhysic:destroyJoint(tBody)

Note:

25.3. box2d Joint 483 MBM Documentation, Release 3.1.f

The engine will destroy the joint in the next cycle. destroyJoint is only available for box2d instance. It is not available for joint table.

25.3.10 Force options getMaxForce Available for mouse, friction, motor, prismatic. Max motor force for prismatic. Returns number - maximum friction force in newton. Example: local maximum_friction_force= tJoint:getMaxForce() setMaxForce(number max_friction_force) Available for mouse, friction, motor, prismatic. Max motor force for prismatic.Motor options joint Parameters number – maximum friction force in newton. Example: local max_friction_force= 10 tJoint:setMaxForce(max_friction_force)

25.3.11 Frequency options setFrequencyHz(number hertz) Available for distance , wheel, weld . Parameters number – hertz. Example: local hertz= 30 tJoint:setFrequencyHz(hertz) getFrequencyHz Available for distance , wheel, weld . Returns number - hertz Example: local hertz= tJoint:getFrequencyHz()

25.3.12 Get joint getJoint(tBody, number * absolute_index) Retrieve a joint previously created passing any of body used to create th joint through the method joint and the absolute index (not mandatory). Parameters

484 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

• renderizable – body. • number – absolute index of the joint in the engine. (this index can be invalid after destroy- ing joint). Returns table - joint Example: tJoint= tPhysic:getJoint(tBody,indexMyJoint)

Note: Retrieve a joint previously created using box2d instance.

25.3.13 Length options getLength Available for distance , rope . Max length for rope .

Returns number - length for distance or max length for rope .

Example: local length= tJoint:getLength() setLength Available for distance , rope . Max length for rope . Parameters number – length for distance or max length for rope . Example: local length= 10 tJoint:setLength(length)

25.3.14 Limit options enableLimit(boolean value) Available for revolute, prismatic. Parameters boolean – value. Example: local enable= true tJoint:enableLimit(enable) getLimits Available for revolute, prismatic. Returns number lower - number - upper Example:

25.3. box2d Joint 485 MBM Documentation, Release 3.1.f

local lower, upper= tJoint:getLimits() setLimits(number lower, number upper) Available for revolute, prismatic. Parameters • number – lower. • number – upper. Example: local lower, upper= 10, 10 tJoint:setLimits(lower,upper)

25.3.15 Linear offset options getLinearOffset Available for motor. Returns number x - number - y (Frame A in Meters). Example: local x,y= tJoint:getLinearOffset() setLinearOffset(number x, number y) Available for motor Parameters • number – x (Frame A in Meters). • number – y (Frame A in Meters). Example: local x,y= 10,15 tJoint:setLinearOffset(x,y)

25.3.16 Motor options getMotorSpeed Available for revolute, prismatic, wheel. Returns number - speed in radian per second. Example: local motor_speed_rad= tJoint:getMotorSpeed() -- speed in radian per second setMotorSpeed(number speed) Available for revolute, prismatic, wheel. Parameters number – speed in radian per second. Example:

486 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

local speed= math.rad(360) tJoint:setMotorSpeed(speed) getMaxMotorTorque Available for revolute, wheel, motor Returns number - max motor torque Example: local max_torque= tJoint:getMaxMotorTorque() setMaxMotorTorque(number max_torque) Available for revolute, wheel, motor Parameters number – max torque. Example: local torque=5 tJoint:setMaxMotorTorque(torque) enableMotor(boolean value) Available for revolute, prismatic, wheel. Parameters boolean – value. Example: local enable= true tJoint:enableMotor(enable)

25.3.17 Reaction options getReactionForce(number inv_delta) Available for all joints Parameters number – inv_delta. Returns number x - number - y reaction force on body B at the joint anchor in Newtons. Example: local inv_delta=1/60 local x,y= tJoint:getReactionForce(inv_delta) getReactionTorque(number inv_delta) Available for all joints Parameters number – inv_delta. Returns number - reaction torque on body B in N x m Example: local inv_delta=1/60 local reaction_torque= tJoint:getReactionTorque(inv_delta)

25.3. box2d Joint 487 MBM Documentation, Release 3.1.f

25.3.18 Target options getTarget

Available for mouse. You should consider the box2d scale to this method to transform to 2dw coordinates.

Returns number x - number - y

Example: local box2d_scale= tPhysic:getScale() local x,y= tJoint:getTarget() x,y=x * box2d_scale, y * box2d_scale setTarget(number x, number y)

Available for mouse. You should consider the box2d scale to this method.

Parameters • number – x. • number – y.

Example:

-- part of example here function onTouchDown(key,x,y) x,y= mbm.to2dw(x,y) local box2d_scale= tPhysic:getScale() x,y=x/ box2d_scale, y/ box2d_scale tJoint:setTarget(x,y) end

Table of Contents

• Module ImGui – Begin / End methods

* Begin / End * BeginPopupModal * BeginChild * BeginMenu * BeginPopupContextVoid * BeginPopupContextWindow * BeginPopupContextItem * BeginPopup

488 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

* BeginMainMenuBar * BeginTooltip * BeginTabBar * BeginDragDropSource * BeginGroup * BeginChildFrame * BeginTabItem * BeginDragDropTarget * BeginMenuBar – Calc methods

* CalcItemWidth * CalcTextSize – Capture methods

* CaptureKeyboardFromApp * CaptureMouseFromApp – Color methods

* ColorConvertHSVtoRGB * ColorConvertFloat4ToU32 * ColorConvertU32ToFloat4 * ColorConvertRGBtoHSV * Columns – CreateContext – DestroyContext – Flag / Enum

* Flags * All Flags / Enum Listed * ImGuiKey – General methods

* Dummy * Indent * InvisibleButton * NextColumn * ResetMouseDragDelta * SameLine * Separator

25.3. box2d Joint 489 MBM Documentation, Release 3.1.f

* Spacing * Unindent – Get methods

* GetClipboardText * GetScrollY * GetMainMenuBarHeight * GetMouseCursor * GetWindowContentRegionMin * GetWindowContentRegionMax * GetContentRegionAvail * GetID * GetContentRegionMax * GetMouseDragDelta * GetFrameHeight * GetFrameHeightWithSpacing * GetMousePosOnOpeningCurrentPopup * GetMousePos * GetStyleColorName * GetKeyIndex * GetKeyPressedAmount * GetScrollMaxY * GetScrollMaxX * GetScrollX * GetIO * GetTextLineHeight * GetWindowContentRegionWidth * GetWindowHeight * GetTextLineHeightWithSpacing * GetWindowSize * GetColorU32 * GetItemRectMin * GetItemRectSize * GetItemRectMax * GetFrameCount * GetTime

490 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

* GetColorU32 * GetFontSize * GetColumnOffset * GetDragDropPayload * GetColumnsCount * GetFontTexUvWhitePixel * GetColumnWidth * GetVersion * GetColumnIndex * GetFont * GetStyleColorVec4 * GetCursorScreenPos * GetCursorPos * GetWindowPos * GetCursorPosX * GetCursorPosY * GetContentRegionAvailWidth * GetCursorStartPos * GetWindowWidth * GetZoom – ImDrawList

* SetImDrawListToBackground * SetImDrawListToForeground * AddImageQuad * AddText * AddPolyline * AddNgonFilled * AddNgon * AddCircle * AddConvexPolyFilled * AddImage * AddBezierCurve * AddDrawCmd * AddImageRounded * AddTriangleFilled

25.3. box2d Joint 491 MBM Documentation, Release 3.1.f

* AddCircleFilled * AddLine * AddTriangle * AddRect * AddRectFilledMultiColor * AddRectFilled * AddQuadFilled * AddQuad * ImDrawList PopTextureID * ImDrawList PushTextureID – Is methods

* IsAnyItemHovered * IsAnyMouseDown * IsAnyWindowHovered * IsAnyWindowFocused * IsAnyItemFocused * IsAnyItemActive * IsItemDeactivatedAfterEdit * IsItemEdited * IsItemToggledOpen * IsItemDeactivatedAfterChange * IsItemDeactivated * IsItemActive * IsItemHovered * IsItemActivated * IsItemVisible * IsItemFocused * IsItemClicked * IsKeyReleased * IsKeyDown * IsKeyPressed * IsMouseDown * IsMouseDoubleClicked * IsMouseClicked * IsMouseHoveringRect

492 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

* IsMouseDragging * IsMouseReleased * IsMousePosValid * IsPopupOpen * IsRectVisible * IsScrollVisible * IsWindowFocused * IsWindowHovered * IsWindowCollapsed * IsWindowAppearing – Save / Load methods

* SaveIniSettingsToMemory * SaveIniSettingsToDisk * LoadIniSettingsFromDisk * LoadIniSettingsFromMemory – Log methods

* LogText * LogFinish * LogButtons * LogToTTY * LogToClipboard * LogToFile – NewFrame / EndFrame – Open / Close methods

* OpenPopupOnItemClick * OpenPopup * CloseCurrentPopup – Pop methods

* PopAllowKeyboardFocus * PopItemWidth * PopButtonRepeat * PopTextWrapPos * PopFont * PopClipRect * PopID

25.3. box2d Joint 493 MBM Documentation, Release 3.1.f

– Push methods

* PushFont * PushAllowKeyboardFocus * PushID * PushID * PushID * PushButtonRepeat * PushTextWrapPos * PushClipRect * PushItemWidth – Render – Set methods

* SetKeyboardFocusHere * SetMouseCursor * SetCurrentContext * SetClipboardText * SetNextTreeNodeOpen * SetItemDefaultFocus * SetScrollHere * SetItemAllowOverlap * SetDragDropPayload * SetWindowFocus * SetTabItemClosed * SetWindowFontScale * SetWindowCollapsed * SetWindowSize * SetCursorPosY * SetCursorScreenPos * SetCursorPosX * SetWindowPos * SetColorEditOptions * SetNextWindowSize * SetNextWindowPos * SetNextWindowBgAlpha * SetNextWindowSizeConstraints

494 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

* SetNextWindowCollapsed * SetNextWindowContentSize * SetNextWindowFocus * SetCursorPos * SetScrollHereX * SetScrollY * SetColumnOffset * SetScrollX * SetColumnWidth * SetScrollHereY * SetNextItemWidth * SetTooltip * SetScrollFromPosY * SetScrollFromPosX – Show methods

* ShowUserGuide * ShowFontSelector * ShowStyleSelector – Style methods

* PushStyleColor * PopStyleColor * PushStyleVar * PopStyleVar * ImGuiStyleVar flag table * StyleColorsLight * StyleColorsDark * StyleColorsClassic * GetStyle * ImGuiStyle Table * ImGuiCol Table – Text methods

* AlignTextToFramePadding * TextColored * Text * TextDisabled

25.3. box2d Joint 495 MBM Documentation, Release 3.1.f

* TextWrapped – Widgets

* ArrowButton * BeginCombo * Bullet * Button * Checkbox * Combo * Color · ColorPicker · ColorButton · ColorEdit3 · ColorEdit4

* Drag · DragInt · DragIntRange2 · DragFloat · DragFloatRange2

* HelpMarker * Image * ImageQuad * ImageButton * Input · InputInt · InputInt2 · InputInt3 · InputInt4 · InputFloat · InputFloat2 · InputFloat3 · InputFloat4 · InputDouble · InputText · InputTextWithHint · InputTextMultiline

496 Chapter 25. Module box2d MBM Documentation, Release 3.1.f

* LabelText * ListBox · ListBoxHeader · ListBoxFooter

* Menu · Menu · MainMenuBar · MenuItem

* NewLine * PlotLines * PlotHistogram * ProgressBar * RadioButton * Selectable * SmallButton * Slider · SliderInt · SliderInt2 · SliderInt3 · SliderInt4 · SliderFloat · SliderFloat2 · SliderFloat3 · SliderFloat4 · SliderAngle

* TreeNode · TreeNode · TreeNode · TreeNodeEx · TreePush · TreePop · TreeAdvanceToLabelPos · CollapsingHeader · GetTreeNodeToLabelSpacing · SetNextItemOpen

25.3. box2d Joint 497 MBM Documentation, Release 3.1.f

* VSlider · VSliderInt · VSliderFloat

498 Chapter 25. Module box2d CHAPTER 26

Module ImGui

This Plugin is a wrapper over Dear ImGui and has some modification to be able to use it in Lua as external mod- ule/plugin for this engine. It is widely used to build editor such as sprite maker shader editor , etc. . .

Important: Dear ImGui is immediate GUI! so it is based on loop. Then, basically, you have to control what should be render inside the main loop of the engine otherwise will not be render.

26.1 Begin / End methods

26.1.1 Begin / End

Window • Begin() = push window to the stack and start appending to it. • End() = pop window from the stack. – You may append multiple times to the same window during the same frame. – Passing boolean closeable as true shows a window-closing widget in the upper-right corner of the window, which clicking will result the second boolean closed_clicked as true. • Begin() return false to indicate the window is collapsed or fully clipped. – You may early out and omit submitting anything to the window checking this flag. – Always call a matching End() for each Begin() call, regardless of its return value!

Important: Due to legacy reason, this is inconsistent with most other functions such as Begin- Popup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX

499 MBM Documentation, Release 3.1.f

Figure 26.1: Sprite maker running.

500 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

function returned true. Begin() and BeginChild() are the only odd ones out. Will be fixed in a future update! • Note that the bottom of window stack always contains a window called “Debug”.

Begin(title, closeable, flags) Parameters • string – title • boolean – closeable might be closed? • number – flags Returns boolean, boolean - is_opened, closed_clicked End End a Window Example: tImGui= require"ImGui" function loop(delta) local title='Hello ImGui Plugin' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags) print(is_opened, closed_clicked) if is_opened then tImGui.Text('Some nice content to show!') end tImGui.End() end

26.1.2 BeginPopupModal

BeginPopupModal(title, closeable, flags) Modal dialog (regular window with title bar, block interactions behind the modal window, can’t close the modal window by clicking outside)

Parameters • string – title • boolean – closeable might be closed?

26.1. Begin / End methods 501 MBM Documentation, Release 3.1.f

• number – flags Returns boolean, boolean - is_opened, closed_clicked

EndPopup Only call EndPopup() if BeginPopupXXX() returns true! Example: tImGui= require"ImGui" open_modal= true function loop(delta) if open_modal then local flags= tImGui.Flags('ImGuiWindowFlags_AlwaysAutoResize') local title_popup='Remove all images ?' tImGui.OpenPopup(title_popup); local is_opened, closed_clicked= tImGui.BeginPopupModal(title_popup, false,

˓→flags) if is_opened then tImGui.Text('Are vou sure to remove all images?') tImGui.Separator(); if tImGui.Button("OK", {x=120, y=0}) then tImGui.CloseCurrentPopup() open_modal= false end tImGui.SetItemDefaultFocus(); tImGui.SameLine(); if tImGui.Button("Cancel", {x=120, y=0}) then tImGui.CloseCurrentPopup() open_modal= false end tImGui.EndPopup() end end end

26.1.3 BeginChild

Child Windows • Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. • For each independent axis of ‘size’: ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400).

502 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

• BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. • Always call a matching EndChild() for each BeginChild() call, regardless of its return value [as with Begin: this is due to legacy reason and inconsistent with most BeginXXX functions apart from the regular Begin() which behaves like BeginChild().] BeginChild(str_id, size, border, flags) Parameters • string – str_id (might be nil) • table – size default: { x = 0, y = 0} • boolean – border • number – flags Returns boolean - result EndChild End Child. Example:

tImGui= require"ImGui"

function loop(delta) local title='Main window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags) if is_opened then tImGui.Text('Other nice content to show!')

local str_id='01' local size= {x= 200, y= 50} local border= true

tImGui.BeginChild(str_id, size, border, flags) tImGui.Text('I am a child') tImGui.EndChild() end tImGui.End() end

26.1. Begin / End methods 503 MBM Documentation, Release 3.1.f

26.1.4 BeginMenu

BeginMenu(label, enabled) Create a sub-menu entry. only call EndMenu() if this returns true!

Parameters • string – label • boolean – enabled Returns boolean - result

EndMenu Only call EndMenu() if BeginMenu() returns true! Example: tImGui= require"ImGui" local title='Main window' local closeable= true local flags=0 function loop(delta) local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags) if is_opened then tImGui.Text('Other nice content to show!')

local label='menu 1' local label2='menu 2' local enabled= true

if tImGui.BeginMenu(label, enabled) then tImGui.Text('Option menu 1') if tImGui.BeginMenu(label2, enabled) then tImGui.Text('Option menu 2') tImGui.EndMenu() end tImGui.EndMenu() end end tImGui.End() end

504 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.1.5 BeginPopupContextVoid

BeginPopupContextVoid(str_id, mouse_button) Helper to open and begin popup when clicked in void (where there are no ImGui windows).

Parameters • string – str_id (might be nil) • number – mouse_button (0=left, 1=right, 2=middle) Returns boolean - result

Example:

tImGui= require"ImGui" local str_id='id_1' local mouse_button=0 function loop(delta) if tImGui.BeginPopupContextVoid(str_id, mouse_button) then if tImGui.Selectable("Some option") then print('You have chosen this option') end tImGui.EndPopup() end end

26.1.6 BeginPopupContextWindow

BeginPopupContextWindow(str_id, mouse_button, also_over_items) Helper to open and begin popup when clicked on current window.

Parameters • string – str_id (might be nil) • number – mouse_button (0=left, 1=right, 2=middle) • boolean – also_over_items Returns boolean - result

Example:

tImGui= require"ImGui" local str_id='01' local mouse_button=1 local also_over_items= true function loop(delta) if tImGui.BeginPopupContextWindow(str_id, mouse_button, also_over_items) then if tImGui.Selectable("Some option") then print('You have chosen this option') end tImGui.EndPopup() end end

26.1. Begin / End methods 505 MBM Documentation, Release 3.1.f

26.1.7 BeginPopupContextItem

BeginPopupContextItem(str_id, mouse_button) Helper to open and begin popup when clicked on last item. if you can pass a nil str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp!

Parameters • string – str_id (might be nil) • number – mouse_button (0=left, 1=right, 2=middle) Returns boolean - result

Example:

tImGui= require"ImGui" local str_id='01' local mouse_button=1 function loop(delta) if tImGui.BeginPopupContextItem(str_id, mouse_button) then if tImGui.Selectable("Some option") then print('You have chosen this option') end tImGui.EndPopup() end end

26.1.8 BeginPopup

BeginPopup(str_id, flags) Return true if the popup is open, and you can start outputting to it. only call EndPopup() if Begin- Popup() returns true!

Parameters • string – str_id (might be nil) • number – flags Returns boolean - result

EndPopup Only call EndPopup() if BeginPopupXXX() returns true! Example:

tImGui= require"ImGui" function loop(delta) local str_id='01' local flags=0 if tImGui.BeginPopup(str_id, flags) then tImGui.EndPopup() end end

506 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.1.9 BeginMainMenuBar

BeginMainMenuBar Create and append to a full screen menu-bar.

Returns boolean - result

EndMainMenuBar Only call EndMainMenuBar() if BeginMainMenuBar() returns true! Example: tImGui= require"ImGui" bAutoSave= false bOtherMenuBar= false function loop(delta) -- Main Menu Bar if (tImGui.BeginMainMenuBar()) then

if tImGui.BeginMenu("File") then

local pressed,checked= tImGui.MenuItem("Auto Save", nil, bAutoSave) if pressed then bAutoSave= checked end tImGui.EndMenu(); end if tImGui.BeginMenu("Examples") then

local pressed,checked= tImGui.MenuItem("Other menu bar", nil,

˓→bOtherMenuBar) if pressed then bOtherMenuBar= checked end tImGui.EndMenu() end tImGui.EndMainMenuBar() end end

26.1.10 BeginTooltip

BeginTooltip Begin/append a tooltip window. to create full-featured tooltip (with any kind of items).

26.1. Begin / End methods 507 MBM Documentation, Release 3.1.f

EndTooltip End Tooltip Example: tImGui= require"ImGui" function loop(delta) tImGui.BeginTooltip() tImGui.Text('This area is free!') tImGui.EndTooltip() end

26.1.11 BeginTabBar

BeginTabBar(str_id, flags) Create and append into a TabBar

Parameters • string – str_id (might be nil) • number – flags Returns boolean - result

EndTabBar Only call EndTabBar() if BeginTabBar() returns true! Example: tImGui= require"ImGui" function loop(delta) local flags= tImGui.Flags('ImGuiTabBarFlags_Reorderable') if tImGui.BeginTabBar('##TabBar_id', flags) then if tImGui.BeginTabItem("Tab 1") then tImGui.Text('Hello') tImGui.EndTabItem() end if tImGui.BeginTabItem("Tab 2") then tImGui.Text('Tab') tImGui.EndTabItem() end tImGui.EndTabBar() end end

26.1.12 BeginDragDropSource

BeginDragDropSource(flags)

508 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Call when the current item is active. If this return true, you can call SetDragDropPayload() + End- DragDropSource()

Parameters number – flags Returns boolean - result

EndDragDropSource Only call EndDragDropSource() if BeginDragDropSource() returns true! Example:

tImGui= require"ImGui" function loop(delta) local flags=0 if tImGui.BeginDragDropSource(flags) then tImGui.EndDragDropSource() end end

26.1.13 BeginGroup

BeginGroup Lock horizontal starting position EndGroup Unlock horizontal starting position + capture the whole group bounding box into one “item” (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) Example:

tImGui= require"ImGui" function loop(delta) tImGui.BeginGroup() tImGui.EndGroup() end

26.1.14 BeginChildFrame

BeginChildFrame(id, size, flags) Helper to create a child window / scrolling region that looks like a normal widget frame

Parameters • number – id • table – size default is {x=0, y=0} • number – flags Returns boolean - result

EndChildFrame Always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a col- lapsed/clipped window) Example:

26.1. Begin / End methods 509 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" function loop(delta) local id=1 local size= {x= 200, y= 200} local flags=0 tImGui.BeginChildFrame(id, size, flags) tImGui.EndChildFrame() end

26.1.15 BeginTabItem

BeginTabItem(label, p_open, flags) Create a Tab. Returns true if the Tab is selected.

Parameters • string – label • boolean – p_open (might be nil) • number – flags (ImGuiTabItemFlags_SetSelected, ImGuiTabItemFlags_UnsavedDocument, etc. . . ) Returns boolean - result

EndTabItem Only call EndTabItem() if BeginTabItem() returns true! Example:

tImGui= require"ImGui" function loop(delta) local flags=0 if tImGui.BeginTabBar('##TabBar_id', flags) then if tImGui.BeginTabItem("Tab 1") then tImGui.Text('Hello') tImGui.EndTabItem() end if tImGui.BeginTabItem("Tab 2") then tImGui.Text('Tab') tImGui.EndTabItem() end tImGui.EndTabBar() end end

26.1.16 BeginDragDropTarget

BeginDragDropTarget Call after submitting an item that may receive a payload. If this returns true, you can call Accept- DragDropPayload() + EndDragDropTarget()

Returns boolean - result

510 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

EndDragDropTarget Only call EndDragDropTarget() if BeginDragDropTarget() returns true! AcceptDragDropPayload(type, flags) Accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released.

Parameters • string – type • number – flags Returns table - ImGuiPayload

Example:

tImGui= require"ImGui"

tImGui.BeginDragDropTarget()

26.1.17 BeginMenuBar

BeginMenuBar Append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window).

Returns boolean - result

EndMenuBar Only call EndMenuBar() if BeginMenuBar() returns true! Example:

tImGui= require"ImGui"

bMain_file_checked= false bOtherMenuBar= false

function loop(delta) local flags= 1024 --ImGuiWindowFlags_MenuBar local closeable= true local is_opened, closed_clicked= tImGui.Begin('Demo menu bar', closeable, flags) if is_opened then -- Menu Bar if tImGui.BeginMenuBar() then

if tImGui.BeginMenu("Menu") then

local pressed,checked= tImGui.MenuItem("Main file", nil, bMain_file_

˓→checked) if pressed then bMain_file_checked= checked end tImGui.EndMenu(); end (continues on next page)

26.1. Begin / End methods 511 MBM Documentation, Release 3.1.f

(continued from previous page) if tImGui.BeginMenu("Examples") then

local pressed,checked= tImGui.MenuItem("Other menu bar", nil,

˓→bOtherMenuBar) if pressed then bOtherMenuBar= checked end tImGui.EndMenu() end tImGui.EndMenuBar() end end tImGui.End() end

26.2 Calc methods

26.2.1 CalcItemWidth

CalcItemWidth Width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most ‘Item’ functions.

Returns number - value

Example:

tImGui= require"ImGui"

tImGui.CalcItemWidth()

26.2.2 CalcTextSize

CalcTextSize(text, text_end, hide_text_after_double_hash, wrap_width) Parameters • string – text • string – text_end • boolean – hide_text_after_double_hash

512 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

• number – wrap_width Returns table - ImVec2 {x,y} Example:

tImGui= require"ImGui" local text='some text' local text_end='some text' local hide_text_after_double_hash= false local wrap_width=-1.0

tImGui.CalcTextSize(text, text_end, hide_text_after_double_hash, wrap_width)

CalcListClipping(items_count, items_height, out_items_display_start, out_items_display_end) Calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can.

Parameters • number – items_count • number – items_height Returns number items_display_start, number items_display_end

Example:

tImGui= require"ImGui" local items_count=2 local items_height= 10 local items_display_start=0 local items_display_end=0

items_display_start, items_display_end= tImGui.CalcListClipping(items_count, items_

˓→height)

26.3 Capture methods

26.3.1 CaptureKeyboardFromApp

CaptureKeyboardFromApp(want_capture_keyboard_value) Attention: misleading name! manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to handle). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting “io.WantCaptureKeyboard = want_capture_keyboard_value”; after the next NewFrame() call.

Parameters boolean – want_capture_keyboard_value

Example:

tImGui= require"ImGui" local want_capture_keyboard_value= true

tImGui.CaptureKeyboardFromApp(want_capture_keyboard_value)

26.3. Capture methods 513 MBM Documentation, Release 3.1.f

26.3.2 CaptureMouseFromApp

CaptureMouseFromApp(want_capture_mouse_value) Attention: misleading name! manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle). This is equivalent to setting “io.WantCaptureMouse = want_capture_mouse_value;” after the next NewFrame() call.

Parameters boolean – want_capture_mouse_value

Example:

tImGui= require"ImGui" local want_capture_mouse_value= true tImGui.CaptureMouseFromApp(want_capture_mouse_value)

26.4 Color methods

26.4.1 ColorConvertHSVtoRGB

ColorConvertHSVtoRGB(h, s, v, out_r, out_g, out_b) Parameters • number – h • number – s • number – v Returns number - red, number - green, number - blue Example:

tImGui= require"ImGui" local h= 0.1 local s= 0.2 local v= 0.3

local r,g,b= tImGui.ColorConvertHSVtoRGB(h, s, v)

26.4.2 ColorConvertFloat4ToU32

ColorConvertFloat4ToU32(in) Parameters table – in {x=0,y=0,z=0,w=0} or {r=0,g=0,b=0,a=0} Returns number - ImU32 Example:

tImGui= require"ImGui" local in = {x=0.66,y=0.5,z=1,z=0.1}

local ret= tImGui.ColorConvertFloat4ToU32( in)

514 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.4.3 ColorConvertU32ToFloat4

ColorConvertU32ToFloat4(in) Parameters number – integer Returns table - ImVec4 {x,y,z,w} Example: tImGui= require"ImGui" local in = 255 local tVec4= tImGui.ColorConvertU32ToFloat4( in)

26.4.4 ColorConvertRGBtoHSV

ColorConvertRGBtoHSV(r, g, b, out_h, out_s, out_v) Parameters • number – r • number – g • number – b Returns number - h, number - s, number - v Example: tImGui= require"ImGui" local r= 1.0 local g= 0.5 local b= 0.1 local h,s,v= tImGui.ColorConvertRGBtoHSV(r, g, b)

26.4.5 Columns

Columns(count, id, border) Parameters • number – count • string – id • boolean – border Example: tImGui= require"ImGui" local count=1 local id= nil local border= true tImGui.Columns(count, id, border)

26.4. Color methods 515 MBM Documentation, Release 3.1.f

26.5 CreateContext

Note: You do not need to create a context for this module. It is automatically created by the engine.

26.6 DestroyContext

Note: You do not need to destroy the context for this module. It is automatically destroyed by the engine.

26.7 Flag / Enum

26.7.1 Flags

It is possible to list flag or make flags combining as string. Enum is considered as Flag. Flags(string flag_name_1, string flag_name_2, string flag_name_3, ...) This method accept variable argument of string as input and make it as unique flag out. Parameters string – flag name - it must be identical to the real name. Returns number - flag combined OR operation. Example: tImGui= require"ImGui" local ImGuiWindowFlags_MenuBar= tImGui.Flags('ImGuiWindowFlags_MenuBar') local ImGuiWindowFlags_NoCollapse= tImGui.Flags('ImGuiWindowFlags_NoCollapse') local flag_combined= tImGui.Flags('ImGuiWindowFlags_MenuBar',

˓→'ImGuiWindowFlags_NoCollapse') print('ImGuiWindowFlags_MenuBar',ImGuiWindowFlags_MenuBar) print('ImGuiWindowFlags_NoCollapse',ImGuiWindowFlags_NoCollapse) print('flag_combined',flag_combined)

Flags(table flags) This method accept a table with array of string as input and make it as unique flag out. Parameters table – flags - it must contains array of flags identical to the real name. Returns number - flag combined OR operation. Example:

516 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local tFlags={'ImGuiWindowFlags_MenuBar','ImGuiWindowFlags_NoCollapse',} local flag_combined= tImGui.Flags(tFlags) print('flag_combined',flag_combined) -- flag_combined 1056

FlagList(string flag_name_1, string flag_name_2, string flag_name_3, ...) This method accept a var argument of string as input to list all flags that match as string. Parameters string – flag name - it must be partial case sensitive to the real name. Returns table - flags {key = flag, value = number} Example: tImGui= require"ImGui" local flags= tImGui.FlagList('Window') for k,v in pairs(flags) do local l= k:len() print(k.. string.rep('',50- l).. tostring(v)) end

FlagList(table flags) This method accept a table of string as input to list all flags that match as string. Parameters table – flag table - it must have strings partial case sensitive to the real name. Returns table - flags {key = flag, value = number} Example: tImGui= require"ImGui" local flags= tImGui.FlagList({'Window','InputText'}) for k,v in pairs(flags) do local l= k:len() print(k.. string.rep('',50- l).. tostring(v)) end

26.7.2 All Flags / Enum Listed

ImDrawCornerFlags_All 15 ImDrawCornerFlags_Bot 12 ImDrawCornerFlags_BotLeft 4 ImDrawCornerFlags_BotRight 8 ImDrawCornerFlags_Left 5 ImDrawCornerFlags_None 0 ImDrawCornerFlags_Right 10 ImDrawCornerFlags_Top 3 ImDrawCornerFlags_TopLeft 1 ImDrawCornerFlags_TopRight 2 ImDrawListFlags_AllowVtxOffset 4 ImDrawListFlags_AntiAliasedFill 2 ImDrawListFlags_AntiAliasedLines 1 ImDrawListFlags_None 0 ImGuiBackendFlags_HasGamepad 1 Continued on next page

26.7. Flag / Enum 517 MBM Documentation, Release 3.1.f

Table 26.1 – continued from previous page ImGuiBackendFlags_HasMouseCursors 2 ImGuiBackendFlags_HasSetMousePos 4 ImGuiBackendFlags_None 0 ImGuiBackendFlags_RendererHasVtxOffset 8 ImGuiCol_Border 5 ImGuiCol_BorderShadow 6 ImGuiCol_Button 21 ImGuiCol_ButtonActive 23 ImGuiCol_ButtonHovered 22 ImGuiCol_CheckMark 18 ImGuiCol_ChildBg 3 ImGuiCol_DragDropTarget 43 ImGuiCol_FrameBg 7 ImGuiCol_FrameBgActive 9 ImGuiCol_FrameBgHovered 8 ImGuiCol_Header 24 ImGuiCol_HeaderActive 26 ImGuiCol_HeaderHovered 25 ImGuiCol_MenuBarBg 13 ImGuiCol_ModalWindowDimBg 47 ImGuiCol_NavHighlight 44 ImGuiCol_NavWindowingDimBg 46 ImGuiCol_NavWindowingHighlight 45 ImGuiCol_PlotHistogram 40 ImGuiCol_PlotHistogramHovered 41 ImGuiCol_PlotLines 38 ImGuiCol_PlotLinesHovered 39 ImGuiCol_PopupBg 4 ImGuiCol_ResizeGrip 30 ImGuiCol_ResizeGripActive 32 ImGuiCol_ResizeGripHovered 31 ImGuiCol_ScrollbarBg 14 ImGuiCol_ScrollbarGrab 15 ImGuiCol_ScrollbarGrabActive 17 ImGuiCol_ScrollbarGrabHovered 16 ImGuiCol_Separator 27 ImGuiCol_SeparatorActive 29 ImGuiCol_SeparatorHovered 28 ImGuiCol_SliderGrab 19 ImGuiCol_SliderGrabActive 20 ImGuiCol_Tab 33 ImGuiCol_TabActive 35 ImGuiCol_TabHovered 34 ImGuiCol_TabUnfocused 36 ImGuiCol_TabUnfocusedActive 37 ImGuiCol_Text 0 ImGuiCol_TextDisabled 1 ImGuiCol_TextSelectedBg 42 ImGuiCol_TitleBg 10 ImGuiCol_TitleBgActive 11 Continued on next page

518 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Table 26.1 – continued from previous page ImGuiCol_TitleBgCollapsed 12 ImGuiCol_WindowBg 2 ImGuiColorEditFlags_AlphaBar 65536 ImGuiColorEditFlags_AlphaPreview 131072 ImGuiColorEditFlags_AlphaPreviewHalf 262144 ImGuiColorEditFlags_DisplayHSV 2097152 ImGuiColorEditFlags_DisplayHex 4194304 ImGuiColorEditFlags_DisplayRGB 1048576 ImGuiColorEditFlags_Float 1.677722e+07 ImGuiColorEditFlags_HDR 524288 ImGuiColorEditFlags_InputHSV 2.684355e+08 ImGuiColorEditFlags_InputRGB 1.342177e+08 ImGuiColorEditFlags_NoAlpha 2 ImGuiColorEditFlags_NoDragDrop 512 ImGuiColorEditFlags_NoInputs 32 ImGuiColorEditFlags_NoLabel 128 ImGuiColorEditFlags_NoOptions 8 ImGuiColorEditFlags_NoPicker 4 ImGuiColorEditFlags_NoSidePreview 256 ImGuiColorEditFlags_NoSmallPreview 16 ImGuiColorEditFlags_NoTooltip 64 ImGuiColorEditFlags_None 0 ImGuiColorEditFlags_PickerHueBar 3.355443e+07 ImGuiColorEditFlags_PickerHueWheel 6.710886e+07 ImGuiColorEditFlags_Uint8 8388608 ImGuiColorEditFlags__OptionsDefault 1.772093e+08 ImGuiComboFlags_HeightLarge 8 ImGuiComboFlags_HeightLargest 16 ImGuiComboFlags_HeightMask_ 30 ImGuiComboFlags_HeightRegular 4 ImGuiComboFlags_HeightSmall 2 ImGuiComboFlags_NoArrowButton 32 ImGuiComboFlags_NoPreview 64 ImGuiComboFlags_None 0 ImGuiComboFlags_PopupAlignLeft 1 ImGuiCond_Always 1 ImGuiCond_Appearing 8 ImGuiCond_FirstUseEver 4 ImGuiCond_Once 2 ImGuiConfigFlags_IsSRGB 1048576 ImGuiConfigFlags_IsTouchScreen 2097152 ImGuiConfigFlags_NavEnableGamepad 2 ImGuiConfigFlags_NavEnableKeyboard 1 ImGuiConfigFlags_NavEnableSetMousePos 4 ImGuiConfigFlags_NavNoCaptureKeyboard 8 ImGuiConfigFlags_NoMouse 16 ImGuiConfigFlags_NoMouseCursorChange 32 ImGuiConfigFlags_None 0 ImGuiDir_Down 3 ImGuiDir_Left 0 Continued on next page

26.7. Flag / Enum 519 MBM Documentation, Release 3.1.f

Table 26.1 – continued from previous page ImGuiDir_None -1 ImGuiDir_Right 1 ImGuiDir_Up 2 ImGuiDragDropFlags_AcceptBeforeDelivery 1024 ImGuiDragDropFlags_AcceptNoDrawDefaultRect 2048 ImGuiDragDropFlags_AcceptNoPreviewTooltip 4096 ImGuiDragDropFlags_AcceptPeekOnly 3072 ImGuiDragDropFlags_None 0 ImGuiDragDropFlags_SourceAllowNullID 8 ImGuiDragDropFlags_SourceAutoExpirePayload 32 ImGuiDragDropFlags_SourceExtern 16 ImGuiDragDropFlags_SourceNoDisableHover 2 ImGuiDragDropFlags_SourceNoHoldToOpenOthers 4 ImGuiDragDropFlags_SourceNoPreviewTooltip 1 ImGuiFocusedFlags_AnyWindow 4 ImGuiFocusedFlags_ChildWindows 1 ImGuiFocusedFlags_None 0 ImGuiFocusedFlags_RootAndChildWindows 3 ImGuiFocusedFlags_RootWindow 2 ImGuiHoveredFlags_AllowWhenBlockedByActiveItem 32 ImGuiHoveredFlags_AllowWhenBlockedByPopup 8 ImGuiHoveredFlags_AllowWhenDisabled 128 ImGuiHoveredFlags_AllowWhenOverlapped 64 ImGuiHoveredFlags_AnyWindow 4 ImGuiHoveredFlags_ChildWindows 1 ImGuiHoveredFlags_None 0 ImGuiHoveredFlags_RectOnly 104 ImGuiHoveredFlags_RootAndChildWindows 3 ImGuiHoveredFlags_RootWindow 2 ImGuiInputTextFlags_AllowTabInput 1024 ImGuiInputTextFlags_AlwaysInsertMode 8192 ImGuiInputTextFlags_AutoSelectAll 16 ImGuiInputTextFlags_CallbackAlways 256 ImGuiInputTextFlags_CallbackCharFilter 512 ImGuiInputTextFlags_CallbackCompletion 64 ImGuiInputTextFlags_CallbackHistory 128 ImGuiInputTextFlags_CallbackResize 262144 ImGuiInputTextFlags_CharsDecimal 1 ImGuiInputTextFlags_CharsHexadecimal 2 ImGuiInputTextFlags_CharsNoBlank 8 ImGuiInputTextFlags_CharsScientific 131072 ImGuiInputTextFlags_CharsUppercase 4 ImGuiInputTextFlags_CtrlEnterForNewLine 2048 ImGuiInputTextFlags_EnterReturnsTrue 32 ImGuiInputTextFlags_NoHorizontalScroll 4096 ImGuiInputTextFlags_NoUndoRedo 65536 ImGuiInputTextFlags_None 0 ImGuiInputTextFlags_Password 32768 ImGuiInputTextFlags_ReadOnly 16384 ImGuiMouseButton_COUNT 5 Continued on next page

520 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Table 26.1 – continued from previous page ImGuiMouseButton_Left 0 ImGuiMouseButton_Middle 2 ImGuiMouseButton_Right 1 ImGuiMouseCursor_Arrow 0 ImGuiMouseCursor_Hand 7 ImGuiMouseCursor_None -1 ImGuiMouseCursor_NotAllowed 8 ImGuiMouseCursor_ResizeAll 2 ImGuiMouseCursor_ResizeEW 4 ImGuiMouseCursor_ResizeNESW 5 ImGuiMouseCursor_ResizeNS 3 ImGuiMouseCursor_ResizeNWSE 6 ImGuiMouseCursor_TextInput 1 ImGuiNavInput_Activate 0 ImGuiNavInput_Cancel 1 ImGuiNavInput_DpadDown 7 ImGuiNavInput_DpadLeft 4 ImGuiNavInput_DpadRight 5 ImGuiNavInput_DpadUp 6 ImGuiNavInput_FocusNext 13 ImGuiNavInput_FocusPrev 12 ImGuiNavInput_Input 2 ImGuiNavInput_LStickDown 11 ImGuiNavInput_LStickLeft 8 ImGuiNavInput_LStickRight 9 ImGuiNavInput_LStickUp 10 ImGuiNavInput_Menu 3 ImGuiNavInput_TweakFast 15 ImGuiNavInput_TweakSlow 14 ImGuiSelectableFlags_AllowDoubleClick 4 ImGuiSelectableFlags_AllowItemOverlap 16 ImGuiSelectableFlags_Disabled 8 ImGuiSelectableFlags_DontClosePopups 1 ImGuiSelectableFlags_None 0 ImGuiSelectableFlags_SpanAllColumns 2 ImGuiStyleVar_Alpha 0 ImGuiStyleVar_ButtonTextAlign 21 ImGuiStyleVar_ChildBorderSize 7 ImGuiStyleVar_ChildRounding 6 ImGuiStyleVar_FrameBorderSize 12 ImGuiStyleVar_FramePadding 10 ImGuiStyleVar_FrameRounding 11 ImGuiStyleVar_GrabMinSize 18 ImGuiStyleVar_GrabRounding 19 ImGuiStyleVar_IndentSpacing 15 ImGuiStyleVar_ItemInnerSpacing 14 ImGuiStyleVar_ItemSpacing 13 ImGuiStyleVar_PopupBorderSize 9 ImGuiStyleVar_PopupRounding 8 ImGuiStyleVar_ScrollbarRounding 17 Continued on next page

26.7. Flag / Enum 521 MBM Documentation, Release 3.1.f

Table 26.1 – continued from previous page ImGuiStyleVar_ScrollbarSize 16 ImGuiStyleVar_SelectableTextAlign 22 ImGuiStyleVar_TabRounding 20 ImGuiStyleVar_WindowBorderSize 3 ImGuiStyleVar_WindowMinSize 4 ImGuiStyleVar_WindowPadding 1 ImGuiStyleVar_WindowRounding 2 ImGuiStyleVar_WindowTitleAlign 5 ImGuiTabBarFlags_AutoSelectNewTabs 2 ImGuiTabBarFlags_FittingPolicyDefault_ 64 ImGuiTabBarFlags_FittingPolicyMask_ 192 ImGuiTabBarFlags_FittingPolicyResizeDown 64 ImGuiTabBarFlags_FittingPolicyScroll 128 ImGuiTabBarFlags_NoCloseWithMiddleMouseButton 8 ImGuiTabBarFlags_NoTabListScrollingButtons 16 ImGuiTabBarFlags_NoTooltip 32 ImGuiTabBarFlags_None 0 ImGuiTabBarFlags_Reorderable 1 ImGuiTabBarFlags_TabListPopupButton 4 ImGuiTabItemFlags_NoCloseWithMiddleMouseButton 4 ImGuiTabItemFlags_NoPushId 8 ImGuiTabItemFlags_None 0 ImGuiTabItemFlags_SetSelected 2 ImGuiTabItemFlags_UnsavedDocument 1 ImGuiTreeNodeFlags_AllowItemOverlap 4 ImGuiTreeNodeFlags_Bullet 512 ImGuiTreeNodeFlags_DefaultOpen 32 ImGuiTreeNodeFlags_FramePadding 1024 ImGuiTreeNodeFlags_Framed 2 ImGuiTreeNodeFlags_Leaf 256 ImGuiTreeNodeFlags_NavLeftJumpsBackHere 8192 ImGuiTreeNodeFlags_NoAutoOpenOnLog 16 ImGuiTreeNodeFlags_NoTreePushOnOpen 8 ImGuiTreeNodeFlags_None 0 ImGuiTreeNodeFlags_OpenOnArrow 128 ImGuiTreeNodeFlags_OpenOnDoubleClick 64 ImGuiTreeNodeFlags_Selected 1 ImGuiTreeNodeFlags_SpanAvailWidth 2048 ImGuiTreeNodeFlags_SpanFullWidth 4096 ImGuiWindowFlags_AlwaysAutoResize 64 ImGuiWindowFlags_AlwaysHorizontalScrollbar 32768 ImGuiWindowFlags_AlwaysUseWindowPadding 65536 ImGuiWindowFlags_AlwaysVerticalScrollbar 16384 ImGuiWindowFlags_HorizontalScrollbar 2048 ImGuiWindowFlags_MenuBar 1024 ImGuiWindowFlags_NoBackground 128 ImGuiWindowFlags_NoBringToFrontOnFocus 8192 ImGuiWindowFlags_NoCollapse 32 ImGuiWindowFlags_NoDecoration 43 ImGuiWindowFlags_NoFocusOnAppearing 4096 Continued on next page

522 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Table 26.1 – continued from previous page ImGuiWindowFlags_NoInputs 786944 ImGuiWindowFlags_NoMouseInputs 512 ImGuiWindowFlags_NoMove 4 ImGuiWindowFlags_NoNav 786432 ImGuiWindowFlags_NoNavFocus 524288 ImGuiWindowFlags_NoNavInputs 262144 ImGuiWindowFlags_NoResize 2 ImGuiWindowFlags_NoSavedSettings 256 ImGuiWindowFlags_NoScrollWithMouse 16 ImGuiWindowFlags_NoScrollbar 8 ImGuiWindowFlags_NoTitleBar 1 ImGuiWindowFlags_None 0 ImGuiWindowFlags_UnsavedDocument 1048576

26.7.3 ImGuiKey

ImGuiKey_A ImGuiKey_Backspace ImGuiKey_C ImGuiKey_Delete ImGuiKey_DownArrow ImGuiKey_End ImGuiKey_Enter ImGuiKey_Escape ImGuiKey_Home ImGuiKey_Insert ImGuiKey_KeyPadEnter ImGuiKey_LeftArrow ImGuiKey_PageDown ImGuiKey_PageUp ImGuiKey_RightArrow ImGuiKey_Space ImGuiKey_Tab ImGuiKey_UpArrow ImGuiKey_V ImGuiKey_X ImGuiKey_Y ImGuiKey_Z

Note: ImGuiKey is dependent on system operation. Use GetKeyIndex method to retrieve the value.

26.7. Flag / Enum 523 MBM Documentation, Release 3.1.f

524 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.8 General methods

26.8.1 Dummy

Dummy(size) Add a dummy item of given size. unlike InvisibleButton(), Dummy() won’t take the mouse click or be navigable into.

Parameters table – size {x,y}

Example:

tImGui= require"ImGui" local size= {x=100,y=100} tImGui.Dummy(size)

26.8.2 Indent

Indent(indent_w) Move content position toward the right, by style.IndentSpacing or indent_w if != 0

Parameters number – indent_w

Example:

tImGui= require"ImGui" local indent_w= 0.0 tImGui.Indent(indent_w)

26.8.3 InvisibleButton

InvisibleButton(str_id, size) Button behavior without the visuals, frequently useful to build custom behaviors using the public (along with IsItemActive, IsItemHovered, etc.)

Parameters • string – str_id • table – size {x,y} Returns boolean - result

Example:

tImGui= require"ImGui" local str_id='01' local size= {x=100,y=100} tImGui.InvisibleButton(str_id, size)

26.8. General methods 525 MBM Documentation, Release 3.1.f

26.8.4 NextColumn

NextColumn Next column, defaults to current row or next row if the current row is finished Example:

tImGui= require"ImGui" tImGui.NextColumn()

26.8.5 ResetMouseDragDelta

ResetMouseDragDelta(button) Parameters number – button Example:

tImGui= require"ImGui" local button=0 tImGui.ResetMouseDragDelta(button)

26.8.6 SameLine

SameLine(offset_from_start_x, spacing) Call between widgets or groups to layout them horizontally. X position given in window coordinates.

Parameters • number – offset_from_start_x • number – spacing

Example:

tImGui= require"ImGui" local offset_from_start_x= 0.0 local spacing=-1.0 tImGui.SameLine(offset_from_start_x, spacing)

26.8.7 Separator

Separator Separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. Example:

tImGui= require"ImGui" tImGui.Separator()

526 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.8.8 Spacing

Spacing Add vertical spacing. Example:

tImGui= require"ImGui" tImGui.Spacing()

26.8.9 Unindent

Unindent(indent_w) Move content position back to the left, by style.IndentSpacing or indent_w if != 0

Parameters number – indent_w

Example:

tImGui= require"ImGui" local indent_w= 0.0 tImGui.Unindent(indent_w)

26.9 Get methods

26.9.1 GetClipboardText

GetClipboardText Returns string - text Example:

tImGui= require"ImGui"

local text= tImGui.GetClipboardText() print(text)

Note: TODO: On Linux is used just the internal clipboard text.

26.9.2 GetScrollY

GetScrollY Get scrolling amount [0..GetScrollMaxY()]

Returns number - value

Example:

26.9. Get methods 527 MBM Documentation, Release 3.1.f

tImGui= require"ImGui"

tImGui.GetScrollY()

26.9.3 GetMainMenuBarHeight

GetMainMenuBarHeight Returns number - height Example:

tImGui= require"ImGui" local height= tImGui.GetMainMenuBarHeight()

26.9.4 GetMouseCursor

GetMouseCursor Get cursor type, reset in ImGui:NewFrame(), this is updated during the frame. Make sense be the last ImGui function called since everything was rendered.

Returns string - One of the followings: ImGuiMouseCursor_None, ImGuiMouseCursor_Arrow, ImGuiMouseCursor_TextInput, ImGuiMouseCursor_ResizeAll, ImGuiMouseCursor_ResizeNS, ImGuiMouseCursor_ResizeEW, ImGuiMouseCursor_ResizeNESW, ImGuiMouseCursor_ResizeNWSE, ImGuiMouseCursor_Hand, ImGuiMouseCursor_NotAllowed.

Example:

tImGui= require"ImGui" local sCursor= tImGui.GetMouseCursor()

26.9.5 GetWindowContentRegionMin

GetWindowContentRegionMin Content boundaries min (roughly (0,0)-Scroll), in window coordinates

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" local ImVec2= tImGui.GetWindowContentRegionMin() print(ImVec2.x,ImVec2.y)

528 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.9.6 GetWindowContentRegionMax

GetWindowContentRegionMax Content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWin- dowContentSize(), in window coordinates

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui"

local tMax= tImGui.GetWindowContentRegionMax() print(tMax.x,tMax.y)

26.9.7 GetContentRegionAvail

GetContentRegionAvail Returns table - ImVec2 {x,y} Example:

tImGui= require"ImGui" local ImVec2= tImGui.GetContentRegionAvail() print(ImVec2.x,ImVec2.y)

26.9.8 GetID

Calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiS- torage yourself GetID(ptr_id) Parameters string – ptr_id Returns number - ImGuiID Example:

tImGui= require"ImGui" local ptr_id='id_0' local id= tImGui.GetID(ptr_id)

26.9.9 GetContentRegionMax

GetContentRegionMax Current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates

Returns table - ImVec2 {x,y}

Example:

26.9. Get methods 529 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local ImVec2= tImGui.GetContentRegionMax() print(ImVec2.x,ImVec2.y)

26.9.10 GetMouseDragDelta

GetMouseDragDelta(button, lock_threshold) Return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (if lock_threshold < -1.0, uses io.MouseDraggingThreshold)

Parameters • number – button • number – lock_threshold Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" local button=0 local lock_threshold=-1.0 tImGui.GetMouseDragDelta(button, lock_threshold)

26.9.11 GetFrameHeight

GetFrameHeight ~FontSize + style.FramePadding.y * 2

Returns number - value

Example:

tImGui= require"ImGui" local frame_height= tImGui.GetFrameHeight() print(frame_height)

26.9.12 GetFrameHeightWithSpacing

GetFrameHeightWithSpacing ~FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecu- tive lines of framed widgets)

Returns number - value

Example:

530 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui"

local s= tImGui.GetFrameHeightWithSpacing() print(s)

26.9.13 GetMousePosOnOpeningCurrentPopup

GetMousePosOnOpeningCurrentPopup Retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves)

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" local ImVec2= tImGui.GetMousePosOnOpeningCurrentPopup() print(ImVec2.x,ImVec2.y)

26.9.14 GetMousePos

GetMousePos Shortcut to ImGui:GetIO().MousePos provided by user, to be consistent with other calls

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" local ImVec2= tImGui.GetMousePos() print(ImVec2.x,ImVec2.y)

26.9.15 GetStyleColorName

GetStyleColorName(idx) Get a string corresponding to the enum value (for display, saving, etc.).

Parameters string – idx Returns string - style

Example:

tImGui= require"ImGui" local idx='id 09' local style= tImGui.GetStyleColorName(idx) print(style)

26.9. Get methods 531 MBM Documentation, Release 3.1.f

26.9.16 GetKeyIndex

GetKeyIndex(imgui_key) Map ImGuiKey * values into user’s key index. == io.KeyMap[key] (0 to ImGuiKey_COUNT -1 (22))

Parameters string – imgui_key * any of ImGuiKey_XXX Returns number - value

Example:

tImGui= require"ImGui" local imgui_key='ImGuiKey_DownArrow' local key_down_arrow= tImGui.GetKeyIndex(imgui_key) if tImGui.IsKeyDown(key_down_arrow) then print('Pressed key arrow down') end

GetKeyIndex(imgui_key) Map ImGuiKey * values into user’s key index. == io.KeyMap[key] (0 to ImGuiKey_COUNT -1 (22))

Parameters number – imgui_key * Dependent on SO. prefer to use ImGuiKey_XXX Returns number - value

Example:

tImGui= require"ImGui" local imgui_key= 13 -- ImGuiKey_Enter if Windows local enter= tImGui.GetKeyIndex(imgui_key) print(enter)

26.9.17 GetKeyPressedAmount

GetKeyPressedAmount(ImGuiKey, repeat_delay, rate) Uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate

Parameters • string – ImGuiKey or raw index as number • number – repeat_delay • number – rate Returns number - value

Example:

tImGui= require"ImGui" local ImGuiKey='ImGuiKey_Space' local repeat_delay= 0.2 local rate=1

tImGui.GetKeyPressedAmount(ImGuiKey, repeat_delay, rate)

532 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.9.18 GetScrollMaxY

GetScrollMaxY Get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y

Returns number - value

Example:

tImGui= require"ImGui"

tImGui.GetScrollMaxY()

26.9.19 GetScrollMaxX

GetScrollMaxX Get maximum scrolling amount ~~ ContentSize.X - WindowSize.X

Returns number - value

Example:

tImGui= require"ImGui" tImGui.GetScrollMaxX()

26.9.20 GetScrollX

GetScrollX Get scrolling amount [0..GetScrollMaxX()]

Returns number - value

Example:

tImGui= require"ImGui"

local ret= tImGui.GetScrollX() print(ret)

26.9.21 GetIO

Note: It is not exported to lua. It is used internally by the engine.

26.9. Get methods 533 MBM Documentation, Release 3.1.f

26.9.22 GetTextLineHeight

GetTextLineHeight ~FontSize

Returns number - value

Example:

tImGui= require"ImGui"

tImGui.GetTextLineHeight()

26.9.23 GetWindowContentRegionWidth

GetWindowContentRegionWidth Returns number - value Example:

tImGui= require"ImGui"

tImGui.GetWindowContentRegionWidth()

26.9.24 GetWindowHeight

GetWindowHeight Get current window height (shortcut for GetWindowSize().y)

Returns number - value

Example:

tImGui= require"ImGui" local h= tImGui.GetWindowHeight()

26.9.25 GetTextLineHeightWithSpacing

GetTextLineHeightWithSpacing ~FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)

Returns number - value

Example:

tImGui= require"ImGui"

tImGui.GetTextLineHeightWithSpacing()

534 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.9.26 GetWindowSize

GetWindowSize Get current window size

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui"

local size= tImGui.GetWindowSize() print(size.x,size.y)

26.9.27 GetColorU32

GetColorU32(color) Retrieve given color with style alpha applied

Parameters • number – color • number – alpha_mul Returns number - ImU32

Example:

tImGui= require"ImGui" local color=1 local alpha_mul= 1.0 tImGui.GetColorU32(color,alpha_mul)

26.9.28 GetItemRectMin

GetItemRectMin Get upper-left bounding rectangle of the last item (screen space)

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" ImVec2= tImGui.GetItemRectMin()

26.9.29 GetItemRectSize

GetItemRectSize Get size of last item

26.9. Get methods 535 MBM Documentation, Release 3.1.f

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" ImVec2= tImGui.GetItemRectSize()

26.9.30 GetItemRectMax

GetItemRectMax Get lower-right bounding rectangle of the last item (screen space)

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" ImVec2= tImGui.GetItemRectMax()

26.9.31 GetFrameCount

GetFrameCount Get global ImGui frame count. incremented by 1 every frame.

Returns number - value

Example:

tImGui= require"ImGui" local fps= tImGui.GetFrameCount()

26.9.32 GetTime

GetTime Get global ImGui time. incremented by io.DeltaTime every frame.

Returns number - value

Example:

tImGui= require"ImGui" tImGui.GetTime()

26.9.33 GetColorU32

GetColorU32(idx, alpha_mul) Retrieve given style color with style alpha applied and optional extra alpha multiplier

536 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • number – idx • number – alpha_mul Returns number - ImU32

Example:

tImGui= require"ImGui" local idx=0 local alpha_mul= 1.0

tImGui.GetColorU32(idx, alpha_mul)

26.9.34 GetFontSize

GetFontSize Get current font size (= height in pixels) of current font with current scale applied

Returns number - value

Example:

tImGui= require"ImGui" local s= tImGui.GetFontSize() print(s)

26.9.35 GetColumnOffset

GetColumnOffset(column_index) Get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f

Parameters number – column_index Returns number - value

Example:

tImGui= require"ImGui" local column_index=-1

local ret= tImGui.GetColumnOffset(column_index)

26.9.36 GetDragDropPayload

GetDragDropPayload Peek directly into the current payload from anywhere. may return nil. use ImGuiPay- load:IsDataType() to test for the payload type.

26.9. Get methods 537 MBM Documentation, Release 3.1.f

Returns table - ImGuiPayload (might be nil)

Example:

tImGui= require"ImGui" local ImGuiPayload= tImGui.GetDragDropPayload()

26.9.37 GetColumnsCount

GetColumnsCount Returns number - value Example:

tImGui= require"ImGui" local s= tImGui.GetColumnsCount() print(s)

26.9.38 GetFontTexUvWhitePixel

GetFontTexUvWhitePixel Get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" local ImVec2= tImGui.GetFontTexUvWhitePixel() print(ImVec2.x,ImVec2.y)

26.9.39 GetColumnWidth

GetColumnWidth(column_index) Get column width (in pixels). pass -1 to use current column. Useful to calculate the width till the end when there is more than one component in the same column.

Parameters number – column_index Returns number - value

Example:

tImGui= require"ImGui" local column_index=-1 local width= tImGui.GetColumnWidth(column_index) print(width)

538 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.9.40 GetVersion

GetVersion Get the compiled version string e.g. “1.23” (essentially the compiled value for IMGUI_VERSION)

Returns string - version

Example:

tImGui= require"ImGui" local version= tImGui.GetVersion() print(version) --1.75 WIP

26.9.41 GetColumnIndex

GetColumnIndex Get current column index

Returns number - value

Example:

tImGui= require"ImGui" local index= tImGui.GetColumnIndex() print(index)

26.9.42 GetFont

GetFont Get current font

Returns table - ImFont

Example:

tImGui= require"ImGui" tImGui.GetFont()

26.9.43 GetStyleColorVec4

GetStyleColorVec4(idx) Retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), other- wise use GetColorU32() to get style color with style alpha baked in.

Parameters number – idx (Start from 0) Returns table - rgb {r,g,b,a}

Example:

26.9. Get methods 539 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local idx=0 local color= tImGui.GetStyleColorVec4(0) print('color',color.r,color.g,color.b,color.a)

26.9.44 GetCursorScreenPos

GetCursorScreenPos Cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API)

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" local ImVec2= tImGui.GetCursorScreenPos() print(ImVec2.x,ImVec2.y)

26.9.45 GetCursorPos

GetCursorPos Cursor position in window coordinates (relative to window position)

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" local ImVec2= tImGui.GetCursorPos() print(ImVec2.x,ImVec2.y)

26.9.46 GetWindowPos

GetWindowPos Get current window position in screen space (useful if you want to do your own drawing via the DrawList API)

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" local ImVec2= tImGui.GetWindowPos() print(ImVec2.x,ImVec2.y)

540 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.9.47 GetCursorPosX

GetCursorPosX (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion * etc.

Returns number - value

Example:

tImGui= require"ImGui" local x= tImGui.GetCursorPosX() print(x)

26.9.48 GetCursorPosY

GetCursorPosY other functions such as GetCursorScreenPos or everything in ImDrawList:

Returns number - value

Example:

tImGui= require"ImGui" local y= tImGui.GetCursorPosY()

26.9.49 GetContentRegionAvailWidth

GetContentRegionAvailWidth Returns number - value Example:

tImGui= require"ImGui" local width= tImGui.GetContentRegionAvailWidth()

26.9.50 GetCursorStartPos

GetCursorStartPos Initial cursor position in window coordinates

Returns table - ImVec2 {x,y}

Example:

tImGui= require"ImGui" local ImVec2= tImGui.GetCursorStartPos()

26.9. Get methods 541 MBM Documentation, Release 3.1.f

26.9.51 GetWindowWidth

GetWindowWidth Get current window width (shortcut for GetWindowSize().x)

Returns number - value

Example:

tImGui= require"ImGui" local w= tImGui.GetWindowWidth()

26.9.52 GetZoom

GetZoom Get current zoom or scrolling wheel (zoom might means literally zoom gesture on mobile).

Returns number - value (-1, 0 or 1).

Example:

tImGui= require"ImGui" local zoom= tImGui.GetZoom()

26.10 ImDrawList

ImDrawList is an internal class in the ImGui library responsible to draw native primitive commands. ImDrawList is never accessed from Lua side. All methods are available through the ImGui module. Use SetImDrawListToBackground and SetImDrawListToForeground to any subsequent command from ImDrawList. This enable/disable get ImDrawList from background or foreground.

26.10.1 SetImDrawListToBackground

SetImDrawListToBackground(enable) Parameters boolean – enable Example:

tImGui= require"ImGui" tImGui.SetImDrawListToBackground(true) --any subsequent draw using ImDrawList will be added to background list.

26.10.2 SetImDrawListToForeground

SetImDrawListToForeground(enable) Parameters boolean – enable

542 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Example: tImGui= require"ImGui" tImGui.SetImDrawListToForeground(true) --any subsequent draw using ImDrawList will be added to foreground list.

26.10.3 AddImageQuad

AddImageQuad(texture_file_name, p1, p2, p3, p4, color, uv1, uv2, uv3, uv4) Parameters • string – texture file name or number ( id of texture ) • table – p1 {x,y} • table – p2 {x,y} • table – p3 {x,y} • table – p4 {x,y} • table – color {r,g,b,a} default is {r=1,g=1,g=1,a=1} • table – uv1 {x,y} default is {x=0,y=0} • table – uv2 {x,y} default is {x=1,y=0} • table – uv3 {x,y} default is {x=1,y=1} • table – uv4 {x,y} default is {x=0,y=1} Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then tImGui.Text('Some nice content to show!') local texture_file_name='HB_smile.png' local p1= {x=0,y=0} local p2= {x=0,y=100} local p3= {x=100,y=100} local p4= {x=100,y=0} local color= {r=1,g=1,b=1,a=1} local uv1= {x=0,y=0} local uv2= {x=0,y=1} local uv3= {x=1,y=1} local uv4= {x=1,y=0} tImGui.AddImageQuad(texture_file_name, p1, p2, p3, p4, color, uv1, uv2, uv3,

˓→uv4) end tImGui.End() end

26.10. ImDrawList 543 MBM Documentation, Release 3.1.f

download HB_smile.

26.10.4 AddText

AddText(pos, color, text_begin, text_end) Parameters • table – pos {x,y} • table – color {r,g,b,a} • string – text_begin • string – text_end might be omitted Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then tImGui.Text('Some nice content to show!') local ImVec2= tImGui.GetWindowPos()

local pos= {x=100+ ImVec2.x,y=100+ ImVec2.y} local color= {r=1,g=1,b=1,a=1} local text_begin='123456789 \n 123456789 \n123456789 \n123456789

˓→\n123456789 \n'

tImGui.AddText(pos, color, text_begin) end tImGui.End() end

26.10.5 AddPolyline

AddPolyline(points, color, closed, thickness) Parameters • table – points {{x,y},{x,y},{x,y},...} • table – color {r,g,b,a} • boolean – closed • number – thickness Example:

544 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos() local points= {{x=0,y=0},{x=100,y=100},{x=100,y=200},{x=0,y=200}} local color= {r=1,g=1,b=1,a=1} local closed= false local thickness=1

for i=1,#points do points[i].x= points[i].x+ winPos.x points[i].y= points[i].y+ winPos.y end

tImGui.AddPolyline(points, color, closed, thickness) end tImGui.End() end

26.10.6 AddNgonFilled

AddNgonFilled(center, radius, color, num_segments) Parameters • table – center {x,y} • number – radius

26.10. ImDrawList 545 MBM Documentation, Release 3.1.f

• table – color {r,g,b,a} • number – num_segments Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos()

local center= {x=winPos.x+ 100,y=winPos.y+ 100} local radius= 15 local color= {r=1,g=1,b=1,a=1} local num_segments= 15

tImGui.AddNgonFilled(center, radius, color, num_segments) end tImGui.End() end tImGui.AddNgonFilled(center, radius, color, num_segments)

26.10.7 AddNgon

AddNgon(center, radius, color, num_segments, thickness)

546 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • table – center {x,y} • number – radius • table – color {r,g,b,a} • number – num_segments • number – thickness Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos()

local center= {x=winPos.x+ 100,y=winPos.y+ 100} local radius= 15 local color= {r=1,g=0,b=1,a=1} local num_segments=5 local thickness= 3.0

tImGui.AddNgon(center, radius, color, num_segments, thickness) end tImGui.End() end

26.10. ImDrawList 547 MBM Documentation, Release 3.1.f

26.10.8 AddCircle

AddCircle(center, radius, color, num_segments, thickness) Parameters • table – center {x,y} • number – radius • table – color {r,g,b,a} • number – num_segments • number – thickness Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos()

local center= {x=winPos.x+ 50,y=winPos.y+ 50} local radius= 15 local color= {r=1,g=0,b=0,a=0.8} local num_segments= 12 local thickness= 1.0

tImGui.AddCircle(center, radius, color, num_segments, thickness) end tImGui.End() end

548 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.10.9 AddConvexPolyFilled

AddConvexPolyFilled(points, color) Note: Anti-aliased filling requires points to be in clockwise order.

Parameters • table – points {{x,y},{x,y},{x,y},...} • table – color {r,g,b,a}

Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

local winPos= tImGui.GetWindowPos()

local points= {{x=10,y=10},{x=200,y=10},{x=200,y=100},{x=30,y=90}} local color= {r=0,g=0.2,b=1,a=0.5}

for i=1,#points do points[i].x= points[i].x+ winPos.x points[i].y= points[i].y+ winPos.y end

tImGui.AddConvexPolyFilled(points, color)

tImGui.Text('Some nice content to show!') end tImGui.End() end

26.10.10 AddImage

AddImage(texture_file_name, p_min, p_max, color, uv_min, uv_max) Parameters

26.10. ImDrawList 549 MBM Documentation, Release 3.1.f

• string – texture file name or number ( id of texture ) • table – p_min {x,y} • table – p_max {x,y} • table – color {r,g,b,a} default is {r=1,g=1,b=1,a=1} • table – uv_min {x,y} default is {x=0,y=0} • table – uv_max {x,y} default is {x=1,y=1} Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

local winPos= tImGui.GetWindowPos()

local texture_file_name='HB_smile.png' local color= {r=1,g=1,b=1,a=1} local p_min= winPos local p_max= {x=winPos.x+ 100,y= winPos.y+ 100} local uv_min= {x=0,y=0} local uv_max= {x=1,y=1}

tImGui.AddImage(texture_file_name, p_min, p_max, color, uv_min,uv_max )

tImGui.Text('Some nice content to show!') end tImGui.End() end download HB_smile.

26.10.11 AddBezierCurve

AddBezierCurve(p1, p2, p3, p4, color, thickness, num_segments)

550 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • table – p1 {x,y} • table – p2 {x,y} • table – p3 {x,y} • table – p4 {x,y} • table – color {r,g,b,a} • number – thickness • number – num_segments Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos()

local p1= winPos local p2= {x=winPos.x+ 50,y=winPos.y+ 50} local p3= {x=winPos.x+ 150,y=winPos.y+ 150} local p4= {x=winPos.x+ 200,y=winPos.y+ 50} local color= {r=1,g=1,b=0,a=1} local thickness=2 local num_segments= 30

tImGui.AddBezierCurve(p1, p2, p3, p4, color, thickness, num_segments)

end tImGui.End() end

26.10. ImDrawList 551 MBM Documentation, Release 3.1.f

26.10.12 AddDrawCmd

AddDrawCmd This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible Example:

tImGui= require"ImGui" tImGui.AddDrawCmd()

26.10.13 AddImageRounded

AddImageRounded(texture_file_name, p_min, p_max, uv_min, uv_max, color, rounding, round- ing_corners) Parameters • string – texture file name or number ( id of texture ) • table – p_min {x,y} • table – p_max {x,y} • table – color {r,g,b,a} • table – uv_min {x,y} default is {x=0,y=0} • table – uv_max {x,y} default is {x=1,y=1} • number – rounding default is 0.0 • number – rounding_corners default is ImDrawCornerFlags_All Example:

tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!') (continues on next page)

552 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page)

local winPos= tImGui.GetWindowPos()

local texture_file_name='crate.png' local p_min= {x= 100,y= 100} local p_max= {x= 200,y= 200} local color= {r=1,g=1,b=1,a=1} local uv_min= {x=0,y=0} local uv_max= {x=1,y=1} local rounding= 20.0 local rounding_corners= tImGui.Flags('ImDrawCornerFlags_All')

tImGui.AddImageRounded(texture_file_name, p_min, p_max, color, uv_min, uv_max,

˓→ rounding, rounding_corners)

end tImGui.End() end

Figure 26.2: Texture original

Figure 26.3: AddImageRounded download crate.

26.10. ImDrawList 553 MBM Documentation, Release 3.1.f

26.10.14 AddTriangleFilled

AddTriangleFilled(p1, p2, p3, color) Parameters • table – p1 {x,y} • table – p2 {x,y} • table – p3 {x,y} • table – color {r,g,b,a} Example: tImGui= require"ImGui" function loop(delta) local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local p1= {x=10,y=100} local p2= {x=50,y=200} local p3= {x=100,y=100} local color= {r=1,g=1,b=0,a=1}

tImGui.AddTriangleFilled(p1, p2, p3, color)

end tImGui.End() end

26.10.15 AddCircleFilled

AddCircleFilled(center, radius, color, num_segments)

554 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • table – center {x,y} • number – radius • table – color {r,g,b,a} • number – num_segments Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos() local center= {x=winPos.x+ 50,y=winPos.y+ 50} local radius= 15 local color= {r=0,g=0,b=1,a=1} local num_segments= 12

tImGui.AddCircleFilled(center, radius, color, num_segments)

end tImGui.End() end

26.10.16 AddLine

AddLine(p1, p2, color, thickness) Parameters • table – p1 {x,y} • table – p2 {x,y} • number – color {r,g,b,a} • number – thickness Example:

26.10. ImDrawList 555 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos() local p1= winPos local p2= {x= winPos.x+ 50, y= winPos.y+ 50} local color= {r=1, g=1, b=0, a=1} local thickness= 1.0

tImGui.AddLine(p1, p2, color, thickness)

end tImGui.End() end

26.10.17 AddTriangle

AddTriangle(p1, p2, p3, color, thickness) Parameters • table – p1 {x,y} • table – p2 {x,y} • table – p3 {x,y} • table – color {r,g,b,a} • number – thickness Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0 (continues on next page)

556 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page)

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos() local p1= {x=100+ winPos.x,y=100+ winPos.y} local p2= {x=150+ winPos.x,y=200+ winPos.y} local p3= {x=200+ winPos.x,y=100+ winPos.y} local color= {r=1,g=1,b=1,a=1} local thickness= 10.0

tImGui.AddTriangle(p1, p2, p3, color, thickness)

end tImGui.End() end

26.10.18 AddRect

AddRect(p_min, p_max, color, rounding, rounding_corners, thickness) A: upper-left, b: lower-right (== upper-left + size), rounding_corners_flags: 4 bits corresponding to which corner to round

Parameters • table – p_min {x,y} • table – p_max {x,y} • table – color {r,g,b,a}

26.10. ImDrawList 557 MBM Documentation, Release 3.1.f

• number – rounding • table – rounding_corners • number – thickness

Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local p_min= {x=100,y=100} local p_max= {x=200,y=200} local color= {r=1,g=1,b=1,a=1} local rounding= 10.0 local rounding_corners= tImGui.Flags('ImDrawCornerFlags_All') local thickness= 5.0

tImGui.AddRect(p_min, p_max, color, rounding, rounding_corners, thickness)

end tImGui.End() end

26.10.19 AddRectFilledMultiColor

AddRectFilledMultiColor(p_min, p_max, color_upr_left, color_upr_right, color_bot_right, color_bot_left) Parameters

558 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

• table – p_min {x,y} • table – p_max {x,y} • table – color_upr_left {r,g,b,a} • table – color_upr_right {r,g,b,a} • table – color_bot_right {r,g,b,a} • table – color_bot_left {r,g,b,a} Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos() local p_min= winPos local p_max= {x= winPos.x+ 100, y= winPos.y+ 90} local color_upr_left= {r=1, g=0, b=0, a=1} local color_upr_right= {r=0, g=1, b=0, a=1} local color_bot_right= {r=0, g=0, b=1, a=1} local color_bot_left= {r=1, g=1, b=0, a=1}

tImGui.AddRectFilledMultiColor(p_min, p_max, color_upr_left, color_upr_right,

˓→color_bot_right, color_bot_left)

end tImGui.End() end

26.10.20 AddRectFilled

AddRectFilled(p_min, p_max, color, rounding, rounding_corners) A: upper-left, b: lower-right (== upper-left + size)

Parameters

26.10. ImDrawList 559 MBM Documentation, Release 3.1.f

• table – p_min {x,y} • table – p_max {x,y} • table – color {r,g,b,a} • number – rounding • number – rounding_corners

Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos() local p_min= {x=winPos.x+ 50,y=winPos.y+ 50} local p_max= {x=winPos.x+ 150,y=winPos.y+ 100} local color= {r=0,g=0,b=0.5,a=1} local rounding= 20.0 local rounding_corners= tImGui.Flags('ImDrawCornerFlags_All')

tImGui.AddRectFilled(p_min, p_max, color, rounding, rounding_corners)

end tImGui.End() end

26.10.21 AddQuadFilled

AddQuadFilled(p1, p2, p3, p4, color) Parameters • table – p1 {x,y}

560 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

• table – p2 {x,y} • table – p3 {x,y} • table – p4 {x,y} • table – color {r,g,b,a} Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos() local p1= {x= winPos.x+ 100 ,y= winPos.y+ 100} local p2= {x= winPos.x+ 200 ,y= winPos.y+ 100} local p3= {x= winPos.x+ 200 ,y= winPos.y+ 200} local p4= {x= winPos.x+ 100 ,y= winPos.y+ 150} local color= {r=1,g=0,b=0,a=1}

tImGui.AddQuadFilled(p1, p2, p3, p4, color)

end tImGui.End() end

26.10. ImDrawList 561 MBM Documentation, Release 3.1.f

26.10.22 AddQuad

AddQuad(p1, p2, p3, p4, color, thickness) Parameters • table – p1 {x,y} • table – p2 {x,y} • table – p3 {x,y} • table – p4 {x,y} • table – color {r,g,b,a} • number – thickness Example: tImGui= require"ImGui" function loop(delta)

local title='Some window' local closeable= true local flags=0

local is_opened, closed_clicked= tImGui.Begin(title, closeable, flags)

if is_opened then

tImGui.Text('Some nice content to show!')

local winPos= tImGui.GetWindowPos() local p1= {x= winPos.x+ 100 ,y= winPos.y+ 100} local p2= {x= winPos.x+ 200 ,y= winPos.y+ 100} local p3= {x= winPos.x+ 200 ,y= winPos.y+ 200} local p4= {x= winPos.x+ 100 ,y= winPos.y+ 150} local color= {r=1,g=1,b=1,a=1} local thickness= 10.0

tImGui.AddQuad(p1, p2, p3, p4, color, thickness)

end tImGui.End() end

26.10.23 ImDrawList PopTextureID

PopTextureID Example: tImGui= require"ImGui" tImGui.PopTextureID()

562 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.10.24 ImDrawList PushTextureID

PushTextureID(texture_filename) Parameters string – texture_filename Example:

tImGui= require"ImGui" local texture_filename='mario.png'

tImGui.PushTextureID(texture_filename)

NB: all primitives needs to be reserved via PrimReserve() beforehand!

26.11 Is methods

26.11.1 IsAnyItemHovered

IsAnyItemHovered Is any item hovered?

Returns boolean - result

Example:

tImGui= require"ImGui" local hovered= tImGui.IsAnyItemHovered() print(hovered)

26.11. Is methods 563 MBM Documentation, Release 3.1.f

26.11.2 IsAnyMouseDown

IsAnyMouseDown Is any mouse button held?

Returns boolean - result

Example: tImGui= require"ImGui" local result= tImGui.IsAnyMouseDown() print(result)

26.11.3 IsAnyWindowHovered

IsAnyWindowHovered Returns boolean - result Example: tImGui= require"ImGui" local result= tImGui.IsAnyWindowHovered() print(result)

26.11.4 IsAnyWindowFocused

IsAnyWindowFocused Returns boolean - result Example: tImGui= require"ImGui" local result= tImGui.IsAnyWindowFocused() print(result)

26.11.5 IsAnyItemFocused

IsAnyItemFocused Is any item focused?

Returns boolean - result

Example: tImGui= require"ImGui" local result= tImGui.IsAnyItemFocused() print(result)

564 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.11.6 IsAnyItemActive

IsAnyItemActive Is any item active?

Returns boolean - result

Example:

tImGui= require"ImGui" local result= tImGui.IsAnyItemActive() print(result)

26.11.7 IsItemDeactivatedAfterEdit

IsItemDeactivatedAfterEdit Was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item).

Returns boolean - result

Example:

tImGui= require"ImGui" local result= tImGui.IsItemDeactivatedAfterEdit() print(result)

26.11.8 IsItemEdited

IsItemEdited Did the last item modify its underlying value this frame? or was pressed? This is generally the same as the “bool” return value of many widgets.

Returns boolean - result

Example:

tImGui= require"ImGui" local result= tImGui.IsItemEdited() print(result)

26.11.9 IsItemToggledOpen

IsItemToggledOpen Was the last item open state toggled? set by TreeNode().

Returns boolean - result

26.11. Is methods 565 MBM Documentation, Release 3.1.f

Example:

tImGui= require"ImGui" local result= tImGui.IsItemToggledOpen() print(result)

26.11.10 IsItemDeactivatedAfterChange

IsItemDeactivatedAfterChange Returns boolean - result Example:

tImGui= require"ImGui" local result= tImGui.IsItemDeactivatedAfterChange() print(result)

26.11.11 IsItemDeactivated

IsItemDeactivated Was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing.

Returns boolean - result

Example:

tImGui= require"ImGui" local result= tImGui.IsItemDeactivated() print(result)

26.11.12 IsItemActive

IsItemActive Is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don’t interact will always return false)

Returns boolean - result

Example:

tImGui= require"ImGui" local result= tImGui.IsItemActive() print(result)

26.11.13 IsItemHovered

IsItemHovered(flags)

566 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options.

Parameters number – flags Returns boolean - result

Example:

tImGui= require"ImGui" local flags=0 local result= tImGui.IsItemHovered(flags) print(result)

26.11.14 IsItemActivated

IsItemActivated Was the last item just made active (item was previously inactive).

Returns boolean - result

Example:

tImGui= require"ImGui" local result= tImGui.IsItemActivated() print(result)

26.11.15 IsItemVisible

IsItemVisible Is the last item visible? (items may be out of sight because of clipping/scrolling)

Returns boolean - result

Example:

tImGui= require"ImGui" local result= tImGui.IsItemVisible() print(result)

26.11.16 IsItemFocused

IsItemFocused Is the last item focused for keyboard/gamepad navigation?

Returns boolean - result

Example:

26.11. Is methods 567 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local result= tImGui.IsItemFocused() print(result)

26.11.17 IsItemClicked

IsItemClicked(mouse_button) Is the last item clicked? (e.g. button/node just clicked on) == IsMouseClicked(mouse_button) && IsItemHovered()

Parameters number – mouse_button (0=left, 1=right, 2=middle) Returns boolean - result

Example:

tImGui= require"ImGui" local mouse_button=0 local result= tImGui.IsItemClicked(mouse_button) print(result)

26.11.18 IsKeyReleased

IsKeyReleased(ImGuiKey) Was key released (went from Down to !Down)?

Parameters string – ImGuiKey or raw index as number Returns boolean - result

Example:

tImGui= require"ImGui" local ImGuiKey='ImGuiKey_Enter' local result= tImGui.IsKeyReleased(ImGuiKey) print(result)

26.11.19 IsKeyDown

IsKeyDown(ImGuiKey) Is key being held. == io.KeysDown[key_index].

Parameters string – ImGuiKey or raw index as number Returns boolean - result

Example:

568 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local ImGuiKey='ImGuiKey_A' local result= tImGui.IsKeyDown(ImGuiKey) print(result)

26.11.20 IsKeyPressed

IsKeyPressed(ImGuiKey, is_repeated) Was key pressed (went from !Down to Down)? if is_repeated = true, uses io.KeyRepeatDelay / KeyRepeatRate

Parameters • string – ImGuiKey or raw index as number • boolean – is_repeated Returns boolean - result

Example:

tImGui= require"ImGui" local ImGuiKey='ImGuiKey_Space' local is_repeated= true local result= tImGui.IsKeyPressed(ImGuiKey,is_repeated) print(result)

26.11.21 IsMouseDown

IsMouseDown(button) Is mouse button held? (0=left, 1=right, 2=middle)

Parameters number – button Returns boolean - result

Example:

tImGui= require"ImGui" local button=1 local result= tImGui.IsMouseDown(button) print(result)

26.11.22 IsMouseDoubleClicked

IsMouseDoubleClicked(button) Did mouse button double-clicked? a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime.

Parameters number – button Returns boolean - result

26.11. Is methods 569 MBM Documentation, Release 3.1.f

Example: tImGui= require"ImGui" local button=0 local result= tImGui.IsMouseDoubleClicked(button) print(result)

26.11.23 IsMouseClicked

IsMouseClicked(button, is_repeated) Did mouse button clicked? (went from !Down to Down) (0=left, 1=right, 2=middle)

Parameters • number – button • boolean – is_repeated Returns boolean - result

Example: tImGui= require"ImGui" local button=0 local is_repeated= false local result= tImGui.IsMouseClicked(button,is_repeated) print(result)

26.11.24 IsMouseHoveringRect

IsMouseHoveringRect(r_min, r_max, clip) Is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block.

Parameters • table – r_min {x,y} • table – r_max {x,y} • boolean – clip Returns boolean - result

Example: tImGui= require"ImGui" local r_min= {x=0,y=0} local r_max= {x= 100,y= 100} local clip= true local result= tImGui.IsMouseHoveringRect(r_min, r_max, clip) print(result)

570 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.11.25 IsMouseDragging

IsMouseDragging(button, lock_threshold) Is mouse dragging? (if lock_threshold < -1.0, uses io.MouseDraggingThreshold)

Parameters • number – button • number – lock_threshold Returns boolean - result

Example:

tImGui= require"ImGui" local button=0 local lock_threshold=-1.0 local result= tImGui.IsMouseDragging(button, lock_threshold) print(result)

26.11.26 IsMouseReleased

IsMouseReleased(button) Did mouse button released? (went from Down to !Down)

Parameters number – button Returns boolean - result

Example:

tImGui= require"ImGui" local button=0 local result= tImGui.IsMouseReleased(button) print(result)

26.11.27 IsMousePosValid

IsMousePosValid(mouse_pos) By convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available

Parameters table – mouse_pos {x,y} Returns boolean - result

Example:

tImGui= require"ImGui" local mouse_pos= {x=100,y=100} local result= tImGui.IsMousePosValid(mouse_pos) print(result)

26.11. Is methods 571 MBM Documentation, Release 3.1.f

26.11.28 IsPopupOpen

IsPopupOpen(str_id, * flag) Return true if the popup is open at the current begin-ed level of the popup stack.

Parameters • string – str_id (might be nil) • param – flag (default is 0) Returns boolean - result

Example:

tImGui= require"ImGui" local str_id='01' tImGui.IsPopupOpen(str_id)

IsPopupOpen(id) Return true if the popup is open at the current begin-ed level of the popup stack.

Parameters number – id Returns boolean - result

Example:

tImGui= require"ImGui" local id=1 tImGui.IsPopupOpen(id)

26.11.29 IsRectVisible

IsRectVisible(rect_min, rect_max) Test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user’s side.

Parameters • table – rect_min {x,y} • table – rect_max {x,y} Returns boolean - result

Example:

tImGui= require"ImGui" local rect_min= {x=0,y=0} local rect_max= {x= 100,y= 100} local result= tImGui.IsRectVisible(rect_min, rect_max) print(result)

572 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.11.30 IsScrollVisible

IsScrollVisible Return the state of the scroll (visible / not visible)

Returns boolean - x, boolean - y

Example:

tImGui= require"ImGui" local x,y= tImGui.IsScrollVisible() print('Scroll visible in the axis x?',x) print('Scroll visible in the axis y?',y)

26.11.31 IsWindowFocused

IsWindowFocused(flags) Is current window focused? or its root/child, depending on flags. see flags for options.

Parameters number – flags Returns boolean - result

Example:

tImGui= require"ImGui" local flags=0 local result= tImGui.IsWindowFocused(flags) print(result)

26.11.32 IsWindowHovered

IsWindowHovered(flags) Is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to ImGui or to your app, you should use the ‘io.WantCaptureMouse’ boolean for that! Please read the FAQ!

Parameters number – flags Returns boolean - result

Example:

tImGui= require"ImGui" local flags=0 local result= tImGui.IsWindowHovered(flags) print(result)

26.11. Is methods 573 MBM Documentation, Release 3.1.f

26.11.33 IsWindowCollapsed

IsWindowCollapsed Returns boolean - result Example:

tImGui= require"ImGui" local result= tImGui.IsWindowCollapsed() print(result)

26.11.34 IsWindowAppearing

IsWindowAppearing Returns boolean - result Example:

tImGui= require"ImGui" local result= tImGui.IsWindowAppearing() print(result)

26.12 Save / Load methods

26.12.1 SaveIniSettingsToMemory

SaveIniSettingsToMemory Return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings.

Returns string - setting as string

Example:

tImGui= require"ImGui" local settings= tImGui.SaveIniSettingsToMemory()

26.12.2 SaveIniSettingsToDisk

SaveIniSettingsToDisk(ini_filename) This is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext).

Parameters string – ini_filename

Example:

574 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local ini_filename='file_name.ini' tImGui.SaveIniSettingsToDisk(ini_filename)

26.12.3 LoadIniSettingsFromDisk

TODO: This method is available however is not implemented properly (it should be called after Create- Context() and before the first call to NewFrame()) LoadIniSettingsFromDisk(ini_filename) Call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename).

Parameters string – ini_filename

Example: tImGui= require"ImGui" local ini_filename='file_name.ini' tImGui.LoadIniSettingsFromDisk(ini_filename)

26.12.4 LoadIniSettingsFromMemory

TODO: This method is available however is not implemented properly (it should be called after Create- Context() and before the first call to NewFrame()) LoadIniSettingsFromMemory(ini_data) Call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source.

Parameters string – ini_data

Example: tImGui= require"ImGui" local ini_data='[Window][Debug##Default] \n Pos=229,80\n Size=407,363 \n

˓→Collapsed=0' tImGui.LoadIniSettingsFromMemory(ini_data)

26.13 Log methods

26.13.1 LogText

LogText(text) Pass text data straight to log (without being displayed)

Parameters string – text

26.13. Log methods 575 MBM Documentation, Release 3.1.f

Example: tImGui= require"ImGui" local text='some log ..' tImGui.LogText(text)

26.13.2 LogFinish

LogFinish Stop logging (close file, etc.) Example: tImGui= require"ImGui" tImGui.LogFinish()

26.13.3 LogButtons

LogButtons Helper to display buttons for logging to tty/file/clipboard Example: tImGui= require"ImGui" tImGui.LogButtons()

26.13.4 LogToTTY

LogToTTY(auto_open_depth) Start logging to tty (stdout)

Parameters number – auto_open_depth

Example: tImGui= require"ImGui" local auto_open_depth=-1 tImGui.LogToTTY(auto_open_depth)

26.13.5 LogToClipboard

LogToClipboard(auto_open_depth) Start logging to OS clipboard

Parameters number – auto_open_depth

Example:

576 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local auto_open_depth=-1 tImGui.LogToClipboard(auto_open_depth)

26.13.6 LogToFile

LogToFile(auto_open_depth, filename) Start logging to file

Parameters • number – auto_open_depth • string – filename

Example: tImGui= require"ImGui" local auto_open_depth=-1 local filename='file.log' tImGui.LogToFile(auto_open_depth, filename)

26.14 NewFrame / EndFrame

The engine calls NewFrame() / EndFrame() automatically. You do not to need to worry if using this module with mbm engine.

26.15 Open / Close methods

26.15.1 OpenPopupOnItemClick

OpenPopupOnItemClick(str_id, mouse_button) Helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened.

Parameters • string – str_id (might be nil) • number – mouse_button (0=left, 1=right, 2=middle) Returns boolean - result

Example: tImGui= require"ImGui" local str_id= nil local mouse_button=0 tImGui.OpenPopupOnItemClick(str_id, mouse_button)

26.14. NewFrame / EndFrame 577 MBM Documentation, Release 3.1.f

26.15.2 OpenPopup

Popups, Modals The properties of popups windows are: • They block normal mouse hovering detection outside them. (*) - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. • Their visibility state (~bool) is held internally by imgui instead of being held by the programmer as we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup(). • We default to use the right mouse (ImGuiMouseButton_Right=1) for the Popup Context functions.

Note: You can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even when normally blocked by a popup. Those three properties are connected. The library needs to hold their visibility state because it can close popups at any time.

OpenPopup(str_id) Call to mark popup as open (don’t call every frame!). popups are closed when user click out- side, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Se- lectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).

Parameters string – str_id

Example: tImGui= require"ImGui" local str_id='01' tImGui.OpenPopup(str_id)

26.15.3 CloseCurrentPopup

CloseCurrentPopup Close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. Example: tImGui= require"ImGui" tImGui.CloseCurrentPopup()

26.16 Pop methods

26.16.1 PopAllowKeyboardFocus

PopAllowKeyboardFocus Example:

578 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" tImGui.PopAllowKeyboardFocus()

26.16.2 PopItemWidth

PopItemWidth Example: tImGui= require"ImGui" tImGui.PopItemWidth()

26.16.3 PopButtonRepeat

PopButtonRepeat Example: tImGui= require"ImGui" tImGui.PopButtonRepeat()

26.16.4 PopTextWrapPos

PopTextWrapPos Example: tImGui= require"ImGui" tImGui.PopTextWrapPos()

26.16.5 PopFont

PopFont Example: tImGui= require"ImGui" tImGui.PopFont()

26.16.6 PopClipRect

PopClipRect Example: tImGui= require"ImGui" tImGui.PopClipRect()

26.16. Pop methods 579 MBM Documentation, Release 3.1.f

26.16.7 PopID

PopID Pop from the ID stack. Example:

tImGui= require"ImGui" tImGui.PopID()

26.17 Push methods

26.17.1 PushFont

TODO: implement / check PushFont(font) Use nil as a shortcut to push default font

Parameters table – font

Example:

tImGui= require"ImGui" local font={} tImGui.PushFont(font)

26.17.2 PushAllowKeyboardFocus

PushAllowKeyboardFocus(allow_keyboard_focus) Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets

Parameters boolean – allow_keyboard_focus

Example:

tImGui= require"ImGui" local allow_keyboard_focus={} tImGui.PushAllowKeyboardFocus(allow_keyboard_focus)

26.17.3 PushID

ID stack/scopes • Read the FAQ for more details about how ID are handled in dear imgui. If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them. • The resulting ID are hashes of the entire stack. • You can also use the “Label##foobar” syntax within widget label to distinguish them from each others.

580 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

• In this header file we use the “label”/”name” terminology to denote a string that will be displayed and used as an ID, whereas “str_id” denote a string that is only used as an ID and not normally displayed. PushID(str_id_begin, str_id_end) Push string into the ID stack (will hash string).

Parameters • string – str_id_begin • string – str_id_end

Example: tImGui= require"ImGui" local str_id_begin='id 0' local str_id_end='9' tImGui.PushID(str_id_begin, str_id_end)

26.17.4 PushID

PushID(str_id) Push string into the ID stack (will hash string).

Parameters string – str_id

Example: tImGui= require"ImGui" local str_id='01' tImGui.PushID(str_id)

26.17.5 PushID

PushID(value) Push number into the ID stack (will hash int).

Parameters number – value

Example: tImGui= require"ImGui" local value=1 tImGui.PushID(value)

26.17.6 PushButtonRepeat

PushButtonRepeat(repeated)

26.17. Push methods 581 MBM Documentation, Release 3.1.f

In ‘repeat’ mode, Button * () functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any But- ton() to tell if the button is held in the current frame.

Parameters boolean – repeated

Example:

tImGui= require"ImGui" local repeated= false tImGui.PushButtonRepeat(repeated)

26.17.7 PushTextWrapPos

PushTextWrapPos(wrap_local_pos_x) Word-wrapping for Text * () commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at ‘wrap_pos_x’ position in window local space

Parameters number – wrap_local_pos_x

Example:

tImGui= require"ImGui" local wrap_local_pos_x= 0.0 tImGui.PushTextWrapPos(wrap_local_pos_x)

26.17.8 PushClipRect

PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect) Parameters • table – clip_rect_min {x,y} • table – clip_rect_max {x,y} • boolean – intersect_with_current_clip_rect Example:

tImGui= require"ImGui" local clip_rect_min= {x=0,y=0} local clip_rect_max= {x=0,y=0} local intersect_with_current_clip_rect= false tImGui.PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect)

26.17.9 PushItemWidth

PushItemWidth(item_width) Set width of items for common large “item+label” widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0 always align width to the right side). 0.0f = default to ~2/3 of windows width,

582 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters number – item_width

Example: tImGui= require"ImGui" local item_width= 50 tImGui.PushItemWidth(item_width)

26.18 Render

Note: You do not need to call render for this module. It is automatically called by the engine.

26.19 Set methods

26.19.1 SetKeyboardFocusHere

SetKeyboardFocusHere(offset) Focus keyboard on the next widget. Use positive ‘offset’ to access sub components of a multiple component widget. Use -1 to access previous widget.

Parameters number – offset

Example: tImGui= require"ImGui" local offset=0 tImGui.SetKeyboardFocusHere(offset)

26.19.2 SetMouseCursor

SetMouseCursor(string cursor_type) Set desired cursor type

Parameters struing – cursor_type valids are: ImGuiMouseCursor_None, ImGuiMouseCursor_Arrow, ImGuiMouseCursor_TextInput, ImGuiMouseCursor_ResizeAll, ImGuiMouseCursor_ResizeNS, ImGuiMouseCursor_ResizeEW, ImGuiMouseCursor_ResizeNESW, ImGuiMouseCursor_ResizeNWSE, ImGuiMouseCursor_Hand, ImGuiMouseCursor_NotAllowed.

Example: tImGui= require"ImGui" local cursor_type='ImGuiMouseCursor_Hand' tImGui.SetMouseCursor(cursor_type)

26.18. Render 583 MBM Documentation, Release 3.1.f

26.19.3 SetCurrentContext

Note: You do not need to set the context for this module. It is automatically set by the engine.

26.19.4 SetClipboardText

SetClipboardText(text) Parameters string – text Example: tImGui= require"ImGui" local text='your data' tImGui.SetClipboardText(text)

Note: TODO: On Linux is used just the internal clipboard text.

26.19.5 SetNextTreeNodeOpen

SetNextTreeNodeOpen(open, cond) Parameters • boolean – open • number – condition Example: tImGui= require"ImGui" local open= true local condition=0 tImGui.SetNextTreeNodeOpen(open, condition)

26.19.6 SetItemDefaultFocus

SetItemDefaultFocus Make last item the default focused item of a window. Example: tImGui= require"ImGui" tImGui.SetItemDefaultFocus()

26.19.7 SetScrollHere

SetScrollHere(center_ratio) Parameters number – center_ratio

584 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Example:

tImGui= require"ImGui" local center_ratio= 0.5 tImGui.SetScrollHere(center_ratio)

26.19.8 SetItemAllowOverlap

SetItemAllowOverlap Allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. Example:

tImGui= require"ImGui" tImGui.SetItemAllowOverlap()

26.19.9 SetDragDropPayload

SetDragDropPayload(str_type, string_data, cond) Type is a user defined string of maximum 32 characters. Strings starting with ‘_’ are reserved for dear ImGui internal types. Data is copied and held by ImGui.

Parameters • string – str_type • string – data • number – cond Returns boolean - result

Example:

tImGui= require"ImGui" local str_type='my type 01' local data='some data' local cond=0 local ret= tImGui.SetDragDropPayload(str_type, data, cond)

26.19.10 SetWindowFocus

SetWindowFocus(name) Set named window to be focused / top-most. use nil to remove focus.

Parameters string – name

Example:

26.19. Set methods 585 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local name= nil

tImGui.SetWindowFocus(name)

26.19.11 SetTabItemClosed

SetTabItemClosed(tab_or_docked_window_label) Notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name.

Parameters string – tab_or_docked_window_label

Example:

tImGui= require"ImGui" local tab_or_docked_window_label='name' tImGui.SetTabItemClosed(tab_or_docked_window_label)

26.19.12 SetWindowFontScale

SetWindowFontScale(scale) Set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes().

Parameters number – scale

Example:

tImGui= require"ImGui" local scale= 2.0 tImGui.SetWindowFontScale(scale)

26.19.13 SetWindowCollapsed

SetWindowCollapsed(name, collapsed, cond) (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().

Parameters • string – name (might be nil for the current window) • boolean – collapsed • number – cond

Example:

586 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local name= nil local collapsed= true local cond=0

tImGui.SetWindowCollapsed(collapsed, cond)

26.19.14 SetWindowSize

SetWindowSize(name, size, cond) (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects.

Parameters • string – name (might be nil for the current window) • table – size {x,y} • number – cond

Example:

tImGui= require"ImGui" local name= nil local size= {x=200,y=200} local cond=0 tImGui.SetWindowSize(size, cond)

26.19.15 SetCursorPosY

SetCursorPosY(local_y) Parameters number – local_y Example:

tImGui= require"ImGui" local local_y= 100

tImGui.SetCursorPosY(local_y)

26.19.16 SetCursorScreenPos

SetCursorScreenPos(pos) Cursor position in absolute screen coordinates [0..io.DisplaySize]

Parameters table – pos

Example:

26.19. Set methods 587 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local pos= {x=0,y=0} tImGui.SetCursorScreenPos(pos)

26.19.17 SetCursorPosX

SetCursorPosX(local_x) GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.)

Parameters number – local_x

Example:

tImGui= require"ImGui" local local_x=0

tImGui.SetCursorPosX(local_x)

26.19.18 SetWindowPos

SetWindowPos(name, pos, cond) Set named window position.

Parameters • string – name might be nil for the current window. • table – pos {x,y} • number – cond see ImGuiCond_

Example:

tImGui= require"ImGui" local name= nil local pos= {x=0,y=0} local cond= tImGui.Flags('ImGuiCond_Always') tImGui.SetWindowPos(name, pos, cond)

26.19.19 SetColorEditOptions

SetColorEditOptions(flags) Initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls.

Parameters number – flags

Example:

588 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local flags=0 tImGui.SetColorEditOptions(flags)

26.19.20 SetNextWindowSize

SetNextWindowSize(size, cond) Set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin()

Parameters • table – size {x,y} • number – cond

Example:

tImGui= require"ImGui" local size= {x=200,y=200} local cond=0 tImGui.SetNextWindowSize(size, cond)

26.19.21 SetNextWindowPos

SetNextWindowPos(pos, cond, pivot) Set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc.

Parameters • table – pos {x,y} • number – cond • table – pivot {x,y}

Example:

tImGui= require"ImGui" local pos= {x=0,y= 100} local cond=0 local pivot= {x=0.5,y=0.5} tImGui.SetNextWindowPos(pos, cond, pivot)

26.19.22 SetNextWindowBgAlpha

SetNextWindowBgAlpha(alpha) Set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground.

Parameters number – alpha

Example:

26.19. Set methods 589 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local alpha= 0.5 tImGui.SetNextWindowBgAlpha(alpha)

26.19.23 SetNextWindowSizeConstraints

SetNextWindowSizeConstraints(size_min, size_max) Set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down.

Parameters • table – size_min {x,y} • table – size_max {x,y}

Example: tImGui= require"ImGui" local size_min= {x= 100, y= 200} local size_max= {x= 150, y= 250} tImGui.SetNextWindowSizeConstraints(size_min, size_max)

26.19.24 SetNextWindowCollapsed

SetNextWindowCollapsed(collapsed, cond) Set next window collapsed state. call before Begin()

Parameters • boolean – collapsed • number – cond

Example: tImGui= require"ImGui" local collapsed= true local cond=0 tImGui.SetNextWindowCollapsed(collapsed, cond)

26.19.25 SetNextWindowContentSize

SetNextWindowContentSize(size) Set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin()

Parameters table – size {x,y}

590 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Example: tImGui= require"ImGui" local size= {x=100,y=100} tImGui.SetNextWindowContentSize(size)

26.19.26 SetNextWindowFocus

SetNextWindowFocus Set next window to be focused / top-most. call before Begin() Example: tImGui= require"ImGui" tImGui.SetNextWindowFocus()

26.19.27 SetCursorPos

SetCursorPos(local_pos) Using the absolute coordinate system.

Parameters table – local_pos

Example: tImGui= require"ImGui" local local_pos= {x=0,y=0} tImGui.SetCursorPos(local_pos)

26.19.28 SetScrollHereX

SetScrollHereX(center_x_ratio) Adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a “default/current item” visible, consider using SetItemDefaultFo- cus() instead.

Parameters number – center_x_ratio

Example: tImGui= require"ImGui" local center_x_ratio= 0.5 tImGui.SetScrollHereX(center_x_ratio)

26.19.29 SetScrollY

SetScrollY(scroll_y) Set scrolling amount [0..GetScrollMaxY()]

26.19. Set methods 591 MBM Documentation, Release 3.1.f

Parameters number – scroll_y

Example:

tImGui= require"ImGui" local scroll_y=1 tImGui.SetScrollY(scroll_y)

26.19.30 SetColumnOffset

SetColumnOffset(column_index, offset_x) Set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column

Parameters • number – column_index • number – offset_x

Example:

tImGui= require"ImGui" local column_index=1 local offset_x=0

tImGui.SetColumnOffset(column_index, offset_x)

26.19.31 SetScrollX

SetScrollX(scroll_x) Set scrolling amount [0..GetScrollMaxX()]

Parameters number – scroll_x

Example:

tImGui= require"ImGui" local scroll_x=1 tImGui.SetScrollX(scroll_x)

26.19.32 SetColumnWidth

SetColumnWidth(column_index, width) Set column width (in pixels). pass -1 to use current column

Parameters • number – column_index • number – width

592 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Example: tImGui= require"ImGui" local column_index=0 local width= 100 tImGui.SetColumnWidth(column_index, width)

26.19.33 SetScrollHereY

SetScrollHereY(center_y_ratio) Adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a “default/current item” visible, consider using SetItemDefaultFo- cus() instead.

Parameters number – center_y_ratio

Example: tImGui= require"ImGui" local center_y_ratio= 0.5 tImGui.SetScrollHereY(center_y_ratio)

26.19.34 SetNextItemWidth

SetNextItemWidth(item_width) Set width of the _next_ common large “item+label” widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0 always align width to the right side)

Parameters number – item_width

Example: tImGui= require"ImGui" local item_width= 100 tImGui.SetNextItemWidth(item_width)

26.19.35 SetTooltip

SetTooltip(text) Set a text-only tooltip, typically use with ImGui:IsItemHovered(). override any previous call to SetTooltip().

Parameters string – text

Example: tImGui= require"ImGui" local text='tool tip' tImGui.SetTooltip(text)

26.19. Set methods 593 MBM Documentation, Release 3.1.f

26.19.36 SetScrollFromPosY

SetScrollFromPosY(local_y, center_y_ratio) Adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.

Parameters • number – local_y • number – center_y_ratio

Example: tImGui= require"ImGui" local local_y=1 local center_y_ratio= 0.5 tImGui.SetScrollFromPosY(local_y, center_y_ratio)

26.19.37 SetScrollFromPosX

SetScrollFromPosX(local_x, center_x_ratio) Adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.

Parameters • number – local_x • number – center_x_ratio

Example: tImGui= require"ImGui" local local_x=0 local center_x_ratio= 0.5 tImGui.SetScrollFromPosX(local_x, center_x_ratio)

26.20 Show methods

26.20.1 ShowUserGuide

ShowUserGuide Add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls). Example: tImGui= require"ImGui" tImGui.ShowUserGuide()

594 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.20.2 ShowFontSelector

ShowFontSelector(label) Add font selector block (not a window), essentially a combo listing the loaded fonts.

Parameters string – label

Example: tImGui= require"ImGui" function loop(delta) tImGui.ShowFontSelector('Font') end

26.20.3 ShowStyleSelector

ShowStyleSelector(label) Add style selector block (not a window), essentially a combo listing the default styles.

Parameters string – label Returns boolean - result

Example: tImGui= require"ImGui" local label='label' function loop(delta) tImGui.ShowStyleSelector('Selector') end

26.20. Show methods 595 MBM Documentation, Release 3.1.f

26.21 Style methods

26.21.1 PushStyleColor

PushStyleColor(styleColorEnum, color) Parameters • string – styleColorEnum (see GuiStyle) or number (0 to ImGuiCol_COUNT-1) • table – color rgb {r,g,b,a} or {x,y,z,w} Example:

tImGui= require"ImGui" local idx= tImGui.Flags('ImGuiCol_ButtonHovered') local color= {r=1,g=0,b=0.3,a=1} tImGui.PushStyleColor(idx, color)

PushStyleColor(styleColorEnum, color) Parameters • string – styleColorEnum (see GuiStyle) or number (0 to ImGuiCol_COUNT-1) • number – color Example:

tImGui= require"ImGui" local color= 0xff0000ff tImGui.PushStyleColor('ImGuiCol_ButtonHovered', color)

26.21.2 PopStyleColor

PopStyleColor(count) Parameters number – count Example:

tImGui= require"ImGui" local count=1 tImGui.PopStyleColor(count)

26.21.3 PushStyleVar

PushStyleVar(ImGuiStyleVar, value) Parameters • string – ImGuiStyleVar • table – value {x,y} or number Example:

596 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local ImGuiStyleVar='ImGuiStyleVar_WindowMinSize' local value= {x= 400, y= 400} tImGui.PushStyleVar(ImGuiStyleVar, value)

PushStyleVar(idx, value) Parameters • number – idx (0 to ImGuiStyleVar_COUNT) • table – value {x,y} or number Example: tImGui= require"ImGui" local idx= tImGui.Flags('ImGuiStyleVar_Alpha') local value= 0.5 tImGui.PushStyleVar(idx, value)

26.21.4 PopStyleVar

PopStyleVar(count) Parameters number – count Example: tImGui= require"ImGui" local count=1 tImGui.PopStyleVar(count)

26.21. Style methods 597 MBM Documentation, Release 3.1.f

26.21.5 ImGuiStyleVar flag table

ImGuiStyleVar_Alpha number ImGuiStyleVar_WindowPadding {x,y} ImGuiStyleVar_WindowRounding number ImGuiStyleVar_WindowBorderSize number ImGuiStyleVar_WindowMinSize {x,y} ImGuiStyleVar_WindowTitleAlign {x,y} ImGuiStyleVar_ChildRounding number ImGuiStyleVar_ChildBorderSize number ImGuiStyleVar_PopupRounding number ImGuiStyleVar_PopupBorderSize number ImGuiStyleVar_FramePadding {x,y} ImGuiStyleVar_FrameRounding number ImGuiStyleVar_FrameBorderSize number ImGuiStyleVar_ItemSpacing {x,y} ImGuiStyleVar_ItemInnerSpacing {x,y} ImGuiStyleVar_IndentSpacing number ImGuiStyleVar_ScrollbarSize number ImGuiStyleVar_ScrollbarRounding number ImGuiStyleVar_GrabMinSize number ImGuiStyleVar_GrabRounding number ImGuiStyleVar_TabRounding number ImGuiStyleVar_ButtonTextAlign {x,y} ImGuiStyleVar_SelectableTextAlign {x,y}

26.21.6 StyleColorsLight

StyleColorsLight(ImGuiStyle) Best used with borders and a custom, thicker font

Parameters table – ImGuiStyle (might be nil)

Example: tImGui= require"ImGui" local ImGuiStyle= nil tImGui.StyleColorsLight(dst)

26.21.7 StyleColorsDark

StyleColorsDark(ImGuiStyle) New, recommended style (default)

Parameters table – ImGuiStyle (might be nil)

Example:

598 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local ImGuiStyle= nil tImGui.StyleColorsDark(ImGuiStyle)

26.21.8 StyleColorsClassic

StyleColorsClassic(ImGuiStyle) Classic ImGui style

Parameters table – ImGuiStyle (might be nil)

Example:

tImGui= require"ImGui" local ImGuiStyle= nil tImGui.StyleColorsClassic(ImGuiStyle)

26.21.9 GetStyle

GetStyle(string * attribute) Access the Style structure (colors, sizes). Always use PushStyleColor(), PushStyleVar() to modify style mid-frame. If not supplied attribute then will return the whole structure. Returns table - ImGuiStyle or an attribute Example:

tImGui= require"ImGui"

local WindowPadding= tImGui.GetStyle('WindowPadding') print(WindowPadding.x,WindowPadding.y) local ImGuiCol_Button= tImGui.GetStyle('ImGuiCol_Button') print(ImGuiCol_Button.r,ImGuiCol_Button.g,ImGuiCol_Button.b,ImGuiCol_Button.a)

26.21.10 ImGuiStyle Table

Note: Use ImGuiStyleVar Flag Table + PushStyleColor(), PushStyleVar() to modify.

ImGuiStyle attribute Type Alpha number Global alpha applies to everything in
Dear ImGui. WindowPadding {x,y} Padding within a window. WindowRounding number Radius of window corners rounding. Set to 0.0f to have rectangular windows. WindowBorderSize number Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). WindowMinSize {x,y} Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints(). WindowTitleAlign {x,y} Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. Continued on next page

26.21. Style methods 599 MBM Documentation, Release 3.1.f

Table 26.2 – continued from previous page ImGuiStyle attribute Type WindowMenuButtonPosition number Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left. ChildRounding number Radius of child window corners rounding. Set to 0.0f to have rectangular windows. ChildBorderSize number Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). PopupRounding number Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) PopupBorderSize number Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). FramePadding {x,y} Padding within a framed rectan- gle (used by most widgets). FrameRounding number Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). FrameBorderSize number Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). ItemSpacing {x,y} Horizontal and vertical spacing between widgets/lines. ItemInnerSpacing {x,y} Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). TouchExtraPadding {x,y} Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don’t sort widgets so priority on overlap will always be given to the first widget. IndentSpacing number Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). ColumnsMinSpacing number Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). ScrollbarSize number Width of the vertical scrollbar, Height of the horizontal scroll- bar. ScrollbarRounding number Radius of grab corners for scrollbar. GrabMinSize number Minimum width/height of a grab box for slider/scrollbar. GrabRounding number Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. TabRounding number Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize number Thickness of border around tabs. ColorButtonPosition number Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign {x,y} Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). SelectableTextAlign {x,y} Alignment of selectable text when selectable is larger than text. Defaults to (0.0f, 0.0f) (top-left aligned). DisplayWindowPadding {x,y} Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. DisplaySafeAreaPadding {x,y} If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! MouseCursorScale number Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines boolean Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. AntiAliasedFill boolean Enable anti-aliasing on filled shapes (rounded rectangles, cir- cles, etc.) CurveTessellationTol number Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. Colors {{r,g,b,a},...} Colors [40] from ImGuiCol_Text to ImGuiCol_ModalWindowDimBg, see ImGuiCol Table.

600 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.21.11 ImGuiCol Table

ImGuiCol_XXX attributes Type ImGuiCol_Text {r,g,b,a} ImGuiCol_TextDisabled {r,g,b,a} ImGuiCol_WindowBg {r,g,b,a} ImGuiCol_ChildBg {r,g,b,a} ImGuiCol_PopupBg {r,g,b,a} ImGuiCol_Border {r,g,b,a} ImGuiCol_BorderShadow {r,g,b,a} ImGuiCol_FrameBg {r,g,b,a} ImGuiCol_FrameBgHovered {r,g,b,a} ImGuiCol_FrameBgActive {r,g,b,a} ImGuiCol_TitleBg {r,g,b,a} ImGuiCol_TitleBgActive {r,g,b,a} ImGuiCol_TitleBgCollapsed {r,g,b,a} ImGuiCol_MenuBarBg {r,g,b,a} ImGuiCol_ScrollbarBg {r,g,b,a} ImGuiCol_ScrollbarGrab {r,g,b,a} ImGuiCol_ScrollbarGrabHovered {r,g,b,a} ImGuiCol_ScrollbarGrabActive {r,g,b,a} ImGuiCol_CheckMark {r,g,b,a} ImGuiCol_SliderGrab {r,g,b,a} ImGuiCol_SliderGrabActive {r,g,b,a} ImGuiCol_Button {r,g,b,a} ImGuiCol_ButtonHovered {r,g,b,a} ImGuiCol_ButtonActive {r,g,b,a} ImGuiCol_Header {r,g,b,a} ImGuiCol_HeaderHovered {r,g,b,a} ImGuiCol_HeaderActive {r,g,b,a} ImGuiCol_Separator {r,g,b,a} ImGuiCol_SeparatorHovered {r,g,b,a} ImGuiCol_SeparatorActive {r,g,b,a} ImGuiCol_ResizeGrip {r,g,b,a} ImGuiCol_ResizeGripHovered {r,g,b,a} ImGuiCol_ResizeGripActive {r,g,b,a} ImGuiCol_Tab {r,g,b,a} ImGuiCol_TabHovered {r,g,b,a} ImGuiCol_TabActive {r,g,b,a} ImGuiCol_TabUnfocused {r,g,b,a} ImGuiCol_TabUnfocusedActive {r,g,b,a} ImGuiCol_PlotLines {r,g,b,a} ImGuiCol_PlotLinesHovered {r,g,b,a} ImGuiCol_PlotHistogram {r,g,b,a} ImGuiCol_PlotHistogramHovered {r,g,b,a} ImGuiCol_TextSelectedBg {r,g,b,a} ImGuiCol_DragDropTarget {r,g,b,a} ImGuiCol_NavHighlight {r,g,b,a} ImGuiCol_NavWindowingHighlight {r,g,b,a} ImGuiCol_NavWindowingDimBg {r,g,b,a} Continued on next page

26.21. Style methods 601 MBM Documentation, Release 3.1.f

Table 26.3 – continued from previous page ImGuiCol_XXX attributes Type ImGuiCol_ModalWindowDimBg {r,g,b,a}

Tip: Use attribute to get only what you need!

26.22 Text methods

26.22.1 AlignTextToFramePadding

AlignTextToFramePadding Vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item) Example:

tImGui= require"ImGui" tImGui.AlignTextToFramePadding()

26.22.2 TextColored

TextColored(color, text) Shortcut for PushStyleColor(ImGuiCol_Text, color); Text(text); PopStyleColor();

Parameters • table – color rgb {r,g,b,a} or {x,y,z,w} • string – text

Example:

tImGui= require"ImGui" local color= {r=1,g=0,b=0,a=1} local text='Some text' tImGui.TextColored(color, text)

26.22.3 Text

Text(text) Formatted text

Parameters string – text

Example:

602 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local text='Some text' tImGui.Text(text)

26.22.4 TextDisabled

TextDisabled(text) Shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(text); PopStyleColor();

Parameters string – text

Example:

tImGui= require"ImGui" local text='Text disabled' tImGui.TextDisabled(text)

26.22.5 TextWrapped

TextWrapped(text) Shortcut for PushTextWrapPos(0.0f); Text(fmt, . . . ); PopTextWrapPos();. Note that this won’t work on an auto-resizing window if there’s no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().

Parameters string – text

Example:

tImGui= require"ImGui" local text='Some text' tImGui.TextWrapped(text)

26.23 Widgets

Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.

26.23.1 ArrowButton

ArrowButton(str_id, dir) Square button with an arrow shape

Parameters • string – str_id • number – dir Returns boolean - result

26.23. Widgets 603 MBM Documentation, Release 3.1.f

Example: tImGui= require"ImGui" function loop(delta) local str_id='01' local dir=0 tImGui.ArrowButton(str_id, dir) end

26.23.2 BeginCombo

• The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. • The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. BeginCombo(label, preview_value, flags) Parameters • string – label • string – preview_value • number – flags Returns boolean - result EndCombo Only call EndCombo() if BeginCombo() returns true! Example: tImGui= require"ImGui" items={"AAAA","BBBB","CCCC","DDDD","EEEE","FFFF","GGGG","HHHH","IIII",

˓→"JJJJ","KKKK","LLLLLLL","MMMM","OOOOOOO"} item_current= items[1] -- global function loop(delta) local flags=0 if tImGui.BeginCombo("combo 1", item_current, flags) then -- The second parameter

˓→is the label previewed before opening the combo. for n=1,#items do local is_selected= (item_current == items[n]) if (tImGui.Selectable(items[n], is_selected)) then item_current= items[n] end if (is_selected) then tImGui.SetItemDefaultFocus() -- Set the initial focus when opening

˓→the combo (scrolling + for keyboard navigation support in the upcoming navigation

˓→branch) end end tImGui.EndCombo() (continues on next page)

604 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page) end end

26.23.3 Bullet

BulletText(str) Shortcut for Bullet()+Text()

Parameters string – text

Example: tImGui= require"ImGui" function loop(delta) local str='text' tImGui.BulletText(str) end

Bullet Draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLa- belSpacing(), same distance that TreeNode() uses Example: tImGui= require"ImGui" tImGui.Bullet()

26.23.4 Button

Button(label, size) Button

26.23. Widgets 605 MBM Documentation, Release 3.1.f

Parameters • string – label • table – size Returns boolean - result

Example:

tImGui= require"ImGui"

function loop(delta) local label='Start' local size= {x=0,y=0} if tImGui.Button(label, size) then print('Clicked') end end

26.23.5 Checkbox

Checkbox(label, value) Parameters • string – label • boolean – value Returns boolean - checked Example:

tImGui= require"ImGui" value= false

function loop(delta) local label='Check me' value= tImGui.Checkbox(label,value) end

CheckboxFlags(label, flags, flags_value) Parameters • string – label • number – flags • number – flags_value Returns boolean - result, number flags

606 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Example: tImGui= require"ImGui" value= false local flags=0 function loop(delta) local label='Check me' local flags_value=1

ret, flags= tImGui.CheckboxFlags(label, flags, flags_value) flags_value= flags end

26.23.6 Combo

Combo(label, current_item, out_text), data, items_count, popup_max_height_in_items) Parameters • string – label might be nil • number – current_item one based! • table – array of items {'option 1', 'option 2', 'option 3',... } • number – height_in_items Returns boolean - result, number - current_item, string - item Example: tImGui= require"ImGui" items={"AAAA","BBBB","CCCC","DDDD","EEEE","FFFF","GGGG","HHHH","IIII",

˓→"JJJJ","KKKK","LLLLLLL","MMMM","OOOOOOO",1,2,3, false,true,{} } current_item_selected=1 function loop(delta)

local label='Options' local current_item= current_item_selected local height_in_items=-1

local ret, current_item, item_as_string= tImGui.Combo(label, current_item, items,

˓→ height_in_items) if ret then current_item_selected= current_item --number of item selected end end

26.23.7 Color

ColorPicker

ColorPicker3(label, color, flags) Parameters

26.23. Widgets 607 MBM Documentation, Release 3.1.f

• string – label • table – color {r,g,b} • number – flags Returns boolean - result, table {r,g,b} Example:

tImGui= require"ImGui" color= {r=1,g=0,b=0}

function loop(delta) local label='Pick a color' local flags=0

local ret, tRgb= tImGui.ColorPicker3(label, color, flags) if ret then color= tRgb end end

ColorPicker4(label, color, flags, ref_col) Parameters • string – label • table – color {r,g,b,a} • number – flags • number – ref_col {r,g,b,a} Returns boolean - result, table {r,g,b,a} Example:

tImGui= require"ImGui" color= {r=1,g=0,b=0,a=1} ref_color= {r=0,g=1,b=1,a=1}

(continues on next page)

608 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page) function loop(delta) local label='Pick a color' local flags=0

local ret, tRgba= tImGui.ColorPicker4(label, color, flags, ref_color) if ret then color= tRgba end end

ColorButton

ColorButton(desc_id, color, flags, size) Display a colored square/button, hover for details, return true when pressed.

Parameters • string – desc_id • table – color {r,g,b,a} • number – flags • table – size {x,y} Returns boolean - result

Example:

26.23. Widgets 609 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" function loop(delta) local desc_id='id 01' local color= {r=1,g=0,b=1,a=1} local flags=0 local size= {x=0,y=0}

local clicked= tImGui.ColorButton(desc_id, color, flags, size) end

ColorEdit3

ColorEdit3(label, color, flags) Parameters • string – label • table – color {r,g,b} • number – flags Returns boolean - result, table - {r,g,b} Example: tImGui= require"ImGui" color= {r=1,g=0,b=0} (continues on next page)

610 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page) function loop(delta)

local label='select your color' local flags= tImGui.Flags('ImGuiColorEditFlags_HDR','ImGuiColorEditFlags_

˓→NoLabel') -- ImGuiColorEditFlags_HDR -> Currently all this does is to lift the 0..1 limits

˓→on dragging widgets

local clicked, tRgb= tImGui.ColorEdit3(label, color, flags) if clicked then color= tRgb end end

ColorEdit4

ColorEdit4(label, color, flags) Parameters • string – label • number – color {r,g,b,a}

26.23. Widgets 611 MBM Documentation, Release 3.1.f

• number – flags Returns boolean - result, table - {r,g,b,a} Example: tImGui= require"ImGui" color= {r=1,g=0,b=0,a=1} function loop(delta)

local label='select your color' local flags= tImGui.Flags('ImGuiColorEditFlags_NoLabel')

local clicked, tRgba= tImGui.ColorEdit4(label, color, flags) if clicked then color= tRgba end end

26.23.8 Drag

DragInt

DragInt(label, value, v_speed, v_min, v_max, format) If v_min >= v_max we have no bound

Parameters • string – label • number – value • number – v_speed • number – v_min • number – v_max • string – format Returns boolean - result, number value

Example: tImGui= require"ImGui" value=0 function loop(delta) local label='drag int' local v_speed= 1.0 local v_min=0 local v_max=0 local format="%d seconds"

local dragged, iValue= tImGui.DragInt(label,value, v_speed, v_min, v_max, format) if dragged then value= iValue (continues on next page)

612 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page) end end

DragInt2(label, values, v_speed, v_min, v_max, format) Parameters • string – label • table – int values {v1,v2} • number – v_speed • number – v_min • number – v_max • string – format Returns boolean - result, table - {v1,v2} Example:

tImGui= require"ImGui" local values={5,255}

function loop(delta) local label='drag int2' local v_speed= 1.0 local v_min=0 local v_max=0 local format="%d"

local dragged, tValues= tImGui.DragInt2(label,values, v_speed, v_min, v_max,

˓→format) if dragged then values= tValues end end

DragInt3(label, values, v_speed, v_min, v_max, format) Parameters • string – label • table – int values {v1,v2,v3} • number – v_speed • number – v_min • number – v_max • string – format

26.23. Widgets 613 MBM Documentation, Release 3.1.f

Returns boolean - result, table - {v1,v2,v3} Example: tImGui= require"ImGui" values={5,255,34} function loop(delta) local label='drag int3' local v_speed= 1.0 local v_min=0 local v_max=0 local format="%d"

local dragged, tValues= tImGui.DragInt3(label,values, v_speed, v_min, v_max,

˓→format) if dragged then values= tValues end end

DragInt4(label, values, v_speed, v_min, v_max, format) Parameters • string – label • table – int values {v1,v2,v3,v4} • number – v_speed • number – v_min • number – v_max • string – format Returns boolean - result, table - {v1,v2,v3,v4} Example: tImGui= require"ImGui" values={5,255,34,99} function loop(delta) local label='drag int4' local v_speed= 1.0 local v_min=0 local v_max=0 local format="%d"

local dragged, tValues= tImGui.DragInt4(label,values, v_speed, v_min, v_max,

˓→format) if dragged then values= tValues end end

DragIntRange2

DragIntRange2(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max)

614 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • string – label • number – v_current_min • number – v_current_max • number – v_speed • number – v_min • number – v_max • string – format_min • string – format_max Returns boolean - result, number - dragged_min, number - dragged_max Example: tImGui= require"ImGui" v_current_min=0 v_current_max= 255 function loop(delta) local label='Drag Int Range 2' local v_speed= 1.0 local v_min=0 local v_max= 255 local format_min="%d MIN" local format_max="%d MAX"

local dragged, dragged_min, dragged_max= tImGui.DragIntRange2(label, v_current_

˓→min, v_current_max, v_speed, v_min, v_max, format_min, format_max) if dragged then v_current_min= dragged_min v_current_max= dragged_max end end

DragFloat

DragFloat(label, value, v_speed, v_min, v_max, format, power)

26.23. Widgets 615 MBM Documentation, Release 3.1.f

If v_min >= v_max we have no bound

Parameters • string – label • number – value • number – v_speed • number – v_min • number – v_max • string – format • number – power Returns boolean - result, number value

Example: tImGui= require"ImGui" value=0 function loop(delta) local label='drag float' local v_speed= 1.0 local v_min=0 local v_max= 1000 local format="%.4f" local power=1

local dragged, fValue= tImGui.DragFloat(label,value, v_speed, v_min, v_max,

˓→format, power) if dragged then value= fValue end end

DragFloat2(label, values, v_speed, v_min, v_max, format, power) Parameters • string – label • table – values {v1,v2} • number – v_speed • number – v_min • number – v_max • string – format

616 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

• number – power Returns boolean - result, table - {v1,v2} Example: tImGui= require"ImGui" tValues={0.0, 1000.0} function loop(delta) local label='drag float 2' local v_speed= 0.5 local v_min=0 local v_max= 1000 local format="%.2f" local power=1

local dragged, fValue= tImGui.DragFloat2(label,tValues, v_speed, v_min, v_max,

˓→format, power) if dragged then tValues= fValue end end

DragFloat3(label, values, v_speed, v_min, v_max, format, power) Parameters • string – label • table – values {v1,v2,v3} • number – v_speed • number – v_min • number – v_max • string – format • number – power Returns boolean - result, table - {v1,v2,v3} Example: tImGui= require"ImGui" tValues={0.0, 1000.0, 88.8} function loop(delta) local label='drag float 3' local v_speed= 0.5 local v_min=0 local v_max= 1000 local format="%.2f" local power=1 (continues on next page)

26.23. Widgets 617 MBM Documentation, Release 3.1.f

(continued from previous page)

local dragged, fValue= tImGui.DragFloat3(label,tValues, v_speed, v_min, v_max,

˓→format, power) if dragged then tValues= fValue end end

DragFloat4(label, values, v_speed, v_min, v_max, format, power) Parameters • string – label • table – values {v1,v2,v3,v4} • number – v_speed • number – v_min • number – v_max • string – format • number – power Returns boolean - result, table - {v1,v2,v3,v4} Example: tImGui= require"ImGui" tValues={0.0, 1000.0, 88.8, 66.65} function loop(delta) local label='drag float 4' local v_speed= 0.5 local v_min=0 local v_max= 1000 local format="%.2f" local power=1

local dragged, fValue= tImGui.DragFloat3(label,tValues, v_speed, v_min, v_max,

˓→format, power) if dragged then tValues= fValue end end

DragFloatRange2

DragFloatRange2(label, v_current_min, v_current_max, v_speed, v_min, v_max, format_min, for- mat_max, power) Parameters • string – label • number – v_current_min • number – v_current_max

618 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

• number – v_speed • number – v_min • number – v_max • string – format_min • string – format_max • number – power Returns boolean - result, number - dragged_min, number - dragged_max Example: tImGui= require"ImGui" v_current_min= 0.0 v_current_max= 1000.0 function loop(delta) local label='Drag float Range 2' local v_speed= 0.5 local v_min=0 local v_max= 1000.0 local format_min="%.1f MIN" local format_max="%.1f MAX" local power= 1.0

local dragged, dragged_min, dragged_max= tImGui.DragFloatRange2(label, v_current_

˓→min, v_current_max, v_speed, v_min, v_max, format_min, format_max) if dragged then v_current_min= dragged_min v_current_max= dragged_max end end

26.23.9 HelpMarker

HelpMarker(text, string * mark) Helper to display a little (?) mark which shows a tooltip when hovered. Parameters • string – text • string – mark (default is (?)) Example:

26.23. Widgets 619 MBM Documentation, Release 3.1.f

tImGui= require"ImGui"

function loop(delta) local text='Those flags are set by the back-ends (imgui_impl_xxx files) bla bla

˓→bla...' tImGui.HelpMarker(text) end

26.23.10 Image

Image(texture_file_name, size, uv0, uv1, bg_col, line_color) Parameters • string – texture file name or number ( id of texture ) • table – size {x,y} (pass nil to get the default size) • table – uv0 {x,y} (default size is 0,0) • table – uv1 {x,y} (default size is 1,1) • table – bg_col {x,y,z,w} or {r,g,b,a} (default size is 1,1,1,1) • table – line_color {x,y,z,w} or {r,g,b,a} (default size is 0,0,0,1) Example:

tImGui= require"ImGui"

function loop(delta) local texture_name='HB_smile.png' local size= {x=50,y=50} local uv0= {x=0,y=0} local uv1= {x=1,y=1} local bg_col= {r=1,g=1,b=1,a=1} local line_color= {r=1,g=1,b=1,a=1} -- white color

tImGui.Image(texture_name, size,uv0,uv1,bg_col,line_color) end

download HB_smile.

26.23.11 ImageQuad

ImageQuad(texture_file_name, size, uv0, uv1, bg_col, line_color)

620 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • string – texture file name or number ( id of texture ) • table – size {x,y} (pass nil to get the default size) • table – uv0 {x,y} • table – uv1 {x,y} • table – uv2 {x,y} • table – uv3 {x,y} • table – bg_col {x,y,z,w} or {r,g,b,a} (default size is 1,1,1,1) • table – line_color {x,y,z,w} or {r,g,b,a} (default size is 0,0,0,1) Example:

tImGui= require"ImGui"

function loop(delta) local texture_name='HB_smile.png' local size= {x=50,y=50} local uv1= {x=0, y=0} local uv2= {x=1, y=0} local uv3= {x=1, y=1} local uv4= {x=0, y=1} local bg_col= {r=1,g=1,b=1,a=1} local line_color= {r=1,g=1,b=1,a=1} -- white color

tImGui.ImageQuad(texture_name, size,uv1, uv2, uv3, uv4, bg_col, line_color) end

download HB_smile.

26.23.12 ImageButton

ImageButton(texture_file_name, size, uv0, uv1, bg_col, line_color)

26.23. Widgets 621 MBM Documentation, Release 3.1.f

Parameters • string – texture file name or number ( id of texture ) • table – size {x,y} (pass nil to get the default size) • table – uv0 {x,y} (default size is 0,0) • table – uv1 {x,y} (default size is 1,1) • number – frame_padding <0 use default frame padding settings. 0 for no padding. • table – bg_col {x,y,z,w} or {r,g,b,a} (default size is 1,1,1,1) • table – tint_color {x,y,z,w} or {r,g,b,a} (default size is 1,1,1,1) Example:

tImGui= require"ImGui"

function loop(delta) local texture='HB_smile.png' local size= {x=100,y=100} local uv0= {x=0,y=0} local uv1= {x=1,y=1} local frame_padding=-1 local bg_col= {r=0,g=0,b=0,a=0} local tint_color= {r=1,g=1,b=1,a=1}

if tImGui.ImageButton(texture, size,uv0,uv1,frame_padding,bg_col,tint_color) then print('Button image pressed') end end

download HB_smile.

26.23.13 Input

InputInt

InputInt(label, value, step, step_fast, flags) Parameters • string – label

622 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

• number – value • number – step • number – step_fast • number – flags Returns boolean - result, number value Example: tImGui= require"ImGui" value=0 function loop(delta)

local label='input int' local step=1 local step_fast= 100 local flags=0

local result, iValue= tImGui.InputInt(label, value, step, step_fast, flags) if result then value= iValue end end

InputInt2

InputInt2(label, values, flags) Parameters • string – label • table – values {v1,v2} • number – flags Returns boolean - result, table values Example: tImGui= require"ImGui" values={10,5} function loop(delta)

local label='InputInt2' local flags=0

local result, iValues= tImGui.InputInt2(label, values, flags) if result then values= iValues end end

26.23. Widgets 623 MBM Documentation, Release 3.1.f

InputInt3

InputInt3(label, values, flags) Parameters • string – label • table – values {v1,v2,v3} • number – flags Returns boolean - result, table values Example:

tImGui= require"ImGui" values={10,5,25}

function loop(delta)

local label='InputInt3' local flags=0

local result, iValues= tImGui.InputInt3(label, values, flags) if result then values= iValues end end

InputInt4

InputInt4(label, values, flags) Parameters • string – label • table – values {v1,v2,v3,v4} • number – flags Returns boolean - result, table values Example:

tImGui= require"ImGui" values={10,-5,25,-99}

function loop(delta)

(continues on next page)

624 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page) local label='InputInt4' local flags=0

local result, iValues= tImGui.InputInt4(label, values, flags) if result then values= iValues end end

InputFloat

InputFloat(label, value, step, step_fast, format, flags) Parameters • string – label • number – value • number – step • number – step_fast • string – format • number – flags Returns boolean - result, number value Example: tImGui= require"ImGui" value= 50.0 function loop(delta)

local label='input float' local step= 1.0 local step_fast= 100.0 local format="%.2f" local flags=0

local result, fValue= tImGui.InputFloat(label, value, step, step_fast, format,

˓→flags) if result then value= fValue end end

26.23. Widgets 625 MBM Documentation, Release 3.1.f

InputFloat2

InputFloat2(label, values, format, flags) Parameters • string – label • table – values {v1,v2} • string – format • number – flags Returns boolean - result, table values Example:

tImGui= require"ImGui" values={10,5} function loop(delta)

local label='InputFloat2' local format='%.2f' local flags=0

local result, fValues= tImGui.InputFloat2(label, values, format, flags) if result then values= fValues end end

InputFloat3

InputFloat3(label, values, format, flags) Parameters • string – label • table – values {v1,v2,v3} • string – format • number – flags Returns boolean - result, table values Example:

tImGui= require"ImGui" values={10,5,88} function loop(delta)

local label='InputFloat3' local format='%.2f' local flags=0 (continues on next page)

626 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page)

local result, fValues= tImGui.InputFloat3(label, values, format, flags) if result then values= fValues end end

InputFloat4

InputFloat4(label, values, format, flags) Parameters • string – label • table – values {v1,v2,v3,v4} • string – format • number – flags Returns boolean - result, table values Example: tImGui= require"ImGui" values={10,5,-78.5,99.95} function loop(delta)

local label='InputFloat4' local format='%.2f' local flags=0

local result, fValues= tImGui.InputFloat4(label, values, format, flags) if result then values= fValues end end

InputDouble

InputDouble(label, value, step, step_fast, format, flags) Parameters • string – label • number – value • number – step

26.23. Widgets 627 MBM Documentation, Release 3.1.f

• number – step_fast • string – format • number – flags Returns boolean - result, number value Example: tImGui= require"ImGui" value= math.pi function loop(delta)

local label='input double' local step= 0.0001 local step_fast= 1.0 local format="%.9f" local flags=0

local result, fValue= tImGui.InputDouble(label, value, step, step_fast, format,

˓→flags) if result then value= fValue end end

InputText

InputText(label, text, flags) Parameters • string – label • string – text • number – flags Returns boolean - modified, string - new_text Example: tImGui= require"ImGui" text='text' function loop(delta)

local label='Label' local flags=0

local modified , sNewText= tImGui.InputText(label,text,flags) if modified then text= sNewText end (continues on next page)

628 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page) end

InputTextWithHint

InputTextWithHint(label, hint, text, flags) Parameters • string – label • string – hint • string – text • number – flags Returns boolean - modified, string - new_text Example: tImGui= require"ImGui" text='text' function loop(delta)

local label='Label' local hint='' local flags=0

local modified , sNewText= tImGui.InputTextWithHint(label,text,hint,flags) if modified then text= sNewText end end

InputTextMultiline

InputTextMultiline(label, text, size, flags) Parameters • string – label • string – text • table – size {x,y} • number – flags

26.23. Widgets 629 MBM Documentation, Release 3.1.f

Returns boolean - modified, string - new_text Example: tImGui= require"ImGui" text='line 1 \nline 2\nline 3\n...' function loop(delta)

local label='Label' local size= {x=100,y=100} local flags=0

local modified , sNewText= tImGui.InputTextMultiline(label,text,size,flags) if modified then text= sNewText end end

26.23.14 LabelText

LabelText(label, text) Display text+label aligned the same way as value+label widgets

Parameters • string – label • string – text

Example: tImGui= require"ImGui" function loop(delta) local label='Label' local text='text' tImGui.LabelText(label, text) end

26.23.15 ListBox

ListBox(label, current_item, items, height_in_items)

630 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • string – label • number – current_item • table – array of items {'item 1', 'item 2', 'item 3',... } • number – height_in_items Returns boolean - result, number - current_item, string - item Example: tImGui= require"ImGui" current_item=1 function loop(delta)

local label="listbox \n(single select)" local items={1,2,3, true,false,"Apple","Banana","Cherry","Kiwi",

˓→"Mango","Orange","Pineapple","Strawberry","Watermelon"} local height_in_items=-1 local ret, iItem, item= tImGui.ListBox(label, current_item,items, height_in_

˓→items) if ret then print(item) current_item= iItem end end

ListBoxHeader

In principle this function should be called BeginListBox().

26.23. Widgets 631 MBM Documentation, Release 3.1.f

ListBoxHeader(label, size) Use if you want to re-implement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards.

Parameters • string – label • table – size {x,y} Returns boolean - result

Example:

tImGui= require"ImGui" local label='label' local size_arg= {x=200,y=70}

local ret= tImGui.ListBoxHeader(label, size_arg)

ListBoxHeader(label, items_count, height_in_items) Use if you want to re-implement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards.

Parameters • string – label • number – items_count • number – height_in_items (default: -1) Returns boolean - result

Example:

tImGui= require"ImGui" local label='label' local items_count= 20 local height_in_items=-1

local ret= tImGui.ListBoxHeader(label, items_count,height_in_items)

ListBoxFooter

ListBoxFooter Terminate the scrolling region. only call ListBoxFooter() if ListBoxHeader() returned true! Example:

tImGui= require"ImGui"

tImGui.ListBoxFooter()

632 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

26.23.16 Menu

Menu

In the section Begin Menu.

MainMenuBar

In the section Begin Main Menu Bar

MenuItem

MenuItem(label, shortcut, selected, enabled) Return true when clicked and boolean checked. shortcuts are displayed for convenience but not processed by ImGui at the moment

Parameters • string – label • string – shortcut (Might be nil) • boolean – selected • boolean – enabled Returns boolean - clicked, boolean - checked

Example:

tImGui= require"ImGui" selected= true

(continues on next page)

26.23. Widgets 633 MBM Documentation, Release 3.1.f

(continued from previous page) function loop(delta)

local label='menu label' local shortcut='F6' local enabled= true

local clicked,checked= tImGui.MenuItem(label, shortcut, selected, enabled) if clicked then selected= checked end end

26.23.17 NewLine

NewLine Undo a SameLine() or force a new line when in an horizontal-layout context. Example: tImGui= require"ImGui" tImGui.NewLine()

26.23.18 PlotLines

PlotLines(label, values, values_offset, overlay_text, scale_min, scale_max, graph_size) Parameters • string – label • number – values {v1,v2,v3,v4,...} • number – values_offset • string – overlay_text • number – scale_min • number – scale_max • number – graph_size {x,y} Example: tImGui= require"ImGui" function loop(delta) local label="Lines" local values={ 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2} (continues on next page)

634 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

(continued from previous page) local values_offset=0 local overlay_text='Result' -- might be nil local scale_min= 0.1 local scale_max= 1.0 local graph_size= {x=200,y=70}

tImGui.PlotLines(label, values, values_offset, overlay_text, scale_min, scale_max,

˓→ graph_size) end

26.23.19 PlotHistogram

PlotHistogram(label, values, values_offset, overlay_text, scale_min, scale_max, graph_size) Parameters • string – label • number – values {v1,v2,v3,v4,...} • number – values_offset • string – overlay_text • number – scale_min • number – scale_max • number – graph_size {x,y} Example: tImGui= require"ImGui" function loop(delta) local label="" local values={ 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2} local values_offset=0 local overlay_text='Fancy Histogram' -- might be nil local scale_min= 0.1 local scale_max= 1.0 local graph_size= {x=300,y=150}

tImGui.PlotHistogram(label, values, values_offset, overlay_text, scale_min, scale_

˓→max, graph_size) end

26.23. Widgets 635 MBM Documentation, Release 3.1.f

26.23.20 ProgressBar

ProgressBar(progress, size_arg, overlay) Parameters • number – progress • table – size_arg • string – overlay Example: tImGui= require"ImGui" local estimated=2 local current=0 function loop(delta)

current= current+ delta if current >= estimated then current=0 end

local progress= current/ estimated local size_arg= {x=-1, y=0} local overlay= string.format('Loading %d',progress * 100) tImGui.ProgressBar(progress, size_arg, overlay) end

26.23.21 RadioButton

RadioButton(label, active) Parameters • string – label • number – index_activated Radio-button which is activated. • number – my_index .

636 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Returns number - index of activated radio-button Example:

tImGui= require"ImGui" index_activated=2

function loop(delta) index_activated= tImGui.RadioButton('Option 1', index_activated,1) index_activated= tImGui.RadioButton('Option 2', index_activated,2) index_activated= tImGui.RadioButton('Option 3', index_activated,3) end

26.23.22 Selectable

Selectable(label, selected, flags, size) “bool selected” carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height

Parameters • string – label • boolean – selected • number – flags • table – size Returns boolean - result, boolean selected

Example:

tImGui= require"ImGui" local label='label' local selected= false local flags=0 local size= {x=0,y=0} local result, selected= tImGui.Selectable(label, selected, flags, size)

26.23.23 SmallButton

SmallButton(label)

26.23. Widgets 637 MBM Documentation, Release 3.1.f

Button with FramePadding=(0,0) to easily embed within text

Parameters string – label Returns boolean - result

Example: tImGui= require"ImGui" function loop(delta) local label='Start' tImGui.SmallButton(label) end

26.23.24 Slider

SliderInt

SliderInt(label, value, v_min, v_max, format) Parameters • string – label • number – value • number – v_min • number – v_max • string – format Returns boolean - result, number value Example: tImGui= require"ImGui" value=0 function loop(delta) local label='SliderInt' local v_min=0 local v_max= 100 local format="%d" local result, iValue= tImGui.SliderInt(label, value, v_min, v_max, format) if result then value= iValue end end

638 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

SliderInt2

SliderInt2(label, values, v_min, v_max, format) Parameters • string – label • table – values {v1,v2} • number – v_min • number – v_max • string – format Returns boolean - result, table values Example:

tImGui= require"ImGui" tValue={0,0}

function loop(delta) local label='SliderInt2' local v_min=0 local v_max= 100 local format="%d" local result, iValues= tImGui.SliderInt2(label, tValue, v_min, v_max, format) if result then tValue= iValues end end

SliderInt3

SliderInt3(label, values, v_min, v_max, format) Parameters • string – label • table – values {v1,v2,v3} • number – v_min • number – v_max • string – format Returns boolean - result, table values Example:

tImGui= require"ImGui" tValue={0,0,0}

function loop(delta) (continues on next page)

26.23. Widgets 639 MBM Documentation, Release 3.1.f

(continued from previous page) local label='SliderInt3' local v_min=0 local v_max= 100 local format="%d" local result, iValues= tImGui.SliderInt3(label, tValue, v_min, v_max, format) if result then tValue= iValues end end

SliderInt4

SliderInt4(label, values, v_min, v_max, format) Parameters • string – label • table – values {v1,v2,v3,v4} • number – v_min • number – v_max • string – format Returns boolean - result, table values Example:

tImGui= require"ImGui" tValue={0,0,0,0}

function loop(delta) local label='SliderInt4' local v_min=0 local v_max= 100 local format="%d" local result, iValues= tImGui.SliderInt4(label, tValue, v_min, v_max, format) if result then tValue= iValues end end

SliderFloat

SliderFloat(label, value, v_min, v_max, format, power) Adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders

640 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • string – label • number – value • number – v_min • number – v_max • string – format • number – power Returns boolean - result, number value

Example:

tImGui= require"ImGui" value=0

function loop(delta) local label='SliderFloat' local v_min=0 local v_max= 100 local format="%.3f" local power= 1.0 local result, fValue= tImGui.SliderFloat(label, value, v_min, v_max, format,

˓→power) if result then value= fValue end end

SliderFloat2

SliderFloat2(label, values, v_min, v_max, format, power) Parameters • string – label • table – values {v1,v2} • number – v_min • number – v_max • string – format • number – power Returns boolean - result, table values Example:

26.23. Widgets 641 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" tValue={0.0, 0.0} function loop(delta) local label='SliderFloat2' local v_min=0 local v_max= 100 local format="%.3f" local power= 1.0 local result, fValues= tImGui.SliderFloat2(label, tValue, v_min, v_max, format,

˓→power) if result then tValue= fValues end end

SliderFloat3

SliderFloat3(label, values, v_min, v_max, format, power) Parameters • string – label • table – values {v1,v2,v3} • number – v_min • number – v_max • string – format • number – power Returns boolean - result, table values Example: tImGui= require"ImGui" tValue={0.0, 0.0, 0.0} function loop(delta) local label='SliderFloat3' local v_min=0 local v_max= 100 local format="%.3f" local power= 1.0 local result, fValues= tImGui.SliderFloat3(label, tValue, v_min, v_max, format,

˓→power) if result then tValue= fValues end end

642 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

SliderFloat4

SliderFloat4(label, values, v_min, v_max, format, power) Parameters • string – label • table – values {v1,v2,v3,v4} • number – v_min • number – v_max • string – format • number – power Returns boolean - result, table values Example:

tImGui= require"ImGui" tValue={0.0, 0.0, 0.0, 0.0}

function loop(delta) local label='SliderFloat4' local v_min=0 local v_max= 100 local format="%.1f" local power= 1.0 local result, fValues= tImGui.SliderFloat4(label, tValue, v_min, v_max, format,

˓→power) if result then tValue= fValues end end

SliderAngle

Display angle in degree from radian value. The returned value is in radian. SliderAngle(label, value_in_radian, v_degrees_min, v_degrees_max, format) Parameters • string – label • number – value_in_radian • number – v_degrees_min • number – v_degrees_max • string – format

26.23. Widgets 643 MBM Documentation, Release 3.1.f

Returns boolean - result, number radian Example: tImGui= require"ImGui" radian= math.rad(90) function loop(delta) local label='SliderAngle' local a_min=0 local a_max= 180 local format="%.1f" local result, fRadian= tImGui.SliderAngle(label, radian, a_min, a_max, format) if result then radian= fRadian end end

26.23.25 TreeNode

TreeNode

TreeNode(label) Parameters string – label Returns boolean - result Example: tImGui= require"ImGui" function loop(delta) if tImGui.TreeNode("this is a tree node") then if tImGui.TreeNode("another one of those tree node...") then tImGui.Text("Some tree contents") tImGui.TreePop() end tImGui.TreePop() end end

TreeNode

TreeNode(str_id, label)

644 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • string – str_id (might be nil) • string – label Returns boolean - result Example: tImGui= require"ImGui" function loop(delta)

if tImGui.TreeNode('id_0',"this is a tree node") then if tImGui.TreeNode('id_1',"another one of those tree node...") then tImGui.Text("Some tree contents") tImGui.TreePop() end tImGui.TreePop() end end

TreeNodeEx

TreeNodeEx(label, flags, str_id*) Parameters • string – label • number – flags • string – str_id (might be omitted) Returns boolean - result Example: tImGui= require"ImGui" function loop(delta) local flags=0 if tImGui.TreeNodeEx("this is a tree node Ex",flags) then if tImGui.TreeNodeEx("another one of those tree node Ex...",flags) then tImGui.Text("Some tree contents") tImGui.TreePop() end tImGui.TreePop() end end

26.23. Widgets 645 MBM Documentation, Release 3.1.f

TreePush

TreePush(str_id) ~Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Tree- Push/TreePop yourself if desired.

Parameters string – str_id (might be nil)

Example: tImGui= require"ImGui" local str_id='01' tImGui.TreePush(str_id)

TreePop

TreePop ~Unindent()+PopId() Example: tImGui= require"ImGui" tImGui.TreePop()

TreeAdvanceToLabelPos

TreeAdvanceToLabelPos Example: tImGui= require"ImGui" function loop(delta) tImGui.TreeAdvanceToLabelPos() if tImGui.TreeNode("this is a tree node") then if tImGui.TreeNode("another one of those tree node...") then tImGui.Text("Some tree contents") tImGui.TreePop() end tImGui.TreePop() end end

CollapsingHeader

CollapsingHeader(label, p_open, flags)

646 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

When ‘p_open’ isn’t false, display an additional small close button on upper right of the header

Parameters • string – label • boolean – p_open • number – flags Returns boolean - result, boolean - p_open

Example:

tImGui= require"ImGui" local label='my label' local p_open= true local flags=0 local ret, p_open= tImGui.CollapsingHeader(label, p_open, flags)

GetTreeNodeToLabelSpacing

GetTreeNodeToLabelSpacing Horizontal distance preceding label when using TreeNode * () or Bullet() == (g.FontSize + style.FramePadding.x * 2) for a regular unframed TreeNode

Returns number - value

Example:

tImGui= require"ImGui"

tImGui.GetTreeNodeToLabelSpacing()

SetNextItemOpen

SetNextItemOpen(is_open, cond) Set next TreeNode/CollapsingHeader open state.

Parameters • boolean – is_open • number – cond

Example:

26.23. Widgets 647 MBM Documentation, Release 3.1.f

tImGui= require"ImGui" local is_open= true local cond=0 tImGui.SetNextItemOpen(is_open, cond)

26.23.26 VSlider

VSliderInt

VSliderInt(label, size, value, v_min, v_max, format) Parameters • string – label • table – size {x,y} • number – value • number – v_min • number – v_max • string – format Returns boolean - result, number value Example: tImGui= require"ImGui" value=0 function loop(delta) local label='VSliderInt' local size= {x=20,y=100} local v_min=0 local v_max=5 local format="%d" local result, iValue= tImGui.VSliderInt(label, size, value, v_min, v_max, format) if result then value= iValue end end

VSliderFloat

VSliderFloat(label, size, value, v_min, v_max, format, power)

648 Chapter 26. Module ImGui MBM Documentation, Release 3.1.f

Parameters • string – label • table – size {x,y} • number – value • number – v_min • number – v_max • string – format • number – power Returns boolean - result, number value Example: tImGui= require"ImGui" value=0 function loop(delta) local label='VSliderFloat' local size= {x=30,y=100} local v_min=0 local v_max= 100 local format="%.1f" local power= 1.0 local result, iValue= tImGui.VSliderFloat(label, size, value, v_min, v_max,

˓→format,power) if result then value= iValue end end

Table of Contents

• Module lsqlite3 – Asset

* add_asset_folder * save_asset * delete_asset_folder * save_path_asset

26.23. Widgets 649 MBM Documentation, Release 3.1.f

– Editor – Examples

650 Chapter 26. Module ImGui CHAPTER 27

Module lsqlite3

SQLite is a C-language library that implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine. SQLite is the most used database engine in the world. SQLite is built into all mobile phones and most computers and comes bundled inside countless other applications that people use every day. lSQLite it is a binding to use Sqlite in Lua script. This version of Lua SQLite contains embedded SQL functions for creation and manipulation of assets to be used in the engine. The idea is to be able to make your assets in one unique file. Then, during runtime, it is possible to query and dump files from SQlite database to specific folder or even, anonymous folder. Some people or company want to make the assets not so easy to access for many reasons. This feature (although it is optional), could be used for that. For that, there are some builtin function in sql and also there is an editor to facilitate the construction of your asset.

27.1 Asset

Asset might have images files, scripts files, music files, etc. The idea is to be able to make your assets in one unique file as mentioned before. For this happen, there are some functions builtin available. An asset database is organized with the following tables:

TABLE dumped_folder(path TEXT);

TABLE paths(id INTEGER PRIMARY KEY, path TEXT);

TABLE assets(id INTEGER PRIMARY KEY, name TEXT, category TEXT, (continues on next page)

651 MBM Documentation, Release 3.1.f

(continued from previous page) content BLOB, id_path INTEGER REFERENCES paths(id) ON DELETE CASCADE);

Next, explanation for each function available.

27.1.1 add_asset_folder

Create a folder and register the path to the engine. This path will be used as the next folder to dump assets. add_asset_folder(TEXT * folder) Parameters string – folder (optional). Might be omitted.

Note: If the folder path is not supplied, the engine will create in the temp system folder.

Syntax SQL:

SELECT ADD_ASSET_FOLDER(); SELECT ADD_ASSET_FOLDER('path'); SELECT ADD_ASSET_FOLDER('.');

Example LUA script:

sqlite3= require"lsqlite3"

local sDataBaseFilePath='test.asset' local db= sqlite3.open(sDataBaseFilePath,sqlite3.OPEN_READWRITE) if db then local result= db:exec(" SELECT ADD_ASSET_FOLDER('my_asset_folder');") if result ~= sqlite3.OK then print('error',db:errmsg()) end db:close() else print('error','Could not open the database:',sDataBaseFilePath) end

Important: The argument '.' instruct to use the current path of the engine. It will not create any path. For Android it will use the cache folder. The argument 'path' instruct to create in the path that you passed. If not exist, the engine will try to create it.

27.1.2 save_asset

save_asset(TEXT name, BLOB content) Parameters • text – name • blob – content

652 Chapter 27. Module lsqlite3 MBM Documentation, Release 3.1.f

Note: The name and content are result of any query.

SELECT SAVE_ASSET(name,content) FROM assets; SELECT SAVE_ASSET(name,content) FROM assets where name like '%.png'; sqlite3= require"lsqlite3" local sDataBaseFilePath='my_resource.asset' local db= sqlite3.open(sDataBaseFilePath,sqlite3.OPEN_READONLY) if db then -- Dump all assets from SELECT query to a random folder. the engine will know the

˓→path. local result= db:exec([[ SELECT SAVE_ASSET(name,content) FROM assets; ]]) if result ~= sqlite3.OK then print('error',db:errmsg()) end db:close() else print('error','Could not open the database:',sDataBaseFilePath) end

Or you can specify the path before dump the assets from query: sqlite3= require"lsqlite3" local sDataBaseFilePath='my_resource.asset' local db= sqlite3.open(sDataBaseFilePath,sqlite3.OPEN_READONLY) if db then local result= db:exec(" SELECT ADD_ASSET_FOLDER('/tmp/my_folder');") if result == sqlite3.OK then -- Dump all assets from SELECT query to the last folder added. local result= db:exec([[ SELECT SAVE_ASSET(name,content) FROM assets; ]]) if result ~= sqlite3.OK then print('error',db:errmsg()) end else print('error',db:errmsg()) end db:close() else print('error','Could not open the database:',sDataBaseFilePath) end

27.1.3 delete_asset_folder

Delete a folder previously created by the engine. You might specify the number of folder created (1 to total of folder created). Negative numbers are accepted. -1 means the last folder created. delete_asset_folder(INTEGER * number_folder_created) Parameters integer – folder identify, (optional). Might be omitted.

27.1. Asset 653 MBM Documentation, Release 3.1.f

Note: If the number of folder is not supplied, the engine will delete all folders created to the current database.

Syntax SQL:

SELECT DELETE_ASSET_FOLDER(); SELECT DELETE_ASSET_FOLDER(1); SELECT DELETE_ASSET_FOLDER(-1);

Example LUA script: sqlite3= require"lsqlite3" local sDataBaseFilePath='my_game.asset' local db= sqlite3.open(sDataBaseFilePath,sqlite3.OPEN_READWRITE) if db then --create some folder local result= db:exec([[ SELECT ADD_ASSET_FOLDER(); ]]) -- anonymous folder (the

˓→engine will know) if result ~= sqlite3.OK then print(result,db:errmsg()) tUtil.showMessageWarn('Error:\n'.. msg) end

-- delete all folder created (this example one) local result= db:exec(" SELECT DELETE_ASSET_FOLDER();") if result ~= sqlite3.OK then print('error',db:errmsg()) end db:close() else print('error','Could not open the database:',sDataBaseFilePath) end

Delete specific folder: sqlite3= require"lsqlite3" local sDataBaseFilePath='my_game.asset' local db= sqlite3.open(sDataBaseFilePath,sqlite3.OPEN_READWRITE) if db then --create some folder local result= db:exec([[ SELECT ADD_ASSET_FOLDER('C:\\folder_A'); ]]) if result ~= sqlite3.OK then print(result,db:errmsg()) tUtil.showMessageWarn('Error:\n'.. msg) end

--create some folder local result= db:exec([[ SELECT ADD_ASSET_FOLDER('C:\\folder_B'); ]]) if result ~= sqlite3.OK then print(result,db:errmsg()) tUtil.showMessageWarn('Error:\n'.. msg) end

--create some folder local result= db:exec([[ SELECT ADD_ASSET_FOLDER('C:\\folder_C'); ]]) (continues on next page)

654 Chapter 27. Module lsqlite3 MBM Documentation, Release 3.1.f

(continued from previous page) if result ~= sqlite3.OK then print(result,db:errmsg()) tUtil.showMessageWarn('Error:\n'.. msg) end

-- delete all folder created (this example one) local result= db:exec(" SELECT DELETE_ASSET_FOLDER(2);") --Delete the

˓→'C:\\folder_B' folder if result ~= sqlite3.OK then print('error',db:errmsg()) end db:close() else print('error','Could not open the database:',sDataBaseFilePath) end

Note: Now the internal list will have two folders. C:\\folder_A and C:\\folder_C

Important: If you close the database without save the internal path and load the database, the list will no longer exist. The extended function does not save the internal path if not requested. The folder will be present. You might use the function save_path_assets to register the folders to the database. Then, next time you open the database, you may delete also the previously folder created.

Important: This function requires that the database be open as read/write.

27.1.4 save_path_asset

Save the internal path created by the engine (encripted). It will create a table called internal_path_asset if not exist to save the path there. save_path_asset Syntax SQL:

SELECT SAVE_PATH_ASSETS();

Example LUA script:

sqlite3= require"lsqlite3"

local sDataBaseFilePath='my_game.asset' local db= sqlite3.open(sDataBaseFilePath,sqlite3.OPEN_READWRITE) if db then --create some folder local result= db:exec([[ SELECT ADD_ASSET_FOLDER(); ]]) -- anonymous folder (the

˓→engine will know) if result ~= sqlite3.OK then print(result,db:errmsg()) tUtil.showMessageWarn('Error:\n'.. msg) (continues on next page)

27.1. Asset 655 MBM Documentation, Release 3.1.f

(continued from previous page) end

local result= db:exec(" SELECT SAVE_PATH_ASSETS();") if result ~= sqlite3.OK then print('error',db:errmsg()) end db:close() else print('error','Could not open the database:',sDataBaseFilePath) end

-- open the data base again local db= sqlite3.open(sDataBaseFilePath,sqlite3.OPEN_READWRITE) if db then -- delete all folder created (this example one) local result= db:exec(" SELECT DELETE_ASSET_FOLDER();") if result ~= sqlite3.OK then print('error',db:errmsg()) end db:close() else print('error','Could not open the database:',sDataBaseFilePath) end

Important: This function requires that the database be open as read/write.

27.2 Editor

There is an editor to create easily your asset package. This is how it looks: The editor is a lua script named asset_packager.lua and it is located at editor folder.

27.3 Examples

Here an example of how generate a random folder each time that you game runs: main.lua: sqlite3= require"lsqlite3" local sAsset= mbm.getFullPath('my_package.asset') --Important to use getFullPath local db= sqlite3.open(sAsset,sqlite3.OPEN_READWRITE) if db then -- extract all assets. You might select which one should be extracted local result= db:exec(" SELECT SAVE_ASSET(name,content) FROM assets;") if result == sqlite3.OK then --now we have the scene 'start-scene.lua' (hypothetical) which were inside

˓→the asset, load it (continues on next page)

656 Chapter 27. Module lsqlite3 MBM Documentation, Release 3.1.f

27.3. Examples 657 MBM Documentation, Release 3.1.f

(continued from previous page) mbm.loadScene('start-scene.lua') --the game continues normally else print('error',db:errmsg()) end db:close() else print('error','Could not open the database:',sAsset) end

Here an example of how extract the asset to the expected folder each time that you game runs: main.lua: sqlite3= require"lsqlite3" local sAsset= mbm.getFullPath('my_package.asset') --Important to use getFullPath local db= sqlite3.open(sAsset,sqlite3.OPEN_READWRITE) if db then local result= db:exec(" SELECT ADD_ASSET_FOLDER('my_asset_folder');") if result == sqlite3.OK then -- extract all assets. You might select which one should be extracted local result= db:exec(" SELECT SAVE_ASSET(name,content) FROM assets;") if result == sqlite3.OK then --now we have the scene 'start-scene.lua' (hypothetical) which were

˓→inside the asset, load it mbm.loadScene('start-scene.lua') --the game continues normally else print('error',db:errmsg()) end else print('error',db:errmsg()) end db:close() else print('error','Could not open the database:',sAsset) end

On Android it is possible to list the files in the cache folder through command line using adb from folder ~/Android/ Sdk/platform-tools: $ ./adb exec-out run-as com.mini.mbm.yourcompany ls -R /data/data/com.mini.mbm.yourcompany More information at https://developer.android.com/studio/command-line/adb

Warning: known issue. The current implementation does not load sound stream from cache folder in Android. This is a TODO. You can leave the sound stream in asset folder (NOT inside of your database) then it will works.

658 Chapter 27. Module lsqlite3 CHAPTER 28

Indices and tables

• genindex • modindex • search

659 MBM Documentation, Release 3.1.f

660 Chapter 28. Indices and tables Index

A applyAngularImpulse (built-in variable), 446 AcceptDragDropPayload (built-in variable), 511 applyForce (built-in variable), 442 add (built-in variable), 101, 113, 170, 198, 362, 363, applyForceToCenter (built-in variable), 443 375, 376 applyLinearImpulse (built-in variable), 444 add_asset_folder (built-in variable), 652 applyLinearImpulseToCenter (built-in vari- addAnim (built-in variable), 141, 223 able), 445 AddBezierCurve (built-in variable), 550 applyTorque (built-in variable), 452 AddCircle (built-in variable), 548 ArrowButton (built-in variable), 603 AddCircleFilled (built-in variable), 554 azimuth (built-in variable), 367 AddConvexPolyFilled (built-in variable), 549 AddDrawCmd (built-in variable), 552 B addDynamicBody (built-in variable), 439 Begin (built-in variable), 501 AddImage (built-in variable), 549 BeginChild (built-in variable), 503 AddImageQuad (built-in variable), 543 BeginChildFrame (built-in variable), 509 AddImageRounded (built-in variable), 552 BeginCombo (built-in variable), 604 addIndex (built-in variable), 156 BeginDragDropSource (built-in variable), 508 addKinematicBody (built-in variable), 447 BeginDragDropTarget (built-in variable), 510 AddLine (built-in variable), 555 BeginGroup (built-in variable), 509 AddNgon (built-in variable), 546 BeginMainMenuBar (built-in variable), 507 AddNgonFilled (built-in variable), 545 BeginMenu (built-in variable), 504 addOnTouch (built-in variable), 55 BeginMenuBar (built-in variable), 511 addPath (built-in variable), 54 BeginPopup (built-in variable), 506 AddPolyline (built-in variable), 544 BeginPopupContextItem (built-in variable), 506 AddQuad (built-in variable), 562 BeginPopupContextVoid (built-in variable), 505 AddQuadFilled (built-in variable), 560 BeginPopupContextWindow (built-in variable), AddRect (built-in variable), 557 505 AddRectFilled (built-in variable), 559 BeginPopupModal (built-in variable), 501 AddRectFilledMultiColor (built-in variable), BeginTabBar (built-in variable), 508 558 BeginTabItem (built-in variable), 510 addShader (built-in variable), 76 BeginTooltip (built-in variable), 507 addStage (built-in variable), 182 Bullet (built-in variable), 605 addStaticBody (built-in variable), 451 BulletText (built-in variable), 605 AddText (built-in variable), 544 Button (built-in variable), 605 addText (built-in variable), 101 AddTriangle (built-in variable), 556 C AddTriangleFilled (built-in variable), 554 CalcItemWidth (built-in variable), 512 addVertex (built-in variable), 147, 148 CalcListClipping (built-in variable), 513 AlignTextToFramePadding (built-in variable), CalcTextSize (built-in variable), 512 602 CaptureKeyboardFromApp (built-in variable), 513

661 MBM Documentation, Release 3.1.f

CaptureMouseFromApp (built-in variable), 514 E centralize (built-in variable), 166 elapsed (built-in variable), 355 Checkbox (built-in variable), 606 enableClearScreen (built-in variable), 66 CheckboxFlags (built-in variable), 606 enableFrame (built-in variable), 196 clear (built-in variable), 199 enableLimit (built-in variable), 485 clearGlobals (built-in variable), 60 enableMotor (built-in variable), 487 CloseCurrentPopup (built-in variable), 578 enableNormal (built-in variable), 161 CollapsingHeader (built-in variable), 646 enableTile (built-in variable), 344 collide (built-in variable), 208 enableUv (built-in variable), 162 ColorButton (built-in variable), 609 encrypt (built-in variable), 78 ColorConvertFloat4ToU32 (built-in variable), End (built-in variable), 501 514 EndChild (built-in variable), 503 ColorConvertHSVtoRGB (built-in variable), 514 EndChildFrame (built-in variable), 509 ColorConvertRGBtoHSV (built-in variable), 515 EndCombo (built-in variable), 604 ColorConvertU32ToFloat4 (built-in variable), EndDragDropSource (built-in variable), 509 515 EndDragDropTarget (built-in variable), 510 ColorEdit3 (built-in variable), 610 EndGroup (built-in variable), 509 ColorEdit4 (built-in variable), 611 EndMainMenuBar (built-in variable), 507 ColorPicker3 (built-in variable), 607 EndMenu (built-in variable), 504 ColorPicker4 (built-in variable), 608 EndMenuBar (built-in variable), 511 Columns (built-in variable), 515 EndPopup (built-in variable), 502, 506 Combo (built-in variable), 607 EndTabBar (built-in variable), 508 compress (built-in variable), 77 EndTabItem (built-in variable), 510 copyAnimationsFromMesh (built-in variable), 143 EndTooltip (built-in variable), 507 create (built-in variable), 193, 308, 309 existFile (built-in variable), 80 createDynamicIndexed (built-in variable), 313 existShader (built-in variable), 76 createIndexed (built-in variable), 311 existTexture (built-in variable), 72 createTexture (built-in variable), 69 createTileObject (built-in variable), 350 F cross (built-in variable), 382 FlagList (built-in variable), 517 D Flags (built-in variable), 516 forceEndAnimFx (built-in variable), 212 decompress (built-in variable), 78 decrypt (built-in variable), 79 G delete_asset_folder (built-in variable), 653 get (built-in variable), 61, 355, 360, 374 destroy (built-in variable), 213, 356, 388 getAABB (built-in variable), 210 destroyBody (built-in variable), 439 getAllPaths (built-in variable), 54 destroyJoint (built-in variable), 483 getAnchorA (built-in variable), 482 disableTile (built-in variable), 343 getAnchorB (built-in variable), 482 div (built-in variable), 366, 367, 378, 379 getAngle (built-in variable), 206 doCommands (built-in variable), 84 getAngularOffset (built-in variable), 482 dot (built-in variable), 368, 380, 381 getAngularVelocity (built-in variable), 457 DragFloat (built-in variable), 615 getAnim (built-in variable), 142, 219 DragFloat2 (built-in variable), 616 getAriseTime (built-in variable), 183 DragFloat3 (built-in variable), 617 getBlend (built-in variable), 216 DragFloat4 (built-in variable), 618 getBlendOp (built-in variable), 252 DragFloatRange2 (built-in variable), 618 getCamera (built-in variable), 60, 196 DragInt (built-in variable), 612 GetClipboardText (built-in variable), 527 DragInt2 (built-in variable), 613 getCode (built-in variable), 249 DragInt3 (built-in variable), 613 GetColorU32 (built-in variable), 535, 536 DragInt4 (built-in variable), 614 GetColumnIndex (built-in variable), 539 DragIntRange2 (built-in variable), 614 GetColumnOffset (built-in variable), 537 drawBounding (built-in variable), 116 GetColumnsCount (built-in variable), 538 Dummy (built-in variable), 525

662 Index MBM Documentation, Release 3.1.f

GetColumnWidth (built-in variable), 538 getLocalPoint (built-in variable), 455 GetContentRegionAvail (built-in variable), 529 GetMainMenuBarHeight (built-in variable), 528 GetContentRegionAvailWidth (built-in vari- getManifolds (built-in variable), 427 able), 541 getMapSize (built-in variable), 347 GetContentRegionMax (built-in variable), 529 getMass (built-in variable), 447 getCorrectionFactor (built-in variable), 483 getMaxColor (built-in variable), 178 GetCursorPos (built-in variable), 540 getMaxDirection (built-in variable), 174 GetCursorPosX (built-in variable), 541 getMaxForce (built-in variable), 484 GetCursorPosY (built-in variable), 541 getMaxLifeTime (built-in variable), 179 GetCursorScreenPos (built-in variable), 540 getMaxMotorTorque (built-in variable), 487 GetCursorStartPos (built-in variable), 541 getMaxOffset (built-in variable), 172 getDampingRatio (built-in variable), 483 getMaxSize (built-in variable), 180 getDisplayMetrics (built-in variable), 66 getMaxSpeed (built-in variable), 176 GetDragDropPayload (built-in variable), 537 getMinColor (built-in variable), 177 getExt (built-in variable), 139 getMinDirection (built-in variable), 173 getFocus (built-in variable), 93 getMinLifeTime (built-in variable), 178 GetFont (built-in variable), 539 getMinOffset (built-in variable), 171 GetFontSize (built-in variable), 537 getMinSize (built-in variable), 180 GetFontTexUvWhitePixel (built-in variable), 538 getMinSpeed (built-in variable), 175 getFps (built-in variable), 59 getModeCullFace (built-in variable), 145 GetFrameCount (built-in variable), 536 getModeDraw (built-in variable), 144 GetFrameHeight (built-in variable), 530 getModeFrontFace (built-in variable), 146 GetFrameHeightWithSpacing (built-in variable), getMotorSpeed (built-in variable), 486 530 GetMouseCursor (built-in variable), 528 getFrequencyHz (built-in variable), 484 GetMouseDragDelta (built-in variable), 530 getFullPath (built-in variable), 81 GetMousePos (built-in variable), 531 getGlobal (built-in variable), 60 GetMousePosOnOpeningCurrentPopup (built-in getGravity (built-in variable), 426 variable), 531 getGravityScale (built-in variable), 446 getMultiply (built-in variable), 431 getHeight (built-in variable), 100 getName (built-in variable), 387 GetID (built-in variable), 529 getNames (built-in variable), 249 getIdiom (built-in variable), 83 getNearPosition (built-in variable), 345 getIndex (built-in variable), 156 getNormal (built-in variable), 94 getIndexFrame (built-in variable), 222 getObjects (built-in variable), 348 getInertia (built-in variable), 447 getObjectsRendered (built-in variable), 68 getInfo (built-in variable), 137 getPan (built-in variable), 387 getInvertedColor (built-in variable), 184 getPathEngine (built-in variable), 80 GetItemRectMax (built-in variable), 536 getPhysics (built-in variable), 162, 224 GetItemRectMin (built-in variable), 535 getPhysicsBrick (built-in variable), 349 GetItemRectSize (built-in variable), 535 getPitch (built-in variable), 386 getJoint (built-in variable), 484 getPos (built-in variable), 93, 204 getKeyCode (built-in variable), 82 getPosition (built-in variable), 448 GetKeyIndex (built-in variable), 532 getPositionFromTileID (built-in variable), 345 getKeyName (built-in variable), 81 getPositionIterations (built-in variable), 426 GetKeyPressedAmount (built-in variable), 532 getPositionsFromBrickID (built-in variable), getLayerZ (built-in variable), 350 344 getLen (built-in variable), 387 getProperties (built-in variable), 347 getLength (built-in variable), 485 getPS (built-in variable), 241 getLetterXDiff (built-in variable), 103 getPSmax (built-in variable), 242 getLetterYDiff (built-in variable), 104 getPSmin (built-in variable), 241 getLimits (built-in variable), 485 getPStime (built-in variable), 244 getLinearOffset (built-in variable), 486 getPStype (built-in variable), 244 getLinearVelocity (built-in variable), 457 getReactionForce (built-in variable), 487 getLocalCenter (built-in variable), 456 getReactionTorque (built-in variable), 487

Index 663 MBM Documentation, Release 3.1.f getRealPos (built-in variable), 88 GetWindowContentRegionMax (built-in variable), getRealSizeScreen (built-in variable), 66 529 getScale (built-in variable), 205, 432 GetWindowContentRegionMin (built-in variable), getSceneName (built-in variable), 83 528 GetScrollMaxX (built-in variable), 533 GetWindowContentRegionWidth (built-in vari- GetScrollMaxY (built-in variable), 533 able), 534 GetScrollX (built-in variable), 533 GetWindowHeight (built-in variable), 534 GetScrollY (built-in variable), 527 GetWindowPos (built-in variable), 540 getShader (built-in variable), 224 GetWindowSize (built-in variable), 535 getShaderList (built-in variable), 73 GetWindowWidth (built-in variable), 542 getSize (built-in variable), 209, 331 getWorldCenter (built-in variable), 453 getSizeLetter (built-in variable), 102 getWorldManifold (built-in variable), 430 getSizeScreen (built-in variable), 66 getWorldPoint (built-in variable), 454 getSizeText (built-in variable), 332 getWorldVector (built-in variable), 455 getSpace (built-in variable), 100 GetZoom (built-in variable), 542 getSplash (built-in variable), 62 getStage (built-in variable), 181 H getStageTime (built-in variable), 182 HelpMarker (built-in variable), 619 GetStyle (built-in variable), 599 GetStyleColorName (built-in variable), 531 I GetStyleColorVec4 (built-in variable), 539 Image (built-in variable), 620 getTarget (built-in variable), 488 ImageButton (built-in variable), 621 GetTextLineHeight (built-in variable), 534 ImageQuad (built-in variable), 620 GetTextLineHeightWithSpacing (built-in vari- include (built-in variable), 62 able), 534 Indent (built-in variable), 525 getTexture (built-in variable), 160, 185 inputBox (built-in variable), 58 getTextureStage2 (built-in variable), 249 InputDouble (built-in variable), 627 getTileID (built-in variable), 343, 346 InputFloat (built-in variable), 625 getTileSize (built-in variable), 347 InputFloat2 (built-in variable), 626 GetTime (built-in variable), 536 InputFloat3 (built-in variable), 626 getTotalAlive (built-in variable), 184 InputFloat4 (built-in variable), 627 getTotalAnim (built-in variable), 223 InputInt (built-in variable), 622 getTotalFrame (built-in variable), 146, 213 InputInt2 (built-in variable), 623 getTotalIndex (built-in variable), 154 InputInt3 (built-in variable), 624 getTotalLayer (built-in variable), 342 InputInt4 (built-in variable), 624 getTotalParticle (built-in variable), 184, 185 inputPassword (built-in variable), 58 getTotalStage (built-in variable), 181 InputText (built-in variable), 628 getTotalSubset (built-in variable), 146 InputTextMultiline (built-in variable), 629 getTotalVertex (built-in variable), 148 InputTextWithHint (built-in variable), 629 GetTreeNodeToLabelSpacing (built-in variable), InvisibleButton (built-in variable), 525 647 isActive (built-in variable), 450, 481 getType (built-in variable), 138, 457 IsAnyItemActive (built-in variable), 565 getTypeMap (built-in variable), 343 IsAnyItemFocused (built-in variable), 564 getUserName (built-in variable), 83 IsAnyItemHovered (built-in variable), 563 getVars (built-in variable), 249 IsAnyMouseDown (built-in variable), 564 getVelocityIterations (built-in variable), 426 IsAnyWindowFocused (built-in variable), 564 GetVersion (built-in variable), 539 IsAnyWindowHovered (built-in variable), 564 getVertex (built-in variable), 148 isAwake (built-in variable), 450 getVolume (built-in variable), 386 isCapitalKeyOn (built-in variable), 82 getVS (built-in variable), 245 isEndedAnim (built-in variable), 221 getVSmax (built-in variable), 246 isIndexBuffer (built-in variable), 154 getVSmin (built-in variable), 245 IsItemActivated (built-in variable), 567 getVStime (built-in variable), 248 IsItemActive (built-in variable), 566 getVStype (built-in variable), 248 IsItemClicked (built-in variable), 568

664 Index MBM Documentation, Release 3.1.f

IsItemDeactivated (built-in variable), 566 LogButtons (built-in variable), 576 IsItemDeactivatedAfterChange (built-in vari- LogFinish (built-in variable), 576 able), 566 LogText (built-in variable), 575 IsItemDeactivatedAfterEdit (built-in vari- LogToClipboard (built-in variable), 576 able), 565 LogToFile (built-in variable), 577 IsItemEdited (built-in variable), 565 LogToTTY (built-in variable), 576 IsItemFocused (built-in variable), 567 loop (built-in variable), 35 IsItemHovered (built-in variable), 566 luaFunction (built-in variable), 85 IsItemToggledOpen (built-in variable), 565 IsItemVisible (built-in variable), 567 M IsKeyDown (built-in variable), 568 MenuItem (built-in variable), 633 IsKeyPressed (built-in variable), 569 messageBox (built-in variable), 57 IsKeyReleased (built-in variable), 568 move (built-in variable), 88, 94, 207, 368, 380 isLoaded (built-in variable), 211 mul (built-in variable), 364, 365, 377, 378 IsMouseClicked (built-in variable), 570 IsMouseDoubleClicked (built-in variable), 569 N IsMouseDown (built-in variable), 569 new (built-in variable), 99, 100, 109, 113, 123, 139, 169, IsMouseDragging (built-in variable), 571 193, 307, 317, 335, 341, 353, 354, 359, 360, IsMouseHoveringRect (built-in variable), 570 373, 374, 385, 422 IsMousePosValid (built-in variable), 571 NewLine (built-in variable), 634 IsMouseReleased (built-in variable), 571 NextColumn (built-in variable), 526 isOnScreen (built-in variable), 210 normalize (built-in variable), 369, 370, 382 isOver (built-in variable), 207 isPaused (built-in variable), 386 O isPersistent (built-in variable), 388 onEnd (built-in variable), 388 isPlaying (built-in variable), 386 onEndAnim (built-in variable), 220, 221 IsPopupOpen (built-in variable), 572 onEndFx (built-in variable), 211, 212 IsRectVisible (built-in variable), 572 onEndScene (built-in variable), 36 isRunning (built-in variable), 355 onErrorStop (built-in variable), 81 IsScrollVisible (built-in variable), 573 onInfoJoystick (built-in variable), 37 IsWindowAppearing (built-in variable), 574 onInitScene (built-in variable), 35 IsWindowCollapsed (built-in variable), 574 onKeyDown (built-in variable), 37 IsWindowFocused (built-in variable), 573 onKeyDownJoystick (built-in variable), 37 IsWindowHovered (built-in variable), 573 onKeyUp (built-in variable), 37 onKeyUpJoystick (built-in variable), 37 J onMoveJoystick (built-in variable), 38 joint (built-in variable), 466 onRender (built-in variable), 314 onRestore (built-in variable), 36 L onTouchDown (built-in variable), 36 LabelText (built-in variable), 630 onTouchMove (built-in variable), 36 length (built-in variable), 367, 380 onTouchUp (built-in variable), 36 lerp (built-in variable), 369, 381 onTouchZoom (built-in variable), 37 ListBox (built-in variable), 630 openFile (built-in variable), 56 ListBoxFooter (built-in variable), 632 openFolder (built-in variable), 57 ListBoxHeader (built-in variable), 632 openMultiFile (built-in variable), 56 listFiles (built-in variable), 84 OpenPopup (built-in variable), 578 load (built-in variable), 110, 123, 140, 170, 231, 317, OpenPopupOnItemClick (built-in variable), 577 335, 341 LoadIniSettingsFromDisk (built-in variable), P 575 pause (built-in variable), 64, 354, 386, 433 LoadIniSettingsFromMemory (built-in variable), play (built-in variable), 386 575 PlotHistogram (built-in variable), 635 loadScene (built-in variable), 63 PlotLines (built-in variable), 634 loadTexture (built-in variable), 72 PopAllowKeyboardFocus (built-in variable), 578

Index 665 MBM Documentation, Release 3.1.f

PopButtonRepeat (built-in variable), 579 setAngularDamping (built-in variable), 438 PopClipRect (built-in variable), 579 setAngularOffset (built-in variable), 482 PopFont (built-in variable), 579 setAngularVelocity (built-in variable), 457 PopID (built-in variable), 580 setAnim (built-in variable), 219 PopItemWidth (built-in variable), 579 setAriseTime (built-in variable), 183 PopStyleColor (built-in variable), 596 setAwake (built-in variable), 450 PopStyleVar (built-in variable), 597 setBlend (built-in variable), 215 PopTextureID (built-in variable), 562 setBlendOp (built-in variable), 251 PopTextWrapPos (built-in variable), 579 setBrickID (built-in variable), 351 print (built-in variable), 64 setBullet (built-in variable), 437 ProgressBar (built-in variable), 636 setCallBack (built-in variable), 356 PushAllowKeyboardFocus (built-in variable), 580 SetClipboardText (built-in variable), 584 PushButtonRepeat (built-in variable), 581 setColor (built-in variable), 67, 115, 199, 223, 313 PushClipRect (built-in variable), 582 SetColorEditOptions (built-in variable), 588 PushFont (built-in variable), 580 SetColumnOffset (built-in variable), 592 PushID (built-in variable), 581 SetColumnWidth (built-in variable), 592 PushItemWidth (built-in variable), 582 setContactListener (built-in variable), 424 PushStyleColor (built-in variable), 596 setCorrectionFactor (built-in variable), 483 PushStyleVar (built-in variable), 596, 597 SetCursorPos (built-in variable), 591 PushTextureID (built-in variable), 563 SetCursorPosX (built-in variable), 588 PushTextWrapPos (built-in variable), 582 SetCursorPosY (built-in variable), 587 SetCursorScreenPos (built-in variable), 587 Q setDampingRatio (built-in variable), 483 queryAABB (built-in variable), 435 setDensity (built-in variable), 438 quit (built-in variable), 68 SetDragDropPayload (built-in variable), 585 setEnable (built-in variable), 440 R setFakeFps (built-in variable), 59 RadioButton (built-in variable), 636 setFar (built-in variable), 95 rayCast (built-in variable), 433 setFilter (built-in variable), 441 refresh (built-in variable), 84 setFixedRotation (built-in variable), 449 release (built-in variable), 199 setFocus (built-in variable), 92 remove (built-in variable), 198 setFps (built-in variable), 59 reset (built-in variable), 387 setFrequencyHz (built-in variable), 484 ResetMouseDragDelta (built-in variable), 526 setFriction (built-in variable), 446 restart (built-in variable), 355 setGlobal (built-in variable), 60 resume (built-in variable), 64 setGravity (built-in variable), 426 rotate (built-in variable), 209 setGravityScale (built-in variable), 446 SetImDrawListToBackground (built-in variable), S 542 SetImDrawListToForeground SameLine (built-in variable), 526 (built-in variable), save (built-in variable), 140, 199 542 setInvertedColor save_asset (built-in variable), 652 (built-in variable), 183 SetItemAllowOverlap save_path_asset (built-in variable), 655 (built-in variable), 585 SetItemDefaultFocus saveFile (built-in variable), 56 (built-in variable), 584 SetKeyboardFocusHere SaveIniSettingsToDisk (built-in variable), 574 (built-in variable), 583 setLayerVisible SaveIniSettingsToMemory (built-in variable), (built-in variable), 342 setLayerZ 574 (built-in variable), 350 setLength scaleToScreen (built-in variable), 89 (built-in variable), 485 setLetterXDiff Selectable (built-in variable), 637 (built-in variable), 103 setLetterYDiff Separator (built-in variable), 526 (built-in variable), 104 setLimits set (built-in variable), 114, 355, 361, 362, 375 (built-in variable), 486 setLinearOffset setActive (built-in variable), 450, 481 (built-in variable), 486 setLinearVelocity setAngle (built-in variable), 205, 206 (built-in variable), 458 setManifolds setAngleOfView (built-in variable), 95 (built-in variable), 428

666 Index MBM Documentation, Release 3.1.f setMass (built-in variable), 447 setSize (built-in variable), 110, 336 setMaxColor (built-in variable), 177 setSizeLetter (built-in variable), 102 setMaxDirection (built-in variable), 174 setSleepingAllowed (built-in variable), 449 setMaxForce (built-in variable), 484 setSpace (built-in variable), 100 setMaxLifeTime (built-in variable), 179 setStage (built-in variable), 181 setMaxMotorTorque (built-in variable), 487 setStageTime (built-in variable), 182 setMaxOffset (built-in variable), 171, 172 setStride (built-in variable), 161 setMaxSize (built-in variable), 180 SetTabItemClosed (built-in variable), 586 setMaxSpeed (built-in variable), 175 setTarget (built-in variable), 488 setMinColor (built-in variable), 176 setTexture (built-in variable), 160, 222, 223 setMinDirection (built-in variable), 173 setTileID (built-in variable), 346 setMinLifeTime (built-in variable), 178 SetTooltip (built-in variable), 593 setMinOffset (built-in variable), 170, 171 setTotalParticle (built-in variable), 185 setMinSize (built-in variable), 179 setTransform (built-in variable), 452 setMinSpeed (built-in variable), 175 setType (built-in variable), 141, 456 setModeCullFace (built-in variable), 145 setTypeAnim (built-in variable), 220 setModeDraw (built-in variable), 144 setUp (built-in variable), 92, 93 setModeFrontFace (built-in variable), 145 setVertex (built-in variable), 150 setMotorSpeed (built-in variable), 486 setVolume (built-in variable), 386 SetMouseCursor (built-in variable), 583 setVS (built-in variable), 237 setMultiply (built-in variable), 431 setVSall (built-in variable), 239 setNear (built-in variable), 95 setVSmax (built-in variable), 238 SetNextItemOpen (built-in variable), 647 setVSmin (built-in variable), 237 SetNextItemWidth (built-in variable), 593 setVStime (built-in variable), 239 SetNextTreeNodeOpen (built-in variable), 584 setVStype (built-in variable), 240 SetNextWindowBgAlpha (built-in variable), 589 setWildCard (built-in variable), 332 SetNextWindowCollapsed (built-in variable), 590 SetWindowCollapsed (built-in variable), 586 SetNextWindowContentSize (built-in variable), SetWindowFocus (built-in variable), 585 590 SetWindowFontScale (built-in variable), 586 SetNextWindowFocus (built-in variable), 591 SetWindowPos (built-in variable), 588 SetNextWindowPos (built-in variable), 589 SetWindowSize (built-in variable), 587 SetNextWindowSize (built-in variable), 589 showConsole (built-in variable), 68 SetNextWindowSizeConstraints (built-in vari- ShowFontSelector (built-in variable), 595 able), 590 ShowStyleSelector (built-in variable), 595 setPan (built-in variable), 387 ShowUserGuide (built-in variable), 594 setPersistent (built-in variable), 388 shuffle (built-in variable), 79 setPhysics (built-in variable), 117, 118, 163 size (built-in variable), 115 setPitch (built-in variable), 386 SliderAngle (built-in variable), 643 setPos (built-in variable), 87, 88, 91, 203, 204 SliderFloat (built-in variable), 640 setPS (built-in variable), 232 SliderFloat2 (built-in variable), 641 setPSall (built-in variable), 234 SliderFloat3 (built-in variable), 642 setPSmax (built-in variable), 234 SliderFloat4 (built-in variable), 643 setPSmin (built-in variable), 233 SliderInt (built-in variable), 638 setPStime (built-in variable), 235 SliderInt2 (built-in variable), 639 setPStype (built-in variable), 236 SliderInt3 (built-in variable), 639 setRestitution (built-in variable), 449 SliderInt4 (built-in variable), 640 setScale (built-in variable), 205, 432 SmallButton (built-in variable), 637 SetScrollFromPosX (built-in variable), 594 Spacing (built-in variable), 527 SetScrollFromPosY (built-in variable), 594 start (built-in variable), 354, 435 SetScrollHere (built-in variable), 584 stop (built-in variable), 354, 386 SetScrollHereX (built-in variable), 591 StyleColorsClassic (built-in variable), 599 SetScrollHereY (built-in variable), 593 StyleColorsDark (built-in variable), 598 SetScrollX (built-in variable), 592 StyleColorsLight (built-in variable), 598 SetScrollY (built-in variable), 591 sub (built-in variable), 363, 364, 376, 377

Index 667 MBM Documentation, Release 3.1.f

T testPoint (built-in variable), 451 Text (built-in variable), 602 TextColored (built-in variable), 602 TextDisabled (built-in variable), 603 TextWrapped (built-in variable), 603 times (built-in variable), 355 to2ds (built-in variable), 67 to2dw (built-in variable), 67 to3d (built-in variable), 68 TreeAdvanceToLabelPos (built-in variable), 646 TreeNode (built-in variable), 644 TreeNodeEx (built-in variable), 645 TreePop (built-in variable), 646 TreePush (built-in variable), 646 U undoShuffle (built-in variable), 79 Unindent (built-in variable), 527 updateAnim (built-in variable), 142 V VSliderFloat (built-in variable), 648 VSliderInt (built-in variable), 648

668 Index