コード例 #1
0
 public JacobianConstraint(
     IShapeCommon objectA,
     IShapeCommon objectB,
     int?contactReference,
     Vector3d?linearComponentA,
     Vector3d?linearComponentB,
     Vector3d angularComponentA,
     Vector3d angularComponentB,
     ConstraintType type,
     double constraintValue,
     double jacobianVelocity,
     double correctionValue,
     double cfm,
     double constraintLimit)
 {
     ObjectA           = objectA;
     ObjectB           = objectB;
     ContactReference  = contactReference;
     LinearComponentA  = linearComponentA;
     LinearComponentB  = linearComponentB;
     AngularComponentA = angularComponentA;
     AngularComponentB = angularComponentB;
     Type             = type;
     ConstraintValue  = constraintValue;
     JacobianVelocity = jacobianVelocity;
     CorrectionValue  = correctionValue;
     CFM             = cfm;
     ConstraintLimit = constraintLimit;
 }
コード例 #2
0
 public void reset()
 {
     angle            = 0;
     force            = new Vector3d();
     movement         = new Vector3d();
     previousPosition = null;
 }
コード例 #3
0
ファイル: gl_lines.cs プロジェクト: tsal/Principia
            public static void RenderAndDeleteTrajectory(IntPtr trajectory_iterator,
                                                         UnityEngine.Color colour,
                                                         Style style)
            {
                try {
                    Vector3d?previous_point = null;

                    UnityEngine.GL.Color(colour);
                    int size = trajectory_iterator.IteratorSize();

                    for (int i = 0;
                         !trajectory_iterator.IteratorAtEnd();
                         trajectory_iterator.IteratorIncrement(), ++i)
                    {
                        Vector3d current_point = (Vector3d)trajectory_iterator.IteratorGetXYZ();
                        if (previous_point.HasValue)
                        {
                            if (style == Style.FADED)
                            {
                                colour.a = (float)(4 * i + size) / (float)(5 * size);
                                UnityEngine.GL.Color(colour);
                            }
                            if (style != Style.DASHED || i % 2 == 1)
                            {
                                AddSegment(previous_point.Value,
                                           current_point,
                                           hide_behind_bodies: true);
                            }
                        }
                        previous_point = current_point;
                    }
                } finally {
                    Interface.IteratorDelete(ref trajectory_iterator);
                }
            }
コード例 #4
0
        public Vector3d?Execute(
            IShape[] shapes,
            Vector3d origin,
            Vector3d direction)
        {
            var      minDistance = double.MaxValue;
            Vector3d?res         = null;

            foreach (var shape in shapes)
            {
                var hit = Execute(shape, origin, direction, false);

                if (hit.HasValue)
                {
                    var dist = (origin - hit.Value).Length();
                    if (dist < minDistance)
                    {
                        minDistance = dist;
                        res         = hit.Value;
                    }
                }
            }

            return(res);
        }
コード例 #5
0
        // DotColour = transparent, use the map colour associated with each entry.  Else use this colour for all

        public List <IData3DSet> BuildSystems(bool DrawLines, bool DrawDots, Color DotColour, List <HistoryEntry> syslists)
        {
            // we use the expanded capability of Line and Point to holds colours for each element instead of the previous sorting system
            // This means less submissions to GL.

            if (syslists.Any())
            {
                if (DrawLines)
                {
                    var datasetl = Data3DSetClass <LineData> .Create("visitedstarslines", Color.Transparent, 2.0f);

                    Vector3d?lastpos = null;

                    foreach (HistoryEntry sp in syslists)
                    {
                        if (sp.System.HasCoordinate)
                        {
                            if (lastpos.HasValue)
                            {
                                Color c = Color.FromArgb(255, Color.FromArgb(sp.MapColour));         // convert to colour, ensure alpha is 255 (some time in the past this value could have been screwed up)
                                if (c.GetBrightness() < 0.05)                                        // and ensure it shows
                                {
                                    c = Color.Red;
                                }

                                datasetl.Add(new LineData(sp.System.x, sp.System.y, sp.System.z,
                                                          lastpos.Value.X, lastpos.Value.Y, lastpos.Value.Z, c));
                            }

                            lastpos = new Vector3d(sp.System.x, sp.System.y, sp.System.z);
                        }
                    }

                    _datasets.Add(datasetl);
                }

                if (DrawDots)
                {
                    var datasetp = Data3DSetClass <PointData> .Create("visitedstarsdots", DotColour, 2.0f);

                    foreach (HistoryEntry vs in syslists)
                    {
                        if (vs.System.HasCoordinate)
                        {
                            Color c = Color.FromArgb(255, Color.FromArgb(vs.MapColour));         // convert to colour, ensure alpha is 255 (some time in the past this value could have been screwed up)
                            if (c.GetBrightness() < 0.05)                                        // and ensure it shows
                            {
                                c = Color.Red;
                            }

                            datasetp.Add(new PointData(vs.System.x, vs.System.y, vs.System.z, c));
                        }
                    }

                    _datasets.Add(datasetp);
                }
            }

            return(_datasets);
        }
