示例#1
0
        static void Main(string[] args)
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(
                DriverType.OpenGL, new Dimension2Di(640, 480), 16, false, false, false);

            device.SetWindowCaption("testing irrlicht engine lol");

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

            gui.AddStaticText("Hello World! This is the Irrlicht Software renderer!",
                              new Recti(10, 10, 260, 22), true);

            smgr.AddCameraSceneNode(null, new Vector3Df(0, 30, -40), new Vector3Df(0, 5, 0));

            while (device.Run())
            {
                driver.BeginScene(ClearBufferFlag.All, new Color(100, 101, 140));

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

                driver.EndScene();
            }

            device.Drop();
        }
示例#2
0
        private void initScene()
        {
            SceneManager smgr = device.SceneManager;

            AnimatedMesh m = smgr.AddHillPlaneMesh("plane", new Dimension2Df(16), new Dimension2Di(16), null, 8);

            sceneNodePainter       = smgr.AddAnimatedMeshSceneNode(m);
            sceneNodePainter.Scale = new Vector3Df(0.4f);
            sceneNodePainter.SetMaterialTexture(0, texture);
            sceneNodePainter.SetMaterialFlag(MaterialFlag.Lighting, false);
            SceneNodeAnimator a = smgr.CreateRotationAnimator(new Vector3Df(0, 0.1f, 0));

            sceneNodePainter.AddAnimator(a);
            a.Drop();

            sceneNodeRTT = smgr.AddWaterSurfaceSceneNode(m.GetMesh(0), 2, 100, 20);
            sceneNodeRTT.SetMaterialFlag(MaterialFlag.Lighting, false);
            sceneNodeRTT.SetMaterialType(MaterialType.Solid);
            sceneNodeRTT.Scale    = new Vector3Df(0.2f);
            sceneNodeRTT.Position = new Vector3Df(60, 10, 40);
            sceneNodeRTT.Rotation = new Vector3Df(-30, 20, 0);

            textureRTT = smgr.VideoDriver.AddRenderTargetTexture(new Dimension2Di(512));
            sceneNodeRTT.SetMaterialTexture(0, textureRTT);

            smgr.AddCameraSceneNode(null, new Vector3Df(0, 40, -60), new Vector3Df(0, -15, 0));
        }
示例#3
0
        static void Main()
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(800, 600));

            device.SetWindowCaption("RGB swirl example - Irrlicht Lime");

            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;

            var camera = scene.AddCameraSceneNode(null, new Vector3Df(0, 0, -15), new Vector3Df());

            camera.ViewMatrixAffector = camera.ProjectionMatrix.GetInverse();

            var lightRed = scene.AddLightSceneNode(null, new Vector3Df(0, 40, 0));

            lightRed.LightData.DiffuseColor = new Colorf(1, 0, 0);
            var a = scene.CreateFlyCircleAnimator(new Vector3Df(), 40, 0.0003f, new Vector3Df(0, 0, 1), 0.000f);

            lightRed.AddAnimator(a);
            a.Drop();

            var lightGreen = scene.AddLightSceneNode(null, new Vector3Df(-30, -20, 0));

            lightGreen.LightData.DiffuseColor = new Colorf(0, 1, 0);
            a = scene.CreateFlyCircleAnimator(new Vector3Df(), 40, 0.0003f, new Vector3Df(0, 0, 1), 0.333f);
            lightGreen.AddAnimator(a);
            a.Drop();

            var lightBlue = scene.AddLightSceneNode(null, new Vector3Df(30, -20, 0));

            lightBlue.LightData.DiffuseColor = new Colorf(0, 0, 1);
            a = scene.CreateFlyCircleAnimator(new Vector3Df(), 40, 0.0003f, new Vector3Df(0, 0, 1), 0.667f);
            lightBlue.AddAnimator(a);
            a.Drop();

            var node = scene.AddSphereSceneNode(5.5f, 255);

            node.SetMaterialFlag(MaterialFlag.BackFaceCulling, false);
            node.SetMaterialFlag(MaterialFlag.PointCloud, true);
            node.GetMaterial(0).Thickness = 4;

            while (device.Run())
            {
                node.Rotation = new Vector3Df(device.Timer.Time / 1, device.Timer.Time / 2, device.Timer.Time / 3);

                driver.BeginScene(ClearBufferFlag.Depth);
                scene.DrawAll();
                driver.EndScene();
            }

            device.Drop();
        }
示例#4
0
        static void Main()
        {
            device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1280, 720));
            if (device == null)
            {
                return;
            }

            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;

            device.SetWindowCaption("Abstract Trace - Irrlicht Engine");
            device.OnEvent += Device_OnEvent;

            GUIFont font      = device.GUIEnvironment.GetFont("../../media/fontlucida.png");
            Color   textColor = Color.SolidWhite;

            CameraSceneNode camera = scene.AddCameraSceneNode();

            camera.FarValue = 20000;
            SceneNodeAnimator a = scene.CreateFlyCircleAnimator(new Vector3Df(), (AbstractTrace.CubeSize * AbstractTrace.GridDim) / 1.25f, 0.000025f, new Vector3Df(0.1f, 1, 0));

            camera.AddAnimator(a);
            a.Drop();

            trace = new AbstractTrace(device);
            trace.Init();

            while (device.Run())
            {
                driver.BeginScene();
                scene.DrawAll();

                if (!isPaused)
                {
                    trace.Step();
                }

                trace.Draw(drawGenerator);

                font.Draw("[G]enerator: " + (drawGenerator ? "ON" : "OFF"), new Vector2Di(20, 20), textColor);
                font.Draw("[P]ause: " + (isPaused ? "ON" : "OFF"), new Vector2Di(20, 35), textColor);
                font.Draw("Cubes: " + trace.GetTotalCubeCount(), new Vector2Di(20, 50), textColor);
                font.Draw("FPS: " + driver.FPS, new Vector2Di(20, 65), textColor);

                driver.EndScene();
            }

            trace.Drop();
            device.Drop();
        }
        public bool init_scene()
        {
            _scene.AddCameraSceneNode(null);

            _scene.ActiveCamera.Position = new Vector3D(0, -15, 0);
            _scene.ActiveCamera.Target   = new Vector3D();

            _scene.AddLightSceneNode(null, new Vector3D(20, -15, 3), new Colorf(1.0f, 1.0f, 1.0f, 1.0f), 100.0f, -1);

            _scene.AddLightSceneNode(null, new Vector3D(-20, -15, -4), new Colorf(1.0f, 1.0f, 1.0f, 1.0f), 100.0f, -1);

            _model3D = new LaserDataSceneNode(null, _scene, 666);

            return(true);
        }
示例#6
0
        public WaterSceneNode(SceneNode parent, SceneManager mgr, Dimension2Df tileSize,
                              Dimension2D tileCount, Dimension2D precision, int id) :
            base(parent, mgr, id)
        {
            _scene = mgr;
            _driver = mgr.VideoDriver;

            AnimatedMesh wmesh = _scene.AddHillPlaneMesh("watermesh" + _current,
                tileSize,
                tileCount, 0,
                new Dimension2Df(0, 0),
                new Dimension2Df(1, 1));
            _current++;

            int dmat;
            if (_driver.DriverType == DriverType.OpenGL)
                dmat = _driver.GPUProgrammingServices.AddHighLevelShaderMaterial(
                 WATER_VERTEX_GLSL, "main", VertexShaderType._1_1, WATER_FRAGMENT_GLSL,
                 "main", PixelShaderType._1_1, OnShaderSet, MaterialType.TransparentAlphaChannel, 0);
            else
                dmat = _driver.GPUProgrammingServices.AddHighLevelShaderMaterial(
                 WATER_HLSL, "vertexMain", VertexShaderType._2_0, WATER_HLSL,
                 "pixelMain", PixelShaderType._2_0, OnShaderSet, MaterialType.TransparentAlphaChannel, 2);

            if (_driver.DriverType == DriverType.OpenGL)
                ClampShader = _driver.GPUProgrammingServices.AddHighLevelShaderMaterial(
                 CLAMP_VERTEX_GLSL, "main", VertexShaderType._1_1, CLAMP_FRAGMENT_GLSL,
                 "main", PixelShaderType._1_1, OnShaderSet, MaterialType.TransparentAlphaChannel, 1);
            else
                ClampShader = _driver.GPUProgrammingServices.AddHighLevelShaderMaterial(
                 CLAMP_HLSL, "vertexMain", VertexShaderType._2_0, CLAMP_HLSL,
                 "pixelMain", PixelShaderType._2_0, OnShaderSet, MaterialType.TransparentAlphaChannel, 3);

            _waternode = _scene.AddMeshSceneNode(wmesh.GetMesh(0), this, -1);
            _waternode.SetMaterialType(dmat);
            _waternode.SetMaterialFlag(MaterialFlag.BackFaceCulling, false);
            _waternode.SetMaterialFlag(MaterialFlag.Lighting, false);
            _waternode.SetMaterialFlag(MaterialFlag.FogEnable, false);

            _rt = _driver.CreateRenderTargetTexture(precision);
            _waternode.SetMaterialTexture(0, _rt);

            CameraSceneNode oldcam = _scene.ActiveCamera;
            _fixedcam = _scene.AddCameraSceneNode(null);
            if (oldcam != null)
                _scene.ActiveCamera = oldcam;
        }
