Exemple #1
0
 /// <summary>
 /// 地形更新处理
 /// </summary>
 public void HandleForUpdateNavMesh()
 {
     if (navMeshIsUpdating)
     {
         if (navMeshUpdateOperation.isDone)
         {
             if (navMeshInstance.valid)
             {
                 NavMesh.RemoveNavMeshData(navMeshInstance);
             }
             navMeshInstance   = NavMesh.AddNavMeshData(navMeshData);
             navMeshIsUpdating = false;
         }
     }
     else if (navMeshHasNewData)
     {
         try
         {
             navMeshUpdateOperation = NavMeshBuilder.UpdateNavMeshDataAsync(navMeshData, navMeshBuildSettings, navMeshSources.Values.ToList(), worldBounds);
             navMeshIsUpdating      = true;
         }
         catch
         {
         }
         navMeshHasNewData = false;
     }
 }
Exemple #2
0
    private void OnEnable()
    {
        terrain                    = GetComponent <Terrain>();
        terrain.terrainData        = GenerateTerrain(terrain.terrainData);
        terrain.transform.position = new Vector3(-config.width / 2, 0, -config.depth / 2);

        List <NavMeshBuildSource> buildSources = new List <NavMeshBuildSource>();

        NavMeshBuilder.CollectSources(
            null,
            ~9, // TODO Custom editor so we can select layers
            NavMeshCollectGeometry.RenderMeshes,
            0,
            new List <NavMeshBuildMarkup>(),
            buildSources
            );

        NavMeshData navData = NavMeshBuilder.BuildNavMeshData(
            NavMesh.GetSettingsByID(0),
            buildSources,
            new Bounds(new Vector3(0, 0, 0), new Vector3(config.width, config.height, config.depth)),
            Vector3.zero,
            Quaternion.identity
            );

        if (navData == null)
        {
            Debug.LogError("Failed to create nav mesh data!");
        }
        else
        {
            navMeshDataInstance = NavMesh.AddNavMeshData(navData);
        }
    }
        public void BuildNavMesh(GameObject[] fromObjects = null)
        {
            RemoveData();

            var sources = new List <NavMeshBuildSource>();
            var markups = new List <NavMeshBuildMarkup>();

            var buildSettings = NavMesh.GetSettingsByID(agentTypeID);

            if (fromObjects == null)
            {
                NavMeshBuilder.CollectSources(null, layerMask, useGeometry, defaultArea, markups, sources);
            }
            else
            {
                foreach (var obj in fromObjects)
                {
                    var localSources = new List <NavMeshBuildSource>();
                    NavMeshBuilder.CollectSources(obj.transform, layerMask, useGeometry, defaultArea, markups, localSources);
                    sources.AddRange(localSources);
                }
            }

            var bounds = CalculateWorldBounds(transform, sources);

            navMeshData = NavMeshBuilder.BuildNavMeshData(buildSettings, sources, bounds, Vector3.zero, Quaternion.identity);

            AddData();
        }
Exemple #4
0
    // Use this for initialization
    void Start()
    {
        //wall = GameObject.FindGameObjectWithTag("Base_Wall");
        floor = new GameObject("Floor");
        if (file != null)
        {
            Debug.Log("JSON file exists.");
            myJSON = JSONNode.Parse(file.text);
        }
        else
        {
            Debug.Log("JSON file is not existing.");
        }

        Debug.Log(myJSON.Count);
        Debug.Log(myJSON.AsObject.GetKeys().Count);

        ArrayList roomNames = myJSON.AsObject.GetKeys();

        for (int i = 0; i < myJSON.Count; i++)
        {
            //string name = (string)roomNames[i];
            Debug.Log("Creating " + i + "th Room.");
            createRoomFromJSON(myJSON[i],
                               (string)roomNames[i]);
        }
#if UNITY_EDITOR
        NavMeshBuilder.BuildNavMesh();
#endif
    }