コード例 #6
0
ファイル: Autodesk3ds.cs プロジェクト: layshua/Alexandria
            /// <summary>Read a content color.</summary>
            /// <param name="defaultValue"></param>
            /// <returns></returns>
            public Vector3d ReadContentColor(Vector3d defaultValue)
            {
                Vector3d?value3b = null, value3f = null, valueLinear3b = null, valueLinear3f = null;
                Chunk    subchunk;

                if (DataLength == 0)
                {
                    Loader.AddError(Offset, "Expected chunk {0} to contain a color, but it is empty.", IdString);
                }
                while (ReadSubchunk(out subchunk))
                {
                    switch (subchunk.Id)
                    {
                    case ChunkId.Color3b: value3b = new Vector3d(Reader.ReadByte() / 255.0, Reader.ReadByte() / 255.0, Reader.ReadByte() / 255.0); break;

                    case ChunkId.Color3f: value3f = Reader.ReadVector3f(); break;

                    case ChunkId.LinearColor3b: valueLinear3b = new Vector3d(Reader.ReadByte() / 255.0, Reader.ReadByte() / 255.0, Reader.ReadByte() / 255.0); break;

                    case ChunkId.LinearColor3f: valueLinear3f = Reader.ReadVector3f(); break;

                    default: ReportUnknownSubchunkError(subchunk); break;
                    }
                    subchunk.RequireAtEnd();
                }

                return(valueLinear3f.HasValue ? valueLinear3f.Value : valueLinear3b.HasValue?valueLinear3b.Value : value3f.HasValue ? value3f.Value : value3b.HasValue ? value3b.Value : defaultValue);
            }
コード例 #7
0
        public Intersection Intersect(Ray ray)
        {
            double t = Vector3d.Dot((Origin - ray.Origin), Normal)
                       / Vector3d.Dot(ray.Direction, Normal);
            Vector3d?intersectionPos = ray.Evaluate(t);

            return(intersectionPos.HasValue ?
                   new Intersection(intersectionPos.Value) : null);
        }
コード例 #8
0
        /// <summary>
        /// Corrects axes (different axes labels/positioning system for scene in original raytracer and system used for PLY files)
        /// Inverts 3rd axis of position
        /// </summary>
        /// <param name="position">Position in original raytracer scene</param>
        /// <returns>Position in standard system for PLY files (or zero vector if input is null)</returns>
        public static Vector3d AxesCorrector(Vector3d?position)
        {
            if (position == null)
            {
                return(Vector3d.Zero);
            }

            return((Vector3d)position * axesCorrectionVector);
        }
コード例 #9
0
 /// <summary>
 /// (境界込みで) 直線と三角形との交点が存在するか否かを判定します
 /// (注意:直線は半直線ではありません)
 /// </summary>
 /// <param name="line">直線</param>
 /// <param name="intersection">交点</param>
 /// <returns>true -> 交点 (三角形に対し IN or ON) が存在する, false -> 存在しない</returns>
 public bool Intersects(Line line, out Vector3d?intersection)
 {
     // 直線と平面との交点計算 と 点と三角形との包含判定に還元する
     intersection = line.GetIntersection(this.Plane);
     if (intersection.HasValue)
     {
         return(IsInOrOn(intersection.Value));
     }
     return(false);
 }
コード例 #10
0
        public Vector3d?Execute(
            IShape shape,
            Vector3d origin,
            Vector3d direction,
            bool selectShape)
        {
            var boundingBox = shape.AABBox;
            var hitBB       = Helper.HitBoundingBox(
                boundingBox.Min,
                boundingBox.Max,
                origin,
                direction);

            if (hitBB.HasValue)
            {
                var      vertices  = Helper.GetVertexPosition1(shape);
                var      triangles = Helper.GetTriangles(shape);
                Vector3d?result    = null;

                for (int i = 0; i < vertices.Length; i++)
                {
                    var vt       = vertices[i];
                    var distance = double.MaxValue;
                    foreach (var triangle in triangles[i])
                    {
                        var intersection = GeometryUtils.RayIntersectTriangle(
                            vt[triangle.a],
                            vt[triangle.b],
                            vt[triangle.c],
                            origin,
                            direction);

                        if (intersection.HasValue)
                        {
                            if (selectShape)
                            {
                                return(intersection);
                            }

                            var dst = (origin - intersection.Value).Length();

                            if (dst < distance)
                            {
                                distance = dst;
                                result   = intersection.Value;
                            }
                        }
                    }
                }

                return(result);
            }

            return(null);
        }
コード例 #11
0
 /// <summary>
 /// Corrects axes (different axes labels/positioning system for scene in original raytracer and system used for PLY files)
 /// Inverts 3rd axis of position
 /// </summary>
 /// <param name="position">Position in original raytracer scene</param>
 /// <returns>Position in standard system for PLY files (or zero vector if input is null)</returns>
 public static Vector3d AxesCorrector(Vector3d?position)
 {
     if (position == null)
     {
         return(new Vector3d(0, 0, 0));
     }
     else
     {
         return((Vector3d)position * axesCorrectionVector);
     }
 }
コード例 #12
0
        public Entity Create(string filepath, Vector3d?position = null, Vector3d?scale = null, string program = "standard", string texture = "Resources/Textures/debug-256.png")
        {
            var g = new GraphicComponent();

            g.ModelName     = filepath;
            g.ProgramName   = program;
            g.TextureName   = texture;
            g.Model         = ResourceManager.Models.Load(filepath);
            g.Model.Program = ResourceManager.Programs[program];
            g.Model.Texture = ResourceManager.Textures[texture];

            var b = new BaseComponent();

            if (null != scale)
            {
                b.Scale = scale.Value;
            }
            if (null != position)
            {
                b.Position = position.Value;
            }

            var bb = g.Model.Mesh().BoundingBox;

            if (null != scale)
            {
                bb.Max = Vector3d.Multiply(bb.Max, scale.Value);
                bb.Min = Vector3d.Multiply(bb.Min, scale.Value);
            }

            var bs = g.Model.Mesh().BoundingSphere;

            if (null != scale)
            {
                bs.Radius *= scale.Value.Length;
            }

            var e = new Entity(filepath, true)
                    .Add(b)
                    .Add(new PhysicComponent()
            {
                BoundingBox = bb, BoundingSphere = bs
            })
                    .Add(g);

            EntityManager.AddEntity(e);

            return(e);
        }
