Example #1
0
        static void Main(string[] args)
        {
            // Initialize device.

            DriverType driverType;

            if (!AskUserForDriver(out driverType))
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            // Add event handling.

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

            // Save important pointers.

            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;
            Logger       logger = device.Logger;

            // Initialize joysticks and print info about them.

            List <JoystickInfo> joystickList = device.ActivateJoysticks();

            if (joystickList != null)
            {
                logger.Log("Joystick support is enabled and " + joystickList.Count.ToString() + " joystick(s) are present.");

                foreach (JoystickInfo j in joystickList)
                {
                    logger.Log("Joystick " + j.Joystick.ToString() + ":");
                    logger.Log("\tName: \"" + j.Name + "\"");
                    logger.Log("\tAxisCount: " + j.AxisCount.ToString());
                    logger.Log("\tButtonCount: " + j.ButtonCount.ToString());
                    logger.Log("\tPovHat: " + j.PovHat.ToString());
                }
            }
            else
            {
                logger.Log("Joystick support is not enabled.");
            }

            device.SetWindowCaption("Mouse and joystick - Irrlicht Lime - " + joystickList.Count.ToString() + " joystick(s)");

            // Create an arrow mesh and move it around either with the joystick axis/hat,
            // or make it follow the mouse pointer (when no joystick movement).

            SceneNode node = smgr.AddMeshSceneNode(
                smgr.AddArrowMesh(
                    "Arrow",
                    new Color(255, 0, 0),
                    new Color(0, 255, 0),
                    16, 16,
                    2.0f, 1.3f,
                    0.1f, 0.6f
                    )
                );

            node.SetMaterialFlag(MaterialFlag.Lighting, false);

            CameraSceneNode camera = smgr.AddCameraSceneNode();

            camera.Position = new Vector3Df(0, 0, -10);

            // As in example #4, we'll use framerate independent movement.
            uint        then          = device.Timer.Time;
            const float MovementSpeed = 5.0f;

            // Run main cycle.

            while (device.Run())
            {
                // Work out a frame delta time.
                uint  now            = device.Timer.Time;
                float frameDeltaTime = (float)(now - then) / 1000.0f;                 // in seconds
                then = now;

                bool      movedWithJoystick = false;
                Vector3Df nodePosition      = node.Position;

                if (joystickList.Count > 0)
                {
                    float moveHorizontal = 0.0f;                   // range is -1.0 for full left to +1.0 for full right
                    float moveVertical   = 0.0f;                   // range is -1.0 for full down to +1.0 for full up

                    // We receive the full analog range of the axes, and so have to implement our own dead zone.
                    // This is an empirical value, since some joysticks have more jitter or creep around the center
                    // point than others. We'll use 5% of the range as the dead zone, but generally you would want
                    // to give the user the option to change this.
                    float DeadZone = 0.05f;

                    moveHorizontal = joystickState.Axis[0] / 32767.0f;                     // "0" for X axis
                    if (Math.Abs(moveHorizontal) < DeadZone)
                    {
                        moveHorizontal = 0.0f;
                    }

                    moveVertical = joystickState.Axis[1] / -32767.0f;                     // "1" for Y axis
                    if (Math.Abs(moveVertical) < DeadZone)
                    {
                        moveVertical = 0.0f;
                    }

                    // POV will contain 65535 if POV hat info no0t supported, so we can check its range.
                    ushort povDegrees = (ushort)(joystickState.POV / 100);
                    if (povDegrees < 360)
                    {
                        if (povDegrees > 0 && povDegrees < 180)
                        {
                            moveHorizontal = +1.0f;
                        }
                        else if (povDegrees > 180)
                        {
                            moveHorizontal = -1.0f;
                        }

                        if (povDegrees > 90 && povDegrees < 270)
                        {
                            moveVertical = -1.0f;
                        }
                        else if (povDegrees > 270 || povDegrees < 90)
                        {
                            moveVertical = +1.0f;
                        }
                    }

                    // If we have any movement, apply it.
                    if (Math.Abs(moveHorizontal) > 0.0001f || Math.Abs(moveVertical) > 0.0001f)
                    {
                        float m = frameDeltaTime * MovementSpeed;
                        nodePosition      = new Vector3Df(moveHorizontal * m, moveVertical * m, nodePosition.Z);
                        movedWithJoystick = true;
                    }
                }

                // If the arrow node isn't being moved with the joystick, then have it follow the mouse cursor.
                if (!movedWithJoystick)
                {
                    // Create a ray through the mouse cursor.
                    Line3Df ray = smgr.SceneCollisionManager.GetRayFromScreenCoordinates(mouseState.Position, camera);

                    // And intersect the ray with a plane around the node facing towards the camera.
                    Plane3Df  plane = new Plane3Df(nodePosition, new Vector3Df(0, 0, -1));
                    Vector3Df mousePosition;
                    if (plane.GetIntersectionWithLine(ray.Start, ray.Vector, out mousePosition))
                    {
                        // We now have a mouse position in 3d space; move towards it.
                        Vector3Df toMousePosition   = mousePosition - nodePosition;
                        float     availableMovement = frameDeltaTime * MovementSpeed;

                        if (toMousePosition.Length <= availableMovement)
                        {
                            nodePosition = mousePosition;                             // jump to the final position
                        }
                        else
                        {
                            nodePosition += toMousePosition.Normalize() * availableMovement;                             // move towards it
                        }
                    }
                }

                node.Position = nodePosition;

                // Turn lighting on and off depending on whether the left mouse button is down.
                node.SetMaterialFlag(MaterialFlag.Lighting, mouseState.IsLeftButtonDown);

                // Draw all.
                driver.BeginScene(true, true, new Color(113, 113, 133));
                smgr.DrawAll();
                driver.EndScene();
            }

            // Drop the device.

            device.Drop();
        }