Exemple #5
0
    public void RebuildNavmesh(bool async)
    {
        if (async && buildOperation != null && !buildOperation.isDone)
        {
            return;
        }

        buildOperation = null;

        var totalBounds = new Bounds();

        NavMeshSourceTag2D.Collect(ref buildSources, ref totalBounds);
        var buildSettings       = NavMesh.GetSettingsByID(0);
        var totalBoundsReversed = new Bounds(Plane2DRotationInverse * totalBounds.center, Plane2DRotationInverse * totalBounds.size); // We need to reverse the rotation that's going to be used for baking to get proper bounds
        var buildBounds         = new Bounds(Vector3.zero, Vector3.one * float.MaxValue);                                             //Using enclosing and empty bounds is bugged at the moment - use arbitrarily big one

        if (!data)
        {
            data = NavMeshBuilder.BuildNavMeshData(buildSettings, buildSources, buildBounds, totalBounds.center, Plane2DRotation);
        }
        else
        {
            if (async)
            {
                buildOperation = NavMeshBuilder.UpdateNavMeshDataAsync(data, buildSettings, buildSources, buildBounds);
            }
            else
            {
                NavMeshBuilder.UpdateNavMeshData(data, buildSettings, buildSources, buildBounds);
            }
        }

        dataInstance.Remove();
        dataInstance = NavMesh.AddNavMeshData(data);
    }
    // Use this for initialization
    void Start()
    {
        Debug.Log("Editor mode");
        //Get all GameObjects with tag "Wall"
        if (Wall == null)
        {
            Wall = GameObject.FindGameObjectsWithTag("Wall");
        }
        if (Door == null)
        {
            Door = GameObject.FindGameObjectsWithTag("Door");
        }

        plane = GameObject.CreatePrimitive(PrimitiveType.Plane);           //The plane(GameObject) that will cloned

        // Instantiate planes at base of all walls and doors in map/scene
        foreach (GameObject w in Wall)
        {
            instantiateFloorPlanes(w);
        }
        foreach (GameObject d in Door)
        {
            createDoorPlanes(d);
        }

        NavMeshBuilder.BuildNavMesh();                                  // BAKE THE NAVMESH
    }
Exemple #7
0
    private void BakeBoxColliders()
    {
        CleanUpOldNavMeshItems();
        BoxCollider[] allBoxColliders   = GameObject.FindObjectsOfType <BoxCollider>();
        GameObject    navMeshCubePrefab = GameObject.CreatePrimitive(PrimitiveType.Cube);

        DestroyImmediate(navMeshCubePrefab.GetComponent <Collider>());
        navMeshCubePrefab.name = TEMP_NAV_MESH_OBJECT_TAG;
        GameObjectUtility.SetStaticEditorFlags(navMeshCubePrefab, StaticEditorFlags.NavigationStatic);
        navMeshCubePrefab.tag = TEMP_NAV_MESH_OBJECT_TAG;

        GameObject tempNavMeshCube;

        foreach (BoxCollider c in allBoxColliders)
        {
            if (COLLIDER_LAYER < 0 || c.gameObject.layer == COLLIDER_LAYER)
            {
                tempNavMeshCube                         = Instantiate(navMeshCubePrefab) as GameObject;
                tempNavMeshCube.name                    = navMeshCubePrefab.name;
                tempNavMeshCube.transform.parent        = c.transform;
                tempNavMeshCube.transform.localPosition = c.center;
                tempNavMeshCube.transform.localRotation = Quaternion.identity;
                tempNavMeshCube.transform.localScale    = c.size;
                tempNavMeshCube.hideFlags               = HideFlags.DontSave;
            }
        }
        DestroyImmediate(navMeshCubePrefab);
        NavMeshBuilder.BuildNavMeshAsync();
        CleanUpOldNavMeshItems();
    }
Exemple #8
0
 private void Bake()
 {
     if (RefreshPreviewMesh())
     {
         NavMeshBuilder.BuildNavMesh();
     }
 }