コード例 #13
0
ファイル: Mesh.cs プロジェクト: rgsmohan/CodeFullToolkit
        /// <summary>
        /// Performs a ray casting hit test using the specified ray. This function does not
        /// take the ray into its own space! Thus make sure the ray is specified in the space of this
        /// object (with proper transforms applied to it).
        /// </summary>
        /// <param name="ray">The ray to perform hit test for</param>
        /// <returns>The result of the hit test if anything occurred. null otherwise.</returns>
        public override HitTestResult HitTest(Ray ray)
        {
            // First determine if the ray hits the AABB
            if (this.AABB.HitTest(ray) == null)
            {
                return(null);
            }

            System.Collections.Concurrent.ConcurrentBag <MeshHitTestResult> hits = new System.Collections.Concurrent.ConcurrentBag <MeshHitTestResult>();

            Parallel.ForEach(Triangles, item =>
            {
                Vector3d?intersection = item.IntersectionWith(ray);

                if (intersection != null)
                {
                    hits.Add(new MeshHitTestResult(this, Transform.Transform(intersection.Value), item));
                }
            });

            double   minDist        = int.MaxValue;
            Vector3d bestHit        = Vector3d.Zero;
            Triangle triHit         = null;
            Vector3d cameraPoistion = Camera.MainCamera.Position;

            foreach (var item in hits)
            {
                if (item == null)
                {
                    continue;
                }

                double dist = (cameraPoistion - item.HitPoint).LengthSquared;
                if (dist < minDist)
                {
                    minDist = dist;
                    bestHit = Vector3d.Transform(item.HitPoint, Transform.Value.Inverted());
                    triHit  = item.TriangleHit;
                }
            }

            // If nothing was hit
            if (triHit == null)
            {
                return(null);
            }

            return(new MeshHitTestResult(this, bestHit, triHit));
        }
コード例 #14
0
 public JacobianConstraint(JacobianConstraint jc)
 {
     ObjectA           = jc.ObjectA;
     ObjectB           = jc.ObjectB;
     ContactReference  = jc.ContactReference;
     LinearComponentA  = jc.LinearComponentA;
     LinearComponentB  = jc.LinearComponentB;
     AngularComponentA = jc.AngularComponentA;
     AngularComponentB = jc.AngularComponentB;
     Type             = jc.Type;
     JacobianVelocity = jc.JacobianVelocity;
     ConstraintValue  = jc.ConstraintValue;
     JacobianVelocity = jc.JacobianVelocity;
     CorrectionValue  = jc.CorrectionValue;
     CFM             = jc.CFM;
     ConstraintLimit = jc.ConstraintLimit;
 }
コード例 #15
0
        /// <summary>Determines if an antenna can connect to a target indirectly, using a cone.</summary>
        /// <returns><c>true</c> if <paramref name="target"/> lies within the cone of <paramref name="dish"/>;
        /// otherwise, <c>false</c>.</returns>
        /// <param name="dish">The antenna being queried.</param>
        /// <param name="target">The satellite being tested for being the antenna target.</param>
        /// <param name="antennaSat">The satellite containing <paramref name="dish"/>.</param>
        ///
        /// <exceptsafe>The program state is unchanged in the event of an exception.</exceptsafe>
        public static bool IsInFieldOfView(this IAntenna dish, ISatellite target, ISatellite antennaSat)
        {
            if (dish.Target == Guid.Empty)
            {
                return(false);
            }

            Vector3d?coneCenter = RTCore.Instance.Network.GetPositionFromGuid(dish.Target);

            if (coneCenter.HasValue)
            {
                Vector3d dirToConeCenter = (coneCenter.Value - antennaSat.Position);
                Vector3d dirToTarget     = (target.Position - antennaSat.Position);

                return(Vector3d.Dot(dirToConeCenter.normalized, dirToTarget.normalized) >= dish.CosAngle);
            }

            return(false);
        }
コード例 #16
0
        private void AddLCPValues(
            ref List <int> index,
            ref List <double> values,
            int indexVal,
            KeyValuePair <HashSetStruct, List <DictionaryConstraintValue> > constraintCheckItem,
            HashSetStruct constraintValuesKey,
            HashSetStruct symmetricHashSet,
            Vector3d?linearComponentA,
            Vector3d angularComponentA,
            MassData massData,
            bool componentA)
        {
            double mValue = 0.0;

            if (!constraintCheckItem.Key.Equals(constraintValuesKey) &&
                !constraintCheckItem.Key.Equals(symmetricHashSet))
            {
                for (int i = 0; i < constraintCheckItem.Value.Count; i++)
                {
                    int innerIndex = constraintCheckItem.Value[i].Index;

                    JacobianConstraint contactB = constraintCheckItem.Value[i].Constraint;

                    var lComponent = contactB.LinearComponentB;
                    var aComponent = contactB.AngularComponentB;

                    if (componentA)
                    {
                        lComponent = contactB.LinearComponentA;
                        aComponent = contactB.AngularComponentA;
                    }

                    mValue = GetLCPMatrixValue(
                        linearComponentA,
                        lComponent,
                        angularComponentA,
                        aComponent,
                        massData);

                    AddValues(ref index, ref values, mValue, innerIndex);
                }
            }
        }
コード例 #17
0
        public VisualModel(
            List <Vertex3D> vertices,
            List <EdgesLineStrip> edges,
            List <Triangle3D> triangles)
        {
            Vertices        = vertices;
            verticesVectors = vertices.Select(x => x.Position).ToList();

            Edges        = edges;
            edgesVectors = new List <Vector3d>();
            Vector3d?previousPosition = null;

            foreach (var edge in edges)
            {
                foreach (var edgeElement in edge.Elements)
                {
                    if (previousPosition != null)
                    {
                        edgesVectors.Add(previousPosition.Value);
                        edgesVectors.Add(edgeElement.Position.Position);
                    }

                    previousPosition = edgeElement.Position.Position;
                }

                if (edge.Type == ContourType.Closed)
                {
                    edgesVectors.Add(edge.End.Position);
                    edgesVectors.Add(edge.Start.Position);
                }

                previousPosition = null;
            }

            Triangles        = triangles;
            trianglesVectors = triangles
                               .SelectMany(x => x.Vertices)
                               .Select(x => x.Position)
                               .ToList();

            boundingBox = BoundingBox.CreateFromPoints(trianglesVectors);
        }