示例#7
0
        static void Main(string[] args)
        {
            IrrlichtDevice device =
                IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(640, 480), 16, false);

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

            smgr.AddCameraSceneNode(null, new Vector3Df(0, -40, 0), new Vector3Df(0));

            CSampleSceneNode myNode = new CSampleSceneNode(smgr.RootNode, smgr, 667);

            SceneNodeAnimator anim = smgr.CreateRotationAnimator(new Vector3Df(0.8f, 0, 0.8f));

            if (anim != null)
            {
                myNode.AddAnimator(anim);
                anim.Drop();
                anim = null;
            }

            myNode.Drop();
            myNode = null;

            int frames = 0;

            while (device.Run())
            {
                driver.BeginScene(true, true, new Color(100, 100, 100));
                smgr.DrawAll();
                driver.EndScene();

                if (++frames == 100)
                {
                    device.SetWindowCaption(String.Format(
                                                "Custom Scene Node - Irrlicht Engine [{0}] fps: {1}",
                                                driver.Name, driver.FPS));

                    frames = 0;
                }
            }

            device.Drop();
        }
示例#8
0
        static void Main(string[] args)
        {
            device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1280, 720));
            if (device == null)
            {
                return;
            }

            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;

            CameraSceneNode camera = scene.AddCameraSceneNode();

            camera.FarValue = 20000;
            SceneNodeAnimator a = scene.CreateFlyCircleAnimator(new Vector3Df(), (AbstractTrace.CubeSize * AbstractTrace.GridDim) / 1.25f, 0.000025f, new Vector3Df(0.1f, 1, 0));

            camera.AddAnimator(a);
            a.Drop();

            trace = new AbstractTrace(device);
            trace.Init();

            int lastFps = -1;

            while (device.Run())
            {
                driver.BeginScene();
                scene.DrawAll();
                trace.Step();
                trace.Draw();
                driver.EndScene();

                int fps = driver.FPS;
                if (fps != lastFps)
                {
                    device.SetWindowCaption("Abstract Trace - Irrlicht Engine [" + fps + " fps; " + trace.GetTotalCubeCount() + " cubes]");
                    lastFps = fps;
                }
            }

            trace.Drop();
            device.Drop();
        }
示例#9
0
        static void Main(string[] args)
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(
                DriverType.Software, new Dimension2Di(640, 480), 16, false, false, false);

            device.SetWindowCaption("Hello World! - Irrlicht Engine Demo");

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

            gui.AddStaticText("Hello World! This is the Irrlicht Software renderer!",
                              new Recti(10, 10, 260, 22), true);

            //          AnimatedMesh mesh = smgr.GetMesh("../../media/sydney.md2");
            //          AnimatedMeshSceneNode node = smgr.AddAnimatedMeshSceneNode(mesh);
            //
            //          if (node != null)
            //          {
            //              node.SetMaterialFlag(MaterialFlag.Lighting, false);
            //              node.SetMD2Animation(AnimationTypeMD2.Stand);
            //              node.SetMaterialTexture(0, driver.GetTexture("../../media/sydney.bmp"));
            //          }

            smgr.AddCameraSceneNode(null, new Vector3Df(0, 30, -40), new Vector3Df(0, 5, 0));

            while (device.Run())
            {
                driver.BeginScene(true, true, new Color(100, 101, 140));

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

                driver.EndScene();
            }

            device.Drop();
        }
示例#10
0
        private static void Main()
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(
                DriverType.OpenGL, new Dimension2Di(640, 480), 16, false, false, false);

            device.SetWindowCaption("Rockplanets BUILD 16 (DEBUG MODE)");

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

            CameraSceneNode cam = smgr.AddCameraSceneNode();

            cam.Target = new Vector3Df(0);

            SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f);

            cam.AddAnimator(anim);
            anim.Drop();

            SceneNode cube = smgr.AddCubeSceneNode(20f);

            cube.SetMaterialFlag(MaterialFlag.Lighting, false);



            while (device.Run())
            {
                driver.BeginScene(ClearBufferFlag.All, new Color(235, 235, 235));

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

                driver.EndScene();
            }

            device.Drop();
        }
示例#11
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();
        }
示例#12
0
        private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker   = sender as BackgroundWorker;
            DeviceSettings   settings = e.Argument as DeviceSettings;

            // create irrlicht device using provided settings

            IrrlichtDevice dev = IrrlichtDevice.CreateDevice(settings);

            if (dev == null)
            {
                throw new Exception("Failed to create Irrlicht device.");
            }

            VideoDriver  drv  = dev.VideoDriver;
            SceneManager smgr = dev.SceneManager;

            // setup a simple 3d scene

            CameraSceneNode cam = smgr.AddCameraSceneNode();

            cam.Target = new Vector3Df(0);

            SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f);

            cam.AddAnimator(anim);
            anim.Drop();

            SceneNode cube = smgr.AddCubeSceneNode(20);

            cube.SetMaterialTexture(0, drv.GetTexture("../../media/wall.bmp"));
            cube.SetMaterialTexture(1, drv.GetTexture("../../media/water.jpg"));
            cube.SetMaterialFlag(MaterialFlag.Lighting, false);
            cube.SetMaterialType(MaterialType.Reflection2Layer);

            if (settings.BackColor == null)
            {
                smgr.AddSkyBoxSceneNode(
                    "../../media/irrlicht2_up.jpg",
                    "../../media/irrlicht2_dn.jpg",
                    "../../media/irrlicht2_lf.jpg",
                    "../../media/irrlicht2_rt.jpg",
                    "../../media/irrlicht2_ft.jpg",
                    "../../media/irrlicht2_bk.jpg");
            }

            dev.GUIEnvironment.AddImage(
                drv.GetTexture("../../media/lime_logo_alpha.png"),
                new Vector2Di(30, 0));

            // draw all

            int lastFPS = -1;

            while (dev.Run())
            {
                if (settings.BackColor == null)
                {
                    // indeed, we do not need to spend time on cleaning color buffer if we use skybox
                    drv.BeginScene(false);
                }
                else
                {
                    drv.BeginScene(true, true, settings.BackColor);
                }

                smgr.DrawAll();
                dev.GUIEnvironment.DrawAll();
                drv.EndScene();

                int fps = drv.FPS;
                if (lastFPS != fps)
                {
                    // report progress using common BackgroundWorker' method
                    // note: we cannot do just labelRenderingStatus.Text = "...",
                    // because we are running another thread
                    worker.ReportProgress(fps, drv.Name);
                    lastFPS = fps;
                }

                // if we requested to stop, we close the device
                if (worker.CancellationPending)
                {
                    dev.Close();
                }
            }

            // drop device
            dev.Drop();
        }