Exemple #9
0
    protected override void OnUpdate()
    {
        var commandBuffer = new EntityCommandBuffer(Allocator.TempJob);
        var chunks        = hybridQuery.CreateArchetypeChunkArray(Allocator.TempJob);

        var entityType       = GetArchetypeChunkEntityType();
        var translationType  = GetArchetypeChunkComponentType <Translation>(true);
        var matrixType       = GetArchetypeChunkComponentType <CellSystem.MatrixComponent>(true);
        var localToWorldType = GetArchetypeChunkComponentType <LocalToWorld>(true);
        var meshType         = GetArchetypeChunkSharedComponentType <RenderMesh>();

        for (int c = 0; c < chunks.Length; c++)
        {
            var chunk = chunks[c];

            var entities               = chunk.GetNativeArray(entityType);
            var translations           = chunk.GetNativeArray(translationType);
            var matrixComponents       = chunk.GetNativeArray(matrixType);
            var localToWorldComponents = chunk.GetNativeArray(localToWorldType);

            for (int e = 0; e < entities.Length; e++)
            {
                Entity entity   = entities[e];
                float3 position = translations[e].Value;
                CellSystem.MatrixComponent matrix = matrixComponents[e];
                float4x4 localToWorld             = localToWorldComponents[e].Value;
                Mesh     mesh = chunk.GetSharedComponentData <RenderMesh>(meshType, entityManager).mesh;

                GameObject sectorGameObject = GameObject.Instantiate(sectorPrefab, position, Quaternion.identity);
                sectorGameObject.GetComponent <MeshCollider>().sharedMesh = mesh;
                NavMeshSurface navMeshComponent = sectorGameObject.GetComponent <NavMeshSurface>();

                NavMeshBuildSettings      settings = NavMesh.GetSettingsByID(0);
                List <NavMeshBuildSource> sources  = CreateNavMeshSource(matrix.width, navMeshComponent, mesh, localToWorld);
                Bounds      bounds = CalculateWorldBounds(sources, position);
                NavMeshData data   = NavMeshBuilder.BuildNavMeshData(settings, sources, bounds, position, Quaternion.identity);

                if (data != null)
                {
                    data.name = sectorGameObject.name;
                    navMeshComponent.RemoveData();
                    navMeshComponent.navMeshData = data;
                    if (navMeshComponent.isActiveAndEnabled)
                    {
                        navMeshComponent.AddData();
                    }
                }

                commandBuffer.AddComponent <Tags.HybridGameObjectCreated>(entity, new Tags.HybridGameObjectCreated());
                commandBuffer.AddSharedComponent <GameObjectComponent>(entity, new GameObjectComponent {
                    gameObject = sectorGameObject
                });
            }
        }

        commandBuffer.Playback(entityManager);
        commandBuffer.Dispose();

        chunks.Dispose();
    }
