//Methods

        List<Vector3d> calcNodalWindLoads(List<Vector3d> vertexNormals, Vector3d wind, bool scale)
        {
            List<Vector3d> windload = new List<Vector3d>();

            double w = wind.Length;                                 //kN/m2
            Vector3d wDir = new Vector3d(wind);
            wDir.Unitize();

            for(int i=0; i<vertexNormals.Count; i++)
            {
                //Calculate projection onto wind direction
                Vector3d vN = vertexNormals[i];
                double vertexArea = vN.Length;                      //m2
                vN.Unitize();

                double dotProduct = Vector3d.Multiply(vN, wDir);

                //Calculate wind force
                Vector3d force = vN * vertexArea * w * 1e3;         //N

                if(dotProduct < 0.0)
                {
                    force.Reverse();
                }

                if (scale)
                {
                    force *= Math.Abs(dotProduct);
                }

                windload.Add(force);
            }

            return windload;
        }
 /// <summary>
 /// Makes a plane that includes a line and a vector and goes through a bounding box.
 /// </summary>
 /// <param name="lineInPlane">A line that will lie on the plane.</param>
 /// <param name="vectorInPlane">A vector the direction of which will be in plane.</param>
 /// <param name="box">A box to cut through.</param>
 /// <returns>A new plane surface on success, or null on error.</returns>
 public static PlaneSurface CreateThroughBox(Line lineInPlane, Vector3d vectorInPlane, BoundingBox box)
 {
   IntPtr ptr = UnsafeNativeMethods.RHC_RhinoPlaneThroughBox(ref lineInPlane, vectorInPlane, ref box);
   if (IntPtr.Zero == ptr)
     return null;
   return new PlaneSurface(ptr, null);
 }
Example #3
0
    public readonly Vector3d v; // Velocity in primary's inertial frame

    #endregion Fields

    #region Constructors

    // Straightforward constructor
    public Orbpos(Vector3d r, Vector3d v, double t, double mu)
    {
        this.r = r;
        this.v = v;
        this.t = t;
        this.mu = mu;
    }
Example #4
0
 //
 public Movil(ref ObjectId line, ref ObjectId mobile, double minSeparation, double maxSeparation, bool loopTravel)
 {
     this.line = line;
     this.mobile = mobile;
     this.dPromMin = minSeparation;
     this.dPromMax = maxSeparation;
     this.loopTravel = loopTravel;
     this.goal = false;
     this.ruta = Lab3.DBMan.OpenEnity(line) as Polyline;
     this.bloque = Lab3.DBMan.OpenEnity(mobile) as BlockReference;
     this.bloqueCentro = new Point3d((bloque.GeometricExtents.MinPoint.X +
                      bloque.GeometricExtents.MaxPoint.X) / 2,
                      (bloque.GeometricExtents.MinPoint.Y +
                      bloque.GeometricExtents.MaxPoint.Y) / 2,
                      0);
     this.numeroSegmentos = this.ruta.NumberOfVertices - 1;
     this.segmentoActualIndex = 0;
     this.segmentoActual = this.ruta.GetLineSegment2dAt(segmentoActualIndex);
     Lab3.DBMan.UpdateBlockPosition(new Point3d(this.segmentoActual.StartPoint.X, this.segmentoActual.StartPoint.Y, 0), mobile);
     //
     AttributeManager attribute = new AttributeManager(mobile);
     attribute.SetAttribute("Velocity", this.velocity+" [Kms/hr]");
     //
     this.pointActualCurve = 0;
     this.velocityScale = 0.00001f;
     this.velocity = this.UpdateDireccion();
     Lab3.DBMan.UpdateBlockRotation(new Vector2d(this.velocity.X, this.velocity.Y).Angle, this.mobile);
 }
Example #5
0
 public HUDQuad(RenderSet render_set, Vector3d p, Vector3d s)
     : this(render_set, p,
          p + new Vector3d(s.X, 0.0, 0.0),
          p + new Vector3d(s.X, s.Y, 0.0),
          p + new Vector3d(0.0, s.Y, 0.0))
 {
 }
Example #6
0
        /// <summary>
        /// Orbit foo, this finds the nodes of two orbits
        /// </summary>
        /// <returns>
        /// The true anomaly of the ascending node(descing node is 180degrees off)
        /// </returns>
        /// <param name='orbit'>
        /// Orbit.
        /// </param>
        /// <param name='tgtorbit'>
        /// Target Orbit
        /// </param>
        public static double FindAN(Orbit orbit, Orbit tgtorbit)
        {
            double rad = Math.PI/180;
            double Lan1 = orbit.LAN;
            double inc1 = orbit.inclination;
            double Lan2 = tgtorbit.LAN;
            double inc2 = tgtorbit.inclination;

            //see braeunig.us/space... cross product of two orbital planes gives the node location
            var a = new Vector3d(Math.Sin(inc1*rad)*Math.Cos(Lan1*rad), Math.Sin(inc1*rad)*Math.Sin(Lan1*rad),
                                 Math.Cos(inc1*rad));
            var b = new Vector3d(Math.Sin(inc2*rad)*Math.Cos(Lan2*rad), Math.Sin(inc2*rad)*Math.Sin(Lan2*rad),
                                 Math.Cos(inc2*rad));
            var c = new Vector3d(0, 0, 0);
            c = Vector3d.Cross(a, b);
            var coord = new double[] {0, 0};
            coord = LatLonofVector(c); //get the coordinates lat/lon of the ascending node
            double lat = coord[0];
            double lon = coord[1];

            //go look at the diagrams at braeunig.us/space
            double α = lon - Lan1; //its all greek to me
            if (α < 0) α += 360;
            double λ = Math.Atan(Math.Tan(α*rad)/Math.Cos(inc1*rad))/rad;
            double x = 180 + (λ - orbit.argumentOfPeriapsis);
            if (x > 360) return 360 - x;
            else return x;
        }