示例#13
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

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

            if (device == null)
            {
                return;
            }

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

            // load and display animated fairy mesh
            AnimatedMeshSceneNode fairy = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/faerie.md2"));

            if (fairy != null)
            {
                fairy.SetMaterialTexture(0, driver.GetTexture("../../media/faerie2.bmp")); // set diffuse texture
                fairy.SetMaterialFlag(MaterialFlag.Lighting, true);                        // enable dynamic lighting
                fairy.GetMaterial(0).Shininess = 20.0f;                                    // set size of specular highlights
                fairy.Position = new Vector3Df(-10, 0, -100);
                fairy.SetMD2Animation(AnimationTypeMD2.Stand);
            }

            // add white light
            smgr.AddLightSceneNode(null, new Vector3Df(-15, 5, -105), new Colorf(1, 1, 1));

            // set ambient light
            smgr.AmbientLight = new Colorf(0.25f, 0.25f, 0.25f);

            // add fps camera
            CameraSceneNode fpsCamera = smgr.AddCameraSceneNodeFPS();

            fpsCamera.Position = new Vector3Df(-50, 50, -150);

            // disable mouse cursor
            device.CursorControl.Visible = false;

            // create test cube
            SceneNode test = smgr.AddCubeSceneNode(60);

            // let the cube rotate and set some light settings
            SceneNodeAnimator anim = smgr.CreateRotationAnimator(new Vector3Df(0.3f, 0.3f, 0));

            test.Position = new Vector3Df(-100, 0, -100);
            test.SetMaterialFlag(MaterialFlag.Lighting, false);             // disable dynamic lighting
            test.AddAnimator(anim);
            anim.Drop();

            // create render target
            Texture         rt       = null;
            CameraSceneNode fixedCam = null;

            if (driver.QueryFeature(VideoDriverFeature.RenderToTarget))
            {
                rt = driver.AddRenderTargetTexture(new Dimension2Di(256), "RTT1");
                test.SetMaterialTexture(0, rt);                 // set material of cube to render target

                // add fixed camera
                fixedCam = smgr.AddCameraSceneNode(null, new Vector3Df(10, 10, -80), new Vector3Df(-10, 10, -100));
            }
            else
            {
                // create problem text
                GUIFont font = env.GetFont("../../media/fonthaettenschweiler.bmp");
                if (font != null)
                {
                    env.Skin.SetFont(font);
                }

                GUIStaticText text = env.AddStaticText(
                    "Your hardware or this renderer is not able to use the " +
                    "render to texture feature. RTT Disabled.",
                    new Recti(150, 20, 470, 60));

                text.OverrideColor = new Color(255, 255, 255, 100);
            }

            int lastFPS = -1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(ClearBufferFlag.All, new Color(0));

                    if (rt != null)
                    {
                        // draw scene into render target

                        // set render target texture
                        driver.SetRenderTarget(rt, ClearBufferFlag.All, new Color(0, 0, 255));

                        // make cube invisible and set fixed camera as active camera
                        test.Visible      = false;
                        smgr.ActiveCamera = fixedCam;

                        // draw whole scene into render buffer
                        smgr.DrawAll();

                        // set back old render target
                        // The buffer might have been distorted, so clear it
                        driver.SetRenderTarget(null, ClearBufferFlag.All, new Color(0));

                        // make the cube visible and set the user controlled camera as active one
                        test.Visible      = true;
                        smgr.ActiveCamera = fpsCamera;
                    }

                    // draw scene normally
                    smgr.DrawAll();
                    env.DrawAll();

                    driver.EndScene();

                    // display frames per second in window title
                    int fps = driver.FPS;
                    if (lastFPS != fps)
                    {
                        device.SetWindowCaption(String.Format(
                                                    "Render to Texture and Specular Highlights example - Irrlicht Engine [{0}] fps: {1}",
                                                    driver.Name, fps));

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }
        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker           worker = sender as BackgroundWorker;
            IrrlichtCreationParameters p      = new IrrlichtCreationParameters();

            p.DriverType = DriverType.Direct3D9;
            p.WindowID   = (IntPtr)e.Argument;

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(p);

            if (device == null)
            {
                // if device cannot be created by any reason - we just leave this thread,
                // after all IsRedering will report false, so it is all OK.
                return;
            }

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

            // setup a simple 3d scene

            CameraSceneNode cam = smgr.AddCameraSceneNode();

            cam.Target = new Vector3Df(0);

            SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f);

            cam.AddAnimator(anim);
            anim.Drop();

            SceneNode cube = smgr.AddCubeSceneNode(20);

            cube.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
            cube.SetMaterialTexture(1, driver.GetTexture("../../media/water.jpg"));
            cube.SetMaterialFlag(MaterialFlag.Lighting, false);
            cube.SetMaterialType(MaterialType.Reflection2Layer);

            smgr.AddSkyBoxSceneNode(
                "../../media/irrlicht2_up.jpg",
                "../../media/irrlicht2_dn.jpg",
                "../../media/irrlicht2_lf.jpg",
                "../../media/irrlicht2_rt.jpg",
                "../../media/irrlicht2_ft.jpg",
                "../../media/irrlicht2_bk.jpg");

            gui.AddImage(
                driver.GetTexture("../../media/lime_logo_alpha.png"),
                new Vector2Di(30, 0));

            // draw all

            while (device.Run())
            {
                driver.BeginScene(false);

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

                // draw stats

                int x = 20;
                int y = driver.ScreenSize.Height - 50;

                driver.Draw2DRectangle(
                    new Recti(x, y, x + driver.ScreenSize.Width - 2 * x, y + 30),
                    new IrrlichtLime.Video.Color(0, 0, 0, 128));

                device.GUIEnvironment.BuiltInFont.Draw(
                    "Driver: " + driver.Name,
                    new Vector2Di(x + 5, y + 5),
                    new IrrlichtLime.Video.Color(255, 255, 255));

                device.GUIEnvironment.BuiltInFont.Draw(
                    "FPS: " + driver.FPS.ToString(),
                    new Vector2Di(x + 5, y + 15),
                    new IrrlichtLime.Video.Color(255, 255, 255));

                driver.EndScene();

                // check for cancellation

                if (worker.CancellationPending)
                {
                    device.Close();
                }

                // check for new command

                lock (backgroundCommand)
                {
                    switch (backgroundCommand.Type)
                    {
                    case Command.Kind.Resized:
                        driver.ResizeNotify(backgroundCommand.Value as Dimension2Di);
                        backgroundCommand.Clear();
                        break;
                    }
                }
            }

            // drop the device

            device.Drop();
        }