Exemple #10
0
    public void UpdateNavMeshAsync()
    {
        if (this.HasBuildOperationStarted || AiManager.nav_disable || !ConVar.AI.npc_enable)
        {
            return;
        }
        float realtimeSinceStartup = Time.get_realtimeSinceStartup();

        Debug.Log((object)("Starting Monument Navmesh Build with " + (object)this.sources.Count + " sources"));
        NavMeshBuildSettings settingsByIndex = NavMesh.GetSettingsByIndex(this.NavMeshAgentTypeIndex);

        ((NavMeshBuildSettings) ref settingsByIndex).set_overrideVoxelSize(true);
        ((NavMeshBuildSettings) ref settingsByIndex).set_voxelSize(((NavMeshBuildSettings) ref settingsByIndex).get_voxelSize() * this.NavmeshResolutionModifier);
        this.BuildingOperation = NavMeshBuilder.UpdateNavMeshDataAsync(this.NavMeshData, settingsByIndex, this.sources, this.Bounds);
        this.BuildTimer.Reset();
        this.BuildTimer.Start();
        this.HasBuildOperationStarted = true;
        float num = Time.get_realtimeSinceStartup() - realtimeSinceStartup;

        if ((double)num <= 0.100000001490116)
        {
            return;
        }
        Debug.LogWarning((object)("Calling UpdateNavMesh took " + (object)num));
    }
    void Awake()
    {
        nvData = new NavMeshData();
        foreach (var obj in notWalkable)
        {
            NavMeshBuildMarkup navMeshBuildMarkup = new NavMeshBuildMarkup();
            navMeshBuildMarkup.area         = NavMesh.GetAreaFromName("Not Walkable");
            navMeshBuildMarkup.overrideArea = true;
            navMeshBuildMarkup.root         = obj.transform;
            objectsNotTreated.Add(navMeshBuildMarkup);
        }
        NavMesh.AddNavMeshData(nvData);
        NavMeshBuilder.CollectSources(
            new Bounds(gameObject.transform.position, new Vector3(bounds, bounds, bounds)),
            mask.value,
            NavMeshCollectGeometry.PhysicsColliders,
            0,
            objectsNotTreated,
            watchedSources);

        status = NavMeshBuilder.UpdateNavMeshDataAsync(
            nvData,
            NavMesh.GetSettingsByID(0),
            watchedSources,
            new Bounds(gameObject.transform.position, new Vector3(bounds, bounds, bounds)));
    }
        //------------------------------------------------------------------------------------------------------------------
        void Start()
        {
//#if UNITY_EDITOR
//            UnityEditor.SceneView.FocusWindowIfItsOpen(typeof(UnityEditor.SceneView));
//#endif

            this.m_charProxy = GameObject.Find("GAMEOBJ_CharProxy");
            this.m_mainPath  = "Prefab/_Level_A/";

#if UNITY_EDITOR
            LoadCrossPieces();
            LoadCornerPieces();
            LoadLinePieces();
            LoadDeadEndPieces();
            LoadTriplePieces();
            LoadNonePiece();
            CreateRandomDungeon();
            MoveAllMapLinkedToFirstPiecePivot(0, 0);
            ScrambleTileVersions();
            ModifyTilePatterns();
            PopulatePiecesAtDungeon();
            PlaceAgentAtStartPointInNavmesh();

            NavMeshBuilder.ClearAllNavMeshes();
            NavMeshBuilder.BuildNavMesh();
#endif
        }
Exemple #13
0
        /// <summary>
        /// Bakes the Unity NavMesh on created NavMeshObjects.
        /// </summary>
        public void BakeNavMesh()
        {
            //loop over renderers and enable them for the baking process,
            //as otherwise the NavMeshBuilder will ignore them
            List <Renderer> disabledObjects = new List <Renderer>();

            {
                var __array1       = Object.FindObjectsOfType(typeof(Renderer));
                var __arrayLength1 = __array1.Length;
                for (int __i1 = 0; __i1 < __arrayLength1; ++__i1)
                {
                    var item = (Renderer)__array1[__i1];
                    {
                        if (GameObjectUtility.AreStaticEditorFlagsSet(item.gameObject, StaticEditorFlags.NavigationStatic) &&
                            !item.enabled)
                        {
                            disabledObjects.Add(item);
                            item.renderer.enabled = true;
                        }
                    }
                }
            }
            //trigger navmesh builder
            NavMeshBuilder.BuildNavMesh();
            //re-enable disabled renderers
            disabledObjects.ForEach(obj => obj.enabled = false);

            ShowNotification("NavMesh successfully built.");
        }
Exemple #14
0
    void UpdateNavMesh()
    {
        NavMeshSourceTag.Collect(ref m_Sources, transform);
        NavMeshBuildSettings defaultBuildSettings = NavMesh.GetSettingsByID(0);

        defaultBuildSettings.agentClimb       *= transform.lossyScale.x;
        defaultBuildSettings.agentHeight      *= transform.lossyScale.x;
        defaultBuildSettings.agentRadius      *= transform.lossyScale.x;
        defaultBuildSettings.minRegionArea    *= transform.lossyScale.x;
        defaultBuildSettings.overrideVoxelSize = true;
        defaultBuildSettings.voxelSize         = defaultBuildSettings.agentRadius / 3f;
        Bounds bounds = new Bounds(Vector3.zero, Vector3.Scale(new Vector3(3f, 3f, 3f), transform.lossyScale));

        NavMeshBuilder.UpdateNavMeshData(m_NavMesh, defaultBuildSettings, m_Sources, bounds);

        /*
         * navMeshVis.transform.SetParent(null, false);
         * NavMeshTriangulation triangulation = NavMesh.CalculateTriangulation();
         * Mesh mesh = navMeshVis.mesh;
         * mesh.Clear();
         * mesh.vertices = triangulation.vertices;
         * mesh.triangles = triangulation.indices;
         * mesh.RecalculateNormals();
         */
        for (int i = 0; i < placedInArea.Count; i++)
        {
            if (placedInArea[i].GetComponent <NavMeshSourceTag>() == null)
            {
                placedInArea[i].transform.position = PlacementManager.Instance.GetNavPos(placedInArea[i].transform.position);
                MoveInArea(placedInArea[i]);
            }
        }
    }