コード例 #18
0
        private void CreateEntities(Point3d insertionPoint, List <Point3d> middlePoints, Point3d endPoint, double scale)
        {
            var points = GetPointsForMainPolyline(insertionPoint, middlePoints, endPoint);

            _mainPolyline = new Polyline(points.Count);
            SetImmutablePropertiesToNestedEntity(_mainPolyline);
            for (var i = 0; i < points.Count; i++)
            {
                _mainPolyline.AddVertexAt(i, points[i], 0.0, 0.0, 0.0);
            }

            _offsetPolylineEntities.Clear();
            foreach (Entity offsetCurve in _mainPolyline.GetOffsetCurves(LineThickness))
            {
                _offsetPolylineEntities.Add(offsetCurve);
            }

            // create strokes
            _strokes.Clear();
            if (_mainPolyline.Length >= MinDistanceBetweenPoints)
            {
                for (var i = 1; i < _mainPolyline.NumberOfVertices; i++)
                {
                    var      segmentStartPoint     = _mainPolyline.GetPoint3dAt(i - 1);
                    var      segmentEndPoint       = _mainPolyline.GetPoint3dAt(i);
                    Vector3d?previousSegmentVector = null;
                    Vector3d?nextSegmentVector     = null;
                    if (i > 1)
                    {
                        previousSegmentVector = segmentStartPoint - _mainPolyline.GetPoint3dAt(i - 2);
                    }
                    if (i < _mainPolyline.NumberOfVertices - 1)
                    {
                        nextSegmentVector = _mainPolyline.GetPoint3dAt(i + 1) - segmentEndPoint;
                    }

                    _strokes.AddRange(CreateStrokesOnMainPolylineSegment(
                                          segmentEndPoint, segmentStartPoint, scale, previousSegmentVector, nextSegmentVector));
                }
            }
        }
コード例 #19
0
        private double GetLCPMatrixValue(
            Vector3d?linearComponentA,
            Vector3d?linearComponentB,
            Vector3d angularComponentA,
            Vector3d angularComponentB,
            MassData massData)
        {
            double LCPValue = 0.0;

            if (linearComponentA.HasValue &&
                linearComponentB.HasValue)
            {
                LCPValue += linearComponentA.Value.Dot(
                    linearComponentB.Value * massData.InverseMass);
            }

            LCPValue += angularComponentA.Dot(
                massData.InverseInertiaTensor * angularComponentB);

            return(LCPValue);
        }
コード例 #20
0
        // v2.4.0 and above suffixes.
        private GeoCoordinates GetTarget()
        {
            if (shared.Vessel != FlightGlobals.ActiveVessel)
            {
                throw new KOSException("You may only call addons:tr:GETTARGET from the active vessel and must also have a trajectories target set." +
                                       " Always check addons:tr:HASTARGET");
            }
            if (Available())
            {
                Vector3d?result = TRWrapper.GetTarget();
                if (result != null)
                {
                    return(new GeoCoordinates(shared, result.Value.x, result.Value.y));
                }

                throw new KOSException("GETTARGET is not available or no target is set. Remember to check addons:tr:HASTARGET." +
                                       " Also GETTARGET was added in Trajectories v2.4.0. and your version might be older." +
                                       " Check addons:tr:ISVERTWOFOUR or addons:tr:GETVERSION");
            }
            throw new KOSUnavailableAddonException("GETTARGET", "Trajectories");
        }
コード例 #21
0
        /// <summary>
        /// Checks to see if the curve is roughly aligned with a vector. This uses the start and
        /// end points to create a vector to check with, so it is useless for closed curves
        /// or ones with excessive curvature.
        /// </summary>
        /// <param name="c"></param>
        /// <param name="t">Parameter at 'bottom' of the curve, at the end which is the furthest
        /// from the vector.</param>
        /// <param name="v">Vector to compare to. If null, the Z-axis will be used.</param>
        /// <param name="limit">Dot product limit to test if it is aligned.</param>
        /// <returns>Whether or not the curve is 'aligned' with the vector.</returns>
        public static bool IsAlignedWithVector(this Curve c, out double t, Vector3d?v, double limit = 0.5)
        {
            if (v == null)
            {
                v = Vector3d.ZAxis;
            }
            t = 0.0;
            double m;
            Plane  p = c.GetAlignedPlane(5, out m);

            if (p.YAxis * v > limit)
            {
                t = c.Domain.Min;
                return(true);
            }
            else if (-p.YAxis * v > limit)
            {
                t = c.Domain.Max;
                return(true);
            }
            return(false);
        }
コード例 #22
0
        /// <summary>
        /// 生成多边形
        /// </summary>
        /// <param name="vertexs"></param>
        /// <returns></returns>
        public Poly CreatePoly(List <Vector3d[]> polyVertexsList, Vector3d?faceNormal)
        {
            Poly poly = new Poly();

            poly.vertexsList = polyVertexsList;

            if (faceNormal == null)
            {
                Vector3d[] polyVertexs = polyVertexsList[0];
                Vector3d   vec1        = polyVertexs[1] - polyVertexs[0];
                Vector3d   vec2        = polyVertexs[2] - polyVertexs[0];
                poly.faceNormal = Vector3d.Cross(vec1, vec2);
                poly.faceNormal.Normalize();
            }
            else
            {
                poly.faceNormal = faceNormal.Value;
            }

            poly.sidesList = CreatePolySidesList(poly.vertexsList, poly.faceNormal);
            return(poly);
        }