示例#15
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

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

            if (device == null)
            {
                return;
            }

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

            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;

            scene.GUIEnvironment.AddStaticText("Press Space to hide occluder.", new Recti(10, 10, 200, 50));

            // Create the node to be occluded. We create a sphere node with high poly count.

            MeshSceneNode node = scene.AddSphereSceneNode(10, 64);

            if (node != null)
            {
                node.Position = new Vector3Df(0, 0, 60);
                node.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
                node.SetMaterialFlag(MaterialFlag.Lighting, false);
            }

            // Now we create another node, the occluder. It's a simple plane.

            SceneNode plane = scene.AddMeshSceneNode(
                scene.AddHillPlaneMesh("plane", new Dimension2Df(10), new Dimension2Di(2)), // mesh
                null,                                                                       // parent
                -1,                                                                         // id
                new Vector3Df(0, 0, 20),                                                    // position
                new Vector3Df(270, 0, 0));                                                  // rotation

            if (plane != null)
            {
                plane.SetMaterialTexture(0, driver.GetTexture("../../media/t351sml.jpg"));
                plane.SetMaterialFlag(MaterialFlag.Lighting, false);
                plane.SetMaterialFlag(MaterialFlag.BackFaceCulling, true);
            }

            // Here we create the occlusion query. Because we don't have a plain mesh scene node
            // (SceneNodeType.Mesh or SceneNodeType.AnimatedMesh), we pass the base geometry as well. Instead,
            // we could also pass a simpler mesh or the bounding box. But we will use a time
            // based method, where the occlusion query renders to the frame buffer and in case
            // of success (occlusion), the mesh is not drawn for several frames.

            driver.AddOcclusionQuery(node, node.Mesh);

            // We have done everything, just a camera and draw it. We also write the
            // current frames per second and the name of the driver to the caption of the
            // window to examine the render speedup.
            // We also store the time for measuring the time since the last occlusion query ran
            // and store whether the node should be visible in the next frames.

            scene.AddCameraSceneNode();
            uint timeNow     = device.Timer.Time;
            bool nodeVisible = true;

            while (device.Run())
            {
                plane.Visible = !IsKeyDown(KeyCode.Space);

                driver.BeginScene(ClearBufferFlag.All, new Color(113, 113, 133));

                // First, we draw the scene, possibly without the occluded element. This is necessary
                // because we need the occluder to be drawn first. You can also use several scene
                // managers to collect a number of possible occluders in a separately rendered scene.

                node.Visible = nodeVisible;
                scene.DrawAll();
                scene.GUIEnvironment.DrawAll();

                // Once in a while, here every 100 ms, we check the visibility. We run the queries,
                // update the pixel value, and query the result. Since we already rendered the node
                // we render the query invisible. The update is made blocking, as we need the result
                // immediately. If you don't need the result immediately, e.g. because oyu have other
                // things to render, you can call the update non-blocking. This gives the GPU more
                // time to pass back the results without flushing the render pipeline.
                // If the update was called non-blocking, the result from getOcclusionQueryResult is
                // either the previous value, or 0xffffffff if no value has been generated at all, yet.
                // The result is taken immediately as visibility flag for the node.

                if (device.Timer.Time - timeNow > 100)
                {
                    driver.RunAllOcclusionQueries(false);
                    driver.UpdateAllOcclusionQueries();
                    nodeVisible = driver.GetOcclusionQueryResult(node) > 0;
                    timeNow     = device.Timer.Time;
                }

                driver.EndScene();

                device.SetWindowCaption(String.Format(
                                            "Occlusion Query Example - Irrlicht Engine [{0}] fps: {1} (primitives: {2})",
                                            driver.Name, driver.FPS, driver.PrimitiveCountDrawn));
            }

            device.Drop();
        }
        private static float _playerVerticalSpeed = 0.0f; // used to calculate vertical speed for gravity and jump
        static void Main(string[] args)
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(ResolutionX, ResolutionY), 24, false, false, false);

            device.OnEvent += Device_OnEvent;
            device.SetWindowCaption("Hello World! - Irrlicht Engine Demo");

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

            GUIEnvironment gui = device.GUIEnvironment;

            gui.AddStaticText("Hello World! This is the Irrlicht Software renderer!",
                              new Recti(10, 10, 260, 22), true);

            AnimatedMesh          mesh       = smgr.GetMesh("../../media/sydney.md2");
            AnimatedMeshSceneNode sydneyNode = smgr.AddAnimatedMeshSceneNode(mesh);

            var cubeSceneNode = smgr.AddCubeSceneNode(2.0f);

            cubeSceneNode.Scale    = new Vector3Df(6.0f, 2.0f, 100.0f);
            cubeSceneNode.Position = new Vector3Df(cubeSceneNode.Position.X, GroundAltitude + 0.5f, cubeSceneNode.Position.Z);

            if (sydneyNode != null)
            {
                sydneyNode.SetMaterialFlag(MaterialFlag.Lighting, true);
                sydneyNode.SetMD2Animation(AnimationTypeMD2.Stand);
                sydneyNode.SetMaterialTexture(0, driver.GetTexture("../../media/sydney.bmp"));
            }

            var lightSceneNode = smgr.AddLightSceneNode();
            var light          = lightSceneNode.LightData;

            light.DiffuseColor = new Colorf(0.8f, 1.0f, 1.0f);
            light.Type         = LightType.Directional;
            light.Position     = new Vector3Df(0.0f, 5.0f, 5.0f);


            var cam = smgr.AddCameraSceneNode(null, new Vector3Df(20, 30, -40), new Vector3Df(20, 5, 0));

            device.Timer.Start();

            uint then = device.Timer.RealTime;

            while (device.Run())
            {
                // As the game is simple we will handle our simple physics ourselves
                uint  now            = device.Timer.RealTime;
                uint  elapsed        = now - then;
                float elapsedTimeSec = (float)elapsed / 1000.0f;
                then = now;

                // we target 58.8 FPS
                if (elapsed < 17)
                {
                    device.Sleep(17 - (int)elapsed);
                }
                else
                {
                    // uh-oh, it took more than .125 sec to do render loop!
                    // what do we do now?
                }

                _playerVerticalSpeed += elapsedTimeSec * -(VerticalGravity * 10.0f);

                var calculatedNewPos = sydneyNode.Position - new Vector3Df(0.0f, _playerVerticalSpeed * elapsedTimeSec, 0.0f);

                float offsetSydney = sydneyNode.BoundingBox.Extent.Y / 2.0f;
                _isGrounded = calculatedNewPos.Y <= (GroundAltitude + offsetSydney);
                if (_isGrounded)
                {
                    _playerVerticalSpeed = 0.0f;
                    calculatedNewPos.Y   = GroundAltitude + offsetSydney;
                }
                else
                {
                    calculatedNewPos.Y = calculatedNewPos.Y;
                }

                sydneyNode.Position = calculatedNewPos;

                driver.BeginScene(true, true, new Color(100, 101, 140));
                smgr.DrawAll();
                gui.DrawAll();

                driver.EndScene();
            }

            device.Drop();
        }
示例#17
0
        private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker   = sender as BackgroundWorker;
            DeviceSettings   settings = e.Argument as DeviceSettings;

            // create irrlicht device using provided settings

            IrrlichtDevice dev = IrrlichtDevice.CreateDevice(settings);

            if (dev == null)
            {
                throw new Exception("Failed to create Irrlicht device.");
            }

            dev.Logger.LogLevel = LogLevel.Warning;
            VideoDriver  drv  = dev.VideoDriver;
            SceneManager smgr = dev.SceneManager;

            smgr.FileSystem.AddFileArchive("E:/WitcherMods/modTest/Test/files/Mod/Bundle");
            smgr.FileSystem.AddFileArchive("E:/WitcherMods/modTest/Test/files/Raw/Mod/TextureCache");

            smgr.Attributes.AddValue("TW_TW3_LOAD_SKEL", true);
            smgr.Attributes.AddValue("TW_TW3_LOAD_BEST_LOD_ONLY", true);

            // setup a simple 3d scene

            //CameraSceneNode cam = smgr.AddCameraSceneNode();
            //cam.Target = new Vector3Df(0);

            // added by vl
            AnimatedMesh mesh = smgr.GetMesh("E:/WitcherMods/modTest/Test/files/Mod/Bundle/characters/models/animals/cat/model/t_01__cat.w2mesh");

            if (mesh == null)
            {
                throw new Exception("Failed to load mesh.");
            }

            smgr.MeshManipulator.RecalculateNormals(mesh);

            List <String> animList = null;

            float scaleMul               = 1.0f;
            AnimatedMeshSceneNode node   = smgr.AddAnimatedMeshSceneNode(mesh);
            MeshLoaderHelper      helper = smgr.GetMeshLoader(smgr.MeshLoaderCount - 1).getMeshLoaderHelper();

            if (node != null)
            {
                scaleMul   = node.BoundingBox.Radius / 4;
                node.Scale = new Vector3Df(3.0f);
                node.SetMaterialFlag(MaterialFlag.Lighting, false);

                SkinnedMesh sm = helper.loadRig("E:/WitcherMods/modTest/Test/files/Mod/Bundle/characters/base_entities/cat_base/cat_base.w2rig", mesh);
                if (sm == null)
                {
                    throw new Exception("Failed to load rig.");
                }

                animList = helper.loadAnimation("E:/WitcherMods/modTest/Test/files/Mod/Bundle/animations/animals/cat/cat_animation.w2anims", sm);
                if (animList.Count > 0)
                {
                    AnimatedMesh am = helper.applyAnimation(animList[0], sm);
                    node.Mesh = am;
                }
                //scaleSkeleton(sm, 3.0f);
                //sm.SkinMesh();

                mesh.Drop();
                sm.Drop();
                setMaterialsSettings(node);

                /*
                 * animList = helper.loadAnimation("E:/WitcherMods/modTest/Test/files/Mod/Bundle/animations/animals/cat/cat_animation.w2anims", node);
                 * if (animList.Count > 0)
                 * {
                 *      helper.applyAnimation(animList[0]);
                 * }
                 */
            }

            var camera = smgr.AddCameraSceneNode(null,
                                                 new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0),
                                                 new Vector3Df(0, node.BoundingBox.Radius, 0)
                                                 );

            camera.NearValue = 0.001f;
            camera.FOV       = 45.0f * 3.14f / 180.0f;

            node.DebugDataVisible ^= DebugSceneType.BBox | DebugSceneType.Skeleton;

            node.Position = new Vector3Df(0.0f);

            /*
             * SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f);
             * cam.AddAnimator(anim);
             * anim.Drop();
             *
             * SceneNode cube = smgr.AddCubeSceneNode(20);
             * cube.SetMaterialTexture(0, drv.GetTexture("../../media/wall.bmp"));
             * cube.SetMaterialTexture(1, drv.GetTexture("../../media/water.jpg"));
             * cube.SetMaterialFlag(MaterialFlag.Lighting, false);
             * cube.SetMaterialType(MaterialType.Reflection2Layer);
             */

            if (settings.BackColor == null)
            {
                smgr.AddSkyBoxSceneNode(
                    "../../media/irrlicht2_up.jpg",
                    "../../media/irrlicht2_dn.jpg",
                    "../../media/irrlicht2_lf.jpg",
                    "../../media/irrlicht2_rt.jpg",
                    "../../media/irrlicht2_ft.jpg",
                    "../../media/irrlicht2_bk.jpg");
            }

            dev.GUIEnvironment.AddImage(
                drv.GetTexture("../../media/lime_logo_alpha.png"),
                new Vector2Di(30, 0));

            // draw all

            int lastFPS = -1;

            while (dev.Run())
            {
                if (settings.BackColor == null)
                {
                    // indeed, we do not need to spend time on cleaning color buffer if we use skybox
                    drv.BeginScene(ClearBufferFlag.Depth);
                }
                else
                {
                    drv.BeginScene(ClearBufferFlag.Depth | ClearBufferFlag.Color, settings.BackColor);
                }

                smgr.DrawAll();
                dev.GUIEnvironment.DrawAll();
                drv.EndScene();

                int fps = drv.FPS;
                if (lastFPS != fps)
                {
                    // report progress using common BackgroundWorker' method
                    // note: we cannot do just labelRenderingStatus.Text = "...",
                    // because we are running another thread
                    worker.ReportProgress(fps, drv.Name);
                    lastFPS = fps;
                }

                // if we requested to stop, we close the device
                if (worker.CancellationPending)
                {
                    dev.Close();
                }
            }

            // drop device
            dev.Drop();
        }
