private void pbImage_MouseUp(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { int soundunit = m_themeManager.MaxDistance * 2; int unitx = (pbImage.Size.Width / soundunit); int unity = (pbImage.Size.Height / soundunit); int posx = 0; // left right posx = (e.X / unitx) - (soundunit / 2); int posy = 0; // up down int posz = 0; // forward backward posz = (e.Y / unity) - (soundunit / 2); SoundVector vec = new SoundVector(posx, posy, -posz); int index = lbEffectSounds.SelectedIndex; if (index == -1) { m_themeManager.PlaySound(0, vec); } else { m_themeManager.PlaySound(index, vec); } } }
/// <summary> /// Create tables for joint elements /// </summary> /// <param name="cn"></param> /// <param name="obj"></param> private void store(OleDbConnection cn, Joint obj) { Microsoft.DirectX.Vector3 pos = obj.Position; string sql = "INSERT INTO [Joint Coordinates](Joint, CoordSys, CoordType, XorR, Y, Z, SpecialJt, GlobalX, GlobalY, GlobalZ) " + "VALUES (" + obj.Id + ", \"GLOBAL\", \"Cartesian\", " + pos.X + ", " + pos.Y + ", " + pos.Z + ", \"Yes\", " + pos.X + ", " + pos.Y + ", " + pos.Z + ");"; new OleDbCommand(sql, cn).ExecuteNonQuery(); float[] masses = obj.Masses; if (masses != null && masses.Length >= 6) { if (masses[0] + masses[1] + masses[2] + masses[3] + masses[4] + masses[5] > float.Epsilon) { sql = "INSERT INTO [Joint Added Mass Assignments](Joint, CoordSys, Mass1, Mass2, Mass3, MMI1, MMI2, MMI3) " + "VALUES (" + obj.Id + ", \"GLOBAL\", " + masses[0] + ", " + masses[1] + ", " + masses[2] + ", " + masses[3] + ", " + masses[4] + ", " + masses[5] + ");"; new OleDbCommand(sql, cn).ExecuteNonQuery(); } } JointDOF dof = obj.DoF; if (dof != null) { store(cn, obj.Id, obj.DoF); } AssignedLoads loads = obj.Loads; if (loads != null) { store(cn, obj.Id, loads); } }
/// <summary> /// Returns whether the argument point is inside this instance. /// </summary> /// <param name="point">The point in world coordinates.</param> /// <returns>Whether the point is inside this.</returns> public bool IsPointInside(ref Vector3 point) { return ((Position.X - point.X) * (Position.X - Position.X) + (Position.Y - point.Y) * (Position.Y - Position.Y) + (Position.Z - point.Z) * (Position.Z - Position.Z) < Radius * Radius); }
/// <summary> /// Performs a bounce collision (a collision which modifies velocity and acceleration), and separates the objects if so. /// </summary> /// <param name="sphere">The Sphere to perform collision against.</param> /// <param name="thisMass">The mass of this instance.</param> /// <param name="otherMass">Th e mass of the argument cube.</param> /// <param name="elasticity">The ratio of velocity to preserve.</param> /// <returns>Whether a collision occurred.</returns> public bool CollideAgainstBounce(Sphere sphere, float thisMass, float otherMass, float elasticity) { #if DEBUG if (thisMass == 0 && otherMass == 0) { throw new ArgumentException("Both masses cannot be 0. For equal masses pick a non-zero value"); } #endif if (CollideAgainstMove(sphere, thisMass, otherMass)) { // Get the relative velocity of this circle to the argument circle: Vector3 relativeVelocity = new Vector3( this.TopParent.XVelocity - sphere.TopParent.XVelocity, this.TopParent.YVelocity - sphere.TopParent.YVelocity, this.TopParent.ZVelocity - sphere.TopParent.ZVelocity); #if FRB_MDX float velocityNormalDotResult = Vector3.Dot(relativeVelocity, LastMoveCollisionReposition); #else float velocityNormalDotResult; Vector3.Dot(ref relativeVelocity, ref LastMoveCollisionReposition, out velocityNormalDotResult); #endif if (velocityNormalDotResult >= 0) { return(true); } #if FRB_MDX //Vector2 tangentVector = new Vector2((float)mLastCollisionTangent.X, (float)mLastCollisionTangent.Y); // Perform the bounce if the relative velocity and the tangent are the opposite direction. Vector3 reverseNormal = -Vector3.Normalize(LastMoveCollisionReposition); float length = Vector3.Dot(relativeVelocity, reverseNormal); Vector3 velocityOnNormal = Vector3.Multiply(reverseNormal, length); #else Vector3 reverseNormal = -LastMoveCollisionReposition; reverseNormal.Normalize(); float length = Vector3.Dot(relativeVelocity, reverseNormal); Vector3 velocityOnNormal; Vector3.Multiply(ref reverseNormal, length, out velocityOnNormal); #endif sphere.TopParent.Velocity.X += (1 + elasticity) * thisMass / (thisMass + otherMass) * velocityOnNormal.X; sphere.TopParent.Velocity.Y += (1 + elasticity) * thisMass / (thisMass + otherMass) * velocityOnNormal.Y; sphere.TopParent.Velocity.Z += (1 + elasticity) * thisMass / (thisMass + otherMass) * velocityOnNormal.Z; this.TopParent.Velocity.X -= (1 + elasticity) * otherMass / (thisMass + otherMass) * velocityOnNormal.X; this.TopParent.Velocity.Y -= (1 + elasticity) * otherMass / (thisMass + otherMass) * velocityOnNormal.Y; this.TopParent.Velocity.Z -= (1 + elasticity) * otherMass / (thisMass + otherMass) * velocityOnNormal.Z; return(true); } return(false); }
public Microsoft.DirectX.Vector3 Get3Dposition(System.Drawing.Point position2D) { Microsoft.DirectX.Vector3 v = new Microsoft.DirectX.Vector3(); v.X = position2D.X * this.fieldWidth; v.Y = 1; v.Z = position2D.Y * this.fieldHeight; return(v); }
public bool IsPositionOnTerainBlocked(Microsoft.DirectX.Vector3 position) { if (this.blockedPosition.Contains(Get2DMapPosition(position))) { return(true); } return(false); }
public System.Drawing.Point Get2DMapPosition(Microsoft.DirectX.Vector3 position) { PointF p = new PointF(position.X, position.Z); int x = (int)(p.X / this.fieldWidth); int y = (int)(p.Y / this.fieldHeight); return(new Point(x, y)); }
public static Vector3 ConvertFrom(Microsoft.DirectX.Vector3 value) { return(new Vector3() { X = value.X, Y = value.Y, Z = value.Z }); }
/// <summary> /// Initializes a new instance of the threeAxisRectangle class with the /// specified location and size. /// </summary> /// <param name="rightLowerPos">The x & y & z coordinate of the lower-right corner of the rectangle.</param> /// <param name="width">The width of the rectangle.</param> /// <param name="height">The height of the rectangle.</param> /// <param name="depth">The depth of the rectangle.</param> public threeAxisRectangle(Microsoft.DirectX.Vector3 rightLowerPos, int width, int height, int depth) { this.x = rightLowerPos.X; this.y = rightLowerPos.Y; this.z = rightLowerPos.Z; this.Width = width; this.Height = height; this.Depth = depth; _rightLowerPos = rightLowerPos; }
public GamePlayEvent(ushort playerId, Constants.GamePlayEventTypeEnumeration eventType, DateTime timestamp,Microsoft.DirectX.Vector3 position,Microsoft.DirectX.Vector3 lookingDirection, Microsoft.DirectX.Vector3 velocity) { this.playerIdField = playerId; this.gameplayEventTypeField = eventType; this.timestampField = timestamp; this.lookingDirectionField = lookingDirection; this.positionField = position; this.velocityField = velocity; }
public static Microsoft.DirectX.Vector3 Normalize(Microsoft.DirectX.Vector3 vect) { Microsoft.DirectX.Vector3 ret = new Microsoft.DirectX.Vector3(); float legnth = GetFourDigitsNumber(Math.Sqrt(vect.X * vect.X + vect.Y * vect.Y + vect.Z * vect.Z).ToString()); ret.X = vect.X / legnth; ret.Y = vect.Y / legnth; ret.Z = vect.Z / legnth; return(ret); }
private void LoadNpcConfig(string path, out List <string> npcNames, out List <string> controlMechanisms, out List <Microsoft.DirectX.Vector3> positions, out List <string> characterNames, out List <string> actions) { controlMechanisms = new List <string>(); npcNames = new List <string>(); positions = new List <Microsoft.DirectX.Vector3>(); characterNames = new List <string>(); actions = new List <string>(); System.Xml.XmlDataDocument doc = new System.Xml.XmlDataDocument(); doc.Load(path); XmlNode rootNode = doc.GetElementsByTagName("List")[0]; foreach (XmlNode npcNode in rootNode.ChildNodes) { foreach (XmlNode node in npcNode.ChildNodes) { switch (node.Name) { case "Name": npcNames.Add(node.InnerText); break; case "Script": controlMechanisms.Add(node.InnerText); break; case "FSM": controlMechanisms.Add(node.InnerText); break; case "Position": Microsoft.DirectX.Vector3 position = new Microsoft.DirectX.Vector3(); int x = Convert.ToInt32(node.ChildNodes[0].InnerText); int z = Convert.ToInt32(node.ChildNodes[1].InnerText); position = terrain.Get3Dposition(new System.Drawing.Point(x, z)); positions.Add(position); break; case "Character": characterNames.Add(node.InnerText); break; case "Actions": actions.Add(node.InnerText); break; } } } }
//public override void Run(Canguro.Controller.CommandServices services) //{ // List<Item> selection = GetSelection(services); // if (selection.Count == 0) // return; // Stream stream = new MemoryStream(); // try // { // BinaryFormatter bformatter = new BinaryFormatter(); // Magnet magnet = services.GetPoint("selectPivot"); // bformatter.Serialize(stream, magnet.SnapPosition); // bformatter.Serialize(stream, selection.Count); // foreach (Item item in selection) // { // bformatter.Serialize(stream, item); // item.IsSelected = true; // } // Clipboard.SetData("Canguro", stream); // } // finally // { // stream.Close(); // } //} /// <summary> /// Executes the command. /// Gets the selection and a pivot point, and adds them to the Clipboard with the key "Canguro" /// </summary> /// <param name="services">CommandServices object to interact with the system</param> public override void Run(Canguro.Controller.CommandServices services) { Dictionary <uint, Joint> joints = new Dictionary <uint, Joint>(); List <LineElement> lines = new List <LineElement>(); List <AreaElement> areas = new List <AreaElement>(); bool haveSelection = false; haveSelection = services.GetSelection(joints, lines, areas); if (!haveSelection) { services.GetMany(Culture.Get("selectItems")); haveSelection = services.GetSelection(joints, lines, areas); } if (haveSelection) { Magnet magnet = services.GetPoint(Culture.Get("selectPivot")); if (magnet != null) { Microsoft.DirectX.Vector3 pivot = magnet.SnapPosition; Clipboard.Clear(); object[] objs = new object[] { joints, lines, areas, pivot }; //// Test Serialization //System.IO.MemoryStream s = new MemoryStream(); //new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Serialize(s, objs); Clipboard.SetData("Canguro", objs); } } foreach (Item item in joints.Values) { if (item != null) { item.IsSelected = true; } } foreach (Item item in lines) { if (item != null) { item.IsSelected = true; } } foreach (Item item in areas) { if (item != null) { item.IsSelected = true; } } }
public bool PlaySound(int idx, SoundVector vec) { if (m_activeTheme.effect.Count == 0) { return(false); } bool success = m_soundManager.PlaySound3D(m_activeTheme.effect[idx], vec, false, m_themes.SoundVolume); m_owner.Log("play effect: {0} pos:{1}:{2}:{3} - {4}", m_activeTheme.effect[idx], vec.X, vec.Y, vec.Z, success); m_owner.SoundEvent(vec); return(success); }
/// <summary> /// Set the Rotation Parameters /// </summary> /// <param name="rot"></param> public void SetRotation(Microsoft.DirectX.Vector3 rot) { SetRotation( Microsoft.DirectX.Quaternion.RotationMatrix( Microsoft.DirectX.Matrix.Multiply( Microsoft.DirectX.Matrix.RotationX(rot.X), Microsoft.DirectX.Matrix.Multiply( Microsoft.DirectX.Matrix.RotationY(rot.Y), Microsoft.DirectX.Matrix.RotationZ(rot.Z) ) ) )); }
/// <summary> /// Calculate the forces that act on the aircraft in the three axis. /// You should only adjust the Fx, Fy and Fz fields in this function, all /// others will be recalculated by the base class. /// </summary> /// <param name="elapsedTime">The time elapsed since last call (in seconds).</param> /// <param name="wind">The windvector in airplane coordincates.</param> /// <returns>True if you've implemented this function, false if you want /// to use the default implementation.</returns> public override bool CalculateForces(float elapsedTime, Microsoft.DirectX.Vector3 wind) { // Here you've got access to all parameters from the flightmodel, as well as // the aircraft parameters (through the AircraftParameters property). // Fx = force front/back // Fy = force left/right // Fz = force up/down // Return true if you want to override the default implementation // Return false if you don't want to implement this method yourself. return(false); }
/// <summary> /// Calculate the torques that act on the aircraft in the three axis. /// You should only adjust the Tx, Ty and Tz fields in this function, all /// others will be recalculated by the base class. /// </summary> /// <param name="elapsedTime">The time elapsed since last call (in seconds).</param> /// <param name="wind">The windvector in airplane coordincates.</param> /// <returns>True if you've implemented this function, false if you want /// to use the default implementation.</returns> public override bool CalculateTorques(float elapsedTime, Microsoft.DirectX.Vector3 wind) { // Here you've got access to all parameters from the flightmodel, as well as // the aircraft parameters (through the AircraftParameters property). // Tx = Torque around x-axis. // Ty = Torque around y-axis. // Tz = Torque around z-axis. // Return true if you want to override the default implementation // Return false if you don't want to implement this method yourself. return(false); }
private static void SetFocusValues(float distanceAway, Vector3 targetPosition) { float minimumDistanceFromClipPlane = SpriteManager.Camera.NearClipPlane * 1.05f; float maximumDistanceFromClipPlane = SpriteManager.Camera.FarClipPlane * .95f; distanceAway = Math.Max(distanceAway, minimumDistanceFromClipPlane); distanceAway = Math.Min(distanceAway, maximumDistanceFromClipPlane); #if FRB_MDX SpriteManager.Camera.Position = targetPosition - distanceAway * SpriteManager.Camera.RotationMatrix.Forward(); #else SpriteManager.Camera.Position = targetPosition - distanceAway * SpriteManager.Camera.RotationMatrix.Forward; #endif CameraMethods.CenterTarget = targetPosition; }
void MenuMonster_OnButtonFocus(object sender, object arg) { ButtonBox bbs = (ButtonBox)sender; //if (bbs.Visible == false) //{ // FocusNextButtonBox(); //} //else { Microsoft.DirectX.Vector3 loc = Util.Point2Vector3(bbs.Location); loc.X -= 48; loc.Y -= 32; game.MovieManager.PlayMovie("cursor", loc); } }
//joining AI library #region IWalkable Members public bool IsPositionOnTereain(Microsoft.DirectX.Vector3 position) { PointF p = new PointF(position.X, position.Z); if (p.X < 0 || p.X > this.size.Width) { return(false); } if (p.Y < 0 || p.Y > this.size.Height) { return(false); } return(true); }
/// <summary> /// This method returns a Magnet whose SnapPoint property has the point obtained either typed or clicked. /// </summary> /// <param name="prompt">The instruction text that appears at the SmallPanel.</param> /// <returns>The Magnet whose SnapPoint was found.</returns> public Snap.Magnet GetPoint(string prompt) { controller.MainFrm.SmallPanel.Start(controller.ModelCommand.Title, prompt, 10, "1,2,3 " + Culture.Get("or") + " @1,2,3"); wait(WaitingFor.Point, true); Snap.Magnet m = waitingObj as Snap.Magnet; if (m == null) { return(null); } lastPoint = m.SnapPosition; SnapPrimaryPoint = new Snap.PointMagnet(m.SnapPositionInt, Snap.PointMagnetType.SimplePoint); return(m); }
private static void ZoomBy(Camera camera, float zoomValue) { if (camera.Orthogonal == false) { Vector3 distanceFromTarget = camera.Position - CenterTarget; distanceFromTarget *= 1 + zoomValue * -.1f; camera.Position = CenterTarget + distanceFromTarget; } else { camera.OrthogonalHeight *= 1 + zoomValue * -.1f; camera.OrthogonalWidth *= 1 + zoomValue * -.1f; } }
/// <summary> /// Executes the command. /// Gets a number of segments and divides all selected line elements in equal length segments. /// </summary> /// <param name="services">CommandServices object to interact with the system</param> public override void Run(Canguro.Controller.CommandServices services) { List <Item> selection = services.GetSelection(); if (selection.Count == 0) { return; } List <LineElement> lineList = new List <LineElement>(); foreach (Item item in selection) { if (item != null && item is LineElement) { lineList.Add((LineElement)item); } } if (lineList.Count == 0) { lineList.Add(services.GetLine()); } int parts = (int)services.GetSingle(Culture.Get("getSplitParts") + " [2-100]"); parts = (parts < 2) ? 2 : (parts > 100) ? 100 : parts; foreach (LineElement line in lineList) { Joint ji = line.I; Joint jj = line.J; Joint last = jj; Microsoft.DirectX.Vector3 v = new Microsoft.DirectX.Vector3(jj.X - ji.X, jj.Y - ji.Y, jj.Z - ji.Z); v.Multiply(1.0f / parts); if (parts > 1 && v.LengthSq() > 0) { LineElement newLine = line; for (int i = 0; i < parts - 1; i++) { jj = new Joint(ji.X + v.X, ji.Y + v.Y, ji.Z + v.Z); services.Model.JointList.Add(jj); newLine = Split(newLine, jj, services.Model); services.Model.LineList.Add(newLine); ji = jj; } } } }
public void RunTests() { Vector3 v1 = new Vector3(3, 2, 1); Vector3 v2 = new Vector3(-4, 1, 2 ); DXVec3 dx1 = new DXVec3(3, 2, 1); DXVec3 dx2 = new DXVec3(-4, 1, 2 ); TestMagnitude(v1, v2, dx1, dx2); TestNormalize(v1, v2, dx1, dx2); TestDot(v1, v2, dx1, dx2); TestAdd(v1, v2, dx1, dx2); TestSub(v1, v2, dx1, dx2); TestScale(v1, v2, dx1, dx2); TestTransform(v1, v2, dx1, dx2); PrintResults(v1, v2); }
private void Play() { m_play = true; int themeidx = cbTheme.SelectedIndex; if (themeidx != -1) { string theme = (string)cbTheme.Items[themeidx]; Log("Playing theme: {0}", theme); m_soundVector = new SoundVector(0.0f, 0.0f, 0.0f); m_themeManager.PlayTheme(theme); } else { Log("No theme selected"); } }
/// <summary> /// This method requests a point and returns a joint. If a joint is found, the method gets it. If not, then creates one and if the created joint lies on a line, /// then the command splits the line and adds the new line to the newLines list. /// </summary> /// <param name="newLines"> List of new lines created by this method while creating new joints </param> /// <returns> The created or found joint </returns> public Model.Joint GetJoint(IList <Model.LineElement> newLines) { Model.Joint joint; Canguro.Controller.Snap.Magnet magnet = GetPoint(); if (magnet == null) { return(null); } if (magnet is Canguro.Controller.Snap.PointMagnet && ((Canguro.Controller.Snap.PointMagnet)magnet).Joint != null) { joint = ((Canguro.Controller.Snap.PointMagnet)magnet).Joint; } else { Microsoft.DirectX.Vector3 v = magnet.SnapPosition; joint = new Canguro.Model.Joint(v.X, v.Y, v.Z); Model.JointList.Add(joint); if (magnet is Canguro.Controller.Snap.PointMagnet) { Canguro.Controller.Snap.PointMagnet pmag = (Canguro.Controller.Snap.PointMagnet)magnet; if (pmag.RelatedMagnets != null && pmag.RelatedMagnets.Count > 0) { for (int i = 0; i < pmag.RelatedMagnets.Count; i++) { if (pmag.RelatedMagnets[i] is Canguro.Controller.Snap.LineMagnet && ((Canguro.Controller.Snap.LineMagnet)pmag.RelatedMagnets[i]).Line != null) { Canguro.Commands.Model.SplitCmd.Split(((Canguro.Controller.Snap.LineMagnet)pmag.RelatedMagnets[i]).Line, joint, Model); } } } } else if (magnet is Canguro.Controller.Snap.LineMagnet) { Canguro.Controller.Snap.LineMagnet lmag = (Canguro.Controller.Snap.LineMagnet)magnet; if (lmag.Line != null) { Canguro.Commands.Model.SplitCmd.Split(((Canguro.Controller.Snap.LineMagnet)magnet).Line, joint, Model); } } } SnapPrimaryPoint = new Canguro.Controller.Snap.PointMagnet(joint); return(joint); }
/// <summary> /// Larger comes first. /// </summary> /// <param name="first">The first instance.</param> /// <param name="second">The second instance.</param> /// <returns>-1 if the first comes first, 1 if the second comes first, 0 if they're equal.</returns> #endregion public int Compare(IDrawableBatch first, IDrawableBatch second) { Vector3 firstCameraRelativePosition = new Vector3( first.X - mCamera.X, first.Y - mCamera.Y, first.Z - mCamera.Z); Vector3 secondCameraRelativePosition = new Vector3( second.X - mCamera.X, second.Y - mCamera.Y, second.Z - mCamera.Z); float firstDistance; #if FRB_MDX Vector3 forwardVector = mCamera.RotationMatrix.Forward(); Vector3Extensions.Dot(ref firstCameraRelativePosition, ref forwardVector, out firstDistance); float secondDistance; Vector3Extensions.Dot(ref secondCameraRelativePosition, ref forwardVector, out secondDistance); #else Vector3 forwardVector = mCamera.RotationMatrix.Forward; Vector3.Dot(ref firstCameraRelativePosition, ref forwardVector, out firstDistance); float secondDistance; Vector3.Dot(ref secondCameraRelativePosition, ref forwardVector, out secondDistance); #endif if (firstDistance < secondDistance) { return(1); } else if (firstDistance > secondDistance) { return(-1); } else { return(0); } }
/// <summary> /// Executes the command. /// Gets the parameters and calls beamGrid3D() to make the grid. /// </summary> /// <param name="services">CommandServices object to interact with the system</param> public override void Run(Canguro.Controller.CommandServices services) { if (section == null) { section = Canguro.Model.Section.SectionManager.Instance.DefaultFrameSection as Canguro.Model.Section.FrameSection; } services.GetProperties(Culture.Get("gridCmdTitle"), this); Controller.Snap.Magnet m = services.GetPoint(Culture.Get("selectGridOrigin")); if (m == null) { return; } Microsoft.DirectX.Vector3 o = m.SnapPosition; StraightFrameProps props = new StraightFrameProps(); props.Section = section; beamGrid3D(services.Model, o.X, o.Y, o.Z, dx, 0, 0, 0, dy, 0, 0, 0, dz, nx + 1, ny + 1, nz + 1, true, props); }
/// <summary> /// Returns whether this instance overlaps the argument AxisAlignedCube /// </summary> /// <param name="cube">The instance AxisAlignedCube to test against.</param> /// <returns>Whether collision has occurred</returns> public bool CollideAgainst(AxisAlignedCube cube) { UpdateDependencies(TimeManager.CurrentTime); cube.UpdateDependencies(TimeManager.CurrentTime); Vector3 relativeCenter = Position - cube.Position; if (System.Math.Abs(relativeCenter.X) - Radius > cube.ScaleX || System.Math.Abs(relativeCenter.Y) - Radius > cube.ScaleY || System.Math.Abs(relativeCenter.Z) - Radius > cube.ScaleZ) { return(false); } Vector3 nearest = GetNearestPoint(cube, relativeCenter); float distance = (nearest - relativeCenter).LengthSquared(); return(distance <= Radius * Radius); }
private Vector3 GetNearestPoint(AxisAlignedCube cube, Vector3 relativeCenter) { float distance; Vector3 nearest = new Vector3(); distance = relativeCenter.X; if (distance > cube.ScaleX) { distance = cube.ScaleX; } if (distance < -cube.ScaleX) { distance = -cube.ScaleX; } nearest.X = distance; distance = relativeCenter.Y; if (distance > cube.ScaleY) { distance = cube.ScaleY; } if (distance < -cube.ScaleY) { distance = -cube.ScaleY; } nearest.Y = distance; distance = relativeCenter.Z; if (distance > cube.ScaleZ) { distance = cube.ScaleZ; } if (distance < -cube.ScaleZ) { distance = -cube.ScaleZ; } nearest.Z = distance; return(nearest); }
/// <summary> /// Calculates the intersection of the given Joint and LineElement and returns the /// float value corresponding to the proportion of the vector from defined by the line Joints. /// </summary> /// <param name="line">The LineElement to intersect</param> /// <param name="joint">The Joint to intersect with line</param> /// <returns>A float in [0, 1). If the joint is in the line, the proportion, 0 otherwise.</returns> public static float getIntersection(LineElement line, Joint joint) { Microsoft.DirectX.Vector3 i = line.I.Position; Microsoft.DirectX.Vector3 j = line.J.Position; Microsoft.DirectX.Vector3 pos = joint.Position; float ret, retx, rety, retz; float eps = 0.001f; //retx = (j.X != i.X) ? (pos.X - i.X) / (j.X - i.X) : (equals(pos.X, i.X, eps)) ? float.NaN : 0; //rety = (j.Y != i.Y) ? (pos.Y - i.Y) / (j.Y - i.Y) : (equals(pos.Y, i.Y, eps)) ? retx : 0; //retz = (j.Z != i.Z) ? (pos.Z - i.Z) / (j.Z - i.Z) : (equals(pos.Z, i.Z, eps)) ? rety : 0; //rety = (!float.IsNaN(rety)) ? rety : retz; //retx = (!float.IsNaN(retx)) ? retx : rety; //return (equals(retx, rety, eps) && equals(rety, retz, eps) && retx - eps > 0 && retx + eps < 1) ? retx : 0; Microsoft.DirectX.Vector3 xmp = joint.Position - line.I.Position; Microsoft.DirectX.Vector3 dir = line.J.Position - line.I.Position; ret = (Math.Abs(xmp.X) > Math.Abs(xmp.Y)) ? ((Math.Abs(xmp.X) > Math.Abs(xmp.Z)) ? xmp.X / dir.X : xmp.Z / dir.Z) : ((Math.Abs(xmp.Y) > Math.Abs(xmp.Z)) ? xmp.Y / dir.Y : xmp.Z / dir.Z); return((equals(ret * dir.X, xmp.X, eps) && equals(ret * dir.Y, xmp.Y, eps) && equals(ret * dir.Z, xmp.Z, eps)) ? ret : 0); }
/// <summary> /// This method returns a vector (displacement) obtained by user input, /// either from clicking or typing. The input works by asking for a /// basepoint and then for a second point, which can be typed with absolute /// or relative coordinates. The difference between the 2 points is returned. /// </summary> /// <param name="v">The vector (diplacement) to be returned or Vector3.Empty if /// no vector could be obtained.</param> /// <returns>True if a valid vector (displacement) could be obtained, false otherwise.</returns> public bool GetVector(out Microsoft.DirectX.Vector3 v) { Snap.Magnet m1, m2; // Ask for 1st point if ((m1 = GetPoint(Culture.Get("getVector1"))) == null) { v = Microsoft.DirectX.Vector3.Empty; return(false); } // Activate vector Tracking Tracking.TrackingService ts = TrackingService; TrackingService = Tracking.VectorTrackingService.Instance; Microsoft.DirectX.Vector3 origin = m1.SnapPositionInt; TrackingService.SetPoint(origin); SnapPrimaryPoint = new Canguro.Controller.Snap.PointMagnet(origin, Canguro.Controller.Snap.PointMagnetType.SimplePoint); // Ask for 2nd point if ((m2 = GetPoint(Culture.Get("getVector2"))) == null) { v = Microsoft.DirectX.Vector3.Empty; TrackingService = ts; return(false); } SnapPrimaryPoint = new Canguro.Controller.Snap.PointMagnet(m2.SnapPositionInt, Canguro.Controller.Snap.PointMagnetType.SimplePoint); // Calculate and return difference v = m2.SnapPositionInt - origin; Model.UnitSystem.UnitSystem us = Canguro.Model.UnitSystem.UnitSystemsManager.Instance.CurrentSystem; v.X = us.FromInternational(v.X, Canguro.Model.UnitSystem.Units.Distance); v.Y = us.FromInternational(v.Y, Canguro.Model.UnitSystem.Units.Distance); v.Z = us.FromInternational(v.Z, Canguro.Model.UnitSystem.Units.Distance); TrackingService = ts; return(true); }
/// <summary> /// Executes the command. /// Gets a number of segments and divides all selected line elements in equal length segments. /// </summary> /// <param name="services">CommandServices object to interact with the system</param> public override void Run(Canguro.Controller.CommandServices services) { List<Item> selection = services.GetSelection(); if (selection.Count == 0) return; List<LineElement> lineList = new List<LineElement>(); foreach (Item item in selection) if (item != null && item is LineElement) lineList.Add((LineElement)item); if (lineList.Count == 0) lineList.Add(services.GetLine()); int parts = (int)services.GetSingle(Culture.Get("getSplitParts") + " [2-100]"); parts = (parts < 2) ? 2 : (parts > 100) ? 100 : parts; foreach (LineElement line in lineList) { Joint ji = line.I; Joint jj = line.J; Joint last = jj; Microsoft.DirectX.Vector3 v = new Microsoft.DirectX.Vector3(jj.X - ji.X, jj.Y - ji.Y, jj.Z - ji.Z); v.Multiply(1.0f / parts); if (parts > 1 && v.LengthSq() > 0) { LineElement newLine = line; for (int i = 0; i < parts - 1; i++) { jj = new Joint(ji.X + v.X, ji.Y + v.Y, ji.Z + v.Z); services.Model.JointList.Add(jj); newLine = Split(newLine, jj, services.Model); services.Model.LineList.Add(newLine); ji = jj; } } } }
private void TestMagnitude(Vector3 v1, Vector3 v2, DXVec3 dx1, DXVec3 dx2) { Magnitudes = new float[4]; Magnitudes[0] = v1.Magnitude(); Magnitudes[1] = v2.Magnitude(); Magnitudes[2] = dx1.Length(); Magnitudes[3] = dx2.Length(); MagnitudesSq = new float[4]; MagnitudesSq[0] = v1.MagnitudeS(); MagnitudesSq[1] = v2.MagnitudeS(); MagnitudesSq[2] = dx1.LengthSq(); MagnitudesSq[3] = dx2.LengthSq(); }
public static Microsoft.DirectX.Vector3 TranslateBetweenVectorAndVector(Vector from) { Microsoft.DirectX.Vector3 to = new Microsoft.DirectX.Vector3(from.X, from.Y, from.Z); return to; }
public static void CameraControlFps(Camera camera) { GuiManager.Cursor.StaticPosition = true; Vector3 up = new Vector3(0, 1, 0); camera.Velocity = new Vector3(); Keys forwardKey = Keys.W; Keys backKey = Keys.S; Keys leftKey = Keys.A; Keys rightKey = Keys.D; FlatRedBall.Input.Keyboard keyboard = InputManager.Keyboard; float movementSpeed = 7; if (keyboard.KeyDown(forwardKey)) { camera.Velocity += new Vector3(camera.RotationMatrix.M31, camera.RotationMatrix.M32, camera.RotationMatrix.M33) * movementSpeed; } else if (keyboard.KeyDown(backKey)) { camera.Velocity += new Vector3(camera.RotationMatrix.M31, camera.RotationMatrix.M32, camera.RotationMatrix.M33) * -movementSpeed; } if (keyboard.KeyDown(leftKey)) { camera.Velocity += new Vector3(camera.RotationMatrix.M11, camera.RotationMatrix.M12, camera.RotationMatrix.M13) * -movementSpeed; } if (keyboard.KeyDown(rightKey)) { camera.Velocity += new Vector3(camera.RotationMatrix.M11, camera.RotationMatrix.M12, camera.RotationMatrix.M13) * movementSpeed; } #if FRB_XNA // These vaules may be way too fast/slow because I modified it to use pixels rather // than the somewhat arbitrary world coordinates camera.RotationMatrix *= Matrix.CreateFromAxisAngle( camera.RotationMatrix.Right, -.2f * GuiManager.Cursor.ScreenYChange * TimeManager.SecondDifference); camera.RotationMatrix *= Matrix.CreateFromAxisAngle( up, -.2f * GuiManager.Cursor.ScreenXChange * TimeManager.SecondDifference); #elif FRB_MDX camera.RotationMatrix *= Matrix.RotationAxis( new Vector3(camera.RotationMatrix.M11, camera.RotationMatrix.M12, camera.RotationMatrix.M13), -.2f * GuiManager.Cursor.YVelocity * TimeManager.SecondDifference); camera.RotationMatrix *= Matrix.RotationAxis( up, -.2f * GuiManager.Cursor.XVelocity * TimeManager.SecondDifference); #endif }
private void TestScale(Vector3 v1, Vector3 v2, DXVec3 dx1, DXVec3 dx2) { ScaleResults = new Vector3[4]; ScaleResults[0] = v1 * 2.0f; ScaleResults[1] = v2 * .5f; ScaleResults[2] = DXToV3(DXVec3.Multiply(dx1, 2.0f)); ScaleResults[3] = DXToV3(DXVec3.Multiply(dx2, 0.5f)); }
private void TestSub(Vector3 v1, Vector3 v2, DXVec3 dx1, DXVec3 dx2) { SubtractionResults = new Vector3[2]; SubtractionResults[0] = v1 - v2; SubtractionResults[1] = DXToV3(dx1 - dx2); }
private void TestTransform(Vector3 v1, Vector3 v2, DXVec3 dx1, DXVec3 dx2) { TransformResults = new Vector3[4]; float rads = (float)(30 * Math.PI / 180); Vector3 axis = (new Vector3(1, 2, 3)).Normalize(); Matrix3 rotation = Matrix3.RotateAxisAngle(new Vector3(1, 2, 3), rads); Microsoft.DirectX.Matrix dxaxisangle = Microsoft.DirectX.Matrix.RotationAxis(new DXVec3(1, 2, 3), rads); DXTransformMatrix = Microsoft.DirectX.Matrix.RotationAxis(new DXVec3(1, 2, 3), rads); DXTransformResults = new Microsoft.DirectX.Vector4[2]; DXTransformResults[0] = DXVec3.Transform(dx1, DXTransformMatrix); DXTransformResults[1] = DXVec3.Transform(dx2, DXTransformMatrix); TransformResults[0] = v1 * rotation; TransformResults[1] = v2 * rotation; TransformResults[2] = new Vector3(DXTransformResults[0].X, DXTransformResults[0].Y, DXTransformResults[0].Z); TransformResults[3] = new Vector3(DXTransformResults[1].X, DXTransformResults[1].Y, DXTransformResults[1].Z); }
public static void MouseCameraControl3D(Camera camera) { Cursor cursor = GuiManager.Cursor; if (cursor.WindowOver == null && GuiManager.DominantWindowActive == false && !cursor.MiddlePush #if SUPPORTS_FRB_DRAWN_GUI && cursor.WindowMiddleButtonPushed == null #endif #if FRB_XNA && FlatRedBallServices.Game.IsActive #endif ) { #region ScrollWheel zooms in/out if (InputManager.Mouse.ScrollWheelChange != 0) { int zoomValue = System.Math.Sign(InputManager.Mouse.ScrollWheelChange); ZoomBy(camera, zoomValue); } #endregion #region Alt+Right Mouse Button Down - Zoom if ((InputManager.Keyboard.KeyDown(Keys.LeftAlt) || InputManager.Keyboard.KeyDown(Keys.RightAlt)) && InputManager.Mouse.ButtonDown(FlatRedBall.Input.Mouse.MouseButtons.RightButton)) { if (InputManager.Mouse.YVelocity != 0) { ZoomBy(camera, (-InputManager.Mouse.YVelocity/512.0f )); } } #endregion #region Alt+Middle Mouse Button - Rotate if ((InputManager.Keyboard.KeyDown(Keys.LeftAlt) || InputManager.Keyboard.KeyDown(Keys.RightAlt)) && InputManager.Mouse.ButtonDown(FlatRedBall.Input.Mouse.MouseButtons.MiddleButton)) { Vector3 upVector; switch(mUpAxis) { case Axis.X: upVector = new Vector3(1,0,0); break; case Axis.Y: upVector = new Vector3(0,1,0); break; case Axis.Z: upVector = new Vector3(0,0,1); break; default: upVector = new Vector3(0, 1, 0); break; } InputManager.Mouse.ControlPositionedObjectOrbit(camera, CenterTarget, false, upVector); } #endregion #region MiddleMouseButtonPan else if (InputManager.Mouse.ButtonDown(FlatRedBall.Input.Mouse.MouseButtons.MiddleButton)) { float distanceAway = (camera.Position - CenterTarget).Length(); const float multiplier = .0015f; #if FRB_MDX Vector3 cameraRight = camera.RotationMatrix.Right(); Vector3 cameraUp = camera.RotationMatrix.Up(); #else Vector3 cameraRight = camera.RotationMatrix.Right; Vector3 cameraUp = camera.RotationMatrix.Up; #endif Vector3 offset = -InputManager.Mouse.XChange * distanceAway * multiplier * cameraRight + InputManager.Mouse.YChange * distanceAway * multiplier * cameraUp; camera.Position += offset; CenterTarget += offset; } #endregion } }
private Vector3 DXToV3(DXVec3 dxv) { return new Vector3(dxv.X, dxv.Y, dxv.Z); }
/// <summary> /// Method that responds to the EnterData event of SmallPanel. /// The text input by the user on the SmallPanel's TextBox (data) is /// parsed here. If the input is successfull locks are released and /// execution continues normally, i.e.: waitingObj is assigned to the /// refered object and the selectionFilter is set to None. Otherwise, /// the input is rejected. /// </summary> /// <param name="sender">Usually, the SmallPanel in MainFrm</param> /// <param name="e">Event args with the user input</param> void onEnterData(object sender, Canguro.View.EnterDataEventArgs e) { char[] charSeparators = new char[] {',', ';', ' ', '\t', '@'}; waitingObj = null; switch (selectionFilter) { case WaitingFor.Point: if (!string.IsNullOrEmpty(e.Data)) { bool relativePt = false; string trimmedPt = e.Data.Trim(); if (trimmedPt.Length > 0 && trimmedPt[0] == '@') relativePt = true; string[] pt = trimmedPt.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); Microsoft.DirectX.Vector3 v; try { if (pt.Length != 3) throw new FormatException(); v = new Microsoft.DirectX.Vector3( float.Parse(pt[0]), float.Parse(pt[1]), float.Parse(pt[2])); if (relativePt) v += lastPoint; } catch (FormatException) { System.Windows.Forms.MessageBox.Show( Culture.Get("enterDataError") + "'" + Culture.Get("enterDataPoint") + "'", Culture.Get("enterDataErrorTitle"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return; } waitingObj = new Snap.PointMagnet(v); } selectionFilter = WaitingFor.None; break; case WaitingFor.Joint: parseItem(e.Data, Canguro.Model.Model.Instance.JointList, Culture.Get("enterDataJoint")); break; case WaitingFor.Line: parseItem(e.Data, Canguro.Model.Model.Instance.LineList, Culture.Get("enterDataLine")); break; case WaitingFor.Area: parseItem(e.Data, Canguro.Model.Model.Instance.AreaList, Culture.Get("enterDataArea")); break; case WaitingFor.Text: waitingObj = e.Data; selectionFilter = WaitingFor.None; break; case WaitingFor.SimpleValue: try { waitingObj = float.Parse(e.Data); selectionFilter = WaitingFor.None; } catch (FormatException) { System.Windows.Forms.MessageBox.Show( Culture.Get("enterDataError") + "'" + Culture.Get("enterDataSimpleValue") + "'", Culture.Get("enterDataErrorTitle"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return; } break; case WaitingFor.Any: case WaitingFor.Many: case WaitingFor.None: break; default: throw new NotImplementedException("CommandServices.onEnterData"); } }
/// <summary> /// This method returns a Magnet whose SnapPoint property has the point obtained either typed or clicked. /// </summary> /// <param name="prompt">The instruction text that appears at the SmallPanel.</param> /// <returns>The Magnet whose SnapPoint was found.</returns> public Snap.Magnet GetPoint(string prompt) { controller.MainFrm.SmallPanel.Start(controller.ModelCommand.Title, prompt, 10, "1,2,3 " + Culture.Get("or") + " @1,2,3"); wait(WaitingFor.Point, true); Snap.Magnet m = waitingObj as Snap.Magnet; if (m == null) return null; lastPoint = m.SnapPosition; SnapPrimaryPoint = new Snap.PointMagnet(m.SnapPositionInt, Snap.PointMagnetType.SimplePoint); return m; }
private void TestAdd(Vector3 v1, Vector3 v2, DXVec3 dx1, DXVec3 dx2) { AdditionResults = new Vector3[2]; AdditionResults[0] = v1 + v2; AdditionResults[1] = DXToV3(dx1 + dx2); }
private void TestDot(Vector3 v1, Vector3 v2, DXVec3 dx1, DXVec3 dx2) { DotProducts = new float[2]; DotProducts[0] = Vector3.Dot(v1, v2); DotProducts[1] = DXVec3.Dot(dx1, dx2); }
private void TestNormalize(Vector3 v1, Vector3 v2, DXVec3 dx1, DXVec3 dx2) { NormResults = new Vector3[4]; NormResults[0] = (new Vector3(v1)).Normalize(); NormResults[1] = (new Vector3(v2)).Normalize(); NormResults[2] = DXToV3(DXVec3.Normalize(dx1)); NormResults[3] = DXToV3(DXVec3.Normalize(dx2)); }
public static Microsoft.DirectX.Vector3 Normalize(Microsoft.DirectX.Vector3 vect) { Microsoft.DirectX.Vector3 ret = new Microsoft.DirectX.Vector3(); float legnth = GetFourDigitsNumber(Math.Sqrt(vect.X * vect.X + vect.Y * vect.Y + vect.Z * vect.Z).ToString()); ret.X = vect.X / legnth; ret.Y = vect.Y / legnth; ret.Z = vect.Z / legnth; return ret; }