Example #2
0
        /// <summary>
        /// The irrlicht thread for rendering.
        /// </summary>
        private void StartIrr()
        {
            try
            {
                //Setup
                IrrlichtCreationParameters irrparam = new IrrlichtCreationParameters();
                if (irrlichtPanel.IsDisposed)
                {
                    throw new Exception("Form closed!");
                }
                if (irrlichtPanel.InvokeRequired)
                {
                    irrlichtPanel.Invoke(new MethodInvoker(delegate { irrparam.WindowID = irrlichtPanel.Handle; }));
                }
                irrparam.DriverType   = DriverType.Direct3D9;
                irrparam.DriverType   = DriverType.OpenGL;
                irrparam.BitsPerPixel = 16;

                device = IrrlichtDevice.CreateDevice(irrparam);

                if (device == null)
                {
                    throw new NullReferenceException("Could not create device for engine!");
                }

                driver = device.VideoDriver;
                smgr   = device.SceneManager;
                gui    = device.GUIEnvironment;

                var cam = smgr.AddCameraSceneNode(null);
                cam.TargetAndRotationBinding = true;
                cam.Position = new Vector3Df(-100.0f, 500.0f, 100.0f);
                cam.Target   = new Vector3Df(0.0f);
                cam.FarValue = 42000.0f;

                device.CursorControl.Visible = false;

                //Terrain
                heightmap = driver.CreateImage("Terrain\\basemap.bmp");

                terrain = smgr.AddTerrainSceneNode(
                    "Terrain\\basemap.bmp",
                    null,
                    -1,
                    new Vector3Df(0.0f)
                    );
                terrain.Scale = new Vector3Df(32, 5, 32);
                terrain.SetMaterialFlag(MaterialFlag.Lighting, false);

                terrain.SetMaterialTexture(0, driver.GetTexture("Terrain\\rockwall.jpg"));
                selector = smgr.CreateTerrainTriangleSelector(terrain, 0);

                var arrow = smgr.AddAnimatedMeshSceneNode(smgr.AddArrowMesh("arrow", new IrrlichtLime.Video.Color(255, 255, 0, 0), new IrrlichtLime.Video.Color(255, 0, 255, 0)), null);
                arrow.SetMaterialFlag(MaterialFlag.Lighting, false);
                arrow.Scale    = new Vector3Df(100.0f);
                arrow.Rotation = new Vector3Df(0.0f, 0.0f, 180.0f);

                //Skybox and skydome
                driver.SetTextureCreationFlag(TextureCreationFlag.CreateMipMaps, false);

                /*var box = smgr.AddSkyBoxSceneNode(
                 *  ("Terrain\\irrlicht2_up.jpg"),
                 *  ("Terrain\\irrlicht2_dn.jpg"),
                 *  ("Terrain\\irrlicht2_lf.jpg"),
                 *  ("Terrain\\irrlicht2_rt.jpg"),
                 *  ("Terrain\\irrlicht2_ft.jpg"),
                 *  ("Terrain\\irrlicht2_bk.jpg"));
                 * box.Visible = true;*/

                var dome = smgr.AddSkyDomeSceneNode(driver.GetTexture("Terrain\\skydome.jpg"), 16, 8, 0.95f, 2.0f);
                dome.Visible = true;
                driver.SetTextureCreationFlag(TextureCreationFlag.CreateMipMaps, true);

                var helpq = gui.AddStaticText("Press Q to disable focus!",
                                              new Recti(0, this.ClientSize.Height - 40, 100, this.ClientSize.Height), true, true, null, 1, true);
                var helpesc = gui.AddStaticText("Press ESC to quit",
                                                new Recti(0, this.ClientSize.Height - 20, 100, this.ClientSize.Height), true, true, null, 1, true);
                middletext = gui.AddStaticText("Click to enable mouselook and move with WASD",
                                               new Recti(ClientSize.Width / 2 - 100, this.ClientSize.Height / 2, ClientSize.Width / 2 + 100, this.ClientSize.Height / 2 + 30), true, true, null, 1, true);
                middletext.OverrideColor   = IrrlichtLime.Video.Color.SolidWhite;
                middletext.BackgroundColor = IrrlichtLime.Video.Color.SolidBlack;
                var irrTimer = device.Timer;
                var then     = 0;
                var then30   = 0;

                device.CursorControl.Visible = false;

                Vector2Df lastcurr = new Vector2Df(0f);
                uint      dt       = 0;
                while (device.Run())
                {
                    driver.BeginScene(ClearBufferFlag.All);

                    if (catchmouse)
                    {
                        // move the arrow to the nearest vertex ...
                        IrrlichtLime.Core.Vector2Di center = new IrrlichtLime.Core.Vector2Di(irrlichtPanel.Width / 2, irrlichtPanel.Height / 2);
                        Line3Df     ray = smgr.SceneCollisionManager.GetRayFromScreenCoordinates(center, cam);
                        Vector3Df   pos;
                        Triangle3Df Tri;
                        var         curr = device.CursorControl.RelativePosition;

                        // Threshold and periodical check so we don't spin around due to float conversions
                        if (device.Timer.Time > dt && curr.GetDistanceFrom(lastcurr) > 0.01f)
                        {
                            Line3Df cursor_ray = smgr.SceneCollisionManager
                                                 .GetRayFromScreenCoordinates(new Vector2Di((int)(curr.X * irrlichtPanel.Width), (int)(curr.Y * irrlichtPanel.Height)), cam);

                            smgr.ActiveCamera.Target = cursor_ray.Middle;
                            dt       = device.Timer.Time + 30;
                            lastcurr = curr;
                            device.CursorControl.Position = center;
                        }

                        if (smgr.SceneCollisionManager.GetCollisionPoint(ray, selector, out pos, out Tri, out outnode))
                        {
                            var scale = 32;  // terrain is scaled 32X
                            var size  = 512; // heightmap is 512x512 pixels
                            var x     = (pos.X / scale);
                            var z     = (pos.Z / scale);
                            var index = x * size + z;

                            x *= scale;
                            z *= scale;

                            arrow.Position = new Vector3Df(x, terrain.GetHeight(x, z) + 100, z);
                        }
                    }

                    smgr.DrawAll();
                    gui.DrawAll();

                    driver.EndScene();

                    //device.CursorControl.Position = new Vector2Di(irrlichtPanel.
                }

                device.Drop();
            }
            catch (ThreadAbortException) { }
            catch (NullReferenceException) { }
            catch (Exception ex)
            {
                if (!this.IsDisposed)
                {
                    MessageBox.Show(ex.Message);
                    //this.Invoke(new MethodInvoker(delegate { this.Close(); }));
                }
            }
        }