Example #7
0
        // Perturb an orbit by a deltaV vector
        public static void Perturb(this Orbit orbit, Vector3d deltaVV, double UniversalTime, double deltaTime)
        {
            // If there is a deltaV, perturb orbit
            if (deltaVV.magnitude <= 0) return;

            // Transpose deltaVV Y and Z to match orbit frame
            Vector3d deltaVV_orbit = deltaVV.xzy;
            Vector3d position = orbit.getRelativePositionAtUT(UniversalTime);
            //Orbit orbit2 = orbit.Clone();
            //orbit2.UpdateFromStateVectors(position, orbit.getOrbitalVelocityAtUT(UniversalTime) + deltaVV_orbit, orbit.referenceBody, UniversalTime);
            //if (!double.IsNaN(orbit2.inclination) && !double.IsNaN(orbit2.eccentricity) && !double.IsNaN(orbit2.semiMajorAxis) && orbit2.timeToAp > deltaTime)
            //{
            //    orbit.inclination = orbit2.inclination;
            //    orbit.eccentricity = orbit2.eccentricity;
            //    orbit.semiMajorAxis = orbit2.semiMajorAxis;
            //    orbit.LAN = orbit2.LAN;
            //    orbit.argumentOfPeriapsis = orbit2.argumentOfPeriapsis;
            //    orbit.meanAnomalyAtEpoch = orbit2.meanAnomalyAtEpoch;
            //    orbit.epoch = orbit2.epoch;
            //    orbit.referenceBody = orbit2.referenceBody;
            //    orbit.Init();
            //    orbit.UpdateFromUT(UniversalTime);
            //}
            //else
            //{
                orbit.UpdateFromStateVectors(position, orbit.getOrbitalVelocityAtUT(UniversalTime) + deltaVV_orbit, orbit.referenceBody, UniversalTime);
                orbit.Init();
                orbit.UpdateFromUT(UniversalTime);
            //}
        }
Example #8
0
            public MengerCube( Vector3d center, double sidelength, eSides[] visibleSides, eSides[] parentsVisibility )
            {
                Center = center;
                SideLength = sidelength;

                /*  List<eSides> Sides = new List<eSides>();
                  foreach ( eSides s in visibleSides )
                  {
                      bool isVisible = false;
                      foreach ( eSides p in parentsVisibility )
                      {
                          if ( (int)p == (int)s )
                          {
                              isVisible = true;
                              break;
                          }
                      }
                      if ( isVisible )
                      {
                          Sides.Add( s );
                      }
                  }
                  VisibleSides = Sides.ToArray();*/
                VisibleSides = visibleSides;
                VisibilityToInherit = visibleSides;
            }
        public void Set(Vector3d vec)
        {
            Vector = vec;

            XValue.Value = (decimal)Vector.X;
            YValue.Value = (decimal)Vector.Y;
            ZValue.Value = (decimal)Vector.Z;

            if (UseDecimalIncrement)
            {
                XValue.Increment = (decimal)0.001;
                YValue.Increment = (decimal)0.001;
                ZValue.Increment = (decimal)0.001;
            }
            else
            {
                XValue.Increment = (decimal)1;
                YValue.Increment = (decimal)1;
                ZValue.Increment = (decimal)1;
            }

            XYLock.Enabled = UseLocks;
            if (!UseLocks)
                YValue.Enabled = true;
        }
Example #10
0
 public Vertex(Vector3d p, /*Vector3d n,*/ Vector2d tc, Vector4 c)
 {
     Position = p;
     //Normal = n;
     TexCoord = tc;
     Color = c;
 }
    public void RunCalculations(
        Vessel vessel,
        Quaternion gymbal)
    {
        // Calculations thanks to Mechjeb
        Vector3d CoM = vessel.findWorldCenterOfMass();
        Vector3d up = (CoM - vessel.mainBody.position).normalized;
        Vector3d velocityVesselOrbit = vessel.orbit.GetVel();
        Vector3d velocityVesselOrbitUnit = velocityVesselOrbit.normalized;
        Vector3d radialPlus = Vector3d.Exclude(velocityVesselOrbit, up).normalized;
        Vector3d velocityVesselSurface = velocityVesselOrbit - vessel.mainBody.getRFrmVel(CoM);
        Vector3d velocityVesselSurfaceUnit = velocityVesselSurface.normalized;

        RadialPlus = gymbal * radialPlus;
        NormalPlus = gymbal * -Vector3d.Cross(radialPlus, velocityVesselOrbitUnit);
        ProgradeOrbit = gymbal * velocityVesselOrbitUnit;
        ProgradeSurface = gymbal * velocityVesselSurfaceUnit;

        if (vessel.patchedConicSolver.maneuverNodes.Count > 0)
        {
            Vector3d burnVector = vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(vessel.orbit);
            ManeuverPlus = gymbal * burnVector.normalized;
            ManeuverPresent = true;
        }
        else
        {
            ManeuverPresent = false;
        }
    }
