using System;
using System.Collections.Generic;
using System.Text;
using IrrlichtNetSwig;

namespace Meshviewer
{
    class Program
    {
        static IrrlichtDevice Device = null;
        static string StartUpModelFile = "";
        static string MessageText = "";
        static string Caption = "";
        static ISceneNode Model = null;
        static ISceneNode SkyBox = null;
        static bool Octree = false;
        static ICameraSceneNode[] Camera = new ICameraSceneNode[2];

        static void Main(string[] args)
        {
            // ask user for driver

            E_DRIVER_TYPE driverType = E_DRIVER_TYPE.EDT_DIRECT3D8;

            Console.WriteLine(
                @"Please select the driver you want for this example:
(a) Direct3D 9.0c
(b) Direct3D 8.1
(c) OpenGL 1.5
(d) Software Renderer
(e) Burning's Software Renderer
(f) NullDevice
(otherKey) exit");

            ConsoleKeyInfo keyInfo = Console.ReadKey();

            switch (keyInfo.KeyChar)
            {
                case 'a':
                    driverType = E_DRIVER_TYPE.EDT_DIRECT3D9;
                    break;
                case 'b':
                    driverType = E_DRIVER_TYPE.EDT_DIRECT3D8;
                    break;
                case 'c':
                    driverType = E_DRIVER_TYPE.EDT_OPENGL;
                    break;
                case 'd':
                    driverType = E_DRIVER_TYPE.EDT_SOFTWARE;
                    break;
                case 'e':
                    driverType = E_DRIVER_TYPE.EDT_BURNINGSVIDEO;
                    break;
                case 'f':
                    driverType = E_DRIVER_TYPE.EDT_NULL;
                    break;
                default:
                    return;
            }

            // create device and exit if creation failed

            MyEventReceiver receiver = new MyEventReceiver();
            Device = IrrlichtNet.createDevice(driverType, new dimension2di(800, 600),
                                                 16, false, false, false, receiver);

            if (Device == null)
                return; // could not create selected driver.

            Device.setResizeAble(true);

            Device.setWindowCaption("Irrlicht Engine - Loading...");

            IVideoDriver driver = Device.getVideoDriver();
            IGUIEnvironment env = Device.getGUIEnvironment();
            ISceneManager smgr = Device.getSceneManager();
            smgr.getParameters().setAttribute(IrrlichtNet.COLLADA_CREATE_SCENE_INSTANCES, true);

            driver.setTextureCreationFlag(E_TEXTURE_CREATION_FLAG.ETCF_ALWAYS_32_BIT, true);

            smgr.addLightSceneNode();
            smgr.addLightSceneNode(null, new vector3df(50, -50, 100),
                                   new SColorf(1.0f, 1.0f, 1.0f), 20000);
            // add our media directory as "search path"
            Device.getFileSystem().addFolderFileArchive("../../media/");

            /*
            The next step is to read the configuration file. It is stored in the xml
            format and looks a little bit like this:

            @verbatim
            <?xml version="1.0"?>
            <config>
                <startUpModel file="some filename" />
                <messageText caption="Irrlicht Engine Mesh Viewer">
                    Hello!
                </messageText>
            </config>
            @endverbatim

            We need the data stored in there to be written into the global variables
            StartUpModelFile, MessageText and Caption. This is now done using the
            Irrlicht Engine integrated XML parser:
            */

            // read configuration from xml file

            IIrrXMLReaderReferenceCounted xml = Device.getFileSystem().createXMLReader("config.xml");

            while (xml != null && xml.read())
            {
                switch (xml.getNodeType())
                {
                    case EXML_NODE.EXN_TEXT:
                        // in this xml file, the only text which occurs is the
                        // messageText
                        MessageText = xml.getNodeData();
                        break;
                    case EXML_NODE.EXN_ELEMENT:
                        {
                            if ("startUpModel" == xml.getNodeName())
                                StartUpModelFile = xml.getAttributeValue("file");
                            else if ("messageText" == xml.getNodeName())
                                Caption = xml.getAttributeValue("caption");
                        }
                        break;
                    default:
                        break;
                }
            }

            if (xml != null)
            {
                //xml.drop(); // don't forget to delete the xml reader
            }

            if (args.Length > 1)
                StartUpModelFile = args[1];

            /*
            That wasn't difficult. Now we'll set a nicer font and create the Menu.
            It is possible to create submenus for every menu item. The call
            menu.addItem("File", -1, true, true); for example adds a new menu
            Item with the name "File" and the id -1. The following parameter says
            that the menu item should be enabled, and the last one says, that there
            should be a submenu. The submenu can now be accessed with
            menu.getSubMenu(0), because the "File" entry is the menu item with
            index 0.
            */

            // set a nicer font

            IGUISkin skin = env.getSkin();
            IGUIFont font = env.getFont("fonthaettenschweiler.bmp");
            if (font != null)
                skin.setFont(font);

            // create menu
            IGUIContextMenu menu = env.addMenu();
            menu.addItem("File", -1, true, true);
            menu.addItem("View", -1, true, true);
            menu.addItem("Camera", -1, true, true);
            menu.addItem("Help", -1, true, true);

            IGUIContextMenu submenu;
            submenu = menu.getSubMenu(0);
            submenu.addItem("Open Model File & Texture...", 100);
            submenu.addItem("Set Model Archive...", 101);
            submenu.addItem("Load as Octree", 102);
            submenu.addSeparator();
            submenu.addItem("Quit", 200);

            submenu = menu.getSubMenu(1);
            submenu.addItem("sky box visible", 300, true, false, true);
            submenu.addItem("toggle model debug information", 400, true, true);
            submenu.addItem("model material", -1, true, true);

            submenu = submenu.getSubMenu(1);
            submenu.addItem("Off", 401);
            submenu.addItem("Bounding Box", 410);
            submenu.addItem("Normals", 420);
            submenu.addItem("Skeleton", 430);
            submenu.addItem("Wire overlay", 440);
            submenu.addItem("Half-Transparent", 450);
            submenu.addItem("Buffers bounding boxes", 460);
            submenu.addItem("All", 499);

            submenu = menu.getSubMenu(1).getSubMenu(2);
            submenu.addItem("Solid", 610);
            submenu.addItem("Transparent", 620);
            submenu.addItem("Reflection", 630);

            submenu = menu.getSubMenu(2);
            submenu.addItem("Maya Style", 1000);
            submenu.addItem("First Person", 1100);

            submenu = menu.getSubMenu(3);
            submenu.addItem("About", 500);

            /*
            Below the menu we want a toolbar, onto which we can place colored
            buttons and important looking stuff like a senseless combobox.
            */

            // create toolbar

            IGUIToolBar bar = env.addToolBar();

            ITexture image = driver.getTexture("open.png");
            bar.addButton(1102, null, "Open a model", image, null, false, true);

            image = driver.getTexture("tools.png");
            bar.addButton(1104, null, "Open Toolset", image, null, false, true);

            image = driver.getTexture("zip.png");
            bar.addButton(1105, null, "Set Model Archive", image, null, false, true);

            image = driver.getTexture("help.png");
            bar.addButton(1103, null, "Open Help", image, null, false, true);

            // create a combobox with some senseless texts

            IGUIComboBox box = env.addComboBox(new recti(250, 4, 350, 23), bar, 108);
            box.addItem("No filtering");
            box.addItem("Bilinear");
            box.addItem("Trilinear");
            box.addItem("Anisotropic");
            box.addItem("Isotropic");

            /*
            To make the editor look a little bit better, we disable transparent gui
            elements, and add an Irrlicht Engine logo. In addition, a text showing
            the current frames per second value is created and the window caption is
            changed.
            */

            // disable alpha

            for (int i = 0; i < (int) EGUI_DEFAULT_COLOR.EGDC_COUNT; ++i)
            {
                SColor col = env.getSkin().getColor((EGUI_DEFAULT_COLOR) i);
                col.setAlpha(255);
                env.getSkin().setColor((EGUI_DEFAULT_COLOR) i, col);
            }

            // add a tabcontrol

            createToolBox();

            // create fps text

            IGUIStaticText fpstext = env.addStaticText("",
                                                       new recti(400, 4, 570, 23), true, false, bar);

            IGUIStaticText postext = env.addStaticText("",
                                                       new recti(10, 50, 470, 80), false, false, null, 2001);
            postext.setVisible(false);

            // set window caption

            Caption += " - [";
            Caption += driver.getName();
            Caption += "]";
            Device.setWindowCaption(Caption);

            /*
            That's nearly the whole application. We simply show the about message
            box at start up, and load the first model. To make everything look
            better, a skybox is created and a user controled camera, to make the
            application a little bit more interactive. Finally, everything is drawn
            in a standard drawing loop.
            */

            // show about message box and load default model
            if (args.Length == 1)
                showAboutText();
            loadModel(StartUpModelFile);

            // add skybox

            SkyBox = smgr.addSkyBoxSceneNode(
                driver.getTexture("irrlicht2_up.jpg"),
                driver.getTexture("irrlicht2_dn.jpg"),
                driver.getTexture("irrlicht2_lf.jpg"),
                driver.getTexture("irrlicht2_rt.jpg"),
                driver.getTexture("irrlicht2_ft.jpg"),
                driver.getTexture("irrlicht2_bk.jpg"));

            // add a camera scene node
            Camera[0] = smgr.addCameraSceneNodeMaya();
            Camera[0].setFarValue(20000.0f);
            // Maya cameras reposition themselves relative to their target, so target the location
            // where the mesh scene node is placed.
            Camera[0].setTarget(new vector3df(0, 30, 0));

            Camera[1] = smgr.addCameraSceneNodeFPS();
            Camera[1].setFarValue(20000.0f);
            Camera[1].setPosition(new vector3df(0, 0, -70));
            Camera[1].setTarget(new vector3df(0, 30, 0));

            setActiveCamera(Camera[0]);

            // load the irrlicht engine logo
            IGUIImage img =
                env.addImage(driver.getTexture("irrlichtlogo2.png"),
                             new position2di(10, driver.getScreenSize().Height - 128));

            // lock the logo's edges to the bottom left corner of the screen
            img.setAlignment(EGUI_ALIGNMENT.EGUIA_UPPERLEFT, EGUI_ALIGNMENT.EGUIA_UPPERLEFT,
                             EGUI_ALIGNMENT.EGUIA_LOWERRIGHT, EGUI_ALIGNMENT.EGUIA_LOWERRIGHT);

            // draw everything

            while (Device.run() && driver != null)
            {
                if (Device.isWindowActive())
                {
                    driver.beginScene(true, true, new SColor(150, 50, 50, 50));

                    smgr.drawAll();
                    env.drawAll();

                    driver.endScene();

                    StringBuilder str = new StringBuilder("FPS: ");
                    str.Append(driver.getFPS());
                    str.Append(" Tris: ");
                    str.Append(driver.getPrimitiveCountDrawn());
                    fpstext.setText(str.ToString());

                    ICameraSceneNode cam = Device.getSceneManager().getActiveCamera();
                    str = new StringBuilder("Pos: ");
                    str.Append(cam.getPosition().X);
                    str.Append(" ");
                    str.Append(cam.getPosition().Y);
                    str.Append(" ");
                    str.Append(cam.getPosition().Z);
                    str.Append(" Tgt: ");
                    str.Append(cam.getTarget().X);
                    str.Append(" ");
                    str.Append(cam.getTarget().Y);
                    str.Append(" ");
                    str.Append(cam.getTarget().Z);
                    postext.setText(str.ToString());
                }
                else
                    Device.yield();
            }

            //Device.drop();
            return;
        }



        /*
        Toggle between various cameras
        */
        static void setActiveCamera(ICameraSceneNode newActive)
        {
            if (null == Device)
                return;

            Device.getSceneManager().getActiveCamera();

            newActive.setInputReceiverEnabled(true);
            Device.getSceneManager().setActiveCamera(newActive);
        }
        /*
        The three following functions do several stuff used by the mesh viewer. The
        first function showAboutText() simply displays a messagebox with a caption and
        a message text. The texts will be stored in the MessageText and Caption
        variables at startup.
        */
        static void showAboutText()
        {
            // create modal message box with the text
            // loaded from the xml file.
            Device.getGUIEnvironment().addMessageBox(
                Caption, MessageText);
        }

        /*
        The second function loadModel() loads a model and displays it using an
        addAnimatedMeshSceneNode and the scene manager. Nothing difficult. It also
        displays a short message box, if the model could not be loaded.
        */
        static void loadModel(string fn)
        {
            // modify the name if it a .pk3 file

            string filename = fn;

            string extension = System.IO.Path.GetExtension(filename);
            extension = extension.ToLower();

            // if a texture is loaded apply it to the current model..
            if (extension == ".jpg" || extension == ".pcx" ||
                extension == ".png" || extension == ".ppm" ||
                extension == ".pgm" || extension == ".pbm" ||
                extension == ".psd" || extension == ".tga" ||
                extension == ".bmp" || extension == ".wal")
            {
                ITexture texture =
                    Device.getVideoDriver().getTexture(filename);
                if (texture != null && Model != null)
                {
                    // always reload texture
                    Device.getVideoDriver().removeTexture(texture);
                    texture = Device.getVideoDriver().getTexture(filename);

                    Model.setMaterialTexture(0, texture);
                }
                return;
            }
            // if a archive is loaded add it to the FileSystems..
            else if (extension == ".pk3" || extension == ".zip")
            {
                Device.getFileSystem().addZipFileArchive(filename);
                return;
            }
            else if (extension == ".pak")
            {
                Device.getFileSystem().addPakFileArchive(filename);
                return;
            }

            // load a model into the engine

            if (Model != null)
                Model.remove();

            Model = null;

            IAnimatedMesh m = Device.getSceneManager().getMesh(filename);

            if (m == null)
            {
                // model could not be loaded

                if (StartUpModelFile != filename)
                    Device.getGUIEnvironment().addMessageBox(
                    Caption, "The model could not be loaded. Maybe it is not a supported file format.");
                return;
            }

            // set default material properties

            if (Octree)
                Model = Device.getSceneManager().addOctTreeSceneNode(m.getMesh(0));
            else
            {
                IAnimatedMeshSceneNode animModel = Device.getSceneManager().addAnimatedMeshSceneNode(m);
                animModel.setAnimationSpeed(30);
                Model = animModel;
            }
            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_LIGHTING, false);
            //	Model.setMaterialFlag(video::EMF_BACK_FACE_CULLING, false);
            Model.setDebugDataVisible((int)E_DEBUG_SCENE_TYPE.EDS_OFF);

            // we need to uncheck the menu entries. would be cool to fake a menu event, but
            // that's not so simple. so we do it brute force
            IGUIElement tmpGUI = Device.getGUIEnvironment().getRootGUIElement().getElementFromId(400, true);
            IGUIContextMenu menu = IGUIContextMenu.cast(tmpGUI);
            if (menu != null)
            {
                menu.setItemChecked(1, false);
                menu.setItemChecked(2, false);
                menu.setItemChecked(3, false);
                menu.setItemChecked(4, false);
                menu.setItemChecked(5, false);
                menu.setItemChecked(6, false);
            }
            Device.getGUIEnvironment().getRootGUIElement().getElementFromId(901, true).setText("1.0");
            Device.getGUIEnvironment().getRootGUIElement().getElementFromId(902, true).setText("1.0");
            Device.getGUIEnvironment().getRootGUIElement().getElementFromId(903, true).setText("1.0");
        }


