private Texture2D GetTileImg(AtlasData imageData) { if (_tileImgPool.ContainsKey(imageData.imageName)) { return(_tileImgPool[imageData.imageName]); } var leftTop = new Vector2(imageData.offsetX, imageData.offsetY + imageData.scaleY); var leftBottom = new Vector2(imageData.offsetX, imageData.offsetY); var rightBottom = new Vector2(imageData.offsetX + imageData.scaleX, imageData.offsetY); int x = (int)(_tileAtlasTexture.width * leftBottom.x); int y = (int)(_tileAtlasTexture.height * leftBottom.y); int width = (int)(_tileAtlasTexture.width * (Vector2.Distance(leftBottom, rightBottom))); int height = (int)(_tileAtlasTexture.height * (Vector2.Distance(leftBottom, leftTop))); var tileImg = new Texture2D(width, height); tileImg.SetPixels(_tileAtlasTexture.GetPixels(x, y, width, height)); tileImg.Apply(false); _tileImgPool.Add(imageData.imageName, tileImg); return(tileImg); }
internal static void CacheOldUIData() { AtlasData ad = null; oldIndexAtlasName = new List <string>(); for (int i = 0, count = atlasList.Count; i < count; i++) { ad = atlasList[i]; if (ad != null) { oldIndexAtlasName.Add(ad.atlasName); } } TextureData td = null; oldIndexTextureName = new List <string>(); for (int i = 0, count = textureList.Count; i < count; i++) { td = textureList[i]; if (td != null) { oldIndexTextureName.Add(td.textureName); } } }
public static int Priority(this Item map) { var cleanName = map.CleanName(); if (!MapDict.TryGetValue(cleanName, out var data)) { return(int.MinValue); } if (GeneralSettings.AtlasExplorationEnabled && !data.IgnoredBossroom && !AtlasData.IsCompleted(cleanName)) { return(int.MaxValue); } var priority = data.Priority; if (map.Name.StartsWith("Shaped")) { priority += GeneralSettings.ShapedPriority; } if (AtlasData.IsShaperInfluenced(cleanName)) { priority += GeneralSettings.ShaperInfluencePriority; } if (AtlasData.IsElderInfluenced(cleanName)) { priority += GeneralSettings.ElderInfluencePriority; } return(priority); }
private Texture2D GetPlacedTileImg(AtlasData imageData) { if (_objectPlacedTileImgPool.ContainsKey(imageData.imageName)) { return(_objectPlacedTileImgPool[imageData.imageName]); } var texture = GetTileImg(imageData); Texture2D blendTexture = new Texture2D(texture.width, texture.height); var blendingColor = new Color(1f, 0.5f, 0.5f); for (int i = 0; i < texture.width; ++i) { for (int j = 0; j < texture.height; ++j) { blendTexture.SetPixel(i, j, Color.Lerp(texture.GetPixel(i, j), blendingColor, 0.5f)); } } blendTexture.Apply(); _objectPlacedTileImgPool.Add(imageData.imageName, blendTexture); return(blendTexture); }
private static void ProcessAtlas(UIAtlas atlas, int index, AtlasUnloadType unloadType, float param_f) { if (atlas != null) { if (index < 0 || index >= atlasList.Count) { Debugger.LogError("ui atlas index is invalid->" + index); return; } AtlasData data = atlasList[index]; if (data.atlas == null) { data.atlas = atlas; } else { Debug.LogError("mulitiple load atlas->" + atlas.name); return; } ProcessAtlasUnloadType(data, unloadType, param_f); if (loadCallDic.ContainsKey(index)) { List <System.Action> list = loadCallDic[index]; if (list.Count == 0) { Debugger.LogError("load ui atlas call zero->" + atlas.name + "^" + index); RemoveAtlas(index); return; } if (data.referenceNum < 0) { data.referenceNum = 0; } data.referenceNum += (short)list.Count; System.Action callback = null; for (int i = 0, count = list.Count; i < count; i++) { callback = list[i]; if (callback != null) { callback(); } } list.Clear(); } else { RemoveAtlas(index); Debugger.LogError("load ui atlas call not contains->" + atlas.name); } } else { } }
private static void ProcessAtlasUnloadType(AtlasData atlasData, AtlasUnloadType unloadType, float param_f) { if (atlasData == null) { return; } int curu = (int)(atlasData.unloadType); int newu = (int)unloadType; if (curu >= newu) { return; } atlasData.unloadType = unloadType; if (unloadType == AtlasUnloadType.TIME) { atlasData.beginTime = Time.realtimeSinceStartup; if (param_f > atlasData.intervalTime) { atlasData.intervalTime = param_f; } } }
public static bool ShouldUpgrade(this Item map, Upgrade upgrade) { var tier = map.MapTier; if (GeneralSettings.AtlasExplorationEnabled) { var cleanName = map.CleanName(); if (!AtlasData.IsCompleted(cleanName) && MapDict.TryGetValue(cleanName, out var data) && !data.IgnoredBossroom) { if (tier >= 6 && (upgrade == GeneralSettings.RareUpgrade || upgrade == GeneralSettings.MagicRareUpgrade)) { return(true); } if (tier >= 11 && upgrade == GeneralSettings.VaalUpgrade) { return(true); } } } if (upgrade.TierEnabled && tier >= upgrade.Tier) { return(true); } if (upgrade.PriorityEnabled && map.Priority() >= upgrade.Priority) { return(true); } return(false); }
private void UpdateKeys(AtlasData data) { var oldRegions = _regions; _regions = new Dictionary <string, Region>(data.Items.Count, oldRegions.Comparer); foreach (var item in data.Items) { var keyBounds = new Rectangle(item.X, item.Y, item.Width, item.Height); var texture = _textures[item.Texture]; if (oldRegions.TryGetValue(item.Key, out var existingRegion)) { oldRegions.Remove(item.Key); existingRegion.Set(texture, keyBounds); _regions.Add(item.Key, existingRegion); } else { _regions.Add(item.Key, new Region(item.Key, texture, keyBounds)); } } foreach (var unusedRegion in oldRegions) { unusedRegion.Value.Set(null, Rectangle.Empty); } }
void GenerateAtlas() { GameObject AtlasObject = new GameObject("AtlasData"); AtlasData AD = AtlasObject.AddComponent <AtlasData>(); // backup texture settings per texture settingBackup = new TextureImporterSettings[Textures.Length]; for (int i = 0; i < settingBackup.Length; i++) { settingBackup[i] = getTextureSettings(AssetDatabase.GetAssetPath(Textures[i])); } //Generate texture names and sprite frame sizes (if any) AD.TextureNames = new string[Textures.Length]; AD.frameSizePixels = new Vector2[Textures.Length]; for (int i = 0; i < Textures.Length; i++) { string texPath = AssetDatabase.GetAssetPath(Textures[i]); ConfigureForAtlas(texPath, maxTextureSize); AD.TextureNames[i] = texPath; // set frame size in pixels. (0,0) means is not a sprite AD.frameSizePixels[i] = getFrameSizeFromTextureName(texPath); } //Generate Atlas texture Texture2D tex = new Texture2D(1, 1, TextureFormat.ARGB32, mipmap); // png encode accepts ARGB32 or RGB24 AD.UVs = tex.PackTextures(Textures, Padding, maxAtlasSize); //Generate Unique Asset Path string AssetPath = AssetDatabase.GenerateUniqueAssetPath("Assets/" + path + "/" + AtlasName + ".png"); //Write texture to file byte[] bytes = tex.EncodeToPNG(); System.IO.File.WriteAllBytes(AssetPath, bytes); bytes = null; //Delete generated texture UnityEngine.Object.DestroyImmediate(tex); //Import Asset AssetDatabase.ImportAsset(AssetPath); //Get Imported Texture tex = AssetDatabase.LoadAssetAtPath(AssetPath, typeof(Texture2D)) as Texture2D; //Configure texture as atlas ConfigureForAtlas(AssetDatabase.GetAssetPath(tex), maxAtlasSize); AD.AtlasTexture = tex; // restore read only property per texture for (int i = 0; i < settingBackup.Length; i++) { string texPath = AssetDatabase.GetAssetPath(Textures[i]); setTextureSettings(texPath, settingBackup[i]); } }
private void LoadAtlas(string resPath, SpriteAlignment alignment = SpriteAlignment.Center) { if (!_atlases.ContainsKey(resPath)) { TextAsset xmlAsset = Resources.Load <TextAsset>(resPath); AtlasData atlas = new AtlasData(); XmlDocument document = new XmlDocument(); document.LoadXml(xmlAsset.text); XmlElement root = document.DocumentElement; if (root.Name == "TextureAtlas") { bool failed = false; atlas.texture = Resources.Load <Texture2D>(resPath); int textureHeight = atlas.texture.height; foreach (XmlNode childNode in root.ChildNodes) { if (childNode.Name == "sprite") { try { int width = Convert.ToInt32(childNode.Attributes["w"].Value); int height = Convert.ToInt32(childNode.Attributes["h"].Value); int x = Convert.ToInt32(childNode.Attributes["x"].Value); int y = textureHeight - (height + Convert.ToInt32(childNode.Attributes["y"].Value)); SpriteFrameData spriteMetaData = new SpriteFrameData { border = new Vector4(), name = childNode.Attributes["n"].Value, pivot = GetPivotValue(alignment), rect = new Rect(x, y, width, height) }; atlas.frames.Add(spriteMetaData.name, spriteMetaData); } catch (Exception exception) { failed = true; Debug.LogException(exception); } } else { Debug.Log("Child nodes should be named 'sprite' !"); } } if (!failed) { _atlases.Add(resPath, atlas); } } else { Debug.Log("XML needs to have a 'TextureAtlas' root node!"); } } }
/* *** Private Methods *** */ /// <summary> /// Read and parse atlas data from XML file. /// </summary> private void ImportAtlasData() { XmlDocument xml = new XmlDocument(); xml.LoadXml(atlasDataFile.text); XmlNode frames = xml.DocumentElement.SelectSingleNode("dict/key"); List <AtlasData> data = new List <AtlasData>(); if (frames != null && frames.InnerText == "frames") { XmlNodeList subTextureNames = xml.DocumentElement.SelectNodes("dict/dict/key"); XmlNodeList subTextures = xml.DocumentElement.SelectNodes("dict/dict/dict"); try { for (int si = 0; si < subTextures.Count; si++) { _subTexture = subTextures[si]; AtlasData ad = new AtlasData(); bool rotated = _subTexture.GetBool("rotated"); Rect frame = _subTexture.GetRect("frame"); Rect colorRect = _subTexture.GetRect("sourceColorRect"); Vector2 sourceSize = _subTexture.GetVector2("sourceSize"); try { ad.name = subTextureNames[si].InnerText.Split('.')[0]; } catch (System.Exception) { ad.name = subTextureNames[si].InnerText; } ad.position = new Vector2(frame.xMin, frame.yMin); ad.rotated = rotated; ad.size = new Vector2(colorRect.width, colorRect.height); ad.frameSize = sourceSize; ad.offset = new Vector2(colorRect.xMin, colorRect.yMin); data.Add(ad); } } catch (System.Exception ERR) { Debug.LogError("Atlas Import error!"); Debug.LogError(ERR.Message); } } InitVertices(); spriteData = new SpriteData[data.Count]; SpriteData sprite = null; for (int i = 0; i < data.Count; i++) { sprite = new SpriteData(); sprite.name = data[i].name; sprite.size = data[i].size; sprite.sheetPixelCoords = data[i].position; sprite.texture = texture; sprite.UpdateUVs(); spriteData[i] = sprite; } }
IEnumerator DownloadAnimationRes(string prefabName, AnimationData data, LoadAnimationCallback callback, string aniName) { AssetParam refParam = new AssetParam(); foreach (string atlas in data.refAtlas) { if (!mAtlasReferences.ContainsKey(atlas)) { mAtlasReferences.Add(atlas, new AtlasReferenceData()); } //引用计数 +1 mAtlasReferences[atlas].reference_count += 1; if (CheckAtlasComplete(atlas)) { continue; } AtlasData atlasData = mConfig.AtlasDatas[atlas]; List <AssetPtr> depresList = new List <AssetPtr>(); ///加载字体依赖的贴图 AssetParam atlasparam = new AssetParam(); foreach (string texdep in atlasData.texs) { yield return(AssetManager.Instance.LoadResource(UI_PATH + "Texture/" + texdep + AssetConfig.AssetSuffix, atlasparam)); depresList.Add(atlasparam.asset); } yield return(AssetManager.Instance.LoadResource(UI_PATH + "Atlas/" + atlas + ".ab", refParam)); if (refParam.asset != null) { mAtlasReferences[atlas].resources.Add(refParam.asset); // if (!mTempAssetsHolders.ContainsKey(refParam.asset.Data.url)) // mTempAssetsHolders.Add(refParam.asset.Data.url, refParam.asset); UnityEngine.Object[] objs = refParam.asset.Data.LoadAll(); CacheUIAtlas(objs); } foreach (AssetPtr ptr in depresList) { ptr.Data.UnloadWebStream(); mAtlasReferences[atlas].resources.Add(ptr); // if (!mTempAssetsHolders.ContainsKey(ptr.Data.url)) // mTempAssetsHolders.Add(ptr.Data.url, ptr); } } OnAniLoadComplete(prefabName, callback, aniName); }
void Start() { //read and parse skeleton josn into SkeletonData TextAsset jsonReader = (TextAsset)Resources.Load("skeleton.json", typeof(TextAsset)); TextReader reader = new StringReader(jsonReader.text); Dictionary <String, System.Object> skeletonRawData = Json.Deserialize(reader) as Dictionary <String, System.Object>; SkeletonData skeletonData = ObjectDataParser.ParseSkeletonData(skeletonRawData); //read and parse texture atlas josn into TextureAtlas Texture _textures = Resources.Load <Texture>("texture"); jsonReader = (TextAsset)Resources.Load("texture.json", typeof(TextAsset)); reader = new StringReader(jsonReader.text); Dictionary <String, System.Object> atlasRawData = Json.Deserialize(reader) as Dictionary <String, System.Object>; AtlasData atlasData = AtlasDataParser.ParseAtlasData(atlasRawData); TextureAtlas textureAtlas = new TextureAtlas(_textures, atlasData); //use the above data to make factory UnityFactory factory = new UnityFactory(); factory.AddSkeletonData(skeletonData, skeletonData.Name); factory.AddTextureAtlas(textureAtlas); //add 20 centaur into scene at some random positions. System.Random random = new System.Random(); for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { Armature armature = factory.BuildArmature("centaur/charactor", null, "charactor_all"); armature.AdvanceTime(0f); float r0 = (float)random.NextDouble() + 0.5f; float r1 = 0; //(float)random.NextDouble(); float r2 = (float)random.NextDouble(); ((armature.Display as UnityArmatureDisplay).Display as GameObject).transform.position = new Vector3((float)j + r0 * 20f, 1, r2 * 15f); WorldClock.Clock.Add(armature); armature.Animation.GotoAndPlay("run", -1, -1, 0); } } //add 20 bird into scene at some random positions. for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { Armature armature = factory.BuildArmature("bird/charactor", null, "charactor_all"); armature.AdvanceTime(0f); float r0 = (float)random.NextDouble() + 0.5f; float r1 = (float)random.NextDouble() + 1; float r2 = (float)random.NextDouble(); ((armature.Display as UnityArmatureDisplay).Display as GameObject).transform.position = new Vector3((float)j + r0 * 20f, (float)i * 3f + r1 * 5f, r2 * 15f); WorldClock.Clock.Add(armature); armature.Animation.GotoAndPlay("fly", -1, -1, 0); } } }
//------------------------------------------------ void OnGUI() { //Draw Atlas Object Selector GUILayout.Label("Atlas Generation", EditorStyles.boldLabel); atlasDataObject = (GameObject)EditorGUILayout.ObjectField("Atlas Object", atlasDataObject, typeof(GameObject), true); if (atlasDataObject == null) { return; } atlasDataComponent = atlasDataObject.GetComponent <AtlasData>(); // if no has a valid AtlasData component then exit drawing GUI, until the game object be the correct one if (!atlasDataComponent) { return; } AtlasW = atlasDataComponent.AtlasTexture.width; AtlasH = atlasDataComponent.AtlasTexture.height; PopupIndex = EditorGUILayout.Popup(PopupIndex, atlasDataComponent.TextureNames); if (GUILayout.Button("Select Sprite From Atlas")) { // Selection works when at least one gameObject is selected in the hierarchy if (Selection.gameObjects.Length > 0) { foreach (GameObject Obj in Selection.gameObjects) { // if sprite frame size is (0,0) means it is not a game object with sprite animation. Update the mesh uvs if (Vector2.zero.Equals(atlasDataComponent.frameSizePixels[PopupIndex])) { if (Obj.GetComponent <MeshFilter>()) { UpdateMeshUVs(Obj, atlasDataComponent.UVs[PopupIndex]); } } // its a game object with a sprite anim. Update the animation objects accordingly else { // get AnimateTiledTexture component to update some properties for Atlas configuration AnimateTiledTexture anim = Obj.GetComponentInChildren <AnimateTiledTexture>(); // get all AnimateTiledConfig components to update their properties for Atlas configuration AnimateTiledConfig[] configs = Obj.GetComponentsInChildren <AnimateTiledConfig>(); // for the AnimateTiledTexture component set the total number of rows in the atlas according to the sprite frame's height //anim._rowsTotalInSprite = ; // for all the AnimateTiledConfig components set the properties accordingly } } } } }
public void SetAtlasData(List <Sprite> sprites, Material mat) { atlas = new AtlasData(); atlas.sprites = new List <Sprite>(); for (int i = 0; i < sprites.Count; i++) { atlas.sprites.Add(sprites[i]); } atlas.material = mat; }
public bool ContainsFrame(string resPath, string spriteName) { AtlasData atlas = GetAtlas(resPath); if (atlas != null) { return(atlas.frames.ContainsKey(spriteName)); } return(false); }
public TextureAtlas(Texture texture, AtlasData atlasData) { Name = atlasData.Name; Texture = texture; AtlasData = atlasData; Shader shader = Shader.Find("Transparent/Depth Ordered Unlit"); Material = new Material(shader); Material.mainTexture = texture; }
void _receiver_OnPositionEvent(AtlasData data) { lock (_tracksData) { var target = new VTSAtlasTarget(data.TrackID); target.MMSI = data.MMSI; target.Update(data.Lon, data.Lat, data.SOG, data.COG, DateTime.Now); target.ReceiverTime = data.Time; _tracksData.UpdateDynamicEvent(target); } }
public void GenerateAtlas() { //Generate Atlas Object GameObject AtlasObject = new GameObject("obj_" + AtlasName); AtlasData AtlasComp = AtlasObject.AddComponent <AtlasData>(); //Initialize string array AtlasComp.TextureNames = new string[Textures.Length]; AtlasComp.TexturePaths = new string[Textures.Length]; //Cycle through textures and configure for atlasing for (int i = 0; i < Textures.Length; i++) { //Get asset path string TexturePath = AssetDatabase.GetAssetPath(Textures[i]); //Configure texture ConfigureForAtlas(TexturePath); //Add file name to atlas texture name list AtlasComp.TexturePaths[i] = TexturePath; AtlasComp.TextureNames[i] = Textures[i].name; } //Generate Atlas Texture2D tex = new Texture2D(1, 1, TextureFormat.ARGB32, false); AtlasComp.UVs = tex.PackTextures(Textures, Padding, 4096); //Generate Unique Asset Path string AssetPath = AssetDatabase.GenerateUniqueAssetPath(AtlasPath + AtlasName + ".png"); //Write texture to file byte[] bytes = tex.EncodeToPNG(); System.IO.File.WriteAllBytes(AssetPath, bytes); bytes = null; //Delete generated texture UnityEngine.Object.DestroyImmediate(tex); //Import Asset AssetDatabase.ImportAsset(AssetPath); //Get Imported Texture AtlasComp.AtlasTexture = AssetDatabase.LoadAssetAtPath(AssetPath, typeof(Texture2D)) as Texture2D; //Configure texture as atlas ConfigureForAtlas(AssetDatabase.GetAssetPath(AtlasComp.AtlasTexture)); //Now create prefab from atlas object AssetPath = AssetDatabase.GenerateUniqueAssetPath(AtlasPath + "atlasdata_" + AtlasName + ".prefab"); //Create prefab object Object prefab = PrefabUtility.CreateEmptyPrefab(AssetPath); //Update prefab and save PrefabUtility.ReplacePrefab(AtlasObject, prefab, ReplacePrefabOptions.ConnectToPrefab); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); //Destroy original object DestroyImmediate(AtlasObject); }
private static void SetAtlas(UISpriteData data, bool set) { if (set) { AtlasData atlasData = atlasList[data.index]; data.sprite.atlas = atlasData.atlas; data.sprite.Update(); } else { data.sprite.atlas = null; } }
//生成纹理图集的函数 public void GenerateAtlas() { //生成图集对象 GameObject AtlasObject = new GameObject("obj_" + AtlasName); AtlasData AtlasComp = AtlasObject.AddComponent <AtlasData>(); AtlasComp.TextureNames = new string[Textures.Length]; //使用循环配置每一个要加入到图集的纹理 for (int i = 0; i < Textures.Length; i++) { //获取纹理在资源中的路径 string TexturePath = AssetDatabase.GetAssetPath(Textures[i]); //修改纹理的设置信息 ConfigureForAtlas(TexturePath); //将所有纹理的名字都加入到列表中 AtlasComp.TextureNames[i] = TexturePath; } //生成纹理图集 Texture2D tex = new Texture2D(1, 1, TextureFormat.ARGB32, false); //PackTextures()用于打包多个纹理为一个纹理 AtlasComp.UVs = tex.PackTextures(Textures, Padding, 4096); //生成唯一的资源路径 string AssetPath = AssetDatabase.GenerateUniqueAssetPath("Assets/" + AtlasName + ".png"); //把纹理图集保存成文件 byte[] bytes = tex.EncodeToPNG(); System.IO.File.WriteAllBytes(AssetPath, bytes); bytes = null; //删除生成的纹理图集 UnityEngine.Object.DestroyImmediate(tex); //导入纹理资源 AssetDatabase.ImportAsset(AssetPath); //获取导入的纹理 AtlasComp.AtlasTexture = AssetDatabase.LoadAssetAtPath(AssetPath, typeof(Texture2D)) as Texture2D; //配置纹理图集 ConfigureForAtlas(AssetDatabase.GetAssetPath(AtlasComp.AtlasTexture)); AssetPath = AssetDatabase.GenerateUniqueAssetPath("Assets/atlasdata_" + AtlasName + ".prefab"); //创建预置对象 Object prefab = PrefabUtility.CreateEmptyPrefab(AssetPath); //更新、保存预置对象 PrefabUtility.ReplacePrefab(AtlasObject, prefab, ReplacePrefabOptions.ConnectToPrefab); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); //销毁原来的对象 DestroyImmediate(AtlasObject); }
public void AddRef(Image image, AtlasData ad) { if (m_refences.ContainsKey(image)) { --m_refences [image].ReferenceCount; m_refences [image] = ad; } else { m_refences.Add(image, ad); } ++ad.ReferenceCount; }
internal static void SceneLoadProcessAtlases() { AtlasData data = null; for (int i = 0, count = atlasList.Count; i < count; i++) { data = atlasList[i]; if (data.unloadType == AtlasUnloadType.SCENELOAD) { data.referenceNum = 0; _DeleteAtlas(data); } } }
private static void BeforeInit() { //prev atlas AtlasData ad = null; tempAtlasList = new List <AtlasData>(); for (int i = 0, count = atlasList.Count; i < count; i++) { ad = atlasList[i]; if (ad != null && ad.referenceNum > 0) { tempAtlasList.Add(ad); } } UnloadData uld; for (int i = 0, count = unloadList.Count; i < count; i++) { uld = unloadList[i]; if (uld != null && uld.count > 0) { ResLoader.RemoveAssetCacheByName(uld.data.atlasName); } } tempTextureList = new List <TextureData>(); TextureData td = null; //prev texture for (int i = 0, count = textureList.Count; i < count; i++) { td = textureList[i]; if (td != null && td.referenceNum > 0) { tempTextureList.Add(td); } } UnloadTexData ultd = null; for (int i = 0, count = unloadTexList.Count; i < count; i++) { ultd = unloadTexList[i]; if (ultd != null && ultd.count > 0) { ResLoader.RemoveAssetCacheByName(ultd.data.textureName, false, false); } } }
public static void AtlasCreate() { string[] guids = Selection.assetGUIDs; for (int i = 0; i < guids.Length; i++) { string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); Debug.Log(assetPath); string dictPath = Application.dataPath.Replace("Assets", assetPath); DirectoryInfo Dir = new DirectoryInfo(dictPath); string resPath = UGUIConfig.SpriteDir + Dir.Name; if (!Directory.Exists(resPath)) { Directory.CreateDirectory(resPath); } FileInfo[] infos = Dir.GetFiles("*.png"); if (infos.Length > 0) { string dicPath = infos[0].ToString().Remove(0, infos[0].ToString().IndexOf("Assets")).Replace("\\", "/"); AtlasData atlasData = ScriptableObject.CreateInstance <AtlasData>(); atlasData.spDataList = new List <SpriteData>(); foreach (FileInfo f in infos) //查找文件 { int index = f.ToString().IndexOf("Assets"); string modPath = f.ToString().Remove(0, index); modPath = modPath.Replace("\\", "/"); TextureImporter texImport = AssetImporter.GetAtPath(modPath) as TextureImporter; texImport.textureType = TextureImporterType.Sprite; texImport.spritePackingTag = new DirectoryInfo(Path.GetDirectoryName(modPath)).Name; texImport.mipmapEnabled = false; AssetDatabase.ImportAsset(modPath); Sprite sprite = AssetDatabase.LoadAssetAtPath(modPath, typeof(Sprite)) as Sprite; SpriteData data = new SpriteData(sprite.name, sprite); atlasData.spDataList.Add(data); } string prePath = resPath + "/" + new DirectoryInfo(Path.GetDirectoryName(dicPath)).Name + ".asset"; prePath = prePath.Substring(prePath.IndexOf("Assets")); AssetDatabase.CreateAsset(atlasData, prePath); AssetDatabase.Refresh(); } else { Debug.LogError("文件夹下没有png文件!"); return; } } }
private void SaveJson(Rect[] rectInfos) { if (rectInfos == null) { return; } List <AtlasData> _rects = new List <AtlasData>(); for (int i = 0; i < rectInfos.Length; ++i) { if (_targetTextures[i] != null) { var info = new AtlasData(); info.imageName = _targetTextures[i].name; info.offsetX = rectInfos[i].x; info.offsetY = rectInfos[i].y; info.scaleX = rectInfos[i].width; info.scaleY = rectInfos[i].height; _rects.Add(info); } } AtlasDataList atlasInfo = new AtlasDataList(); atlasInfo.name = _atlasName; atlasInfo.infos = _rects.ToArray(); string json = JsonUtility.ToJson(atlasInfo); string resultPath = GetResultPath(eAtlasType.JSON); if (resultPath == null || resultPath == string.Empty) { return; } try { var file = File.Open(resultPath, FileMode.Create, FileAccess.Write); var binary = new BinaryWriter(file); binary.Write(json.ToCharArray()); file.Close(); } catch (IOException e) { EditorUtility.DisplayDialog("Save", e.ToString(), "Ok"); } }
private void onPositionData(int trackID, int lat, int lon, int sog, int cog, int timeStamp) { AtlasData ad = new AtlasData(trackID); ad.Time = DateTime.Now; ad.Shape = new GeoPointShape(lon / 600000.0, lat / 600000.0); ad.SOG = sog / 10.0; ad.COG = cog / 10.0; ad.TimeStamp = timeStamp; ad.Time = DateTime.Now; if (OnReceivedData != null) { OnReceivedData(ad); } }
private static AtlasData FindAtlasData(string name) { AtlasData ad = null; for (int i = 0, count = atlasList.Count; i < count; i++) { ad = atlasList[i]; if (ad != null && ad.atlasName == name) { return(ad); } } return(null); }
private Texture2D[] LoadTextures(AtlasData data, ProgressDelegate onProgress) { var textures = new Texture2D[data.Textures.Length]; for (int i = 0; i < textures.Length; i++) { string file = $"{_atlasCacheDirectory.FullName}/{data.Textures[i]}"; using (var fs = new FileStream(file, FileMode.Open)) //using (var ds = new DeflateStream(fs, CompressionMode.Decompress)) textures[i] = Texture2D.FromStream(_graphicsDevice, fs); onProgress?.Invoke((i + 1) / textures.Length); } return(textures); }
private static void _DeleteAtlas(AtlasData data) { if (data.atlas != null) { data.atlas = null; } if (!atlasIndexToName.ContainsKey(data.index)) { Debugger.LogError("delete ui atlas index to name not find->" + data.index); return; } string name = atlasIndexToName[data.index]; ResLoader.RemoveAssetCacheByName(name, true, true); }
void OnGUI() { // 绘制纹理图集选择器 GUILayout.Label("Atlas Generation",EditorStyles.boldLabel); AtlasDataObject = (GameObject)EditorGUILayout.ObjectField ("Atlas Object",AtlasDataObject,typeof(GameObject),true); // 如果没有可用的纹理图集对象,则取消 if(AtlasDataObject == null){ return; } // 获取纹理预置对象的 atlas data 组件 AtlasDataComponent = AtlasDataObject.GetComponent<AtlasData>(); if (!AtlasDataComponent) { return; } // 显示弹出的选择器,选择可用的纹理 ModeIndex = EditorGUILayout.Popup(ModeIndex,Modes); if (ModeIndex != 1) { // 弹出当前可用的纹理的选择器 PopupIndex = EditorGUILayout.Popup (PopupIndex, AtlasDataComponent.TextureNames); // 点击按钮 if(GUILayout.Button("Select From Atlas")){ // 开始设置选中的网格对象的UV坐标 if(Selection.gameObjects.Length > 0){ foreach (GameObject obj in Selection.gameObjects) { // 确认是否是网格对象 if(obj.GetComponent<MeshFilter>()){ UpdateUVs (obj,AtlasDataComponent.UVs[PopupIndex]); } } } } } else { // select UVs GUILayout.Label("X"); CustomRect.x = EditorGUILayout.FloatField(CustomRect.x); GUILayout.Label ("Y"); CustomRect.y = EditorGUILayout.FloatField (CustomRect.y); GUILayout.Label ("Width"); CustomRect.width = EditorGUILayout.FloatField (CustomRect.width); GUILayout.Label ("Height"); CustomRect.height = EditorGUILayout.FloatField (CustomRect.height); // 点击按钮 if(GUILayout.Button("Select From Atlas")){ // 开始设置选中的网格对象的UV坐标 if(Selection.gameObjects.Length > 0){ foreach (GameObject obj in Selection.gameObjects) { // 确认是否为网格对象 if(obj.GetComponent<MeshFilter>()){ UpdateUVs (obj,CustomRect); } } } } } }
/// <summary> /// Import atlasData from sparrow xml /// </summary> protected AtlasData[] Import() { if (!ValidXML()) return new AtlasData[] { }; List<AtlasData> data = new List<AtlasData>(); if (xml.DocumentElement.Name == "plist") { XmlNode frames = xml.DocumentElement.SelectSingleNode("dict/key"); if (frames != null && frames.InnerText == "frames") { XmlNodeList subTextureNames = xml.DocumentElement.SelectNodes("dict/dict/key"); XmlNodeList subTextures = xml.DocumentElement.SelectNodes("dict/dict/dict"); try { for (int si = 0; si < subTextures.Count; si++) { subTexture = subTextures[si]; AtlasData ad = new AtlasData(); bool rotated = GetBool("rotated"); Rect frame = GetRect("frame"); Rect colorRect = GetRect("sourceColorRect"); Vector2 sourceSize = GetVector2("sourceSize"); try { ad.name = subTextureNames[si].InnerText.Split('.')[0]; } catch (System.Exception) { ad.name = subTextureNames[si].InnerText; } ad.position = new Vector2(frame.xMin, frame.yMin); if (rotated) ad.rotated = true; ad.size = new Vector2(colorRect.width, colorRect.height); ad.frameSize = sourceSize; ad.offset = new Vector2(colorRect.xMin, colorRect.yMin); data.Add(ad); } } catch (System.Exception ERR) { Debug.LogError("Orthello : Cocos2D Atlas Import error!"); Debug.LogError(ERR.Message); } } } return data.ToArray(); }
public static FrameData[] GetFrames(AtlasData[] atlasData, Texture texture) { if ((atlasData == null) || (texture == null)) { Debug.LogError(" can't find atlas data or texture, please check it!!"); return new FrameData[] { }; } Vector2 texSize = Vector2.zero; if (Vector2.Equals(texSize, Vector2.zero) && texture != null) texSize = new Vector2(texture.width, texture.height); // convert atlasData to frames FrameData[] frames = new FrameData[atlasData.Length]; for (int a = 0; a < atlasData.Length; a++) { AtlasData data = atlasData[a]; FrameData frame = new FrameData(); frame.name = data.name; frame.offset = Vector2.zero; frame.size = data.frameSize; Vector2 vOffset = new Vector2(data.offset.x / frame.size.x, data.offset.y / frame.size.y); Vector2 vSize = new Vector2(data.size.x / frame.size.x, data.size.y / frame.size.y); Vector3 tl = new Vector3(((1f / 2f) * -1) + vOffset.x, (1f / 2f) - vOffset.y, 0); frame.vertices = new Vector3[] { tl, tl + new Vector3(vSize.x,0,0), tl + new Vector3(vSize.x,vSize.y * -1,0), tl + new Vector3(0,vSize.y * -1,0) }; frame.imageSize = data.frameSize; frame.uv = new Vector2[4]; float sx = data.position.x / texSize.x; float sy = 1 - ((data.position.y + data.size.y) / texSize.y); float scx = data.size.x / texSize.x; float scy = data.size.y / texSize.y; if (data.rotated) { sy = 1 - ((data.position.y + data.size.x) / texSize.y); scx = data.size.y / texSize.x; scy = data.size.x / texSize.y; frame.uv[3] = new Vector2(sx, sy + scy); frame.uv[0] = new Vector2(sx + scx, sy + scy); frame.uv[1] = new Vector2(sx + scx, sy); frame.uv[2] = new Vector2(sx, sy); } else { frame.uv[0] = new Vector2(sx, sy + scy); frame.uv[1] = new Vector2(sx + scx, sy + scy); frame.uv[2] = new Vector2(sx + scx, sy); frame.uv[3] = new Vector2(sx, sy); } frames[a] = frame; } return frames; }
/* *** Private Methods *** */ /// <summary> /// Read and parse atlas data from XML file. /// </summary> private void ImportAtlasData() { XmlDocument xml = new XmlDocument(); xml.LoadXml(atlasDataFile.text); XmlNode frames = xml.DocumentElement.SelectSingleNode("dict/key"); List<AtlasData> data = new List<AtlasData>(); if (frames != null && frames.InnerText == "frames") { XmlNodeList subTextureNames = xml.DocumentElement.SelectNodes("dict/dict/key"); XmlNodeList subTextures = xml.DocumentElement.SelectNodes("dict/dict/dict"); try { for (int si = 0; si < subTextures.Count; si++) { _subTexture = subTextures[si]; AtlasData ad = new AtlasData(); bool rotated = _subTexture.GetBool("rotated"); Rect frame = _subTexture.GetRect("frame"); Rect colorRect = _subTexture.GetRect("sourceColorRect"); Vector2 sourceSize = _subTexture.GetVector2("sourceSize"); try { ad.name = subTextureNames[si].InnerText.Split('.')[0]; } catch (System.Exception) { ad.name = subTextureNames[si].InnerText; } ad.position = new Vector2(frame.xMin, frame.yMin); ad.rotated = rotated; ad.size = new Vector2(colorRect.width, colorRect.height); ad.frameSize = sourceSize; ad.offset = new Vector2(colorRect.xMin, colorRect.yMin); data.Add(ad); } } catch (System.Exception ERR) { Debug.LogError("Atlas Import error!"); Debug.LogError(ERR.Message); } } InitVertices(); spriteData = new SpriteData[data.Count]; SpriteData sprite = null; for (int i = 0; i < data.Count; i++) { sprite = new SpriteData(); sprite.name = data[i].name; sprite.size = data[i].size; sprite.sheetPixelCoords = data[i].position; sprite.texture = texture; sprite.UpdateUVs(); spriteData[i] = sprite; } }