public override void Init(MyObjectBuilder_AutopilotBase objectBuilder)
        {
            MyObjectBuilder_SimpleAutopilot ob = (MyObjectBuilder_SimpleAutopilot)objectBuilder;

            m_destination = ob.Destination;
            m_direction = ob.Direction;
        }
Example #2
0
		/// <summary>
		/// Calculates the angle subtended by two line segments that meet at a vertex.
		/// </summary>
		/// <param name="start">The end of one of the line segments.</param>
		/// <param name="vertex">The vertex of the angle formed by the two line segments.</param>
		/// <param name="end">The end of the other line segment.</param>
		/// <returns>The angle subtended by the two line segments in degrees.</returns>
		public static double SubtendedAngle(PointF start, PointF vertex, PointF end)
		{
			Vector3D vertexPositionVector = new Vector3D(vertex.X, vertex.Y, 0);
			Vector3D a = new Vector3D(start.X, start.Y, 0) - vertexPositionVector;
			Vector3D b = new Vector3D(end.X, end.Y, 0) - vertexPositionVector;

			float dotProduct = a.Dot(b);

			Vector3D crossProduct = a.Cross(b);

			float magA = a.Magnitude;
			float magB = b.Magnitude;

			if (FloatComparer.AreEqual(magA, 0F) || FloatComparer.AreEqual(magB, 0F))
				return 0;

			double cosTheta = dotProduct/magA/magB;

			// Make sure cosTheta is within bounds so we don't
			// get any errors when we take the acos.
			if (cosTheta > 1.0f)
				cosTheta = 1.0f;

			if (cosTheta < -1.0f)
				cosTheta = -1.0f;

			double theta = Math.Acos(cosTheta)*(crossProduct.Z == 0 ? 1 : -Math.Sign(crossProduct.Z));
			double thetaInDegrees = theta/Math.PI*180;

			return thetaInDegrees;
		}
Example #3
0
        /// <summary>
        /// Creates a deep copy of an existing orientation object.
        /// </summary>
        /// <param name="source">The source orientation for the copy.</param>
        private Orientation3D(Orientation3D source)
        {
            forwardVector = source.ForwardVector;
            downVector = source.downVector;

            angleMeasurement = source.angleMeasurement;
        }
        public static Vector3 CalculateNaturalGravityInPoint(Vector3D worldPoint, bool clearVectors = true)
        {
            if (GravityVectors == null)
                GravityVectors = new List<Vector3>();

            Vector3 resultGravity = Vector3.Zero;
			m_lastLargestNaturalGravityMultiplier = 0.0f;
			if(clearVectors)
				GravityVectors.Clear();

            foreach (IMyGravityProvider generator in m_naturalGravityGenerators)
            {
                if (generator.IsPositionInRange(worldPoint))
                {
                    Vector3 worldGravity = generator.GetWorldGravity(worldPoint);
					var gravityMultiplier = generator.GetGravityMultiplier(worldPoint);

					if (gravityMultiplier > m_lastLargestNaturalGravityMultiplier)
						m_lastLargestNaturalGravityMultiplier = gravityMultiplier;

                    resultGravity += worldGravity;
                    GravityVectors.Add(worldGravity);
                }
            }

            return resultGravity;
        }
        public override void DebugDraw(ref Vector3D translation, ref Color materialColor)
        {
            Shape.DebugDraw(ref translation, materialColor);
            VRageRender.MyRenderProxy.DebugDrawText3D(Shape.Center() + translation, "layered", Color.White, 1f, false);

            m_oreDeposits.DebugDraw(ref translation, ref materialColor);
        }
Example #6
0
        /// <summary>
        /// Instantiates a new Orientation object.
        /// </summary>
        public Orientation3D()
        {
            forwardVector = new Vector3D(1, 0, 0);
            downVector = new Vector3D(0, 0, 1);

            angleMeasurement = AngleMeasurement.Degrees;
        }
 public MyEncounterId(BoundingBoxD box, int seed, int encounterId)
 {
     BoundingBox = box;
     Seed = seed;
     EncounterId = encounterId;
     PlacePosition = Vector3D.Zero;
 }
Example #8
0
 protected void ProcessNormalsPerVertex(PointerToVertex[] pointersToVertex, int verticesCount)
 {
     Vector3D[] normalsPerVertex = new Vector3D[verticesCount];
     for (int i = 0; i < this.triangles.Length; i++) {
         normalsPerVertex[pointersToVertex[i].Vertex1 - 1] += this.triangles[i].Normal;
         normalsPerVertex[pointersToVertex[i].Vertex2 - 1] += this.triangles[i].Normal;
         normalsPerVertex[pointersToVertex[i].Vertex3 - 1] += this.triangles[i].Normal;
         int percent = (int) (i * 100 / this.triangles.Length);
         if ((percent % 5) == 0) {
             this.OnElementLoaded((int) ((i * 100 / this.triangles.Length * 0.5)), ElementMesh.VertexNormal);
         }
     }
     for (int i = 0; i < this.triangles.Length; i++) {
         this.triangles[i].NormalOnVertex1 = normalsPerVertex[pointersToVertex[i].Vertex1 - 1];
         this.triangles[i].NormalOnVertex1.Normalize();
         this.triangles[i].NormalOnVertex2 = normalsPerVertex[pointersToVertex[i].Vertex2 - 1];
         this.triangles[i].NormalOnVertex2.Normalize();
         this.triangles[i].NormalOnVertex3 = normalsPerVertex[pointersToVertex[i].Vertex3 - 1];
         this.triangles[i].NormalOnVertex3.Normalize();
         int percent = (int) (i * 100 / this.triangles.Length);
         if ((percent % 5) == 0) {
             this.OnElementLoaded(50 + (int) ((i * 100 / this.triangles.Length * 0.5)), ElementMesh.VertexNormal);
         }
     }
     normalsPerVertex = null;
     //for (int i = 0; i < this.triangles.Length; i++) {
     //    this.triangles[i].NormalOnVertex1 = this.normalsPerVertex[this.pointersToVertex[i].Vertex1];
     //    this.triangles[i].NormalOnVertex2 = this.normalsPerVertex[this.pointersToVertex[i].Vertex2];
     //    this.triangles[i].NormalOnVertex3 = this.normalsPerVertex[this.pointersToVertex[i].Vertex3];
     //}
 }
Example #9
0
        public ConferenceRoom(GraphicsInterface gi, Vector3D roomSize)
            : base(gi, roomSize, new Vector3D(0, roomSize.Y / 2.0f, 0), new Resolution(10, 10))
        {


            fWallTexture = TextureHelper.CreateTextureFromFile(gi, "Textures\\Wall.tiff", false);
            fCeilingTexture = TextureHelper.CreateTextureFromFile(gi, "Textures\\Ceiling.tiff", false);
            fFloorTexture = TextureHelper.CreateTextureFromFile(gi, "Textures\\Carpet_berber_dirt.jpg", false);

            fChildren = new List<IRenderable>();

            SetWallTexture(AABBFace.Ceiling, fCeilingTexture);
            SetWallTexture(AABBFace.Floor, fFloorTexture);

            SetWallTexture(AABBFace.Front, fWallTexture);
            SetWallTexture(AABBFace.Back, fWallTexture);
            SetWallTexture(AABBFace.Left, fWallTexture);
            SetWallTexture(AABBFace.Right, fWallTexture);

            Vector3D wbSize = new Vector3D(4.0f-(0.305f*2.0f), 3.0f, 0.01f);
            Point3D wbTrans = new Point3D(0, (wbSize.Y/2)+(roomSize.Y-wbSize.Y)/2, -roomSize.Z / 2.0f+.02f);
            AABB wbBB = new AABB(wbSize, wbTrans);
            whiteboard = new Whiteboard(gi, wbBB);
            //whiteboard.ImageSource = localCamProjector;
            
            fTable = new PedestalTable(gi);

            
            
            fChildren.Add(whiteboard);
            fChildren.Add(fTable);
        }
Example #10
0
        public double ComputeArea(Vector3D a, Vector3D b, Vector3D c)
        {
            double area = 0;
            area = ((b - a).Cross(c - a)).Length() / 2.0;

            return area;
        }
Example #11
0
 public override void Parse(GameBitBuffer buffer)
 {
     Field0 = new Vector3D();
     Field0.Parse(buffer);
     Field1 = buffer.ReadInt(32);
     Field2 = buffer.ReadInt(32);
 }