#pragma warning restore 0649
        #endregion

        private void Awake()
        {
            Terrain terrain = GetComponent <Terrain> ();

            terrain.terrainData = GenerateTerrain(terrain.terrainData);
            NavMeshBuilder.BuildNavMesh();
        }
Exemple #16
0
        public void BuildNavMesh()
        {
            var sources = CollectSources();

            // Use unscaled bounds - this differs in behaviour from e.g. collider components.
            // But is similar to reflection probe - and since navmesh data has no scaling support - it is the right choice here.
            var sourcesBounds = new Bounds(m_Center, Abs(m_Size));

            if (m_CollectObjects == CollectObjects.All || m_CollectObjects == CollectObjects.Children)
            {
                sourcesBounds = CalculateWorldBounds(sources);
            }

            var data = NavMeshBuilder.BuildNavMeshData(GetBuildSettings(),
                                                       sources, sourcesBounds, transform.position, transform.rotation);

            if (data != null)
            {
                data.name = gameObject.name;
                RemoveData();
                m_NavMeshData = data;
                if (isActiveAndEnabled)
                {
                    AddData();
                }
            }
        }
Exemple #17
0
    public void RebakeMesh()
    {
        area = new Bounds();

        List <NavMeshBuildSource> sources = new List <NavMeshBuildSource>();

        foreach (Transform go in transform)
        {
            var src = new NavMeshBuildSource();
            src.transform    = go.localToWorldMatrix;
            src.shape        = NavMeshBuildSourceShape.Mesh;
            src.sourceObject = go.GetComponent <MeshFilter>().mesh;
            sources.Add(src);

            area.Encapsulate(go.GetComponent <Renderer>().bounds);
        }
        area.Expand(1);

        List <NavMeshBuildSettings> configs = new List <NavMeshBuildSettings>();

        foreach (var agent in settings)
        {
            var s = NavMesh.CreateSettings();
            s.agentClimb  = agent.climbAngle;
            s.agentRadius = agent.radius;
            s.agentSlope  = agent.jump;
            s.agentTypeID = 1;
            configs.Add(s);
        }

        NavMeshBuilder.UpdateNavMeshData(data, configs[0], sources, area);
    }
Exemple #18
0
 void BuildAllNavMesh(float agentRadius)
 {
     map.SetActive(false);
     ClearTmp();
     SetAgentRadius(agentRadius);
     xingzouceng.GetComponent <Renderer>().enabled = true;
     if (feixingceng != null)
     {
         feixingceng.GetComponent <Renderer>().enabled = true;
     }
     if (qinggong != null)
     {
         qinggong.GetComponent <Renderer>().enabled = true;
     }
     NavMeshBuilder.ClearAllNavMeshes();
     NavMeshBuilder.BuildNavMesh();
     xingzouceng.GetComponent <Renderer>().enabled = false;
     if (feixingceng != null)
     {
         feixingceng.GetComponent <Renderer>().enabled = false;
     }
     if (qinggong != null)
     {
         qinggong.GetComponent <Renderer>().enabled = false;
     }
     map.SetActive(true);
 }
