Esempio n. 1
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <remarks>
        /// <para>
        /// A 'no result' object will be created if the <paramref name="polyMesh"/> parameter
        /// is null or has a polygon count of zero.
        /// </para>
        /// </remarks>
        /// <param name="tx">The x-index of the tile within the tile grid. (tx, tz)</param>
        /// <param name="tz">The z-index of the tile within the tile grid. (tx, tz)</param>
        /// <param name="polyMesh">The polymesh.</param>
        /// <param name="detailMesh">The detail mesh.</param>
        /// <param name="heightfield">The heightfield.</param>
        /// <param name="compactField">The compact field.</param>
        /// <param name="contours">The contour set.</param>
        public NMGenAssets(int tx, int tz
                           , PolyMesh polyMesh
                           , PolyMeshDetail detailMesh
                           , Heightfield heightfield
                           , CompactHeightfield compactField
                           , ContourSet contours)
        {
            mTileX = tx;
            mTileZ = tz;

            if (polyMesh == null || polyMesh.PolyCount == 0)
            {
                mPolyMesh     = null;
                mDetailMesh   = null;
                mHeightfield  = null;
                mCompactField = null;
                mContours     = null;
            }
            else
            {
                mPolyMesh     = polyMesh;
                mDetailMesh   = detailMesh; // OK to be null.
                mHeightfield  = heightfield;
                mCompactField = compactField;
                mContours     = contours;
            }
        }