示例#18
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(); }));
                }
            }
        }
        private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            //DeviceSettings settings = e.Argument as DeviceSettings;

            // create irrlicht device using provided settings
            if (panelRenderWindow.IsDisposed)
            {
                throw new Exception("Form closed!");
            }

            DeviceSettings s = new DeviceSettings(
                IntPtr.Zero,
                DriverType.Direct3D9,
                0,                  //antialias
                new Color(100, 101, 140),
                false);

            if (panelRenderWindow.InvokeRequired)
            {
                panelRenderWindow.Invoke(new MethodInvoker(delegate { s.WindowID = panelRenderWindow.Handle; }));
            }

            dev = IrrlichtDevice.CreateDevice(s);
            if (dev == null)
            {
                throw new NullReferenceException("Could not create device for engine!");
            }
            dev.OnEvent        += new IrrlichtDevice.EventHandler(this.device_OnEvent);
            dev.Logger.LogLevel = LogLevel.Warning;

            drv  = dev.VideoDriver;
            smgr = dev.SceneManager;
            gui  = dev.GUIEnvironment;

            _ = smgr.FileSystem.AddFileArchive(activeMod.FileDirectory);

            smgr.Attributes.AddValue("TW_TW3_LOAD_SKEL", true);
            smgr.Attributes.AddValue("TW_TW3_LOAD_BEST_LOD_ONLY", true);


            // added by vl
            if (meshFile != null && meshFile.Length > 0)
            {
                mesh = smgr.GetMesh(meshFile);
            }

            if (mesh == null)
            {
                throw new Exception("Failed to load mesh.");
            }

            mesh.Grab();
            smgr.MeshManipulator.RecalculateNormals(mesh);
            meshLoaded = true;

            float scaleMul = 1.0f;

            node   = smgr.AddAnimatedMeshSceneNode(mesh);
            helper = smgr.GetMeshLoader(smgr.MeshLoaderCount - 1).getMeshLoaderHelper();             // hacked to gat witcher3 loader
            if (node != null && meshLoaded)
            {
                node.Scale = new Vector3Df(3.0f);
                node.SetMaterialFlag(MaterialFlag.Lighting, false);

                scaleMul = node.BoundingBox.Radius / 4;

                if (!string.IsNullOrEmpty(rigFile))
                {
                    meshToAnimate = helper.loadRig(rigFile, mesh);
                    if (meshToAnimate == null)
                    {
                        throw new Exception("Failed to load rig.");
                    }
                    else
                    {
                        meshToAnimate.Grab();
                        rigLoaded = true;
                        Logger.LogString("Rig loaded!", Logtype.Success);
                        node.Mesh = meshToAnimate;
                    }
                }

                if (!string.IsNullOrEmpty(animFile) && rigLoaded)
                {
                    animList = helper.loadAnimation(animFile, meshToAnimate);
                    if (animList.Count > 0)
                    {
                        animLoaded = true;
                        Logger.LogString($"{animList.Count} animations loaded! Select animation to play", Logtype.Success);
                    }
                    else
                    {
                        Logger.LogString("No animations loaded!", Logtype.Important);
                    }
                }

                setMaterialsSettings(node);
            }

            var camera = smgr.AddCameraSceneNode(null,
                                                 new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0),
                                                 new Vector3Df(0, node.BoundingBox.Radius, 0));

            camera.NearValue = 0.001f;
            camera.FOV       = 45.0f * 3.14f / 180.0f;


            var animText = activeAnim;

            var mAnimText     = gui.AddStaticText(animText, new Recti(0, this.ClientSize.Height - 80, 100, this.ClientSize.Height - 70));
            var mPositionText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 70, 100, this.ClientSize.Height - 60));
            var mRotationText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 60, 100, this.ClientSize.Height - 50));
            var fpsText       = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 50, 100, this.ClientSize.Height - 40));
            var infoText      = gui.AddStaticText("[Space] - Reset\n[LMouse] - Rotate\n[MMouse] - Move\n[Wheel] - Zoom", new Recti(0, this.ClientSize.Height - 40, 100, this.ClientSize.Height));

            mAnimText.OverrideColor   = mPositionText.OverrideColor = mRotationText.OverrideColor = fpsText.OverrideColor = infoText.OverrideColor = new Color(255, 255, 255);
            mAnimText.BackgroundColor = mPositionText.BackgroundColor = mRotationText.BackgroundColor = fpsText.BackgroundColor = infoText.BackgroundColor = new Color(0, 0, 0);

            viewPort = drv.ViewPort;
            var lineMat = new Material
            {
                Lighting = false
            };

            while (dev.Run())
            {
                drv.ViewPort = viewPort;

                drv.BeginScene(ClearBufferFlag.Depth | ClearBufferFlag.Color, s.BackColor);

                node.Position = modelPosition;
                node.Rotation = modelAngle;

                //update info box
                mPositionText.Text = $"X: {modelPosition.X.ToString("F2")} Y: {modelPosition.Y.ToString("F2")} Z: {modelPosition.Z.ToString("F2")}";
                mRotationText.Text = $"Yaw: {modelAngle.Y.ToString("F2")} Roll: {modelAngle.Z.ToString("F2")}";
                fpsText.Text       = $"FPS: {drv.FPS}";

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

                // draw xyz axis right bottom

                drv.ViewPort = new Recti(this.ClientSize.Width - 100, this.ClientSize.Height - 80, this.ClientSize.Width, this.ClientSize.Height);

                drv.SetMaterial(lineMat);
                var matrix = new Matrix(new Vector3Df(0, 0, 0), modelAngle);
                drv.SetTransform(TransformationState.World, matrix);
                matrix = matrix.BuildProjectionMatrixOrthoLH(100, 80, camera.NearValue, camera.FarValue);
                drv.SetTransform(TransformationState.Projection, matrix);
                matrix = matrix.BuildCameraLookAtMatrixLH(new Vector3Df(50, 0, 0), new Vector3Df(0, 0, 0), new Vector3Df(0, 1f, 0));
                drv.SetTransform(TransformationState.View, matrix);
                drv.Draw3DLine(0, 0, 0, 30f, 0, 0, Color.SolidGreen);
                drv.Draw3DLine(0, 0, 0, 0, 30f, 0, Color.SolidBlue);
                drv.Draw3DLine(0, 0, 0, 0, 0, 30f, Color.SolidRed);

                drv.EndScene();

                // if we requested to stop, we close the device
                if (worker.CancellationPending)
                {
                    dev.Close();
                }
            }
            // drop device
            dev.Drop();
        }