Exemple #19
0
    private IEnumerator CollectSourcesAsync(Action callback)
    {
        float time = Time.get_realtimeSinceStartup();

        Debug.Log((object)"Starting Navmesh Source Collecting.");
        NavMeshBuilder.CollectSources(this.Bounds, LayerMask.op_Implicit(this.LayerMask), this.NavMeshCollectGeometry, this.defaultArea, new List <NavMeshBuildMarkup>(), this.sources);
        if (Object.op_Inequality((Object)TerrainMeta.HeightMap, (Object)null))
        {
            for (float x = (float)-((Bounds) ref this.Bounds).get_extents().x; (double)x < ((Bounds) ref this.Bounds).get_extents().x; x += (float)this.CellSize)
            {
                for (float z = (float)-((Bounds) ref this.Bounds).get_extents().z; (double)z < ((Bounds) ref this.Bounds).get_extents().z; z += (float)this.CellSize)
                {
                    AsyncTerrainNavMeshBake terrainSource = new AsyncTerrainNavMeshBake(Vector3.op_Addition(((Bounds) ref this.Bounds).get_center(), new Vector3(x, 0.0f, z)), this.CellSize, this.Height, false, true);
                    yield return((object)terrainSource);

                    this.terrainBakes.Add(terrainSource);
                    NavMeshBuildSource navMeshBuildSource = terrainSource.CreateNavMeshBuildSource(true);
                    ((NavMeshBuildSource) ref navMeshBuildSource).set_area(this.defaultArea);
                    this.sources.Add(navMeshBuildSource);
                    terrainSource = (AsyncTerrainNavMeshBake)null;
                }
            }
        }
        this.AppendModifierVolumes(ref this.sources);
        float num = Time.get_realtimeSinceStartup() - time;

        if ((double)num > 0.100000001490116)
        {
            Debug.LogWarning((object)("Calling CollectSourcesAsync took " + (object)num));
        }
        if (callback != null)
        {
            callback();
        }
    }
Exemple #20
0
    // Use this for initialization
    void Start()
    {
        // add 20 random big cuboids into the level.
        // The prefab has been tagged as StaticBatchingUtility Navigation in The Navigation editor
        for (int i = 0; i < 20; i++)
        {
            GameObject go = Instantiate(prefab, new Vector3(Random.Range(-25, 25), Random.Range(0, 1), Random.Range(-25, 25)), Quaternion.AngleAxis(Random.Range(-180, 180), Vector3.up));
            go.transform.parent = transform;
        }

        // Use the standard settings from the editor (I think)
        NavMeshBuildSettings settings = NavMesh.GetSettingsByID(0);

        // gather all the physics colliders which are children of this transform (or you can do this by volume)
        List <NavMeshBuildSource> results = new List <NavMeshBuildSource>();

        NavMeshBuilder.CollectSources(transform, 255, NavMeshCollectGeometry.PhysicsColliders, 0, new List <NavMeshBuildMarkup>(), results);

        // make a 100m box around the origin
        Bounds bounds = new Bounds(Vector3.zero, 100 * Vector3.one);

        // Build the actual navmesh
        NavMeshData data = NavMeshBuilder.BuildNavMeshData(settings, results, bounds, Vector3.zero, Quaternion.identity);

        NavMesh.AddNavMeshData(data);
        success = NavMeshBuilder.UpdateNavMeshData(data, settings, results, bounds);
    }
Exemple #21
0
    public void UpdateNavMeshAsync()
    {
        if (this.HasBuildOperationStarted)
        {
            return;
        }
        if (AiManager.nav_disable || !AI.npc_enable)
        {
            return;
        }
        float single = UnityEngine.Time.realtimeSinceStartup;

        UnityEngine.Debug.Log(string.Concat("Starting Monument Navmesh Build with ", this.sources.Count, " sources"));
        NavMeshBuildSettings settingsByIndex = NavMesh.GetSettingsByIndex(this.NavMeshAgentTypeIndex);

        settingsByIndex.overrideVoxelSize = true;
        settingsByIndex.voxelSize         = settingsByIndex.voxelSize * this.NavmeshResolutionModifier;
        this.BuildingOperation            = NavMeshBuilder.UpdateNavMeshDataAsync(this.NavMeshData, settingsByIndex, this.sources, this.Bounds);
        this.BuildTimer.Reset();
        this.BuildTimer.Start();
        this.HasBuildOperationStarted = true;
        float single1 = UnityEngine.Time.realtimeSinceStartup - single;

        if (single1 > 0.1f)
        {
            UnityEngine.Debug.LogWarning(string.Concat("Calling UpdateNavMesh took ", single1));
        }
    }