コード例 #23
0
ファイル: MeshMeshCut.cs プロジェクト: CBenghi/geometry3Sharp
        private void DebugInfo(string type, Dictionary <int, List <SegmentVtx> > vtcs, Vector3d?query = null)
        {
            // Debug.WriteLine(type + "s");
            var i = -1;

            foreach (var pair in vtcs)
            {
                i++;
                if (query.HasValue)
                {
                    if (!pair.Value.Any(x => x.v.DistanceSquared(query.Value) == 0))
                    {
                        continue; // skip if not found
                    }
                }

                Debug.WriteLine($"{type}s[{i}]");

                Debug.WriteLine($"  {type} id: {pair.Key}");
                foreach (var segV in pair.Value)
                {
                    Debug.WriteLine($"  {segV.v}");
                }
            }
        }
コード例 #24
0
    public void Generate()
    {
        int    s       = GridSize + 1;
        double scale   = size / GridSize;
        double invSize = 1.0 / size;

        Vector3d p1, p2, p3, tmp, tan;
        double   n;
        Vector3d offset = new Vector3d(GridSize * .5, 0, GridSize * .5);

        vertices  = new Vector3[s * s];
        normals   = new Vector3[s * s];
        tangents  = new Vector4[s * s];
        texcoord0 = new Vector4[s * s];
        weights   = new Color[s * s];

        Vector3d?[,] vertexCache = new Vector3d?[s, s];
        double?[,] noiseCache    = new double?[s, s];

        bool outwardNormals = type != SurfaceType.Ground;

        hasVisibleVertices = false;

        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        int j = 0;

        // surface mesh
        for (int x = 0; x < s; x++)
        {
            for (int z = 0; z < s; z++)
            {
                // get normalized cube space vertex (vertices -.5 to .5)
                if (vertexCache[x, z].HasValue)
                {
                    p1 = vertexCache[x, z].Value;
                    n  = noiseCache[x, z].Value;
                }
                else
                {
                    p1 = Vector3d.Normalize(cubePos + rotation * (scale * (new Vector3d(x, 0, z) - offset)));
                    p1 = p1 * GetHeight(p1, out n, ref hasVisibleVertices) - meshPos;
                    vertexCache[x, z] = p1;
                    noiseCache[x, z]  = n;
                }

                if (z + 1 < s && vertexCache[x, z + 1].HasValue)
                {
                    p2 = vertexCache[x, z + 1].Value;
                }
                else
                {
                    p2 = Vector3d.Normalize(cubePos + rotation * (scale * (new Vector3d(x, 0, z + 1) - offset)));
                    p2 = p2 * GetHeight(p2, out n, ref hasVisibleVertices) - meshPos;
                    if (z + 1 < s)
                    {
                        vertexCache[x, z + 1] = p2;
                        noiseCache[x, z + 1]  = n;
                    }
                }

                if (x + 1 < s && vertexCache[x + 1, z].HasValue)
                {
                    p3 = vertexCache[x + 1, z].Value;
                }
                else
                {
                    p3 = Vector3d.Normalize(cubePos + rotation * (scale * (new Vector3d(x + 1, 0, z) - offset)));
                    p3 = p3 * GetHeight(p3, out n, ref hasVisibleVertices) - meshPos;
                    if (x + 1 < s)
                    {
                        vertexCache[x + 1, z] = p3;
                        noiseCache[x + 1, z]  = n;
                    }
                }

                tmp = (p1 + meshPos).normalized;
                tan = Vector3d.Cross(planet.rotation * Vector3d.up, tmp).normalized;

                vertices[j]  = (Vector3)(p1 * invSize);
                normals[j]   = outwardNormals ? (Vector3)tmp : Vector3.Cross((Vector3)Vector3d.Normalize(p2 - p1), (Vector3)Vector3d.Normalize(p3 - p1));
                texcoord0[j] = new Vector4((float)tmp.x, (float)tmp.y, (float)tmp.z, (float)size);
                tangents[j]  = (Vector3)tan;
                weights[j]   = planet.heightWeightGradient.Evaluate((float)n);
                j++;
            }
        }

        sw.Stop();
        lock (sfctimes) sfctimes.Add(sw.Elapsed.TotalMilliseconds);
        sw.Reset();

        // grass, trees, surface objects
        if (type == SurfaceType.Ground)
        {
            // trees
            if (planet.hasTrees &&
                vertexResolution >= planet.treeVertexResolution && vertexResolution * .5 < planet.treeVertexResolution)
            {
                sw.Start();
                trees = new TreeInstance[1];
                System.Random rand = new System.Random(planet.seed ^ (meshPos.GetHashCode()));

                GameObject tree = planet.treePrefabs[0];
                bool       q    = false;

                double           h;
                float            x, z;
                List <Matrix4x4> m = new List <Matrix4x4>();
                for (int i = 0; i < .01 * (size * size); i++)
                {
                    x  = (float)rand.NextDouble() * GridSize;
                    z  = (float)rand.NextDouble() * GridSize;
                    p1 = (cubePos + rotation * (scale * (new Vector3d(x, 0, z) - offset)));
                    p1 = p1.normalized;
                    h  = GetHeight(p1, out n, ref q);
                    if (h > planet.radius + planet.waterHeight)
                    {
                        p2 = p1;
                        p1 = p1 * h - meshPos;
                        m.Add(Matrix4x4.TRS(
                                  (Vector3)p1, Quaternion.FromToRotation(Vector3.up, (Vector3)p2), Vector3.one
                                  ));
                    }
                }

                TreeInstance t = new TreeInstance()
                {
                    instances    = m.ToArray(),
                    tmpinstances = new Matrix4x4[m.Count],
                    prefab       = tree
                };
                trees[0] = t;

                sw.Stop();
                lock (treetimes) treetimes.Add(sw.Elapsed.TotalMilliseconds);
                sw.Reset();
            }

            // grass
            // TODO: grass generation is atrociously slow
            if (planet.hasGrass &&
                vertexResolution >= planet.grassVertexResolution && vertexResolution * .5 < planet.grassVertexResolution)
            {
                sw.Start();

                System.Random rand = new System.Random(~(planet.seed ^ (meshPos.GetHashCode())));

                int        count = (int)(planet.grassDensity * size * size);
                List <int> ginds = new List <int>(count);
                gverts = new List <Vector3>(count);
                gnorms = new List <Vector3>(count);
                guvs   = new List <Vector4>(count);
                double   h2 = (planet.radius + planet.waterHeight) * (planet.radius + planet.waterHeight);
                float    x, z, xr, zr;
                Vector3d pos;
                for (int i = 0; i < count; i++)
                {
                    x = (float)(rand.NextDouble() * GridSize);
                    z = (float)(rand.NextDouble() * GridSize);

                    xr = x - (int)x;
                    zr = z - (int)z;

                    // interpolate height from mesh
                    pos = (Vector3d)bilinear(
                        vertices[(int)x * s + (int)z],
                        vertices[(int)x * s + (int)z + 1],
                        vertices[(int)(x + 1) * s + (int)z],
                        vertices[(int)(x + 1) * s + (int)z + 1],
                        xr, zr) * size;

                    double h = ((pos + meshPos).magnitude - planet.radius) / planet.terrainHeight;
                    if (planet.heightWeightGradient.Evaluate((float)h).g > .5f)
                    {
                        gverts.Add((Vector3)pos);
                        gnorms.Add(bilinear(
                                       normals[(int)x * s + (int)z],
                                       normals[(int)x * s + (int)z + 1],
                                       normals[(int)(x + 1) * s + (int)z],
                                       normals[(int)(x + 1) * s + (int)z + 1],
                                       xr, zr).normalized);
                        guvs.Add(new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), 1f, (float)rand.NextDouble()));
                        ginds.Add(gverts.Count - 1);
                    }
                }

                grassindices = ginds.ToArray();

                sw.Stop();
                lock (grasstimes) grasstimes.Add(sw.Elapsed.TotalMilliseconds);
                sw.Reset();
            }
        }

        generated = true;
    }