示例#20
0
        static void Main(string[] args)
        {
            DriverType driverType;

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

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType, new Dimension2Di(ResX, ResY), 32, fullScreen);

            if (device == null)
            {
                return;
            }

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            // load model
            AnimatedMesh model = smgr.GetMesh("../../media/sydney.md2");

            if (model == null)
            {
                return;
            }

            AnimatedMeshSceneNode model_node = smgr.AddAnimatedMeshSceneNode(model);

            // load texture
            if (model_node != null)
            {
                Texture texture = driver.GetTexture("../../media/sydney.bmp");
                model_node.SetMaterialTexture(0, texture);
                model_node.SetMD2Animation(AnimationTypeMD2.Run);
                model_node.SetMaterialFlag(MaterialFlag.Lighting, false);
            }

            // load map
            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");
            AnimatedMesh map = smgr.GetMesh("20kdm2.bsp");

            if (map != null)
            {
                SceneNode map_node = smgr.AddOctreeSceneNode(map.GetMesh(0));
                map_node.Position = new Vector3Df(-850, -220, -850);
            }

            // create 3 fixed and one user-controlled cameras
            camera[0]          = smgr.AddCameraSceneNode(null, new Vector3Df(50, 0, 0), new Vector3Df(0)); // font
            camera[1]          = smgr.AddCameraSceneNode(null, new Vector3Df(0, 50, 0), new Vector3Df(0)); // top
            camera[2]          = smgr.AddCameraSceneNode(null, new Vector3Df(0, 0, 50), new Vector3Df(0)); // left
            camera[3]          = smgr.AddCameraSceneNodeFPS();                                             // user-controlled
            camera[3].Position = new Vector3Df(-50, 0, -50);

            device.CursorControl.Visible = false;

            int lastFPS = -1;

            while (device.Run())
            {
                // set the viewpoint to the whole screen and begin scene
                driver.ViewPort = new Recti(0, 0, ResX, ResY);
                driver.BeginScene(true, true, new Color(100, 100, 100));

                if (splitScreen)
                {
                    smgr.ActiveCamera = camera[0];
                    driver.ViewPort   = new Recti(0, 0, ResX / 2, ResY / 2);                   // top left
                    smgr.DrawAll();

                    smgr.ActiveCamera = camera[1];
                    driver.ViewPort   = new Recti(ResX / 2, 0, ResX, ResY / 2);                   // top right
                    smgr.DrawAll();

                    smgr.ActiveCamera = camera[2];
                    driver.ViewPort   = new Recti(0, ResY / 2, ResX / 2, ResY);                   // bottom left
                    smgr.DrawAll();

                    driver.ViewPort = new Recti(ResX / 2, ResY / 2, ResX, ResY);                     // bottom right
                }

                smgr.ActiveCamera = camera[3];
                smgr.DrawAll();

                driver.EndScene();

                int fps = driver.FPS;
                if (lastFPS != fps)
                {
                    device.SetWindowCaption(String.Format(
                                                "Split Screen example - Irrlicht Engine [{0}] fps: {1}",
                                                driver.Name, fps));

                    lastFPS = fps;
                }
            }

            device.Drop();
        }
