Exemplo n.º 1
0
        CollisionShape bulletGetCollisionShape(Shape shape, SceneNode node)
        {
            switch (shape)
            {
            case Shape.Box:
            {
                return(new BoxShape(node.BoundingBox.Extent.X / 2));
            }

            case Shape.Shpere:
            {
                return(new SphereShape(node.BoundingBox.Extent.X / 2));
            }

            case Shape.Mesh:
            {
                MeshSceneNode meshNode = node as MeshSceneNode;
                if (meshNode == null)
                {
                    throw new ArgumentException();
                }

                TriangleMesh triangleMesh = new TriangleMesh();
                for (int i = 0; i < meshNode.Mesh.MeshBufferCount; i++)
                {
                    MeshBuffer         b     = meshNode.Mesh.GetMeshBuffer(i);
                    ushort[]           inds  = b.Indices as ushort[];
                    Vertex3DTTCoords[] verts = b.Vertices as Vertex3DTTCoords[];

                    if (inds == null || verts == null)
                    {
                        throw new ArgumentException();
                    }

                    for (int j = 0; j < inds.Length; j += 3)
                    {
                        Vector3Df v0 = verts[inds[j + 0]].Position;
                        Vector3Df v1 = verts[inds[j + 1]].Position;
                        Vector3Df v2 = verts[inds[j + 2]].Position;

                        triangleMesh.AddTriangle(
                            new Vector3(v0.X, v0.Y, v0.Z),
                            new Vector3(v1.X, v1.Y, v1.Z),
                            new Vector3(v2.X, v2.Y, v2.Z));
                    }
                }

                return(new BvhTriangleMeshShape(triangleMesh, false));
            }

            default:
                throw new ArgumentException();
            }
        }
        public void Initialize()
        {
            Camera cam = Engine.Instance.SceneManager.AddCamera(new vector3df(0, 5, -10), new vector3df(0, 0, 0), new vector3df(0, 1, 0), 0.5f, 2400.0f, (float)Math.PI / 4.0f);

            Engine.Instance.ManualMeshServices.AddGridMesh("$grid10", 10, 1, new SColor(128, 128, 128));

            gridSceneNode = Engine.Instance.SceneManager.AddMeshSceneNode("$grid10", null);

            coordSceneNode = Engine.Instance.SceneManager.AddCoordSceneNode();
            coordSceneNode.SetPosition2D(E_POSITION_2D.EP2D_BOTTOMLEFT, 18);
            coordSceneNode.SetAxisText("x", "y", "z");
        }
Exemplo n.º 3
0
        static void Main()
        {
            device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(800, 600));
            device.SetWindowCaption("Sphere Camera - Irrlicht Engine");
            driver = device.VideoDriver;
            scene  = device.SceneManager;

            sphere = scene.AddSphereSceneNode(5, 100);
            sphere.SetMaterialTexture(0, driver.GetTexture("../../media/earth.jpg"));
            sphere.TriangleSelector = scene.CreateTriangleSelector(sphere.Mesh, sphere);
            sphere.TriangleSelector.Drop();

            scene.AmbientLight = new Colorf(0.2f, 0.2f, 0.2f);
            LightSceneNode light = scene.AddLightSceneNode();

            light.Position = new Vector3Df(-10, 10, -10);

            camera             = new SphereCamera(device, new Vector3Df(0), 8, 20, 10, 0, 0);
            camera.Inclination = 200;

            path = new SpherePath(5.4f);

            GUIFont font = device.GUIEnvironment.BuiltInFont;

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.PostEvent(new Event('r', KeyCode.KeyR, true));             // pretend user pressed [R]

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

                scene.DrawAll();

                path.Draw(driver);

                font.Draw("Press [Arrows], [LMB] and [Mouse Scroll] to change view", 10, 10, Color.SolidYellow);
                font.Draw("Press [RMB] on Earth to place new path point", 10, 20, Color.SolidYellow);
                font.Draw("Press [R] to reload path data from file", 10, 30, Color.SolidYellow);
                font.Draw("Press [C] to clean up", 10, 40, Color.SolidYellow);

                font.Draw(driver.FPS.ToString() + " fps", 10, driver.ScreenSize.Height - 40, Color.SolidYellow);
                font.Draw(path.PointCount.ToString() + " point(s)", 10, driver.ScreenSize.Height - 30, Color.SolidYellow);
                font.Draw(camera.ToString(), 10, driver.ScreenSize.Height - 20, Color.SolidYellow);

                driver.EndScene();
                device.Yield();
            }

            path.Drop();
            device.Drop();
        }
Exemplo n.º 4
0
        static bool device_OnEvent(Event evnt)
        {
            if (evnt.Type == EventType.Key &&
                evnt.Key.PressedDown)
            {
                switch (evnt.Key.Key)
                {
                case KeyCode.Space:
                    simPaused = !simPaused;
                    return(true);

                case KeyCode.KeyT:
                    useTrails = !useTrails;
                    return(true);
                }
            }

            if (evnt.Type == EventType.Mouse)
            {
                if (evnt.Mouse.IsLeftPressed())
                {
                    if (!mouseCanShoot)
                    {
                        return(true);
                    }

                    MeshSceneNode n = device.SceneManager.AddSphereSceneNode(sphereRadius);
                    n.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../media/wall.bmp"));
                    n.SetMaterialFlag(MaterialFlag.Lighting, false);

                    Vector3Df v = (device.SceneManager.ActiveCamera.Target - device.SceneManager.ActiveCamera.Position).Normalize();
                    n.Position = device.SceneManager.ActiveCamera.Position + v * 100;

                    if (useTrails)
                    {
                        particles.Add(n, device.Timer.Time);
                    }

                    physics.AddShape(Physics.Shape.Shpere, n, sphereMass, false, v * cubeMass * 10000);

                    mouseCanShoot = false;
                    return(true);
                }
                else
                {
                    mouseCanShoot = true;
                }
            }

            return(false);
        }
Exemplo n.º 5
0
		static void Main(string[] args)
		{
			device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(800, 600));
			device.SetWindowCaption("Sphere Camera - Irrlicht Engine");
			driver = device.VideoDriver;
			scene = device.SceneManager;

			sphere = scene.AddSphereSceneNode(5, 100);
			sphere.SetMaterialTexture(0, driver.GetTexture("../../media/earth.jpg"));
			sphere.TriangleSelector = scene.CreateTriangleSelector(sphere.Mesh, sphere);
			sphere.TriangleSelector.Drop();

			scene.AmbientLight = new Colorf(0.2f, 0.2f, 0.2f);
			LightSceneNode light = scene.AddLightSceneNode();
			light.Position = new Vector3Df(-10, 10, -10);

			camera = new SphereCamera(device, new Vector3Df(0), 8, 20, 10, 0, 0);
			camera.Inclination = 200;

			path = new SpherePath(5.4f);

			GUIFont font = device.GUIEnvironment.BuiltInFont;
			device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
			device.PostEvent(new Event('r', KeyCode.KeyR, true)); // pretend user pressed [R]

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

				scene.DrawAll();

				path.Draw(driver);

				font.Draw("Press [Arrows], [LMB] and [Mouse Scroll] to change view", 10, 10, Color.OpaqueYellow);
				font.Draw("Press [RMB] on Earth to place new path point", 10, 20, Color.OpaqueYellow);
				font.Draw("Press [R] to reload path data from file", 10, 30, Color.OpaqueYellow);
				font.Draw("Press [C] to clean up", 10, 40, Color.OpaqueYellow);

				font.Draw(driver.FPS.ToString() + " fps", 10, driver.ScreenSize.Height - 40, Color.OpaqueYellow);
				font.Draw(path.PointCount.ToString() + " point(s)", 10, driver.ScreenSize.Height - 30, Color.OpaqueYellow);
				font.Draw(camera.ToString(), 10, driver.ScreenSize.Height - 20, Color.OpaqueYellow);

				driver.EndScene();
			}

			path.Drop();
			device.Drop();
		}
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(1024, 600));
            device.SetWindowCaption("LightningShots - Irrlicht Engine");
            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");

            AnimatedMesh  mesh = smgr.GetMesh("20kdm2.bsp");
            MeshSceneNode node = smgr.AddMeshSceneNode(mesh.GetMesh(0));

            node.Position = new Vector3Df(-1300, -144, -1249);

            node.SetMaterialType(MaterialType.LightMapLightingM4);
            node.SetMaterialFlag(MaterialFlag.Lighting, true);

            node.TriangleSelector = smgr.CreateTriangleSelector(node.Mesh, node);
            node.TriangleSelector.Drop();

            smgr.AmbientLight = new Colorf(0.15f, 0.14f, 0.13f);

            CameraSceneNode camera = smgr.AddCameraSceneNodeFPS();

            lightningShot   = new LightningShot(smgr, node.TriangleSelector);
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.CursorControl.Visible = false;

            while (device.Run())
            {
                driver.BeginScene(true, true, new Color(100, 80, 75));

                smgr.DrawAll();

                lightningShot.Draw(device.Timer.Time);

                GUIFont f = device.GUIEnvironment.BuiltInFont;
                f.Draw("Use [LMB] to shoot", 10, 10, Color.OpaqueYellow);
                f.Draw("Total lightnings: " + lightningShot.TotalLightnings, 10, 20, Color.OpaqueWhite);
                f.Draw("Total shots: " + lightningShot.TotalShots, 10, 30, Color.OpaqueWhite);
                f.Draw(driver.FPS + " fps", 10, 40, Color.OpaqueWhite);

                driver.EndScene();
            }

            lightningShot.Drop();
            device.Drop();
        }