Example #12
0
 public static void Move(TriMesh mesh, Vector3D vec)
 {
     foreach (var v in mesh.Vertices)
     {
         v.Traits.Position += vec;
     }
 }
        //called each frame by vvvv
        public void Evaluate(int SpreadMax)
        {
            //update particles and remove timed out particles
            for (int i = FParticles.Count - 1; i >= 0; i--)
                if (!FParticles[i].Update(FHDEHost.GetCurrentTime()))
                    FParticles.RemoveAt(i);

            for (int i = 0; i < SpreadMax; i++) {
                //add new particles
                if (FBang[i]) {
                    for (int j = 0; j < 4; j++) {
                        var vel = new Vector3D(0, FRandom.NextDouble() + 0.3, FRandom.NextDouble() - 0.5);
                //		vel.z = 0;
                        var acc = new Vector3D(0,0, FAcc[0]);
                        FParticles.Add(new Particle(FHDEHost.GetCurrentTime(), FMaxLifeTime[i], FInput[i], vel, acc));
                    }
                }
            }

            //set outputs
            FOutput.SliceCount = FParticles.Count;
            FAge.SliceCount = FParticles.Count;
            for (int i = 0; i < FParticles.Count; i++) {
                FOutput[i] = FParticles[i].Position;
                FAge[i] = FParticles[i].Age;
            }
        }
Example #14
0
        public Portal(World world, int actorSNO, Vector3D position, Dictionary<int, TagMapEntry> tags)
            : base(world, world.NewActorID, position, tags)
        {
            this.SNOId = actorSNO;
            this.Destination = new ResolvedPortalDestination
            {
                WorldSNO = tags[(int)MarkerTagTypes.DestinationWorld].Int2,
            };

            if (tags.ContainsKey((int)MarkerTagTypes.DestinationLevelArea))
                this.Destination.DestLevelAreaSNO = tags[(int)MarkerTagTypes.DestinationLevelArea].Int2;

            if (tags.ContainsKey((int)MarkerTagTypes.DestinationActorTag))
                this.Destination.StartingPointActorTag = tags[(int)MarkerTagTypes.DestinationActorTag].Int2;
            else
                Logger.Warn("Found portal {0}without target location actor", this.SNOId);

            this.Field8 = this.SNOId;
            this.Field2 = 16;
            this.Field3 = 0;
            this.CollFlags = 0x00000001;

            // FIXME: Hardcoded crap; probably don't need to set most of these. /komiga
            this.Attributes[GameAttribute.MinimapActive] = true;
            this.Attributes[GameAttribute.Hitpoints_Max_Total] = 1f;
            this.Attributes[GameAttribute.Hitpoints_Max] = 0.0009994507f;
            this.Attributes[GameAttribute.Hitpoints_Total_From_Level] = 3.051758E-05f;
            this.Attributes[GameAttribute.Hitpoints_Cur] = 0.0009994507f;
            this.Attributes[GameAttribute.TeamID] = 1;
            this.Attributes[GameAttribute.Level] = 1;
        }
Example #15
0
		public IsometricCamera(Device device, Window window, Vector3D lookDirection)
			: base(device, window)
		{
			base.Position = -lookDirection;
			ResetZoom();
			leftDirection = Vector3D.Normalize(Vector3D.Cross(lookDirection, -UpDirection));
		}
Example #16
0
        /// <summary>
        /// Prepares the simplex with two initial points.
        /// </summary>
        /// <param name="point1">The first point to initialize the simplex with.</param>
        /// <param name="point2">The second point to initialize the simplex with.</param>
        public void Initialize(Vector3D point1, Vector3D point2)
        {
            simplex[0] = point1;
            simplex[1] = point2;

            count = 2;
        }
Example #17
0
        public void Update(Vector3D worldPosition, Vector3 rotation)
        {
            m_translationStuckDetection = m_translationStuckDetection * 0.8 + worldPosition * 0.2;
            m_rotationStuckDetection = m_rotationStuckDetection * 0.95f + rotation * 0.05f;

            bool isStuck = (m_translationStuckDetection - worldPosition).LengthSquared() < 0.0001// m_positionToleranceSq
                 && (m_rotationStuckDetection - rotation).LengthSquared() < 0.0001//m_rotationToleranceSq
                 && !m_isRotating;

            if (m_counter <= 0)
            {
                if (isStuck)
                {
                    IsStuck = true;
                }
                else
                {
                    m_counter = STUCK_COUNTDOWN;
                }

                return;
            }

            if (m_counter == STUCK_COUNTDOWN && !isStuck)
            {
                return;
            }

            m_counter--;
        }
Example #18
0
 public override void Parse(GameBitBuffer buffer)
 {
     ActorId = buffer.ReadInt(32);
     if (buffer.ReadBool())
     {
         Position = new Vector3D();
         Position.Parse(buffer);
     }
     if (buffer.ReadBool())
     {
         Angle = buffer.ReadFloat32();
     }
     if (buffer.ReadBool())
     {
         Field3 = buffer.ReadBool();
     }
     if (buffer.ReadBool())
     {
         Speed = buffer.ReadFloat32();
     }
     if (buffer.ReadBool())
     {
         Field5 = buffer.ReadInt(25);
     }
     if (buffer.ReadBool())
     {
         AnimationTag = buffer.ReadInt(21) + (-1);
     }
     if (buffer.ReadBool())
     {
         Field7 = buffer.ReadInt(32);
     }
 }
		public override byte[] CreateSlicePixelData(Vector3D imagePositionPatient)
		{
			var rowOrientation = RowOrientationPatient;
			var columnOrientation = ColumnOrientationPatient;
			var stackOrientation = rowOrientation.Cross(columnOrientation).Normalize();

			// VTK reslice axes are in the volume coordinate system and should be positioned at the center of the desired output image
			var reslicePosition = imagePositionPatient + Columns*ColumnSpacing/2f*rowOrientation + Rows*RowSpacing/2f*columnOrientation;
			reslicePosition = VolumeReference.ConvertToVolume(reslicePosition);

			var resliceAxes = new Matrix(new[,]
			                             	{
			                             		{rowOrientation.X, rowOrientation.Y, rowOrientation.Z, 0},
			                             		{columnOrientation.X, columnOrientation.Y, columnOrientation.Z, 0},
			                             		{stackOrientation.X, stackOrientation.Y, stackOrientation.Z, 0},
			                             		{0, 0, 0, 1}
			                             	});
			resliceAxes = VolumeReference.RotateToVolumeOrientation(resliceAxes).Transpose();
			resliceAxes.SetColumn(3, reslicePosition.X, reslicePosition.Y, reslicePosition.Z, 1);

			if (Subsamples > 1)
			{
				// if subsampling is required, extract the thick slice ("slab") from the volume and then aggregate it using the specified projection method
				return GetSlabPixelData(VolumeReference, resliceAxes, stackOrientation, Rows, Columns, Subsamples, RowSpacing, ColumnSpacing, SliceThickness, Interpolation, Projection);
			}
			else
			{
				// extract the (thin) slice from the volume
				return GetSlicePixelData(VolumeReference, resliceAxes, Rows, Columns, RowSpacing, ColumnSpacing, Interpolation);
			}
		}
Example #20
0
            public MyAutopilotWaypoint(Vector3D coords, string name, List<MyObjectBuilder_ToolbarItem> actionBuilders, List<int> indexes, MyRemoteControl owner)
            {
                Coords = coords;
                Name = name;

                if (actionBuilders != null)
                {
                    InitActions();
                    bool hasIndexes = indexes != null && indexes.Count > 0;

                    Debug.Assert(actionBuilders.Count <= MyToolbar.DEF_SLOT_COUNT);
                    if (hasIndexes)
                    {
                        Debug.Assert(indexes.Count == actionBuilders.Count);
                    }
                    for (int i = 0; i < actionBuilders.Count; i++)
                    {
                        if (actionBuilders[i] != null)
                        {
                            if (hasIndexes)
                            {
                                Actions[indexes[i]] = MyToolbarItemFactory.CreateToolbarItem(actionBuilders[i]);
                            }
                            else
                            {
                                Actions[i] = MyToolbarItemFactory.CreateToolbarItem(actionBuilders[i]);
                            }
                        }
                    }
                }
            }