        /*
        Finally, the third function creates a toolbox window. In this simple mesh
        viewer, this toolbox only contains a tab control with three edit boxes for
        changing the scale of the displayed model.
        */
        static void createToolBox()
        {
            // remove tool box if already there
            IGUIEnvironment env = Device.getGUIEnvironment();
            IGUIElement root = env.getRootGUIElement();
            IGUIElement e = root.getElementFromId(5000, true);
            if (e!=null)
                e.remove();

            // create the toolbox window
            IGUIWindow wnd = env.addWindow(new recti(600, 45, 800, 480),
                false, "Toolset", null, 5000);

            // create tab control and tabs
            IGUITabControl tab = env.addTabControl(
                new recti(2, 20, 800 - 602, 480 - 7), wnd, true, true);

            IGUITab t1 = tab.addTab("Config");

            // add some edit boxes and a button to tab one
            env.addStaticText("Scale:",
                    new recti(10, 20, 150, 45), false, false, t1);
            env.addStaticText("X:", new recti(22, 48, 40, 66), false, false, t1);
            env.addEditBox("1.0", new recti(40, 46, 130, 66), true, t1, 901);
            env.addStaticText("Y:", new recti(22, 82, 40, 100), false, false, t1);
            env.addEditBox("1.0", new recti(40, 76, 130, 96), true, t1, 902);
            env.addStaticText("Z:", new recti(22, 108, 40, 126), false, false, t1);
            env.addEditBox("1.0", new recti(40, 106, 130, 126), true, t1, 903);

            env.addButton(new recti(10, 134, 85, 165), t1, 1101, "Set");

            // add transparency control
            env.addStaticText("GUI Transparency Control:",
                    new recti(10, 200, 150, 225), true, false, t1);
            IGUIScrollBar scrollbar = env.addScrollBar(true,
                    new recti(10, 225, 150, 240), t1, 104);
            scrollbar.setMax(255);
            scrollbar.setPos(255);

            // add framerate control
            env.addStaticText("Framerate:",
                    new recti(10, 240, 150, 265), true, false, t1);
            scrollbar = env.addScrollBar(true,
                    new recti(10, 265, 150, 280), t1, 105);
            scrollbar.setMax(1000);
            scrollbar.setPos(30);

            // bring irrlicht engine logo to front, because it
            // now may be below the newly created toolbox
            root.bringToFront(root.getElementFromId(666, true));
        }
        
/*
To get all the events sent by the GUI Elements, we need to create an event
receiver. This one is really simple. If an event occurs, it checks the id of
the caller and the event type, and starts an action based on these values. For
example, if a menu item with id 100 was selected, if opens a file-open-dialog.
*/