Esempio n. 2
0
        static PolyMesh MakeDoubleSided(PolyMesh mesh)
        {
            // duplicate indices to backside
            var via = mesh.VertexIndexArray;
            var fia = mesh.FirstIndexArray;

            var viaDouble = new int[via.Length * 2].SetByIndex(via.Length, i => via[i]);
            var fiaDouble = new int[fia.Length * 2 - 1].SetByIndex(fia.Length, i => fia[i]);

            for (int fi = 0; fi < mesh.FaceCount; fi++)
            {
                int fvs = fia[fi];
                int fve = fia[fi + 1];

                // end of current face
                fiaDouble[fia.Length + fi] = via.Length + fve;

                for (int fvi = fvs; fvi < fve; fvi++)
                {
                    int revInd = fve - (fvi - fvs) - 1; // reverse index order
                    viaDouble[via.Length + fvi] = via[revInd];
                }
            }

            // create new mesh with just positions and double-sided face indices
            return new PolyMesh()
            {
                PositionArray = mesh.PositionArray,
                VertexIndexArray = viaDouble,
                FirstIndexArray = fiaDouble,
            };
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes non-serialized internal cache in the component.
        /// Should be called after instantiation.
        /// Use <see cref="isInitialized"/> to check if it has already been initialized.
        /// </summary>
        internal void Initialize()
        {
            if (isInitialized)
            {
                return;
            }

            if (!m_ComponentsCache.IsValid())
            {
                m_ComponentsCache = new MeshComponentsCache(gameObject);
            }

            if (m_PolyMesh == null)
            {
                m_PolyMesh = new PolyMesh();
            }

            Mesh mesh = null;

            if (m_ComponentsCache.MeshFilter != null)
            {
                mesh = m_ComponentsCache.MeshFilter.sharedMesh;
            }
            else if (m_ComponentsCache.SkinnedMeshRenderer != null)
            {
                mesh = m_ComponentsCache.SkinnedMeshRenderer.sharedMesh;
            }

            if (!polyMesh.IsValid() && mesh)
            {
                SetMesh(mesh);
            }

            m_Initialized = true;
        }
Esempio n. 4
0
        /// <summary>
        /// Split edge in half
        /// </summary>
        /// <param name="m">Polymesh</param>
        /// <param name="eh">Edge Handle</param>
        /// <returns>New Half-edge Handle for the new Edge</returns>
        public static int SplitEdge(PolyMesh m, int eh)
        {
            int heh     = m.GetHalfedgeEdgeH(eh, 0);
            int opp_heh = m.GetHalfedgeEdgeH(eh, 1);

            int new_heh, opp_new_heh, t_heh;
            int vh, vh1 = m.GetEndVertexH(heh);

            Vector3 midP = m.GetPoint(vh1);

            midP += m.GetPoint(m.GetEndVertexH(opp_heh));
            midP *= 0.5f;

            // new vertex
            vh = m.AddVertex(midP);

            // Re-link mesh entities
            if (m.IsBoundaryEdge(eh))
            {
                for (t_heh = heh;
                     m.GetNextHalfedgeH(t_heh) != opp_heh;
                     t_heh = m.GetOppositeHalfedgeH(m.GetNextHalfedgeH(t_heh)))
                {
                }
            }
            else
            {
                for (t_heh = m.GetNextHalfedgeH(opp_heh);
                     m.GetNextHalfedgeH(t_heh) != opp_heh;
                     t_heh = m.GetNextHalfedgeH(t_heh))
                {
                }
            }

            new_heh     = m.NewEdge(vh, vh1);
            opp_new_heh = m.GetOppositeHalfedgeH(new_heh);
            m.SetVertexH(heh, vh);

            m.SetNextHalfedgeH(t_heh, opp_new_heh);
            m.SetNextHalfedgeH(new_heh, m.GetNextHalfedgeH(heh));
            m.SetNextHalfedgeH(heh, new_heh);
            m.SetNextHalfedgeH(opp_new_heh, opp_heh);

            if (m.GetFaceH(opp_heh).isValidHandle())
            {
                m.SetFaceH(opp_new_heh, m.GetFaceH(opp_heh));
                m.SetHalfedgeFaceH(m.GetFaceH(opp_new_heh), opp_new_heh);
            }

            m.SetFaceH(new_heh, m.GetFaceH(heh));
            m.SetHalfedgeVertexH(vh, new_heh);
            m.SetHalfedgeFaceH(m.GetFaceH(heh), heh);
            m.SetHalfedgeVertexH(vh1, opp_new_heh);

            // Never forget this, when playing with the topology
            m.AdjustOutgoingHalfedge(vh);
            m.AdjustOutgoingHalfedge(vh1);

            return(new_heh);
        }
Esempio n. 5
0
        /// <summary>
        /// Provide the object whose mesh representation you'd like to modify. You will
        /// receive a PolyMesh object, position indices into that PolyMesh, and polygon
        /// indices into that PolyMesh; these indices are the polygon mesh data associated
        /// with the keyed object.
        ///
        /// Valid modifications currently only _ADD_ positions or polygons to the PolyMesh.
        /// You must at least re-use all of the existing positions and polygons for the
        /// keyed object (you can modify the values at the existing indices), but you can
        /// also add new positions and new polygons as long as you report them in using the
        /// callback Action.
        ///
        /// When you are finished modifying the PolyMesh, call the provided Action, which
        /// will update the Unity mesh representation of the PolyMesh, and allow future
        /// modifications. You must also provide the indices of any additional positions or
        /// polygons you added to the PolyMesh as keyed by the key object.
        /// (Hint: PolyMesh modification methods can pass back the added indices of any new
        /// positions or polygons.)
        /// </summary>
        public void ModifyDataFor(object key,
                                  out PolyMesh polyMesh,
                                  List <int> keyedPositionIndices,
                                  List <int> keyedPolygonIndices,
                                  out NotifyPolyMeshModifiedAction
                                  callWhenDoneModifyingPolyMesh)
        {
            if (_modificationPending)
            {
                throw new InvalidOperationException(
                          "A PolyMesh modification is already in progress for this LivePolyMeshObject. "
                          + "(Did you forget to call the Action when the modification was finished?)");
            }

            callWhenDoneModifyingPolyMesh = _notifyPolyMeshModifiedAction;
            polyMesh = this.polyMesh;

            PolygonData polyData;

            if (!objectPolygonData.TryGetValue(key, out polyData))
            {
                throw new InvalidOperationException(
                          "No polygon data was found for key: " + key.ToString() + "; "
                          + "Did you add data for this key first?");
            }

            keyedPositionIndices.AddRange(polyData.a);
            keyedPolygonIndices.AddRange(polyData.b);
        }
Esempio n. 6
0
        private void Start()
        {
            _meshFilter.mesh      = new Mesh();
            _meshFilter.mesh.name = "Subtracted Dodecahedron";

            _polyMesh = new PolyMesh();
        }
Esempio n. 7
0
        public static PolyMesh CreatePolyMesh(int numVerts)
        {
            var mesh = new PolyMesh();

            FillPolyMesh(numVerts, mesh);
            return(mesh);
        }
Esempio n. 8
0
        public static void FillPolyMesh(int numVerts, PolyMesh mesh)
        {
            numVerts = Mathf.Max(numVerts, 3);

            var positions = Pool <List <Vector3> > .Spawn();

            positions.Clear();
            try {
                Quaternion rot    = Quaternion.AngleAxis(360f / numVerts, -Vector3.forward);
                Vector3    radial = Vector3.right;
                positions.Add(radial);
                for (int i = 1; i < numVerts; i++)
                {
                    radial = rot * radial;
                    positions.Add(radial);
                }

                var indices = Values.Range(0, numVerts);
                var polygon = new Polygon()
                {
                    mesh = mesh, verts = indices.ToList()
                };

                mesh.Fill(positions, polygon);
            }
            finally {
                positions.Clear();
                Pool <List <Vector3> > .Recycle(positions);
            }
        }
Esempio n. 9
0
        public NavMeshBuilder GenerateNavmesh(BBox3 bbox)
        {
            float[]  vertices;
            int[]    indices;
            AreaId[] areas;
            GetRawData(out vertices, out indices, out areas);
            var settings = WoWSettings;

            var hf = new Heightfield(bbox, settings);

            hf.RasterizeTrianglesWithAreas(vertices, areas);
            hf.FilterLedgeSpans(settings.VoxelAgentHeight, settings.VoxelMaxClimb);
            hf.FilterLowHangingWalkableObstacles(settings.VoxelMaxClimb);
            hf.FilterWalkableLowHeightSpans(settings.VoxelAgentHeight);

            var chf = new CompactHeightfield(hf, settings);

            chf.Erode(settings.VoxelAgentWidth);
            chf.BuildDistanceField();
            chf.BuildRegions((int)(settings.AgentWidth / settings.CellSize) + 8, settings.MinRegionSize, settings.MergedRegionSize);

            var cset  = new ContourSet(chf, settings);
            var pmesh = new PolyMesh(cset, settings);
            var dmesh = new PolyMeshDetail(pmesh, chf, settings);

            var buildData = new NavMeshBuilder(pmesh, dmesh, new SharpNav.Pathfinding.OffMeshConnection[0], settings);

            return(buildData);
        }
Esempio n. 10
0
 static void CreateSquare(PolyMesh polyMesh, float size)
 {
     polyMesh.keyPoints.AddRange(new Vector3[] { new Vector3(size, size), new Vector3(size, -size), new Vector3(-size, -size), new Vector3(-size, size) });
     polyMesh.curvePoints.AddRange(new Vector3[] { Vector3.zero, Vector3.zero, Vector3.zero, Vector3.zero });
     polyMesh.isCurve.AddRange(new bool[] { false, false, false, false });
     polyMesh.BuildMesh();
 }
Esempio n. 11
0
        public void TestDoubleSidedPrimitive()
        {
            //var mesh = PolyMeshPrimitives.Sphere(50, 1, C4b.White);

            var simple = new PolyMesh()
            {
                PositionArray = new[]
                {
                    new V3d(0, 0, 0),
                    new V3d(2, 0, 0),
                    new V3d(1, 1, 0),
                    new V3d(1, 2, 0),
                },
                FirstIndexArray = new[] { 0, 3, 6, 9 },
                VertexIndexArray = new[]
                {
                    0, 1, 2,
                    1, 3, 2,
                    0, 2, 3
                }
            };

            var dd = MakeDoubleSided(simple);

            dd = dd.WithPerVertexIndexedNormals(30 * Constant.RadiansPerDegree);

            var faceNormals = (V3d[])dd.FaceAttributes[PolyMesh.Property.Normals];
            var creaseNormals = (V3d[])dd.FaceVertexAttributes[-PolyMesh.Property.Normals];
            var creaseNormalIndices = (int[])dd.FaceVertexAttributes[PolyMesh.Property.Normals];

            Assert.IsTrue(creaseNormals.Length == 8);
        }
Esempio n. 12
0
        /// <summary>
        /// Generates a <see cref="NavMesh"/> given a collection of triangles and some settings.
        /// </summary>
        /// <param name="triangles">The triangles that form the level.</param>
        /// <param name="settings">The settings to generate with.</param>
        /// <returns>A <see cref="NavMesh"/>.</returns>
        public static NavMesh Generate(IEnumerable <Triangle3> triangles, NavMeshGenerationSettings settings)
        {
            BBox3 bounds = triangles.GetBoundingBox(settings.CellSize);
            var   hf     = new Heightfield(bounds, settings);

            hf.RasterizeTriangles(triangles);
            hf.FilterLedgeSpans(settings.VoxelAgentHeight, settings.VoxelMaxClimb);
            hf.FilterLowHangingWalkableObstacles(settings.VoxelMaxClimb);
            hf.FilterWalkableLowHeightSpans(settings.VoxelAgentHeight);

            var chf = new CompactHeightfield(hf, settings);

            chf.Erode(settings.VoxelAgentRadius);
            chf.BuildDistanceField();
            chf.BuildRegions(2, settings.MinRegionSize, settings.MergedRegionSize);

            var cont = chf.BuildContourSet(settings);

            var polyMesh = new PolyMesh(cont, settings);

            var polyMeshDetail = new PolyMeshDetail(polyMesh, chf, settings);

            var buildData = new NavMeshBuilder(polyMesh, polyMeshDetail, new Pathfinding.OffMeshConnection[0], settings);

            var navMesh = new NavMesh(buildData);

            return(navMesh);
        }
Esempio n. 13
0
 public void InitMesh()
 {
     if (polyMesh == null)
     {
         polyMesh = new PolyMesh(this.transform);
     }
     Dodecahedron.FillPolyMesh(polyMesh);
 }
Esempio n. 14
0
        public static PolyMesh CreatePolyMesh()
        {
            var mesh = new PolyMesh();

            FillPolyMesh(mesh);

            return(mesh);
        }
        public Car create(PolyMesh carMesh)
        {
            Car c = new Car();

            c.mesh = carMesh;
            car_list.Add(c);
            return(c);
        }
Esempio n. 16
0
        private void Start()
        {
            MeshFilter   = GetComponent <MeshFilter>();
            MeshRenderer = GetComponent <MeshRenderer>();

            Mesh = PolyMesh.LoadMesh(System.IO.Path.Combine(Application.streamingAssetsPath, "Character", FileName));
            GenerateMesh();
        }
        internal override void DrawGizmos(BrushTarget target, BrushSettings settings)
        {
            PolyMesh mesh = target.editableObject.editMesh;

            if (Util.IsValid(target) && m_PaintMode == PaintMode.Fill)
            {
                Vector3[] vertices = mesh.vertices;
                int[]     indices  = mesh.GetTriangles();

                using (new Handles.DrawingScope(target.transform.localToWorldMatrix))
                {
                    int index = 0;

                    var data = m_EditableObjectsData[target.editableObject];
                    foreach (PolyRaycastHit hit in target.raycastHits)
                    {
                        if (hit.triangle > -1)
                        {
                            Handles.color = Color.green;

                            index = hit.triangle * 3;

                            Handles.DrawLine(vertices[indices[index + 0]] + hit.normal * .1f, vertices[indices[index + 1]] + hit.normal * .1f);
                            Handles.DrawLine(vertices[indices[index + 1]] + hit.normal * .1f, vertices[indices[index + 2]] + hit.normal * .1f);
                            Handles.DrawLine(vertices[indices[index + 2]] + hit.normal * .1f, vertices[indices[index + 0]] + hit.normal * .1f);

                            m_FillModeEdges[0].x = indices[index + 0];
                            m_FillModeEdges[0].y = indices[index + 1];

                            m_FillModeEdges[1].x = indices[index + 1];
                            m_FillModeEdges[1].y = indices[index + 2];

                            m_FillModeEdges[2].x = indices[index + 2];
                            m_FillModeEdges[2].y = indices[index + 0];

                            for (int i = 0; i < 3; i++)
                            {
                                if (data.TriangleLookup.TryGetValue(m_FillModeEdges[i], out m_FillModeAdjacentTriangles))
                                {
                                    for (int n = 0; n < m_FillModeAdjacentTriangles.Count; n++)
                                    {
                                        index = m_FillModeAdjacentTriangles[n] * 3;

                                        Handles.DrawLine(vertices[indices[index + 0]] + hit.normal * .1f, vertices[indices[index + 1]] + hit.normal * .1f);
                                        Handles.DrawLine(vertices[indices[index + 1]] + hit.normal * .1f, vertices[indices[index + 2]] + hit.normal * .1f);
                                        Handles.DrawLine(vertices[indices[index + 2]] + hit.normal * .1f, vertices[indices[index + 0]] + hit.normal * .1f);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                base.DrawGizmos(target, settings);
            }
        }
Esempio n. 18
0
 /// <summary>
 /// Sets the context as having produced no result.
 /// </summary>
 public void SetAsNoResult()
 {
     mHeightfield  = null;
     mCompactField = null;
     mContours     = null;
     mPolyMesh     = null;
     mDetailMesh   = null;
     mNoResult     = true;
 }
Esempio n. 19
0
        private static void PostProcess(GameObject go)
        {
            PolyMesh polymesh = go.GetComponent <PolyMesh>();

            if (polymesh != null)
            {
                polymesh.BuildMesh();
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Split the face with Corner Cutting
        /// </summary>
        /// <param name="m">Polymesh</param>
        /// <param name="heh">Half-edge for the Face</param>
        /// <returns>New Face Handle</returns>
        public static int CornerCutting(PolyMesh m, int heh)
        {
            int heh1 = heh,
                heh5 = heh1,
                heh6 = m.GetNextHalfedgeH(heh1);

            // Cycle around the polygon to find correct Halfedge
            for (; m.GetNextHalfedgeH(m.GetNextHalfedgeH(heh5)) != heh1;
                 heh5 = m.GetNextHalfedgeH(heh5))
            {
            }

            int vh1 = m.GetEndVertexH(heh1),
                vh2 = m.GetEndVertexH(heh5);

            int heh2 = m.GetNextHalfedgeH(heh5),
                heh3 = m.NewEdge(vh1, vh2),
                heh4 = m.GetOppositeHalfedgeH(heh3);

            /* Intermediate result
             *
             *            *
             *         5 /|\
             *          /_  \
             *    vh2> *     *
             *        /|\3   |\
             *     2 /_  \|4   \
             *      *----\*----\*
             *          1 ^   6
             *            vh1 (adjust_outgoing half - edge!)
             */

            // Old and new Face
            int fh_old = m.GetFaceH(heh6);
            int fh_new = m.NewFace();

            // Re-Set Handles around old Face
            m.SetNextHalfedgeH(heh4, heh6);
            m.SetNextHalfedgeH(heh5, heh4);

            m.SetFaceH(heh4, fh_old);
            m.SetFaceH(heh5, fh_old);
            m.SetFaceH(heh6, fh_old);
            m.SetHalfedgeFaceH(fh_old, heh4);

            // Re-Set Handles around new Face
            m.SetNextHalfedgeH(heh1, heh3);
            m.SetNextHalfedgeH(heh3, heh2);

            m.SetFaceH(heh1, fh_new);
            m.SetFaceH(heh2, fh_new);
            m.SetFaceH(heh3, fh_new);

            m.SetHalfedgeFaceH(fh_new, heh1);
            return(fh_new);
        }
Esempio n. 21
0
        /// <summary>
        /// Process the build context.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The flags will be applied during the <see cref="NMGenState.PolyMeshBuild"/>
        /// state.
        /// </para>
        /// </remarks>
        /// <param name="state">The current build state.</param>
        /// <param name="context">The context to process.</param>
        /// <returns>False on error, otherwise true.</returns>
        public override bool ProcessBuild(NMGenContext context, NMGenState state)
        {
            if (state != NMGenState.PolyMeshBuild)
            {
                return(true);
            }

            PolyMesh     mesh = context.PolyMesh;
            PolyMeshData data = mesh.GetData(false);

            if (data.polyCount == 0)
            {
                return(true);
            }

            bool applied = false;

            for (int i = 0; i < mAreas.Length; i++)
            {
                byte   area  = mAreas[i];
                ushort flags = mFlags[i];

                int marked = 0;

                for (int iPoly = 0; iPoly < data.polyCount; iPoly++)
                {
                    if (data.areas[iPoly] == area)
                    {
                        data.flags[iPoly] |= flags;
                        marked++;
                    }
                }

                if (marked > 0)
                {
                    string msg = string.Format(
                        "{0} : Added '0x{1:X}' flag(s) to {2} poylgons assigned to area {3}."
                        , Name, flags, marked, area);

                    context.Log(msg, this);

                    applied = true;
                }
            }

            if (applied)
            {
                mesh.Load(data);
            }
            else
            {
                context.Log(Name + ": No flags applied.", this);
            }

            return(true);
        }
Esempio n. 22
0
        public void FillBoundaryTreeNode()
        {
            PolyMesh      mesh       = new PolyMesh(currentMeshFileName);
            List <string> patchNames = mesh.GetAllPatchNames();

            treeNode_boundary.Nodes.Clear();
            foreach (string patchName in patchNames)
            {
                treeNode_boundary.Nodes.Add(patchName, patchName, 2);
            }
        }
Esempio n. 23
0
 public QuickHull(IEnumerable <Point3d> Points)
 {
     this._mesh          = null;
     this._faceplanes    = new List <Plane>();
     this._facedenoms    = new List <double>();
     this._faceequations = new List <double[]>();
     this._removed       = 0;
     this.rnd            = new Random(123);
     this.Mesh           = new PolyMesh();
     this.Mesh.Vertices.AddRange(Points);
     this._used = new bool[checked (checked (Points.Count <Point3d>() - 1) + 1)];
 }
 static void ValidateNormals(PolyMesh mesh)
 {
     mesh.Faces.ForEach(f =>
     {
         var fn = f.Polygon3d.ComputeNormal();
         for (int i = 0; i < f.VertexCount; i++)
         {
             // check if face vertex normal points in similar direction
             var fvn = f.GetVertexAttribute <V3d>(PolyMesh.Property.Normals, 0);
             Assert.True(fvn.Dot(fn) > 0);
         }
     });
 }
        public void TestSubPolygon()
        {
            var meshPoints = new[]
            {
                new V3d(5719.47607421875, 10842.48046875, 269.109008789063),
                new V3d(5719.47607421875, 10600.814453125, 269.109008789063),
                new V3d(5719.623046875, 10603.544921875, 271.355010986328),
                new V3d(5719.8662109375, 10608.0615234375, 275.071990966797),
                new V3d(5720.8759765625, 10634.0517578125, 290.489990234375),
                new V3d(5721.4921875, 10657.4775390625, 299.914001464844),
                new V3d(5721.494140625, 10657.50390625, 299.924011230469),
                new V3d(5721.494140625, 10603.6572265625, 299.924011230469),
                new V3d(5721.4921875, 10603.63671875, 299.912994384766),
                new V3d(5721.13623046875, 10594.4521484375, 294.463989257813),
                new V3d(5719.72802734375, 10568.3193359375, 272.963989257813),
                new V3d(5719.47607421875, 10564.873046875, 269.109008789063),
                new V3d(5719.47607421875, 10554.31640625, 269.109008789063),
                new V3d(5721.4921875, 10581.8486328125, 299.912994384766),
                new V3d(5721.494140625, 10581.859375, 299.924011230469),
                new V3d(5721.494140625, 10550.1767578125, 299.924011230469),
                new V3d(5719.51806640625, 10523.21484375, 269.760009765625),
                new V3d(5719.47607421875, 10522.423828125, 269.109008789063),
                new V3d(5719.47607421875, 10498.8857421875, 269.109008789063),
                new V3d(5719.93408203125, 10510.69140625, 276.111999511719),
                new V3d(5721.4912109375, 10539.62109375, 299.911987304688),
                new V3d(5721.4921875, 10581.8486328125, 299.912994384766),
                new V3d(5721.4921875, 10603.63671875, 299.912994384766),
                new V3d(5721.4921875, 10657.4775390625, 299.914001464844),
                new V3d(5721.4921875, 10785.8115234375, 299.915985107422),
                new V3d(5720.8759765625, 10809.2421875, 290.489990234375),
                new V3d(5719.8662109375, 10835.232421875, 275.071990966797),
                new V3d(5719.623046875, 10839.7490234375, 271.355010986328)
            };

            var mesh = new PolyMesh();

            foreach (var p in meshPoints)
            {
                mesh.AddVertex(p);
            }

            mesh.AddFace(0.UpToExclusive(meshPoints.Length).ToArray());

            var triangleMesh = mesh.TriangulatedCopy();

            // Requirement 1: should not crash

            // Requirement 2: valid polygon / TODO
            Assert.That(triangleMesh.FaceCount > 0);
        }
Esempio n. 26
0
        internal void SetWorkingData(int x, int z, PolyMesh polyMesh, PolyMeshDetail detailMesh)
        {
            int i = GetIndex(x, z);

            if (i == IndexError)
            {
                return;
            }

            unsafeItems[i].SetWorkingData(polyMesh, detailMesh);

            mIsDirty = true;
            unsafeVersion++;
        }
Esempio n. 27
0
        public Edge(PolyMesh mesh, int a, int b, bool literalOrder = false)
        {
            this.mesh = mesh;

            if (!literalOrder)
            {
                if (a > b)
                {
                    Utils.Swap(ref a, ref b);
                }
            }

            _a = a;
            _b = b;
        }
Esempio n. 28
0
        protected override void Initialize(SharpDxGraphicsSystem system)
        {
            this.shader = system.ShaderCache.GetNewOrCachedShader(
                system.Renderer.Device,
                system.Renderer.DeviceContext,
                Resources.LightShaderPath,
                "VS",
                "PS",
                SimpleVertex.VertexInputLayout);

            this.cubeMesh = new PolyMesh(system.Renderer.Device,
                                         cubeVertices,
                                         cubeIndices);

            system.Renderer.AddRenderable(this);
        }
Esempio n. 29
0
        //private void GenerateNavMesh()
        //{
        //    Console.WriteLine("Generating NavMesh");

        //    long prevMs = 0;
        //    try
        //    {
        //        var levelTris = level.GetTriangles();
        //        var triEnumerable = TriangleEnumerable.FromTriangle(levelTris, 0, levelTris.Length);
        //        BBox3 bounds = triEnumerable.GetBoundingBox();

        //        settings = NavMeshGenerationSettings.Default;
        //        heightfield = new Heightfield(bounds, settings);

        //        heightfield.RasterizeTriangles(levelTris, Area.Default);
        //        heightfield.FilterLedgeSpans(settings.VoxelAgentHeight, settings.VoxelMaxClimb);
        //        heightfield.FilterLowHangingWalkableObstacles(settings.VoxelMaxClimb);
        //        heightfield.FilterWalkableLowHeightSpans(settings.VoxelAgentHeight);
        //        compactHeightfield = new CompactHeightfield(heightfield, settings);
        //        compactHeightfield.Erode(settings.VoxelAgentRadius);
        //        compactHeightfield.BuildDistanceField();
        //        compactHeightfield.BuildRegions(0, settings.MinRegionSize, settings.MergedRegionSize);

        //        contourSet = compactHeightfield.BuildContourSet(settings);

        //        polyMesh = new PolyMesh(contourSet, settings);

        //        polyMeshDetail = new PolyMeshDetail(polyMesh, compactHeightfield, settings);


        //        buildData = new NavMeshBuilder(polyMesh, polyMeshDetail, new SharpNav.Pathfinding.OffMeshConnection[0], settings);
        //        tiledNavMesh = new TiledNavMesh(buildData);
        //        navMeshQuery = new NavMeshQuery(tiledNavMesh, 2048);
        //    }
        //    catch (Exception e)
        //    {
        //        //if (!interceptExceptions)
        //        //    throw;
        //        //else
        //        //    Console.WriteLine("Navmesh generation failed with exception:" + Environment.NewLine + e.ToString());
        //    }
        //    finally
        //    {
        //        //sw.Stop();
        //    }
        //}


        private void GenerateNavMesh()
        {
            Console.WriteLine("Generating NavMesh");

            long prevMs = 0;
            //try
            //{
            var   levelTris     = level.GetTriangles();
            var   triEnumerable = TriangleEnumerable.FromTriangle(levelTris, 0, levelTris.Length);
            BBox3 bounds        = triEnumerable.GetBoundingBox();

            settings    = NavMeshGenerationSettings.Default;
            heightfield = new Heightfield(bounds, settings);

            heightfield.RasterizeTriangles(levelTris, Area.Default);
            heightfield.FilterLedgeSpans(settings.VoxelAgentHeight, settings.VoxelMaxClimb);
            heightfield.FilterLowHangingWalkableObstacles(settings.VoxelMaxClimb);
            heightfield.FilterWalkableLowHeightSpans(settings.VoxelAgentHeight);
            compactHeightfield = new CompactHeightfield(heightfield, settings);
            compactHeightfield.Erode(settings.VoxelAgentRadius);
            compactHeightfield.BuildDistanceField();
            compactHeightfield.BuildRegions(0, settings.MinRegionSize, settings.MergedRegionSize);

            contourSet = compactHeightfield.BuildContourSet(settings);

            polyMesh = new PolyMesh(contourSet, settings);

            polyMeshDetail = new PolyMeshDetail(polyMesh, compactHeightfield, settings);


            buildData    = new NavMeshBuilder(polyMesh, polyMeshDetail, new SharpNav.Pathfinding.OffMeshConnection[0], settings);
            tiledNavMesh = new TiledNavMesh(buildData);
            navMeshQuery = new NavMeshQuery(tiledNavMesh, 2048);
            OutMesh();
            //}
            //catch (Exception e)
            //{
            //    //if (!interceptExceptions)
            //    //    throw;
            //    //else
            //    //    Console.WriteLine("Navmesh generation failed with exception:" + Environment.NewLine + e.ToString());
            //}
            //finally
            //{
            //    //sw.Stop();
            //}
        }
        private bool PostPolyMeshCheck()
        {
            PolyMesh polyMesh = mBuildContext.PolyMesh;

            if (polyMesh == null || polyMesh.IsDisposed)
            {
                FinalizeAbort("Custom processors destroyed the poly mesh. (" + mState + " Post)");
                return(false);
            }
            else if (polyMesh.PolyCount < 1)
            {
                FinalizeNoResult(
                    "Aborted after poly mesh build. No polygons generated. (" + mState + " Post)");
                return(false);
            }
            return(true);
        }
Esempio n. 31
0
    private Detour.AtavismNavTile BuildTileMesh(int tx, int ty, RecastVertex min, RecastVertex max)
    {
        Config.Width = Config.TileSize + Config.BorderSize * 2;
        Config.Height = Config.TileSize + Config.BorderSize * 2;
        Config.MinBounds = min;
        Config.MaxBounds = max;
        Config.MinBounds.X -= Config.BorderSize * Config.CellSize;
        Config.MinBounds.Z -= Config.BorderSize * Config.CellSize;

        Config.MaxBounds.X += Config.BorderSize * Config.CellSize;
        Config.MaxBounds.Z += Config.BorderSize * Config.CellSize;

        HeightField heightfield = new HeightField(Config.Width, Config.Height, Config.MinBounds.ToArray(), Config.MaxBounds.ToArray(), Config.CellSize, Config.CellHeight);

        short[] triAreas = new short[Geometry.ChunkyTriMesh.MaxTrisPerChunk];

        float[] tbmin = new float[2], tbmax = new float[2];
        tbmin[0] = Config.MinBounds.X;
        tbmin[1] = Config.MinBounds.Z;

        tbmax[0] = Config.MaxBounds.X;
        tbmax[1] = Config.MaxBounds.Z;

        int[] cid = new int[512];

        int ncid = Geometry.ChunkyTriMesh.GetChunksOverlappingRect(tbmin, tbmax, ref cid, 512);

        if (ncid == 0)
            return null;

        for (int i = 0; i < ncid; i++)
        {
            ChunkyTriMeshNode node = Geometry.ChunkyTriMesh.Nodes[cid[i]];
            int[] tris = new int[node.n * 3];
            Array.Copy(Geometry.ChunkyTriMesh.Tris, node.i * 3, tris, 0, node.n * 3);
            List<int> ctris = new List<int>(tris);
            int nctris = node.n;

            Array.Clear(triAreas, 0, triAreas.Length);
            Geometry.MarkWalkableTriangles(Config.WalkableSlopeAngle, ctris, nctris, ref triAreas);

            heightfield.RasterizeTriangles(Geometry, ctris, nctris, triAreas, Config.WalkableClimb);
        }

        heightfield.FilterLowHangingWalkableObstacles(Config.WalkableClimb);
        heightfield.FilterLedgeSpans(Config.WalkableHeight, Config.WalkableClimb);
        heightfield.FilterWalkableLowHeightSpans(Config.WalkableHeight);

        CompactHeightfield compactHeightfield = new CompactHeightfield(Config.WalkableHeight, Config.WalkableClimb, heightfield);
        compactHeightfield.ErodeWalkableArea(Config.WalkableRadius);

        // optional convex volumes

        compactHeightfield.BuildDistanceField();
        compactHeightfield.BuildRegions(Config.BorderSize, Config.MinRegionArea, Config.MergeRegionArea);

        ContourSet contourSet = new ContourSet(compactHeightfield, Config.MaxSimplificationError, Config.MaxEdgeLength);

        if (contourSet.NConts == 0)
            return null;

        PolyMesh polyMesh = new PolyMesh(contourSet, Config.MaxVertexesPerPoly);

        DetailPolyMesh detailPolyMesh = new DetailPolyMesh(polyMesh, compactHeightfield, Config.DetailSampleDistance,
                                                            Config.DetailSampleMaxError);

        // Convert the Areas and Flags for path weighting
        for (int i = 0; i < polyMesh.NPolys; i++)
        {

            if (polyMesh.Areas[i] == Geometry.WalkableArea)
            {
                polyMesh.Areas[i] = 0; // Sample_polyarea_ground
                polyMesh.Flags[i] = 1; // Samply_polyflags_walk
            }
        }
        NavMeshCreateParams param = new NavMeshCreateParams
        {
            Verts = polyMesh.Verts,
            VertCount = polyMesh.NVerts,
            Polys = polyMesh.Polys,
            PolyAreas = polyMesh.Areas,
            PolyFlags = polyMesh.Flags,
            PolyCount = polyMesh.NPolys,
            Nvp = polyMesh.Nvp,
            DetailMeshes = detailPolyMesh.Meshes,
            DetailVerts = detailPolyMesh.Verts,
            DetailVertsCount = detailPolyMesh.NVerts,
            DetailTris = detailPolyMesh.Tris,
            DetailTriCount = detailPolyMesh.NTris,

            // Off Mesh data
            OffMeshConVerts = Geometry.OffMeshConnectionVerts.ToArray(),
            OffMeshConRad = Geometry.OffMeshConnectionRadii.ToArray(),
            OffMeshConDir = Geometry.OffMeshConnectionDirections.ToArray(),
            OffMeshConAreas = Geometry.OffMeshConnectionAreas.ToArray(),
            OffMeshConFlags = Geometry.OffMeshConnectionFlags.ToArray(),
            OffMeshConUserId = Geometry.OffMeshConnectionIds.ToArray(),
            OffMeshConCount = (int)Geometry.OffMeshConnectionCount,
            // end off mesh data

            WalkableHeight = Config.WalkableHeight,
            WalkableRadius = Config.WalkableRadius,
            WalkableClimb = Config.WalkableClimb,
            BMin = new float[] { polyMesh.BMin[0], polyMesh.BMin[1], polyMesh.BMin[2] },
            BMax = new float[] { polyMesh.BMax[0], polyMesh.BMax[1], polyMesh.BMax[2] },
            Cs = polyMesh.Cs,
            Ch = polyMesh.Ch,
            BuildBvTree = true,
            TileX = tx,
            TileY = ty,
            TileLayer = 0
        };
        return new Detour.AtavismNavTile(param);
    }
Esempio n. 32
0
	static void CreateSquare(PolyMesh polyMesh, float size)
	{
		polyMesh.keyPoints.AddRange(new Vector3[] { new Vector3(size, size), new Vector3(size, -size), new Vector3(-size, -size), new Vector3(-size, size)} );
		polyMesh.curvePoints.AddRange(new Vector3[] { Vector3.zero, Vector3.zero, Vector3.zero, Vector3.zero } );
		polyMesh.isCurve.AddRange(new bool[] { false, false, false, false } );
		polyMesh.BuildMesh();
	}