Exemple #22
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);
        }
Exemple #23
0
    private void OnDrawGizmos()
    {
        NavMeshBuilder builder = navMeshBuilder;
        float          radius  = builder ? builder.repeatDistance : 0.1f;
        float          height  = builder ? builder.viewHeight : 0.01f;

        Vector3 vHeight = new Vector3(0, height, 0);

        if (meshFilter.sharedMesh)
        {
            Gizmos.color = color;
            Gizmos.DrawMesh(meshFilter.sharedMesh, vHeight);
        }

        if (vertices.Count > 1)
        {
            Gizmos.color = Color.cyan;

            for (int i = 0; i < vertices.Count - 1; i++)
            {
                Vector3 v1 = vertices[i];
                Vector3 v2 = vertices[i + 1];
                Gizmos.DrawLine(v1, v2);
            }
        }

        for (int i = 0; i < vertices.Count; i++)
        {
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(vertices[i] + vHeight, radius);
        }
    }
Exemple #24
0
    public static void Generate()
    {
        var sources = new List <NavMeshBuildSource>();
        var meshs   = Object.FindObjectsOfType <MeshFilter>();

        foreach (var mesh in meshs)
        {
            if (!mesh.gameObject.isStatic)
            {
                continue;
            }
            var source = new NavMeshBuildSource();
            source.sourceObject = mesh.sharedMesh;
            source.area         = 0;
            source.transform    = mesh.transform.localToWorldMatrix;
            sources.Add(source);
        }
        var navMeshData = new NavMeshData();

        NavMesh.AddNavMeshData(navMeshData);
        var  id     = NavMesh.GetSettingsByID(0);
        var  bounds = new Bounds(Vector3.zero, Vector3.one * 50.0f);
        bool result = NavMeshBuilder.UpdateNavMeshData(navMeshData, id, sources, bounds);

        Debug.Log(result);
        Debug.Log(id.agentRadius);
    }
Exemple #25
0
        public override void Execute()
        {
            Retain();
            NavMeshBuilder.ClearAllNavMeshes();

            NavMeshBuilder.BuildNavMesh();
            Release();
        }
        public IEnumerator UpdateNavMeshData()
        {
            var defaultBuildSettings = NavMesh.GetSettingsByID(0);
            var sources   = navMeshTargets.Select(x => x.NavMeshTargetData.NavMeshBuildSource).ToList();
            var operation = NavMeshBuilder.UpdateNavMeshDataAsync(navMeshData, defaultBuildSettings, sources, QuantizedBounds());

            yield return(operation);
        }
Exemple #27
0
    NavMeshData InitializeBakeData()
    {
        var emptySources = new List <NavMeshBuildSource>();
        var emptyBounds  = new Bounds();

        return(NavMeshBuilder.BuildNavMeshData(navMeshSurface.GetBuildSettings(), emptySources, emptyBounds,
                                               navMeshSurface.transform.position, navMeshSurface.transform.rotation));
    }