Example #12
0
        public static void DrawBox(Vector3d mvMin, Vector3d mvMax)
        {
            Vector3d[] v = new Vector3d[8];
            v[0] = new Vector3d(mvMin.X, mvMin.Y, mvMin.Z);
            v[1] = new Vector3d(mvMax.X, mvMin.Y, mvMin.Z);
            v[2] = new Vector3d(mvMax.X, mvMax.Y, mvMin.Z);
            v[3] = new Vector3d(mvMin.X, mvMax.Y, mvMin.Z);
            v[4] = new Vector3d(mvMin.X, mvMin.Y, mvMax.Z);
            v[5] = new Vector3d(mvMax.X, mvMin.Y, mvMax.Z);
            v[6] = new Vector3d(mvMax.X, mvMax.Y, mvMax.Z);
            v[7] = new Vector3d(mvMin.X, mvMax.Y, mvMax.Z);

            GL.PushAttrib(AttribMask.AllAttribBits);
            GL.Disable(EnableCap.Lighting);
            GL.Color4(Color4.Red);
            GL.Begin(PrimitiveType.Lines);
            GL.Vertex3(v[0]); GL.Vertex3(v[1]);
            GL.Vertex3(v[1]); GL.Vertex3(v[2]);
            GL.Vertex3(v[2]); GL.Vertex3(v[3]);
            GL.Vertex3(v[3]); GL.Vertex3(v[0]);
            GL.Vertex3(v[4]); GL.Vertex3(v[5]);
            GL.Vertex3(v[5]); GL.Vertex3(v[6]);
            GL.Vertex3(v[6]); GL.Vertex3(v[7]);
            GL.Vertex3(v[7]); GL.Vertex3(v[4]);
            GL.Vertex3(v[0]); GL.Vertex3(v[4]);
            GL.Vertex3(v[1]); GL.Vertex3(v[5]);
            GL.Vertex3(v[2]); GL.Vertex3(v[6]);
            GL.Vertex3(v[3]); GL.Vertex3(v[7]);
            GL.End();
            GL.PopAttrib();
        }
 public static Vector3d GetRotateVector(Vector3d v, double xr, double yr, double zr)
 {
     v = v.TransformBy(Matrix3d.Rotation(xr * System.Math.PI / 180, Vector3d.XAxis, Point3d.Origin));
     v = v.TransformBy(Matrix3d.Rotation(yr * System.Math.PI / 180, Vector3d.YAxis, Point3d.Origin));
     v = v.TransformBy(Matrix3d.Rotation(zr * System.Math.PI / 180, Vector3d.ZAxis, Point3d.Origin));
     return v;
 }
            public override Mesh Generate(Point3d P, Vector3d V)
            {
                Vector3d diffx;
                Vector3d diffy;
                Vector3d diffz = new Vector3d(V);
                double proj;
                diffx = new Vector3d(0, 0, 1);
                proj = System.Math.Abs(Vector3d.Multiply(diffz, diffx));

                if (0.99 < proj && 1.01 > proj) diffx = new Vector3d(1, 0, 0);
                diffy = diffz;
                diffy = Vector3d.CrossProduct(diffy, diffx);
                diffx = Vector3d.CrossProduct(diffy, diffz);
                diffx.Unitize();
                diffy.Unitize();
                diffz.Unitize();

                Mesh M = new Mesh();
                M.Vertices.SetVertex(0, P + diffz * 0.25);
                M.Vertices.SetVertex(1, P + (diffx * 0.7072 + diffy * -.5 + diffz * -.5) * 0.25);
                M.Vertices.SetVertex(2, P + (diffy + diffz * -.5) * 0.25);
                M.Vertices.SetVertex(3, P + (diffx * -0.7072 + diffy * -.5 + diffz * -.5) * 0.25);

                M.Faces.SetFace(0, 0, 1, 2);
                M.Faces.SetFace(1, 0, 2, 3);
                M.Faces.SetFace(2, 0, 3, 1);
                M.Faces.SetFace(3, 3, 2, 1);
                M.FaceNormals.ComputeFaceNormals();
                //M.ComputeVertexNormals();

                return M;
            }
        /// <summary>
        /// Проводит десериалзиацию
        /// </summary>
        /// <param name="package">Содержимое пакета</param>
        /// <returns>Структура из трех величин</returns>
        public override Vector3d Do(string package)
        {
            string sub = "";
            Vector3d result = new Vector3d();

            int index1 = 0;
            int index2 = package.LastIndexOf('>');

            for (int i = index2 - 1; i >= 0; i--)
            {
                if (package[i] == '<')
                {
                    index1 = i;
                    break;
                }
            }

            if ((index1 != -1) && (index2 != -1) && (index2 >= index1))
                sub = package.Substring(index1 + 1, index2 - index1 - 1);
            else
                throw new ExceptionServer("Block borders are not found");

            string[] parameters = sub.Split(';');

            result.X = double.Parse(parameters[0].Replace(',', '.'), CultureInfo.InvariantCulture); // Pitch
            result.Y = double.Parse(parameters[1].Replace(',', '.'), CultureInfo.InvariantCulture); // Roll
            result.Z = double.Parse(parameters[2].Replace(',', '.'), CultureInfo.InvariantCulture); // Yaw

            return result;
        }
Example #16
0
        /// <summary>
        /// Calculates distance between a hole edge and all other holes. This distance is used to calculate the force between the points and assign an acceleration to a point.
        /// </summary>
        /// <param name="others"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        private void CalculateAcceleration(IList<Hole> others)
        {
            this.newAccelerationVector = Vector3d.Zero;
            double minimumDenominatorToAvoidDivideByZero = 5;
            for (int i = 0; i < others.Count; i++)
            {
                Hole other = others[i];
                Vector3d VectorPointToPointInfluence = other.point - this.point;
                double distanceBetweenPoints = VectorPointToPointInfluence.Length;
                if (distanceBetweenPoints < double.Epsilon)
                {
                    continue;
                }

                double distanceBetweenHoles = distanceBetweenPoints - other.radius - this.radius;
                if (distanceBetweenHoles <= 0) //checks if holes intersect.
                {
                    distanceBetweenHoles = 0;
                }

                VectorPointToPointInfluence.Unitize();
                VectorPointToPointInfluence *= -this.force / (minimumDenominatorToAvoidDivideByZero + distanceBetweenHoles * distanceBetweenHoles);
                VectorPointToPointInfluence = AdjustAccelerationForColourSensitivity(VectorPointToPointInfluence, other);
                this.newAccelerationVector += VectorPointToPointInfluence;
            }

            this.newAccelerationVector = this.ConstrainVectorToMeshFace(this.newAccelerationVector);
        }