Example #21
0
		public void CreateFromVector2D()
		{
			var v = new Vector3D(new Vector2D(1, 2));
			Assert.AreEqual(1, v.X);
			Assert.AreEqual(2, v.Y);
			Assert.AreEqual(0, v.Z);
		}
 public override void OnWorldPositionChanged(ref MatrixD worldMatrix)
 {
     var forward = worldMatrix.Forward;
     m_origin = worldMatrix.Translation + forward * m_originOffset;
     FrontPoint = m_origin + m_rayLength * forward;
     Center = (m_origin + FrontPoint) * 0.5f;
 }
            internal MyLodMeshMerge(MyClipmap parentClipmap, int lod, int lodDivisions, ref MatrixD worldMatrix, ref Vector3D massiveCenter, float massiveRadius, RenderFlags renderFlags)
            {
                Debug.Assert(parentClipmap != null, "Parent clipmap cannot be null");
                Debug.Assert(lod >= 0, "Lod level must be non-negative");
                Debug.Assert(lodDivisions >= 0, "Invalid number of lod divisions");
                m_parentClipmap = parentClipmap;
                m_lod = lod;
                m_lodDivisions = lodDivisions;

                if (m_lodDivisions <= 0)
                    return;

                m_dirtyProxyIndices = new HashSet<int>();
                m_cellProxyToAabbProxy = new Dictionary<MyClipmapCellProxy, int>();
                m_boundingBoxes = new MyDynamicAABBTreeD(Vector3D.Zero);

                int cellCount = lodDivisions*lodDivisions*lodDivisions;
                m_mergeJobs = new MergeJobInfo[cellCount];
                m_mergedLodMeshProxies = new MyClipmapCellProxy[cellCount];
                m_trackedActors = new HashSet<MyActor>[cellCount];

                for (int divideIndex = 0; divideIndex < cellCount; ++divideIndex)
                {
                    m_mergedLodMeshProxies[divideIndex] = new MyClipmapCellProxy(new MyCellCoord(Lod, GetCellFromDivideIndex(divideIndex)), ref worldMatrix, massiveCenter, massiveRadius, renderFlags, true);
                    m_mergeJobs[divideIndex] = new MergeJobInfo { CurrentWorkId = 0, LodMeshesBeingMerged = new List<LodMeshId>(), NextPossibleMergeStartTime = MyCommon.FrameCounter };
                    m_trackedActors[divideIndex] = new HashSet<MyActor>();
                    m_dirtyProxyIndices.Add(divideIndex);
                }
            }
 private Vector3D CalculateMoments(State state)
 {
     Vector3D vector = new Vector3D(0);
     vector.Z += 0.2f * (_commands.LeftAileron - _commands.RightAileron);
     vector.Y += 0.1f * (_commands.Elevator);
     return vector;
 }
 public static void WorldPositionToRenderCellCoord(int lod, Vector3D referenceVoxelMapPosition, ref Vector3D worldPosition, out Vector3I renderCellCoord)
 {
     Vector3D tmp;
     WorldPositionToLocalPosition(referenceVoxelMapPosition, ref worldPosition, out tmp);
     tmp /= RenderCellSizeInMeters(lod);
     Vector3I.Floor(ref tmp, out renderCellCoord);
 }
Example #26
0
        public RotationAnimator(Vector3D p_RotationStart, Vector3D p_rotationEnd, uint p_durationMs)
        {
            m_rotationStart = p_RotationStart;
            m_rotationEnd = p_rotationEnd;
            m_durationMs = p_durationMs;

        }
Example #27
0
        public TriangleTest(Vector3D a, Vector3D b, Vector3D c)
        {
            this.A = a;
            this.B = b;
            this.C = c;

            Vector2D sa;
            Vector2D sb;
            Vector2D sc;

            sa = new Vector2D(1, 5);
            sb = new Vector2D(2, 3);
            sc = new Vector2D(4, 2);

            this.sA = sa;
            this.sB = sb;
            this.sC = sc;

            triVertices.Add(A);
            triVertices.Add(B);
            triVertices.Add(C);

            AB = (A - B).Length();
            BC = (B - C).Length();
            AC = (C - A).Length();

            lengthOfTheEdge.Add(AB);
            lengthOfTheEdge.Add(BC);
            lengthOfTheEdge.Add(AC);
            lengthOfTheEdge.Sort();

        }
            public virtual void ReadFromXMLNode(XmlNode node)
            {
                try
                {
                    // Deal with model path, must be only one
                    LoadModelPathNode(node);

                    // Deal with the start position
                    XmlNode startPositionNode = node.SelectSingleNode(ModelXMLDefinition.StartPosition);
                    if (startPositionNode != null)
                    {
                        m_ptStartPoint = CPoint3DSerializer.ReadPoint(startPositionNode);
                    }

                    // Read the scaleDirection
                    XmlNode scaleDirectionNode = node.SelectSingleNode(ModelXMLDefinition.SacleDirection);
                    CPoint3D scaleDirection = CPoint3DSerializer.ReadPoint(scaleDirectionNode);

                    Vector3D vec = new Vector3D(scaleDirection.X, scaleDirection.Y, scaleDirection.Z);
                    if (vec.LengthSquared != 0)
                    {
                        vec.Normalize();
                        m_scaleDirection = vec;
                    }
                }
                catch (SystemException ex)
                {
                    string errMsg = ex.Message + "\n" + ex.StackTrace;
                    vtk.vtkOutputWindow.GetInstance().DisplayErrorText(errMsg);
                    throw;
                }
            }
		public bool TrySpawnParticle(Vector3D worldPosition)
		{
			if (!MyFakes.ENABLE_DRIVING_PARTICLES)
				return false;

			MyWheel wheel = Entity as MyWheel;
			if(wheel == null)
				return false;

			var speedMultiplier = wheel.GetTopMostParent().Physics.LinearVelocity.Length() / MyGridPhysics.ShipMaxLinearVelocity();
			var currentTime = MySandboxGame.TotalGamePlayTimeInMilliseconds;
			if (currentTime - m_lastGlobalEffectCreationTime < 5
				|| currentTime - m_lastEffectCreationTime < m_effectCreationInterval * MyUtils.GetRandomFloat(0.9f * (1.5f - speedMultiplier), 1.1f / (0.25f + speedMultiplier)))
				return false;

			MyParticleEffect drivingEffect = null;
			if (!MyParticlesManager.TryCreateParticleEffect(51, out drivingEffect))
				return false;

			m_lastEffectCreationTime = currentTime;
			m_lastGlobalEffectCreationTime = m_lastEffectCreationTime;

			drivingEffect.WorldMatrix = MatrixD.CreateTranslation(worldPosition);
			drivingEffect.Preload = 1.0f;
			var speedScaleMultiplier = 1.0f + speedMultiplier*6.0f;
			drivingEffect.UserScale = 0.25f * speedScaleMultiplier;

			return true;
		}