Exemplo n.º 7
0
        static void openFolder(string newFolder)
        {
            textureManager.Stop();
            textureManager.Start(TextureManagerThreadCount);
            textureManager.EnqueueUnloadingOfAllLoadedTextures();
            animationManager.Clear();
            previewPlateInfo.Clear();

            irr.GUI.RootElement.GetElementFromID(CurrentFolderStaticTextId).Text = newFolder;

            SceneNode p = irr.Scene.GetSceneNodeFromID(PreviewRootNodeId);

            p.RemoveChildren();

            int   r = 10;
            float x = 0, z = 0;
            Mesh  m = irr.Scene.MeshCache.GetMesh(PreviewPlateMeshName);

            string[] f = Directory.GetFiles(newFolder, "*.*", SearchOption.TopDirectoryOnly);
            for (int i = 0; i < f.Length; i++)
            {
                x += PreviewPlateSize * 1.1f;
                if ((i % r) == 0)
                {
                    x  = 0;
                    z += PreviewPlateSize * 1.1f;
                }

                MeshSceneNode n = irr.Scene.AddMeshSceneNode(m, p, i | PreviewPlateNodeIdFlag);
                n.SetMaterialFlag(MaterialFlag.Lighting, false);
                n.Position = new Vector3Df(x, 1000, z);

                textureManager.LoadTexture(n, f[i], PreviewTextureSize);

                TriangleSelector s = irr.Scene.CreateTriangleSelector(n.Mesh, n);
                n.TriangleSelector = s;
                s.Drop();

                previewPlateInfo.Add(n.ID, Path.GetFileName(f[i]));
            }

            irr.Scene.ActiveCamera.Position = new Vector3Df(PreviewPlateSize * (r - 1) * 1.1f / 2, 6 * PreviewPlateSize, 0);
            irr.Scene.ActiveCamera.Target   = new Vector3Df(irr.Scene.ActiveCamera.Position.X, 0, PreviewPlateSize * 5);
            maxScrollPosition = (f.Length / r) * PreviewPlateSize * 1.1f;

            tasksAddedToTextureManager = textureManager.GetCommandQueueLength();
        }
Exemplo n.º 8
0
        public void Initialize()
        {
            Engine.Instance.ManualMeshServices.AddGridMesh("$grid20", 20, 1, new SColor(128, 128, 128));

            gridSceneNode = Engine.Instance.SceneManager.AddMeshSceneNode("$grid20", null);

            coordSceneNode = Engine.Instance.SceneManager.AddCoordSceneNode();
            coordSceneNode.SetPosition2D(E_POSITION_2D.EP2D_BOTTOMLEFT, 18);
            coordSceneNode.SetAxisText("x", "y", "z");

            lightCoordSceneNode         = Engine.Instance.SceneManager.AddCoordSceneNode();
            lightCoordSceneNode.Visible = false;
            lightCoordSceneNode.SetPosition2D(E_POSITION_2D.EP2D_TOPCENTER, 18);
            lightCoordSceneNode.SetAxisVisible(false, false, true);
            lightCoordSceneNode.SetAxisColor(new SColor(), new SColor(), new SColor(255, 255, 255));
            lightCoordSceneNode.SetAxisText("", "", "light");
            lightCoordSceneNode.SetAxisDir(E_AXIS.ESA_Z, Engine.Instance.SceneEnvironment.LightDir);
        }
Exemplo n.º 9
0
        public void deformCyl(MeshSceneNode t, Vector3Df position, Vector3Df direction, Triangle3Df triangle)
        {
            //get the closest vector to this point
            //USE BRUTE FORCE FOR RIGHT NOW

            Vertex3D[]       v   = (Vertex3D[])t.Mesh.MeshBuffers[0].Vertices;
            TriangleSelector tri = device.SceneManager.CreateTriangleSelector(t.Mesh, t);

            t.TriangleSelector = tri;
            tri.Drop();
            int size = t.Mesh.MeshBuffers[0].VertexCount;


            int min = 0;

            float minDist = v[0].Position.GetDistanceFromSQ(position);

            for (int i = 1; i < size; i++)
            {
                //nsole.WriteLine(v[i].Position.SphericalCoordinateAngles.X);
                //query verts

                float currDist = v[i].Position.GetDistanceFromSQ(position);
                // float currDist = v[i].TCoords - position;
                if (currDist < minDist)
                {
                    min     = i;
                    minDist = currDist;
                }
            }
            //int radius = 2;
            //for (; radius > 0; radius--)
            //{// this should give a staircase like effect
            //v[min - radius].Position = new Vector3Df(v[min - radius].Position + v[min - radius].Normal * direction);
            if ((v[min].Position.X * v[min].Position.X + v[min].Position.Z * v[min].Position.Z) > 100 || direction.X > 0)
            {
                Console.WriteLine("Min = " + min);
                v[min].Position = new Vector3Df(v[min].Position + v[min].Normal * 2 * direction);
                //}
                t.Mesh.MeshBuffers[0].UpdateVertices(v, 0);
                t.Mesh.MeshBuffers[0].SetDirty(HardwareBufferType.VertexAndIndex);
            }
            //device.SceneManager.MeshManipulator.RecalculateNormals(t.Mesh);
        }
Exemplo n.º 10
0
        public void Initialize()
        {
            //var light = Scene.AddLightSceneNode(Scene.RootNode,new Vector3Df(2, 6, 3), new Colorf(200, 200, 180), 20);
            var light = Scene.AddLightSceneNode(null, new Vector3Df(-30, 35, -25));

            light.Radius      = 25;
            light.CastShadows = true;
            light.LightType   = LightType.Point;

            var sun = Scene.AddLightSceneNode(null, new Vector3Df(40, 100, 40));

            sun.Radius      = 50;
            sun.CastShadows = true;
            sun.LightType   = LightType.Point;


            sphere       = Scene.AddAnimatedMeshSceneNode(Scene.AddSphereMesh("sphere", 10f));
            sphere.Scale = new Vector3Df(1);
            sphere.SetMaterialFlag(MaterialFlag.Lighting, true);
            sphere.Position = new Vector3Df(1, 11, 1);
            //sphere.SetMaterialTexture(0, Driver.GetTexture("Mars.jpg"));
            sphere.SetMaterialTexture(0, GeneratePlanetTexture(new Vector2Dd(300, 300)));
            Scene.MeshManipulator.SetVertexColors(sphere.Mesh, new Color(200, 200, 200));

            var terrain =
                Scene.AddAnimatedMeshSceneNode(Scene.AddHillPlaneMesh("terrain", new Dimension2Df(1, 1),
                                                                      new Dimension2Di(128, 128),
                                                                      new Material(), 0));

            terrain.Position = new Vector3Df(0, 0, 0);
            terrain.SetMaterialFlag(MaterialFlag.Lighting, true);
            Scene.MeshManipulator.SetVertexColors(terrain.Mesh, new Color(220, 220, 220));
            selector = Scene.CreateOctreeTriangleSelector(terrain.Mesh, terrain, 128);
            terrain.TriangleSelector = selector;
            Scene.CreateCollisionResponseAnimator(selector, terrain);

            _cam = new Camera(this);

            selectionCube = Scene.AddCubeSceneNode(10, null, -1);
            selectionCube.SetMaterialFlag(MaterialFlag.Wireframe, true);
        }
Exemplo n.º 11
0
        private void ExportNode(RenderTreeNode node, string exportMeshDirectory, string modelExtension, string texExtension, bool transformToWorld, string instanceName)
        {
            string meshNameOnly = Path.GetFileNameWithoutExtension(node.FullPath);
            string filename     = exportMeshDirectory + "\\" + meshNameOnly + instanceName + modelExtension;

            // export textures too!
            if (node.MeshNode.GetType().Equals(typeof(MeshSceneNode)))
            {
                MeshSceneNode meshNode = (MeshSceneNode)node.MeshNode;
                foreach (var mb in meshNode.Mesh.MeshBuffers)
                {
                    if (mb.Material.GetTexture(0) != null)
                    {
                        string tname = mb.Material.GetTexture(0).Name.ToString();
                        tname = tname.Replace(".xbm", texExtension);
                        tname = exportMeshDirectory + "\\" + Path.GetFileName(tname);

                        ExportTexture(tname, mb.Material.GetTexture(0));
                    }

                    if (mb.Material.GetTexture(1) != null)
                    {
                        string tname = mb.Material.GetTexture(1).Name.ToString();
                        tname = tname.Replace(".xbm", texExtension);
                        tname = exportMeshDirectory + "\\" + Path.GetFileName(tname);

                        ExportTexture(tname, mb.Material.GetTexture(1));
                    }
                }
            }

            if (modelExtension == ".obj")
            {
                var mw = smgr.CreateMeshWriter(MeshWriterType.Obj);
                if (transformToWorld)
                {
                    Matrix localToWorld = new Matrix(node.MeshNode.Position, node.MeshNode.Rotation);
                    mw.SetTransform(localToWorld);
                }
                mw.SetImageType(texExtension);
                if (node.MeshNode.GetType().Equals(typeof(MeshSceneNode)))
                {
                    mw.WriteMesh(device.FileSystem.CreateWriteFile(filename), ((MeshSceneNode)(node.MeshNode)).Mesh, MeshWriterFlag.None);
                }
                else
                {
                    mw.WriteMesh(device.FileSystem.CreateWriteFile(filename), ((TerrainSceneNodeWolvenKit)(node.MeshNode)).Mesh, MeshWriterFlag.None);
                }
                mw.Drop();
            }
            else if (modelExtension == ".fbx")
            {
                var mw = smgr.CreateMeshWriter(MeshWriterType.Fbx);
                if (transformToWorld)
                {
                    Matrix localToWorld = new Matrix(node.MeshNode.Position, node.MeshNode.Rotation);
                    mw.SetTransform(localToWorld);
                }
                mw.SetImageType(texExtension);
                if (node.MeshNode.GetType().Equals(typeof(MeshSceneNode)))
                {
                    mw.WriteMesh(device.FileSystem.CreateWriteFile(filename), ((MeshSceneNode)(node.MeshNode)).Mesh, MeshWriterFlag.None);
                }
                //else
                //    mw.WriteMesh(device.FileSystem.CreateWriteFile(filename), ((TerrainSceneNodeWolvenKit)(node.MeshNode)).Mesh, MeshWriterFlag.None);
                mw.Drop();
            }
        }
