void OnKeyboardPress(KeyEvent eventArgs) { if (LKernel.GetG<InputSwallowerManager>().IsSwallowed()) return; Kart kart = LKernel.GetG<PlayerManager>().MainPlayer.Kart; Vector3 pos; Quaternion quat; switch (eventArgs.key) { case KeyCode.KC_NUMPAD0: pos = new Vector3(122.245f, 55f, 135.99f); quat = new Quaternion(0.3107f, 0.001f, 0.9505f, 0.0029f); break; default: return; } Matrix4 mat = new Matrix4(); mat.MakeTransform(pos, Vector3.UNIT_SCALE, quat); kart.Body.WorldTransform = mat; kart.Body.Activate(); }
/// <summary> /// set the offset to zero so when we switch back to being active, we don't start zooming off /// </summary> public override void OnSwitchToInactive(LCamera newCamera) { base.OnSwitchToInactive(newCamera); Offset = Vector3.ZERO; moveMultiplier = DEFAULT_MOVE_MULTIPLIER; turnMultiplier = DEFAULT_TURN_MULTIPLIER; }
public override void Update(float timeSinceLastFrame) { base.Update(timeSinceLastFrame); CameraPosition += new Vector3(v.x, 0, v.z); if (CameraCS.HasCameraTarget) { CameraCS.TargetNode.Position += new Vector3(v.x, 0, v.z); v = new Vector3(0, 0, 0); } }
void OnKeyboardPress(KeyEvent eventArgs) { if (LKernel.GetG<InputSwallowerManager>().IsSwallowed()) return; Kart kart = LKernel.GetG<PlayerManager>().MainPlayer.Kart; Vector3 pos; Quaternion quat; switch (eventArgs.key) { case KeyCode.KC_NUMPAD0: pos = new Vector3(-50.8083f, -6.74291f, 324.711f) / 5f; quat = new Quaternion(0.7039f, 0, 0.7102f, 0); break; case KeyCode.KC_NUMPAD1: pos = new Vector3(-282.546f, 20.7933f, 327.82f) / 5f; quat = new Quaternion(0.7789f, 0, 0.627f, 0); break; case KeyCode.KC_NUMPAD2: pos = new Vector3(-354.992f, -3.4451f, -204.558f) / 5f; quat = new Quaternion(1, 0, 0, 0); break; case KeyCode.KC_NUMPAD3: pos = new Vector3(-305.8f, 45.4037f, -693.169f) / 5f; quat = new Quaternion(0.7143f, 0, -0.6998f, 0); break; case KeyCode.KC_NUMPAD4: pos = new Vector3(79.2f, 45.2845f, -696.161f) / 5f; quat = new Quaternion(0.70514f, 0, -0.709f, 0); break; case KeyCode.KC_NUMPAD5: pos = new Vector3(283.799f, 14.8f, -350.52f) / 5f; quat = new Quaternion(0, 0, 1, 0); break; case KeyCode.KC_NUMPAD6: pos = new Vector3(218.534f, 2.806f, -13.362f) / 5f; quat = new Quaternion(0.8834f, 0, 0.4686f, 0); break; case KeyCode.KC_NUMPAD7: pos = new Vector3(85.0738f, -2.5893f, 114.471f) / 5f; quat = new Quaternion(-0.0593f, 0, 0.9982f, 0); break; default: return; } // I copied all of the rotations wrong so we need to rotate them by 180 degrees around the Y axis quat = quat * new Quaternion(0, 0, 1, 0); Matrix4 mat = new Matrix4(); mat.MakeTransform(pos, Vector3.UNIT_SCALE, quat); kart.Body.WorldTransform = mat; kart.Body.Activate(); }
protected Vector3 GetTranslation() { var mTranslation = new Vector3(0, 0, 0); mTranslation.z = State.InputManger.IsKeyDown(KeyCode.KC_W) ? -TRANSLATE : mTranslation.z; mTranslation.z = State.InputManger.IsKeyDown(KeyCode.KC_S) ? TRANSLATE : mTranslation.z; mTranslation.y = State.InputManger.IsKeyDown(KeyCode.KC_Q) ? -TRANSLATE : mTranslation.y; mTranslation.y = State.InputManger.IsKeyDown(KeyCode.KC_E) ? TRANSLATE : mTranslation.y; mTranslation.x = State.InputManger.IsKeyDown(KeyCode.KC_A) ? -TRANSLATE : mTranslation.x; mTranslation.x = State.InputManger.IsKeyDown(KeyCode.KC_D) ? TRANSLATE : mTranslation.x; if (State.InputManger.InputJoyStick != null && mTranslation.Equals(new Vector3())) mTranslation = TranslateJoystick(); return mTranslation; }
bool FrameStarted(FrameEvent evt) { if (elapsed >= 0.1f) { elapsed = 0; var mainPlayer = LKernel.GetG<PlayerManager>().MainPlayer; if (label.Visible && LKernel.GetG<LevelManager>().IsValidLevel && mainPlayer != null && mainPlayer.Kart != null && !mainPlayer.Kart.Body.IsDisposed) { Kart kart = mainPlayer.Kart; Mogre.Vector3 axisA = new Mogre.Vector3(0,1,0); Quaternion quat1; quat1 = kart.ActualOrientation.XAxis.GetRotationTo(axisA); label.Text = string.Format( @"Speed: {0} Turn angle: {1}, {2}, {3}, {4} Linear velocity: {5}, {6} Wheel friction: {7}, {8} Skid info: {9}, {10} Brake? {11} AccelMultiplier: {12} IntOr: {13} Gravity: {14} KartDriftState: {15} , WheelDriftState: {16} Player Pos: {17} X, {18} Y, {19} Z Quat: {20} Quat W: {21}", kart.VehicleSpeed, Math.RadiansToDegrees(kart.Vehicle.GetSteeringValue(0)), Math.RadiansToDegrees(kart.Vehicle.GetSteeringValue(1)), Math.RadiansToDegrees(kart.Vehicle.GetSteeringValue(2)), Math.RadiansToDegrees(kart.Vehicle.GetSteeringValue(3)), kart.Body.LinearVelocity.Length, kart.Body.LinearVelocity, kart.Vehicle.GetWheelInfo(0).FrictionSlip, kart.Vehicle.GetWheelInfo(2).FrictionSlip, kart.Vehicle.GetWheelInfo(0).SkidInfo, kart.Vehicle.GetWheelInfo(2).SkidInfo, kart.WheelFL.IsBrakeOn, kart.Acceleration, kart.InterpolatedOrientation, kart.Body.Gravity, kart.DriftState, kart.WheelFL.DriftState, mainPlayer.NodePosition.x, mainPlayer.NodePosition.y, mainPlayer.NodePosition.z, quat1, quat1.w*180/Math.PI); } } elapsed += evt.timeSinceLastFrame; return true; }
public void CreatePlane( string materialName, Mogre.Vector3 rkNormals, float consts, int width, int height, int xsegements, int ysegements, ushort numTexCoords, int uTile, int vTile, Mogre.Vector3 upVector, Mogre.Vector3 initPosition) { ScenePlane plane = new ScenePlane(gameObjects.Count, world, rkNormals, consts, materialName, ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, width, height, xsegements, ysegements, true, numTexCoords, uTile, vTile, upVector, initPosition); if (!gameObjects.ContainsKey("PLANE")) { gameObjects.Add("PLANE", new List <GameObject>()); } gameObjects["PLANE"].Add(plane); }
private void setupBody(SceneManager sceneMgr) { mBodyNode = sceneMgr.RootSceneNode.CreateChildSceneNode(Mogre.Vector3.UNIT_Y * CHAR_HEIGHT); mBodyEnt = sceneMgr.CreateEntity("SinbadBody" + Id, "Sinbad.mesh"); mBodyEnt.QueryFlags = (uint)QUERY_MASK.AGENT_QUERY_MASK; mBodyNode.AttachObject(mBodyEnt); mBodyNode.Position = mSpawnPos; // create swords and attach to sheath mSword1 = sceneMgr.CreateEntity("SinbadSword1" + Id, "Sword.mesh"); mSword2 = sceneMgr.CreateEntity("SinbadSword2" + Id, "Sword.mesh"); mBodyEnt.AttachObjectToBone("Sheath.L", mSword1); mBodyEnt.AttachObjectToBone("Sheath.R", mSword2); // create a couple of ribbon trails for the swords, just for fun NameValuePairList paramslist = new NameValuePairList(); paramslist["numberOfChains"] = "2"; paramslist["maxElements"] = "80"; mSwordTrail = (RibbonTrail)sceneMgr.CreateMovableObject("RibbonTrail", paramslist); //mSwordTrail.MaterialName=("Examples/LightRibbonTrail"); mSwordTrail.TrailLength = 20; mSwordTrail.Visible = (false); sceneMgr.RootSceneNode.AttachObject(mSwordTrail); for (uint i = 0; i < 2; i++) { mSwordTrail.SetInitialColour(i, 1f, 0.8f, 0f); mSwordTrail.SetColourChange(i, 0.75f, 1.25f, 1.25f, 1.25f); mSwordTrail.SetWidthChange(i, 1); mSwordTrail.SetInitialWidth(i, 0.5f); } mKeyDirection = Mogre.Vector3.ZERO; mVerticalVelocity = 0; }
/// <summary> /// Create a scene prop that player can control /// </summary> /// <param name="scenePropID"></param> /// <param name="position"></param> public void CreatePlayerSceneProp(string scenePropID, Mogre.Vector3 position) { var findSceneProps = modData.SceneProps.Where(o => o.ID == scenePropID); if (findSceneProps.Count() > 0) { var findSceneProp = findSceneProps.ElementAt(0); var findModelTypes = modData.ModModelTypes.Where(o => o.Name == findSceneProp.ModelType); if (findModelTypes.Count() > 0) { var findModelType = findModelTypes.ElementAt(0); object[] MeshMaterialArray = findModelType.Process(modData, findSceneProp.Model) as object[]; Item attachedItem = null; if (MeshMaterialArray.Length == 3) { attachedItem = MeshMaterialArray[2] as Item; } SceneProp sceneProp = new SceneProp( gameObjects.Count, world, findSceneProp.Name, MeshMaterialArray[0].ToString(), MeshMaterialArray[1].ToString(), position, attachedItem ); if (!gameObjects.ContainsKey(scenePropID)) { gameObjects.Add(scenePropID, new List <GameObject>()); } string guidStr = Guid.NewGuid().ToString(); sceneProp.SetID(guidStr); player = new Player(findSceneProp.Name, guidStr, new ControlObjectTypeSceneProp(sceneProp)); } } }
/// <summary> /// Move the specific scene prop with movement /// </summary> /// <param name="propInstanceID">Scene Prop ID</param> /// <param name="axis">Axis 0 - X, 1 - Y, 2 - Z</param> /// <param name="movement">movement</param> public void MoveSceneProp(string propInstanceID, int axis, int movement) { Mogre.Vector3 mov = new Mogre.Vector3(); switch (axis) { case 0: //X Axis mov.x = movement; break; case 1: //Y Axis mov.y = movement; break; case 2: //Z Axis mov.z = movement; break; } SceneProp prop = GetSceneProp(propInstanceID); if (prop != null) { prop.Move(mov); } }
public override void init() { #region ground MeshManager.Singleton.CreatePlane("ground", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, new Plane(Mogre.Vector3.UNIT_Y, 0), 1500, 1500, 20, 20, true, 1, 5, 5, Mogre.Vector3.UNIT_Z); // Create a ground plane entities.Add(OgreWindow.Instance.mSceneMgr.CreateEntity("GroundEntity", "ground")); entities["GroundEntity"].CastShadows = false; entities["GroundEntity"].SetMaterialName("dirt"); nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("ground")); nodes["ground"].AttachObject(entities["GroundEntity"]); nodes["ground"].Position = new Mogre.Vector3(0f, 0f, 0f) + Location().toMogre; // the actor properties control the mass, position and orientation // if you leave the body set to null it will become a static actor and wont move ActorDesc actorDesc2 = new ActorDesc(); actorDesc2.Density = 4; actorDesc2.Body = null; actorDesc2.GlobalPosition = nodes["ground"].Position; actorDesc2.GlobalOrientation = nodes["ground"].Orientation.ToRotationMatrix(); PhysXHelpers.StaticMeshData meshdata = new PhysXHelpers.StaticMeshData(entities["GroundEntity"].GetMesh()); actorDesc2.Shapes.Add(PhysXHelpers.CreateTriangleMesh(meshdata)); Actor actor2 = null; try { actor2 = OgreWindow.Instance.scene.CreateActor(actorDesc2); } catch (System.AccessViolationException ex) { log(ex.ToString()); } if (actor2 != null) { // create our special actor node to tie together the scene node and actor that we can update its position later ActorNode actorNode2 = new ActorNode(nodes["ground"], actor2); actors.Add(actorNode2); } #endregion lights.Add(OgreWindow.Instance.mSceneMgr.CreateLight("playerLight")); lights["playerLight"].Type = Light.LightTypes.LT_POINT; lights["playerLight"].Position = Location().toMogre; lights["playerLight"].DiffuseColour = ColourValue.White; lights["playerLight"].SpecularColour = ColourValue.White; #region drone OgreWindow.Instance.skeletons["\\Drone.skeleton"].Load(); OgreWindow.Instance.meshes["\\Drone.mesh"].Load(); OgreWindow.Instance.meshes["\\Drone.mesh"].SkeletonName = "\\Drone.skeleton"; entities.Add(OgreWindow.Instance.mSceneMgr.CreateEntity("drone", "\\Drone.mesh")); entities["drone"].CastShadows = true; walkState = entities["drone"].GetAnimationState("walk"); walkState.Enabled = true; walkState.Loop = true; entities["drone"].SetMaterialName("metal"); nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("drone")); nodes["drone"].AttachObject(entities["drone"]); nodes["drone"].Position = new Mogre.Vector3(0f, 40f, 0f) + Location().toMogre; nodes["drone"].Scale(new Mogre.Vector3(.3f)); nodes.Add(nodes["drone"].CreateChildSceneNode("orbit0")); nodes.Add(nodes["orbit0"].CreateChildSceneNode("orbit")); nodes["orbit"].Position = Location().toMogre; nodes["orbit"].AttachObject(OgreWindow.Instance.mCamera); nodes["drone"].SetFixedYawAxis(true); #endregion //#region baseball //entities.Add(OgreWindow.Instance.mSceneMgr.CreateEntity("baseball", "\\baseball.mesh")); //entities["baseball"].SetMaterialName("baseball"); ////nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("baseball")); //nodes.Add(nodes["drone"].CreateChildSceneNode("baseball")); //nodes["baseball"].AttachObject(entities["baseball"]); //nodes["baseball"].SetScale(.5f, .5f, .5f); //nodes["baseball"].SetPosition(-3f, 7f, 3f); //// nodes["baseball"].SetScale(5f, 5f, 5f); //#endregion #region player physics bcd = new BoxControllerDesc(); control = OgreWindow.Instance.physics.ControllerManager.CreateController(OgreWindow.Instance.scene, bcd); //System.NullReferenceException #endregion nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("suspensionY")); OgreWindow.g_m.MouseMoved += new MouseListener.MouseMovedHandler(mouseMoved); middlemousetimer.reset(); middlemousetimer.start(); this.btnLimiter_F.reset(); this.btnLimiter_F.start(); ready = true; new Thread(new ThreadStart(controlThread)).Start(); new Thread(new ThreadStart(statusUpdaterThread)).Start(); localY = nodes["drone"]._getDerivedOrientation() * Mogre.Vector3.UNIT_Y; localZ = nodes["drone"]._getDerivedOrientation() * Mogre.Vector3.UNIT_Z; localX = nodes["drone"]._getDerivedOrientation() * Mogre.Vector3.UNIT_X; OgreWindow.Instance.tbTextToSend.GotFocus += new EventHandler(tbTextToSend_GotFocus); OgreWindow.Instance.tbTextToSend.LostFocus += new EventHandler(tbTextToSend_LostFocus); OgreWindow.Instance.tbConsole.GotFocus += new EventHandler(tbConsole_GotFocus); OgreWindow.Instance.tbConsole.LostFocus += new EventHandler(tbConsole_LostFocus); }
private unsafe uint ReadVertexData(uint vertexOffset, VertexData vertexData) { VertexElement posElem = vertexData.vertexDeclaration.FindElementBySemantic(VertexElementSemantic.VES_POSITION); HardwareVertexBufferSharedPtr vertexBuffer = vertexData.vertexBufferBinding.GetBuffer(posElem.Source); byte* vertexMemory = (byte*)vertexBuffer.Lock(HardwareBuffer.LockOptions.HBL_READ_ONLY); float* pElem; for (uint i = 0; i < vertexData.vertexCount; i++) { posElem.BaseVertexPointerToElement(vertexMemory, &pElem); Mogre.Vector3 point = new Mogre.Vector3(pElem[0], pElem[1], pElem[2]); vertices[vertexOffset] = point * this.scale; vertexMemory += vertexBuffer.VertexSize; vertexOffset++; } vertexBuffer.Unlock(); return vertexOffset; }
protected virtual void Translate(Vector3 amount) { State.CameraManager.CameraNode.MoveForward(amount); }
SceneNode CreateNode(Vector3 pos, string meshFile, string material = "yellowbrick") { SceneNode boxNode = sceneMgr.RootSceneNode.CreateChildSceneNode(); Entity ent = sceneMgr.CreateEntity(meshFile); ent.CastShadows = true; boxNode.AttachObject(ent); boxNode.Position = pos; ent.SetMaterialName(material); return boxNode; }
private Vector FromWinScreenToWorldPosition(IntPtr hwnd, IntPtr param) { RECT rect; // unpack x and y from the param double x = unchecked((short)(long)param); double y = unchecked((short)((long)param >> 16)); Vector worldPos = Vector.Zero; // get the size of the screen so we can tell how big we are. // this could be cahced in the future if we wanted to // should be done if we need the performance if(GetWindowRect( hwnd, out rect)) { double width = rect.Right - rect.Left; double height = rect.Bottom - rect.Top; //convert the positions to relative to top left corner. top left 0,0 bottom right 1,1 double relx = x/ width; double rely = y / height; double cameraWidth = m_Camera.OrthoWindowWidth; double cameraHeight = m_Camera.OrthoWindowHeight; //calc a corner for the camera. //should be top left corner Vector3 cornerPosition = m_Camera.Position - new Vector3(cameraWidth / 2.0, 0, cameraHeight / 2.0); //camera coordinates decrease as the go down so subtract the z value Vector3 inputPosition = new Vector3( relx * cameraWidth, 0 ,(1 - rely) * cameraHeight); Vector3 worldVector = cornerPosition + inputPosition; worldPos = new Vector(worldVector.z, worldVector.x); } return worldPos; }
public string CreateSceneProp(string scenePropID, Mogre.Vector3 position) { return(GameMapManager.Instance.CurrentMap.CreateSceneProp(scenePropID, position)); }
public override void inbox(ExtraMegaBlob.References.Event ev) { if (!ready) { return; } switch (ev._Keyword) { case KeyWord.PLAYER_RESET: chat("resetting player"); Quaternion q = new Quaternion( float.Parse(ev._Memories[KeyWord.DATA_QUATERNION_W].Value), float.Parse(ev._Memories[KeyWord.DATA_QUATERNION_X].Value), float.Parse(ev._Memories[KeyWord.DATA_QUATERNION_Y].Value), float.Parse(ev._Memories[KeyWord.DATA_QUATERNION_Z].Value)); Mogre.Vector3 v = new Mogre.Vector3( float.Parse(ev._Memories[KeyWord.DATA_VECTOR3_X].Value), float.Parse(ev._Memories[KeyWord.DATA_VECTOR3_Y].Value), float.Parse(ev._Memories[KeyWord.DATA_VECTOR3_Z].Value)); resetPlayer2(v, q); break; case KeyWord.CMD_GO: this.logConsole("parsing coordinates"); string arguments = ev._Memories[KeyWord.DATA_STRING].Value.Trim(); if (arguments == "") { return; } //" -63.60852f, 95.18869f, -115.0435f " //resetPlayer2(v, q); string[] x = arguments.Split(','); int a = 0; Mogre.Vector3 u = new Mogre.Vector3(); try { for (int s = 0; s < x.Length; s++) { string j = x[s].Trim().Replace("f", ""); if (j != "") { switch (a) { case 0: u.x = float.Parse(j); a++; break; case 1: u.y = float.Parse(j); a++; break; case 2: u.z = float.Parse(j); a++; break; default: break; } } } } catch { } resetPlayer2(u, nodes["drone"].Orientation); this.logConsole("coordinates: " + u.ToString()); break; case KeyWord.PLAYER_FREEZE: player_freeze = true; break; case KeyWord.PLAYER_UNFREEZE: player_freeze = false; break; default: break; } }
private void updateBody(float deltaTime) { goalDirection = Mogre.Vector3.ZERO; // we will calculate this if (keyDirection != Mogre.Vector3.ZERO && baseAnim.Type != ChaAnimType.CAT_CUSTOME_BLOCK) { // calculate actually goal direction in world based on player's key directions goalDirection += keyDirection.z * cameraNode.Orientation.ZAxis; goalDirection += keyDirection.x * cameraNode.Orientation.XAxis; goalDirection.y = 0; goalDirection.Normalise(); Quaternion toGoal = entityNode.Orientation.ZAxis.GetRotationTo(goalDirection); // calculate how much the character has to turn to face goal direction float yawToGoal = toGoal.Yaw.ValueDegrees; // this is how much the character CAN turn this frame float yawAtSpeed = yawToGoal / Mogre.Math.Abs(yawToGoal) * deltaTime * TURN_SPEED; // reduce "turnability" if we're in midair if (baseAnim.Type == ChaAnimType.CAT_JUMP_LOOP) { yawAtSpeed *= 0.2f; } // turn as much as we can, but not more than we need to if (yawToGoal < 0) { yawToGoal = System.Math.Min(0, System.Math.Max(yawToGoal, yawAtSpeed)); //yawToGoal = Math::Clamp<Real>(yawToGoal, yawAtSpeed, 0); } else if (yawToGoal > 0) { yawToGoal = System.Math.Max(0, System.Math.Min(yawToGoal, yawAtSpeed)); //yawToGoal = Math::Clamp<Real>(yawToGoal, 0, yawAtSpeed); } entityNode.Yaw(new Degree(yawToGoal)); // move in current body direction (not the goal direction) var dist = deltaTime * RUN_SPEED /* * baseAnim.AnimationState.Weight*/; Mogre.Vector3 displacement = new Mogre.Vector3(0, 0, dist); entityNode.Translate(displacement.x, displacement.y, displacement.z, Node.TransformSpace.TS_LOCAL); /*Get world movement*/ displacement = entityNode.Orientation * displacement; ControllerFlags flag; physicsController.Move(displacement, 0, 0.01f, out flag); entityNode.Position = new Mogre.Vector3( physicsController.Actor.GlobalPosition.x, entityNode.Position.y, physicsController.Actor.GlobalPosition.z); } if (baseAnim.Type == ChaAnimType.CAT_JUMP_LOOP) { // if we're jumping, add a vertical offset too, and apply gravity entityNode.Translate(0, verticalVelocity * deltaTime, 0, Node.TransformSpace.TS_LOCAL); verticalVelocity -= GRAVITY * deltaTime; Mogre.Vector3 pos = entityNode.Position; if (pos.y <= CHAR_HEIGHT * lastPosition.y) { // if we've hit the ground, change to landing state pos.y = CHAR_HEIGHT * lastPosition.y; entityNode.Position = pos; ControllerFlags flag; physicsController.Move(pos, 1 << 3, 0.01f, out flag); entityNode.Position = physicsController.Actor.GlobalPosition; SetBaseAnimation(anims.Where(o => o.Type == ChaAnimType.CAT_JUMP_END).First(), true); timer = 0; } } }
public void UpdateAutoCameraPosition(float time) { if (ActiveCamera == null) return; if (this.newCamPosition != Mogre.Vector3.ZERO) { Mogre.Vector3 curPos = ActiveCamera.DerivedPosition; Mogre.Vector3 diff = this.newCamPosition - curPos; if (diff.Length > 0.03f) { curPos += diff * System.Math.Min(time * 3.0f, 1.0f); } else { this.newCamPosition = Mogre.Vector3.ZERO; } ActiveCamera.DerivedPosition = curPos; } }
private BaseEditor GetObjectUnderMouse(Ray mouseRay, bool pickWidgets, bool pickTerrain) { Mogre.Entity result; Mogre.Vector3 hitLocation = new Mogre.Vector3(); Mogre.RaySceneQuery raySceneQuery = MogitorsRoot.Instance.SceneManager.CreateRayQuery(new Mogre.Ray()); BaseEditor selected = null; AxisType editorAxis = AxisType.None; if (pickWidgets && MogitorsRoot.Instance.PickGizmos(mouseRay, ref editorAxis)) { selected = MogitorsRoot.Instance.Selected; EditorAxis = editorAxis; } else { raySceneQuery.QueryMask = ~QueryFlags.Widget; if (MogitorsRoot.Instance.PickEntity(raySceneQuery, mouseRay, out result, hitLocation, "", -1.0f) && result.Name != "HydraxMeshEnt") { selected = MogitorsRoot.Instance.FindObject(result.Name, 0); } } MogitorsRoot.Instance.SceneManager.DestroyQuery(raySceneQuery); return selected; }
public void TranslateBody(Mogre.Vector3 vector3) { entityNode.Translate(vector3); }
/// <summary> /// Moves in visible mood, it means when planet is in active solar system. /// </summary> /// <param name="delay">The delay between last two frames</param> public override void Rotate(float delay) { Update(delay); sceneNode.Roll(new Mogre.Degree((float)(GetProperty<float>(PropertyEnum.Speed).Value * GetProperty<float>(PropertyEnum.Rotate).Value * delay))); if (!mFlying) { if (NextLocation()) { mFlying = true; nextPostion = circularPositions.First.Value; // Get the next destination. PrepareNextPosition(); // Update the direction and the distance mDirection = nextPostion - position.Value; mDistance = mDirection.Normalise(); } else { }// Nothing to do so stay in position } else { double move = GetProperty<float>(PropertyEnum.Speed).Value * delay; mDistance -= move; if (mDistance <= .0f) { // Reached destination sceneNode.Position = nextPostion; position.Value = nextPostion; mDirection = Mogre.Vector3.ZERO; mFlying = false; } else { sceneNode.Translate(mDirection * (float)move); position.Value = sceneNode.Position; } } }
public void MoveTo(Mogre.Vector3 destPos) { movementController.MoveTo(destPos); }
private void resetPlayer2(Mogre.Vector3 loc, Quaternion orient) { //MoveScale_Camera_forwardback = control.Actor.GlobalPosition.z - loc.z; //MoveScale_Camera_leftright = control.Actor.GlobalPosition.x - loc.x; //MoveScale_Camera_updown = control.Actor.GlobalPosition.y - loc.y; //Mogre.Vector3 loc1 = control.Actor.GlobalPosition; pauseUpdates(); Mogre.Vector3 loc2 = control.Actor.GlobalOrientationQuaternion * loc; setPos(loc2 + loc); TranslateVector_Camera = new Mogre.Vector3(0f, 0f, 0f); MoveScale_Camera_forwardback = 0f; MoveScale_Camera_leftright = 0f; MoveScale_Camera_updown = 0f; // setPos(loc); setOrient(orient); unPauseUpdates(); }
internal void Pan(float dx, float dz) { v = CameraCS.CameraOrientation * ((Mogre.Vector3.UNIT_Z * -dz) + (Mogre.Vector3.UNIT_X * -dx)); //CameraPosition += new Vector3(v.x, 0, v.z); }
private void statusUpdaterThread() { while (ready) { Thread.Sleep(1); if (updateThreadPaused) continue; updatingNow = true; if (!control.Actor.IsDisposed) { if (MoveScale_Camera_forwardback != 0 || MoveScale_Camera_leftright != 0 || MoveScale_Camera_updown != 0) { TranslateVector_Camera.z -= MoveScale_Camera_forwardback; TranslateVector_Camera.x -= MoveScale_Camera_leftright; TranslateVector_Camera.y += MoveScale_Camera_updown; Mogre.Vector3 loc1 = control.Actor.GlobalPosition; Mogre.Vector3 loc = control.Actor.GlobalOrientationQuaternion * TranslateVector_Camera; setPos(loc + loc1); if (LocationBeaconInterval.elapsed) { sendLocationBeacon(); LocationBeaconInterval.start(); } TranslateVector_Camera = new Mogre.Vector3(); } if (middleMouseMode == middleMouseBehavior.orbitCamDistance) { if (middleMouseState == middleMouseStates.scrolldown) { camDistance -= .1f; if (camDistance < 0f) camDistance = 0f; updateCam(); } if (middleMouseState == middleMouseStates.scrollup) { camDistance += .1f; if (camDistance > 100f) camDistance = 100f; updateCam(); } } if (turning_left) setOrient(control.Actor.GlobalOrientationQuaternion * ModifyAngleAroundAxis(new Degree(2 * .001f), new Mogre.Vector3(0, 1, 0))); if (turning_right) setOrient(control.Actor.GlobalOrientationQuaternion * ModifyAngleAroundAxis(new Degree(-2 * .001f), new Mogre.Vector3(0, 1, 0))); } updatingNow = false; } }
public void Update(float frameTime) { /*if((this.mMousePos.x < 1 || this.mMousePos.x >= this.mOgreForm.Size.Width - 1 || * this.mMousePos.y < 1 || this.mMousePos.y >= this.mOgreForm.Size.Height - 1) && this.BlockMouse) { * Cursor.Position = new System.Drawing.Point(this.mOgreForm.Location.X + this.mOgreForm.Size.Width / 2, * this.mOgreForm.Location.Y + this.mOgreForm.Size.Height / 2); * this.mUpdateMovement = false; * this.mMousePos = new Mogre.Vector3(Cursor.Position.X, Cursor.Position.Y, this.mMousePos.z); * }*/ XmlNodeList nodes = this.mCommands.ChildNodes[1].ChildNodes; if (this.GamePadState.IsConnected) { if (this.mTimeToVibrate > 0) { this.mTimeToVibrate -= frameTime; } if (this.mTimeToVibrate < 0) { this.Vibrate(0, 0); } this.Yaw = this.GamePadState.ThumbSticks.Right.X * 6.5f; this.Pitch = -this.GamePadState.ThumbSticks.Right.Y * 6.5f; this.mMovementFactor = new Mogre.Vector3(-this.GamePadState.ThumbSticks.Left.X, 0, this.GamePadState.ThumbSticks.Left.Y); } this.mKeyBoard.Capture(); int i = 0; for (; i < 6; i++) // Continuous event { float value = this.GetFloatValue(nodes[i]); switch (nodes[i].Attributes[0].Value) { case "MoveLeft": this.mMovementFactor.x += value; break; case "MoveRight": this.mMovementFactor.x -= value; break; case "MoveUp": this.mMovementFactor.y += value; break; case "MoveDown": this.mMovementFactor.y -= value; break; case "MoveForward": this.mMovementFactor.z += value; break; case "MoveBack": this.mMovementFactor.z -= value; break; } } this.Yaw += this.MouseMove.x; this.Yaw *= YAW_SENSIVITY; this.Pitch += this.MouseMove.y; this.Pitch *= PITCH_SENSIVITY; for (; i < nodes.Count; i++) // Single event { int actionId = (int)Enum.Parse(typeof(UserAction), nodes[i].Attributes[0].Value); bool newValue = this.GetBoolValue(nodes[i]); if (newValue && !this.mUserActions[actionId]) { this.mUserActionsOccured[actionId] = true; } if (!newValue && this.mUserActions[actionId]) { this.mUserActionsEnded[actionId] = true; } this.mUserActions[actionId] = newValue; } }
public virtual void OnMouseWheel(Vector2 point, float delta, MouseDevice mouseDevice) { this.lastMouse = point; this.lastMouseDevice = mouseDevice; if (ActiveCamera == null) return; Mogre.Vector3 vPos = ActiveCamera.DerivedPosition; Mogre.Vector3 vDelta = new Mogre.Vector3(0, 0, delta / 16.0f) * CameraSpeed; vPos = vPos - (ActiveCamera.DerivedOrientation * vDelta); this.newCamPosition = vPos; }
public void CreateCharacter(string characterID, Mogre.Vector3 position, string teamId, bool isBot = true) { GameMapManager.Instance.GetCurrentMap().CreateCharacter(characterID, position, teamId, isBot); }
private Vector FromScreenToWorldPosition(double mouseX, double mouseY) { var windowHeight = m_Camera.OrthoWindowHeight; var windowWidth = m_Camera.OrthoWindowWidth; Vector3 cameraPosition = m_Camera.Position; Vector3 cornerPosition = cameraPosition - new Vector3(windowWidth / 2, 0, windowHeight / 2); cornerPosition.y = 0; var mouseOffset = new Vector3(windowHeight * (1.0 - mouseY / 800.0), 0, windowWidth * mouseX / 800.0); var desiredPosition = cornerPosition + mouseOffset; return new Vector(desiredPosition.x, desiredPosition.z); }
public void CreateSceneProp(string meshName, Mogre.Vector3 position) { GameMapManager.Instance.GetCurrentMap().CreateSceneProp(meshName, position); }
protected override void Translate(Vector3 amount) { State.SubNode.MoveForward(amount); }
public void CreatePlane(string materialName, Mogre.Vector3 vector31, float v1, int v2, int v3, int v4, int v5, ushort v6, int v7, int v8, Mogre.Vector3 vector32, Mogre.Vector3 vector33) { GameMapManager.Instance.GetCurrentMap().CreatePlane(materialName, vector31, v1, v2, v3, v4, v5, v6, v7, v8, vector32, vector33); }
private void Initiliase(MeshPtr meshPtr, Mogre.Vector3 scale) { this.scale = scale; this.meshPtr = meshPtr; PrepareBuffers(); ReadData(); }
public void MoveTo(Mogre.Vector3 destPos) { controller.MoveTo(destPos); }
private static bool Plane(int collisionid, Body body, Quaternion orientation, Vector3 position, ref Plane retplane) { return true; }
//MeshPtr CreateMesh(string Name, string Group, IndexData IndexDataArg, VertexData VertexDataArg, AxisAlignedBox BoundingBox) { // Mogre.Mesh Mesh = Mogre.MeshManager.Singleton.CreateManual(Name, Group,null); // SubMesh SubMesh = Mesh.CreateSubMesh(); // //Shallow copy the IndexBuffer argument into the SubMesh's indexData property // SubMesh.indexData.indexBuffer = IndexDataArg.indexBuffer; // SubMesh.indexData.indexCount = IndexDataArg.indexCount; // //Deep copy the VertexData argument into the Mesh's sharedVertexData // SubMesh.useSharedVertices = true; // Mesh.sharedVertexData = new VertexData(); // Mesh.sharedVertexData.vertexBufferBinding.SetBinding(0, VertexDataArg.vertexBufferBinding.GetBuffer(0)); // Mesh.sharedVertexData.vertexDeclaration = VertexDataArg.vertexDeclaration.Clone(); // Mesh.sharedVertexData.vertexCount = VertexDataArg.vertexCount; // Mesh._setBounds(BoundingBox); // Mesh.Load(); // return Mesh; //} unsafe static public void CreateSphere(string strName, float r, int nRings, int nSegments) { MeshPtr pSphere = Mogre.MeshManager.Singleton.CreateManual(strName, ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME); SubMesh pSphereVertex = pSphere.CreateSubMesh(); pSphere.sharedVertexData = new VertexData(); VertexData vertexData = pSphere.sharedVertexData; // define the vertex format VertexDeclaration vertexDecl = vertexData.vertexDeclaration; uint currOffset = 0; // positions vertexDecl.AddElement(0, currOffset, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_POSITION); currOffset += VertexElement.GetTypeSize(VertexElementType.VET_FLOAT3); // normals vertexDecl.AddElement(0, currOffset, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_NORMAL); currOffset += VertexElement.GetTypeSize(VertexElementType.VET_FLOAT3); // two dimensional texture coordinates vertexDecl.AddElement(0, currOffset, VertexElementType.VET_FLOAT2, VertexElementSemantic.VES_TEXTURE_COORDINATES, 0); currOffset += VertexElement.GetTypeSize(VertexElementType.VET_FLOAT2); // allocate the vertex buffer vertexData.vertexCount = (uint)((nRings + 1) * (nSegments + 1)); HardwareVertexBufferSharedPtr vBuf = HardwareBufferManager.Singleton.CreateVertexBuffer(vertexDecl.GetVertexSize(0), vertexData.vertexCount, HardwareBuffer.Usage.HBU_STATIC_WRITE_ONLY, false); VertexBufferBinding binding = vertexData.vertexBufferBinding; binding.SetBinding(0, vBuf); float *pVertex = (float *)vBuf.Lock(HardwareBuffer.LockOptions.HBL_DISCARD); // allocate index buffer pSphereVertex.indexData.indexCount = (uint)(6 * nRings * (nSegments + 1)); pSphereVertex.indexData.indexBuffer = HardwareBufferManager.Singleton.CreateIndexBuffer(Mogre.HardwareIndexBuffer.IndexType.IT_16BIT, pSphereVertex.indexData.indexCount, HardwareBuffer.Usage.HBU_STATIC_WRITE_ONLY, false); HardwareIndexBufferSharedPtr iBuf = pSphereVertex.indexData.indexBuffer; ushort *pIndices = (ushort *)iBuf.Lock(HardwareBuffer.LockOptions.HBL_DISCARD); float fDeltaRingAngle = (float)(Mogre.Math.PI / nRings); float fDeltaSegAngle = (float)(2 * Mogre.Math.PI / nSegments); ushort wVerticeIndex = 0; // Generate the group of rings for the sphere for (int ring = 0; ring <= nRings; ring++) { float r0 = r * Mogre.Math.Sin(ring * fDeltaRingAngle); float y0 = r * Mogre.Math.Cos(ring * fDeltaRingAngle); // Generate the group of segments for the current ring for (int seg = 0; seg <= nSegments; seg++) { float x0 = r0 * Mogre.Math.Sin(seg * fDeltaSegAngle); float z0 = r0 * Mogre.Math.Cos(seg * fDeltaSegAngle); // Add one vertex to the strip which makes up the sphere *pVertex++ = x0; *pVertex++ = y0; *pVertex++ = z0; Mogre.Vector3 vNormal = (new Mogre.Vector3(x0, y0, z0)).NormalisedCopy; *pVertex++ = vNormal.x; *pVertex++ = vNormal.y; *pVertex++ = vNormal.z; *pVertex++ = (float)seg / (float)nSegments; *pVertex++ = (float)ring / (float)nRings; if (ring != nRings) { // each vertex (except the last) has six indices pointing to it *pIndices++ = (ushort)(wVerticeIndex + nSegments + 1); *pIndices++ = wVerticeIndex; *pIndices++ = (ushort)(wVerticeIndex + nSegments); *pIndices++ = (ushort)(wVerticeIndex + nSegments + 1); *pIndices++ = (ushort)(wVerticeIndex + 1); *pIndices++ = wVerticeIndex; wVerticeIndex++; } } ; // end for seg } // end for ring // Unlock vBuf.Unlock(); iBuf.Unlock(); // Generate face list pSphereVertex.useSharedVertices = true; // the original code was missing this line: pSphere._setBounds(new AxisAlignedBox(new Mogre.Vector3(-r, -r, -r), new Mogre.Vector3(r, r, r)), false); pSphere._setBoundingSphereRadius(r); // this line makes clear the mesh is loaded (avoids memory leaks) pSphere.Load(); }
public override void inbox(ExtraMegaBlob.References.Event ev) { if (!ready) return; switch (ev._Keyword) { case KeyWord.PLAYER_RESET: chat("resetting player"); Quaternion q = new Quaternion( float.Parse(ev._Memories[KeyWord.DATA_QUATERNION_W].Value), float.Parse(ev._Memories[KeyWord.DATA_QUATERNION_X].Value), float.Parse(ev._Memories[KeyWord.DATA_QUATERNION_Y].Value), float.Parse(ev._Memories[KeyWord.DATA_QUATERNION_Z].Value)); Mogre.Vector3 v = new Mogre.Vector3( float.Parse(ev._Memories[KeyWord.DATA_VECTOR3_X].Value), float.Parse(ev._Memories[KeyWord.DATA_VECTOR3_Y].Value), float.Parse(ev._Memories[KeyWord.DATA_VECTOR3_Z].Value)); resetPlayer2(v, q); break; case KeyWord.CMD_GO: this.logConsole("parsing coordinates"); string arguments = ev._Memories[KeyWord.DATA_STRING].Value.Trim(); if (arguments == "") return; //" -63.60852f, 95.18869f, -115.0435f " //resetPlayer2(v, q); string[] x = arguments.Split(','); int a = 0; Mogre.Vector3 u = new Mogre.Vector3(); try { for (int s = 0; s < x.Length; s++) { string j = x[s].Trim().Replace("f", ""); if (j != "") { switch (a) { case 0: u.x = float.Parse(j); a++; break; case 1: u.y = float.Parse(j); a++; break; case 2: u.z = float.Parse(j); a++; break; default: break; } } } } catch { } resetPlayer2(u, nodes["drone"].Orientation); this.logConsole("coordinates: " + u.ToString()); break; case KeyWord.PLAYER_FREEZE: player_freeze = true; break; case KeyWord.PLAYER_UNFREEZE: player_freeze = false; break; default: break; } }
private void mouseTimer_Tick(object sender, EventArgs e) { mousePos.z = 0; lastMousePos = mousePos; }
private Mogre.Vector3 getOrbitalPosition(Mogre.Vector3 focalPoint, Quaternion direction, float distanceToFocalPoint) { Mogre.Vector3 eyePos, xAxis, yAxis, zAxis; Quaternion m_Orientation = direction; Mogre.Matrix3 m_ViewMatrix; // Get the rotation matrix from the quaternion m_ViewMatrix = m_Orientation.ToRotationMatrix(); // Get the axis we need them for the camera position calculation (the axes span a new coord frame) xAxis = new Mogre.Vector3(m_ViewMatrix[0, 0], m_ViewMatrix[0, 1], m_ViewMatrix[0, 2]); yAxis = new Mogre.Vector3(m_ViewMatrix[1, 0], m_ViewMatrix[1, 1], m_ViewMatrix[1, 2]); zAxis = new Mogre.Vector3(m_ViewMatrix[2, 0], m_ViewMatrix[2, 1], m_ViewMatrix[2, 2]); eyePos = focalPoint + zAxis * distanceToFocalPoint; // Transform our vector in the orbital space. Here we rotate and flip it. m_ViewMatrix[0, 3] = -xAxis.DotProduct(eyePos); m_ViewMatrix[1, 3] = -yAxis.DotProduct(eyePos); m_ViewMatrix[2, 3] = -zAxis.DotProduct(eyePos); Mogre.Vector3 m_CamPos = new Mogre.Vector3(); // So extract the cam position for the sake of completeness m_CamPos.x = m_ViewMatrix[0, 3]; m_CamPos.y = m_ViewMatrix[1, 3]; m_CamPos.z = m_ViewMatrix[2, 3]; return m_CamPos; }
public void HandleCameraInput(Keyboard inputKeyboard, Mouse inputMouse, IList <JoyStick> inputJoysticks, FrameEvent evt, Camera camera, Camera minimapCamera, Plane playerPlane) { // Move about 100 units per second, float moveScale = camSpeed * evt.timeSinceLastFrame; // Take about 10 seconds for full rotation Vector3 translateVector = Vector3.ZERO; // set the scaling of camera motion if (camera != null) { if (inputKeyboard.IsKeyDown(KeyCode.KC_A)) { if (inputKeyboard.IsKeyDown(KeyCode.KC_LSHIFT)) { translateVector.x = -3 * moveScale; } else { translateVector.x = -moveScale; } } if (inputKeyboard.IsKeyDown(KeyCode.KC_D)) { if (inputKeyboard.IsKeyDown(KeyCode.KC_LSHIFT)) { translateVector.x = 3 * moveScale; } else { translateVector.x = moveScale; } } if (inputKeyboard.IsKeyDown(KeyCode.KC_W)) { if (inputKeyboard.IsKeyDown(KeyCode.KC_LSHIFT)) { translateVector.z = -3 * moveScale; } else { translateVector.z = -moveScale; } } if (inputKeyboard.IsKeyDown(KeyCode.KC_S)) { if (inputKeyboard.IsKeyDown(KeyCode.KC_LSHIFT)) { translateVector.z = 3 * moveScale; } else { translateVector.z = moveScale; } } if (mouseButtons == MouseButtons.Left) { Degree cameraYaw = -mouseDiff.x * .13f; Degree cameraPitch = -mouseDiff.y * .13f; camera.Yaw(cameraYaw); camera.Pitch(cameraPitch); } // ZOOM IN if (mousePos.z > 0) { translateVector.z -= moveScale * 0.1f * mousePos.z; //camera.Position += new Vector3(0, 0, -mouseDiff.z * .05f); } // ZOOM OUT if (mousePos.z < 0) { translateVector.z -= moveScale * 0.1f * mousePos.z; // camera.Position += new Vector3(0, 0, -mouseDiff.z * .05f); } camera.MoveRelative(translateVector); } }
private void spin(Degree deg) { Mogre.Quaternion orient1 = control.Actor.GlobalOrientationQuaternion; Mogre.Vector3 rkAxis = new Mogre.Vector3(); Degree rfAngle = new Degree(); orient1.ToRotationMatrix().ToAxisAngle(out rkAxis, out rfAngle); Mogre.Quaternion orient2 = new Quaternion(new Radian(deg), new Mogre.Vector3(0, 1, 0)); //control.Actor.GlobalOrientationQuaternion = orient2; //setOrient(orient2); setOrient(orient2); }
/// <summary> /// undo anything that happens when we press anything /// </summary> void OnKeyboardRelease_Anything(KeyEvent eventArgs) { if (LKernel.GetG<InputSwallowerManager>().IsSwallowed() || !IsActive) return; switch (eventArgs.key) { case KeyCode.KC_UP: Offset.z += 1; break; case KeyCode.KC_DOWN: Offset.z -= 1; break; case KeyCode.KC_LEFT: Offset.x += 1; break; case KeyCode.KC_RIGHT: Offset.x -= 1; break; case KeyCode.KC_RSHIFT: Offset.y -= 1; break; case KeyCode.KC_RCONTROL: Offset.y += 1; break; } var keyboard = LKernel.GetG<InputMain>().InputKeyboard; if (!keyboard.IsKeyDown(KeyCode.KC_UP) && !keyboard.IsKeyDown(KeyCode.KC_DOWN) && !keyboard.IsKeyDown(KeyCode.KC_LEFT) && !keyboard.IsKeyDown(KeyCode.KC_RIGHT) && !keyboard.IsKeyDown(KeyCode.KC_RSHIFT) && !keyboard.IsKeyDown(KeyCode.KC_RCONTROL)) { Offset = Vector3.ZERO; } }
private void updateCam() { SceneNode camnode = nodes["orbit"]; SceneNode node = nodes["drone"]; Mogre.Vector3 focalPoint = new Mogre.Vector3(0f, 0f, 0f); Quaternion direction = node.Orientation; direction.Normalise(); //Mogre.Vector3 m_CamPos = getOrbitalPosition(focalPoint, direction); //OgreWindow.Instance.cameraNode.LookAt(focalPoint, Node.TransformSpace.TS_PARENT); //OgreWindow.Instance.cameraNode.Position = m_CamPos + focalPoint; Mogre.Vector3 m_CamPos = getOrbitalPosition(focalPoint, direction, camDistance); camnode.Position = m_CamPos; camnode.LookAt(node.Position, Node.TransformSpace.TS_WORLD); }
public void CreatePlayerSceneProp(string scenePropID, Mogre.Vector3 position) { GameMapManager.Instance.CurrentMap.CreatePlayerSceneProp(scenePropID, position); }
protected virtual void OnUpdateModel(FrameEvent evt) { mouseDiff = mousePos - lastMousePos; Degree scaleRotate = rotateSpeed * evt.timeSinceLastFrame; inputKeyboard.Capture(); if (inputJoysticks != null) { foreach (JoyStick j in inputJoysticks) { j.Capture(); } } /* * if (inputKeyboard.IsKeyDown(KeyMap.Instance.Left)) * { * camera.Yaw(scaleRotate); * } * * if (inputKeyboard.IsKeyDown(KeyMap.Instance.Right)) * { * camera.Yaw(-scaleRotate); * } * * if (inputKeyboard.IsKeyDown(KeyMap.Instance.Up)) * { * camera.Pitch(scaleRotate); * } * * if (inputKeyboard.IsKeyDown(KeyMap.Instance.Down)) * { * camera.Pitch(-scaleRotate); * }*/ if (inputJoysticks != null) { Vector2 joyVector = FrameWorkStaticHelper.GetJoystickVector(inputJoysticks, true); if (joyVector.x != 0) { camera.Yaw(-joyVector.x * scaleRotate); } if (joyVector.y != 0) { camera.Pitch(joyVector.y * scaleRotate); } } // subtract the time since last frame to delay specific key presses toggleDelay -= evt.timeSinceLastFrame; // toggle rendering mode if (inputKeyboard.IsKeyDown(KeyCode.KC_R) && toggleDelay < 0) { if (camera.PolygonMode == PolygonMode.PM_POINTS) { camera.PolygonMode = PolygonMode.PM_SOLID; } else if (camera.PolygonMode == PolygonMode.PM_SOLID) { camera.PolygonMode = PolygonMode.PM_WIREFRAME; } else { camera.PolygonMode = PolygonMode.PM_POINTS; } Console.WriteLine("Rendering mode changed to '{0}'.", camera.PolygonMode); toggleDelay = 1; } if (inputKeyboard.IsKeyDown(KeyCode.KC_SYSRQ)) { string[] temp = Directory.GetFiles(Environment.CurrentDirectory, "wscreenshot*.jpg"); string fileName = string.Format("wscreenshot{0}.jpg", temp.Length + 1); TakeScreenshot(fileName); // show briefly on the screen mDebugText = string.Format("Wrote screenshot '{0}'.", fileName); // show for 2 seconds debugTextDelay = 2.0f; } if (inputKeyboard.IsKeyDown(KeyCode.KC_B)) { sceneMgr.ShowBoundingBoxes = !sceneMgr.ShowBoundingBoxes; } if (inputKeyboard.IsKeyDown(KeyCode.KC_F)) { // hide all overlays, includes ones besides the debug overlay viewport.OverlaysEnabled = !viewport.OverlaysEnabled; } // turn off debug text when delay ends if (debugTextDelay < 0.0f) { debugTextDelay = 0.0f; mDebugText = ""; } else if (debugTextDelay > 0.0f) { debugTextDelay -= evt.timeSinceLastFrame; } // inputMouse.Capture(); HandleCameraInput(inputKeyboard, null, inputJoysticks, evt, camera, null, null); }
public virtual void OnMouseMove(Vector2 point, MouseDevice mouseDevice, bool imitate) { this.lastMouseDevice = mouseDevice; if (isSettingPos) { isSettingPos = false; this.lastMouse = point; return; } float deltaX = (point.x - lastMouse.x) * 0.5f; float deltaY = (point.y - lastMouse.y) * 0.5f; MogitorsRoot mogRoot = MogitorsRoot.Instance; BaseEditor selected = mogRoot.Selected; Ray mouseRay; if (!imitate) { if (mouseDevice.MiddleButton == MouseButtonState.Pressed) { Vector3 vPos = ActiveCamera.DerivedPosition; Vector3 vDelta = new Vector3(deltaX * CameraSpeed / 3.0f, -deltaY * CameraSpeed / 3.0f, 0); ActiveCamera.DerivedPosition = (vPos + (ActiveCamera.DerivedOrientation * vDelta)); this.newCamPosition = Vector3.ZERO; MogitorsSystem.Instance.ShowMouseCursor(false); point.x -= (deltaX * 2.0f); point.y -= (deltaY * 2.0f); isSettingPos = true; MogitorsSystem.Instance.SetMousePosition(point + new Vector2(this.handle.ActualLeft, this.handle.ActualTop)); } else if (mouseDevice.RightButton == MouseButtonState.Pressed) { ActiveCamera.Yaw(new Degree(-deltaX / 4.0f)); ActiveCamera.Pitch(new Degree(-deltaY / 4.0f)); MogitorsSystem.Instance.ShowMouseCursor(false); point.x -= (deltaX * 2.0f); point.y -= (deltaY * 2.0f); isSettingPos = true; MogitorsSystem.Instance.SetMousePosition(point + new Vector2(this.handle.ActualLeft, this.handle.ActualTop)); if (!GetMouseRay(point, out mouseRay)) { return; } if (mogRoot.Selected != null) { this.lastUsedPlane = MogitorsRoot.Instance.FindGizmoTranslationPlane(mouseRay, EditorAxis); } } } if (!GetMouseRay(point, out mouseRay)) { return; } if (EditorTool != EditorTools.Rotate || selected == null) { this.lastMouse = point; } if (selected != null) { if (EditorAxis == AxisType.None) { AxisType axis = AxisType.None; mogRoot.PickGizmos(mouseRay, ref axis); mogRoot.HighlightGizmo(axis); } else { mogRoot.HighlightGizmo(EditorAxis); } } if (isEditing && selected != null) { if ((EditorTool == EditorTools.Move) && selected.Supports(EditFlags.CanMove)) { Vector3 vNewPos = Vector3.ZERO; vNewPos = mogRoot.GetGizmoIntersect(mouseRay, this.lastUsedPlane, EditorAxis, this.lastDerivedPosition); vNewPos = vNewPos - this.last3DDelta + this.lastDerivedPosition; selected.DerivedPosition = vNewPos; } else if ((EditorTool == EditorTools.Scale) && selected.Supports(EditFlags.CanScale)) { Vector3 vNewDist = mogRoot.GetGizmoIntersect(mouseRay, this.lastUsedPlane, EditorAxis, this.lastDerivedPosition); Vector3 vScale = this.lastScale; float fNewDist = vNewDist.Length; float fLength = this.last3DDelta.Length; if ((int)(EditorAxis & AxisType.X) != 0) { vScale.x *= (fNewDist / fLength); } if ((int)(EditorAxis & AxisType.Y) != 0) { vScale.y *= (fNewDist / fLength); } if ((int)(EditorAxis & AxisType.Z) != 0) { vScale.z *= (fNewDist / fLength); } PropertyInfo prop = selected.GetType().GetProperty("Scale"); if (prop != null) { prop.SetValue(selected, vScale, null); } } else if ((EditorTool == EditorTools.Rotate) && selected.Supports(EditFlags.CanRotate)) { Quaternion q1 = this.lastDerivedOrient; switch (EditorAxis) { case AxisType.X: q1 = q1 * new Quaternion(new Degree(-deltaY), new Vector3(1, 0, 0)); break; case AxisType.Y: q1 = q1 * new Quaternion(new Degree(-deltaY), new Vector3(0, 1, 0)); break; case AxisType.Z: q1 = q1 * new Quaternion(new Degree(-deltaY), new Vector3(0, 0, 1)); break; } selected.DerivedOrientation = q1; } } HighlightObjectAtPosition(mouseRay); }
private void RenderPanel_MouseMove(object sender, MouseEventArgs e) { mousePos = new Vector3(e.Location.X, e.Location.Y, mousePos.z); }
private void setupCameraControlSystem() { // Ogre::camera points to -Z by default // Create the camera system using the previously created ogre camera. mCameraCS = new CameraControlSystem(sceneMgr, "CameraControlSystem", camera); // ------------------------------------------------------------------------------------- // Register a "Fixed" camera mode. In this mode the camera position and orientation // never change. FixedCameraMode camMode1; camMode1 = new FixedCameraMode(mCameraCS, Vector3.UNIT_Y); //mCameraCS->registerCameraMode("Fixed (2)",camMode1); mCameraCS.RegisterCameraMode("Fixed", camMode1); cameraModeNames.Add("Fixed"); camMode1.CameraPosition = new Vector3(-500, 0, -500); float roll = 0; float yaw = 225; float pitch = 10; camMode1.CameraOrientation = new Quaternion(new Radian(new Degree(roll)), Vector3.UNIT_Z) * new Quaternion(new Radian(new Degree(yaw)), Vector3.UNIT_Y) * new Quaternion(new Radian(new Degree(pitch)), Vector3.UNIT_X); // ------------------------------------------------------------------------------------- // Register a "FixedTracking" camera mode. In this mode the camera position is fixed // and the camera always points to the target. FixedTrackingCameraMode camMode2; camMode2 = new FixedTrackingCameraMode(mCameraCS, Vector3.UNIT_Y); mCameraCS.RegisterCameraMode("FixedTracking", camMode2); cameraModeNames.Add("FixedTracking"); camMode2.CameraPosition = new Vector3(500, 0, -100); // ------------------------------------------------------------------------------------- // Register a "Chase" camera mode with default tightness (0.01). In // this mode the camera follows the target. The second parameter is the relative position // to the target. The orientation of the camera is fixed by a yaw axis (UNIT_Y by default). ChaseCameraMode camMode3; camMode3 = new ChaseCameraMode(mCameraCS, new Vector3(0, 0, -200), Vector3.UNIT_Y); //mCameraCS.registerCameraMode("Chase(0.01 tightness)",camMode3); mCameraCS.RegisterCameraMode("Chase", camMode3); cameraModeNames.Add("Chase"); // ------------------------------------------------------------------------------------- // Register a "ChaseFreeYawAxis" camera mode with max tightness. This mode is // similar to "Chase" camera mode but the camera orientation is not fixed by // a yaw axis. The camera orientation will be the same as the target. camMode3 = new ChaseFreeYawAxisCameraMode(mCameraCS, new Vector3(0, 0, -200) , new Radian(0), new Radian(new Degree(180)), new Radian(0)); mCameraCS.RegisterCameraMode("ChaseFreeYawAxis", camMode3); cameraModeNames.Add("ChaseFreeYawAxis"); camMode3.CameraTightness = 0.05f; // ------------------------------------------------------------------------------------- // Register a "FirstPerson" camera mode. //FirstPersonCameraMode* camMode4 = new FirstPersonCameraMode(mCameraCS,Vector3(0,17,-16) FirstPersonCameraMode camMode4 = new FirstPersonCameraMode(mCameraCS, new Vector3(0, 6, -20) , new Radian(0), new Radian(new Degree(180)), new Radian(0)); mCameraCS.RegisterCameraMode("FirstPerson", camMode4); cameraModeNames.Add("FirstPerson"); camMode4.IsCharacterVisible = false; // ------------------------------------------------------------------------------------- // Register a "PlaneBinded" camera mode. In this mode the camera is constrained to the // limits of a plane. The camera always points to the target, perpendicularly to the plane. Plane mPlane = new Plane(Vector3.UNIT_Z, new Vector3(0, 0, -200)); PlaneBindedCameraMode camMode5 = new PlaneBindedCameraMode(mCameraCS, mPlane, Vector3.UNIT_Y); mCameraCS.RegisterCameraMode("PlaneBinded (XY)", camMode5); cameraModeNames.Add("PlaneBinded (XY)"); // ------------------------------------------------------------------------------------- // Register another "PlaneBinded" camera mode using a top point of view. // mPlane = new Plane(Vector3.UNIT_Y, new Vector3(0, 1000, 0)); // camMode5 = new PlaneBindedCameraMode(mCameraCS, mPlane, Vector3.UNIT_Z); // mCameraCS.registerCameraMode("PlaneBinded (XZ)", camMode5); // cameraModeNames.Add("PlaneBinded (XZ)"); // ------------------------------------------------------------------------------------- // Register a "ThroughTarget" camera mode. In this mode the camera points to a given // position (the "focus") throuh the target. The camera orientation is fixed by a yaw axis. ThroughTargetCameraMode camMode6 = new ThroughTargetCameraMode(mCameraCS, 400, Vector3.ZERO, Vector3.UNIT_Y); mCameraCS.RegisterCameraMode("ThroughTarget", camMode6); cameraModeNames.Add("ThroughTarget"); //camMode6.CameraFocusPosition=atheneNode._getDerivedPosition() - Vector3(0,100,0); camMode6.CameraFocusPosition = atheneNode._getDerivedPosition() + new Vector3(0, 100, 0); // ------------------------------------------------------------------------------------- // Register a "ClosestToTarget" camera mode. In this camera mode the position of the // camera is chosen to be the closest to the target of a given list. The camera // orientation is fixed by a yaw axis. ClosestToTargetCameraMode camMode7 = new ClosestToTargetCameraMode(mCameraCS, Vector3.UNIT_Y); mCameraCS.RegisterCameraMode("ClosestToTarget", camMode7); cameraModeNames.Add("ClosestToTarget"); Vector3 camPos1 = new Vector3(-400, 0, -400); Vector3 camPos2 = new Vector3(-400, 0, 1400); Vector3 camPos3 = new Vector3(1400, 0, 1400); camMode7.AddCameraPosition(camPos1); camMode7.AddCameraPosition(camPos2); camMode7.AddCameraPosition(camPos3); // ------------------------------------------------------------------------------------- // Register an "Attached" camera mode. In this mode the camera node is attached to the // target node as a child. AttachedCameraMode camMode8 = new AttachedCameraMode(mCameraCS, new Vector3(200, 0, 0) , new Radian(0), new Radian(new Degree(90)), new Radian(0)); //mCameraCS.registerCameraMode("Attached (lateral)",camMode8); mCameraCS.RegisterCameraMode("Attached", camMode8); cameraModeNames.Add("Attached"); // ------------------------------------------------------------------------------------- // Register a "Free" camera mode. In this mode the camera is controlled by the user. // The camera orientation is fixed to a yaw axis. yaw = 225; pitch = -10; FreeCameraMode camMode9 = new FreeCameraMode(mCameraCS, Vector3.ZERO, new Degree(yaw), new Degree(pitch) , SwitchingMode.CurrentState); mCameraCS.RegisterCameraMode("Free", camMode9); cameraModeNames.Add("Free"); camMode9.MoveFactor = 30; // ------------------------------------------------------------------------------------- // Register a "FixedDirection" camera mode. In this mode the // target is always seen from the same point of view. FixedDirectionCameraMode camMode10 = new FixedDirectionCameraMode(mCameraCS, new Vector3(-1, -1, -1), 1000, Vector3.UNIT_Y); mCameraCS.RegisterCameraMode("Fixed direction", camMode10); cameraModeNames.Add("Fixed direction"); camMode10.CameraTightness = 0.01f; // ------------------------------------------------------------------------------------- // Register an "Orbital" camera mode. This is basically an attached camera mode where the user // can mofify the camera position. If the scene focus is seen as the center of a sphere, the camera rotates arount it. // The last parameter indicates if the camera should be reset to its initial position when this mode is selected. OrbitalCameraMode camMode12 = new OrbitalCameraMode(mCameraCS, new Radian(0), new Radian(0), 200, false); mCameraCS.RegisterCameraMode("Orbital", camMode12); cameraModeNames.Add("Orbital"); camMode12.ZoomFactor = 100; camMode12.RotationFactor = 50; //camMode12.CollisionsEnabled = true; //camMode12.collisionDelegate = camMode12.DefaultCollisionDetectionFunction; // ** Uncomment for custom collisions calculation. By default the collisions are based on ogre basic raycast feature ** //camMode12.collisionDelegate = CollidableCamera::newCollisionDelegate(this // , &CameraControlSystemDemo::CustomCollisionDetectionFunction); // ------------------------------------------------------------------------------------- // Register a RTS camera mode. // RTSCameraMode camMode13 = new RTSCameraMode(mCameraCS, new Vector3(500, 1300, 1000) , Vector3.NEGATIVE_UNIT_Z , Vector3.NEGATIVE_UNIT_X , new Radian(new Degree(70)) , 0, 1000); mCameraCS.RegisterCameraMode("RTS", camMode13); cameraModeNames.Add("RTS"); camMode13.MoveFactor = 20; // ------------------------------------------------------------------------------------- // Register the custom "Dummy" camera mode defined previously. It basically goes forward // and backward constantly DummyCameraMode camMode14 = new DummyCameraMode(mCameraCS, 400); mCameraCS.RegisterCameraMode("Dummy", (CameraMode)camMode14); cameraModeNames.Add("Dummy"); // ------------------------------------------------------------------------------------- // Register an "OrbitalWithMouse" camera mode. OrbitalWithMouseCameraMode camMode15 = new OrbitalWithMouseCameraMode(mCameraCS, MOIS.MouseButtonID.MB_Left, new Radian(0), new Radian(0), 200); mCameraCS.RegisterCameraMode("Orbital + mouse", camMode15); cameraModeNames.Add("Orbital + mouse"); camMode15.ZoomFactor = 3; camMode15.RotationFactor = 10; // ------------------------------------------------------------------------------------- // Register a spheric camera mode. Vector3 relativePositionToCameraTarget = new Vector3(0, 50, -300); // THIS IS NOT NECESSARY. just needed for the demo showing integer values in the sliders relativePositionToCameraTarget = relativePositionToCameraTarget.NormalisedCopy * 300; SphericCameraMode camMode16 = new SphericCameraMode(mCameraCS, relativePositionToCameraTarget, 700, Vector3.ZERO, Vector3.UNIT_Y); // outer radious = inner radious = relativePositionToCameraTarget.length() for a perfect sphere camMode16.HeightOffset = 50; mCameraCS.RegisterCameraMode("Spherical", camMode16); cameraModeNames.Add("Spherical"); // Set the camera target mCameraCS.TargetNode = headNode; //mCameraCS.CurrentCameraMode=camMode1;// fixed camera of cause works //mCameraCS.CurrentCameraMode=camMode2;//fixed tracking camera works //mCameraCS.CurrentCameraMode=camMode3;//chase camera works //mCameraCS.CurrentCameraMode=camMode4;//first person camera works //mCameraCS.CurrentCameraMode=camMode5;// plane binded (XY) (YZ) camera works //mCameraCS.CurrentCameraMode=camMode6;// through target camera works, cs game //mCameraCS.CurrentCameraMode=camMode7;// closest target camera works //mCameraCS.CurrentCameraMode=camMode8;// attached camera works //mCameraCS.CurrentCameraMode=camMode9;// free camera works //mCameraCS.CurrentCameraMode=camMode10;// fix direction camera works //mCameraCS.CurrentCameraMode = camMode12;// orbital camera works, but the head entity flickered //mCameraCS.CurrentCameraMode=camMode13;// RTS camera works? //mCameraCS.CurrentCameraMode=camMode14;// dummy camera works mCameraCS.CurrentCameraMode = camMode15;// orbital with mouse camera works //mCameraCS.CurrentCameraMode=camMode16;// spherical camera works }
void OnMousePress_Right(MouseEvent eventArg1, MouseButtonID eventArg2) { if (LKernel.GetG<InputSwallowerManager>().IsSwallowed() || !IsActive) return; Vector3 pos = new Vector3(), norm = new Vector3(); if (new MogreRaycaster().RaycastFromPoint(CameraNode.Position, -CameraNode.GetLocalZAxis(), ref pos, ref norm)) { var kart = LKernel.GetG<PlayerManager>().MainPlayer.Kart; kart.Body.Activate(); Matrix4 mat = new Matrix4(); mat.MakeTransform(pos, Vector3.UNIT_SCALE, kart.ActualOrientation); kart.Body.WorldTransform = mat; } }
public override void ProcessParameters(Mogre.NameValuePairList parameters) { Mogre.NameValuePairList.Iterator ni; if ((ni = parameters.Find("Name")) != parameters.End()) this.name = ni.Value; if ((ni = parameters.Find("Dimensions")) != parameters.End()) this.dimensions = MogreX.StringConverter.ParseVector4(ni.Value); if ((ni = parameters.Find("Skies")) != parameters.End()) this.skies = Mogre.StringConverter.ParseBool(ni.Value); if ((ni = parameters.Find("Shadows")) != parameters.End()) this.shadows = Mogre.StringConverter.ParseBool(ni.Value); if ((ni = parameters.Find("Overlays")) != parameters.End()) this.overlays = Mogre.StringConverter.ParseBool(ni.Value); if ((ni = parameters.Find("CamPosition")) != parameters.End()) this.camPosition = Mogre.StringConverter.ParseVector3(ni.Value); if ((ni = parameters.Find("CamOrientation")) != parameters.End()) this.camOrientation = Mogre.StringConverter.ParseQuaternion(ni.Value); if ((ni = parameters.Find("CamClipDistance")) != parameters.End()) this.camClipDistance = MogreX.StringConverter.ParseVector2(ni.Value); if ((ni = parameters.Find("CamPolyMode")) != parameters.End()) { this.camPolyMode = (Mogre.PolygonMode)Mogre.StringConverter.ParseInt(ni.Value); OnPropertyChanged("CamPolyMode"); } if ((ni = parameters.Find("CamFOV")) != parameters.End()) this.camFOV = Mogre.StringConverter.ParseReal(ni.Value); if ((ni = parameters.Find("Colour")) != parameters.End()) this.colour = Mogre.StringConverter.ParseColourValue(ni.Value); this.compositorStorage.Clear(); for (int cx = 0; cx < 100; ++cx) { string searchstr = "Compositor" + Mogre.StringConverter.ToString(cx); if ((ni = parameters.Find(searchstr + "Name")) != parameters.End()) { CompositorPush compData = new CompositorPush(); compData.Name = ni.Value; ni = parameters.Find(searchstr + "Enabled"); compData.Enabled = Mogre.StringConverter.ParseBool(ni.Value); this.compositorStorage.Add(compData); } else break; } }
private void statusUpdaterThread() { while (ready) { Thread.Sleep(1); if (updateThreadPaused) { continue; } updatingNow = true; if (!control.Actor.IsDisposed) { if (MoveScale_Camera_forwardback != 0 || MoveScale_Camera_leftright != 0 || MoveScale_Camera_updown != 0) { TranslateVector_Camera.z -= MoveScale_Camera_forwardback; TranslateVector_Camera.x -= MoveScale_Camera_leftright; TranslateVector_Camera.y += MoveScale_Camera_updown; Mogre.Vector3 loc1 = control.Actor.GlobalPosition; Mogre.Vector3 loc = control.Actor.GlobalOrientationQuaternion * TranslateVector_Camera; setPos(loc + loc1); if (LocationBeaconInterval.elapsed) { sendLocationBeacon(); LocationBeaconInterval.start(); } TranslateVector_Camera = new Mogre.Vector3(); } if (middleMouseMode == middleMouseBehavior.orbitCamDistance) { if (middleMouseState == middleMouseStates.scrolldown) { camDistance -= .1f; if (camDistance < 0f) { camDistance = 0f; } updateCam(); } if (middleMouseState == middleMouseStates.scrollup) { camDistance += .1f; if (camDistance > 100f) { camDistance = 100f; } updateCam(); } } if (turning_left) { setOrient(control.Actor.GlobalOrientationQuaternion * ModifyAngleAroundAxis(new Degree(2 * .001f), new Mogre.Vector3(0, 1, 0))); } if (turning_right) { setOrient(control.Actor.GlobalOrientationQuaternion * ModifyAngleAroundAxis(new Degree(-2 * .001f), new Mogre.Vector3(0, 1, 0))); } } updatingNow = false; } }
protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); #region Avalon DockableContents visibility handling this.panelsByName["Scene"] = this.adcScene; this.panelsByName["Objects"] = this.adcObjects; this.panelsByName["Entity"] = this.adcEntity; this.panelsByName["Properties"] = this.adcProperties; this.panelsByName["Log"] = this.adcLog; this.panelsByName["Materials"] = this.adcMaterials; this.panelsByName["Templates"] = this.adcTemplates; this.panelsByName["Render"] = this.adcRender; IsPanelVisible.DockManager = this.dockManager; IsPanelVisible.Panels = panelsByName; foreach (var iter in this.panelsByName) { iter.Value.StateChanged += (s, args) => { OnPropertyChanged("IsPanelVisible"); }; } #endregion #region Explicit initializations this.sceneView.MainWindow = this; this.propertiesView.ApplyTemplate(); this.entityView.ApplyTemplate(); this.objectsView.ApplyTemplate(); this.objectsView.PrepareView(); MogitorsSystem.Instance.SetWindows(this.ogreControl, this.sceneView.TreeControl, this.propertiesView); MogitorsSystem.Instance.InitTreeIcons(); #endregion #region Log control event this.logControl.LogBuffer = this.logBuffer; Mogre.LogManager.Singleton.DefaultLog.MessageLogged += (message, lml, maskDebug, logName) => { Dispatcher.Invoke((Action)(() => { this.logBuffer.Add(new LogData(DateTime.Now, lml, message, logName)); })); }; #endregion #region MogitorsRoot event MogitorsRoot.Instance.SceneLoaded += (s, args) => { UpdateWindowTitle(); this.entityView.PrepareView(); this.materialView.PrepareView(); this.templateView.PrepareView(); ProjectOptions opt = MogitorsRoot.Instance.ProjectOptions; string recentFileEntry = MogitorsSystem.Instance.GetFullPath(opt.ProjectDir + "/" + opt.ProjectName + ".mogscene"); AddToRecentFiles(recentFileEntry); this.statusString.Text = "Scene loaded"; }; MogitorsRoot.Instance.SceneTerminated += (s, args) => { this.entityView.ClearView(); this.materialView.DestroyScene(); this.templateView.DestroyScene(); UpdateWindowTitle(); this.statusString.Text = "Scene terminated"; }; MogitorsRoot.Instance.IsSceneModifiedChanged += (s, args) => { UpdateWindowTitle(); }; #endregion #region Mogre.Root event Mogre.Root.Singleton.FrameStarted += (FrameEvent evt) => { DisplayFPS(evt.timeSinceLastFrame); MogitorsRoot.Instance.ActiveViewport.UpdateAutoCameraPosition(evt.timeSinceLastFrame); MogitorsRoot.Instance.Update(evt.timeSinceLastFrame); Mogre.Vector3 camPos = MogitorsRoot.Instance.ActiveViewport.CameraEditor.Camera.DerivedPosition; if (this.oldCamPos != camPos) { this.camPosLabel.Text = string.Format("X:{0:0.00}, Y:{1:0.00}, Z:{2:0.00}", camPos.x, camPos.y, camPos.z); oldCamPos = camPos; } return(true); }; Mogre.Root.Singleton.FrameEnded += (FrameEvent evt) => { return(true); }; #endregion }
public override void ProcessParameters(Mogre.NameValuePairList parameters) { Mogre.NameValuePairList.Iterator ni; if ((ni = parameters.Find("Name")) != parameters.End()) { this.name = ni.Value; } if ((ni = parameters.Find("Dimensions")) != parameters.End()) { this.dimensions = MogreX.StringConverter.ParseVector4(ni.Value); } if ((ni = parameters.Find("Skies")) != parameters.End()) { this.skies = Mogre.StringConverter.ParseBool(ni.Value); } if ((ni = parameters.Find("Shadows")) != parameters.End()) { this.shadows = Mogre.StringConverter.ParseBool(ni.Value); } if ((ni = parameters.Find("Overlays")) != parameters.End()) { this.overlays = Mogre.StringConverter.ParseBool(ni.Value); } if ((ni = parameters.Find("CamPosition")) != parameters.End()) { this.camPosition = Mogre.StringConverter.ParseVector3(ni.Value); } if ((ni = parameters.Find("CamOrientation")) != parameters.End()) { this.camOrientation = Mogre.StringConverter.ParseQuaternion(ni.Value); } if ((ni = parameters.Find("CamClipDistance")) != parameters.End()) { this.camClipDistance = MogreX.StringConverter.ParseVector2(ni.Value); } if ((ni = parameters.Find("CamPolyMode")) != parameters.End()) { this.camPolyMode = (Mogre.PolygonMode)Mogre.StringConverter.ParseInt(ni.Value); OnPropertyChanged("CamPolyMode"); } if ((ni = parameters.Find("CamFOV")) != parameters.End()) { this.camFOV = Mogre.StringConverter.ParseReal(ni.Value); } if ((ni = parameters.Find("Colour")) != parameters.End()) { this.colour = Mogre.StringConverter.ParseColourValue(ni.Value); } this.compositorStorage.Clear(); for (int cx = 0; cx < 100; ++cx) { string searchstr = "Compositor" + Mogre.StringConverter.ToString(cx); if ((ni = parameters.Find(searchstr + "Name")) != parameters.End()) { CompositorPush compData = new CompositorPush(); compData.Name = ni.Value; ni = parameters.Find(searchstr + "Enabled"); compData.Enabled = Mogre.StringConverter.ParseBool(ni.Value); this.compositorStorage.Add(compData); } else { break; } } }
protected override void Translate(Vector3 amount) { if (State.InputManger.IsKeyDown(KeyCode.KC_LCONTROL)) State.CameraManager.CameraChildNode.MoveForward(amount); else State.SubNode.MoveForward(amount); }
public void TranslateBody(Mogre.Vector3 vector3) { controller.TranslateBody(vector3); }
public override void InjectMouseMove(MouseEvent arg) { base.InjectMouseMove(arg); Vector2 cursorPos = new Vector2(arg.state.X.abs, arg.state.Y.abs); Ray ray = UIManager.Instance.GetCursorRay(editor.Map.Camera); switch (state) { case EditState.Add: switch (type) { case EditType.EditAIMeshMode: Mogre.Vector3 pos = Helper.ConvertScreenCoordToWorldCoord( lastMousePos, editor.Map.Camera, EngineManager.Instance.renderWindow); HandleObjectCreate(pos); state = EditState.Edit; operation = EditOperation.ChangingObjCoordFllowMouse; break; case EditType.EditObjectMode: break; case EditType.EditTerrainMode: break; } break; case EditState.Edit: switch (type) { case EditType.EditAIMeshMode: Mogre.Vector3 pos = ray.Origin + ray.Direction * distance; HandleObjOperationNoResize(pos, cursorPos); break; case EditType.EditObjectMode: break; case EditType.EditTerrainMode: break; } break; case EditState.Free: Degree deCameraYaw = new Degree(arg.state.X.rel * -0.1f); editor.Map.Camera.Yaw(deCameraYaw); Degree deCameraPitch = new Degree(arg.state.Y.rel * -0.1f); editor.Map.Camera.Pitch(deCameraPitch); if (currentSelectedEnt != null) { currentSelectedEnt.ParentSceneNode.ShowBoundingBox = false; } var query = editor.Map.SceneManager.CreateRayQuery(ray); query.QueryMask = 1 << 0; RaySceneQueryResult result = query.Execute(); foreach (var sResult in result) { if (sResult.movable != null && (sResult.movable.Name.StartsWith("SCENE_OBJECT") || sResult.movable.Name.StartsWith("AIMESH"))) { //High light the object var ent = editor.Map.SceneManager.GetEntity(sResult.movable.Name); MaterialPtr material = ent.GetSubEntity(0).GetMaterial(); ColourValue cv = new ColourValue(1, 0, 0); material.GetTechnique(0).SetAmbient(cv); ColourValue cv2 = new ColourValue(1, 0, 0); material.GetTechnique(0).SetDiffuse(cv2); ent.GetSubEntity(0).SetMaterial(material); ent.ParentSceneNode.ShowBoundingBox = true; currentSelectedEnt = ent; } } break; } lastMousePos = cursorPos; }
/// <summary> /// Converts a 3D scene position to a 2D screen position (in relative screen size, 0.0-1.0). /// </summary> /// <param name="cam"></param> /// <param name="pt"></param> /// <returns></returns> public static Mogre.Vector2 SceneToScreen(Mogre.Camera cam, Mogre.Vector3 pt) { Mogre.Vector3 result = cam.ProjectionMatrix * cam.ViewMatrix * pt; return(new Mogre.Vector2((result.x + 1) / 2, (-result.y + 1) / 2)); }