Example #30
0
 public static Vector3D GnomonicToStereo( Vector3D g )
 {
     g /= m_gScale;
     double dot = g.Dot( g ); // X^2 + Y^2
     double z = -1 / Math.Sqrt( dot + 1 );
     return g*z / (z - 1);
 }
        //
        // Compute scene vertex normals
        //
        public void computeNormals(Scene3ds scene, Scene result)
        {
            Point3D vcenter  = Point3D.Zero;
            float   vcounter = 0.0f;

            for (int i = 0; i < scene.Meshes.Count(); i++)
            {
                Mesh3ds m = scene.Meshes.ElementAt(i);
                // Alloc memory
                Mesh mesh = new Mesh
                {
                    Name = m.Name
                };
                result.Meshes.Add(mesh);

                //mesh._numTexCoords = 0;

                Vector3D[] tmpFaceNormals = new Vector3D[m.faces()];

                // Compute face normals
                for (int fi = 0; fi < m.faces(); fi++)
                {
                    Face3ds   f  = m.face(fi);
                    Vertex3ds p0 = m.vertex(f.P0);
                    Vertex3ds p1 = m.vertex(f.P1);
                    Vertex3ds p2 = m.vertex(f.P2);

                    /*// Compute face middle point
                     * mesh.faceMiddlePoint[fi] = new PVector();
                     * mesh.faceMiddlePoint[fi].x = (p0.X + p1.X + p2.X) / 3.0f;
                     * mesh.faceMiddlePoint[fi].y = (p0.Y + p1.Y + p2.Y) / 3.0f;
                     * mesh.faceMiddlePoint[fi].z = (p0.Z + p1.Z + p2.Z) / 3.0f;*/

                    Point3D v0 = new Point3D(p0.X, p0.Y, p0.Z);
                    Point3D v1 = new Point3D(p1.X, p1.Y, p1.Z);
                    Point3D v2 = new Point3D(p2.X, p2.Y, p2.Z);

                    Vector3D e0 = v1 - v0;
                    Vector3D e1 = v2 - v0;

                    //mesh.faceNormals[fi] = e1.cross(e0);

                    // save a copy of the unnormalized face normal. used for average vertex normals
                    tmpFaceNormals[fi] = Vector3D.Cross(e1, e0);

                    // normalize face normal
                    //mesh.faceNormals[fi].normalize();
                }

                //
                // Compute vertex normals.Take average from adjacent face normals.find coplanar faces or get weighted normals.
                // One could also use the smooth groups from 3ds to compute normals, we'll see about that.
                //
                //PVector v = new PVector();
                TexCoord3ds tc = new TexCoord3ds(0, 0);
                for (int vi = 0; vi < m.vertices(); vi++)
                {
                    Vertex3ds p = m.vertex(vi);
                    vcenter += new Point3D(p.X, p.Y, p.Z);
                    vcounter++;
                    if (m.texCoords() > 0)
                    {
                        tc = m.texCoord(vi);
                    }
                    Vector3D n   = Vector3D.Zero;
                    float    num = 0;
                    for (int fi = 0; fi < m.faces(); fi++)
                    {
                        Face3ds f = m.face(fi);
                        //        Vertex3ds p0 = m.vertex(f.P0);
                        //        Vertex3ds p1 = m.vertex(f.P1);
                        //        Vertex3ds p2 = m.vertex(f.P2);
                        if (vi == f.P0 || vi == f.P1 || vi == f.P2)
                        {
                            num++;
                            n += tmpFaceNormals[fi];                             //mesh.faceNormals[fi] );
                        }
                    }
                    if (num > 0)
                    {
                        n *= 1.0f / (float)num;
                    }
                    n.Normalize();
                    mesh.Normals.Add(n);

                    if (FLIPYZ)
                    {
                        Vector3D tmp = mesh.Normals[vi];
                        mesh.Normals[vi] = new Vector3D(tmp.X, -tmp.Z, tmp.Y);
                    }
                    // Save vertex data
                    if (FLIPYZ)
                    {
                        mesh.Positions.Add(new Point3D(p.X, -p.Z, p.Y));
                    }
                    else
                    {
                        mesh.Positions.Add(new Point3D(p.X, p.Y, p.Z));
                    }

                    // Save texcoord data
                    //mesh._numTexCoords = m.texCoords();
                    if (m.texCoords() > 0)
                    {
                        if (FLIPV)
                        {
                            mesh.TextureCoordinates.Add(new Point3D(tc.U, 1.0f - tc.V, 0));
                        }
                        else
                        {
                            mesh.TextureCoordinates.Add(new Point3D(tc.U, tc.V, 0));
                        }
                    }
                }
            }

            if (vcounter > 0.0)
            {
                vcenter /= vcounter;
            }
        }
 //multiplication
 public static Quaternion operator *(Quaternion a, Quaternion b) =>
     new Quaternion(a.r*b.r - a.c*b.c, (a.r & b.c) + (b.r & a.c) + (Vector3D.CrossProduct(a.c, b.c)));
        public static List <ImprovedSpawnGroup> GetSpawnGroups(List <string> spawnGroups, Vector3D coords, out Dictionary <string, List <string> > validFactions)
        {
            MyPlanet planet             = SpawnResources.GetNearestPlanet(coords);
            var      planetRestrictions = new List <string>(Settings.General.PlanetSpawnsDisableList.ToList());

            validFactions = new Dictionary <string, List <string> >();

            if (planet != null)
            {
                if (planetRestrictions.Contains(planet.Generator.Id.SubtypeName) == true)
                {
                    return(new List <ImprovedSpawnGroup>());
                }
            }

            string planetName = "";

            if (planet != null)
            {
                planetName = planet.Generator.Id.SubtypeId.ToString();
            }

            var eligibleGroups = new List <ImprovedSpawnGroup>();

            //Filter Eligible Groups To List
            foreach (var spawnGroup in SpawnGroupManager.SpawnGroups)
            {
                if (!spawnGroups.Contains(spawnGroup.SpawnGroupName))
                {
                    continue;
                }

                if (spawnGroup.RivalAiAnySpawn == false)
                {
                    if (planet == null && spawnGroup.RivalAiSpaceSpawn == false)
                    {
                        continue;
                    }

                    if (planet != null)
                    {
                        var airDensity = planet.GetAirDensity(coords);

                        if (spawnGroup.RivalAiAtmosphericSpawn == false || planet.HasAtmosphere == false || airDensity < 0.4f)
                        {
                            continue;
                        }
                    }
                }

                if (SpawnResources.CheckCommonConditions(spawnGroup, coords, planet, false) == false)
                {
                    continue;
                }

                var validFactionsList = SpawnResources.ValidNpcFactions(spawnGroup, coords);

                if (validFactionsList.Count == 0)
                {
                    continue;
                }

                if (validFactions.ContainsKey(spawnGroup.SpawnGroupName) == false)
                {
                    validFactions.Add(spawnGroup.SpawnGroupName, validFactionsList);
                }

                if (spawnGroup.Frequency > 0)
                {
                    if (Settings.SpaceCargoShips.UseMaxSpawnGroupFrequency == true && spawnGroup.Frequency > Settings.SpaceCargoShips.MaxSpawnGroupFrequency * 10)
                    {
                        spawnGroup.Frequency = (int)Math.Round((double)Settings.SpaceCargoShips.MaxSpawnGroupFrequency * 10);
                    }

                    for (int i = 0; i < spawnGroup.Frequency; i++)
                    {
                        eligibleGroups.Add(spawnGroup);
                    }
                }
            }

            return(eligibleGroups);
        }
Example #34
0
        Tuple <Point3DCollection, Point3DCollection> GetDepthData(MultiSourceFrame frame)
        {
            byte[] array = null;

            // filter background with bodyIndex
            using (BodyIndexFrame bodyIndexFrame = frame.BodyIndexFrameReference.AcquireFrame())
            {
                if (bodyIndexFrame != null)
                {
                    var description = bodyIndexFrame.FrameDescription;
                    array = new byte[description.Width * description.Height];
                    bodyIndexFrame.CopyFrameDataToArray(array);
                }
            }

            var depthFrameReference = frame.DepthFrameReference;
            var depthFrame          = depthFrameReference.AcquireFrame();

            if (depthFrame == null)
            {
                return(null);
            }

            int height = depthFrame.FrameDescription.Height;
            int width  = depthFrame.FrameDescription.Width;

            CameraSpacePoint[] depth2xyz   = new CameraSpacePoint[height * width];
            CameraSpacePoint   shoulderPos = new CameraSpacePoint();
            BBox box = new BBox();
            Point3DCollection result = new Point3DCollection();

            using (var bodyFrame = frame.BodyFrameReference.AcquireFrame())
            {
                if (frame != null)
                {
                    var bodies = new Body[bodyFrame.BodyFrameSource.BodyCount];

                    bodyFrame.GetAndRefreshBodyData(bodies);

                    foreach (var body in bodies)
                    {
                        if (body != null)
                        {
                            if (body.IsTracked)
                            {
                                // Find the joints

                                Joint thumbRight = body.Joints[JointType.ThumbRight];
                                Joint thumbLeft  = body.Joints[JointType.ThumbLeft];

                                // Tip
                                Joint tipRight = body.Joints[JointType.HandTipRight];
                                Joint tipLeft  = body.Joints[JointType.HandTipLeft];

                                Joint handRight = body.Joints[JointType.HandRight];
                                Joint handLeft  = body.Joints[JointType.HandLeft];

                                // elbow
                                Joint elbowLeft = body.Joints[JointType.ElbowLeft];

                                // shoulder
                                shoulderPos = body.Joints[JointType.ShoulderLeft].Position;


                                tipLeft.Position   = FilterGroup.GetFilter(FilterGroup.Description.Fingertip).Filter(tipLeft.Position);
                                handLeft.Position  = FilterGroup.GetFilter(FilterGroup.Description.Hand).Filter(handLeft.Position);
                                thumbLeft.Position = FilterGroup.GetFilter(FilterGroup.Description.ThumbTip).Filter(thumbLeft.Position);
                                elbowLeft.Position = FilterGroup.GetFilter(FilterGroup.Description.Elbow).Filter(elbowLeft.Position);

                                result = new Point3DCollection
                                {
                                    Parser3DPoint.FromCameraSpaceToPoint3D(handLeft.Position),
                                    Parser3DPoint.FromCameraSpaceToPoint3D(tipLeft.Position),
                                    Parser3DPoint.FromCameraSpaceToPoint3D(thumbLeft.Position),
                                    Parser3DPoint.FromCameraSpaceToPoint3D(elbowLeft.Position)
                                };


                                //box.Extend(Parser3DPoint.FromCameraSpaceToPoint3D(shoulderPos));
                                box.Extend(Parser3DPoint.FromCameraSpaceToPoint3D(elbowLeft.Position));
                                box.Extend(Parser3DPoint.FromCameraSpaceToPoint3D(handLeft.Position));
                                box.Extend(Parser3DPoint.FromCameraSpaceToPoint3D(tipLeft.Position));
                                box.Extend(Parser3DPoint.FromCameraSpaceToPoint3D(thumbLeft.Position));

                                var vector = new Vector3D
                                {
                                    X = tipRight.Position.X - handRight.Position.X,
                                    Y = tipRight.Position.Y - handRight.Position.Y,
                                    Z = tipRight.Position.Z - handRight.Position.Z
                                };

                                vector.Normalize();
                                var tipR = tipRight.Position;
                            }
                        }
                    }
                }
            }

            ushort[] depthFrameData = new ushort[height * width];

            depthFrame.CopyFrameDataToArray(depthFrameData);
            var radius = 0.08f;

            // Process depth frame data...
            cM.MapDepthFrameToCameraSpace(depthFrameData, depth2xyz);

            for (int i = 0; i < depthFrameData.Length; i++)
            {
                //filter everything around the box
                if (array[i] == 255 ||
                    (box.GetMaxPoint().Z + radius) < depth2xyz[i].Z ||
                    (box.GetMaxPoint().Y + radius) < depth2xyz[i].Y ||
                    (box.GetMaxPoint().X + radius) < depth2xyz[i].X ||
                    (box.GetMinPoint().Z - radius) > depth2xyz[i].Z ||
                    (box.GetMinPoint().Y - radius) > depth2xyz[i].Y ||
                    (box.GetMinPoint().X - radius) > depth2xyz[i].X
                    )
                {
                    depth2xyz[i].Z = -10000;
                }
            }

            /*
             * var boxCloud = new Point3DCollection
             *  {
             *      box.GetMinPoint(),
             *      box.GetMaxPoint()
             *  };
             *
             * renderer.CreatePointCloud(boxCloud, Brushes.DeepPink,false, 0.0235f);
             */
            return(new Tuple <Point3DCollection, Point3DCollection>(Parser3DPoint.FromCameraSpaceToPoint3DCollection(depth2xyz, height * width), result));
        }