Example #17
0
 public static Vector3d Cross(Vector3d lhs, Vector3d rhs)
 {
     return new Vector3d(
         lhs.y * rhs.z - lhs.z * rhs.y,
         lhs.z * rhs.x - lhs.x * rhs.z,
         lhs.x * rhs.y - lhs.y * rhs.x);
 }
 /// <summary>
 /// Initializes a new instance of the WorldBoxEnvironmentComponent class.
 /// </summary>
 public PolysurfaceEnvironmentComponent()
   : base("Polysurface Environment", "PolysrfEnv",
       "A 3D Polysurface Environment.", RS.icon_polysurfaceEnvironment, "646e7585-d3b0-4ebd-8ce3-8efc5cd6b7d9")
 {
   brep = new Brep();
   borderDir = Vector3d.Zero;
 }
        public Vector3d Compute(Vector3d error, Vector3d omega, Vector3d Wlimit)
        {
            derivativeAct = Vector3d.Scale(omega, Kd);
            Wlimit = Vector3d.Scale(Wlimit, Kd);

            // integral actíon + Anti Windup
            intAccum.x = (Math.Abs(derivativeAct.x) < 0.6 * max) ? intAccum.x + (error.x * Ki.x * TimeWarp.fixedDeltaTime) : 0.9 * intAccum.x;
            intAccum.y = (Math.Abs(derivativeAct.y) < 0.6 * max) ? intAccum.y + (error.y * Ki.y * TimeWarp.fixedDeltaTime) : 0.9 * intAccum.y;
            intAccum.z = (Math.Abs(derivativeAct.z) < 0.6 * max) ? intAccum.z + (error.z * Ki.z * TimeWarp.fixedDeltaTime) : 0.9 * intAccum.z;

            propAct = Vector3d.Scale(error, Kp);

            Vector3d action = propAct + intAccum;

            // Clamp (propAct + intAccum) to limit the angular velocity:
            action = new Vector3d(Math.Max(-Wlimit.x, Math.Min(Wlimit.x, action.x)),
                                  Math.Max(-Wlimit.y, Math.Min(Wlimit.y, action.y)),
                                  Math.Max(-Wlimit.z, Math.Min(Wlimit.z, action.z)));

            // add. derivative action
            action += derivativeAct;

            // action clamp
            action = new Vector3d(Math.Max(min, Math.Min(max, action.x)),
                                  Math.Max(min, Math.Min(max, action.y)),
                                  Math.Max(min, Math.Min(max, action.z)));
            return action;
        }
Example #20
0
 public static double AngleBetweenTwoVectors(Vector3d a, Vector3d b)
 {
     double temp = (a.X * b.X + a.Y * b.Y + a.Z * b.Z) / (a.Length * b.Length);
     if (temp > 1.0) temp = 1.0;
     else if (temp < -1.0) temp = -1.0;
     return Math.Acos(temp);
 }
    public static unsafe void Main () {
        for (int i = 0; i < BufferSize; i++)
            Vectors[i] = new Vector3d(i * 0.5, (double)i, i * 1.5);

        Console.WriteLine("Add: {0:00000.00}ms", Time(TestAdd));
        Console.WriteLine("Add Overloaded: {0:00000.00}ms", Time(TestAddOverloaded));
    }
Example #22
0
 public Vertex(double px, double py, double pz, /*double nx, double ny, double nz,*/ double tcx, double tcy)
 {
     Position = new Vector3d(px, py, pz);
     //Normal = new Vector3d(nx, ny, nz);
     TexCoord = new Vector2d(tcx, tcy);
     Color = Vector4.One;
 }
Example #23
0
		/// <summary>
		/// Ctor
		/// </summary>
		/// <param name="pos"></param>
		/// <param name="normal"></param>
		/// <param name="color"></param>
		public Point3D(Vector3d pos, Vector3d normal, Color color)
			: this()
		{
			Position = pos;
			Normal = normal;
			Color = color;
		}
Example #24
0
 public Vertex(double px, double py, double pz, /*double nx, double ny, double nz,*/ double tcx, double tcy, float r, float b, float g, float a)
 {
     Position = new Vector3d(px, py, pz);
     //Normal = new Vector3d(nx, ny, nz);
     TexCoord = new Vector2d(tcx, tcy);
     Color = new Vector4(r, g, b, a);
 }
Example #25
0
 private static bool IsHidden(Vector3d point)
 {
     Vector3d camera = ScaledSpace.ScaledToLocalSpace(
     PlanetariumCamera.Camera.transform.position);
     foreach (CelestialBody body in hiding_bodies_) {
       Vector3d camera_to_point = point - camera;
       Vector3d camera_to_body = body.position - camera;
       double inner_product = Vector3d.Dot(camera_to_point, camera_to_body);
       double r_squared = body.Radius * body.Radius;
       // The projections on the camera-body axis of |point| and of the horizon
       // have lengths |inner_product| / d and d - r^2/d, where d is the distance
       // between the camera and the body and r is the body's radius, thus if
       // |inner_product| < d^2 - r^2, |point| is above the plane passing
       // through the horizon.
       // Otherwise, we check whether |point| is within the cone hidden from the
       // camera, by comparing the squared cosines multiplied by
       // d^2|camera_to_point|^2.
       // In addition, we check whether we're inside the body (this covers the
       // cap above the horizon plane and below the surface of the body, which
       // would otherwise be displayed).
       double d_squared_minus_r_squared =
       camera_to_body.sqrMagnitude - r_squared;
       if ((body.position - point).sqrMagnitude < r_squared ||
       (inner_product > d_squared_minus_r_squared &&
        inner_product * inner_product >
        camera_to_point.sqrMagnitude * d_squared_minus_r_squared)) {
     return true;
       }
     }
     return false;
 }
    protected override Vector3d CalculateDesiredVelocity()
    {
      Vector3d desired = new Vector3d();
      //Predict the vehicle's future location
      Vector3d predict = agent.Velocity3D;
      predict.Unitize();
      predict = predict * predictionDistance;
      predictLoc = agent.Position3D + predict;

      //Find the normal point along the path
      double t;
      path.ClosestPoint(predictLoc, out t);
      pathPt = path.PointAt(t);

      //Move a little further along the path and set a target


      //If we are off the path, seek that target in order to stay on the path
      double distance = pathPt.DistanceTo(predictLoc);
      if (distance > radius)
      {
        pathPt = path.PointAt(t + pathTargetDistance);
        pathPt = agent.Environment.MapTo2D(pathPt);
        // Seek that point
        desired = Util.Agent.Seek(agent, pathPt);
      }
      return desired;
    }