Exemple #28
0
        public static bool LoadNavMeshByJsonFile(string filePath, ref NavMesh navMesh)
        {
            navMesh = null;
            if (string.IsNullOrEmpty(filePath))
            {
                return(false);
            }

            if (File.Exists(filePath) == false)
            {
                Console.WriteLine("LoadNavMeshByJsonFile:{0} is not exist", filePath);
                return(false);
            }

            using (FileStream fsRead = new FileStream(filePath, FileMode.Open))
            {
                int    fsLen  = (int)fsRead.Length;
                byte[] heByte = new byte[fsLen];
                fsRead.Read(heByte, 0, heByte.Length);

                string jsonString = System.Text.Encoding.UTF8.GetString(heByte);
                //var ms = new MemoryStream(heByte);
                //JsonMap jsonMap = (JsonMap)new DataContractJsonSerializer(typeof(JsonMap)).ReadObject(ms);

                JsonMap jsonMap = MathUtils.ParseJson <JsonMap>(jsonString);//JsonConvert.DeserializeObject(jsonString, typeof(JsonMap));
                if (jsonMap == null)
                {
                    Console.WriteLine("JsonConvert.DeserializeObject ==> {0} failed", filePath);
                    return(false);
                }

                navMesh = new NavMesh();

                Status status = navMesh.Init(jsonMap.Param);
                if (status != Status.Success)
                {
                    Console.WriteLine("NavMesh init failed");
                    return(false);
                }

                for (int i = 0; i < jsonMap.NavMeshBuilders.Count; i++)
                {
                    NavMeshBuilder builder = jsonMap.NavMeshBuilders[i];
                    if (builder == null)
                    {
                        continue;
                    }
                    long   result = 0;
                    Status ss     = navMesh.AddTile(builder, NavMesh.TileFreeData, 0, ref result);
                    if (ss != Status.Success)
                    {
                        Console.WriteLine("NavMesh AddTile failed! result = {0}", result);
                    }
                }
            }

            return(true);
        }
Exemple #29
0
        static void TestNavmesh(NavMeshBuilder build)
        {
            // Azeroth 28 28 / Deathknell (wow-style coordinates)
            // Outside church: 1843.734 1604.214 94.55994
            // Inside church: 1844.074 1642.581 97.62832
            // Outside spawn: 1672.226 1662.989 139.2343
            // Inside spawn: 1665.264 1678.277 120.5302
            // Outside cave: 2051.3 1807.121 102.5225
            // Inside cave: 2082.813 1950.718 98.04765
            // Outside house: 1861.465 1582.03 92.79533
            // Upstairs house: 1859.929 1560.804 99.07755

            var tmesh = new TiledNavMesh(build);

            var query   = new NavMeshQuery(tmesh, 65536);
            var extents = new Vector3(5f, 5f, 5f);

            var posStart = WoWToSharpNav(new Vector3(1665.2f, 1678.2f, 120.5f)); // Inside spawn
            var posEnd   = WoWToSharpNav(new Vector3(1672.2f, 1662.9f, 139.2f)); // Outside spawn

            NavPoint endPt;

            query.FindNearestPoly(ref posEnd, ref extents, out endPt);

            NavPoint startPt;

            query.FindNearestPoly(ref posStart, ref extents, out startPt);

            var path = new List <int>();

            if (!query.FindPath(ref startPt, ref endPt, path))
            {
                Console.WriteLine("No path!");
            }

            Vector3 actualStart = new Vector3();

            query.ClosestPointOnPoly(startPt.Polygon, startPt.Position, ref actualStart);

            Vector3 actualEnd = new Vector3();

            query.ClosestPointOnPoly(endPt.Polygon, endPt.Position, ref actualEnd);

            var smoothPath = new List <Vector3>();

            Vector3[] straightPath = new Vector3[2048];
            int[]     pathFlags    = new int[2048];
            int[]     pathRefs     = new int[2048];
            int       pathCount    = -1;

            query.FindStraightPath(actualStart, actualEnd, path.ToArray(), path.Count, straightPath, pathFlags, pathRefs, ref pathCount, 2048, PathBuildFlags.AllCrossingVertices);

            foreach (var v in straightPath)
            {
                Console.WriteLine(v);
            }
        }
Exemple #30
0
        /// <summary>
        /// Creates the NavMeshData
        /// </summary>
        /// <param name="surface"></param>
        /// <returns></returns>
        private NavMeshData InitializeBakeData()
        {
            List <NavMeshBuildSource> buildSources = new List <NavMeshBuildSource>();
            Bounds bounds = new Bounds(primaryViewer.Transform.position, new Vector3(100f, 50f, 100f));

            NavMeshBuilder.CollectSources(transform, navMeshSurface.layerMask, NavMeshCollectGeometry.PhysicsColliders, 0, new List <NavMeshBuildMarkup>(), buildSources);

            return(NavMeshBuilder.BuildNavMeshData(navMeshSurface.GetBuildSettings(), buildSources, bounds, navMeshSurface.transform.position, navMeshSurface.transform.rotation));
        }