コード例 #25
0
        // DotColour = transparent, use the map colour associated with each entry.  Else use this colour for all

        public List <IData3DCollection> BuildSystems(bool DrawLines, bool DrawDots, Color DotColour, List <HistoryEntry> syslists)
        {
            // we use the expanded capability of Line and Point to holds colours for each element instead of the previous sorting system
            // This means less submissions to GL.

            if (syslists.Any())
            {
                if (DrawLines)
                {
                    var datasetl = Data3DCollection <LineData> .Create("visitedstarslines", Color.Transparent, 2.0f);

                    Vector3d?lastpos = null;

                    Color drawcolour = Color.Green;

                    foreach (HistoryEntry sp in syslists)
                    {
                        if (sp.EntryType == JournalTypeEnum.Resurrect || sp.EntryType == JournalTypeEnum.Died)
                        {
                            lastpos = null;
                        }
                        else if (sp.IsLocOrJump && sp.System.HasCoordinate)
                        {
                            if (sp.journalEntry is IJournalJumpColor)
                            {
                                drawcolour = Color.FromArgb(((IJournalJumpColor)sp.journalEntry).MapColor);
                                if (drawcolour.GetBrightness() < 0.05)
                                {
                                    drawcolour = Color.Red;
                                }
                            }

                            if (lastpos.HasValue)
                            {
                                datasetl.Add(new LineData(sp.System.X, sp.System.Y, sp.System.Z,
                                                          lastpos.Value.X, lastpos.Value.Y, lastpos.Value.Z, drawcolour));
                            }

                            lastpos = new Vector3d(sp.System.X, sp.System.Y, sp.System.Z);
                        }
                    }

                    _datasets.Add(datasetl);
                }

                if (DrawDots)
                {
                    var datasetp = Data3DCollection <PointData> .Create("visitedstarsdots", DotColour, 2.0f);

                    Color drawcolour = Color.Green;

                    foreach (HistoryEntry vs in syslists)
                    {
                        if (vs.System.HasCoordinate)
                        {
                            if (vs.journalEntry is IJournalJumpColor)
                            {
                                drawcolour = Color.FromArgb(((IJournalJumpColor)vs.journalEntry).MapColor);
                                if (drawcolour.GetBrightness() < 0.05)
                                {
                                    drawcolour = Color.Red;
                                }
                            }

                            datasetp.Add(new PointData(vs.System.X, vs.System.Y, vs.System.Z, drawcolour));
                        }
                    }

                    _datasets.Add(datasetp);
                }
            }

            return(_datasets);
        }