Example #35
0
 public CommandCreateJunk(string name, Vector3D position, Quaternion rotation)
 {
     Name     = name;
     Position = position;
     Rotation = rotation;
 }
Example #36
0
        public void ResetLights()
        {
            //<AmbientLight Color="White" />
            //<DirectionalLight Color="White" Direction="-1,-1,-1" />
            //<PointLight Color="White" ConstantAttenuation="1" LinearAttenuation="1" Position="0,0,0" QuadraticAttenuation="1" Range="0" />
            //<SpotLight Color="White" ConstantAttenuation="1" Direction="-1,-1,-1" InnerConeAngle="10" LinearAttenuation="1" OuterConeAngle="10" Position="0,0,0" QuadraticAttenuation="1" Range="0" />
            lights.Children.Clear();

            MItDag dagIterator = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kLight);

            for ( ; !dagIterator.isDone; dagIterator.next())
            {
                MDagPath lightPath = new MDagPath();
                dagIterator.getPath(lightPath);

                MFnLight light     = new MFnLight(lightPath);
                bool     isAmbient = light.lightAmbient;
                MColor   mcolor    = light.color;
                Color    color     = Color.FromScRgb(1.0f, mcolor.r, mcolor.g, mcolor.b);
                if (isAmbient)
                {
                    AmbientLight ambient = new AmbientLight(color);
                    lights.Children.Add(ambient);
                    continue;
                }

                MFloatVector lightDirection = light.lightDirection(0, MSpace.Space.kWorld);
                Vector3D     direction      = new Vector3D(lightDirection.x, lightDirection.y, lightDirection.z);
                bool         isDiffuse      = light.lightDiffuse;
                try {
                    MFnDirectionalLight dirLight    = new MFnDirectionalLight(lightPath);
                    DirectionalLight    directional = new DirectionalLight(color, direction);
                    lights.Children.Add(directional);
                    continue;
                } catch {
                }

                MObject               transformNode = lightPath.transform;
                MFnDagNode            transform     = new MFnDagNode(transformNode);
                MTransformationMatrix matrix        = new MTransformationMatrix(transform.transformationMatrix);
                double []             threeDoubles  = new double [3];
                int rOrder = 0;                 //MTransformationMatrix.RotationOrder rOrder ;
                matrix.getRotation(threeDoubles, out rOrder, MSpace.Space.kWorld);
                matrix.getScale(threeDoubles, MSpace.Space.kWorld);
                MVector pos      = matrix.getTranslation(MSpace.Space.kWorld);
                Point3D position = new Point3D(pos.x, pos.y, pos.z);
                try {
                    MFnPointLight pointLight = new MFnPointLight(lightPath);
                    PointLight    point      = new PointLight(color, position);
                    //point.ConstantAttenuation = pointLight.; // LinearAttenuation / QuadraticAttenuation
                    //point.Range = pointLight.rayDepthLimit;
                    lights.Children.Add(point);
                    continue;
                } catch {
                }

                try {
                    MFnSpotLight spotLight      = new MFnSpotLight(lightPath);
                    MAngle       InnerConeAngle = new MAngle(spotLight.coneAngle);
                    MAngle       OuterConeAngle = new MAngle(spotLight.penumbraAngle);
                    SpotLight    spot           = new SpotLight(color, position, direction, OuterConeAngle.asDegrees, InnerConeAngle.asDegrees);
                    spot.ConstantAttenuation = spotLight.dropOff;                     // LinearAttenuation / QuadraticAttenuation
                    //spot.Range =spotLight.rayDepthLimit ;
                    lights.Children.Add(spot);
                    continue;
                } catch {
                }
            }
        }
