private void LoadStampDirFileInfo() { if (m_selectedCategoryID != -99) { string directory = GaiaDirectories.GetStampDirectory() + "/" + m_categoryNames[m_selectedCategoryID]; if (!Directory.Exists(directory)) { directory = GaiaDirectories.GetUserStampDirectory() + "/" + m_categoryNames[m_selectedCategoryID]; } if (!Directory.Exists(directory)) { Debug.LogWarning("Could not find the selected subdirectory '" + m_categoryNames[m_selectedCategoryID] + "' neither in the Gaia Stamps or in the User Stamps folder when trying to browse stamps."); return; } var info = new DirectoryInfo(directory); if (info == null) { Debug.LogWarning("Could not access directory " + directory + " when trying to browse stamps."); return; } m_currentStampDirFileInfo = info.GetFiles(); } }
/// <summary> /// Loads on enable /// </summary> private void OnEnable() { if (String.IsNullOrEmpty(m_exportFolder)) { m_exportFolder = GaiaDirectories.GetScannerExportDirectory(); } SetOrCreateMeshComponents(); }
/// <summary> /// Checks if gaia pro exists /// </summary> /// <returns></returns> public static bool GaiaProDefineCheck() { bool isPro = false; isPro = GaiaDirectories.GetGaiaProDirectory(); return(isPro); }
/// <summary> /// Reset the scanner /// </summary> public void ResetData() { m_exportFolder = GaiaDirectories.GetScannerExportDirectory(); m_exportFileName = "/Scan " + string.Format("{0:YYYYMMDD-hhmmss}", DateTime.Now); m_boundsSet = false; m_scanBounds = new Bounds(GetPosition(gameObject, null), Vector3.one * 10f); m_scanWidth = m_scanDepth = m_scanHeight = 0; m_baseLevel = 0f; transform.localRotation = Quaternion.identity; transform.localScale = Vector3.one; }
/// <summary> /// Checks if gaia pro exists /// </summary> /// <returns></returns> public static bool IsGaiaPro() { bool isPro = false; isPro = GaiaDirectories.GetGaiaProDirectory(); #if GAIA_PRO_PRESENT isPro = true; #else isPro = false; #endif return(isPro); }
/// <summary> /// Create the mask and put it in the root assets directory /// </summary> public void CreateMask() { // Check to see if we have an active terrain if (Terrain.activeTerrain == null) { Debug.LogError("You need an active terrain!"); return; } // Get the terrain UnityHeightMap hm = new UnityHeightMap(Terrain.activeTerrain); // Create a heightmap for the mask HeightMap maskHm = new HeightMap(hm.Width(), hm.Depth()); //Iterate though our terrain, at the resolution of the heightmap and pick up the height float testHeight; float nrmSeaLevel = m_seaLevel / Terrain.activeTerrain.terrainData.size.y; for (int x = 0; x < hm.Width(); x++) { for (int z = 0; z < hm.Depth(); z++) { testHeight = hm[x, z]; if (testHeight < nrmSeaLevel) { continue; } else if (Gaia.GaiaUtils.Math_ApproximatelyEqual(testHeight, nrmSeaLevel)) { //We have a shoreline, lets mask it maskHm[x, z] = m_aboveWaterStrength; MakeMask(x, z, nrmSeaLevel, m_maskSize, hm, maskHm); } else { maskHm[x, z] = m_aboveWaterStrength; } } } maskHm.Flip(); //maskHm.Smooth(1); string path = GaiaDirectories.GetExportDirectory(); path = Path.Combine(path, PWCommon4.Utils.FixFileName(string.Format("TerrainShoreLineMask-{0:yyyyMMdd-HHmmss}", DateTime.Now))); Gaia.GaiaUtils.CompressToSingleChannelFileImage(maskHm.Heights(), path, TextureFormat.RGBA32, false, true); EditorUtility.DisplayDialog("Shoreline Masker", "Your shorline mask has been created at " + path, "OK"); }
/// <summary> /// Looks up terrain layer asset files matching a Gaia terrain, and returns them as an array. /// </summary> /// <param name="terrainName">The Gaia terrain name to look up terrain layer asset files for.</param> /// <returns></returns> // private static TerrainLayer[] LookupTerrainLayerAssetFiles(string terrainName) // { //#if UNITY_EDITOR // string gaiaDirectory = ""; // string terrainLayerDirectory = gaiaDirectory + "Profiles/TerrainLayers"; // DirectoryInfo info = new DirectoryInfo(terrainLayerDirectory); // FileInfo[] fileInfo = info.GetFiles(terrainName + "*.asset"); // TerrainLayer[] returnArray = new TerrainLayer[fileInfo.Length]; // for (int i = 0; i < fileInfo.Length; i++) // { // returnArray[i] = (TerrainLayer)AssetDatabase.LoadAssetAtPath("Assets" + fileInfo[i].FullName.Substring(Application.dataPath.Length), typeof(TerrainLayer)); // } // return returnArray; //#else // Debug.LogError("Runtime Gaia operation is not supported"); // return new TerrainLayer[0]; //#endif // } /// <summary> /// Saves a unity terrain layer as asset file and returns a reference to the newly created Terrain Layerfile. /// </summary> /// <param name="terrainName">The name of the current Gaia terrain (for the filename).</param> /// <param name="layerId">The layer ID of the layer that is to be saved (for the filename).</param> /// <param name="terrainLayer">The terrain layer object to save.</param> /// <returns>Reference to the created TerrainLayer</returns> public static TerrainLayer SaveTerrainLayerAsAsset(string terrainName, string layerId, TerrainLayer terrainLayer) { #if UNITY_EDITOR GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); //The combination of terrain name and layer id should be unique enough so that users don't overwrite layers between terrains. string path = GaiaDirectories.GetTerrainLayerPath(gsm.m_session) + "/" + terrainName + "_" + layerId + ".asset"; AssetDatabase.CreateAsset(terrainLayer, path); AssetDatabase.ImportAsset(path); return(AssetDatabase.LoadAssetAtPath <TerrainLayer>(path)); #else Debug.LogError("Runtime Gaia operation is not supported"); return(new TerrainLayer()); #endif }
private void ExportMask() { GaiaWorldManager mgr = new GaiaWorldManager(Terrain.activeTerrains); if (mgr.TileCount > 0) { GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); string path = GaiaDirectories.GetExportDirectory(gsm.m_session); path = Path.Combine(path, PWCommon4.Utils.FixFileName(m_maskName)); mgr.ExportSplatmapAsPng(path, m_selectedMask); Debug.Log("Created " + path); AssetDatabase.Refresh(); EditorUtility.FocusProjectWindow(); EditorUtility.DisplayDialog("Export complete", " Your texture mask has been saved to : " + path, "OK"); } else { EditorUtility.DisplayDialog("OOPS!", "You must have a valid terrain!!", "OK"); } }
private void WriteCacheEntry(BakedMaskCacheEntry entry, RenderTexture texture, Terrain terrain, string fileName) { //build the paths string assetPath = GaiaDirectories.GetTerrainCollisionDirectory(terrain) + "/" + fileName; string fullPath = assetPath.Replace("Assets", Application.dataPath); //clear old texture if (entry.texture != null && entry.texture != Texture2D.whiteTexture) { UnityEngine.Object.DestroyImmediate(entry.texture); entry.texture = null; } //overwrite texture contents entry.texture = texture; //assign Paths & name entry.fileName = fileName; entry.assetPath = assetPath; entry.fullPath = fullPath; }
private void ExportNormal() { if (Terrain.activeTerrain == null) { EditorUtility.DisplayDialog("OOPS!", "You must have a valid terrain in your scene!!", "OK"); return; } GaiaWorldManager mgr = new GaiaWorldManager(Terrain.activeTerrains); if (mgr.TileCount > 0) { GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); string path = GaiaDirectories.GetExportDirectory(gsm.m_session); mgr.LoadFromWorld(); path = Path.Combine(path, PWCommon4.Utils.FixFileName(m_maskName)); mgr.ExportNormalmapAsPng(path); AssetDatabase.Refresh(); EditorUtility.DisplayDialog("Export complete", " Your normal map has been saved to : " + path, "OK"); } }
private void DrawSummary(bool helpEnabled) { m_manager.m_session = (GaiaSession)m_editorUtils.ObjectField("SessionData", m_manager.m_session, typeof(GaiaSession), helpEnabled); m_editorUtils.InlineHelp("SessionData", helpEnabled); if (m_manager.m_session == null) { if (m_editorUtils.Button("CreateSessionButton")) { m_manager.CreateSession(); } } if (m_manager.m_session == null) { return; } EditorGUI.BeginChangeCheck(); m_manager.m_session.m_name = m_editorUtils.DelayedTextField("Name", m_manager.m_session.m_name, helpEnabled); if (EditorGUI.EndChangeCheck()) { //Get the old path string oldSessionDataPath = GaiaDirectories.GetSessionSubFolderPath(m_manager.m_session); //Rename the session asset AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(m_manager.m_session), m_manager.m_session.m_name + ".asset"); //rename the session data path as well string newSessionDataPath = GaiaDirectories.GetSessionSubFolderPath(m_manager.m_session, false); AssetDatabase.MoveAsset(oldSessionDataPath, newSessionDataPath); //if we have terrain scenes stored in the Terrain Loader, we need to update the paths in there as well foreach (TerrainScene terrainScene in TerrainLoaderManager.TerrainScenes) { terrainScene.m_scenePath = terrainScene.m_scenePath.Replace(oldSessionDataPath, newSessionDataPath); terrainScene.m_impostorScenePath = terrainScene.m_impostorScenePath.Replace(oldSessionDataPath, newSessionDataPath); terrainScene.m_backupScenePath = terrainScene.m_backupScenePath.Replace(oldSessionDataPath, newSessionDataPath); terrainScene.m_colliderScenePath = terrainScene.m_colliderScenePath.Replace(oldSessionDataPath, newSessionDataPath); } TerrainLoaderManager.Instance.SaveStorageData(); AssetDatabase.DeleteAsset(oldSessionDataPath); AssetDatabase.SaveAssets(); } EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(m_editorUtils.GetContent("Description"), GUILayout.MaxWidth(EditorGUIUtility.labelWidth)); m_manager.m_session.m_description = EditorGUILayout.TextArea(m_manager.m_session.m_description, GUILayout.MinHeight(100)); EditorGUILayout.EndHorizontal(); m_editorUtils.InlineHelp("Description", helpEnabled); m_manager.m_session.m_previewImage = (Texture2D)m_editorUtils.ObjectField("PreviewImage", m_manager.m_session.m_previewImage, typeof(Texture2D), helpEnabled); GUILayout.BeginHorizontal(); Rect rect = EditorGUILayout.GetControlRect(); GUILayout.Space(rect.width - 20); if (GUILayout.Button("Generate Image")) { string textureFileName = GaiaDirectories.GetSessionSubFolderPath(m_manager.m_session) + Path.DirectorySeparatorChar + m_manager.m_session + "_Preview"; var originalLODBias = QualitySettings.lodBias; QualitySettings.lodBias = 100; OrthographicBake.BakeTerrain(Terrain.activeTerrain, 2048, 2048, Camera.main.cullingMask, textureFileName); OrthographicBake.RemoveOrthoCam(); QualitySettings.lodBias = originalLODBias; textureFileName += ".png"; AssetDatabase.ImportAsset(textureFileName); var importer = AssetImporter.GetAtPath(textureFileName) as TextureImporter; if (importer != null) { importer.sRGBTexture = false; importer.alphaIsTransparency = false; importer.alphaSource = TextureImporterAlphaSource.None; importer.mipmapEnabled = false; } AssetDatabase.ImportAsset(textureFileName); m_manager.m_session.m_previewImage = (Texture2D)AssetDatabase.LoadAssetAtPath(textureFileName, typeof(Texture2D)); } GUILayout.EndHorizontal(); m_editorUtils.InlineHelp("PreviewImage", helpEnabled); m_editorUtils.LabelField("Created", new GUIContent(m_manager.m_session.m_dateCreated), helpEnabled); m_manager.m_session.m_isLocked = m_editorUtils.Toggle("Locked", m_manager.m_session.m_isLocked, helpEnabled); float maxSeaLevel = 2000f; if (Terrain.activeTerrain != null) { maxSeaLevel = Terrain.activeTerrain.terrainData.size.y + Terrain.activeTerrain.transform.position.y; } else { maxSeaLevel = m_manager.GetSeaLevel(false) + 500f; } float oldSeaLevel = m_manager.GetSeaLevel(false); float newSeaLEvel = oldSeaLevel; newSeaLEvel = m_editorUtils.Slider("SeaLevel", newSeaLEvel, 0, maxSeaLevel, helpEnabled); if (newSeaLEvel != oldSeaLevel) { //Do we have a water instance? If yes, update it & it will update the sea level in the session as well if (PWS_WaterSystem.Instance != null) { PWS_WaterSystem.Instance.SeaLevel = newSeaLEvel; } else { //no water instance yet, just update the sea level in the session m_manager.SetSeaLevel(newSeaLEvel, false); SceneView.RepaintAll(); } } m_manager.m_session.m_spawnDensity = m_editorUtils.FloatField("SpawnDensity", Mathf.Max(0.01f, m_manager.m_session.m_spawnDensity), helpEnabled); GUILayout.BeginHorizontal(); if (m_editorUtils.Button("DeleteAllOperations")) { if (EditorUtility.DisplayDialog(m_editorUtils.GetTextValue("PopupDeleteAllTitle"), m_editorUtils.GetTextValue("PopupDeleteAllMessage"), m_editorUtils.GetTextValue("Continue"), m_editorUtils.GetTextValue("Cancel"))) { foreach (GaiaOperation op in m_manager.m_session.m_operations) { try { if (!String.IsNullOrEmpty(op.scriptableObjectAssetGUID)) { AssetDatabase.DeleteAsset(AssetDatabase.GUIDToAssetPath(op.scriptableObjectAssetGUID)); } } catch (Exception ex) { Debug.LogError("Error while deleting one of the operation data files: " + ex.Message + " Stack Trace:" + ex.StackTrace); } } m_manager.m_session.m_operations.Clear(); } } if (m_editorUtils.Button("PlaySession")) { GaiaLighting.SetDefaultAmbientLight(GaiaUtils.GetGaiaSettings().m_gaiaLightingProfile); GaiaSessionManager.PlaySession(); } GUILayout.EndHorizontal(); }
public void Init(ImageMask imageMask = null) { allBiomeController = (BiomeController[])Resources.FindObjectsOfTypeAll(typeof(BiomeController)); allStampers = (Stamper[])Resources.FindObjectsOfTypeAll(typeof(Stamper)); allSpawners = (Spawner[])Resources.FindObjectsOfTypeAll(typeof(Spawner)); m_categoryNames.Clear(); var info = new DirectoryInfo(GaiaDirectories.GetStampDirectory()); var fileInfo = info.GetDirectories(); foreach (DirectoryInfo dir in fileInfo) { m_categoryNames.Add(dir.Name); } //Do the same with the user stamp folder info = new DirectoryInfo(GaiaDirectories.GetUserStampDirectory()); fileInfo = info.GetDirectories(); foreach (DirectoryInfo dir in fileInfo) { m_categoryNames.Add(dir.Name); } m_categoryNames.Sort(); if (imageMask != null) { m_editedImageMask = imageMask; } //read & store the original texture guid if the user wants to cancel if ((m_editedImageMask != null && m_editedImageMask.ImageMaskTexture != null)) { string pathToImage = ""; if (m_editedImageMask != null) { pathToImage = AssetDatabase.GetAssetPath(m_editedImageMask.ImageMaskTexture); } //else //{ // pathToImage = AssetDatabase.GetAssetPath(m_editedStamperSettings.m_stamperInputImage); //} m_originalTextureGUID = AssetDatabase.AssetPathToGUID(pathToImage); m_previewTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(pathToImage, typeof(Texture2D)); //Try to locate the selected image in the stamps directory if (pathToImage.Contains(GaiaDirectories.STAMP_DIRECTORY)) { string lastFolderName = Path.GetFileName(Path.GetDirectoryName(pathToImage)); m_selectedCategoryID = m_categoryNames.FindIndex(x => x == lastFolderName); LoadStampDirFileInfo(); int index = -1; foreach (var fi in m_currentStampDirFileInfo) { index++; if (pathToImage.Contains(fi.Name)) { m_currentStampIndex = index; } } } } else { m_originalTextureGUID = ""; } }
private bool PickNextStamp(int direction) { //try to load a stamp file from the next index int nextIndexCandidate = m_currentStampIndex + direction; if (m_currentStampDirFileInfo == null) { LoadStampDirFileInfo(); } //still null? abort! if (m_currentStampDirFileInfo == null) { return(false); } if (0 <= nextIndexCandidate && nextIndexCandidate < m_currentStampDirFileInfo.Length - 1) { try { //Try to load the next texture2D into the preview texture, whatever file it is. string assetPath = GaiaDirectories.GetStampDirectory() + "/" + m_categoryNames[m_selectedCategoryID] + "/" + m_currentStampDirFileInfo[nextIndexCandidate].Name; m_previewTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)); if (m_previewTexture == null) { //Not found? Try to load from the user stamps folder instead assetPath = GaiaDirectories.GetUserStampDirectory() + "/" + m_categoryNames[m_selectedCategoryID] + "/" + m_currentStampDirFileInfo[nextIndexCandidate].Name; m_previewTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)); } if (m_previewTexture == null) { //no exception, but no valid texture file either, let's try the next index then m_currentStampIndex = nextIndexCandidate; return(PickNextStamp(direction)); } else { m_currentStampIndex = nextIndexCandidate; if (m_editedImageMask != null) { m_editedImageMask.ImageMaskTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)); } //else //{ // m_editedStamperSettings.m_stamperInputImage = (Texture2D)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)); //} UpdateToolsAndScene(); return(true); } } catch (Exception) { //there might be more valid files, let's try the next index then m_currentStampIndex = nextIndexCandidate; return(PickNextStamp(direction)); } } else { return(false); } }
public Spawner CreateSpawner(bool autoAddResources = false, Transform targetTransform = null) { //Find or create gaia GameObject gaiaObj = GaiaUtils.GetGaiaGameObject(); GameObject spawnerObj = new GameObject(this.name); spawnerObj.AddComponent <Spawner>(); if (targetTransform != null) { spawnerObj.transform.parent = targetTransform; } else { spawnerObj.transform.parent = gaiaObj.transform; } Spawner spawner = spawnerObj.GetComponent <Spawner>(); spawner.LoadSettings(this); //spawner.m_settings.m_resources = (GaiaResource)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(this.m_resourcesGUID), typeof(GaiaResource)); if (autoAddResources) { TerrainLayer[] terrainLayers = new TerrainLayer[0]; DetailPrototype[] terrainDetails = new DetailPrototype[0]; TreePrototype[] terrainTrees = new TreePrototype[0]; GaiaDefaults.GetPrototypes(new List <BiomeSpawnerListEntry>() { new BiomeSpawnerListEntry() { m_spawnerSettings = this, m_autoAssignPrototypes = true } }, ref terrainLayers, ref terrainDetails, ref terrainTrees, Terrain.activeTerrain); foreach (Terrain t in Terrain.activeTerrains) { GaiaDefaults.ApplyPrototypesToTerrain(t, terrainLayers, terrainDetails, terrainTrees); } } //We need to check the texture prototypes in this spawner against the already created terrain layers for this session //- otherwise the spawner will not know about those in subsequent spawns and might create unneccessary additional layers //Get a list of all exisiting Terrain Layers for this session string path = GaiaDirectories.GetTerrainLayerPath(); #if UNITY_EDITOR AssetDatabase.ImportAsset(path); if (Directory.Exists(path)) { string[] allLayerGuids = AssetDatabase.FindAssets("t:TerrainLayer", new string[1] { path }); List <TerrainLayer> existingTerrainLayers = new List <TerrainLayer>(); foreach (string guid in allLayerGuids) { try { TerrainLayer layer = (TerrainLayer)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), typeof(TerrainLayer)); if (layer != null) { existingTerrainLayers.Add(layer); } } catch (Exception ex) { if (ex.Message == "") { } } } foreach (SpawnRule sr in spawner.m_settings.m_spawnerRules) { if (sr.m_resourceType == SpawnerResourceType.TerrainTexture) { ResourceProtoTexture protoTexture = spawner.m_settings.m_resources.m_texturePrototypes[sr.m_resourceIdx]; //if a terrainLayer with these properties exist we can assume it fits to the given spawn rule TerrainLayer terrainLayer = existingTerrainLayers.FirstOrDefault(x => x.diffuseTexture == protoTexture.m_texture && x.normalMapTexture == protoTexture.m_normal && x.tileOffset == new Vector2(protoTexture.m_offsetX, protoTexture.m_offsetY) && x.tileSize == new Vector2(protoTexture.m_sizeX, protoTexture.m_sizeY) ); if (terrainLayer != null) { protoTexture.m_LayerGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(terrainLayer)); } } } } #endif foreach (SpawnRule rule in spawner.m_settings.m_spawnerRules) { rule.m_spawnedInstances = 0; } if (Terrain.activeTerrains.Where(x => !TerrainHelper.IsWorldMapTerrain(x)).Count() > 0) { spawner.FitToAllTerrains(); } //else //{ // spawner.FitToTerrain(); //} return(spawner); }
void OnGUI() { //Set up the box style if (m_boxStyle == null) { m_boxStyle = new GUIStyle(GUI.skin.box); m_boxStyle.normal.textColor = GUI.skin.label.normal.textColor; m_boxStyle.fontStyle = FontStyle.Bold; m_boxStyle.alignment = TextAnchor.UpperLeft; } //Setup the wrap style if (m_wrapStyle == null) { m_wrapStyle = new GUIStyle(GUI.skin.label); m_wrapStyle.fontStyle = FontStyle.Normal; m_wrapStyle.wordWrap = true; } //Text intro GUILayout.BeginVertical("Gaia WaterFlow Mask Exporter", m_boxStyle); GUILayout.Space(20); EditorGUILayout.LabelField("The Gaia waterflow exporter allows you to calculate and export a water flow mask from your terrain.", m_wrapStyle); GUILayout.EndVertical(); if (string.IsNullOrEmpty(m_maskName)) { m_maskName = string.Format("TerrainWaterFlow-{0:yyyyMMdd-HHmmss}", DateTime.Now); } m_maskName = EditorGUILayout.TextField(GetLabel("Mask Name"), m_maskName); m_waterFlowMap.m_dropletVolume = EditorGUILayout.Slider(GetLabel("Droplet Volume"), m_waterFlowMap.m_dropletVolume, 0.1f, 2f); m_waterFlowMap.m_dropletAbsorbtionRate = EditorGUILayout.Slider(GetLabel("Droplet Absorbtion Rate"), m_waterFlowMap.m_dropletAbsorbtionRate, 0.01f, 1f); m_waterFlowMap.m_waterflowSmoothIterations = EditorGUILayout.IntSlider(GetLabel("Smooth Iterations"), m_waterFlowMap.m_waterflowSmoothIterations, 0, 10); GUILayout.Space(5); EditorGUI.indentLevel++; if (DisplayButton(GetLabel("Create Mask"))) { Terrain terrain = Gaia.TerrainHelper.GetActiveTerrain(); if (terrain == null) { EditorUtility.DisplayDialog("OOPS!", "You must have a valid terrain!!", "OK"); return; } GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); string path = GaiaDirectories.GetExportDirectory(gsm.m_session); path = Path.Combine(path, PWCommon4.Utils.FixFileName(m_maskName)); m_waterFlowMap.CreateWaterFlowMap(terrain); m_waterFlowMap.ExportWaterMapToPath(path); GaiaWorldManager mgr = new GaiaWorldManager(Terrain.activeTerrains); mgr.LoadFromWorld(); path += "WaterFlow"; mgr.ExportWaterflowMapAsPng(m_waterFlowMap.m_waterflowSmoothIterations, path); AssetDatabase.Refresh(); EditorUtility.DisplayDialog("Done!", "Your mask is available at " + path, "OK"); } EditorGUI.indentLevel--; }
public void LoadStorageData() { #if UNITY_EDITOR //Try to get the terrain scene storage file from the last used GUID first if (!String.IsNullOrEmpty(m_lastUsedGUID)) { m_terrainSceneStorage = (TerrainSceneStorage)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(m_lastUsedGUID), typeof(TerrainSceneStorage)); } //No guid / storage object? Then we need to create one in the current session directory if (m_terrainSceneStorage == null) { GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); if (gsm != null && gsm.m_session != null) { string path = GaiaDirectories.GetScenePath(gsm.m_session) + "/TerrainScenes.asset"; if (File.Exists(path)) { m_terrainSceneStorage = (TerrainSceneStorage)AssetDatabase.LoadAssetAtPath(path, typeof(TerrainSceneStorage)); } else { m_terrainSceneStorage = ScriptableObject.CreateInstance <TerrainSceneStorage>(); if (TerrainHelper.GetWorldMapTerrain() != null) { m_terrainSceneStorage.m_hasWorldMap = true; } AssetDatabase.CreateAsset(m_terrainSceneStorage, path); AssetDatabase.ImportAsset(path); } } else { m_terrainSceneStorage = ScriptableObject.CreateInstance <TerrainSceneStorage>(); } } //Check if there are scene files existing already and if they are in the storage data - if not, we should pick them up accordingly string directory = GaiaDirectories.GetTerrainScenePathForStorageFile(m_terrainSceneStorage); var dirInfo = new DirectoryInfo(directory); bool madeChanges = false; if (dirInfo != null) { FileInfo[] allFiles = dirInfo.GetFiles(); foreach (FileInfo fileInfo in allFiles) { if (fileInfo.Extension == ".unity") { string path = GaiaDirectories.GetPathStartingAtAssetsFolder(fileInfo.FullName); if (!m_terrainSceneStorage.m_terrainScenes.Exists(x => x.GetTerrainName() == x.GetTerrainName(path))) { string firstSegment = fileInfo.Name.Split('-')[0]; int xCoord = -99; int zCoord = -99; bool successX, successZ; try { successX = Int32.TryParse(firstSegment.Substring(firstSegment.IndexOf('_') + 1, firstSegment.LastIndexOf('_') - (firstSegment.IndexOf('_') + 1)), out xCoord); successZ = Int32.TryParse(firstSegment.Substring(firstSegment.LastIndexOf('_') + 1, firstSegment.Length - 1 - firstSegment.LastIndexOf('_')), out zCoord); } catch (Exception ex) { if (ex.Message == "123") { } successX = false; successZ = false; } if (successX && successZ) { //double centerX = (xCoord - (m_terrainSceneStorage.m_terrainTilesX / 2f)) * m_terrainSceneStorage.m_terrainTilesSize + (m_terrainSceneStorage.m_terrainTilesSize /2f); //double centerZ = (zCoord - (m_terrainSceneStorage.m_terrainTilesZ / 2f)) * m_terrainSceneStorage.m_terrainTilesSize + (m_terrainSceneStorage.m_terrainTilesSize / 2f); Vector2 offset = new Vector2(-m_terrainSceneStorage.m_terrainTilesSize * m_terrainSceneStorage.m_terrainTilesX * 0.5f, -m_terrainSceneStorage.m_terrainTilesSize * m_terrainSceneStorage.m_terrainTilesZ * 0.5f); Vector3Double position = new Vector3(m_terrainSceneStorage.m_terrainTilesSize * xCoord + offset.x, 0, m_terrainSceneStorage.m_terrainTilesSize * zCoord + offset.y); Vector3Double center = new Vector3Double(position + new Vector3Double(m_terrainSceneStorage.m_terrainTilesSize / 2f, 0f, m_terrainSceneStorage.m_terrainTilesSize / 2f)); BoundsDouble bounds = new BoundsDouble(center, new Vector3Double(m_terrainSceneStorage.m_terrainTilesSize, m_terrainSceneStorage.m_terrainTilesSize * 4, m_terrainSceneStorage.m_terrainTilesSize)); //Use forward slashes in the path - The Unity scene management classes expect it that way path = path.Replace("\\", "/"); TerrainScene terrainScene = new TerrainScene() { m_scenePath = path, m_pos = position, m_bounds = bounds, m_useFloatingPointFix = m_terrainSceneStorage.m_useFloatingPointFix }; if (File.Exists(path.Replace("Terrain", GaiaConstants.ImpostorTerrainName))) { terrainScene.m_impostorScenePath = path.Replace("Terrain", GaiaConstants.ImpostorTerrainName); } if (File.Exists(path.Replace("Terrain", "Collider"))) { terrainScene.m_colliderScenePath = path.Replace("Terrain", "Collider"); } if (File.Exists(path.Replace("Terrain", "Backup"))) { terrainScene.m_backupScenePath = path.Replace("Terrain", "Backup"); } m_terrainSceneStorage.m_terrainScenes.Add(terrainScene); madeChanges = true; } } } } if (madeChanges) { EditorUtility.SetDirty(m_terrainSceneStorage); AssetDatabase.SaveAssets(); } } m_lastUsedGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_terrainSceneStorage)); RefreshTerrainsWithCurrentData(); RefreshSceneViewLoadingRange(); ////Go over the currently open scene and close the ones that do not seem to have a reference on them //for (int i = EditorSceneManager.loadedSceneCount-1; i >= 0; i--) //{ // Scene scene = EditorSceneManager.GetSceneAt(i); // if (EditorSceneManager.GetActiveScene().Equals(scene)) // { // continue; // } // TerrainScene terrainScene = m_terrainSceneStorage.m_terrainScenes.Find(x => x.m_scenePath == scene.path || x.m_impostorScenePath == scene.path || x.m_colliderScenePath == scene.path); // if (terrainScene != null) // { // terrainScene.UpdateWithCurrentData(); // } // else // { // EditorSceneManager.UnloadSceneAsync(scene); // } //} #endif }
private void GlobalPanel(bool helpEnabled) { //Text intro GUILayout.BeginVertical("Gaia Scanner", m_boxStyle); GUILayout.Space(20); EditorGUILayout.LabelField("The Gaia Scanner allows you to create new stamps from Windows R16, Windows 16 bit RAW, Mac 16 bit RAW, Terrains, Textures or Meshes. Just drag and drop the file or object onto the area below to scan it.", m_wrapStyle); GUILayout.EndVertical(); DropAreaGUI(); bool originalGUIState = GUI.enabled; if (!m_scanner.m_objectScanned) { GUI.enabled = false; } //DrawDefaultInspector(); GUILayout.BeginVertical("Setup", m_boxStyle); GUILayout.Space(20); m_editorUtils.Heading("GlobalSettings"); m_scanner.m_previewMaterial = (Material)m_editorUtils.ObjectField("PreviewMaterial", m_scanner.m_previewMaterial, typeof(Material), false, helpEnabled); EditorGUILayout.BeginHorizontal(); m_scanner.m_exportFolder = m_editorUtils.TextField("ExportPath", m_scanner.m_exportFolder); if (m_editorUtils.Button("ExportDirectoryOpen", GUILayout.Width(80))) { string path = EditorUtility.SaveFolderPanel(m_editorUtils.GetTextValue("ExportDirectoryWindowTitle"), GaiaDirectories.GetUserStampDirectory(), GaiaDirectories.SCANNER_EXPORT_DIRECTORY.Replace("/", "")); if (path.Contains(Application.dataPath)) { m_scanner.m_exportFolder = GaiaDirectories.GetPathStartingAtAssetsFolder(path); } else { EditorUtility.DisplayDialog("Path outside the Assets folder", "The selected path needs to be inside the Assets folder of the project. Please select an appropiate path.", "OK"); m_scanner.m_exportFolder = GaiaDirectories.GetScannerExportDirectory(); } } EditorGUILayout.EndHorizontal(); m_editorUtils.InlineHelp("ExportPath", helpEnabled); m_scanner.m_exportFileName = m_editorUtils.TextField("ExportFilename", m_scanner.m_exportFileName, helpEnabled); float oldBaseLevel = m_scanner.m_baseLevel; m_scanner.m_baseLevel = m_editorUtils.Slider("BaseLevel", m_scanner.m_baseLevel, 0f, 1f, helpEnabled); if (oldBaseLevel != m_scanner.m_baseLevel) { SceneView.lastActiveSceneView.Repaint(); } EditorGUILayout.Space(10f); m_editorUtils.Heading("ObjectTypeSettings"); if (m_scanner.m_scannerObjectType == ScannerObjectType.Mesh) { m_scanner.m_scanResolution = m_editorUtils.Slider("ScanResolution", m_scanner.m_scanResolution, 0.0001f, 1f, helpEnabled); if (m_scanner.m_lastScanResolution != m_scanner.m_scanResolution) { if (m_editorUtils.Button("RefreshScan")) { m_scanner.LoadGameObject(m_scanner.m_lastScannedMesh); } } } if (m_scanner.m_scannerObjectType == ScannerObjectType.Raw) { //Drop Options section GUILayout.BeginHorizontal(); { EditorGUILayout.PrefixLabel(BYTE_ORDER_LABEL); EditorGUI.BeginChangeCheck(); { m_rawByteOrder = (GaiaConstants.RawByteOrder)GUILayout.Toolbar((int)m_rawByteOrder, new string[] { "IBM PC", "Macintosh" }); } if (EditorGUI.EndChangeCheck()) { ReloadRawFile(); } } GUILayout.EndHorizontal(); m_editorUtils.InlineHelp("RawFileByteOrder", helpEnabled); EditorGUI.BeginChangeCheck(); { m_rawBitDepth = (GaiaConstants.RawBitDepth)EditorGUILayout.Popup(BIT_DEPTH_LABEL, (int)m_rawBitDepth, BIT_DEPTHS_LABELS); m_editorUtils.InlineHelp("RawFileBitDepth", helpEnabled); } if (EditorGUI.EndChangeCheck()) { ReloadRawFile(); } GUILayout.BeginVertical(); if (m_showRawInfo) { EditorGUILayout.HelpBox("Assumed " + (m_rawBitDepth == GaiaConstants.RawBitDepth.Sixteen ? "16-bit" : "8-bit") + " RAW " + m_assumedRawRes + " x " + m_assumedRawRes, MessageType.Info); } if (m_showBitDepthWarning) { EditorGUILayout.HelpBox(m_editorUtils.GetTextValue("8BitWarning"), MessageType.Warning); } GUILayout.EndVertical(); } EditorGUILayout.Space(10f); m_editorUtils.Heading("ExportSettings"); //m_scanner.m_textureExportResolution = (GaiaConstants.GaiaProWaterReflectionsQuality) EditorGUILayout.EnumPopup(new GUIContent("Export Resolution", "Sets the export resolution of the texture generated"), m_scanner.m_textureExportResolution); m_scanner.m_normalize = m_editorUtils.Toggle("Normalize", m_scanner.m_normalize, helpEnabled); m_scanner.m_exportTextureAlso = m_editorUtils.Toggle("ExportPNG", m_scanner.m_exportTextureAlso, helpEnabled); //m_scanner.m_exportBytesData = m_editorUtils.Toggle("ExportBytesData", m_scanner.m_exportBytesData, helpEnabled); GUILayout.EndVertical(); //Terraform section GUILayout.BeginVertical("Scanner Controller", m_boxStyle); GUILayout.Space(20); if (!string.IsNullOrEmpty(m_infoMessage)) { EditorGUILayout.HelpBox(m_infoMessage, MessageType.Info); } if (m_scanner.m_scanMap == null) { EditorGUILayout.HelpBox(m_editorUtils.GetTextValue("NoScanDataInfo"), MessageType.Info); GUI.enabled = false; } GUILayout.BeginHorizontal(); Color normalBGColor = GUI.backgroundColor; if (m_settings == null) { m_settings = GaiaUtils.GetGaiaSettings(); } GUI.backgroundColor = m_settings.GetActionButtonColor(); if (m_editorUtils.Button("SaveScan")) { string path = m_scanner.SaveScan(); AssetDatabase.Refresh(); path += ".exr"; Object exportedTexture = AssetDatabase.LoadAssetAtPath(path, typeof(Object)); if (exportedTexture != null) { m_infoMessage = "Scan exported to: " + path; Debug.Log(m_infoMessage); EditorGUIUtility.PingObject(exportedTexture); } } GUI.backgroundColor = normalBGColor; GUI.enabled = true; if (m_editorUtils.Button("Clear")) { m_scanner.Clear(); } GUILayout.EndHorizontal(); GUILayout.Space(5); GUILayout.EndVertical(); GUILayout.Space(5f); m_showRawInfo = m_assumedRawRes > 0; m_showBitDepthWarning = m_rawBitDepth == GaiaConstants.RawBitDepth.Eight; GUI.enabled = originalGUIState; }
public override void OnInspectorGUI() { //Get our resource m_session = (GaiaSession)target; //Set up the box style if (m_boxStyle == null) { m_boxStyle = new GUIStyle(GUI.skin.box); m_boxStyle.normal.textColor = GUI.skin.label.normal.textColor; m_boxStyle.fontStyle = FontStyle.Bold; m_boxStyle.alignment = TextAnchor.UpperLeft; } //Setup the wrap style if (m_wrapStyle == null) { m_wrapStyle = new GUIStyle(GUI.skin.label); m_wrapStyle.wordWrap = true; } //Set up the description wrap style if (m_descWrapStyle == null) { m_descWrapStyle = new GUIStyle(GUI.skin.textArea); m_descWrapStyle.wordWrap = true; } //Create a nice text intro GUILayout.BeginVertical("Gaia Session", m_boxStyle); GUILayout.Space(20); EditorGUILayout.LabelField("Contains the data used to backup, share and play back sessions. Use the session manager to view, edit or play back sessions.", m_wrapStyle); GUILayout.Space(4); GUILayout.EndVertical(); //Make some space GUILayout.Space(4); //Wrap it up in a box GUILayout.BeginVertical(m_boxStyle); GUILayout.BeginVertical("Summary:", m_boxStyle); GUILayout.Space(20); //Display the basic details EditorGUILayout.LabelField("Name", m_session.m_name); EditorGUILayout.LabelField("Description", m_session.m_description, m_wrapStyle); EditorGUILayout.LabelField("Created", m_session.m_dateCreated); EditorGUILayout.LabelField("Dimensions", string.Format("w{0} d{1} h{2} meters", m_session.m_terrainWidth, m_session.m_terrainDepth, m_session.m_terrainHeight)); EditorGUILayout.LabelField("Sea Level", string.Format("{0} meters", m_session.m_seaLevel)); EditorGUILayout.LabelField("Locked", m_session.m_isLocked.ToString()); Texture2D previewImage = m_session.m_previewImage; if (previewImage != null) { //Get aspect ratio and available space and display the image float width = Screen.width - 43f; float height = previewImage.height * (width / previewImage.width); GUILayout.Label(previewImage, GUILayout.MaxWidth(width), GUILayout.MaxHeight(height)); } GUILayout.EndVertical(); //Iterate through the operations GUILayout.BeginVertical("Operations:", m_boxStyle); GUILayout.Space(20); if (m_session.m_operations.Count == 0) { GUILayout.Space(5); GUILayout.Label("No operations yet..."); GUILayout.Space(5); } else { GaiaOperation op; EditorGUI.indentLevel++; for (int opIdx = 0; opIdx < m_session.m_operations.Count; opIdx++) { op = m_session.m_operations[opIdx]; if (op.m_isActive) { op.m_isFoldedOut = EditorGUILayout.Foldout(op.m_isFoldedOut, op.m_description, true); } else { op.m_isFoldedOut = EditorGUILayout.Foldout(op.m_isFoldedOut, op.m_description + " [inactive]", true); } if (op.m_isFoldedOut) { EditorGUI.indentLevel++; EditorGUILayout.LabelField("Description", op.m_description, m_wrapStyle); EditorGUILayout.LabelField("Created", op.m_operationDateTime); EditorGUILayout.LabelField("Active", op.m_isActive.ToString()); EditorGUI.indentLevel--; } } EditorGUI.indentLevel--; } GUILayout.EndVertical(); GUILayout.EndVertical(); if (GUILayout.Button("Play Session")) { GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(false, false); if (gsm == null) { GameObject gaiaObj = GaiaUtils.GetGaiaGameObject(); GameObject mgrObj = new GameObject("Session Manager"); gsm = mgrObj.AddComponent <GaiaSessionManager>(); mgrObj.transform.parent = gaiaObj.transform; } GaiaLighting.SetDefaultAmbientLight(GaiaUtils.GetGaiaSettings().m_gaiaLightingProfile); //make a copy of the session - otherwise there is the danger of conflicting with the old session data while playing back the session GaiaSession sessionCopy = Instantiate(m_session); sessionCopy.m_name = GaiaSessionManager.GetNewSessionName(); sessionCopy.name = sessionCopy.m_name; gsm.m_session = sessionCopy; string path = GaiaDirectories.GetSessionDirectory(); AssetDatabase.CreateAsset(sessionCopy, path + "/" + sessionCopy.m_name + ".asset"); AssetDatabase.SaveAssets(); GaiaSessionManager.PlaySession(sessionCopy); } if (GUILayout.Button("Open Session in Manager")) { GaiaSessionManager.LoadSession(m_session); } }