Exemplo n.º 12
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;

            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");

            AnimatedMesh  q3levelmesh = smgr.GetMesh("20kdm2.bsp");
            MeshSceneNode q3node      = null;

            // The Quake mesh is pickable, but doesn't get highlighted.
            if (q3levelmesh != null)
            {
                q3node = smgr.AddOctreeSceneNode(q3levelmesh.GetMesh(0), null, IDFlag_IsPickable);
            }

            TriangleSelector selector = null;

            if (q3node != null)
            {
                q3node.Position         = new Vector3Df(-1350, -130, -1400);
                selector                = smgr.CreateOctreeTriangleSelector(q3node.Mesh, q3node, 128);
                q3node.TriangleSelector = selector;
                // We're not done with this selector yet, so don't drop it.
            }

            // Set a jump speed of 3 units per second, which gives a fairly realistic jump
            // when used with the gravity of (0, -1000, 0) in the collision response animator.
            CameraSceneNode camera = smgr.AddCameraSceneNodeFPS(null, 100.0f, 0.3f, ID_IsNotPickable, null, true, 3.0f);

            camera.Position = new Vector3Df(50, 50, -60);
            camera.Target   = new Vector3Df(-70, 30, -60);

            if (selector != null)
            {
                SceneNodeAnimator anim = smgr.CreateCollisionResponseAnimator(
                    selector,
                    camera,
                    new Vector3Df(30, 50, 30),
                    new Vector3Df(0, -1000, 0),
                    new Vector3Df(0, 30, 0));

                selector.Drop();             // As soon as we're done with the selector, drop it.
                camera.AddAnimator(anim);
                anim.Drop();                 // And likewise, drop the animator when we're done referring to it.
            }

            // Now I create three animated characters which we can pick, a dynamic light for
            // lighting them, and a billboard for drawing where we found an intersection.

            // First, let's get rid of the mouse cursor. We'll use a billboard to show what we're looking at.
            device.CursorControl.Visible = false;

            // Add the billboard.
            BillboardSceneNode bill = smgr.AddBillboardSceneNode();

            bill.SetMaterialType(MaterialType.TransparentAddColor);
            bill.SetMaterialTexture(0, driver.GetTexture("../../media/particle.bmp"));
            bill.SetMaterialFlag(MaterialFlag.Lighting, false);
            bill.SetMaterialFlag(MaterialFlag.ZBuffer, false);
            bill.SetSize(20, 20, 20);
            bill.ID = ID_IsNotPickable;             // This ensures that we don't accidentally ray-pick it

            AnimatedMeshSceneNode node = null;

            // Add an MD2 node, which uses vertex-based animation.
            node          = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/faerie.md2"), null, IDFlag_IsPickable | IDFlag_IsHighlightable);
            node.Position = new Vector3Df(-90, -15, -140); // Put its feet on the floor.
            node.Scale    = new Vector3Df(1.6f);           // Make it appear realistically scaled
            node.SetMD2Animation(AnimationTypeMD2.Point);
            node.AnimationSpeed = 20.0f;
            node.GetMaterial(0).SetTexture(0, driver.GetTexture("../../media/faerie2.bmp"));
            node.GetMaterial(0).Lighting         = true;
            node.GetMaterial(0).NormalizeNormals = true;

            // Now create a triangle selector for it.  The selector will know that it
            // is associated with an animated node, and will update itself as necessary.
            selector = smgr.CreateTriangleSelector(node);
            node.TriangleSelector = selector;
            selector.Drop();             // We're done with this selector, so drop it now.

            // And this B3D file uses skinned skeletal animation.
            node                = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/ninja.b3d"), null, IDFlag_IsPickable | IDFlag_IsHighlightable);
            node.Scale          = new Vector3Df(10);
            node.Position       = new Vector3Df(-75, -66, -80);
            node.Rotation       = new Vector3Df(0, 90, 0);
            node.AnimationSpeed = 8.0f;
            node.GetMaterial(0).NormalizeNormals = true;
            // Just do the same as we did above.
            selector = smgr.CreateTriangleSelector(node);
            node.TriangleSelector = selector;
            selector.Drop();

            // This X files uses skeletal animation, but without skinning.
            node                  = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/dwarf.x"), null, IDFlag_IsPickable | IDFlag_IsHighlightable);
            node.Position         = new Vector3Df(-70, -66, -30); // Put its feet on the floor.
            node.Rotation         = new Vector3Df(0, -90, 0);     // And turn it towards the camera.
            node.AnimationSpeed   = 20.0f;
            selector              = smgr.CreateTriangleSelector(node);
            node.TriangleSelector = selector;
            selector.Drop();

            // And this mdl file uses skinned skeletal animation.
            node          = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/yodan.mdl"), null, IDFlag_IsPickable | IDFlag_IsHighlightable);
            node.Position = new Vector3Df(-90, -25, 20);
            node.Scale    = new Vector3Df(0.8f);
            node.GetMaterial(0).Lighting = true;
            node.AnimationSpeed          = 20.0f;

            // Just do the same as we did above.
            selector = smgr.CreateTriangleSelector(node);
            node.TriangleSelector = selector;
            selector.Drop();

            // Add a light, so that the unselected nodes aren't completely dark.
            LightSceneNode light = smgr.AddLightSceneNode(null, new Vector3Df(-60, 100, 400), new Colorf(1.0f, 1.0f, 1.0f), 600.0f);

            light.ID = ID_IsNotPickable;             // Make it an invalid target for selection.

            // Remember which scene node is highlighted
            SceneNode             highlightedSceneNode = null;
            SceneCollisionManager collMan = smgr.SceneCollisionManager;
            int lastFPS = -1;

            // draw the selection triangle only as wireframe
            Material material = new Material();

            material.Lighting  = false;
            material.Wireframe = true;

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

                    // Unlight any currently highlighted scene node
                    if (highlightedSceneNode != null)
                    {
                        highlightedSceneNode.SetMaterialFlag(MaterialFlag.Lighting, true);
                        highlightedSceneNode = null;
                    }

                    // All intersections in this example are done with a ray cast out from the camera to
                    // a distance of 1000.  You can easily modify this to check (e.g.) a bullet
                    // trajectory or a sword's position, or create a ray from a mouse click position using
                    // collMan.GetRayFromScreenCoordinates()
                    Line3Df ray = new Line3Df();
                    ray.Start = camera.Position;
                    ray.End   = ray.Start + (camera.Target - ray.Start).Normalize() * 1000.0f;

                    // This call is all you need to perform ray/triangle collision on every scene node
                    // that has a triangle selector, including the Quake level mesh.  It finds the nearest
                    // collision point/triangle, and returns the scene node containing that point.
                    // Irrlicht provides other types of selection, including ray/triangle selector,
                    // ray/box and ellipse/triangle selector, plus associated helpers.
                    // See the methods of ISceneCollisionManager
                    SceneNode selectedSceneNode =
                        collMan.GetSceneNodeAndCollisionPointFromRay(
                            ray,
                            out Vector3Df intersection,             // This will be the position of the collision
                            out Triangle3Df hitTriangle,            // This will be the triangle hit in the collision
                            IDFlag_IsPickable);                     // This ensures that only nodes that we have set up to be pickable are considered

                    // If the ray hit anything, move the billboard to the collision position
                    // and draw the triangle that was hit.
                    if (selectedSceneNode != null)
                    {
                        bill.Position = intersection;

                        // We need to reset the transform before doing our own rendering.
                        driver.SetTransform(TransformationState.World, Matrix.Identity);
                        driver.SetMaterial(material);
                        driver.Draw3DTriangle(hitTriangle, new Color(255, 0, 0));

                        // We can check the flags for the scene node that was hit to see if it should be
                        // highlighted. The animated nodes can be highlighted, but not the Quake level mesh
                        if ((selectedSceneNode.ID & IDFlag_IsHighlightable) == IDFlag_IsHighlightable)
                        {
                            highlightedSceneNode = selectedSceneNode;

                            // Highlighting in this case means turning lighting OFF for this node,
                            // which means that it will be drawn with full brightness.
                            highlightedSceneNode.SetMaterialFlag(MaterialFlag.Lighting, false);
                        }
                    }

                    // We're all done drawing, so end the scene.
                    driver.EndScene();

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

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            checkBulletSharpDllPresence();

            // setup Irrlicht

            device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1024, 768));
            if (device == null)
            {
                return;
            }

            device.SetWindowCaption("BulletSharp Test - Irrlicht Engine");
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;
            GUIFont      font   = device.GUIEnvironment.GetFont("../../media/fontlucida.png");

            CameraSceneNode camera = scene.AddCameraSceneNodeFPS();

            camera.Position         = new Vector3Df(100, 800, -1000);
            camera.Target           = new Vector3Df(0, 100, 0);
            camera.FarValue         = 30000;
            camera.AutomaticCulling = CullingType.FrustumBox;

            device.CursorControl.Visible = false;

            // setup physics

            physics = new Physics();
            physics.Setup(new Vector3Df(0, -worldGravity, 0));

            // setup particles

            particles = new Particles(device);

            // load quake level

            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");

            Mesh      mesh       = scene.GetMesh("20kdm2.bsp").GetMesh(0);
            SceneNode quakeLevel = scene.AddOctreeSceneNode(mesh, null, -1, 1024);

            quakeLevel.Position = new Vector3Df(-1300, -144, -1249);

            physics.AddShape(Physics.Shape.Mesh, quakeLevel);

            // generate dynamic objects

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 30; j++)
                {
                    for (int k = 0; k < 3; k++)
                    {
                        MeshSceneNode n = scene.AddCubeSceneNode(cubeSize);
                        n.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
                        n.SetMaterialFlag(MaterialFlag.Lighting, false);
                        n.Position = new Vector3Df(70 + i * cubeSize, 520 + j * cubeSize, -650 + k * cubeSize);

                        physics.AddShape(Physics.Shape.Box, n, cubeMass);
                    }
                }
            }

            // main loop

            uint curTime       = 0;
            uint lastTime      = 0;
            int  simFps        = 0;
            int  simFrames     = 0;
            uint simFramesTime = 0;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    // simulate physics

                    lastTime = curTime;
                    curTime  = device.Timer.Time;
                    if (!simPaused)
                    {
                        float deltaTime = (curTime - lastTime) / 1000.0f;
                        bool  b         = physics.StepSimulation(deltaTime);
                        if (b)
                        {
                            simFrames++;
                        }
                    }

                    if (curTime - simFramesTime > 1000)
                    {
                        simFramesTime = curTime;
                        simFps        = simFrames;
                        simFrames     = 0;
                    }

                    // winnow particles

                    particles.Winnow(curTime, simPaused);

                    // render scene

                    driver.BeginScene(true, true, new Color(40, 80, 160));
                    scene.DrawAll();

                    Material material = new Material();
                    material.Lighting = false;
                    device.VideoDriver.SetMaterial(material);

                    // display stats

                    driver.Draw2DRectangle(new Recti(10, 10, 140, 180), new Color(0x7f000000));

                    Vector2Di v = new Vector2Di(20, 20);
                    font.Draw("Rendering", v, Color.OpaqueYellow);
                    v.Y += 16;
                    font.Draw(scene.Attributes.GetValue("calls") + " nodes", v, Color.OpaqueWhite);
                    v.Y += 16;
                    font.Draw(driver.FPS + " fps", v, Color.OpaqueWhite);
                    v.Y += 16;
                    font.Draw("[T]rails " + (useTrails ? "ON" : "OFF"), v, Color.OpaqueGreen);
                    v.Y += 32;
                    font.Draw("Physics" + (simPaused ? " (paused)" : ""), v, Color.OpaqueYellow);
                    v.Y += 16;
                    font.Draw(physics.NumCollisionObjects + " shapes", v, Color.OpaqueWhite);
                    v.Y += 16;
                    font.Draw(simFps + " fps", v, Color.OpaqueWhite);
                    v.Y += 16;
                    font.Draw("[Space] to pause", v, Color.OpaqueGreen);

                    driver.EndScene();
                }

                device.Yield();
            }

            // drop

            physics.Drop();
            device.Drop();
        }