コード例 #26
0
        private IEnumerable <Polyline> CreateStrokesOnMainPolylineSegment(
            Point3d segmentEndPoint, Point3d segmentStartPoint, double scale, Vector3d?previousSegmentVector, Vector3d?nextSegmentVector)
        {
            var strokes = new List <Polyline>();

            var lineThickness = LineThickness * scale;
            var segmentVector = segmentEndPoint - segmentStartPoint;

            var previousToCurrentCrossProductIndex = 1.0;

            if (previousSegmentVector != null)
            {
                previousToCurrentCrossProductIndex =
                    previousSegmentVector.Value.CrossProduct(segmentVector).GetNormal().Z;
            }

            var currentToNextCrossProductIndex = 1.0;

            if (nextSegmentVector != null)
            {
                currentToNextCrossProductIndex = segmentVector.CrossProduct(nextSegmentVector.Value).GetNormal().Z;
            }

            var angleToPreviousSegment = previousSegmentVector != null
                ? previousSegmentVector.Value.GetAngleTo(segmentVector)
                : 0.0;

            var startBackOffset = 0.0;

            if (previousToCurrentCrossProductIndex < 0 && angleToPreviousSegment > 0.0)
            {
                startBackOffset = Math.Abs(lineThickness * Math.Tan(Math.PI - (angleToPreviousSegment / 2.0)));
            }

            var angleToNextSegment = nextSegmentVector != null
                ? segmentVector.GetAngleTo(nextSegmentVector.Value)
                : 0.0;

            var endBackOffset = 0.0;

            if (currentToNextCrossProductIndex < 0 && angleToNextSegment > 0.0)
            {
                endBackOffset = Math.Abs(lineThickness * Math.Tan(Math.PI - (angleToNextSegment / 2.0)));
            }

            var segmentLength          = segmentVector.Length;
            var perpendicular          = segmentVector.GetPerpendicularVector().Negate();
            var distanceAtSegmentStart = _mainPolyline.GetDistAtPoint(segmentStartPoint);

            var overflowIndex = 0;

            var sumDistanceAtSegment = 0.0;
            var isSpace = true;
            var isStart = true;

            while (true)
            {
                overflowIndex++;
                double distance;
                if (isStart)
                {
                    if (FirstStrokeOffset == WaterProofingFirstStrokeOffset.ByHalfStrokeOffset)
                    {
                        distance = StrokeOffset / 2.0 * scale;
                    }
                    else if (FirstStrokeOffset == WaterProofingFirstStrokeOffset.ByStrokeOffset)
                    {
                        distance = StrokeOffset * scale;
                    }
                    else
                    {
                        distance = 0.0;
                    }

                    distance += startBackOffset;

                    isStart = false;
                }
                else
                {
                    if (isSpace)
                    {
                        distance = StrokeOffset * scale;
                    }
                    else
                    {
                        distance = StrokeLength * scale;
                    }
                }

                sumDistanceAtSegment += distance;

                if (!isSpace)
                {
                    var firstStrokePoint = _mainPolyline.GetPointAtDist(distanceAtSegmentStart + sumDistanceAtSegment - distance) +
                                           (perpendicular * lineThickness / 2.0);

                    if ((sumDistanceAtSegment - distance) < (sumDistanceAtSegment - endBackOffset))
                    {
                        // Если индекс, полученный из суммы векторов (текущий и следующий) отрицательный и последний штрих
                        // попадает на конец сегмента полилинии, то его нужно построить так, чтобы он попал на точку не основной
                        // полилинии, а второстепенной

                        Point3d secondStrokePoint;
                        if (sumDistanceAtSegment >= segmentLength)
                        {
                            AcadUtils.WriteMessageInDebug($"segment vector: {segmentVector.GetNormal()}");
                            secondStrokePoint =
                                segmentEndPoint -
                                (segmentVector.GetNormal() * endBackOffset) +
                                (perpendicular * lineThickness / 2.0);
                            AcadUtils.WriteMessageInDebug($"{nameof(secondStrokePoint)}: {secondStrokePoint}");
                        }
                        else
                        {
                            secondStrokePoint =
                                _mainPolyline.GetPointAtDist(distanceAtSegmentStart + sumDistanceAtSegment) +
                                (perpendicular * lineThickness / 2.0);
                        }

                        var stroke = new Polyline(2);
                        stroke.AddVertexAt(0, firstStrokePoint.ConvertPoint3dToPoint2d(), 0.0, lineThickness,
                                           lineThickness);
                        stroke.AddVertexAt(1, secondStrokePoint.ConvertPoint3dToPoint2d(), 0.0, lineThickness,
                                           lineThickness);

                        SetImmutablePropertiesToNestedEntity(stroke);

                        strokes.Add(stroke);
                    }
                }

                if (sumDistanceAtSegment >= segmentLength)
                {
                    break;
                }

                if (overflowIndex >= 1000)
                {
                    break;
                }

                isSpace = !isSpace;
            }

            return(strokes);
        }
コード例 #27
0
 /// <summary>
 /// 生成多边形
 /// </summary>
 /// <param name="polyVertexsList"></param>
 /// <param name="faceNormal"></param>
 /// <returns></returns>
 public Poly CreatePoly(Vector3d[] polyVertexs, Vector3d?faceNormal = null)
 {
     return(CreatePoly(new List <Vector3d[]> {
         polyVertexs
     }, faceNormal));
 }