示例#21
0
        public Application()
        {
            _01.HelloWorld.Kinect kinect = new _01.HelloWorld.Kinect();
            mfX = mouseX = 840; mfY = mouseY = 525; mouseL = false; mouseR = false;
            //device = IrrlichtDevice.CreateDevice(
            //    DriverType.Direct3D9, new Dimension2Di(800, 600), 16, false, true, false);
            //                                                           |
            device = IrrlichtDevice.CreateDevice(                    // \|/ Fullscreen
                DriverType.Direct3D9, new Dimension2Di(1680, 1050), 32, false, true, false);

            device.SetWindowCaption("BENder3D");

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

            device.OnEvent   += new IrrlichtDevice.EventHandler(device_OnEvent);
            smgr.AmbientLight = new Colorf(128, 128, 128, 128);
            //smgr.AddLightSceneNode(null, new Vector3Df(0, 70, 0), new Colorf(122,0,122,0), (float)10);
            MeshSceneNode box = smgr.AddCubeSceneNode(100, null, 9001, new Vector3Df(0.0f, -ballRadius * 3 / 2, 0.0f));

            box.Scale = new Vector3Df(100.0f, 0.1f, 100.0f);
            //Mesh cyl = smgr.GeometryCreator.CreateCylinderMesh(ballRadius, 50, 256);
            //Mesh sphere = smgr.GeometryCreator.CreateSphereMesh(ballRadius, 16,16);
            //MeshSceneNode t = smgr.AddSphereSceneNode(ballRadius, 32);
            //MeshSceneNode t = smgr.AddOctreeSceneNode(sphere);
            MeshSceneNode t = smgr.AddMeshSceneNode(smgr.GetMesh("pill.obj"));
            //MeshSceneNode t = smgr.AddMeshSceneNode(cyl);
            TriangleSelector triselect = smgr.CreateTriangleSelector(t.Mesh, t);

            t.TriangleSelector = triselect;
            triselect.Drop();
            //t = smgr.AddMeshSceneNode(smgr.GetMesh("../../media/sphere.x"));
            //smgr
            t.SetMaterialTexture(0, driver.GetTexture("rockwall.jpg"));
            //t.SetMaterialFlag(MaterialFlag.Lighting, true);
            t.GetMaterial(0).SpecularColor.Set(0, 0, 0);
            //t.GetMaterial(0).Lighting = true;
            t.GetMaterial(0).NormalizeNormals = false;

            /*Texture citrus = driver.AddTexture(new Dimension2Di(200, 200), "citrus.png");
             * gui.AddImage(citrus, new Vector2Di(824, 0), true);*/
            gui.AddStaticText("Hey, Listen! Press C to switch the mesh to a cylinder!\n Press S to change to a sphere, and enter to send yourself the obj file!", new Recti(0, 0, 400, 60));
            //t.AddShadowVolumeSceneNode();
            //           driver.GPUProgrammingServices.OnSetConstants += new GPUProgrammingServices.SetConstantsHandler(gpu_OnSetConstants);

            /*
             * MaterialType shaderMat = MaterialType.Solid;
             * shaderMat = driver.GPUProgrammingServices.AddHighLevelShaderMaterialFromFiles("C:/IrrlichtLime-1.4/examples/01.HelloWorld/bumpmap.hlsl", "VertexShaderFunction", VertexShaderType.VS_3_0,
             * "C:/IrrlichtLime-1.4/examples/01.HelloWorld/bumpmap.hlsl", "PixelShaderFunction", PixelShaderType.PS_3_0, MaterialType.Solid);
             *
             * t.SetMaterialType(shaderMat);
             * t.SetMaterialTexture(1, driver.GetTexture("../../media/rockwall_height.bmp"));*/

            GPUProgrammingServices gpu = driver.GPUProgrammingServices;
            MaterialType           newMaterialType1 = MaterialType.Solid;
            MaterialType           newMaterialType2 = MaterialType.TransparentAddColor;

            gpu.OnSetConstants += new GPUProgrammingServices.SetConstantsHandler(gpu_OnSetConstants);

            // create the shaders depending on if the user wanted high level or low level shaders

            newMaterialType1 = gpu.AddHighLevelShaderMaterialFromFiles(
                "d3d9.hlsl", "vertexMain", VertexShaderType.VS_1_1,
                "d3d9.hlsl", "pixelMain", PixelShaderType.PS_1_1,
                MaterialType.Solid, 0, GPUShadingLanguage.Default);
            t.SetMaterialType(newMaterialType1);
            //t.GetMaterial(0).Wireframe = true;
            //t.DebugDataVisible = DebugSceneType.Full;
            //t.AddShadowVolumeSceneNode(null, -1, false, 1000.0f);
            smgr.AddLightSceneNode(null, new Vector3Df(40, 150, -50), new Colorf(255, 255, 255, 255), 250.0f);
            //CSampleSceneNode sceneNode = new CSampleSceneNode(smgr.RootNode, smgr, 667);
            camera = smgr.AddCameraSceneNode(null, new Vector3Df(0, 50, -140), new Vector3Df(0, 5, 0));

            //camera.Target = new Vector3Df(-70, 30, -60);
            //smgr.AddCameraSceneNodeFPS(null, (float)50.0);
            Material m = new Material();

            m.Lighting = false;
            double PI        = 3.1415926f;
            float  distance  = 200.0f;
            double angle     = 180.0f;
            double angleY    = 20.0f;
            int    oldMouseX = mouseX;
            int    oldMouseY = mouseY;



            uint then          = device.Timer.Time;
            uint currentAutism = device.Timer.Time;
            bool autism        = false;

            while (device.Run())
            {
                uint  now            = device.Timer.Time;
                float frameDeltaTime = (float)(now - then) / 1000.0f;
                then = now;
                if (kinect.isTranslating && (kinect.translation.X < 30 && kinect.translation.X > -30))
                {
                    mfX -= (int)(kinect.translation.X);
                    mfY -= (int)(kinect.translation.Y);

                    Console.WriteLine(mouseX + ", " + mouseY + " ----------------- " + (int)(kinect.translation.X) + ", " + (int)(kinect.translation.Y));
                }

                kinect.resetTranslation();

                /*
                 * if (getDistance((int)mfX, (int)mfY, 512, 384) > 150)
                 * {
                 *  mfX = 512; mfY= 384;
                 * }*/


                mouseX = Math.Abs((int)mfX) % 1024;
                mouseY = Math.Abs((int)mfY) % 768;
                //mouseX = kinect.position.X;

                device.CursorControl.Position = new Vector2Di(mouseX, mouseY);

                if (!potterWheelDown && IsKeyDown(KeyCode.Up))
                {
                    potterWheelDown     = true;
                    deltaAngle          = 1.0d;
                    potterWheelActivate = !potterWheelActivate;
                }
                else if (!IsKeyDown(KeyCode.Up))
                {
                    potterWheelDown = false;
                }
                if (!leftKeyPressed && IsKeyDown(KeyCode.Left))
                {
                    leftKeyPressed = true;
                    deltaAngle    /= 2;
                }
                else if (!IsKeyDown(KeyCode.Left))
                {
                    leftKeyPressed = false;
                }
                if (!rightKeyPressed && IsKeyDown(KeyCode.Right))
                {
                    rightKeyPressed = true;
                    deltaAngle     *= 2;
                }
                else if (!IsKeyDown(KeyCode.Right))
                {
                    rightKeyPressed = false;
                }
                if (potterWheelActivate)
                {
                    angle -= 700.0f * deltaAngle * frameDeltaTime;
                }

                if (angle > 360)
                {
                    angle -= 360;
                }
                else if (angle < 0)
                {
                    angle += 360;
                }

                if (angleY > 360)
                {
                    angle -= 360;
                }
                else if (angleY < 0)
                {
                    angleY += 360;
                }
                driver.BeginScene(true, true, new Color(100, 101, 140));
                camera.Target = new Vector3Df(0, 0, 0);
                double temp = Math.Cos(angleY * PI / 180.0) * distance;
                double X    = Math.Sin(angle * PI / 180.0) * temp;
                double Y    = Math.Sin(angleY * PI / 180.0) * distance;
                double Z    = Math.Cos(angle * PI / 180.0) * temp;
                camera.Position = new Vector3Df((float)X, (float)Y, (float)Z);
                smgr.DrawAll();

                gui.DrawAll();
                driver.SetMaterial(m);
                Triangle3Df triangle = interpolateFrom2D(new Vector2Di(mouseX, mouseY));
                if (kinect.isMorphing && kinect.morphDist > 0)
                //if (IsKeyDown(KeyCode.KeyW))
                {
                    //Console.WriteLine("PRESSED KEY");
                    triangle.A *= new Vector3Df(0.5f);
                    triangle.B *= new Vector3Df(0.5f);
                    triangle.C *= new Vector3Df(0.5f);
                    if (isCyl)
                    {
                        deformCyl(t, triangle.A, new Vector3Df(.5f / (potterWheelActivate ? (float)(1 / deltaAngle) : 60f)), triangle);
                    }
                    else
                    {
                        deformMesh(t, triangle.A, new Vector3Df(.5f / (potterWheelActivate ? (float)(1 / deltaAngle) : 60f)), triangle);
                    }
                }
                else if (kinect.isMorphing && kinect.morphDist < 0)
                {
                    //Console.WriteLine("PRESSED KEY");
                    triangle.A *= new Vector3Df(1.5f);
                    triangle.B *= new Vector3Df(1.5f);
                    triangle.C *= new Vector3Df(1.5f);
                    if (isCyl)
                    {
                        deformCyl(t, triangle.A, new Vector3Df(-.5f / (potterWheelActivate ? (float)(1 / deltaAngle) : 60f)), triangle);
                    }
                    else
                    {
                        deformMesh(t, triangle.A, new Vector3Df(-.5f / (potterWheelActivate ? (float)(1 / deltaAngle) : 60f)), triangle);
                    }
                }
                if (kinect.isZoom && kinect.zoomDist < 0)
                {
                    if (distance < 300.0f)
                    {
                        distance += .0625f;
                    }
                }
                if (kinect.isZoom && kinect.zoomDist > 0)
                {
                    if (distance > 150)
                    {
                        distance -= .0625f;
                    }
                }
                if (kinect.isRotating && kinect.rotation > 0)
                {
                    angle += 200 * frameDeltaTime;
                }
                if (kinect.isRotating && kinect.rotation < 0)
                {
                    angle -= 200 * frameDeltaTime;
                }

                //Change shape

                if (IsKeyDown(KeyCode.KeyA))
                {
                    IrrlichtLime.IO.WriteFile file = device.FileSystem.CreateWriteFile("./Saved.obj");
                    writeMesh(file, t.Mesh, 1);

                    mail();
                }
                if (IsKeyDown(KeyCode.KeyC))
                {
                    isCyl = true;
                    t.Remove();
                    t = smgr.AddMeshSceneNode(smgr.GetMesh("pill.obj"));
                    //MeshSceneNode t = smgr.AddMeshSceneNode(cyl);
                    triselect          = smgr.CreateTriangleSelector(t.Mesh, t);
                    t.TriangleSelector = triselect;
                    triselect.Drop();
                    //t = smgr.AddMeshSceneNode(smgr.GetMesh("../../media/sphere.x"));
                    //smgr
                    t.SetMaterialTexture(0, driver.GetTexture("rockwall.jpg"));
                    //t.SetMaterialFlag(MaterialFlag.Lighting, true);
                    t.GetMaterial(0).SpecularColor.Set(0, 0, 0);
                    //t.GetMaterial(0).Lighting = true;
                    t.GetMaterial(0).NormalizeNormals = false;
                    t.SetMaterialType(newMaterialType1);
                }
                else if (IsKeyDown(KeyCode.KeyS))
                {
                    isCyl = false;
                    t.Remove();
                    t                  = smgr.AddSphereSceneNode(ballRadius, 32);
                    triselect          = smgr.CreateTriangleSelector(t.Mesh, t);
                    t.TriangleSelector = triselect;
                    triselect.Drop();
                    //t = smgr.AddMeshSceneNode(smgr.GetMesh("../../media/sphere.x"));
                    //smgr
                    t.SetMaterialTexture(0, driver.GetTexture("rockwall.jpg"));
                    //t.SetMaterialFlag(MaterialFlag.Lighting, true);
                    t.GetMaterial(0).SpecularColor.Set(0, 0, 0);
                    //t.GetMaterial(0).Lighting = true;
                    t.GetMaterial(0).NormalizeNormals = false;
                    t.SetMaterialType(newMaterialType1);
                }
                driver.EndScene();
            }

            device.Drop();
        }