Example #27
0
        /// <summary>
        /// Creates a new Polyline that is the result of projecting the Polyline3d parallel to 'direction' onto 'plane' and returns it.
        /// </summary>
        /// <param name="pline">The polyline to project.</param>
        /// <param name="plane">The plane onto which the curve is to be projected.</param>
        /// <param name="direction">Direction (in WCS coordinates) of the projection.</param>
        /// <returns>The projected Polyline.</returns>
        public static Polyline GetProjectedPolyline(this Polyline3d pline, Plane plane, Vector3d direction)
        {
            if (plane.Normal.IsPerpendicularTo(direction, new Tolerance(1e-9, 1e-9)))
                return null;

            return GeomExt.ProjectPolyline(pline, plane, direction);
        }
Example #28
0
 /// <summary>
 /// Base initializer for all shapes
 /// </summary>
 /// <param name="vertices">The number of vertices that make up the shape</param>
 /// <param name="Position">The zero position of the vertices (these are shifted around with Calculate())</param>
 public Shape(int vertices, Vector3d Position)
 {
     this.Vertices = new Vector3d[vertices];
     for (int i = 0; i < Vertices.Length; i++) {
         Vertices[i] = Position;
     }
 }
Example #29
0
 public static Ray Reflect(Ray incoming, Vector3d normal)
 {
     Ray reflected = new Ray(
         incoming.Origin,
         Reflect(incoming.Direction, normal));
     return reflected;
 }
Example #30
0
    protected override Vector3d CalculateDesiredVelocity()
    {
      Vector3d desired = new Vector3d();
      int count = 0;

      foreach (IQuelea neighbor in neighbors)
      {
        //Point3d neighborPosition2D = agent.Environment.ClosestRefPoint(neighbor.Position3D);
        Point3d neighborPosition2D = agent.Environment.Wrap ? wrappedPositions[count] : neighbor.Position;
        //Adding up all the others' location
        desired = desired + (Vector3d)neighborPosition2D;
        //For an average, we need to keep track of how many boids
        //are in our vision.
        count++;
      }

      if (count > 0)
      {
        //We desire to go in that direction at maximum speed.
        desired = desired / count;
        desired = Util.Agent.Seek(agent, new Point3d(desired));
      }
      //Seek the average location of our neighbors.
      return desired;
    }
 public void Set(Vector3d position)
 {
     gameObject.transform.position = position;
 }
        // TODO : I should probably use an array and an enum to lower code dup ...
        public override void OnUpdate()
        {
            if (vessel != FlightGlobals.ActiveVessel)
            {
                return;
            }

            if (comSphere == null)
            {
                comSphere = new DebugIcoSphere(XKCDColors.BloodRed, true);

                colSphere = new DebugIcoSphere(XKCDColors.Teal, true);
                cotSphere = new DebugIcoSphere(XKCDColors.PurplePink, true);

                srfVelocityArrow = new DebugArrow(Color.green);
                obtVelocityArrow = new DebugArrow(Color.red);

                dotArrow = new DebugArrow(XKCDColors.PurplePink);

                forwardArrow    = new DebugArrow(XKCDColors.ElectricBlue);
                avgForwardArrow = new DebugArrow(Color.blue);

                requestedAttitudeArrow = new DebugArrow(Color.gray);

                debugArrow  = new DebugArrow(XKCDColors.Fuchsia);
                debugArrow2 = new DebugArrow(XKCDColors.LightBlue);
            }


            var      frameVel   = (vesselState.orbitalVelocity - Krakensbane.GetFrameVelocity() - vessel.orbit.GetRotFrameVel(vessel.orbit.referenceBody).xzy) * Time.fixedDeltaTime;
            Vector3d instantCoM = vesselState.CoM + frameVel;

            Vector3 arrowPos = displayAtCoM
                ? instantCoM
                : (Vector3d)vessel.ReferenceTransform.position;

            comSphere.State(comSphereActive);
            if (comSphereActive)
            {
                comSphere.Set(instantCoM);
                comSphere.SetRadius((float)comSphereRadius.val);
            }

            colSphere.State(colSphereActive && vesselState.CoLScalar > 0);
            if (colSphereActive)
            {
                colSphere.Set(vesselState.CoL + frameVel);
                colSphere.SetRadius((float)comSphereRadius.val);
            }

            cotSphere.State(cotSphereActive && vesselState.CoTScalar > 0);
            if (cotSphereActive)
            {
                cotSphere.Set(vesselState.CoT + frameVel);
                cotSphere.SetRadius((float)comSphereRadius.val);
            }

            srfVelocityArrow.State(srfVelocityArrowActive);
            if (srfVelocityArrowActive)
            {
                srfVelocityArrow.Set(arrowPos, vessel.srf_velocity);
                srfVelocityArrow.SetLength((float)arrowsLength.val);
                srfVelocityArrow.SeeThrough(seeThrough);
            }

            obtVelocityArrow.State(obtVelocityArrowActive);
            if (obtVelocityArrowActive)
            {
                obtVelocityArrow.Set(arrowPos, vessel.obt_velocity);
                obtVelocityArrow.SetLength((float)arrowsLength.val);
                obtVelocityArrow.SeeThrough(seeThrough);
            }

            dotArrow.State(dotArrowActive && vesselState.thrustCurrent > 0);
            if (dotArrowActive)
            {
                dotArrow.Set(vesselState.CoT + frameVel, vesselState.DoT);
                dotArrow.SetLength((float)Math.Log10(vesselState.thrustCurrent + 1));
                dotArrow.SeeThrough(seeThrough);
            }

            forwardArrow.State(forwardArrowActive);
            if (forwardArrowActive)
            {
                forwardArrow.Set(arrowPos, vessel.GetTransform().up);
                forwardArrow.SetLength((float)arrowsLength.val);
                forwardArrow.SeeThrough(seeThrough);
            }

            avgForwardArrow.State(avgForwardArrowActive);
            if (avgForwardArrowActive)
            {
                avgForwardArrow.Set(arrowPos, vesselState.forward);
                avgForwardArrow.SetLength((float)arrowsLength.val);
                avgForwardArrow.SeeThrough(seeThrough);
            }

            requestedAttitudeArrow.State(requestedAttitudeArrowActive && core.attitude.enabled);
            if (requestedAttitudeArrowActive && core.attitude.enabled)
            {
                requestedAttitudeArrow.Set(arrowPos, core.attitude.RequestedAttitude);
                requestedAttitudeArrow.SetLength((float)arrowsLength.val);
                requestedAttitudeArrow.SeeThrough(seeThrough);
            }

            debugArrow.State(debugArrowActive);
            if (debugArrowActive)
            {
                debugArrow.Set(vessel.ReferenceTransform.position, debugVector);
                debugArrow.SetLength((float)debugVector.magnitude);
                debugArrow.SeeThrough(seeThrough);
            }

            debugArrow2.State(debugArrow2Active);
            if (debugArrow2Active)
            {
                //debugArrow2.Set(vessel.ReferenceTransform.position, debugVector2);
                //
                //debugArrow2.SetLength((float)debugVector2.magnitude);
                //debugArrow2.SeeThrough(seeThrough);

                var vector3d = vesselState.CoL - instantCoM + frameVel;
                debugArrow2.Set(instantCoM, vector3d);

                debugArrow2.SetLength((float)vector3d.magnitude);
                debugArrow2.SeeThrough(seeThrough);
            }
        }