Exemplo n.º 14
0
        ClockNode(SceneNode parent, SceneManager smgr)
            : base(parent, smgr)
        {
            OnGetBoundingBox    += new GetBoundingBoxEventHandler(ClockNode_OnGetBoundingBox);
            OnGetMaterialCount  += new GetMaterialCountEventHandler(ClockNode_OnGetMaterialCount);
            OnGetMaterial       += new GetMaterialEventHandler(ClockNode_OnGetMaterial);
            OnRegisterSceneNode += new RegisterSceneNodeEventHandler(ClockNode_OnRegisterSceneNode);
            OnRender            += new RenderEventHandler(ClockNode_OnRender);
            OnAnimate           += new AnimateEventHandler(ClockNode_OnAnimate);

            // add clock face

            Mesh          mesh      = SceneManager.GeometryCreator.CreateCylinderMesh(100, 32, 6, new Color(180, 180, 180));
            MeshSceneNode clockFace = SceneManager.AddMeshSceneNode(mesh, this);

            clockFace.Rotation = new Vector3Df(90, 0, 0);
            clockFace.Position = new Vector3Df(0, 0, 10);
            mesh.Drop();

            clockFace.UpdateAbsolutePosition();
            boundingBox = clockFace.BoundingBoxTransformed;
            for (int i = 0; i < clockFace.MaterialCount; i++)
            {
                materialList.Add(clockFace.GetMaterial(i));
            }

            // add clock center

            mesh = SceneManager.GeometryCreator.CreateCylinderMesh(10, 24, 16, new Color(255, 255, 255), false);
            MeshSceneNode clockCenter = SceneManager.AddMeshSceneNode(mesh, this);

            clockCenter.Rotation = new Vector3Df(90, 0, 0);
            clockCenter.Position = new Vector3Df(0, 0, -14);
            mesh.Drop();

            clockCenter.UpdateAbsolutePosition();
            boundingBox.AddInternalBox(clockCenter.BoundingBoxTransformed);
            for (int i = 0; i < clockCenter.MaterialCount; i++)
            {
                materialList.Add(clockCenter.GetMaterial(i));
            }

            // add clock ticks

            for (int j = 0; j < 12; j++)
            {
                mesh = SceneManager.GeometryCreator.CreateCylinderMesh(5, 10, 16, new Color(255, 255, 255), false);
                MeshSceneNode clockTick = SceneManager.AddMeshSceneNode(mesh, this);
                clockTick.Rotation = new Vector3Df(90, 0, 0);

                float s = (float)Math.Sin((j * (360 / 12)) / (180 / Math.PI));
                float c = (float)Math.Cos((j * (360 / 12)) / (180 / Math.PI));
                clockTick.Position = new Vector3Df(s * 80, c * 80, 0);

                if ((j % 3) == 0)
                {
                    clockTick.Scale = new Vector3Df(2, 1, 2);
                }

                mesh.Drop();

                clockTick.UpdateAbsolutePosition();
                boundingBox.AddInternalBox(clockTick.BoundingBoxTransformed);
                for (int i = 0; i < clockTick.MaterialCount; i++)
                {
                    materialList.Add(clockTick.GetMaterial(i));
                }
            }

            // add hour arrow

            mesh       = SceneManager.GeometryCreator.CreateArrowMesh(12, 12, 40, 35, 4, 4, new Color(40, 40, 255), new Color(40, 40, 255));
            arrowHours = SceneManager.AddMeshSceneNode(mesh, this);
            arrowHours.GetMaterial(0).EmissiveColor = new Color(0, 0, 255);
            arrowHours.GetMaterial(1).EmissiveColor = new Color(0, 0, 255);
            arrowHours.Position = new Vector3Df(0, 0, 3);
            mesh.Drop();

            arrowHours.UpdateAbsolutePosition();
            boundingBox.AddInternalBox(arrowHours.BoundingBoxTransformed);
            for (int i = 0; i < arrowHours.MaterialCount; i++)
            {
                materialList.Add(arrowHours.GetMaterial(i));
            }

            // add minute arrow

            mesh         = SceneManager.GeometryCreator.CreateArrowMesh(12, 12, 60, 50, 4, 4, new Color(40, 255, 40), new Color(40, 255, 40));
            arrowMinutes = SceneManager.AddMeshSceneNode(mesh, this);
            arrowMinutes.GetMaterial(0).EmissiveColor = new Color(0, 255, 0);
            arrowMinutes.GetMaterial(1).EmissiveColor = new Color(0, 255, 0);
            arrowMinutes.Position = new Vector3Df(0, 0, -5);
            mesh.Drop();

            arrowMinutes.UpdateAbsolutePosition();
            boundingBox.AddInternalBox(arrowMinutes.BoundingBoxTransformed);
            for (int i = 0; i < arrowMinutes.MaterialCount; i++)
            {
                materialList.Add(arrowMinutes.GetMaterial(i));
            }

            // add second arrow

            mesh         = SceneManager.GeometryCreator.CreateArrowMesh(12, 12, 70, 60, 2, 2, new Color(255, 40, 40), new Color(255, 40, 40));
            arrowSeconds = SceneManager.AddMeshSceneNode(mesh, this);
            arrowSeconds.GetMaterial(0).EmissiveColor = new Color(255, 0, 0);
            arrowSeconds.GetMaterial(1).EmissiveColor = new Color(255, 0, 0);
            arrowSeconds.Position = new Vector3Df(0, 0, -11);
            mesh.Drop();

            arrowSeconds.UpdateAbsolutePosition();
            boundingBox.AddInternalBox(arrowSeconds.BoundingBoxTransformed);
            for (int i = 0; i < arrowSeconds.MaterialCount; i++)
            {
                materialList.Add(arrowSeconds.GetMaterial(i));
            }

            SceneManager.AddLightSceneNode(arrowSeconds, new Vector3Df(0, 70, 0), new Colorf(arrowSeconds.GetMaterial(0).EmissiveColor), 80);
            SceneManager.AddLightSceneNode(arrowMinutes, new Vector3Df(0, 60, 0), new Colorf(arrowMinutes.GetMaterial(0).EmissiveColor), 60);
            SceneManager.AddLightSceneNode(arrowHours, new Vector3Df(0, 40, 0), new Colorf(arrowHours.GetMaterial(0).EmissiveColor), 40);
        }