Example #37
0
        public void ExecuteCamera(object sender, ExecutedRoutedEventArgs e)
        {
            if (SelFile.T == null)
            {
                return;
            }
            var inst = SelFile.T.SelectedItem as BcfInstance;

            if (inst == null)
            {
                return;
            }
            var v = inst.VisualizationInfo;

            if (v == null)
            {
                return;
            }

            var position    = new XbimPoint3D();
            var direction   = new XbimPoint3D();
            var upDirection = new XbimPoint3D();

            XbimVector3D directionV;
            XbimVector3D upDirectionV;

            if (v.PerspectiveCamera != null)
            {
                var pc = v.PerspectiveCamera;
                position    = new XbimPoint3D(pc.CameraViewPoint.X, pc.CameraViewPoint.Y, pc.CameraViewPoint.Z);
                direction   = new XbimPoint3D(pc.CameraDirection.X, pc.CameraDirection.Y, pc.CameraDirection.Z);
                upDirection = new XbimPoint3D(pc.CameraUpVector.X, pc.CameraUpVector.Y, pc.CameraUpVector.Z);

                _xpWindow.DrawingControl.Viewport.Orthographic = false;
                var pCam = _xpWindow.DrawingControl.Viewport.Camera as System.Windows.Media.Media3D.PerspectiveCamera;
                if (pCam != null)
                {
                    pCam.FieldOfView = pc.FieldOfView;
                }
            }
            else if (v.OrthogonalCamera != null)
            {
                var pc = v.OrthogonalCamera;
                _xpWindow.DrawingControl.Viewport.Orthographic = true;
                position    = new XbimPoint3D(pc.CameraViewPoint.X, pc.CameraViewPoint.Y, pc.CameraViewPoint.Z);
                direction   = new XbimPoint3D(pc.CameraDirection.X, pc.CameraDirection.Y, pc.CameraDirection.Z);
                upDirection = new XbimPoint3D(pc.CameraUpVector.X, pc.CameraUpVector.Y, pc.CameraUpVector.Z);

                var pCam = _xpWindow.DrawingControl.Viewport.Camera as OrthographicCamera;
                if (pCam != null)
                {
                    pCam.Width = pc.ViewToWorldScale;
                }
            }
            directionV   = new XbimVector3D(direction.X, direction.Y, direction.Z);
            upDirectionV = new XbimVector3D(upDirection.X, upDirection.Y, upDirection.Z);

            var pos   = new Point3D(position.X, position.Y, position.Z);
            var dir   = new Vector3D(directionV.X, directionV.Y, directionV.Z);
            var upDir = new Vector3D(upDirectionV.X, upDirectionV.Y, upDirectionV.Z);

            _xpWindow.DrawingControl.Viewport.SetView(pos, dir, upDir, 500);

            if (v.ClippingPlanes.Any())
            {
                var curP = v.ClippingPlanes[0];
                _xpWindow.DrawingControl.SetCutPlane(
                    curP.Location.X, curP.Location.Y, curP.Location.Z,
                    curP.Direction.X, curP.Direction.Y, curP.Direction.Z
                    );
            }
            else
            {
                _xpWindow.DrawingControl.ClearCutPlane();
            }

            // xpWindow.DrawingControl.Viewport.FieldOfViewText
        }
 public static Quaternion Rotate(Vector3D p, Vector3D v, double θ)
 {
     Quaternion rot = new Quaternion(Math.Cos(θ), Math.Sin(θ) & p);
     Quaternion point = new Quaternion(0, p);
     return (rot * (point * -rot));
 }
 public Quaternion(double scalar, Vector3D vect)
 {
     r = scalar;
     c = vect;
 }
 public Quaternion(double r, double x, double y, double z)
 {
     this.r = r;
     this.c = new Vector3D(x, y, z);
 }
 public static Vector3D PlaneDistance(Vector3D a, Vector3D b, Vector3D c, Vector3D q)
     => (q - ClosestPointPlane(a, b, c, q));
 /// <summary>
 /// method takes in two vectors in a plane, AB and AC, and uses then to get a 
 /// crossproduct and then a normal vector of the plane.  This is then used
 /// with the coefficient of restitution, , and the initial velocity, v, 
 /// and returns the new velocity after a collision
 /// </summary>
 /// <param name="v">initial velocity</param>
 /// <param name="ε">coefficient of restitution</param>
 /// <param name="AB">first vector in the plane</param>
 /// <param name="AC">second vector in the plane</param>
 /// <returns></returns>
 public static Vector3D CollisionWithPlane(Vector3D v, double ε, Vector3D AB, Vector3D AC)
     => (v - ((1 + ε) * (v * !CrossProduct(AB, AC)) & !CrossProduct(AB, AC)));
 public static Vector3D LineDistance(Vector3D q, Vector3D p, Vector3D d) =>
     (q - ClosestPointLine(q, p, d));
 /// <summary>
 /// ClosestPointPlane takes in the 3 points on a plane: A,B, and C and 
 /// the point of comparison Q, it returns the closest point
 /// 
 /// PlaneDistance takes the ClosestPointPlane and gives the distance from
 /// the point Q to the closest point
 /// </summary>
 /// <param name="a">First Point on the plane</param>
 /// <param name="b">Second Point on the plane</param>
 /// <param name="c">Third Point on the plane</param>
 /// <param name="q">Point of reference for the closest point</param>
 /// <returns></returns>
 public static Vector3D ClosestPointPlane(Vector3D a, Vector3D b, Vector3D c, Vector3D q)
     //S = Q - Proj(PQ onto n)
     => (q - ((q - a) > CrossProduct(b - a, c - a)));
 /// <summary>
 /// Method to make it so you can take the crossproduct
 /// of two vectors
 /// </summary>
 /// <param name="u">first vector</param>
 /// <param name="v">second vector</param>
 /// <returns>the cross product of the two inputed vectors</returns>
 public static Vector3D CrossProduct(Vector3D u, Vector3D v) =>
     new Vector3D(u.GetY() * v.GetZ() - v.GetY() * u.GetZ(),   //X
                -(u.GetX() * v.GetZ() - v.GetX() * u.GetZ()),  //Y
                  u.GetX() * v.GetY() - v.GetX() * u.GetY());  //Z
                  u.GetX() * v.GetY() - v.GetX() * u.GetY());  //Z
 /// <summary>
 /// ClosestPointLine takes in three vectors: q(point), p(point on the line)
 /// and d(the direction the line goes) and returns what the closest point 
 /// on the line relative to the point Q is
 /// 
 /// LineDistance takes the closest point and the reference point, Q, and
 /// finds the distance between the two
 /// </summary>
 /// <param name="q">Point you're finding a point from</param>
 /// <param name="p">Point on the line</param>
 /// <param name="d">direction of the line</param>
 /// <returns></returns>
 public static Vector3D ClosestPointLine(Vector3D q, Vector3D p, Vector3D d)
     => (p + ((q - p) > d));
        public static void CustomSpawnRequest(List <string> spawnGroups, Vector3D coords, Vector3D forwardDir, Vector3D upDir, Vector3 velocity)
        {
            if (Settings.General.UseMaxNpcGrids == true)
            {
                var totalNPCs = NPCWatcher.ActiveNPCs.Count;

                if (totalNPCs >= Settings.General.MaxGlobalNpcGrids)
                {
                    //return "Spawning Aborted. Max Global NPCs Limit Reached.";
                    return;
                }
            }

            var validFactions  = new Dictionary <string, List <string> >();
            var spawnGroupList = GetSpawnGroups(spawnGroups, coords, out validFactions);

            if (spawnGroupList.Count == 0)
            {
                return;
                //return "No Eligible Spawn Groups Could Be Found To Spawn Near Player.";
            }

            var  spawnGroup      = spawnGroupList[SpawnResources.rnd.Next(0, spawnGroupList.Count)];
            var  startPathCoords = Vector3D.Zero;
            var  endPathCoords   = Vector3D.Zero;
            bool successfulPath  = false;

            //Get Directions
            var  spawnForwardDir = forwardDir;
            var  spawnUpDir      = upDir;
            var  spawnMatrix     = MatrixD.CreateWorld(coords, spawnForwardDir, spawnUpDir);
            long gridOwner       = 0;
            var  randFactionTag  = spawnGroup.FactionOwner;

            if (validFactions.ContainsKey(spawnGroup.SpawnGroupName))
            {
                randFactionTag = validFactions[spawnGroup.SpawnGroupName][SpawnResources.rnd.Next(0, validFactions[spawnGroup.SpawnGroupName].Count)];
            }

            if (NPCWatcher.NPCFactionTagToFounder.ContainsKey(randFactionTag) == true)
            {
                gridOwner = NPCWatcher.NPCFactionTagToFounder[randFactionTag];
            }
            else
            {
                Logger.AddMsg("Could Not Find Faction Founder For: " + randFactionTag);
            }

            foreach (var prefab in spawnGroup.SpawnGroup.Prefabs)
            {
                var options       = SpawnGroupManager.CreateSpawningOptions(spawnGroup, prefab);
                var spawnPosition = Vector3D.Transform((Vector3D)prefab.Position, spawnMatrix);
                var speedL        = velocity;
                var speedA        = Vector3.Zero;
                var gridList      = new List <IMyCubeGrid>();

                //Grid Manipulation
                GridBuilderManipulation.ProcessPrefabForManipulation(prefab.SubtypeId, spawnGroup, "SpaceCargoShip", prefab.Behaviour);

                try{
                    MyAPIGateway.PrefabManager.SpawnPrefab(gridList, prefab.SubtypeId, spawnPosition, spawnForwardDir, spawnUpDir, speedL, speedA, prefab.BeaconText, options, gridOwner);
                }catch (Exception exc) {
                    Logger.AddMsg("Something Went Wrong With Prefab Spawn Manager.", true);
                }

                var pendingNPC = new ActiveNPC();
                pendingNPC.SpawnGroupName        = spawnGroup.SpawnGroupName;
                pendingNPC.SpawnGroup            = spawnGroup;
                pendingNPC.InitialFaction        = randFactionTag;
                pendingNPC.faction               = MyAPIGateway.Session.Factions.TryGetFactionByTag(pendingNPC.InitialFaction);
                pendingNPC.Name                  = prefab.SubtypeId;
                pendingNPC.GridName              = MyDefinitionManager.Static.GetPrefabDefinition(prefab.SubtypeId).CubeGrids[0].DisplayName;
                pendingNPC.StartCoords           = startPathCoords;
                pendingNPC.CurrentCoords         = startPathCoords;
                pendingNPC.EndCoords             = endPathCoords;
                pendingNPC.SpawnType             = "CustomSpawn";
                pendingNPC.AutoPilotSpeed        = speedL.Length();
                pendingNPC.CleanupIgnore         = spawnGroup.IgnoreCleanupRules;
                pendingNPC.ForceStaticGrid       = spawnGroup.ForceStaticGrid;
                pendingNPC.KeenAiName            = prefab.Behaviour;
                pendingNPC.KeenAiTriggerDistance = prefab.BehaviourActivationDistance;

                if (string.IsNullOrEmpty(pendingNPC.KeenAiName) == false)
                {
                    Logger.AddMsg("AI Detected In Prefab: " + prefab.SubtypeId + " in SpawnGroup: " + spawnGroup.SpawnGroup.Id.SubtypeName);
                }

                if (spawnGroup.RandomizeWeapons == true)
                {
                    pendingNPC.ReplenishedSystems = false;
                    pendingNPC.ReplacedWeapons    = true;
                }
                else if ((MES_SessionCore.NPCWeaponUpgradesModDetected == true || Settings.General.EnableGlobalNPCWeaponRandomizer == true) && spawnGroup.IgnoreWeaponRandomizerMod == false)
                {
                    pendingNPC.ReplenishedSystems = false;
                    pendingNPC.ReplacedWeapons    = true;
                }
                else if (spawnGroup.ReplenishSystems == true)
                {
                    pendingNPC.ReplenishedSystems = false;
                }

                NPCWatcher.PendingNPCs.Add(pendingNPC);
            }

            Logger.SkipNextMessage = false;
            //return "Spawning Group - " + spawnGroup.SpawnGroup.Id.SubtypeName;
            return;
        }
 /// <summary>
 /// Sets a vector for a line given two points in Vector3D form
 /// </summary>
 /// <param name="p1">Vector3D of the start point</param>
 /// <param name="p2">Vector3d of the end point</param>
 public void SetRectGivenTwoPoints(Vector3D p1, Vector3D p2)
 {
     this.x = p2.GetX() - p1.GetX();
     this.y = p2.GetY() - p1.GetY();
     this.z = p2.GetZ() - p1.GetZ();
 }
Example #49
0
 public static bool PointInEllipsoid(Vector3D point, MatrixD ellipsoidMatrixInv)
 {
     return(Vector3D.Transform(point, ellipsoidMatrixInv).LengthSquared() <= 1);
 }