Example #33
0
        /// <summary>
        /// Generates the actual mesh for the polyhedron
        /// </summary>
        private void MakeMesh()
        {
            MeshFilter mf;

            mf = Shape.GetComponent <MeshFilter>();
            if (mf == null)
            {
                mf = Shape.AddComponent <MeshFilter>();
            }
            mf.mesh = null;
            Mesh mesh = new Mesh();
            TriangulatedPolygonGenerator tpg = new TriangulatedPolygonGenerator();
            Frame3f frame = new Frame3f();

            tpg.Polygon = Polygon.ToPolygon(ref frame);
            tpg.Generate();
            int nv = tpg.vertices.Count;

            VertexTable.Clear();

            foreach (Dataline ring in Polygon)
            {
                foreach (VertexLookup v in ring.VertexTable)
                {
                    VertexTable.Add(v);
                }
            }
            IEnumerable <Vector3d> vlist = tpg.vertices.AsVector3d();

            Vector3[] vertices = new Vector3[vlist.Count()];

            for (int i = 0; i < vlist.Count(); i++)
            {
                Vector3d v = vlist.ElementAt(i);
                try {
                    VertexLookup vl = VertexTable.Find(item => v.xy.Distance(frame.ToPlaneUV(item.Com.transform.position, 3)) < 0.001);
                    vertices[i] = Shape.transform.InverseTransformPoint(vl.Com.transform.position);
                    vl.pVertex  = i;
                } catch {
                    VertexTable.Add(new VertexLookup()
                    {
                        pVertex = i, Com = VertexTable[0].Com
                    });
                    vertices[i] = Shape.transform.InverseTransformPoint((Vector3)frame.FromFrameV(v));
                }
            }

            List <Vector2>         uvs  = new List <Vector2>();
            IEnumerable <Vector2d> uv2d = tpg.uv.AsVector2f();

            foreach (Vector2d uv in uv2d)
            {
                uvs.Add((Vector2)uv);
            }
            mesh.vertices  = vertices.ToArray();
            mesh.triangles = tpg.triangles.ToArray <int>();
            mesh.uv        = uvs.ToArray <Vector2>();

            mesh.RecalculateBounds();
            mesh.RecalculateNormals();

            mf.mesh = mesh;
        }
Example #34
0
 /// <summary>
 /// Constructor. Creates a new cube with center <c>[0,0,0]</c> and
 /// dimensions <c>[size,size,size]</c>.
 /// </summary>
 ///
 /// <param name="size">size</param>
 ///
 public Cube(double size)
 {
     center     = Vector3d.xyz(0, 0, 0);
     dimensions = Vector3d.xyz(size, size, size);
 }
 public void Set(Vector3d position, Quaternion direction)
 {
     gameObject.transform.position = position;
     gameObject.transform.rotation = direction;
 }
Example #36
0
 /// <summary>
 /// Constructor. Creates a new cuboid with center <c>[0,0,0]</c> and with
 /// the specified dimensions.
 /// </summary>
 ///
 /// <param name="w">width</param>
 /// <param name="h">height</param>
 /// <param name="d">depth</param>
 ///
 public Cube(double w, double h, double d)
     : this(Vector3d.ZERO, Vector3d.xyz(w, h, d))
 {
 }