Exemplo n.º 15
0
        public void NewGame(int boardDimWidth, int boardDimHeight)
        {
            m_boardDimWidth  = boardDimWidth;
            m_boardDimHeight = boardDimHeight;
            m_state          = State.Playing;
            m_board          = new Cell[m_boardDimWidth * m_boardDimHeight];

            m_root.RemoveChildren();

            // init board

            Random r = new Random();

            for (int j = 0; j < m_boardDimHeight; j++)
            {
                for (int i = 0; i < m_boardDimWidth; i++)
                {
                    Cell c = new Cell();
                    c.i        = i;
                    c.j        = j;
                    c.number   = (r.Next() % 6) == 0 ? -1 : 0;
                    c.flagged  = false;
                    c.revealed = false;

                    m_board[i + j * m_boardDimWidth] = c;

                    MeshSceneNode n = m_device.SceneManager.AddMeshSceneNode(m_meshCell, m_root, 0x10000 + i + j * m_boardDimWidth);
                    n.Position = new Vector3Df(i * SIZE_OF_CELL, 0, j * SIZE_OF_CELL);

                    // n must have at least 2 children, where #0 is a flag node and #1 is a bomb node
                    // (that's why we add shadow volume nodes at the very end)

                    MeshSceneNode f = m_device.SceneManager.AddMeshSceneNode(m_meshFlag, n, 0);
                    f.Position = new Vector3Df(
                        (n.BoundingBox.MaxEdge.X - m_meshFlag.BoundingBox.MaxEdge.X) / 2,
                        n.BoundingBox.MaxEdge.Y,
                        (n.BoundingBox.MaxEdge.Z - m_meshFlag.BoundingBox.MaxEdge.Z) / 2 + SIZE_OF_CELL / 6);
                    f.Visible = false;

                    MeshSceneNode b = m_device.SceneManager.AddMeshSceneNode(m_meshBomb, n, 0);
                    b.Position = new Vector3Df(
                        0,
                        n.BoundingBox.MaxEdge.Y,
                        0);
                    b.Visible = false;

                    n.AddShadowVolumeSceneNode(null, 0);
                    f.AddShadowVolumeSceneNode(null, 0);
                    b.AddShadowVolumeSceneNode(null, 0);
                }
            }

            // calc board numbers

            for (int j = 0; j < m_boardDimHeight; j++)
            {
                for (int i = 0; i < m_boardDimWidth; i++)
                {
                    if (!m_board[i + j * m_boardDimWidth].IsBomb)
                    {
                        continue;
                    }

                    if (i - 1 >= 0 && !m_board[i - 1 + j * m_boardDimWidth].IsBomb)                     // left
                    {
                        m_board[i - 1 + j * m_boardDimWidth].number++;
                    }

                    if (i + 1 < m_boardDimWidth && !m_board[i + 1 + j * m_boardDimWidth].IsBomb)                     // right
                    {
                        m_board[i + 1 + j * m_boardDimWidth].number++;
                    }

                    if (j - 1 >= 0 && !m_board[i + (j - 1) * m_boardDimWidth].IsBomb)                     // top
                    {
                        m_board[i + (j - 1) * m_boardDimWidth].number++;
                    }

                    if (j + 1 < m_boardDimHeight && !m_board[i + (j + 1) * m_boardDimWidth].IsBomb)                     // bottom
                    {
                        m_board[i + (j + 1) * m_boardDimWidth].number++;
                    }

                    if (j - 1 >= 0 && i - 1 >= 0 && !m_board[i - 1 + (j - 1) * m_boardDimWidth].IsBomb)                     // top left
                    {
                        m_board[i - 1 + (j - 1) * m_boardDimWidth].number++;
                    }

                    if (j - 1 >= 0 && i + 1 < m_boardDimWidth && !m_board[i + 1 + (j - 1) * m_boardDimWidth].IsBomb)                     // top right
                    {
                        m_board[i + 1 + (j - 1) * m_boardDimWidth].number++;
                    }

                    if (j + 1 < m_boardDimHeight && i + 1 < m_boardDimWidth && !m_board[i + 1 + (j + 1) * m_boardDimWidth].IsBomb)                     // bottom right
                    {
                        m_board[i + 1 + (j + 1) * m_boardDimWidth].number++;
                    }

                    if (j + 1 < m_boardDimHeight && i - 1 >= 0 && !m_board[i - 1 + (j + 1) * m_boardDimWidth].IsBomb)                     // bottom left
                    {
                        m_board[i - 1 + (j + 1) * m_boardDimWidth].number++;
                    }
                }
            }
        }
Exemplo n.º 16
0
        static void Main()
        {
            // setup Irrlicht

            device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(1024, 768), 32, false, true);
            if (device == null)
            {
                return;
            }

            device.SetWindowCaption("Stencil Shadows - Irrlicht Engine");
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

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

            GUIFont statsFont = device.GUIEnvironment.GetFont("../../media/fontlucida.png");

            cameraNode          = scene.AddCameraSceneNodeFPS();
            cameraNode.FarValue = 20000;

            device.CursorControl.Visible = false;

            // setup shadows

            shadows = new Shadows(new Color(0xa0000000), 4000);

            // load quake level

            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");

            Mesh          m = scene.GetMesh("20kdm2.bsp").GetMesh(0);
            MeshSceneNode n = scene.AddOctreeSceneNode(m, null, -1, 1024);

            n.Position     = new Vector3Df(-1300, -144, -1249);
            quakeLevelNode = n;

            // add faerie

            faerieNode = scene.AddAnimatedMeshSceneNode(
                scene.GetMesh("../../media/faerie.md2"),
                null, -1,
                new Vector3Df(100, -40, 80),
                new Vector3Df(0, 30, 0),
                new Vector3Df(1.6f));

            faerieNode.SetMD2Animation(AnimationTypeMD2.Wave);
            faerieNode.AnimationSpeed = 20;
            faerieNode.GetMaterial(0).SetTexture(0, driver.GetTexture("../../media/faerie2.bmp"));
            faerieNode.GetMaterial(0).Lighting         = false;
            faerieNode.GetMaterial(0).NormalizeNormals = true;

            shadows.AddObject(faerieNode);

            // add light

            lightMovementHelperNode = scene.AddEmptySceneNode();

            n = scene.AddSphereSceneNode(2, 6, lightMovementHelperNode, -1, new Vector3Df(15, -10, 15));
            n.SetMaterialFlag(MaterialFlag.Lighting, false);

            lightNode = n;
            shadows.AddLight(lightNode);

            // add flashlight

            m = scene.GetMesh("../../media/flashlight.obj");
            n = scene.AddMeshSceneNode(m, lightNode, -1, new Vector3Df(0), new Vector3Df(0), new Vector3Df(5));
            n.SetMaterialFlag(MaterialFlag.Lighting, false);

            flashlightNode         = n;
            flashlightNode.Visible = false;

            // render

            uint shdFrameTime = 0;
            uint shdFrames    = 0;
            uint shdFps       = 0;

            while (device.Run())
            {
                if (useShadowsRebuilding &&
                    shadows.BuildShadowVolume())
                {
                    shdFrames++;
                }

                uint t = device.Timer.Time;
                if (t - shdFrameTime > 1000)
                {
                    shdFrameTime = t;
                    shdFps       = shdFrames;
                    shdFrames    = 0;
                }

                if (useLightBinding)
                {
                    lightMovementHelperNode.Position = cameraNode.AbsolutePosition.GetInterpolated(lightMovementHelperNode.Position, 0.1);
                    lightMovementHelperNode.Rotation = cameraNode.AbsoluteTransformation.Rotation;
                }

                driver.BeginScene(ClearBufferFlag.All, new Color(0xff112244));

                scene.DrawAll();

                if (useShadowsRendering)
                {
                    shadows.DrawShadowVolume(driver);
                }

                // display stats

                driver.Draw2DRectangle(new Recti(10, 10, 150, 220), new Color(0x7f000000));

                Vector2Di v = new Vector2Di(20, 20);
                statsFont.Draw("Rendering", v, Color.SolidYellow);
                v.Y += 16;
                statsFont.Draw(driver.FPS + " fps", v, Color.SolidWhite);
                v.Y += 16;
                statsFont.Draw("[S]hadows " + (useShadowsRendering ? "ON" : "OFF"), v, Color.SolidGreen);
                v.Y += 16;
                statsFont.Draw("[L]ight binding " + (useLightBinding ? "ON" : "OFF"), v, Color.SolidGreen);
                v.Y += 16;
                statsFont.Draw("[F]lashlight " + (useFlashlight ? "ON" : "OFF"), v, Color.SolidGreen);
                v.Y += 32;
                statsFont.Draw("Shadows", v, Color.SolidYellow);
                v.Y += 16;
                statsFont.Draw(shdFps + " fps", v, Color.SolidWhite);
                v.Y += 16;
                statsFont.Draw(shadows.VerticesBuilt + " vertices", v, Color.SolidWhite);
                v.Y += 16;
                statsFont.Draw("[R]ebuilding " + (useShadowsRebuilding ? "ON" : "OFF"), v, Color.SolidGreen);
                v.Y += 16;
                statsFont.Draw("[Q]uake level " + (useShadowsQuakeLevel ? "ON" : "OFF"), v, Color.SolidGreen);

                driver.EndScene();
            }

            shadows.Drop();
            device.Drop();
        }
