public void SetSceneInfo() { LoadLightMap(); LoadFog(); if (Application.isPlaying) { //避免在editor预览时,合并了场景的mesh for (int i = 0; i < mStaticBatchList.Count; i++) { StaticBatchingUtility.Combine(mStaticBatchList[i]); } } }
public void ApplyStaticBatching() { if (visualizationMode == VisualizationMode.None) { return; // don't bother } List <MeshFilter> meshFilters = m_spatialUnderstanding.UnderstandingCustomMesh.GetMeshFilters(); if (meshFilters.Count > 0) { GameObject root = meshFilters[0].transform.parent.gameObject; StaticBatchingUtility.Combine(root); } }
/////////////////////////////////// // Assemble high resolution terrain and block // IEnumerator AssembleHTBlock() { if (working && currentLoadingHTerrainBlock.Count > 0) { float startTimeAssembleHT = Time.time; ADTRootData.MeshBlockData HTData = ADTRootData.MeshBlockDataQueue.Dequeue(); QueueItem HTGroupItem = currentLoadingHTerrainBlock.Dequeue(); if (HTGroupItem.Block != null) { HTGroupItem.Block.name = HTGroupItem.mapName + "_" + HTGroupItem.x + "_" + HTGroupItem.y; // generate mesh objects // int frameSpread = 8; // spreading terrain chunks creation over multiple frames for (int i = 1; i <= frameSpread; i++) { CreateHTBlockQuarter(frameSpread, i, HTData, HTGroupItem.Block); yield return(null); } if (working) { try { // Batch terrain meshes // StaticBatchingUtility.Combine(HTGroupItem.Block); HTGroupItem.Block.GetComponent <ADTBlock>().enabled = true; LoadedQueueItems.Add(HTGroupItem); // request Objs // ADTObjQueue.Add(HTGroupItem); currentLoadingObjBlock.Enqueue(HTGroupItem); // request the LTexture // mapTextureQueue.Enqueue(HTGroupItem); // request the HTexture // ADTTexQueue.Add(HTGroupItem); currentLoadingHTextureBlock.Enqueue(HTGroupItem); } catch { } } } frameBusy = false; finishedTimeAssembleHT = Time.time - startTimeAssembleHT; } }
private void OptimizeTerrain() { if (!Application.isEditor) { LoadState = TerrainLoadState.BeforeCombine; Invoke_TerrainFullyLoadedBeforeCombine(); StaticBatchingUtility.Combine(LoadedScene.GetRootGameObjects()[0]); LoadState = TerrainLoadState.Fully; Invoke_TerrainFullyLoaded(); } }
// Use this for initialization void Start() { GameObject map = new GameObject("map"); for (int i = 0; i < 50; i++) { GameObject column = (GameObject)Resources.Load("Prefabs/Map/map1_item_" + Random.Range(1, 4)); column = MonoBehaviour.Instantiate(column); column.transform.parent = map.transform; column.transform.position = new Vector3(Random.Range(0, 5), Random.Range(0, 5), Random.Range(0, 5)); } StaticBatchingUtility.Combine(map); }
private static List <GameObject> BuildCombineList(List <MeshCombiner> meshCombines, Transform target, bool deleteOriginal, string combineName) { List <GameObject> created = new List <GameObject>(); for (int i = 0; i < meshCombines.Count; i++) { var combiner = meshCombines[i]; var sceneObj = new GameObject(); created.Add(sceneObj); var newName = meshCombines.Count > 1 ? string.Format("{0}-{1}", combineName, i) : combineName; sceneObj.name = newName; sceneObj.transform.parent = target; sceneObj.transform.localPosition = Vector3.zero; sceneObj.layer = LayerMasks.NumberEnvironment; sceneObj.tag = StringConst.TagEnvironment; sceneObj.isStatic = true; var mf = sceneObj.AddComponent <MeshFilter>(); var meshes = new Mesh[combiner.Combines.Count]; var finalCombines = new CombineInstance[combiner.Combines.Count]; var mats = combiner.Combines.Keys.ToArray(); for (int m = 0; m < mats.Length; m++) { meshes[m] = new Mesh(); meshes[m].CombineMeshes(combiner.Combines[mats[m]].ToArray(), true, true, true); finalCombines[m] = new CombineInstance() { mesh = meshes[m], subMeshIndex = 0 }; } mf.sharedMesh = new Mesh(); //if (deleteOriginal) { // mf.hideFlags = HideFlags.DontSave; //} mf.sharedMesh.CombineMeshes(finalCombines, false, false); var render = sceneObj.AddComponent <MeshRenderer>(); // maybe need to add specific tag for objects that cast shadows and put them on their own renderer render.shadowCastingMode = ShadowCastingMode.Off; render.materials = mats; mf.sharedMesh.name = newName; StaticBatchingUtility.Combine(mf.gameObject); //sceneObj.AddComponent<MeshCollider>(); for (int m = 0; m < mats.Length; m++) { meshes[m].Clear(); UnityEngine.Object.DestroyImmediate(meshes[m]); } } return(created); }
private GameObject InstantiatePrefab(GameObject matchedPrefab, float x, float y, float z) { if (matchedPrefab == null) { return(null); } var newElement = Object.Instantiate(matchedPrefab); newElement.transform.position = new Vector3(x, y, z); newElement.transform.parent = container.transform; StaticBatchingUtility.Combine(newElement); return(newElement); }
public ZEDSpatialMapping(Transform transform, sl.ZEDCamera zedCamera, ZEDManager zedManager) { zedSpatialMapping = new ZEDSpatialMappingHelper(Resources.Load("Materials/SpatialMapping/Mat_ZED_Texture") as Material, Resources.Load("Materials/SpatialMapping/Mat_ZED_Geometry_Wireframe") as Material); this.zedCamera = zedCamera; this.zedManager = zedManager; scanningInitState = sl.ERROR_CODE.FAILURE; holder = new GameObject(); holder.name = "[ZED Mesh Holder]"; //holder.hideFlags = HideFlags.HideInInspector; holder.transform.position = Vector3.zero; holder.transform.rotation = Quaternion.identity; StaticBatchingUtility.Combine(holder); }
public void draw(bool isHouse = true) { Vector3 rotationVector = new Vector3(0, 180, 0); Quaternion rotation = Quaternion.Euler(rotationVector); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { switch (tableOfType[i, j]) { case 0: if (tableOfObj[i, j].name == "stop(Clone)") { continue; } DestroyImmediate(tableOfObj[i, j]); tableOfObj[i, j] = Instantiate(stop, stop.transform.position + new Vector3(i, j), rotation, instance.transform); break; case 1: if (tableOfObj[i, j].name == "go(Clone)") { continue; } DestroyImmediate(tableOfObj[i, j]); tableOfObj[i, j] = Instantiate(go, go.transform.position + new Vector3(i, j), rotation, instance.transform); break; case 2: if (isHouse) { if (tableOfObj[i, j].name == "DragHouse(Clone)") { continue; } } DestroyImmediate(tableOfObj[i, j]); tableOfObj[i, j] = Instantiate(dragHouse, dragHouse.transform.position + new Vector3(i, j), rotation, transform); break; } } } if (!isHouse) { StaticBatchingUtility.Combine(gameObject); // 释放鼠标时,静态批处理 } }
void RunStaticBatcher(GameObject mainParent, List <GameObject> exceptions) { Transform[] transforms = mainParent.transform.gameObject.GetComponentsInChildren <Transform>(); //get all transforms from prefab into array List <Material> temp = new List <Material>(); for (int i = 0; i < transforms.Length; i++) { Renderer renderer = transforms[i].gameObject.GetComponent <Renderer>(); if (renderer) { temp.Add(renderer.sharedMaterial); //add material } } List <Material> materials = temp.Distinct(new MaterialNameComparer()).ToList(); //remove copies, by name List <List <GameObject> > gameobjects = new List <List <GameObject> >(); List <GameObject> parents = new List <GameObject>(); for (int i = 0; i < materials.Count; i++) //initialize lists { gameobjects.Add(new List <GameObject>()); parents.Add(new GameObject()); parents[i].name = materials[i].name; } for (int i = 0; i < transforms.Length; i++) //group gameobjects by material type { if (exceptions.Contains(transforms[i].gameObject)) { continue; } Renderer renderer = transforms[i].gameObject.GetComponent <Renderer>(); if (renderer) { for (int j = 0; j < materials.Count; j++) { if (renderer.sharedMaterial.name == materials[j].name) { gameobjects[j].Add(transforms[i].gameObject); transforms[i].gameObject.transform.parent = parents[j].transform; } } } } for (int i = 0; i < materials.Count; i++) //run static batching for every group { parents[i].transform.parent = mainParent.transform; StaticBatchingUtility.Combine(gameobjects[i].ToArray(), parents[i]); } }
protected override void Execute(List <GameEntity> entities) { foreach (GameEntity e in entities) { Vector3 grassPos = e.grassPos.pos; GameObject glass = UnityEngine.Object.Instantiate(ResourceController.Instance.glassPrefab, GrassLand); glass.isStatic = true; grassGameObjects.Add(glass); glass.transform.position = grassPos; } gos = grassGameObjects.ToArray(); StaticBatchingUtility.Combine(gos, GrassLand.gameObject);// 静态合并 grassGameObjects = new List <GameObject>(200); }
private IEnumerator LoadScene(bool isStartGame) { ResourceRequest req = Resources.LoadAsync("Scene/" + ((stageNum % MAX_STAGE_NUM) + 1)); isLoading = true; yield return(req); isLoading = false; scene = GameObject.Instantiate(req.asset as GameObject).transform; scene.name = "Scene"; StaticBatchingUtility.Combine(scene.gameObject); if (isStartGame) { ContinueGame(); } }
private void CreatePrefabs() { for (int i = 0; i < prefabsLevels.Length; i++) { GameObject cave = Instantiate(prefabsLevels[i], _spawnPoint, Quaternion.identity) as GameObject; CreateVisiblePrefab(cave); StaticBatchingUtility.Combine(cave); SetPortalPosition(cave); cave.name = _iterationCaves.ToString(); levelsList.Add(cave.transform); _iterationCaves++; _spawnPoint += new Vector3(0, 7.4f, 3); } }
public static void Combine(GameObject map) { MonoBehaviour.print("Batch Combine " + map.name); Batch.arrR.Clear(); Renderer[] componentsInChildren = map.GetComponentsInChildren <Renderer>(); Renderer[] array = componentsInChildren; for (int i = 0; i < array.Length; i++) { Renderer renderer = array[i]; if (!(renderer == null)) { Batch.arrR.Add(renderer.gameObject); } } StaticBatchingUtility.Combine(Batch.arrR.ToArray(), Batch.obj); }
static int _CreateStaticBatchingUtility(IntPtr L) { int count = LuaDLL.lua_gettop(L); if (count == 0) { StaticBatchingUtility obj = new StaticBatchingUtility(); LuaScriptMgr.PushObject(L, obj); return(1); } else { LuaDLL.luaL_error(L, "invalid arguments to method: StaticBatchingUtility.New"); } return(0); }
public static int constructor(IntPtr l) { int result; try { StaticBatchingUtility o = new StaticBatchingUtility(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return(result); }
/// <summary> /// Assign references, create the holder gameobject, and other misc. initialization. /// </summary> private void Start() { //Create a holder for all the planes holder = new GameObject(); holder.name = "[ZED Planes]"; holder.transform.parent = this.transform; holder.transform.position = Vector3.zero; holder.transform.rotation = Quaternion.identity; StaticBatchingUtility.Combine(holder); //initialize Vertices/Triangles with enough length planeMeshVertices = new Vector3[65000]; planeMeshTriangles = new int[65000]; //floorPlaneGO = holder.AddComponent<ZEDPlaneGameObject> (); hitPlaneList = new List <ZEDPlaneGameObject>(); }
public bool Init() { if (Initiated) { return(false); } Renderer[] childRenders = GetComponentsInChildren <Renderer>().Where(t => t.tag == "static").ToArray(); List <GameObject> childGos = new List <GameObject>(); foreach (var item in childRenders) { childGos.Add(item.gameObject); } StaticBatchingUtility.Combine(childGos.ToArray(), gameObject); Initiated = true; return(true); }
void Batch() { // We create a list of things to batch and populate it List <GameObject> batchTargets = new List <GameObject>(); for (int i = 0; i < rooms.Count; i++) { // batchTargets.Add(rooms[i].gameObject); } GameObject[] furniture = GameObject.FindGameObjectsWithTag("Furniture"); for (int i = 0; i < furniture.Length; i++) { batchTargets.Add(furniture[i]); } StaticBatchingUtility.Combine(batchTargets.ToArray(), this.gameObject); }
private void StaticBatching() { Transform transform = base.get_transform().FindChild("SceneNoStaticBatching"); if (transform == null) { StaticBatchingUtility.Combine(base.get_gameObject()); } else { Transform transform2 = base.get_transform().FindChild("SceneStaticBatching"); if (transform2 != null) { StaticBatchingUtility.Combine(transform2.get_gameObject()); } } }
private void OptimizeTerrain() { if (!Application.isEditor) { if (TerrainFullyLoadedBeforeCombine != null) { TerrainFullyLoadedBeforeCombine(); } StaticBatchingUtility.Combine(LoadedScene.GetRootGameObjects()[0]); if (TerrainFullyLoaded != null) { TerrainFullyLoaded(); } } }
// Update all vertex lighting in the scene public static void UpdateAllVertexLighting(string lightSetId, bool force = false) { List <GameObject> roots = Utilities.GetAllRoots(); MeshContainer activeContainer = null; List <GameObject> changedGOs = new List <GameObject>(); for (int i = 0; i < roots.Count; ++i) { DaydreamVertexLighting[] dvls = roots[i].GetComponentsInChildren <DaydreamVertexLighting>(); foreach (DaydreamVertexLighting dvl in dvls) { // find the mesh container based on the name, all objects share the same container asset so only need to find it once if (activeContainer == null) { dvl.m_bakeSets.SetActiveBakeSet(lightSetId); activeContainer = dvl.m_bakeSets.GetActiveContainer(); } if (activeContainer != null) { if (dvl.SetVertexLightingContainer(activeContainer, force)) { Renderer renderer = dvl.GetComponent <Renderer>(); // re-assign source mesh in order to re-batch dvl.GetComponent <MeshFilter>().mesh = dvl.m_sourceMesh; if (renderer.isPartOfStaticBatch) { changedGOs.Add(dvl.gameObject); } } } } } // re-batch geometry if it was statically batched if (changedGOs.Count > 0) { StaticBatchingUtility.Combine(changedGOs.ToArray(), null); Resources.UnloadUnusedAssets(); } }
public List <GameObject> Blocks; // Список клеток карты /// <summary> /// Загружает выбранный уровень /// </summary> void LoadLevel() { ClearListObjects(Blocks); // Очищает текущую карту ClearPathPoints(); prm.PointsCount = 0; for (int x = 0; x < prm.CurrentMap.width; x++) { for (int y = 0; y < prm.CurrentMap.height; y++) { SetCell(MainController.Instance._LevelEditor.CharToCell(prm.CurrentMap.map[y][x]), x, y); //Создаём клетку CheckPathPoint(prm.CurrentMap.map, x, y); // Проверяем является ли точка ключевой и добавляем её в список } } ConnectPathPoints(prm.CurrentMap.map); //Рассчтиываем ключевые точки SetUpCamera(); StaticBatchingUtility.Combine(gameObject); }
void CreateNodes() { GameObject[] objCreated = new GameObject[width * length * height]; int count = 0; for (int widthTrav = 0; widthTrav < width; widthTrav++) { for (int lengthTrav = 0; lengthTrav < length; lengthTrav++) { for (int heightTrav = 0; heightTrav < height; heightTrav++) { objCreated[count] = Instantiate(node, new Vector3(widthTrav, lengthTrav, heightTrav), new Quaternion()); count++; } } } StaticBatchingUtility.Combine(objCreated, gameObject); }
void InstantiateHexes() { if (parent == null) { parent = this.gameObject; } mapBounds.width = 0; mapBounds.height = 0; mapBounds.x = islandDim; mapBounds.y = islandDim; for (int x = 0; x < islandDim; x++) { for (int y = 0; y < islandDim; y++) { ProcData data = tilemap[x, y]; if (data.type != CellType.nil) { mapBounds.width = Mathf.Max(HexWidth() * x, mapBounds.width); mapBounds.height = Mathf.Max(HexHeight() * y, mapBounds.height); mapBounds.x = Mathf.Min(mapBounds.x); mapBounds.y = Mathf.Min(mapBounds.y); Vector2 pos = HexCoordinate(x, y); data.obj = Instantiate(tile, new Vector3(0f, 0f, 0f), this.tile.transform.rotation, parent.transform); data.obj.transform.Translate(pos.x, 0f, pos.y); data.pos.x = x; data.pos.y = y; data.agent = this; HexTile hexTile = data.obj.AddComponent <HexTile>(); hexTile.data = data; hexTile.SetName(); ++tileCount; } } } if (!debug) { StaticBatchingUtility.Combine(parent); } }
void Start() { LightmapSettings.lightmapsMode = LightmapsMode.CombinedDirectional; var lightmaps = new LightmapData[1]; lightmaps[0] = new LightmapData { lightmapColor = LightmapLight, lightmapDir = LightmapDir }; LightmapSettings.lightmaps = lightmaps; foreach (var lightMapInfo in LightMapInfos) { lightMapInfo.Renderer.lightmapIndex = lightMapInfo.LightmapIndex; lightMapInfo.Renderer.lightmapScaleOffset = lightMapInfo.LightmapScaleOffset; } StaticBatchingUtility.Combine(gameObject); }
private void Init() { // find the corresponding objects e.g. with loading into cache GameObject batchmaster = Program.BuildsContainer.gameObject; GameObject[] array_gameobjects = GameObject.FindGameObjectsWithTag("HouseMed"); // parent the array under batchmaster for (int i = 0; i < array_gameobjects.Length; i++) { array_gameobjects[i].transform.SetParent(batchmaster.transform); } StaticBatchingUtility.Combine(array_gameobjects, batchmaster); //optionally, in case it does not batch on runtime (don’t ask me why, I found it in a forum, when it didn’t work J) batchmaster.SetActive(false); batchmaster.SetActive(true); }
IEnumerator GenerateMesh() { float startTime = Time.realtimeSinceStartup; for (int i = 0; i < numX * Const.ChunkSize; i++) { for (int k = 0; k < numZ * Const.ChunkSize; k++) { for (int j = 0; j < numY * Const.ChunkSize; j++) { Block.BlockChunk chunk = new BlockChunk(bm, i * Const.ChunkSize, j * Const.ChunkSize, k * Const.ChunkSize); //TerrainTool.calcChunkLight(chunk, i, j, k, rtm, rays, sunDir); //Mesh mesh = MeshTool.createMesh(chunk, blockTypeFun, 0, 0, 0); for (int f = 0; f < 6; f++) { List <Block.MeshTool.BlockSurface> surface = Block.MeshTool.getChunkSurface(chunk, bm.blockTypeFun, f); Texture2D texSurface = Block.MeshTool.SurfacePointsToTexture(surface, f); RenderTexture targetAoResult = rma.RenderByCalcShader(texSurface, new Vector3(i, j, k) * Block.Const.ChunkSize, f); //回读亮度数据 RenderTexture.active = targetAoResult; Texture2D readback = new Texture2D(targetAoResult.width, targetAoResult.height); readback.ReadPixels(new Rect(0, 0, targetAoResult.width, targetAoResult.width), 0, 0); Block.MeshTool.SetRaytraceAo(surface, readback); Mesh mesh = Block.MeshTool.createMesh2(surface, f, bm.blockTypeFun); if (mesh != null) { GameObject obj = new GameObject("Chunk", typeof(MeshRenderer), typeof(MeshFilter)); obj.isStatic = true; obj.GetComponent <Renderer>().material = diffuseMat; obj.GetComponent <MeshFilter>().mesh = mesh; obj.transform.SetParent(transform); obj.transform.position = new Vector3(i * Block.Const.ChunkSize * Block.Const.BlockSize, j * Block.Const.ChunkSize * Block.Const.BlockSize, k * Block.Const.ChunkSize * Block.Const.BlockSize); } } yield return(null); } } } StaticBatchingUtility.Combine(this.gameObject); Debug.Log("计算完," + (Time.realtimeSinceStartup - startTime)); }
private void Awake() { if (enemies.Count <= 0 || !targetPlayerTransform) { return; } for (int i = 0; i < enemies.Count; i++) { enemies[i].gm = gm; enemies[i].targetTransform = targetPlayerTransform; enemies[i].swordCut.plane = plane; enemies[i].swordCut.ObjectContainer = objContainer; } foreach (var building in buildings) { StaticBatchingUtility.Combine(building); } }
private List <GameObject> CombineTilemap(List <GameObject> tiles) { List <GameObject> tilemapObj = new List <GameObject>(); int vertexCount = 0; List <CombineInstance> combine = new List <CombineInstance>(); foreach (GameObject tile in tiles) { foreach (MeshFilter meshFilter in tile.GetComponentsInChildren <MeshFilter>()) { if (vertexCount + meshFilter.sharedMesh.vertexCount >= ushort.MaxValue) { tilemapObj.Add(this.WrapUpTilemapMesh(combine.ToArray())); combine.Clear(); vertexCount = 0; } combine.Add(new CombineInstance { mesh = meshFilter.sharedMesh, transform = meshFilter.transform.localToWorldMatrix }); vertexCount += meshFilter.sharedMesh.vertexCount; } } if (combine.Count > 0) { tilemapObj.Add(this.WrapUpTilemapMesh(combine.ToArray())); } StaticBatchingUtility.Combine(tilemapObj.ToArray(), this.tilemap.gameObject); foreach (GameObject tile in tiles) { GameObject.Destroy(tile); } return(tilemapObj); }