        private class MyEventReceiver : IEventReceiver
        {

            public override bool OnEvent(SEvent ev)
            {
                // Escape swaps Camera Input
                if (ev.EventType == EEVENT_TYPE.EET_KEY_INPUT_EVENT &&
                    ev.getKeyInput().PressedDown == false)
                {
                    if (ev.getKeyInput().Key == EKEY_CODE.KEY_ESCAPE)
                    {
                        if (Device != null)
                        {
                            ICameraSceneNode camera =
                                Device.getSceneManager().getActiveCamera();
                            if (camera != null)
                            {
                                camera.setInputReceiverEnabled(!camera.isInputReceiverEnabled());
                            }
                            return true;
                        }
                    }
                    else if (ev.getKeyInput().Key == EKEY_CODE.KEY_F1)
                    {
                        if (Device != null)
                        {
                            IGUIElement elem = Device.getGUIEnvironment().getRootGUIElement().getElementFromId(2001);
                            if (elem != null)
                                elem.setVisible(!elem.isVisible());
                        }
                    }
                }

                if (ev.EventType == EEVENT_TYPE.EET_GUI_EVENT)
                {
                    int id = ev.getGUIEvent().Caller.getID();
                    IGUIEnvironment env = Device.getGUIEnvironment();

                    switch (ev.getGUIEvent().EventType)
                    {
                        case EGUI_EVENT_TYPE.EGET_MENU_ITEM_SELECTED:
                            {
                                // a menu item was clicked

                                IGUIContextMenu menu = IGUIContextMenu.cast( ev.getGUIEvent().Caller);
                                int id2 = menu.getItemCommandId((uint) menu.getSelectedItem());

                                switch (id2)
                                {
                                    case 100: // File . Open Model
                                        env.addFileOpenDialog("Please select a model file to open");
                                        break;
                                    case 101: // File . Set Model Archive
                                        env.addFileOpenDialog("Please select your game archive/directory");
                                        break;
                                    case 102: // File . LoadAsOctree
                                        Octree = !Octree;
                                        menu.setItemChecked((uint) menu.getSelectedItem(), Octree);
                                        break;
                                    case 200: // File . Quit
                                        Device.closeDevice();
                                        break;
                                    case 300: // View . Skybox
                                        menu.setItemChecked((uint) menu.getSelectedItem(),
                                                            !menu.isItemChecked((uint)menu.getSelectedItem()));
                                        SkyBox.setVisible(!SkyBox.isVisible());
                                        break;
                                    case 401: // View . Debug Information
                                        menu.setItemChecked((uint) menu.getSelectedItem() + 1, false);
                                        menu.setItemChecked((uint) menu.getSelectedItem() + 2, false);
                                        menu.setItemChecked((uint) menu.getSelectedItem() + 3, false);
                                        menu.setItemChecked((uint) menu.getSelectedItem() + 4, false);
                                        menu.setItemChecked((uint) menu.getSelectedItem() + 5, false);
                                        menu.setItemChecked((uint) menu.getSelectedItem() + 6, false);
                                        if (Model != null)
                                            Model.setDebugDataVisible((int) E_DEBUG_SCENE_TYPE.EDS_OFF);
                                        break;
                                    case 410: // View . Debug Information
                                        menu.setItemChecked((uint) menu.getSelectedItem(),
                                                            !menu.isItemChecked((uint) menu.getSelectedItem()));
                                        if (Model != null)
                                            Model.setDebugDataVisible(
                                                (int) (Model.isDebugDataVisible() ^ (int) E_DEBUG_SCENE_TYPE.EDS_BBOX));
                                        break;
                                    case 420: // View . Debug Information
                                        menu.setItemChecked((uint) menu.getSelectedItem(),
                                                            !menu.isItemChecked((uint) menu.getSelectedItem()));
                                        if (Model != null)
                                            Model.setDebugDataVisible(
                                                (int)
                                                (Model.isDebugDataVisible() ^ (int) E_DEBUG_SCENE_TYPE.EDS_NORMALS));
                                        break;
                                    case 430: // View . Debug Information
                                        menu.setItemChecked((uint) menu.getSelectedItem(),
                                                            !menu.isItemChecked((uint) menu.getSelectedItem()));
                                        if (Model != null)
                                            Model.setDebugDataVisible(
                                                (int)
                                                (Model.isDebugDataVisible() ^ (int) E_DEBUG_SCENE_TYPE.EDS_SKELETON));
                                        break;
                                    case 440: // View . Debug Information
                                        menu.setItemChecked((uint) menu.getSelectedItem(),
                                                            !menu.isItemChecked((uint) menu.getSelectedItem()));
                                        if (Model != null)
                                            Model.setDebugDataVisible(
                                                (int)
                                                (Model.isDebugDataVisible() ^
                                                 (int) E_DEBUG_SCENE_TYPE.EDS_MESH_WIRE_OVERLAY));
                                        break;
                                    case 450: // View . Debug Information
                                        menu.setItemChecked((uint) menu.getSelectedItem(),
                                                            !menu.isItemChecked((uint) menu.getSelectedItem()));
                                        if (Model != null)
                                            Model.setDebugDataVisible(
                                                (int)
                                                (Model.isDebugDataVisible() ^
                                                 (int) E_DEBUG_SCENE_TYPE.EDS_HALF_TRANSPARENCY));
                                        break;
                                    case 460: // View . Debug Information
                                        menu.setItemChecked((uint) menu.getSelectedItem(),
                                                            !menu.isItemChecked((uint) menu.getSelectedItem()));
                                        if (Model != null)
                                            Model.setDebugDataVisible(
                                                (int)
                                                (Model.isDebugDataVisible() ^ (int) E_DEBUG_SCENE_TYPE.EDS_BBOX_BUFFERS));
                                        break;
                                    case 499: // View . Debug Information
                                        menu.setItemChecked((uint) menu.getSelectedItem() - 1, true);
                                        menu.setItemChecked((uint) menu.getSelectedItem() - 2, true);
                                        menu.setItemChecked((uint) menu.getSelectedItem() - 3, true);
                                        menu.setItemChecked((uint) menu.getSelectedItem() - 4, true);
                                        menu.setItemChecked((uint) menu.getSelectedItem() - 5, true);
                                        menu.setItemChecked((uint) menu.getSelectedItem() - 6, true);
                                        if (Model != null)
                                            Model.setDebugDataVisible((int) E_DEBUG_SCENE_TYPE.EDS_FULL);
                                        break;
                                    case 500: // Help.About
                                        showAboutText();
                                        break;
                                    case 610: // View . Material . Solid
                                        if (Model != null)
                                            Model.setMaterialType(E_MATERIAL_TYPE.EMT_SOLID);
                                        break;
                                    case 620: // View . Material . Transparent
                                        if (Model != null)
                                            Model.setMaterialType(E_MATERIAL_TYPE.EMT_TRANSPARENT_ADD_COLOR);
                                        break;
                                    case 630: // View . Material . Reflection
                                        if (Model != null)
                                            Model.setMaterialType(E_MATERIAL_TYPE.EMT_SPHERE_MAP);
                                        break;

                                    case 1000:
                                        setActiveCamera(Camera[0]);
                                        break;
                                    case 1100:
                                        setActiveCamera(Camera[1]);
                                        break;

                                }
                                break;
                            }

                        case EGUI_EVENT_TYPE.EGET_FILE_SELECTED:
                            {
                                // load the model file, selected in the file open dialog
                                IGUIFileOpenDialog dialog =
                                    IGUIFileOpenDialog.cast( ev.getGUIEvent().Caller);
                                loadModel(dialog.getFileName());
                            }
                            break;

                        case EGUI_EVENT_TYPE.EGET_SCROLL_BAR_CHANGED:

                            // control skin transparency
                            if (id == 104)
                            {
                                int pos = IGUIScrollBar.cast( ev.getGUIEvent().Caller).getPos();
                                for (int i = 0; i < (int) EGUI_DEFAULT_COLOR.EGDC_COUNT; ++i)
                                {
                                    SColor col = env.getSkin().getColor((EGUI_DEFAULT_COLOR) i);
                                    col.setAlpha((uint) pos);
                                    env.getSkin().setColor((EGUI_DEFAULT_COLOR) i, col);
                                }
                            }
                            else if (id == 105)
                            {
                                int pos = IGUIScrollBar.cast( ev.getGUIEvent().Caller).getPos();
                                if ((int) ESCENE_NODE_TYPE.ESNT_ANIMATED_MESH == Model.getType())
                                    ((IAnimatedMeshSceneNode) Model).setAnimationSpeed((float) pos);
                            }
                            break;

                        case EGUI_EVENT_TYPE.EGET_COMBO_BOX_CHANGED:

                            // control anti-aliasing/filtering
                            if (id == 108)
                            {
                                int pos = IGUIComboBox.cast( ev.getGUIEvent().Caller).getSelected();
                                switch (pos)
                                {
                                    case 0:
                                        if (Model != null)
                                        {
                                            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_BILINEAR_FILTER, false);
                                            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_TRILINEAR_FILTER, false);
                                            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_ANISOTROPIC_FILTER, false);
                                        }
                                        break;
                                    case 1:
                                        if (Model != null)
                                        {
                                            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_BILINEAR_FILTER, true);
                                            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_TRILINEAR_FILTER, false);
                                        }
                                        break;
                                    case 2:
                                        if (Model != null)
                                        {
                                            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_BILINEAR_FILTER, false);
                                            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_TRILINEAR_FILTER, true);
                                        }
                                        break;
                                    case 3:
                                        if (Model != null)
                                        {
                                            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_ANISOTROPIC_FILTER, true);
                                        }
                                        break;
                                    case 4:
                                        if (Model != null)
                                        {
                                            Model.setMaterialFlag(E_MATERIAL_FLAG.EMF_ANISOTROPIC_FILTER, false);
                                        }
                                        break;
                                }
                            }
                            break;

                        case EGUI_EVENT_TYPE.EGET_BUTTON_CLICKED:

                            switch (id)
                            {
                                case 1101:
                                    {
                                        // set scale
                                        IGUIElement root = env.getRootGUIElement();
                                        vector3df scale = new vector3df();
                                        string s;

                                        s = root.getElementFromId(901, true).getText();
                                        scale.X = float.Parse(s);
                                        s = root.getElementFromId(902, true).getText();
                                        scale.Y = float.Parse(s);
                                        s = root.getElementFromId(903, true).getText();
                                        scale.Z = float.Parse(s);

                                        if (Model != null)
                                            Model.setScale(scale);
                                    }
                                    break;
                                case 1102:
                                    env.addFileOpenDialog("Please select a model file to open");
                                    break;
                                case 1103:
                                    showAboutText();
                                    break;
                                case 1104:
                                    createToolBox();
                                    break;
                                case 1105:
                                    env.addFileOpenDialog("Please select your game archive/directory");
                                    break;
                            }

                            break;
                        default:
                            break;
                    }
                }

                return false;
            }
        }
    }
}