Exemplo n.º 17
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(800, 600));

            if (device == null)
            {
                return;
            }

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.SetWindowCaption("Mesh handling - Irrlicht Engine - press [1], [2], [3] to regenerate mesh");
            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;

            // Generate starting height map and mesh

            HeightMap map = new HeightMap(255, 255);

            map.Generate(HeightMap.HeightFunc.EggBox);

            HeightMesh mesh = new HeightMesh();

            mesh.Init(driver, map, 50.0f, HeightMesh.ColorFunc.GreyscaleBasedOnTheHeight);

            // Add the mesh to the scene graph

            MeshSceneNode meshnode = scene.AddMeshSceneNode(mesh.Mesh);

            meshnode.SetMaterialFlag(MaterialFlag.BackFaceCulling, false);

            // Add light (just for nice effects)

            LightSceneNode    lightnode = scene.AddLightSceneNode(null, new Vector3Df(0, 100, 0), new Colorf(1, 1, 1), 500.0f);
            SceneNodeAnimator anim      = scene.CreateFlyCircleAnimator(new Vector3Df(0, 150, 0), 250.0f);

            lightnode.AddAnimator(anim);
            anim.Drop();

            // Add camera

            CameraSceneNode camera = scene.AddCameraSceneNodeFPS();

            camera.Position = new Vector3Df(-20.0f, 100.0f, -20.0f);
            camera.Target   = new Vector3Df(200.0f, -100.0f, 200.0f);
            camera.FarValue = 20000.0f;

            // Main loop

            while (device.Run())
            {
                if (!device.WindowActive)
                {
                    device.Sleep(100);
                    continue;
                }

                if (IsKeyDown(KeyCode.KeyW))
                {
                    meshnode.SetMaterialFlag(MaterialFlag.Wireframe, !meshnode.GetMaterial(0).Wireframe);
                }
                else if (IsKeyDown(KeyCode.Key1))
                {
                    map.Generate(HeightMap.HeightFunc.EggBox);
                    mesh.Init(driver, map, 50.0f, HeightMesh.ColorFunc.GreyscaleBasedOnTheHeight);
                }
                else if (IsKeyDown(KeyCode.Key2))
                {
                    map.Generate(HeightMap.HeightFunc.MoreSine);
                    mesh.Init(driver, map, 50.0f, HeightMesh.ColorFunc.CoordinateInterpolation);
                }
                else if (IsKeyDown(KeyCode.Key3))
                {
                    map.Generate(HeightMap.HeightFunc.JustExp);
                    mesh.Init(driver, map, 50.0f, HeightMesh.ColorFunc.CoordinateInterpolation);
                }

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

            // Clean up

            mesh.Drop();
            device.Drop();
        }
