bool device_OnEvent(Event evnt) { switch (evnt.Type) { case EventType.Key: { if (OnKeyEvent != null) { OnKeyEvent(evnt); } switch (evnt.Key.Key) { case KeyCode.Esc: { device.Close(); Environment.Exit(0); break; } } break; } case EventType.Mouse: { if (OnMouseEvent != null) { OnMouseEvent(evnt); } break; } } return(false); }
static bool device_OnEvent(Event evnt) { if (evnt.Type == EventType.Key && evnt.Key.PressedDown) { switch (evnt.Key.Key) { case KeyCode.KeyS: isStatsMode = !isStatsMode; return(true); case KeyCode.KeyW: isWireframeMode = !isWireframeMode; return(true); case KeyCode.KeyL: isLabelMode = !isLabelMode; return(true); case KeyCode.Esc: device.Close(); return(true); } } return(false); }
static bool device_OnEvent(Event evnt) { if (evnt.Type == EventType.Mouse) { Dimension2Di s = device.VideoDriver.ScreenSize; if (evnt.Mouse.Type == MouseEventType.Wheel) { Rectd r = new Rectd(); if (evnt.Mouse.Wheel > 0) { // zoom in int x1 = evnt.Mouse.X - s.Width / 2 + (int)evnt.Mouse.Wheel * s.Width / 10; int y1 = evnt.Mouse.Y - s.Height / 2 + (int)evnt.Mouse.Wheel * s.Height / 10; r.UpperLeftCorner = fGen.GetWindowCoord(x1, y1); r.LowerRightCorner = fGen.GetWindowCoord(2 * evnt.Mouse.X - x1, 2 * evnt.Mouse.Y - y1); device.CursorControl.Position = new Vector2Di(s.Width / 2, s.Height / 2); } else { // zoom out int x1 = s.Width / 10; int y1 = s.Height / 10; r.UpperLeftCorner = fGen.GetWindowCoord(-x1, -y1); r.LowerRightCorner = fGen.GetWindowCoord(s.Width + x1, s.Height + y1); } fGen.Generate(r); return(true); } if (evnt.Mouse.Type == MouseEventType.LeftDown) { mouseMoveStart = new Vector2Di(evnt.Mouse.X, evnt.Mouse.Y); return(true); } if (evnt.Mouse.Type == MouseEventType.LeftUp) { Vector2Dd p1 = fGen.GetWindowCoord(evnt.Mouse.X, evnt.Mouse.Y); Vector2Dd p2 = fGen.GetWindowCoord(mouseMoveStart.X, mouseMoveStart.Y); Rectd r = fGen.GetWindow() + p2 - p1; fGen.Generate(r); mouseMoveStart = null; return(true); } } if (evnt.Type == EventType.Key) { if (evnt.Key.PressedDown) { if (evnt.Key.Key == KeyCode.Esc) { device.Close(); return(true); } if (evnt.Key.Key == KeyCode.F1) { showHelp = !showHelp; return(true); } switch (evnt.Key.Char) { case '+': fGen.Generate(fGen.GetMaxIterations() + 1); return(true); case '-': fGen.Generate(fGen.GetMaxIterations() - 1); return(true); case '*': fGen.Generate(fGen.GetMaxIterations() + 10); return(true); case '/': fGen.Generate(fGen.GetMaxIterations() - 10); return(true); } } if (evnt.Key.Key == KeyCode.PrintScreen) // PrintScreen never comes with "evnt.Key.PressedDown == true" so we process it without checking that { string n = "Screenshot-" + DateTime.Now.Ticks + ".png"; Image i = device.VideoDriver.CreateScreenShot(); device.VideoDriver.WriteImage(i, n); i.Drop(); device.Logger.Log("Screenshot saved as " + n); return(true); } } return(false); }
static bool device_OnEvent(Event evnt) { if (evnt.Type == EventType.Mouse && evnt.Mouse.Type == MouseEventType.Move) { Vector2Di m = new Vector2Di(evnt.Mouse.X, evnt.Mouse.Y); Line3Df l = device.SceneManager.SceneCollisionManager.GetRayFromScreenCoordinates(m); Plane3Df p = new Plane3Df(new Vector3Df(0, 0, 0), new Vector3Df(100, 0, 0), new Vector3Df(0, 0, 100)); Vector3Df i = p.GetIntersectionWithLimitedLine(l.Start, l.End); if (i != null) { camera.Target = game.CenterOfTheBoard + new Vector3Df( (m.Y - device.VideoDriver.ScreenSize.Height / 2) / 100.0f, 0, (m.X - device.VideoDriver.ScreenSize.Width / 2) / 100.0f); i.Y += 25; // we want light to be a little bit above light.Position = i; } } if (window == null && evnt.Type == EventType.Mouse && (evnt.Mouse.Type == MouseEventType.LeftDown || evnt.Mouse.Type == MouseEventType.RightDown)) { text.Visible = false; // if user started to play - remove the gui text game.MouseClick(evnt.Mouse.X, evnt.Mouse.Y, evnt.Mouse.Type == MouseEventType.RightDown); if (game.StateOfTheGame != Game.State.Playing) { text.Visible = true; text.Text = game.StateOfTheGame == Game.State.Won ? TextWon : TextLost; } return(true); } if (evnt.Type == EventType.Key && evnt.Key.PressedDown && evnt.Key.Key == KeyCode.Esc) { if (window != null) { window.Remove(); window = null; return(true); } GUIEnvironment gui = device.GUIEnvironment; window = gui.AddWindow(new Recti(100, 100, 400, 400), true, "GAME MENU"); gui.AddButton(new Recti(20, 40, window.ClientRect.Width - 20, 60), window, 1510, "NEW GAME 5x5"); gui.AddButton(new Recti(20, 60, window.ClientRect.Width - 20, 80), window, 1520, "NEW GAME 10x10"); gui.AddButton(new Recti(20, 80, window.ClientRect.Width - 20, 100), window, 1530, "NEW GAME 15x15"); gui.AddButton(new Recti(20, 100, window.ClientRect.Width - 20, 120), window, 1540, "NEW GAME 20x20"); gui.AddCheckBox(optionShadows, new Recti(20, 140, window.ClientRect.Width - 20, 160), "SHOW REALTIME SHADOWS", window, 1710); gui.AddCheckBox(optionBackground, new Recti(20, 160, window.ClientRect.Width - 20, 180), "SHOW BACKGROUND", window, 1720); gui.AddCheckBox(optionFPS, new Recti(20, 180, window.ClientRect.Width - 20, 200), "SHOW FPS", window, 1730); gui.AddButton(new Recti(20, 260, window.ClientRect.Width - 20, 280), window, 1590, "EXIT GAME"); return(true); } if (window != null && evnt.Type == EventType.GUI) { if (evnt.GUI.Caller == window && evnt.GUI.Type == GUIEventType.ElementClosed) { window.Remove(); window = null; return(true); } if (evnt.GUI.Caller.ID == 1510 && evnt.GUI.Type == GUIEventType.ButtonClicked) { window.Remove(); window = null; game.NewGame(5, 5); setupCameraPositionAndTarget(); return(true); } if (evnt.GUI.Caller.ID == 1520 && evnt.GUI.Type == GUIEventType.ButtonClicked) { window.Remove(); window = null; game.NewGame(10, 10); setupCameraPositionAndTarget(); return(true); } if (evnt.GUI.Caller.ID == 1530 && evnt.GUI.Type == GUIEventType.ButtonClicked) { window.Remove(); window = null; game.NewGame(15, 15); setupCameraPositionAndTarget(); return(true); } if (evnt.GUI.Caller.ID == 1540 && evnt.GUI.Type == GUIEventType.ButtonClicked) { window.Remove(); window = null; game.NewGame(20, 20); setupCameraPositionAndTarget(); return(true); } if (evnt.GUI.Caller.ID == 1590 && evnt.GUI.Type == GUIEventType.ButtonClicked) { device.Close(); return(true); } if (evnt.GUI.Caller.ID == 1710 && evnt.GUI.Type == GUIEventType.CheckBoxChanged) { optionShadows = (evnt.GUI.Caller as GUICheckBox).Checked; light.CastShadows = optionShadows; return(true); } if (evnt.GUI.Caller.ID == 1720 && evnt.GUI.Type == GUIEventType.CheckBoxChanged) { optionBackground = (evnt.GUI.Caller as GUICheckBox).Checked; device.SceneManager.GetSceneNodeFromID(7777).Visible = optionBackground; return(true); } if (evnt.GUI.Caller.ID == 1730 && evnt.GUI.Type == GUIEventType.CheckBoxChanged) { optionFPS = (evnt.GUI.Caller as GUICheckBox).Checked; return(true); } } return(false); }
private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; //DeviceSettings settings = e.Argument as DeviceSettings; // create irrlicht device using provided settings if (panelRenderWindow.IsDisposed) { throw new Exception("Form closed!"); } DeviceSettings s = new DeviceSettings( IntPtr.Zero, DriverType.Direct3D9, 0, //antialias new Color(100, 101, 140), false); if (panelRenderWindow.InvokeRequired) { panelRenderWindow.Invoke(new MethodInvoker(delegate { s.WindowID = panelRenderWindow.Handle; })); } dev = IrrlichtDevice.CreateDevice(s); if (dev == null) { throw new NullReferenceException("Could not create device for engine!"); } dev.OnEvent += new IrrlichtDevice.EventHandler(this.device_OnEvent); dev.Logger.LogLevel = LogLevel.Warning; drv = dev.VideoDriver; smgr = dev.SceneManager; gui = dev.GUIEnvironment; _ = smgr.FileSystem.AddFileArchive(activeMod.FileDirectory); smgr.Attributes.AddValue("TW_TW3_LOAD_SKEL", true); smgr.Attributes.AddValue("TW_TW3_LOAD_BEST_LOD_ONLY", true); // added by vl if (meshFile != null && meshFile.Length > 0) { mesh = smgr.GetMesh(meshFile); } if (mesh == null) { throw new Exception("Failed to load mesh."); } mesh.Grab(); smgr.MeshManipulator.RecalculateNormals(mesh); meshLoaded = true; float scaleMul = 1.0f; node = smgr.AddAnimatedMeshSceneNode(mesh); helper = smgr.GetMeshLoader(smgr.MeshLoaderCount - 1).getMeshLoaderHelper(); // hacked to gat witcher3 loader if (node != null && meshLoaded) { node.Scale = new Vector3Df(3.0f); node.SetMaterialFlag(MaterialFlag.Lighting, false); scaleMul = node.BoundingBox.Radius / 4; if (!string.IsNullOrEmpty(rigFile)) { meshToAnimate = helper.loadRig(rigFile, mesh); if (meshToAnimate == null) { throw new Exception("Failed to load rig."); } else { meshToAnimate.Grab(); rigLoaded = true; Logger.LogString("Rig loaded!", Logtype.Success); node.Mesh = meshToAnimate; } } if (!string.IsNullOrEmpty(animFile) && rigLoaded) { animList = helper.loadAnimation(animFile, meshToAnimate); if (animList.Count > 0) { animLoaded = true; Logger.LogString($"{animList.Count} animations loaded! Select animation to play", Logtype.Success); } else { Logger.LogString("No animations loaded!", Logtype.Important); } } setMaterialsSettings(node); } var camera = smgr.AddCameraSceneNode(null, new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0), new Vector3Df(0, node.BoundingBox.Radius, 0)); camera.NearValue = 0.001f; camera.FOV = 45.0f * 3.14f / 180.0f; var animText = activeAnim; var mAnimText = gui.AddStaticText(animText, new Recti(0, this.ClientSize.Height - 80, 100, this.ClientSize.Height - 70)); var mPositionText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 70, 100, this.ClientSize.Height - 60)); var mRotationText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 60, 100, this.ClientSize.Height - 50)); var fpsText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 50, 100, this.ClientSize.Height - 40)); var infoText = gui.AddStaticText("[Space] - Reset\n[LMouse] - Rotate\n[MMouse] - Move\n[Wheel] - Zoom", new Recti(0, this.ClientSize.Height - 40, 100, this.ClientSize.Height)); mAnimText.OverrideColor = mPositionText.OverrideColor = mRotationText.OverrideColor = fpsText.OverrideColor = infoText.OverrideColor = new Color(255, 255, 255); mAnimText.BackgroundColor = mPositionText.BackgroundColor = mRotationText.BackgroundColor = fpsText.BackgroundColor = infoText.BackgroundColor = new Color(0, 0, 0); viewPort = drv.ViewPort; var lineMat = new Material { Lighting = false }; while (dev.Run()) { drv.ViewPort = viewPort; drv.BeginScene(ClearBufferFlag.Depth | ClearBufferFlag.Color, s.BackColor); node.Position = modelPosition; node.Rotation = modelAngle; //update info box mPositionText.Text = $"X: {modelPosition.X.ToString("F2")} Y: {modelPosition.Y.ToString("F2")} Z: {modelPosition.Z.ToString("F2")}"; mRotationText.Text = $"Yaw: {modelAngle.Y.ToString("F2")} Roll: {modelAngle.Z.ToString("F2")}"; fpsText.Text = $"FPS: {drv.FPS}"; smgr.DrawAll(); gui.DrawAll(); // draw xyz axis right bottom drv.ViewPort = new Recti(this.ClientSize.Width - 100, this.ClientSize.Height - 80, this.ClientSize.Width, this.ClientSize.Height); drv.SetMaterial(lineMat); var matrix = new Matrix(new Vector3Df(0, 0, 0), modelAngle); drv.SetTransform(TransformationState.World, matrix); matrix = matrix.BuildProjectionMatrixOrthoLH(100, 80, camera.NearValue, camera.FarValue); drv.SetTransform(TransformationState.Projection, matrix); matrix = matrix.BuildCameraLookAtMatrixLH(new Vector3Df(50, 0, 0), new Vector3Df(0, 0, 0), new Vector3Df(0, 1f, 0)); drv.SetTransform(TransformationState.View, matrix); drv.Draw3DLine(0, 0, 0, 30f, 0, 0, Color.SolidGreen); drv.Draw3DLine(0, 0, 0, 0, 30f, 0, Color.SolidBlue); drv.Draw3DLine(0, 0, 0, 0, 0, 30f, Color.SolidRed); drv.EndScene(); // if we requested to stop, we close the device if (worker.CancellationPending) { dev.Close(); } } // drop device dev.Drop(); }
private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; DeviceSettings settings = e.Argument as DeviceSettings; // create irrlicht device using provided settings IrrlichtDevice dev = IrrlichtDevice.CreateDevice(settings); if (dev == null) { throw new Exception("Failed to create Irrlicht device."); } VideoDriver drv = dev.VideoDriver; SceneManager smgr = dev.SceneManager; // setup a simple 3d scene CameraSceneNode cam = smgr.AddCameraSceneNode(); cam.Target = new Vector3Df(0); SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f); cam.AddAnimator(anim); anim.Drop(); SceneNode cube = smgr.AddCubeSceneNode(20); cube.SetMaterialTexture(0, drv.GetTexture("../../media/wall.bmp")); cube.SetMaterialTexture(1, drv.GetTexture("../../media/water.jpg")); cube.SetMaterialFlag(MaterialFlag.Lighting, false); cube.SetMaterialType(MaterialType.Reflection2Layer); if (settings.BackColor == null) { smgr.AddSkyBoxSceneNode( "../../media/irrlicht2_up.jpg", "../../media/irrlicht2_dn.jpg", "../../media/irrlicht2_lf.jpg", "../../media/irrlicht2_rt.jpg", "../../media/irrlicht2_ft.jpg", "../../media/irrlicht2_bk.jpg"); } dev.GUIEnvironment.AddImage( drv.GetTexture("../../media/lime_logo_alpha.png"), new Vector2Di(30, 0)); // draw all int lastFPS = -1; while (dev.Run()) { if (settings.BackColor == null) { // indeed, we do not need to spend time on cleaning color buffer if we use skybox drv.BeginScene(false); } else { drv.BeginScene(true, true, settings.BackColor); } smgr.DrawAll(); dev.GUIEnvironment.DrawAll(); drv.EndScene(); int fps = drv.FPS; if (lastFPS != fps) { // report progress using common BackgroundWorker' method // note: we cannot do just labelRenderingStatus.Text = "...", // because we are running another thread worker.ReportProgress(fps, drv.Name); lastFPS = fps; } // if we requested to stop, we close the device if (worker.CancellationPending) { dev.Close(); } } // drop device dev.Drop(); }
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; IrrlichtCreationParameters p = new IrrlichtCreationParameters(); p.DriverType = DriverType.Direct3D9; p.WindowID = (IntPtr)e.Argument; IrrlichtDevice device = IrrlichtDevice.CreateDevice(p); if (device == null) { // if device cannot be created by any reason - we just leave this thread, // after all IsRedering will report false, so it is all OK. return; } VideoDriver driver = device.VideoDriver; SceneManager smgr = device.SceneManager; GUIEnvironment gui = device.GUIEnvironment; // setup a simple 3d scene CameraSceneNode cam = smgr.AddCameraSceneNode(); cam.Target = new Vector3Df(0); SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f); cam.AddAnimator(anim); anim.Drop(); SceneNode cube = smgr.AddCubeSceneNode(20); cube.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp")); cube.SetMaterialTexture(1, driver.GetTexture("../../media/water.jpg")); cube.SetMaterialFlag(MaterialFlag.Lighting, false); cube.SetMaterialType(MaterialType.Reflection2Layer); smgr.AddSkyBoxSceneNode( "../../media/irrlicht2_up.jpg", "../../media/irrlicht2_dn.jpg", "../../media/irrlicht2_lf.jpg", "../../media/irrlicht2_rt.jpg", "../../media/irrlicht2_ft.jpg", "../../media/irrlicht2_bk.jpg"); gui.AddImage( driver.GetTexture("../../media/lime_logo_alpha.png"), new Vector2Di(30, 0)); // draw all while (device.Run()) { driver.BeginScene(false); smgr.DrawAll(); gui.DrawAll(); // draw stats int x = 20; int y = driver.ScreenSize.Height - 50; driver.Draw2DRectangle( new Recti(x, y, x + driver.ScreenSize.Width - 2 * x, y + 30), new IrrlichtLime.Video.Color(0, 0, 0, 128)); device.GUIEnvironment.BuiltInFont.Draw( "Driver: " + driver.Name, new Vector2Di(x + 5, y + 5), new IrrlichtLime.Video.Color(255, 255, 255)); device.GUIEnvironment.BuiltInFont.Draw( "FPS: " + driver.FPS.ToString(), new Vector2Di(x + 5, y + 15), new IrrlichtLime.Video.Color(255, 255, 255)); driver.EndScene(); // check for cancellation if (worker.CancellationPending) { device.Close(); } // check for new command lock (backgroundCommand) { switch (backgroundCommand.Type) { case Command.Kind.Resized: driver.ResizeNotify(backgroundCommand.Value as Dimension2Di); backgroundCommand.Clear(); break; } } } // drop the device device.Drop(); }
static void OnMenuItemSelected(GUIContextMenu menu) { guiID id = (guiID)menu.SelectedCommandID; GUIEnvironment env = device.GUIEnvironment; switch (id) { case guiID.OpenModel: // FilOnButtonSetScalinge -> Open Model env.AddFileOpenDialog("Please select a model file to open"); break; case guiID.SetModelArchive: // File -> Set Model Archive env.AddFileOpenDialog("Please select your game archive/directory"); break; case guiID.LoadAsOctree: // File -> LoadAsOctree octree = !octree; menu.SetItemChecked(menu.SelectedIndex, octree); break; case guiID.Quit: // File -> Quit device.Close(); break; case guiID.SkyBoxVisible: // View -> Skybox menu.SetItemChecked(menu.SelectedIndex, !menu.GetItemChecked(menu.SelectedIndex)); skybox.Visible = !skybox.Visible; break; case guiID.DebugOff: // View -> Debug Information -> Off for (int i = 1; i <= 6; i++) { menu.SetItemChecked(menu.SelectedIndex + i, false); } if (model != null) { model.DebugDataVisible = DebugSceneType.Off; } break; case guiID.DebugBoundingBox: // View -> Debug Information -> Bounding Box menu.SetItemChecked(menu.SelectedIndex, !menu.GetItemChecked(menu.SelectedIndex)); if (model != null) { model.DebugDataVisible ^= DebugSceneType.BBox; } break; case guiID.DebugNormals: // View -> Debug Information -> Normals menu.SetItemChecked(menu.SelectedIndex, !menu.GetItemChecked(menu.SelectedIndex)); if (model != null) { model.DebugDataVisible ^= DebugSceneType.Normals; } break; case guiID.DebugSkeleton: // View -> Debug Information -> Skeleton menu.SetItemChecked(menu.SelectedIndex, !menu.GetItemChecked(menu.SelectedIndex)); if (model != null) { model.DebugDataVisible ^= DebugSceneType.Skeleton; } break; case guiID.DebugWireOverlay: // View -> Debug Information -> Wire overlay menu.SetItemChecked(menu.SelectedIndex, !menu.GetItemChecked(menu.SelectedIndex)); if (model != null) { model.DebugDataVisible ^= DebugSceneType.MeshWireOverlay; } break; case guiID.DebugHalfTransparent: // View -> Debug Information -> Half-Transparent menu.SetItemChecked(menu.SelectedIndex, !menu.GetItemChecked(menu.SelectedIndex)); if (model != null) { model.DebugDataVisible ^= DebugSceneType.HalfTransparency; } break; case guiID.DebugBuffersBoundingBoxes: // View -> Debug Information -> Buffers bounding boxes menu.SetItemChecked(menu.SelectedIndex, !menu.GetItemChecked(menu.SelectedIndex)); if (model != null) { model.DebugDataVisible ^= DebugSceneType.BBoxBuffers; } break; case guiID.DebugAll: // View -> Debug Information -> All for (int i = 1; i <= 6; i++) { menu.SetItemChecked(menu.SelectedIndex - i, true); } if (model != null) { model.DebugDataVisible = DebugSceneType.Full; } break; case guiID.About: // Help->About showAboutText(); break; case guiID.ModelMaterialSolid: // View -> Material -> Solid if (model != null) { model.SetMaterialType(MaterialType.Solid); } break; case guiID.ModelMaterialTransparent: // View -> Material -> Transparent if (model != null) { model.SetMaterialType(MaterialType.TransparentAddColor); } break; case guiID.ModelMaterialReflection: // View -> Material -> Reflection if (model != null) { model.SetMaterialType(MaterialType.SphereMap); } break; case guiID.CameraMaya: setActiveCamera(camera[0]); break; case guiID.CameraFirstPerson: setActiveCamera(camera[1]); break; } }
private void irrThreadProcessCommandQueue() { Command c; lock (commandQueue) { if (commandQueue.Count == 0) { return; } c = commandQueue.Dequeue(); } switch (c.Type) { case CommandType.Abort: { irrDevice.Close(); break; } case CommandType.Axes: { irrThreadShowAxes((bool)c.Param); break; } case CommandType.Plane: { var n = irrDevice.SceneManager.GetSceneNodeFromID((int)SceneNodeID.Plane); n.Visible = (bool)c.Param; break; } case CommandType.Particle: { var n = irrDevice.SceneManager.GetSceneNodeFromID((int)SceneNodeID.ParticleSystem); n.SetMaterialTexture(0, irrDevice.VideoDriver.GetTexture(((ParticleInfo)c.Param).FileName)); break; } case CommandType.Resize: { int[] i = (int[])c.Param; Dimension2Di d = new Dimension2Di(i[0], i[1]); irrDevice.VideoDriver.ResizeNotify(d); (irrDevice.SceneManager.GetSceneNodeFromID((int)SceneNodeID.Camera) as CameraSceneNode).AspectRatio = i[2] == 1 ? (float)i[0] / i[1] : 1.333333f; break; } case CommandType.Position: { float[] f = (float[])c.Param; var p = irrDevice.SceneManager.GetSceneNodeFromID((int)SceneNodeID.ParticleSystem) as ParticleSystemSceneNode; (p.Emitter as ParticleSphereEmitter).Center = new Vector3Df(f[0], f[1], f[2]); break; } case CommandType.Radius: { float f = (float)c.Param; var p = irrDevice.SceneManager.GetSceneNodeFromID((int)SceneNodeID.ParticleSystem) as ParticleSystemSceneNode; (p.Emitter as ParticleSphereEmitter).Radius = f; break; } case CommandType.CameraView: { float f = (float)c.Param; var p = irrDevice.SceneManager.GetSceneNodeFromID((int)SceneNodeID.Camera) as CameraSceneNode; p.Target = new Vector3Df(p.Target.X, f, p.Target.Z); break; } case CommandType.Rate: { int v = (int)c.Param; var p = irrDevice.SceneManager.GetSceneNodeFromID((int)SceneNodeID.ParticleSystem) as ParticleSystemSceneNode; p.Emitter.MaxParticlesPerSecond = v; p.Emitter.MinParticlesPerSecond = v / 2; break; } case CommandType.Size: { int v = (int)c.Param; var p = irrDevice.SceneManager.GetSceneNodeFromID((int)SceneNodeID.ParticleSystem) as ParticleSystemSceneNode; p.Emitter.MaxStartSize = new Dimension2Df(v); p.Emitter.MinStartSize = new Dimension2Df(v / 2); break; } case CommandType.Direction: { float[] f = (float[])c.Param; var p = irrDevice.SceneManager.GetSceneNodeFromID((int)SceneNodeID.ParticleSystem) as ParticleSystemSceneNode; p.Emitter.Direction = new Vector3Df(f[0], f[1], f[2]); break; } case CommandType.FadeOut: { affFadeOut.Enabled = (bool)c.Param; break; } case CommandType.Rotation: { affRotation.Enabled = (bool)c.Param; break; } case CommandType.Gravity: { affGravity.Enabled = (bool)c.Param; break; } default: throw new InvalidOperationException("Unexpected command type: " + c.Type.ToString()); } }
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; } } } }
static bool device_OnEvent(Event e) { if (e.Type == EventType.GUI) { int id = e.GUI.Caller.ID; GUIEnvironment env = device.GUIEnvironment; switch (e.GUI.Type) { case GUIEventType.ScrollBarChanged: if (id == GUI_ID_ScrollbarTransparency) { int pos = ((GUIScrollBar)e.GUI.Caller).Position; foreach (GUIDefaultColor which in Enum.GetValues(typeof(GUIDefaultColor))) { Color color = env.Skin.GetColor(which); color.Alpha = pos; env.Skin.SetColor(color, which); } } break; case GUIEventType.ButtonClicked: switch (id) { case GUI_ID_ButtonQuit: device.Close(); return(true); case GUI_ID_ButtonWindowNew: listbox.AddItem("Window created"); winPosCounter += 30; if (winPosCounter > 200) { winPosCounter = 0; } int c = winPosCounter; GUIWindow window = env.AddWindow(new Recti(100 + c, 100 + c, 300 + c, 200 + c), false, "Test window"); env.AddStaticText("Please close me", new Recti(35, 35, 140, 50), true, false, window); return(true); case GUI_ID_ButtonFileOpen: listbox.AddItem("File open"); // There are some options for the file open dialog // We set the title, make it a modal window, and make sure // that the working directory is restored after the dialog // is finished. env.AddFileOpenDialog("Please choose a file", true, null, -1, true); return(true); default: return(false); } case GUIEventType.FileDialogFileSelected: { // show the filename, selected in the file dialog GUIFileOpenDialog d = e.GUI.Caller as GUIFileOpenDialog; listbox.AddItem(d.FileName); break; } default: break; } } return(false); }
private void frmTerrain_KeyDown(object sender, KeyEventArgs e) { var cam = smgr.ActiveCamera; float cameraspeed = 100f; switch (e.KeyCode) { case Keys.Escape: { device.Close(); irrThread.Abort(); this.Close(); break; } case Keys.W: { var vec = (cam.Target - cam.Position).Normalize() * cameraspeed; cam.Position += vec; cam.Target += vec; break; } case Keys.S: { var vec = (cam.Target - cam.Position).Normalize() * cameraspeed; cam.Position -= vec; cam.Target -= vec; break; } case Keys.A: { var vec = (cam.Target - cam.Position).Normalize().DotProduct(cam.Target.Normalize()) * cameraspeed; cam.Position -= vec; cam.Target -= vec; break; } case Keys.D: { var vec = (cam.Target - cam.Position).Normalize().DotProduct(cam.Target.Normalize()) * cameraspeed; cam.Position += vec; cam.Target += vec; break; } case Keys.P: { Console.WriteLine("--------- DEBUG ---------"); Console.WriteLine($"[DEBUG] Camera position - (X - {cam.Position.X}, Y - {cam.Position.Y}, Z - {cam.Position.Z})"); Console.WriteLine("--------- DEBUG ---------"); break; } case Keys.Q: { Console.WriteLine("[INFO] Mouse released!"); device.CursorControl.Visible = true; Cursor.Show(); catchmouse = false; middletext = gui.AddStaticText("Click to enable mouselook and move with WASD", new Recti(ClientSize.Width / 2 - 100, this.ClientSize.Height / 2, ClientSize.Width / 2 + 100, this.ClientSize.Height / 2 + 30), true, true, null, 1, true); middletext.OverrideColor = IrrlichtLime.Video.Color.SolidWhite; middletext.BackgroundColor = IrrlichtLime.Video.Color.SolidBlack; break; } } }
private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; DeviceSettings settings = e.Argument as DeviceSettings; // create irrlicht device using provided settings IrrlichtDevice dev = IrrlichtDevice.CreateDevice(settings); if (dev == null) { throw new Exception("Failed to create Irrlicht device."); } dev.Logger.LogLevel = LogLevel.Warning; VideoDriver drv = dev.VideoDriver; SceneManager smgr = dev.SceneManager; smgr.FileSystem.AddFileArchive("E:/WitcherMods/modTest/Test/files/Mod/Bundle"); smgr.FileSystem.AddFileArchive("E:/WitcherMods/modTest/Test/files/Raw/Mod/TextureCache"); smgr.Attributes.AddValue("TW_TW3_LOAD_SKEL", true); smgr.Attributes.AddValue("TW_TW3_LOAD_BEST_LOD_ONLY", true); // setup a simple 3d scene //CameraSceneNode cam = smgr.AddCameraSceneNode(); //cam.Target = new Vector3Df(0); // added by vl AnimatedMesh mesh = smgr.GetMesh("E:/WitcherMods/modTest/Test/files/Mod/Bundle/characters/models/animals/cat/model/t_01__cat.w2mesh"); if (mesh == null) { throw new Exception("Failed to load mesh."); } smgr.MeshManipulator.RecalculateNormals(mesh); List <String> animList = null; float scaleMul = 1.0f; AnimatedMeshSceneNode node = smgr.AddAnimatedMeshSceneNode(mesh); MeshLoaderHelper helper = smgr.GetMeshLoader(smgr.MeshLoaderCount - 1).getMeshLoaderHelper(); if (node != null) { scaleMul = node.BoundingBox.Radius / 4; node.Scale = new Vector3Df(3.0f); node.SetMaterialFlag(MaterialFlag.Lighting, false); SkinnedMesh sm = helper.loadRig("E:/WitcherMods/modTest/Test/files/Mod/Bundle/characters/base_entities/cat_base/cat_base.w2rig", mesh); if (sm == null) { throw new Exception("Failed to load rig."); } animList = helper.loadAnimation("E:/WitcherMods/modTest/Test/files/Mod/Bundle/animations/animals/cat/cat_animation.w2anims", sm); if (animList.Count > 0) { AnimatedMesh am = helper.applyAnimation(animList[0], sm); node.Mesh = am; } //scaleSkeleton(sm, 3.0f); //sm.SkinMesh(); mesh.Drop(); sm.Drop(); setMaterialsSettings(node); /* * animList = helper.loadAnimation("E:/WitcherMods/modTest/Test/files/Mod/Bundle/animations/animals/cat/cat_animation.w2anims", node); * if (animList.Count > 0) * { * helper.applyAnimation(animList[0]); * } */ } var camera = smgr.AddCameraSceneNode(null, new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0), new Vector3Df(0, node.BoundingBox.Radius, 0) ); camera.NearValue = 0.001f; camera.FOV = 45.0f * 3.14f / 180.0f; node.DebugDataVisible ^= DebugSceneType.BBox | DebugSceneType.Skeleton; node.Position = new Vector3Df(0.0f); /* * SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f); * cam.AddAnimator(anim); * anim.Drop(); * * SceneNode cube = smgr.AddCubeSceneNode(20); * cube.SetMaterialTexture(0, drv.GetTexture("../../media/wall.bmp")); * cube.SetMaterialTexture(1, drv.GetTexture("../../media/water.jpg")); * cube.SetMaterialFlag(MaterialFlag.Lighting, false); * cube.SetMaterialType(MaterialType.Reflection2Layer); */ if (settings.BackColor == null) { smgr.AddSkyBoxSceneNode( "../../media/irrlicht2_up.jpg", "../../media/irrlicht2_dn.jpg", "../../media/irrlicht2_lf.jpg", "../../media/irrlicht2_rt.jpg", "../../media/irrlicht2_ft.jpg", "../../media/irrlicht2_bk.jpg"); } dev.GUIEnvironment.AddImage( drv.GetTexture("../../media/lime_logo_alpha.png"), new Vector2Di(30, 0)); // draw all int lastFPS = -1; while (dev.Run()) { if (settings.BackColor == null) { // indeed, we do not need to spend time on cleaning color buffer if we use skybox drv.BeginScene(ClearBufferFlag.Depth); } else { drv.BeginScene(ClearBufferFlag.Depth | ClearBufferFlag.Color, settings.BackColor); } smgr.DrawAll(); dev.GUIEnvironment.DrawAll(); drv.EndScene(); int fps = drv.FPS; if (lastFPS != fps) { // report progress using common BackgroundWorker' method // note: we cannot do just labelRenderingStatus.Text = "...", // because we are running another thread worker.ReportProgress(fps, drv.Name); lastFPS = fps; } // if we requested to stop, we close the device if (worker.CancellationPending) { dev.Close(); } } // drop device dev.Drop(); }