示例#22
0
        static void Main()
        {
            device          = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(1024, 768), 32, false, true);
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.SetWindowCaption("Minesweeper - Irrlicht Engine");

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

            device.FileSystem.AddFileArchive("../../media/minesweeper.media.files");
            game = new Game(device);

            // set up camera

            camera = scene.AddCameraSceneNode();             // Maya(null, -500, 50, 200);
            setupCameraPositionAndTarget();

            // set up background

            Mesh m = scene.GetMesh("back.obj");

            scene.MeshManipulator.Scale(m, new Vector3Df(80));
            scene.MeshManipulator.FlipSurfaces(m);
            scene.MeshManipulator.RecalculateNormals(m);
            scene.MeshManipulator.SetVertexColors(m, new Color(80, 80, 80));

            Material t = new Material();

            t.Type     = MaterialType.Reflection2Layer;
            t.Lighting = false;
            t.SetTexture(0, device.VideoDriver.GetTexture("TEXTURE-ref.jpg"));
            t.SetTexture(1, device.VideoDriver.GetTexture("TEXTURE-ref.jpg"));

            MeshSceneNode n = scene.AddMeshSceneNode(m, null, 7777);

            n.SetMaterial(0, t);
            n.Position = game.CenterOfTheBoard;

            SceneNodeAnimator a = scene.CreateRotationAnimator(new Vector3Df(0.07f, 0.01f, 0.05f));

            n.AddAnimator(a);
            a.Drop();

            // set up light

            light = scene.AddLightSceneNode(null, game.CenterOfTheBoard, new Colorf(1, 1, 1), 200);

            m = scene.AddVolumeLightMesh("lvol1", 32, 32, new Color(5, 5, 5));
            scene.MeshManipulator.Scale(m, new Vector3Df(15, 30, 15));
            n          = scene.AddMeshSceneNode(m, light);
            n.Position = new Vector3Df(0, -10, 0);
            n.Rotation = new Vector3Df(180, 0, 0);
            n.SetMaterialType(MaterialType.TransparentAddColor);

            m = scene.AddVolumeLightMesh("lvol2", 32, 32, new Color(5, 5, 5));
            scene.MeshManipulator.Scale(m, new Vector3Df(15, 30, 15));
            n          = scene.AddMeshSceneNode(m, light);
            n.Position = new Vector3Df(0, -10, 0);
            n.SetMaterialType(MaterialType.TransparentAddColor);

            // add gui hint

            text = gui.AddStaticText(TextStart, new Recti(10, 10, 200, 40));
            text.OverrideColor = Color.SolidYellow;

            // main loop

            while (device.Run())
            {
                driver.BeginScene();
                scene.DrawAll();
                gui.DrawAll();

                if (optionFPS)
                {
                    gui.BuiltInFont.Draw(driver.FPS + " FPS", driver.ScreenSize.Width - 50, 10, Color.SolidWhite);
                }

                driver.EndScene();
            }

            device.Drop();
        }
示例#23
0
        /// <summary>
        /// The irrlicht thread for rendering.
        /// </summary>
        private void StartIrr()
        {
            try
            {
                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.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 animText = "";
                if (Animations.AnimationNames.Count > 0)
                {
                    animText = "Animation: " + Animations.AnimationNames[selectedAnimIdx].Key;
                }
                var mAnimText     = gui.AddStaticText(animText, new Recti(0, this.ClientSize.Height - 80, 100, this.ClientSize.Height - 70));
                var mPositionText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 70, 100, this.ClientSize.Height - 60));
                var mRotationText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 60, 100, this.ClientSize.Height - 50));
                var fpsText       = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 50, 100, this.ClientSize.Height - 40));
                var infoText      = gui.AddStaticText("[Space] - Reset\n[LMouse] - Rotate\n[MMouse] - Move\n[Wheel] - Zoom", new Recti(0, this.ClientSize.Height - 40, 100, this.ClientSize.Height));
                mAnimText.OverrideColor   = mPositionText.OverrideColor = mRotationText.OverrideColor = fpsText.OverrideColor = infoText.OverrideColor = new Color(255, 255, 255);
                mAnimText.BackgroundColor = mPositionText.BackgroundColor = mRotationText.BackgroundColor = fpsText.BackgroundColor = infoText.BackgroundColor = new Color(0, 0, 0);

                SkinnedMesh skinnedMesh = smgr.CreateSkinnedMesh();
                foreach (var meshBuffer in cdata.staticMesh.MeshBuffers)
                {
                    skinnedMesh.AddMeshBuffer(meshBuffer);
                }
                smgr.MeshManipulator.RecalculateNormals(skinnedMesh);
                if (RigFile != null)
                {
                    rig.Apply(skinnedMesh);
                    if (AnimFile != null)
                    {
                        anims.Apply(skinnedMesh);
                    }
                }
                skinnedMesh.SetDirty(HardwareBufferType.VertexAndIndex);
                skinnedMesh.FinalizeMeshPopulation();
                AnimatedMeshSceneNode node = smgr.AddAnimatedMeshSceneNode(skinnedMesh);

                if (node == null)
                {
                    throw new Exception("Could not load file!");
                }

                node.Scale = new Vector3Df(3.0f);
                node.SetMaterialFlag(MaterialFlag.Lighting, false);
                SetMaterials(driver, node);

                CameraSceneNode camera = smgr.AddCameraSceneNode(null, new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0), new Vector3Df(0, node.BoundingBox.Radius, 0));
                camera.NearValue = 0.001f;
                camera.FOV       = 45 * CommonData.PI_OVER_180;
                scaleMul         = node.BoundingBox.Radius / 4;

                var viewPort = driver.ViewPort;
                var lineMat  = new Material();
                lineMat.Lighting = false;

                while (device.Run())
                {
                    driver.ViewPort = viewPort;
                    driver.BeginScene(ClearBufferFlag.All, new Color(100, 101, 140));

                    node.Position         = modelPosition;
                    node.Rotation         = modelAngle;
                    node.DebugDataVisible = DebugSceneType.Skeleton | DebugSceneType.BBox;
                    mPositionText.Text    = $"X: {modelPosition.X.ToString("F2")} Y: {modelPosition.Y.ToString("F2")} Z: {modelPosition.Z.ToString("F2")}";
                    mRotationText.Text    = $"Yaw: {modelAngle.Y.ToString("F2")} Roll: {modelAngle.Z.ToString("F2")}";
                    fpsText.Text          = $"FPS: {driver.FPS}";

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

                    driver.ViewPort = new Recti(this.ClientSize.Width - 100, this.ClientSize.Height - 80, this.ClientSize.Width, this.ClientSize.Height);
                    //driver.ClearBuffers(ClearBufferFlag.None);

                    driver.SetMaterial(lineMat);
                    var matrix = new Matrix(new Vector3Df(0, 0, 0), modelAngle);
                    driver.SetTransform(TransformationState.World, matrix);
                    matrix = matrix.BuildProjectionMatrixOrthoLH(100, 80, camera.NearValue, camera.FarValue);
                    driver.SetTransform(TransformationState.Projection, matrix);
                    matrix = matrix.BuildCameraLookAtMatrixLH(new Vector3Df(50, 0, 0), new Vector3Df(0, 0, 0), new Vector3Df(0, 1f, 0));
                    driver.SetTransform(TransformationState.View, matrix);
                    driver.Draw3DLine(0, 0, 0, 30f, 0, 0, Color.OpaqueGreen);
                    driver.Draw3DLine(0, 0, 0, 0, 30f, 0, Color.OpaqueBlue);
                    driver.Draw3DLine(0, 0, 0, 0, 0, 30f, Color.OpaqueRed);

                    driver.EndScene();
                }

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