Exemplo n.º 18
0
        void ProcessCommand()
        {
            queueSizeBar.Invoke((MethodInvoker) delegate
            {
                if (commandQueue.Count > queueSizeBar.Maximum)
                {
                    queueSizeBar.Maximum = commandQueue.Count;
                    queueSizeBar.Value   = queueSizeBar.Maximum;
                }
                else
                {
                    queueSizeBar.Value = commandQueue.Count;
                }
            });

            RenderMessage m;

            if (commandQueue.TryDequeue(out m))
            {
                switch (m.Message)
                {
                case MessageType.SHOW_NODE:
                {
                    m.Node.Visible = true;
                    var camera = smgr.ActiveCamera;

                    // just set the target
                    camera.Target      = m.Node.AbsolutePosition;
                    lightNode.Position = camera.Position;
                }
                break;

                case MessageType.HIDE_NODE:
                {
                    m.Node.Visible = false;
                }
                break;

                case MessageType.SELECT_NODE:
                {
                    // highlight and
                    smgr.SelectNode(m.Node);
                    var camera = smgr.ActiveCamera;

                    // just set the target
                    camera.Target      = m.Node.AbsolutePosition;
                    lightNode.Position = camera.Position;
                }
                break;

                case MessageType.ADD_MESH_NODE:
                {
                    IrrlichtLime.Scene.Mesh mesh = smgr.GetStaticMesh(depot + m.MeshName);
                    foreach (var mb in mesh.MeshBuffers)
                    {
                        totalVertexCount += mb.VertexCount;
                    }
                    MeshSceneNode meshNode = smgr.AddMeshSceneNode(mesh, worldNode, meshId++, m.Translation, m.Rotation);
#if DEBUG
                    meshNode.Name = m.MeshName;
#endif
                    meshNode.Grab();

                    RenderTreeNode rn = new RenderTreeNode(m.MeshName, meshNode);
                    if (m.TreeNode.GetNodeCount(false) > 0)
                    {
                        // TODO: does this need to be invoked?
                        sceneView.Invoke((MethodInvoker) delegate
                            {
                                m.TreeNode.Nodes.Add(rn);
                            });
                    }
                    else
                    {
                        sceneView.Invoke((MethodInvoker) delegate
                            {
                                sceneView.Nodes.Add(m.TreeNode);
                                m.TreeNode.Nodes.Add(rn);
                            });
                    }

                    ++totalMeshCount;

                    vertexCountText.Text = "Vertices: " + totalVertexCount.ToString();
                    meshCountText.Text   = "Meshes: " + totalMeshCount.ToString();
                }
                break;

                case MessageType.ADD_TERRAIN_NODE:
                {
                    var meshNode = smgr.AddTerrainSceneNodeWolvenKit(depot + m.MeshName, worldNode, meshId, m.TileRes, m.MaxHeight, m.MinHeight, m.TerrainSize, m.Translation);
                    meshNode.Grab();
                    foreach (var mb in meshNode.Mesh.MeshBuffers)
                    {
                        totalVertexCount += mb.VertexCount;
                    }

                    RenderTreeNode rn = new RenderTreeNode("Tile " + meshId.ToString(), meshNode);
                    meshId++;

                    if (m.TreeNode.GetNodeCount(false) > 0)
                    {
                        // TODO: does this need to be invoked?
                        sceneView.Invoke((MethodInvoker) delegate
                            {
                                m.TreeNode.Nodes.Add(rn);
                            });
                    }
                    else
                    {
                        sceneView.Invoke((MethodInvoker) delegate
                            {
                                sceneView.Nodes.Add(m.TreeNode);
                                m.TreeNode.Nodes.Add(rn);
                            });
                    }

                    ++totalMeshCount;

                    vertexCountText.Text = "Vertices: " + totalVertexCount.ToString();
                    meshCountText.Text   = "Meshes: " + totalMeshCount.ToString();
                }
                break;

                case MessageType.DESELECT_NODE:
                {
                    smgr.DeselectNode();
                }
                break;

                case MessageType.HIGHLIGHT_NODE:
                {
                    smgr.SelectNode(m.Node);
                }
                break;

                case MessageType.SHUTDOWN:
                {
                    device.Yield();
                }
                break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 19
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();
        }
Exemplo n.º 20
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();
        }
Exemplo n.º 21
0
        public void Initialize()
        {
            Engine.Instance.ManualMeshServices.AddGridMesh("$grid20", 20, 1, new SColor(128, 128, 128));

            gridSceneNode = Engine.Instance.SceneManager.AddMeshSceneNode("$grid20", null);
        }
Exemplo n.º 22
0
        static bool Device_OnEvent(Event evnt)
        {
            if (evnt.Type == EventType.GUI &&
                evnt.GUI.Type == GUIEventType.ButtonClicked &&
                evnt.GUI.Caller.ID == ChooseFolderButtonId)
            {
                wantChangeFolder = true;
                return(true);
            }

            if (evnt.Type == EventType.Mouse &&
                evnt.Mouse.Type == MouseEventType.Wheel &&
                selectedNode == null)
            {
                Vector3Df p = irr.Scene.ActiveCamera.Position;
                Vector3Df t = irr.Scene.ActiveCamera.Target;
                float     s = irr.Scene.ActiveCamera.Position.Z + evnt.Mouse.Wheel * 16;

                if (s < 0)
                {
                    s = 0;
                }

                if (s > maxScrollPosition)
                {
                    s = maxScrollPosition;
                }

                t.Z = t.Z - p.Z + s;
                p.Z = s;

                irr.Scene.ActiveCamera.Position = p;
                irr.Scene.ActiveCamera.Target   = t;

                return(true);
            }

            if (evnt.Type == EventType.Mouse &&
                evnt.Mouse.Type == MouseEventType.Move &&
                selectedNode == null)
            {
                SceneNode n =
                    irr.Scene.SceneCollisionManager.GetSceneNodeFromScreenCoordinatesBB(
                        new Vector2Di(evnt.Mouse.X, evnt.Mouse.Y),
                        0,
                        irr.Scene.GetSceneNodeFromID(PreviewRootNodeId));

                if (hoveredNode != n)
                {
                    if (hoveredNode != null)
                    {
                        animationManager.Remove(hoveredNode);

                        animationManager.Add(
                            hoveredNode,
                            500,
                            new Vector3Df(hoveredNode.Position.X, hoveredNode.Position.Y - 15, hoveredNode.Position.Z),
                            new Vector3Df(0),
                            hoveredNode.Scale / 1.5f);
                    }

                    if (n != null)
                    {
                        animationManager.Remove(n);

                        animationManager.Add(
                            n,
                            40,
                            new Vector3Df(n.Position.X, n.Position.Y + 15, n.Position.Z),
                            new Vector3Df(-20, 0, 0),
                            n.Scale * 1.5f);
                    }

                    hoveredNode = n;
                }

                return(true);
            }

            if (evnt.Type == EventType.Mouse &&
                evnt.Mouse.Type == MouseEventType.LeftUp &&
                hoveredNode != null &&
                (hoveredNode.ID & SelectableNodeIdFlag) == SelectableNodeIdFlag &&
                selectedNode == null)
            {
                animationManager.Remove(hoveredNode);

                Mesh          m = irr.Scene.MeshCache.GetMesh(PreviewPlateMeshName);
                MeshSceneNode n = irr.Scene.AddMeshSceneNode(m);
                n.SetMaterialFlag(MaterialFlag.Lighting, false);
                n.Position = hoveredNode.Position;
                n.Rotation = hoveredNode.Rotation;
                n.Scale    = hoveredNode.Scale;

                string t = hoveredNode.GetMaterial(0).GetTexture(0).Name.Path.Split('|')[0];

                Dimension2Di d = new Dimension2Di(2048);
                if (d.Area > irr.Driver.MaxTextureSize.Area)
                {
                    d = irr.Driver.MaxTextureSize;
                }

                n.SetMaterialTexture(0, hoveredNode.GetMaterial(0).GetTexture(0));
                textureManager.LoadTexture(n, t, d, true);

                animationManager.Add(
                    n,
                    200,
                    irr.Scene.ActiveCamera.AbsolutePosition + new Vector3Df(0, -48, 40), // TODO: this magic numbers should be calculated somehow
                    new Vector3Df(-39.85f, 0, 0),                                        // using current active camera info (like view matrix or projection one)
                    n.Scale * ((irr.Scene.ActiveCamera.FOV - 0.125f) / n.Scale.Z));

                selectedNode        = n;
                hoveredNode.Visible = false;
                irr.GUI.RootElement.GetElementFromID(ChooseFolderButtonId).Enabled = false;

                return(true);
            }

            if (evnt.Type == EventType.Mouse &&
                evnt.Mouse.Type == MouseEventType.LeftUp &&
                selectedNode != null &&
                selectedNode.GetMaterial(0).GetTexture(0) != hoveredNode.GetMaterial(0).GetTexture(0))
            {
                if (animationManager.IsAnimated(selectedNode))
                {
                    return(true);
                }

                Texture t = selectedNode.GetMaterial(0).GetTexture(0);
                if (t != null)
                {
                    string s = t.Name.Path;
                    selectedNode.SetMaterialTexture(0, null);
                    textureManager.UnloadTexture(s);
                }

                selectedNode.Remove();
                selectedNode = null;

                hoveredNode.Visible = true;
                irr.GUI.RootElement.GetElementFromID(ChooseFolderButtonId).Enabled = true;

                return(true);
            }

            if (evnt.Type == EventType.Log &&
                evnt.Log.Text.StartsWith("Resizing window"))
            {
                wantUpdateActiveCameraAspectRatio = true;
            }

            return(false);
        }
Exemplo n.º 23
0
        public Jeu()
        {
            Device = IrrlichtDevice.CreateDevice(
                DriverType.Direct3D9,
                new Dimension2Di(800, 600),
                32, false, false, true);

            Device.SetWindowCaption("Canardstein 3D");
            Device.OnEvent += Evenement;

            Audio = new ISoundEngine();

            for (int i = 0; i < 3; i++)
            {
                TexturePistolet[i] = Device.VideoDriver.GetTexture(@"Textures\pistolet" + i.ToString() + ".png");
            }

            for (int i = 0; i < 7; i++)
            {
                TextureGarde[i] = Device.VideoDriver.GetTexture(@"Textures\nazi" + i.ToString("00") + ".png");
            }

            TextureMur     = Device.VideoDriver.GetTexture(@"Textures\mur.png");
            TextureMurDeco = Device.VideoDriver.GetTexture(@"Textures\mur_deco.png");
            TextureSol     = Device.VideoDriver.GetTexture(@"Textures\sol.png");
            TexturePlafond = Device.VideoDriver.GetTexture(@"Textures\plafond.png");
            TexturePolice  = Device.VideoDriver.GetTexture(@"Textures\police.png");

            using (Bitmap carte = (Bitmap)System.Drawing.Image.FromFile(@"Textures\carte.png"))
            {
                for (int x = 0; x < 32; x++)
                {
                    for (int y = 0; y < 32; y++)
                    {
                        System.Drawing.Color col = carte.GetPixel(x, y);
                        Murs[x, y] = false;

                        if ((col.R == 255) && (col.G == 255) && (col.B == 255))
                        {
                            SceneNode cube = Device.SceneManager.AddCubeSceneNode(1, null, 0, new Vector3Df(x, 0, y));
                            cube.SetMaterialFlag(MaterialFlag.Lighting, false);
                            cube.SetMaterialFlag(MaterialFlag.Fog, true);
                            cube.SetMaterialTexture(0, TextureMur);
                            Murs[x, y] = true;
                        }
                        else if ((col.R == 0) && (col.G == 0) && (col.B == 255))
                        {
                            SceneNode cube = Device.SceneManager.AddCubeSceneNode(1, null, 0, new Vector3Df(x, 0, y));
                            cube.SetMaterialFlag(MaterialFlag.Lighting, false);
                            cube.SetMaterialFlag(MaterialFlag.Fog, true);
                            cube.SetMaterialTexture(0, TextureMurDeco);
                            Murs[x, y] = true;
                        }
                    }
                }
            }



            //On va maintenant créer un plancher et un plafond, histoire de mettre un peu d'ordre. On commence par générer meshSol,
            //le modèle 3D d'un plan que nous allons nommer « plan » (parce qu'il est obligatoire de fournir un nom), divisé en 32 × 32 cases de taille 1 × 1.
            //On ne va pas lui assigner de texture pour le moment (null). Ce plan sera parfaitement horizontal, avec 0 × 0 variation de hauteur 0.
            //Enfin, la texture sera répétée 32 fois horizontalement et verticalement.
            Mesh meshSol = Device.SceneManager.AddHillPlaneMesh("plan", new Dimension2Df(1, 1), new Dimension2Di(32, 32), null, 0, new Dimension2Df(0, 0), new Dimension2Df(32, 32));

            //On désactive l'éclairage dynamique sur notre nouvel objet, comme on l'avait déjà fait pour le cube, et on lui assigne TextureSol.
            //Puis on le positionne à une distance d'une demi-unité sous le zéro (ou, plus précisément, sous les pieds de notre héros, la position Y de la caméra étant de 0),
            //et à −15.5 sur les axes X et Z (notre plan mesurant 32 par 32 cases de largeur 1, le déplacer de 15,5 unités permet de s'assurer que l'un de ses coins sera à la coordonnée 0,0,
            //ce sera utile dans la prochaine leçon).
            MeshSceneNode sol = Device.SceneManager.AddMeshSceneNode(meshSol);

            sol.SetMaterialFlag(MaterialFlag.Lighting, false);
            sol.SetMaterialFlag(MaterialFlag.Fog, true);
            sol.SetMaterialTexture(0, TextureSol);
            sol.Position = new Vector3Df(15.5f, -0.5f, 15.5f);

            //Pareil pour le plafond, sauf qu'on le place à une hauteur de 0,5 (et non de −0,5), et qu'on le pivote de 180 sur l'axe X pour le tourner vers le bas.
            MeshSceneNode plafond = Device.SceneManager.AddMeshSceneNode(meshSol);

            plafond.SetMaterialFlag(MaterialFlag.Lighting, false);
            plafond.SetMaterialFlag(MaterialFlag.Fog, true);
            plafond.SetMaterialTexture(0, TexturePlafond);
            plafond.Position = new Vector3Df(15.5f, 0.5f, 15.5f);
            plafond.Rotation = new Vector3Df(180, 0, 0);

            CameraSceneNode camera = Device.SceneManager.AddCameraSceneNode(null, new Vector3Df(1, 0, 1), new Vector3Df(2, 0, 1));

            //Abaisse la distance minimum d'affichage de la caméra. La valeur par défaut est de 1, ce qui ne nous convient pas :
            //plafond et sol se trouvant à 0,5 unité de la caméra, ils seraient trop près pour être dessinés.
            camera.NearValue = 0.1f;

            AjouterChose <Ennemi>(3, 3);
            AjouterChose <Ennemi>(6, 12);
            AjouterChose <Ennemi>(12, 12);
            AjouterChose <Ennemi>(20, 6);
            AjouterChose <Ennemi>(28, 16);
            AjouterChose <Ennemi>(11, 27);

            Device.VideoDriver.Fog = new Fog(new IrrlichtLime.Video.Color(138, 125, 81, 0), FogType.Linear, 0, 10);

            ParticleSystemSceneNode part = Device.SceneManager.AddParticleSystemSceneNode(false, null, 0, new Vector3Df(29, -.5f, 30));

            part.SetMaterialFlag(MaterialFlag.Lighting, false);
            ParticleEmitter em = part.CreateBoxEmitter(
                new AABBox(-.5f, 0, -.5f, .5f, 0, .5f),
                new Vector3Df(0.0f, 0.0015f, 0.0f),
                20, 24,
                new IrrlichtLime.Video.Color(0, 128, 255, 0), new IrrlichtLime.Video.Color(0, 255, 255, 0),
                800, 800, 0,
                new Dimension2Df(0.005f, 0.04f), new Dimension2Df(0.01f, 0.08f));

            part.Emitter = em;

            while (Device.Run())
            {
                float tempsEcoule = (Device.Timer.Time - DerniereFrame) / 1000f;
                DerniereFrame = Device.Timer.Time;

                if ((AlphaSang > 0) && (Vies > 0))
                {
                    AlphaSang = Math.Max(0, AlphaSang - tempsEcoule * 500);
                }


                if (((int)camera.Position.X == 29) && ((int)camera.Position.Z == 30))
                {
                    Device.Close();
                }

                if (Device.CursorControl.Position.X != 400)
                {
                    Rotation += (Device.CursorControl.Position.X - 400) * 0.0025;
                    Device.CursorControl.Position = new Vector2Di(400, 300);
                    VecteurAvant  = new Vector3Df((float)Math.Cos(Rotation), 0, -(float)Math.Sin(Rotation));
                    VecteurDroite = VecteurAvant;
                    VecteurDroite.RotateXZby(-90);
                }


                for (int i = 0; i < Choses.Count; i++)
                {
                    Choses[i].MiseAJour(tempsEcoule, camera);
                }


                Vector3Df vitesse = new Vector3Df();
                if (K_Avant)
                {
                    vitesse += VecteurAvant;
                }
                else if (K_Arriere)
                {
                    vitesse -= VecteurAvant;
                }
                if (K_Gauche)
                {
                    vitesse -= VecteurDroite;
                }
                else if (K_Droite)
                {
                    vitesse += VecteurDroite;
                }

                vitesse = vitesse.Normalize() * tempsEcoule * 2;


                if (TenterMouvement(camera, vitesse) || TenterMouvement(camera, new Vector3Df(vitesse.X, 0, 0)) || TenterMouvement(camera, new Vector3Df(0, 0, vitesse.Z)))
                {
                    camera.Target = camera.Position + VecteurAvant;
                }

                Device.VideoDriver.BeginScene(ClearBufferFlag.Color | ClearBufferFlag.Depth, IrrlichtLime.Video.Color.OpaqueMagenta);
                Device.SceneManager.DrawAll();

                Device.VideoDriver.Draw2DImage(TexturePistolet[FramePistolet], new Recti(new Vector2Di(250, 300), new Dimension2Di(300, 300)), new Recti(0, 0, 512, 512), null, COULEUR_BLANC, true);
                DessinerHUD();
                Device.VideoDriver.EndScene();

                if (FramePistolet > 0)
                {
                    ProchaineFramePistolet -= tempsEcoule;

                    if (ProchaineFramePistolet <= 0f)
                    {
                        FramePistolet++;
                        if (FramePistolet > 2)
                        {
                            FramePistolet = 0;
                        }
                        ProchaineFramePistolet = 0.1f;
                    }
                }
            }
        }
Exemplo n.º 24
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();
        }