コード例 #28
0
        private static Vector2d GetCorrection()
        {
            if (!Trajectories.IsVesselAttached)
            {
                return(Vector2d.zero);
            }

            Vector3d?     targetPosition = TargetProfile.WorldPosition;
            CelestialBody body           = TargetProfile.Body;

            if (!targetPosition.HasValue || patch == null || !patch.ImpactPosition.HasValue || patch.StartingState.ReferenceBody != body || !patch.IsAtmospheric)
            {
                return(Vector2d.zero);
            }

            // Get impact position, or, if some point over the trajectory has not enough clearance, smoothly interpolate to that point depending on how much clearance is missing
            Vector3d impactPosition = patch.ImpactPosition.Value;

            foreach (Trajectory.Point p in patch.AtmosphericTrajectory)
            {
                double neededClearance  = 600.0d;
                double missingClearance = neededClearance - (p.pos.magnitude - body.Radius - p.groundAltitude);
                if (missingClearance > 0.0d)
                {
                    if (Vector3d.Distance(p.pos, patch.RawImpactPosition.Value) > 3000.0d)
                    {
                        double   coeff      = missingClearance / neededClearance;
                        Vector3d rotatedPos = p.pos;
                        if (!Settings.BodyFixedMode)
                        {
                            rotatedPos = Trajectory.CalculateRotatedPosition(body, p.pos, p.time);
                        }
                        impactPosition = impactPosition * (1.0d - coeff) + rotatedPos * coeff;
                    }
                    break;
                }
            }

            Vector3d right  = Vector3d.Cross(patch.ImpactVelocity.Value, impactPosition).normalized;
            Vector3d behind = Vector3d.Cross(right, impactPosition).normalized;

            Vector3d offset    = targetPosition.Value - impactPosition;
            Vector2d offsetDir = new Vector2d(Vector3d.Dot(right, offset), Vector3d.Dot(behind, offset));

            offsetDir *= 0.00005d; // 20km <-> 1 <-> 45° (this is purely indicative, no physical meaning, it would be very complicated to compute an actual correction angle as it depends on the spacecraft behavior in the atmosphere ; a small angle will suffice for a plane, but even a big angle might do almost nothing for a rocket)

            Vector3d pos = Trajectories.AttachedVessel.GetWorldPos3D() - body.position;
            Vector3d vel = Trajectories.AttachedVessel.obt_velocity - body.getRFrmVel(body.position + pos); // air velocity

            double plannedAngleOfAttack = (double)DescentProfile.GetAngleOfAttack(body, pos, vel);

            if (plannedAngleOfAttack < Util.HALF_PI)
            {
                offsetDir.y = -offsetDir.y; // behavior is different for prograde or retrograde entry
            }
            double maxCorrection = 1.0d;

            offsetDir.x = Util.Clamp(offsetDir.x, -maxCorrection, maxCorrection);
            offsetDir.y = Util.Clamp(offsetDir.y, -maxCorrection, maxCorrection);

            return(offsetDir);
        }
コード例 #29
0
                if (central != null && central != SO.U.getBody() /**/)
                {
                    position += (central.getPosition());
                    //console.log(this.name+' pos rel to ' + this.relativeTo);
                    velocity += (central.velocity);
                    // bomb
                }
            }
        }

        public void beforeMove(double deltaTIncrement)
        {
        }

        public void afterMove(double deltaTIncrement)
        {
        }

        /**
         *              Calculates orbit line from orbital elements. By default, the orbital elements might not be osculating, i.e. they might account for perturbations. But the given orbit would thus be different slightly from the planet's path, as the velocity is calculated by considering that the orbit is elliptic.
         */

        public List <Vector3d> getOrbitVertices(bool isElliptic)
        {
            var points = new List <Vector3d>();

            double startTime = getEpochTime(SO.U.currentTime);

            OrbitalElements.OrbitalElementsPieces elements = orbitalElements.calculateElements(startTime);
            double period = orbitalElements.calculatePeriod(elements, relativeTo);

            if (period == 0 || Double.IsNaN(period) || Double.IsInfinity(period))
            {
                return(null);
            }

            double incr = period / 360.0;

            OrbitalElements.OrbitalElementsPieces defaultOrbitalElements = null;

            //if we want an elliptic orbit from the current planet's position (i.e. the ellipse from which the velocity was computed with vis-viva), setup fake orbital elements from the position
            if (isElliptic)
            {
                defaultOrbitalElements = new OrbitalElements.OrbitalElementsPieces();

                defaultOrbitalElements.baseElements = orbitalElements.calculateElements(startTime, null);

                defaultOrbitalElements.day = new OrbitalElements.OrbitalElementsPieces {
                    M = 1
                };
                defaultOrbitalElements.baseElements.a /= 1000;
                defaultOrbitalElements.baseElements.i /= SO.DEG_TO_RAD;
                defaultOrbitalElements.baseElements.o /= SO.DEG_TO_RAD;
                defaultOrbitalElements.baseElements.w /= SO.DEG_TO_RAD;
                defaultOrbitalElements.baseElements.M /= SO.DEG_TO_RAD;
                //incr = SO.DAY;
                startTime = 0;
            }

            //Debug.Log(name + " " + incr);
            double   total     = 0.0;
            Vector3d?lastPoint = null;

            for (int i = 0; total < 360; i++)
            {
                OrbitalElements.OrbitalElementsPieces computed = orbitalElements.calculateElements(startTime + (incr * i), defaultOrbitalElements);
                //if(this.name=='moon')console.log(startTime+(incr*i));
                Vector3d point = orbitalElements.getPositionFromElements(computed);
                if (lastPoint.HasValue)
                {
                    angle = Vector3d.Angle(point, lastPoint.Value);
                    //make sure we do not go over 360.5
                    if (angle > 1.3 || ((angle + total) > 360.5))
                    {
                        for (int j = 0; j < angle; j++)
                        {
                            double step = (incr * (i - 1)) + ((incr / angle) * j);
                            computed = orbitalElements.calculateElements(startTime + step, defaultOrbitalElements);
                            point    = orbitalElements.getPositionFromElements(computed);
                            //when finishing the circle try to avoid going too far over 360 (break after first point going over 360)
                            if (total > 358)
                            {
                                double angleToPrevious = Vector3d.Angle(point, points[points.Count - 1]);
                                if ((angleToPrevious + total) > 360)
                                {
                                    points.Add(point);
                                    break;
                                }
                            }

                            points.Add(point);
                        }
                        total    += Vector3d.Angle(point, lastPoint.Value);
                        lastPoint = point;
                        continue;
                    }
                    total += angle;
                }
                points.Add(point);
                lastPoint = point;
            }
            return(points);
        }
コード例 #30
0
 //    旋转
 public static void rotate(this Entity entity, Point3d center, double angle, Vector3d?axis = null)
 {
     entity.TransformBy(Matrix3d.Rotation(angle, axis ?? Vector3d.ZAxis, center));
 }