Example #50
0
        public Vector3D Update(Vector3D missilePosition, Vector3D missileVelocity, Vector3D targetPosition, Vector3D targetVelocity, Vector3D?gravity = null)
        {
            Vector3D targetAcceleration = Vector3D.Zero;

            if (!_lastVelocitySet)
            {
                _lastVelocitySet = true;
            }
            else
            {
                targetAcceleration = (targetVelocity - _lastVelocity) * _updatesPerSecond;
            }
            _lastVelocity = targetVelocity;

            return(GetPointingVector(missilePosition, missileVelocity, targetPosition, targetVelocity, targetAcceleration, gravity == null ? Vector3D.Zero : gravity.Value));
        }
Example #51
0
        /*
        ** Returns the point on the line formed by (point1 + dir1 * x) that is closest to the point
        ** on the line formed by line (point2 + dir2 * t)
        */

        public static Vector3D GetClosestPointOnLine1(Vector3D point1, Vector3D dir1, Vector3D point2, Vector3D dir2)
        {
            Vector3D axis = Vector3D.Cross(dir1, dir2);

            if (Vector3D.IsZero(axis))
            {
                return(point1);
            }
            Vector3D perpDir2  = Vector3D.Cross(dir2, axis);
            Vector3D point1To2 = point2 - point1;

            return(point1 + Vector3D.Dot(point1To2, perpDir2) / Vector3D.Dot(dir1, perpDir2) * dir1);
        }
Example #52
0
 protected abstract Vector3D GetPointingVector(Vector3D missilePosition, Vector3D missileVelocity, Vector3D targetPosition, Vector3D targetVelocity, Vector3D targetAcceleration, Vector3D gravity);
Example #53
0
        protected override Vector3D GetPointingVector(Vector3D missilePosition, Vector3D missileVelocity, Vector3D targetPosition, Vector3D targetVelocity, Vector3D targetAcceleration, Vector3D gravity)
        {
            Vector3D missileToTarget           = targetPosition - missilePosition;
            Vector3D missileToTargetNorm       = Vector3D.Normalize(missileToTarget);
            Vector3D relativeVelocity          = targetVelocity - missileVelocity;
            Vector3D lateralTargetAcceleration = (targetAcceleration - Vector3D.Dot(targetAcceleration, missileToTargetNorm) * missileToTargetNorm);
            Vector3D gravityCompensationTerm   = 1.1 * -(gravity - Vector3D.Dot(gravity, missileToTargetNorm) * missileToTargetNorm);

            Vector3D lateralAcceleration = GetLatax(missileToTarget, missileToTargetNorm, relativeVelocity, lateralTargetAcceleration, gravityCompensationTerm);

            if (Vector3D.IsZero(lateralAcceleration))
            {
                return(missileToTarget);
            }

            double diff = MissileAcceleration * MissileAcceleration - lateralAcceleration.LengthSquared();

            if (diff < 0)
            {
                return(lateralAcceleration); //fly parallel to the target
            }
            return(lateralAcceleration + Math.Sqrt(diff) * missileToTargetNorm);
        }
Example #54
0
        /*
        ** Returns the point on the line1 that is closest to the point on line2
        */

        public static Vector3D GetClosestPointOnLine2(Vector3D line1Start, Vector3D line1End, Vector3D line2Start, Vector3D line2End)
        {
            Vector3D dir1 = line1End - line1Start;
            Vector3D dir2 = line2End - line2Start;
            Vector3D axis = Vector3D.Cross(dir1, dir2);

            if (Vector3D.IsZero(axis))
            {
                return(line1Start);
            }
            Vector3D perpDir2  = Vector3D.Cross(dir2, axis);
            Vector3D point1To2 = line2Start - line1Start;

            return(line1Start + Vector3D.Dot(point1To2, perpDir2) / Vector3D.Dot(dir1, perpDir2) * dir1);
        }
Example #55
0
        internal static bool WeaponLookAt(Weapon weapon, ref Vector3D targetDir, double targetDistSqr, bool setWeapon, bool canSeeOnly, out bool isTracking)
        {
            var system = weapon.System;
            var target = weapon.Target;

            isTracking = false;
            //Get weapon direction and orientation
            Vector3D currentVector;

            Vector3D.CreateFromAzimuthAndElevation(weapon.Azimuth, weapon.Elevation, out currentVector);
            Vector3D.Rotate(ref currentVector, ref weapon.WeaponConstMatrix, out currentVector);

            var      up = weapon.MyPivotUp;
            Vector3D left;

            Vector3D.Cross(ref up, ref currentVector, out left);
            if (!Vector3D.IsUnit(ref left) && !Vector3D.IsZero(left))
            {
                left.Normalize();
            }
            Vector3D forward;

            Vector3D.Cross(ref left, ref up, out forward);
            var constraintMatrix = new MatrixD {
                Forward = forward, Left = left, Up = up,
            };

            // ugly as sin inlined compute GetRotationAngles + AngleBetween, returning the desired az/el doubles;
            var      transposeMatrix = MatrixD.Transpose(constraintMatrix);
            Vector3D localTargetVector;

            Vector3D.TransformNormal(ref targetDir, ref transposeMatrix, out localTargetVector);
            var flattenedTargetVector = new Vector3D(localTargetVector.X, 0, localTargetVector.Z);
            var azVecIsZero           = Vector3D.IsZero(flattenedTargetVector);
            var flatSqr = flattenedTargetVector.LengthSquared();

            var desiredAzimuth = azVecIsZero ? 0 : Math.Acos(MathHelperD.Clamp(-flattenedTargetVector.Z / Math.Sqrt(flatSqr), -1, 1)) * -Math.Sign(localTargetVector.X); //right is positive;

            if (Math.Abs(desiredAzimuth) < 1E-6 && localTargetVector.Z > 0)                                                                                              //check for straight back case
            {
                desiredAzimuth = Math.PI;
            }

            double desiredElevation;

            if (Vector3D.IsZero(flattenedTargetVector)) //check for straight up case
            {
                desiredElevation = MathHelper.PiOver2 * Math.Sign(localTargetVector.Y);
            }
            else
            {
                var elVecIsZero = Vector3D.IsZero(localTargetVector) || Vector3D.IsZero(flattenedTargetVector);
                desiredElevation = elVecIsZero ? 0 : Math.Acos(MathHelperD.Clamp(localTargetVector.Dot(flattenedTargetVector) / Math.Sqrt(localTargetVector.LengthSquared() * flatSqr), -1, 1)) * Math.Sign(localTargetVector.Y); //up is positive
            }

            // return result of desired values being in tolerances
            if (canSeeOnly)
            {
                if (weapon.Azimuth + desiredAzimuth > weapon.MaxAzToleranceRadians && weapon.MaxAzToleranceRadians < Math.PI)
                {
                    return(false);
                }

                if (weapon.Azimuth + desiredAzimuth < weapon.MinAzToleranceRadians && weapon.MinAzToleranceRadians > -Math.PI)
                {
                    return(false);
                }

                if (desiredElevation < weapon.MinElToleranceRadians || desiredElevation > weapon.MaxElToleranceRadians)
                {
                    return(false);
                }

                return(true);
            }

            // check for backAround constraint
            double azToTraverse;

            if (weapon.MaxAzToleranceRadians < Math.PI && weapon.MinAzToleranceRadians > -Math.PI)
            {
                var azAngle = weapon.Azimuth + desiredAzimuth;
                if (azAngle > Math.PI)
                {
                    azAngle -= MathHelperD.TwoPi;
                }
                else if (azAngle < -Math.PI)
                {
                    azAngle = MathHelperD.TwoPi + azAngle;
                }
                azToTraverse = azAngle - weapon.Azimuth;
            }
            else
            {
                azToTraverse = desiredAzimuth;
            }

            // Clamp step within limits.
            var azStep = MathHelperD.Clamp(azToTraverse, -system.AzStep, system.AzStep);
            var elStep = MathHelperD.Clamp(desiredElevation - weapon.Elevation, -system.ElStep, system.ElStep);

            // epsilon based on target type and distance
            var epsilon = target.IsProjectile || system.Session.Tick120 ? 1E-06d : targetDistSqr <= 640000 ? 1E-03d : targetDistSqr <= 3240000 ? 1E-04d : 1E-05d;

            // check if step is within epsilon of zero;
            var azLocked = MyUtils.IsZero(azStep, (float)epsilon);
            var elLocked = MyUtils.IsZero(elStep, (float)epsilon);

            // are az and el both within tolerance of target
            var locked = azLocked && elLocked;

            // Compute actual angle to rotate subparts
            var az = weapon.Azimuth + azStep;
            var el = weapon.Elevation + elStep;

            // This is where we should clamp. az and el are measured relative the WorldMatrix.Forward.
            // desiredAzimuth is measured off of the CURRENT heading of the barrel. The limits are based off of
            // WorldMatrix.Forward as well.
            var azHitLimit = false;
            var elHitLimit = false;

            // Check azimuth angles
            if (az > weapon.MaxAzToleranceRadians && weapon.MaxAzToleranceRadians < Math.PI)
            {
                // Hit upper azimuth limit
                az         = weapon.MaxAzToleranceRadians;
                azHitLimit = true;
            }
            else if (az < weapon.MinAzToleranceRadians && weapon.MinAzToleranceRadians > -Math.PI)
            {
                // Hit lower azimuth limit
                az         = weapon.MinAzToleranceRadians;
                azHitLimit = true;
            }

            // Check elevation angles
            if (el > weapon.MaxElToleranceRadians)
            {
                // Hit upper elevation limit
                el         = weapon.MaxElToleranceRadians;
                elHitLimit = true;
            }
            else if (el < weapon.MinElToleranceRadians)
            {
                // Hit lower elevation limit
                el         = weapon.MinElToleranceRadians;
                elHitLimit = true;
            }


            // Weapon has a degree of freedom to move towards target
            var tracking = !azHitLimit && !elHitLimit;

            if (setWeapon)
            {
                isTracking = tracking;

                if (!azLocked)
                {
                    weapon.Azimuth     = az;
                    weapon.AzimuthTick = system.Session.Tick;
                }

                if (!elLocked)
                {
                    weapon.Elevation     = el;
                    weapon.ElevationTick = system.Session.Tick;
                }
            }


            return(!locked);
        }