Example #37
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve    polyline1   = null;
            Interval angleDomain = new Interval();

            if (!DA.GetData(0, ref polyline1))
            {
                return;
            }
            if (!DA.GetData(1, ref angleDomain))
            {
                return;
            }
            if (angleDomain.Max == angleDomain.Min)/////////如果输入的区间格式不正确
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "输入端的区间的最大值和最小值不能相同");
                return;
            }
            ////string test = this.Params.Input[1].Sources[0].TypeName;
            //if (test == "Number" || test == "Integer")
            //{
            //    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "输入端的区间的最大值和最小值不能相同");
            //    return;
            //}
            Polyline x = new Polyline();

            polyline1.TryGetPolyline(out x);
            Interval y = angleDomain;

            if (x.IsClosed)
            {
                Line[]          ls     = x.GetSegments();
                List <Vector3d> vcs    = new List <Vector3d>();
                List <Vector3d> vcs22  = new List <Vector3d>();
                List <Point3d>  pts    = new List <Point3d>();
                List <Point3d>  pts22  = new List <Point3d>();
                List <double>   angles = new List <double>();
                y.MakeIncreasing();
                double max = y.Max;
                double min = y.Min;
                foreach (Line l in ls)
                {
                    Vector3d vc = l.Direction;
                    vc.Unitize();
                    vcs.Add(vc);
                    vc.Reverse();
                    vcs22.Add(vc);
                    pts.Add(l.From);
                }
                /////////////////////////////////////
                for (int i = 0; i < vcs.Count; i++)
                {
                    if (i == vcs.Count - 1)
                    {
                        double nn = Vector3d.VectorAngle(vcs[i], vcs22[0]);
                        if (nn < min || nn > max)
                        {
                            pts22.Add(pts[0]);
                        }
                        break;
                    }
                    double mm = Vector3d.VectorAngle(vcs[i], vcs22[i + 1]);
                    if (mm < min || mm > max)
                    {
                        pts22.Add(pts[i + 1]);
                    }
                }
                pts22.Add(pts22[0]);
                Polyline pl = new Polyline(pts22);//最终生成的点
                if (!pl.IsValid)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "无法根据条件简化多段线,简化后的多段线无效");
                    return;
                }
                DA.SetData(0, pl);
            }
            //////////////////////////////////////////////////////////////////////////////////////
            else if (!x.IsClosed)
            {
                Line[]          ls     = x.GetSegments();
                List <Vector3d> vcs    = new List <Vector3d>();
                List <Vector3d> vcs22  = new List <Vector3d>();
                List <Point3d>  pts    = new List <Point3d>();
                List <Point3d>  pts22  = new List <Point3d>();
                List <double>   angles = new List <double>();
                y.MakeIncreasing();
                double max = y.Max;
                double min = y.Min;
                foreach (Line l in ls)
                {
                    Vector3d vc = l.Direction;
                    vc.Unitize();
                    vcs.Add(vc);
                    vc.Reverse();
                    vcs22.Add(vc);
                    pts.Add(l.From);
                }
                pts.Add(ls[ls.Length - 1].To); ///不闭合多段线的特殊情况
                //////////////////////////////////////
                pts22.Add(pts[0]);             ///不闭合多段线的特殊情况
                for (int i = 0; i < vcs.Count - 1; i++)
                {
                    double mm = Vector3d.VectorAngle(vcs[i], vcs22[i + 1]);
                    if (mm < min || mm > max)
                    {
                        pts22.Add(pts[i + 1]);
                    }
                }
                pts22.Add(pts[pts.Count - 1]);
                Polyline pl = new Polyline(pts22);//最终生成的点
                if (!pl.IsValid)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "无法根据条件简化多段线,简化后的多段线无效");
                    return;
                }
                DA.SetData(0, pl);
            }
        }
        /// <summary>
        ///     Builds a composited terrain texture given the region texture
        ///     and heightmap settings
        /// </summary>
        /// <param name="heightmap">Terrain heightmap</param>
        /// <param name="textureIDs"></param>
        /// <param name="startHeights"></param>
        /// <param name="heightRanges"></param>
        /// <param name="regionPosition"></param>
        /// <param name="assetService"></param>
        /// <param name="textureTerrain"></param>
        /// <returns>A composited 256x256 RGB texture ready for rendering</returns>
        /// <remarks>
        ///     Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
        /// </remarks>
        public static Bitmap Splat(ITerrainChannel heightmap, UUID [] textureIDs, float [] startHeights,
                                   float [] heightRanges, Vector3d regionPosition, IAssetService assetService,
                                   bool textureTerrain)
        {
            Debug.Assert(textureIDs.Length == 4);
            Debug.Assert(startHeights.Length == 4);
            Debug.Assert(heightRanges.Length == 4);

            Bitmap []   detailTexture = new Bitmap [4];
            int         outWidth      = heightmap.Width;
            int         outHeight     = heightmap.Height;
            IJ2KDecoder m_imgDecoder;

            if (textureTerrain)
            {
                // Swap empty terrain textureIDs with default IDs
                for (int i = 0; i < textureIDs.Length; i++)
                {
                    if (textureIDs [i] == UUID.Zero)
                    {
                        textureIDs [i] = DEFAULT_TERRAIN_DETAIL [i];
                    }
                }

                #region Texture Fetching

                if (assetService != null)
                {
                    m_imgDecoder = heightmap.Scene.RequestModuleInterface <IJ2KDecoder> ();

                    for (int i = 0; i < 4; i++)
                    {
                        UUID      cacheID     = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs [i]);
                        AssetBase cachedAsset = assetService.Get(cacheID.ToString(), false);             // ignore warnings here as the cached texture may not exist

                        if ((cachedAsset != null) && (cachedAsset.Data != null) && (cachedAsset.Data.Length != 0))
                        {
                            try {
                                using (MemoryStream stream = new MemoryStream(cachedAsset.Data))
                                    detailTexture [i] = (Bitmap)Image.FromStream(stream);
                            } catch (Exception ex) {
                                MainConsole.Instance.Warn("Failed to decode cached terrain texture " + cacheID +
                                                          " (textureID: " + textureIDs [i] + "): " + ex.Message);
                            }
                        }
                        if (cachedAsset != null)
                        {
                            cachedAsset.Dispose();
                        }

                        if (detailTexture [i] == null)
                        {
                            // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
                            byte [] assetData = assetService.GetData(textureIDs [i].ToString());
                            if (assetData != null)
                            {
                                try {
                                    detailTexture [i] = (Bitmap)m_imgDecoder.DecodeToImage(assetData);
                                } catch (Exception ex) {
                                    MainConsole.Instance.Warn("Failed to decode terrain texture " + textureIDs [i] + ": " +
                                                              ex.Message);
                                }
                            }

                            if (detailTexture [i] != null)
                            {
                                Bitmap bitmap = detailTexture [i];

                                // Make sure this texture is the correct size, otherwise resize
                                if (bitmap.Width != outWidth || bitmap.Height != outHeight)
                                {
                                    bitmap = ImageUtils.ResizeImage(bitmap, outWidth, outHeight);
                                }

                                // Save the decoded and resized texture to the cache
                                byte [] data;
                                using (MemoryStream stream = new MemoryStream()) {
                                    bitmap.Save(stream, ImageFormat.Png);
                                    data = stream.ToArray();
                                }

                                // Cache a PNG copy of this terrain texture
                                AssetBase newAsset = new AssetBase {
                                    Data        = data,
                                    Description = "PNG",
                                    Flags       = AssetFlags.Collectable | AssetFlags.Temporary | AssetFlags.Local,
                                    ID          = cacheID,
                                    Name        = string.Empty,
                                    TypeString  = "image/png"
                                };
                                newAsset.ID = assetService.Store(newAsset);
                            }
                        }
                    }
                }

                #endregion Texture Fetching
            }

            // Fill in any missing textures with a solid color
            for (int i = 0; i < 4; i++)
            {
                if (detailTexture [i] == null)
                {
                    // Create a solid color texture for this layer
                    detailTexture [i] = new Bitmap(outWidth, outHeight, PixelFormat.Format24bppRgb);
                    using (Graphics gfx = Graphics.FromImage(detailTexture [i])) {
                        using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR [i]))
                            gfx.FillRectangle(brush, 0, 0, outWidth, outHeight);
                    }
                }
                else if (detailTexture [i].Width != outWidth || detailTexture [i].Height != outHeight)
                {
                    detailTexture [i] = ResizeBitmap(detailTexture [i], outWidth, outHeight);
                }
            }

            #region Layer Map

            float diffX  = 1.0f; //(float) heightmap.Width/(float) Constants.RegionSize;
            float diffY  = 1.0f; //(float) heightmap.Height/(float) Constants.RegionSize;
            int   newRsX = heightmap.Width / (int)diffX;
            int   newRsY = heightmap.Height / (int)diffY;

            float [] layermap = new float [newRsX * newRsY];

            for (float y = 0; y < heightmap.Height; y += diffY)
            {
                for (float x = 0; x < heightmap.Width; x += diffX)
                {
                    float newX   = x / diffX;
                    float newY   = y / diffY;
                    float height = heightmap [(int)x, (int)y];

                    float pctX = newX / 255f;
                    float pctY = newY / 255f;

                    // Use bilinear interpolation between the four corners of start height and
                    // height range to select the current values at this position
                    float startHeight = ImageUtils.Bilinear(
                        startHeights [0],
                        startHeights [2],
                        startHeights [1],
                        startHeights [3],
                        pctX, pctY);
                    startHeight = Utils.Clamp(startHeight, 0f, 255f);

                    float heightRange = ImageUtils.Bilinear(
                        heightRanges [0],
                        heightRanges [2],
                        heightRanges [1],
                        heightRanges [3],
                        pctX, pctY);
                    heightRange = Utils.Clamp(heightRange, 0f, 255f);

                    // Generate two frequencies of perlin noise based on our global position
                    // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
                    Vector3 vec = new Vector3
                                  (
                        ((float)regionPosition.X + newX) * 0.20319f,
                        ((float)regionPosition.Y + newY) * 0.20319f,
                        height * 0.25f
                                  );

                    float lowFreq  = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f;
                    float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f;
                    float noise    = (lowFreq + highFreq) * 2f;

                    // Combine the current height, generated noise, start height, and height range parameters, then scale all of it
                    float layer = ((height + noise - startHeight) / heightRange) * 4f;
                    if (Single.IsNaN(layer))
                    {
                        layer = 0f;
                    }
                    layermap [(int)(newY * newRsX + newX)] = Utils.Clamp(layer, 0f, 3f);
                }
            }

            #endregion Layer Map

            #region Texture Compositing

            Bitmap     output     = new Bitmap(outWidth, outHeight, PixelFormat.Format24bppRgb);
            BitmapData outputData = output.LockBits(new Rectangle(0, 0, outWidth, outHeight), ImageLockMode.WriteOnly,
                                                    PixelFormat.Format24bppRgb);

            unsafe
            {
                // Get handles to all of the texture data arrays
                BitmapData [] datas =
                {
                    detailTexture[0].LockBits(new Rectangle(0,               0, outWidth, outHeight),
                                              ImageLockMode.ReadOnly,
                                              detailTexture[0].PixelFormat),
                    detailTexture[1].LockBits(new Rectangle(0,               0, outWidth, outHeight),
                                              ImageLockMode.ReadOnly,
                                              detailTexture[1].PixelFormat),
                    detailTexture[2].LockBits(new Rectangle(0,               0, outWidth, outHeight),
                                              ImageLockMode.ReadOnly,
                                              detailTexture[2].PixelFormat),
                    detailTexture[3].LockBits(new Rectangle(0,               0, outWidth, outHeight),
                                              ImageLockMode.ReadOnly,
                                              detailTexture[3].PixelFormat)
                };

                int [] comps =
                {
                    (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
                    (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
                    (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
                    (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3
                };

                for (int y = 0; y < newRsY; y++)
                {
                    for (int x = 0; x < newRsX; x++)
                    {
                        float layer = layermap [y * newRsX + x];

                        // Select two textures
                        int l0 = (int)Math.Floor(layer);
                        int l1 = Math.Min(l0 + 1, 3);

                        byte *ptrA = (byte *)datas [l0].Scan0 + y * datas [l0].Stride + x * comps [l0];
                        byte *ptrB = (byte *)datas [l1].Scan0 + y * datas [l1].Stride + x * comps [l1];
                        byte *ptrO = (byte *)outputData.Scan0 + y * outputData.Stride + x * 3;

                        float aB = *(ptrA + 0);
                        float aG = *(ptrA + 1);
                        float aR = *(ptrA + 2);

                        float bB = *(ptrB + 0);
                        float bG = *(ptrB + 1);
                        float bR = *(ptrB + 2);

                        float layerDiff = layer - l0;

                        // Interpolate between the two selected textures
                        *(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB));
                        *(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG));
                        *(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR));
                    }
                }

                for (int i = 0; i < 4; i++)
                {
                    detailTexture [i].UnlockBits(datas [i]);
                    detailTexture [i].Dispose();
                }
            }

            layermap = null;
            output.UnlockBits(outputData);

            // We generated the texture upside down, so flip it
            output.RotateFlip(RotateFlipType.RotateNoneFlipY);

            #endregion Texture Compositing

            return(output);
        }
Example #39
0
 /// <summary>
 /// Constructor. Creates a new cube with center <c>[0,0,0]</c> and
 /// dimensions <c>[1,1,1]</c>.
 /// </summary>
 public Cube()
 {
     center     = Vector3d.xyz(0, 0, 0);
     dimensions = Vector3d.xyz(1, 1, 1);
 }