Exemplo n.º 25
0
		ClockNode(SceneNode parent, SceneManager smgr)
			: base(parent, smgr)
		{
			OnGetBoundingBox += new GetBoundingBoxEventHandler(ClockNode_OnGetBoundingBox);
			OnGetMaterialCount += new GetMaterialCountEventHandler(ClockNode_OnGetMaterialCount);
			OnGetMaterial += new GetMaterialEventHandler(ClockNode_OnGetMaterial);
			OnRegisterSceneNode += new RegisterSceneNodeEventHandler(ClockNode_OnRegisterSceneNode);
			OnRender += new RenderEventHandler(ClockNode_OnRender);
			OnAnimate += new AnimateEventHandler(ClockNode_OnAnimate);

			// add clock face

			Mesh mesh = SceneManager.GeometryCreator.CreateCylinderMesh(100, 32, 6, new Color(180, 180, 180));
			MeshSceneNode clockFace = SceneManager.AddMeshSceneNode(mesh, this);
			clockFace.Rotation = new Vector3Df(90, 0, 0);
			clockFace.Position = new Vector3Df(0, 0, 10);
			mesh.Drop();

			clockFace.UpdateAbsolutePosition();
			boundingBox = clockFace.BoundingBoxTransformed;
			for (int i = 0; i < clockFace.MaterialCount; i++) materialList.Add(clockFace.GetMaterial(i));
			
			// add clock center

			mesh = SceneManager.GeometryCreator.CreateCylinderMesh(10, 24, 16, new Color(255, 255, 255), false);
			MeshSceneNode clockCenter = SceneManager.AddMeshSceneNode(mesh, this);
			clockCenter.Rotation = new Vector3Df(90, 0, 0);
			clockCenter.Position = new Vector3Df(0, 0, -14);
			mesh.Drop();

			clockCenter.UpdateAbsolutePosition();
			boundingBox.AddInternalBox(clockCenter.BoundingBoxTransformed);
			for (int i = 0; i < clockCenter.MaterialCount; i++) materialList.Add(clockCenter.GetMaterial(i));

			// add clock ticks

			for (int j = 0; j < 12; j++)
			{
				mesh = SceneManager.GeometryCreator.CreateCylinderMesh(5, 10, 16, new Color(255, 255, 255), false);
				MeshSceneNode clockTick = SceneManager.AddMeshSceneNode(mesh, this);
				clockTick.Rotation = new Vector3Df(90, 0, 0);

				float s = (float)Math.Sin((j * (360 / 12)) / (180 / Math.PI));
				float c = (float)Math.Cos((j * (360 / 12)) / (180 / Math.PI));
				clockTick.Position = new Vector3Df(s * 80, c * 80, 0);

				if ((j % 3) == 0)
					clockTick.Scale = new Vector3Df(2, 1, 2);

				mesh.Drop();

				clockTick.UpdateAbsolutePosition();
				boundingBox.AddInternalBox(clockTick.BoundingBoxTransformed);
				for (int i = 0; i < clockTick.MaterialCount; i++) materialList.Add(clockTick.GetMaterial(i));
			}

			// add hour arrow

			mesh = SceneManager.GeometryCreator.CreateArrowMesh(12, 12, 40, 35, 4, 4, new Color(40, 40, 255), new Color(40, 40, 255));
			arrowHours = SceneManager.AddMeshSceneNode(mesh, this);
			arrowHours.GetMaterial(0).EmissiveColor = new Color(0, 0, 255);
			arrowHours.GetMaterial(1).EmissiveColor = new Color(0, 0, 255);
			arrowHours.Position = new Vector3Df(0, 0, 3);
			mesh.Drop();

			arrowHours.UpdateAbsolutePosition();
			boundingBox.AddInternalBox(arrowHours.BoundingBoxTransformed);
			for (int i = 0; i < arrowHours.MaterialCount; i++) materialList.Add(arrowHours.GetMaterial(i));

			// add minute arrow

			mesh = SceneManager.GeometryCreator.CreateArrowMesh(12, 12, 60, 50, 4, 4, new Color(40, 255, 40), new Color(40, 255, 40));
			arrowMinutes = SceneManager.AddMeshSceneNode(mesh, this);
			arrowMinutes.GetMaterial(0).EmissiveColor = new Color(0, 255, 0);
			arrowMinutes.GetMaterial(1).EmissiveColor = new Color(0, 255, 0);
			arrowMinutes.Position = new Vector3Df(0, 0, -5);
			mesh.Drop();

			arrowMinutes.UpdateAbsolutePosition();
			boundingBox.AddInternalBox(arrowMinutes.BoundingBoxTransformed);
			for (int i = 0; i < arrowMinutes.MaterialCount; i++) materialList.Add(arrowMinutes.GetMaterial(i));

			// add second arrow

			mesh = SceneManager.GeometryCreator.CreateArrowMesh(12, 12, 70, 60, 2, 2, new Color(255, 40, 40), new Color(255, 40, 40));
			arrowSeconds = SceneManager.AddMeshSceneNode(mesh, this);
			arrowSeconds.GetMaterial(0).EmissiveColor = new Color(255, 0, 0);
			arrowSeconds.GetMaterial(1).EmissiveColor = new Color(255, 0, 0);
			arrowSeconds.Position = new Vector3Df(0, 0, -11);
			mesh.Drop();

			arrowSeconds.UpdateAbsolutePosition();
			boundingBox.AddInternalBox(arrowSeconds.BoundingBoxTransformed);
			for (int i = 0; i < arrowSeconds.MaterialCount; i++) materialList.Add(arrowSeconds.GetMaterial(i));

			SceneManager.AddLightSceneNode(arrowSeconds, new Vector3Df(0, 70, 0), new Colorf(arrowSeconds.GetMaterial(0).EmissiveColor), 80);
			SceneManager.AddLightSceneNode(arrowMinutes, new Vector3Df(0, 60, 0), new Colorf(arrowMinutes.GetMaterial(0).EmissiveColor), 60);
			SceneManager.AddLightSceneNode(arrowHours, new Vector3Df(0, 40, 0), new Colorf(arrowHours.GetMaterial(0).EmissiveColor), 40);
		}