Example #56
0
        internal static double CalculateRotorDeviationAngle(Vector3D forwardVector, MatrixD lastOrientation)
        {
            var flattenedForwardVector = Rejection(forwardVector, lastOrientation.Up);

            return(AngleBetween(flattenedForwardVector, lastOrientation.Forward) * Math.Sign(flattenedForwardVector.Dot(lastOrientation.Left)));
        }
Example #57
0
        protected override Vector3D GetLatax(Vector3D missileToTarget, Vector3D missileToTargetNorm, Vector3D relativeVelocity, Vector3D lateralTargetAcceleration, Vector3D gravityCompensationTerm)
        {
            Vector3D omega = Vector3D.Cross(missileToTarget, relativeVelocity) / Math.Max(missileToTarget.LengthSquared(), 1); //to combat instability at close range

            return(NavConstant * relativeVelocity.Length() * Vector3D.Cross(omega, missileToTargetNorm)
                   + NavAccelConstant * lateralTargetAcceleration
                   + gravityCompensationTerm); //normal to LOS
        }
Example #58
0
 protected abstract Vector3D GetLatax(Vector3D missileToTarget, Vector3D missileToTargetNorm, Vector3D relativeVelocity, Vector3D lateralTargetAcceleration, Vector3D gravityCompensationTerm);
Example #59
0
        public void Check(Projectile p)
        {
            Vector3D End = p.Position + p.Velocity * Tools.Tick;

            IHitInfo hit;

            MyAPIGateway.Physics.CastRay(p.Position, End, out hit);
            if (hit != null)
            {
                Tools.Debug($"----- ricochet check start -----");
                if (hit.HitEntity is IMyDestroyableObject)
                {
                    p.Expired = true;
                    (hit.HitEntity as IMyDestroyableObject).DoDamage(p.Ammo.ProjectileMassDamage, MyStringHash.GetOrCompute(p.Ammo.SubtypeId), false, null, p.ShooterId);
                }
                else if (hit.HitEntity is IMyCubeGrid)
                {
                    Tools.Debug($"hit cube grid");
                    IMyCubeGrid grid = hit.HitEntity as IMyCubeGrid;

                    Vector3I?hitPos = grid.RayCastBlocks(hit.Position, hit.Position + Vector3D.Normalize(p.Velocity));  // p.Direction
                    if (hitPos.HasValue)
                    {
                        Tools.Debug($"hit block");
                        IMySlimBlock block = grid.GetCubeBlock(hitPos.Value);

                        Vector3 hitObjectVelocity = Vector3.Zero;
                        if (hit.HitEntity.Physics != null)
                        {
                            hitObjectVelocity = hit.HitEntity.Physics.LinearVelocity;
                        }

                        Vector3D relativeV      = p.Velocity - hitObjectVelocity;
                        float    NotHitAngle    = (float)Tools.AngleBetween(-Vector3D.Normalize(relativeV), hit.Normal);
                        float    HitAngle       = (90f - NotHitAngle);
                        float    NotHitFraction = NotHitAngle / 90f;

                        float random = (float)Tools.Random.NextDouble();

                        if (HitAngle < DeflectionAngle && RicochetChance > random)
                        {
                            Tools.Debug($"angle {HitAngle} < {DeflectionAngle}");
                            // Apply impulse
                            float impulse = p.Ammo.ProjectileHitImpulse * NotHitFraction * MaxVelocityTransfer;
                            if (hit.HitEntity.Physics != null)
                            {
                                hit.HitEntity.Physics.AddForce(MyPhysicsForceType.APPLY_WORLD_IMPULSE_AND_WORLD_ANGULAR_IMPULSE, p.Velocity * impulse * -hit.Normal, hit.Position, null);
                            }

                            // apply partial damage
                            float damage = p.Ammo.ProjectileMassDamage * NotHitFraction * MaxDamageTransfer;
                            if (block != null && MyAPIGateway.Session.IsServer)
                            {
                                Tools.Debug($"damage {damage}");
                                block.DoDamage(damage, MyStringHash.GetOrCompute(p.Ammo.SubtypeId), false, null, p.ShooterId);
                            }

                            // reduce velocity
                            p.Velocity -= p.Velocity * NotHitFraction * MaxVelocityTransfer;

                            // reflect
                            p.Velocity = Vector3.Reflect(p.Velocity, hit.Normal);

                            // calculate new direction
                            p.Direction      = Vector3D.Normalize(p.Velocity);
                            p.Position       = hit.Position + (p.Direction * 0.5f);
                            p.Origin         = p.Position;
                            p.DrawFullTracer = false;

                            //if (!MyAPIGateway.Utilities.IsDedicated)
                            //{
                            //    MatrixD world = MatrixD.CreateFromDir(hit.Normal);
                            //    world.Translation = hit.Position;

                            //    MyParticleEffect effect;
                            //    MyParticlesManager.TryCreateParticleEffect("Collision_Sparks_Directional", world, out effect);

                            //    effect.Loop = false;
                            //    effect.UserScale = 0.5f;
                            //    effect.UserEmitterScale = 16f;
                            //    effect.UserRadiusMultiplier = 0.1f;
                            //    effect.UserBirthMultiplier = 20f;
                            //    effect.DurationMin = 0.015f;
                            //    effect.DurationMax = 0.025f;
                            //    effect.SetRandomDuration();
                            //}
                        }
                        else
                        {
                            Tools.Debug($"obsorb damage");
                            if (block != null && MyAPIGateway.Session.IsServer)
                            {
                                block.DoDamage(p.Ammo.ProjectileMassDamage, MyStringHash.GetOrCompute(p.Ammo.SubtypeId), true);
                            }

                            p.Expired = true;
                        }
                    }
                }

                Tools.Debug($"----- ricochet check end -----");
            }
        }
Example #60
0
        //Relative velocity proportional navigation
        //aka: Whip-Nav
        internal static Vector3D CalculateMissileIntercept(Vector3D targetPosition, Vector3D targetVelocity, Vector3D missilePos, Vector3D missileVelocity, double missileAcceleration, double compensationFactor = 1, double maxLateralThrustProportion = 0.5)
        {
            var missileToTarget  = Vector3D.Normalize(targetPosition - missilePos);
            var relativeVelocity = targetVelocity - missileVelocity;
            var parallelVelocity = relativeVelocity.Dot(missileToTarget) * missileToTarget;
            var normalVelocity   = (relativeVelocity - parallelVelocity);

            var normalMissileAcceleration = normalVelocity * compensationFactor;

            if (Vector3D.IsZero(normalMissileAcceleration))
            {
                return(missileToTarget * missileAcceleration);
            }

            double maxLateralThrust = missileAcceleration * Math.Min(1, Math.Max(0, maxLateralThrustProportion));

            if (normalMissileAcceleration.LengthSquared() > maxLateralThrust * maxLateralThrust)
            {
                Vector3D.Normalize(ref normalMissileAcceleration, out normalMissileAcceleration);
                normalMissileAcceleration *= maxLateralThrust;
            }
            double diff      = missileAcceleration * missileAcceleration - normalMissileAcceleration.LengthSquared();
            var    maxedDiff = Math.Max(0, diff);

            return(Math.Sqrt(maxedDiff) * missileToTarget + normalMissileAcceleration);
        }