public void Remove(SpriteElement element) { if (m_Children.IndexOf(element) > -1) { m_Children.Remove(element); } GameObject.Destroy(element.gameObject); }
public static SpriteElement DrawSpriteBox(Texture2D texture, Vector4 destination, BoxSpriteBounds spriteBounds, float edgeScale) { var allVerts = new List <VertVT>(); float[] BoxSizeX = new float[] { (spriteBounds.GetColumnSize(0) / spriteBounds.Width) * edgeScale, 0, (spriteBounds.GetColumnSize(2) / spriteBounds.Width) * edgeScale }; BoxSizeX[1] = destination.Z - BoxSizeX[0] - BoxSizeX[2]; float[] BoxSizeY = new float[] { (spriteBounds.GetRowSize(0) / spriteBounds.Height) * edgeScale, 0, (spriteBounds.GetRowSize(2) / spriteBounds.Height) * edgeScale }; BoxSizeY[1] = destination.W - BoxSizeY[0] - BoxSizeY[2]; float[] BoxPosX = new float[] { destination.X, destination.X + BoxSizeX[0], destination.X + BoxSizeX[0] + BoxSizeX[1] }; float[] BoxPosY = new float[] { destination.Y, destination.Y + BoxSizeY[0], destination.Y + BoxSizeY[0] + BoxSizeY[1] }; for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) { var boxSpriteBounds = spriteBounds.GetRegionBounds(x, y); if (boxSpriteBounds.Width > 0 && boxSpriteBounds.Height > 0) { var boxVerts = GetElementVertices( new Vector4(BoxPosX[x], BoxPosY[y], BoxSizeX[x], BoxSizeY[y]), boxSpriteBounds); allVerts.AddRange(boxVerts); } } } var sprite = new SpriteElement() { Texture = texture, Offset = VertexList.Count, ElemCount = allVerts.Count }; SpritesToRender.Add(sprite); VertexList.AddRange(allVerts); return(sprite); }
SpriteElement GenerateItem(String img, int center, int top, int width, int height, int frames) { var image = new SpriteElement(img, frames, width, height); image.Style.Position = NativeWebView.HTML.CSS.Attributes.ElementPositions.position_absolute; image.Style.Display = Display.none; image.Style.Left = center - (width / 2); image.Style.Top = top; return(image); }
public void Add(SpriteElement element, Vector2 localPos) { if (m_Children.IndexOf(element) > -1) { m_Children.Remove(element); } m_Children.Add(element); element.transform.SetParent(transform); element.transform.localPosition = localPos; element.transform.localRotation = Quaternion.identity; }
public static int UpdateZSort(SpriteElement rootElement) { int order = rootElement.GetSortOrder(); for (int i = 0; i < rootElement.m_Children.Count; ++i) { SpriteElement child = rootElement.m_Children[i]; child.SetSortOrder(++order); order = UpdateZSort(child); } return(order); }
public static void JustSaveNew(SpriteElement spriteElement, string texturePath) { #region Write New File byte[] byt = spriteElement.texture.EncodeToPNG(); if (texturePath != "") { System.IO.File.WriteAllBytes(texturePath, byt); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); } AssetDatabase.ImportAsset(texturePath); Texture2D mainTexture = AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D)) as Texture2D; TextureImporter ti = AssetImporter.GetAtPath(texturePath) as TextureImporter; TextureImporterSettings settings = new TextureImporterSettings(); ti.ReadTextureSettings(settings); SpriteMetaData[] lstMetaSprite = new SpriteMetaData[1]; SpriteMetaData metaSprite = new SpriteMetaData(); metaSprite.name = spriteElement.name; metaSprite.rect = spriteElement.GetSpriteRect(); metaSprite.pivot = spriteElement.pivot; metaSprite.alignment = spriteElement.alignment; lstMetaSprite[0] = metaSprite; ti.isReadable = true; ti.mipmapEnabled = false; ti.spritesheet = lstMetaSprite; ti.textureType = TextureImporterType.Sprite; ti.spriteImportMode = SpriteImportMode.Multiple; ti.spritePixelsPerUnit = 100; settings.textureFormat = TextureImporterFormat.ARGB32; settings.npotScale = TextureImporterNPOTScale.None; settings.alphaIsTransparency = true; ti.SetTextureSettings(settings); ti.maxTextureSize = 4096; ti.mipmapEnabled = false; ti.spriteImportMode = SpriteImportMode.Multiple; AssetDatabase.ImportAsset(texturePath); EditorUtility.SetDirty(mainTexture); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); AssetDatabase.ImportAsset(texturePath); #endregion }
//this will be called once this game state is up and running. public void Initalise(IGameStateManager stateManager) { this.stateManager = stateManager; //create the sprites, which will bounce around the screen //sprite drawer this.spriteElement = new SpriteElement(); //the sprite positions / velocities for (int i = 0; i < SpriteCount; i++) { this.spritePosition[i] = new Vector2((float)rand.NextDouble() * stateManager.Application.WindowWidth * 0.25f, (float)rand.NextDouble() * stateManager.Application.WindowHeight * 0.25f); this.spriteVelocity[i] = new Vector2((float)rand.NextDouble() * 2000 - 1000, (float)rand.NextDouble() * 2000 - 1000); //add a sprite for each to the sprite drawer this.spriteElement.AddSprite(spritePosition[i], new Vector2(1.5f, 1.5f)); } }
void UpdateSprites(bool clear) { if (clear) { _Sprites.Clear(); } Dictionary <string, SpriteElement> newSprites = new Dictionary <string, SpriteElement>(); if (_SpriteTarget != null) { string atlasPath = AssetDatabase.GetAssetPath(_SpriteTarget.GetInstanceID()); TextureImporter textureImporter = AssetImporter.GetAtPath(atlasPath) as TextureImporter; foreach (SpriteMetaData sprite in textureImporter.spritesheet) { string name = sprite.name; SpriteElement spriteElement = null; if (_Sprites.TryGetValue(name, out spriteElement)) { if (spriteElement.action == SpriteAction.Delete) { spriteElement.action = SpriteAction.Delete; } else { spriteElement.action = SpriteAction.None; } } else { spriteElement = new SpriteElement(); spriteElement.tex = null; spriteElement.action = SpriteAction.None; } spriteElement.meta = sprite; newSprites.Add(name, spriteElement); } } foreach (Object obj in Selection.objects) { Texture2D tex = obj as Texture2D; if (tex == null || tex == _SpriteTarget) { continue; } SpriteElement spriteElement = null; string name = tex.name; if (newSprites.TryGetValue(name, out spriteElement)) { spriteElement.tex = tex; spriteElement.action = SpriteAction.Update; } else { spriteElement = new SpriteElement(); spriteElement.tex = tex; spriteElement.action = SpriteAction.Add; spriteElement.meta = new SpriteMetaData(); spriteElement.meta.name = name; newSprites.Add(name, spriteElement); } } _Sprites = newSprites; }
void OnGUI() { GUILayout.BeginHorizontal(); bool create = false; if (_SpriteTarget == null) { if (_Sprites.Count == 0) { GUI.enabled = false; } create = GUILayout.Button("Create", GUILayout.Width(76f)); if (_Sprites.Count == 0) { GUI.enabled = true; } _SpriteTextureName = EditorGUILayout.TextField(_SpriteTextureName); } else { create = GUILayout.Button("Replace", GUILayout.Width(76f)); GUI.enabled = false; EditorGUILayout.TextField(_SpriteTarget.name); GUI.enabled = true; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Atlas", GUILayout.Width(76f)); bool changeSpriteTarget = false; Texture2D spriteTarget = EditorGUILayout.ObjectField(_SpriteTarget, typeof(Texture2D), false) as Texture2D; if (spriteTarget != _SpriteTarget) { if (spriteTarget != null) { TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(spriteTarget)) as TextureImporter; if (textureImporter != null && textureImporter.textureType == TextureImporterType.Sprite) { _SpriteTarget = spriteTarget; changeSpriteTarget = true; } } else { _SpriteTarget = spriteTarget; changeSpriteTarget = true; } } UpdateSprites(changeSpriteTarget); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Padding", GUILayout.Width(76f)); _Padding = Mathf.Clamp(EditorGUILayout.IntField(_Padding, GUILayout.Width(50f)), 0, 10); GUILayout.EndHorizontal(); if (create) { UpdateTexture(); } if (_Sprites.Count > 0) { EditorGUILayout.Separator(); EditorGUILayout.LabelField("Sprites"); GUILayout.BeginVertical(); _ScrollPos = GUILayout.BeginScrollView(_ScrollPos); foreach (KeyValuePair <string, SpriteElement> pair in _Sprites) { string name = pair.Key; SpriteElement sprite = pair.Value; GUI.backgroundColor = Color.white; GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f)); GUILayout.Label(name, GUILayout.Height(20f)); switch (sprite.action) { case SpriteAction.None: if (GUILayout.Button("Delete", GUILayout.Width(60f))) { sprite.action = SpriteAction.Delete; } break; case SpriteAction.Add: GUI.backgroundColor = Color.green; GUILayout.Box("Add", GUILayout.Width(60f)); GUI.backgroundColor = Color.white; break; case SpriteAction.Update: GUI.backgroundColor = Color.yellow; GUILayout.Box("Update", GUILayout.Width(60f)); GUI.backgroundColor = Color.white; break; case SpriteAction.Delete: GUI.backgroundColor = Color.red; if (GUILayout.Button("Delete", GUILayout.Width(60f))) { sprite.action = SpriteAction.None; } GUI.backgroundColor = Color.white; break; } GUILayout.EndHorizontal(); GUI.backgroundColor = Color.white; } GUILayout.EndScrollView(); GUILayout.EndVertical(); } else { EditorGUILayout.HelpBox("Please select one or more textures in the Project View window.", MessageType.Info); } }
void UpdateTexture() { Texture2D tex = new Texture2D(1, 1, TextureFormat.ARGB32, false); List <Texture2D> spriteTexs = new List <Texture2D>(); List <SpriteMetaData> spritesheet = new List <SpriteMetaData>(); List <string> deleteSprites = new List <string>(); if (_SpriteTarget != null) { string path = AssetDatabase.GetAssetPath(_SpriteTarget.GetInstanceID()); SetTextureSetting(path, true); _SpriteTarget = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D; } foreach (KeyValuePair <string, SpriteElement> pair in _Sprites) { string name = pair.Key; SpriteElement sprite = pair.Value; switch (sprite.action) { case SpriteAction.None: { if (sprite.tex == null) { int x = (int)sprite.meta.rect.x; int y = (int)sprite.meta.rect.y; int width = (int)sprite.meta.rect.width; int height = (int)sprite.meta.rect.height; sprite.tex = new Texture2D(width, height, TextureFormat.ARGB32, false); sprite.tex.SetPixels(_SpriteTarget.GetPixels(x, y, width, height)); sprite.tex.Apply(); } sprite.action = SpriteAction.None; spritesheet.Add(sprite.meta); spriteTexs.Add(sprite.tex); } break; case SpriteAction.Add: { spritesheet.Add(sprite.meta); string path = AssetDatabase.GetAssetPath(sprite.tex.GetInstanceID()); SetTextureSetting(path, true); sprite.tex = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D; sprite.action = SpriteAction.None; spriteTexs.Add(sprite.tex); } break; case SpriteAction.Update: { spritesheet.Add(sprite.meta); string path = AssetDatabase.GetAssetPath(sprite.tex.GetInstanceID()); SetTextureSetting(path, true); sprite.tex = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D; sprite.action = SpriteAction.None; spriteTexs.Add(sprite.tex); } break; case SpriteAction.Delete: { deleteSprites.Add(name); } break; } } int maxSize = Mathf.Min(SystemInfo.maxTextureSize, 2048); Rect[] rects = tex.PackTextures(spriteTexs.ToArray(), _Padding, maxSize); bool newTexture = (_SpriteTarget == null); string newPath; if (newTexture) { newPath = "Assets/" + _SpriteTextureName + ".png"; } else { newPath = AssetDatabase.GetAssetPath(_SpriteTarget.GetInstanceID()); } byte[] bytes = tex.EncodeToPNG(); System.IO.File.WriteAllBytes(newPath, bytes); bytes = null; AssetDatabase.SaveAssets(); if (newTexture) { AssetDatabase.Refresh(); } TextureImporter textureImporter = AssetImporter.GetAtPath(newPath) as TextureImporter; textureImporter.textureType = TextureImporterType.Sprite; textureImporter.spriteImportMode = SpriteImportMode.Multiple; for (int i = 0; i < spriteTexs.Count; ++i) { SpriteMetaData metaData = spritesheet[i]; Rect rect = rects[i]; rect.x *= tex.width; rect.y *= tex.height; rect.width *= tex.width; rect.height *= tex.height; metaData.rect = rect; spritesheet[i] = metaData; } textureImporter.spritesheet = spritesheet.ToArray(); SetTextureSetting(textureImporter, false); AssetDatabase.ImportAsset(newPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); _SpriteTarget = AssetDatabase.LoadAssetAtPath(newPath, typeof(Texture2D)) as Texture2D; AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); foreach (string name in deleteSprites) { _Sprites.Remove(name); } UpdateSprites(true); spriteTexs.Clear(); UnityEditor.EditorUtility.UnloadUnusedAssets(); }
public SpriteElement Request(string path) { if (m_inUsed.TryGetValue(path, out var element)) { element.Trigger(); return(element); } if (m_freeList.TryGetValue(path, out element)) { m_freeList.Remove(path); m_inUsed.Add(path, element); element.Trigger(); return(element); } var packed = true; if (m_notInUsed.Count > 0) { element = m_notInUsed[m_notInUsed.Count - 1]; m_notInUsed.RemoveAt(m_notInUsed.Count - 1); } else if (m_freeList.Count > 0) { element = m_freeList.Dequeue(); } else { packed = false; element = new SpriteElement(null); } element.Path = path; if (packed) { m_inUsed[path] = element; } var loadHandle = AssetService.Get().LoadAsync(path, typeof(TextAsset)); loadHandle.OnComplete += handle => { if (handle.Result.AssetStatus != AssetRefObject.AssetStatus.DONE) { return; } var assetRef = handle.Result; var textAsset = assetRef.GetTextAsset(); var texture = new Texture2D(m_spriteSize, m_spriteSize); texture.LoadImage(textAsset.bytes, false); assetRef.Dispose(); if (m_spriteSize != texture.width || m_spriteSize != texture.height) { Object.Destroy(texture); Debug.LogError($"Texture {path} size : {texture.width} x {texture.height} not match request : {m_spriteSize}"); } else { if (packed) { var iconColors = texture.GetPixels32(); var rect = element.Sprite.rect; m_packTexture.SetPixels32((int)rect.x, (int)rect.y, m_spriteSize, m_spriteSize, iconColors); m_packTexture.Apply(); Object.Destroy(texture); } else { Debug.LogWarning($"Not empty space for {path}. Create an independent sprite."); var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero); element.Sprite = sprite; } element.Trigger(); } }; return(element); }
void UpdateSprites(bool clear) { if( clear ) { _Sprites.Clear (); } Dictionary<string,SpriteElement> newSprites=new Dictionary<string,SpriteElement>(); if( _SpriteTarget!=null ) { string atlasPath = AssetDatabase.GetAssetPath( _SpriteTarget.GetInstanceID() ); TextureImporter textureImporter = AssetImporter.GetAtPath( atlasPath ) as TextureImporter; foreach( SpriteMetaData sprite in textureImporter.spritesheet ) { string name = sprite.name; SpriteElement spriteElement = null; if( _Sprites.TryGetValue( name,out spriteElement ) ) { if( spriteElement.action == SpriteAction.Delete ) { spriteElement.action = SpriteAction.Delete; } else { spriteElement.action = SpriteAction.None; } } else { spriteElement = new SpriteElement(); spriteElement.tex = null; spriteElement.action = SpriteAction.None; } spriteElement.meta = sprite; newSprites.Add( name,spriteElement ); } } foreach( Object obj in Selection.objects ) { Texture2D tex = obj as Texture2D; if( tex ==null || tex == _SpriteTarget ) { continue; } SpriteElement spriteElement=null; string name = tex.name; if( newSprites.TryGetValue( name,out spriteElement ) ) { spriteElement.tex = tex; spriteElement.action = SpriteAction.Update; } else { spriteElement = new SpriteElement(); spriteElement.tex = tex; spriteElement.action = SpriteAction.Add; spriteElement.meta = new SpriteMetaData(); spriteElement.meta.name = name; newSprites.Add( name,spriteElement ); } } _Sprites = newSprites; }
// Update is called once per frame void Update() { SpriteElement.UpdateZSort(m_Root); }
// アトラステクスチャの更新を実行する private void BuildAtlas(Texture2D tAtlas) { Texture2D tTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false); List <SpriteMetaData> tSpriteSheetList = new List <SpriteMetaData>(); List <Texture2D> tSpriteTextureList = new List <Texture2D>(); List <string> tDeleteSpriteList = new List <string>(); string tPath; // 元の状態を保存する(バックアップが必要な項目) TextureImporterCompression tAtlasFormat = TextureImporterCompression.Uncompressed; TextureImporterNPOTScale tAtlasNPOtScale = TextureImporterNPOTScale.None; if (tAtlas != null) { // 既に作成済みのアトラスの更新 tPath = AssetDatabase.GetAssetPath(tAtlas.GetInstanceID()); SetTextureSetting(tPath, true, ref tAtlasFormat, ref tAtlasNPOtScale); // 書き込み属性を有効にする tAtlas = AssetDatabase.LoadAssetAtPath(tPath, typeof(Texture2D)) as Texture2D; } foreach (KeyValuePair <string, SpriteElement> tSpriteElementKeyValue in m_SpriteElementHash) { string tName = tSpriteElementKeyValue.Key; SpriteElement tSpriteElement = tSpriteElementKeyValue.Value; Texture2D tElementTexture; int x, y, w, h; switch (tSpriteElement.action) { // アトラススプライトに内包される領域 case SpriteAction.None: tSpriteSheetList.Add(tSpriteElement.metaData); x = ( int )tSpriteElement.metaData.rect.x; y = ( int )tSpriteElement.metaData.rect.y; w = ( int )tSpriteElement.metaData.rect.width; h = ( int )tSpriteElement.metaData.rect.height; tElementTexture = new Texture2D(w, h, TextureFormat.ARGB32, false); tElementTexture.SetPixels(tAtlas.GetPixels(x, y, w, h)); tElementTexture.Apply(); tSpriteTextureList.Add(tElementTexture); break; // 新規追加 case SpriteAction.Add: tSpriteSheetList.Add(tSpriteElement.metaData); tPath = AssetDatabase.GetAssetPath(tSpriteElement.texture.GetInstanceID()); // 読み込む前にフォーマットを強制的に ARGB32 NPOT にしてやる(アルファテクスチャなどだとオリジナルの状態が正しく読み込めない) SetTextureSetting(tPath, true, ref tSpriteElement.format, ref tSpriteElement.NPOTscale); if (tSpriteElement.type == 0) { // テクスチャまたはシングルスプライトタイプ tSpriteElement.texture = AssetDatabase.LoadAssetAtPath(tPath, typeof(Texture2D)) as Texture2D; tSpriteTextureList.Add(tSpriteElement.texture); } else { // マルチプルスプライトタイプ x = ( int )tSpriteElement.metaData.rect.x; y = ( int )tSpriteElement.metaData.rect.y; w = ( int )tSpriteElement.metaData.rect.width; h = ( int )tSpriteElement.metaData.rect.height; tElementTexture = new Texture2D(w, h, TextureFormat.ARGB32, false); tElementTexture.SetPixels(tSpriteElement.texture.GetPixels(x, y, w, h)); tElementTexture.Apply(); tSpriteTextureList.Add(tElementTexture); } break; // 領域更新 case SpriteAction.Update: tSpriteSheetList.Add(tSpriteElement.metaData); tPath = AssetDatabase.GetAssetPath(tSpriteElement.texture.GetInstanceID()); // 読み込む前にフォーマットを強制的に ARGB32 NPOT にしてやる(アルファテクスチャなどだとオリジナルの状態が正しく読み込めない) SetTextureSetting(tPath, true, ref tSpriteElement.format, ref tSpriteElement.NPOTscale); if (tSpriteElement.type == 0) { // テクスチャまたはシングルスプライトタイプ tSpriteElement.texture = AssetDatabase.LoadAssetAtPath(tPath, typeof(Texture2D)) as Texture2D; tSpriteTextureList.Add(tSpriteElement.texture); } else { // マルチプルスプライトタイプ x = ( int )tSpriteElement.metaData.rect.x; y = ( int )tSpriteElement.metaData.rect.y; w = ( int )tSpriteElement.metaData.rect.width; h = ( int )tSpriteElement.metaData.rect.height; tElementTexture = new Texture2D(w, h, TextureFormat.ARGB32, false); tElementTexture.SetPixels(tSpriteElement.texture.GetPixels(x, y, w, h)); tElementTexture.Apply(); tSpriteTextureList.Add(tElementTexture); } break; case SpriteAction.Delete: tDeleteSpriteList.Add(tName); break; } tElementTexture = null; } if (tSpriteSheetList.Count > 0 && tSpriteTextureList.Count > 0) { int tMaxSize = Mathf.Min(SystemInfo.maxTextureSize, 2048); int tPadding = m_Padding; if (tSpriteTextureList.Count == 1) { // 要素が1つだけの場合はパディングは強制的に0にする tPadding = 0; } Rect[] tRectList = tTexture.PackTextures(tSpriteTextureList.ToArray(), tPadding, tMaxSize); // 後始末 foreach (KeyValuePair <string, SpriteElement> tSpriteElementKeyValue in m_SpriteElementHash) { SpriteElement tSpriteElement = tSpriteElementKeyValue.Value; switch (tSpriteElement.action) { // 新規追加 case SpriteAction.Add: tPath = AssetDatabase.GetAssetPath(tSpriteElement.texture.GetInstanceID()); SetTextureSetting(tPath, false, ref tSpriteElement.format, ref tSpriteElement.NPOTscale); tSpriteElement.texture = null; tSpriteElement.action = SpriteAction.None; break; // 領域更新 case SpriteAction.Update: tPath = AssetDatabase.GetAssetPath(tSpriteElement.texture.GetInstanceID()); SetTextureSetting(tPath, false, ref tSpriteElement.format, ref tSpriteElement.NPOTscale); tSpriteElement.texture = null; tSpriteElement.action = SpriteAction.None; break; } } //--------------------------------------------------- // 出来上がったテクスチャに無駄が無いか確認し無駄があれば除去する int i, l; float tw = tTexture.width; float th = tTexture.height; l = tSpriteSheetList.Count; for (i = 0; i < l; i++) { Rect tRect = tRectList[i]; tRect.x *= tw; tRect.y *= th; tRect.width *= tw; tRect.height *= th; tRectList[i] = tRect; } // ソースのリージョンを検査して無駄が無いか確認する float xMin = tw; float yMin = th; float xMax = 0; float yMax = 0; for (i = 0; i < l; i++) { if (tRectList[i].xMin < xMin) { xMin = tRectList[i].xMin; } if (tRectList[i].yMin < yMin) { yMin = tRectList[i].yMin; } if (tRectList[i].xMax > xMax) { xMax = tRectList[i].xMax; } if (tRectList[i].yMax > yMax) { yMax = tRectList[i].yMax; } } xMin = xMin - tPadding; if (xMin < 0) { xMin = 0; } yMin = yMin - tPadding; if (yMin < 0) { yMin = 0; } xMax = xMax + tPadding; if (xMax > tw) { xMax = tw; } yMax = yMax + tPadding; if (yMax > th) { yMax = th; } int pw = ( int )(xMax - xMin); int ph = ( int )(yMax - yMin); int rw = 1; for (i = 0; i < 16; i++) { if (rw >= pw) { break; } rw = rw << 1; } int rh = 1; for (i = 0; i < 16; i++) { if (rh >= ph) { break; } rh = rh << 1; } if (rw <= ( int )(tw / 2) || rh <= ( int )(th / 2)) { // 無駄がある // Debug.LogWarning( "無駄がある:" + rw + " / " + tw + " " + rh + " / " + th ) ; int rx = ( int )xMin; int ry = ( int )yMin; // Debug.LogWarning( "取得範囲:" + rx + " " + ry + " " + rw + " " + rh ) ; Texture2D tReduceTexture = new Texture2D(rw, rh, TextureFormat.ARGB32, false); tReduceTexture.SetPixels(tTexture.GetPixels(rx, ry, rw, rh)); tReduceTexture.Apply(); tTexture = tReduceTexture; tReduceTexture = null; for (i = 0; i < l; i++) { Rect tRect = tRectList[i]; tRect.x -= rx; tRect.y -= ry; tRectList[i] = tRect; } } //--------------------------------------------------- string tAtlasFullPath; if (tAtlas == null) { // 生成 tAtlasFullPath = m_AtlasFullPath; } else { // 更新 tAtlasFullPath = AssetDatabase.GetAssetPath(tAtlas.GetInstanceID()); } // テクスチャをPNG画像として保存する byte[] tData = tTexture.EncodeToPNG(); System.IO.File.WriteAllBytes(tAtlasFullPath, tData); tData = null; AssetDatabase.SaveAssets(); if (tAtlas == null) { AssetDatabase.Refresh(); } TextureImporter tTextureImporter = AssetImporter.GetAtPath(tAtlasFullPath) as TextureImporter; // 既存の場合は以前の設定を引き継がせる tTextureImporter.textureCompression = tAtlasFormat; tTextureImporter.npotScale = tAtlasNPOtScale; if (tAtlas == null) { // 新規作成の場合に設定する tTextureImporter.textureType = TextureImporterType.Sprite; tTextureImporter.spriteImportMode = SpriteImportMode.Multiple; tTextureImporter.mipmapEnabled = false; } for (i = 0; i < l; i++) { SpriteMetaData tSpriteMetaData = tSpriteSheetList[i]; tSpriteMetaData.rect = tRectList[i]; tSpriteSheetList[i] = tSpriteMetaData; } tTextureImporter.spritesheet = tSpriteSheetList.ToArray(); tTextureImporter.isReadable = false; // 書き込み属性を無効にする AssetDatabase.ImportAsset(tAtlasFullPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); tAtlas = AssetDatabase.LoadAssetAtPath(tAtlasFullPath, typeof(Texture2D)) as Texture2D; tSpriteSheetList.Clear(); tSpriteTextureList.Clear(); Resources.UnloadUnusedAssets(); } else { // 要素が全て無くなるためファイル自体を削除する AssetDatabase.DeleteAsset(m_AtlasFullPath); tAtlas = null; } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); foreach (string tName in tDeleteSpriteList) { m_SpriteElementHash.Remove(tName); } UpdateList(tAtlas, true); }
//--------------------------------------------------------------- // 素材リストの情報を生成する private void UpdateList(Texture2D tAtlas, bool tClear) { if (tClear == true) { m_SpriteElementHash.Clear(); } Dictionary <string, SpriteElement> tSpriteElementHash = new Dictionary <string, SpriteElement>(); if (tAtlas != null) { // 既にある場合はアトラス内のスプライト情報を展開する string tAtlasPath = AssetDatabase.GetAssetPath(tAtlas.GetInstanceID()); TextureImporter tTextureImporter = AssetImporter.GetAtPath(tAtlasPath) as TextureImporter; foreach (SpriteMetaData tSpriteMetaData in tTextureImporter.spritesheet) { SpriteElement tSpriteElement = null; string tName = tSpriteMetaData.name; if (m_SpriteElementHash.TryGetValue(tName, out tSpriteElement)) { // 既にリストに登録済みの情報 tSpriteElement.texture = null; tSpriteElement.metaData = tSpriteMetaData; if (tSpriteElement.action == SpriteAction.Delete) { tSpriteElement.action = SpriteAction.Delete; } else { tSpriteElement.action = SpriteAction.None; } tSpriteElement.type = 0; } else { // リストに存在しない情報 tSpriteElement = new SpriteElement(); tSpriteElement.texture = null; tSpriteElement.metaData = tSpriteMetaData; tSpriteElement.action = SpriteAction.None; tSpriteElement.type = 0; } tSpriteElementHash.Add(tName, tSpriteElement); } } // 選択中の素材を追加する foreach (UnityEngine.Object tObject in Selection.objects) { Texture2D tTexture = tObject as Texture2D; if (tTexture == null || tTexture == tAtlas) { continue; } //----------------------------------------- SpriteElement tSpriteElement = null; string tName; // 素材となる画像がスプライト(アトラス)かそれ以外(テクスチャ)かで処理が異なる string tTexturePath = AssetDatabase.GetAssetPath(tTexture.GetInstanceID()); TextureImporter tTextureImporter = AssetImporter.GetAtPath(tTexturePath) as TextureImporter; if (tTextureImporter != null && tTextureImporter.textureType == TextureImporterType.Sprite) { // スプライト扱い if (tTextureImporter.spriteImportMode == SpriteImportMode.Single) { // シングルタイプ tName = tTexture.name; if (tSpriteElementHash.TryGetValue(tName, out tSpriteElement)) { // 既に存在するのでアップデートになる tSpriteElement.texture = tTexture; tSpriteElement.metaData.border = tTextureImporter.spriteBorder; tSpriteElement.metaData.pivot = tTextureImporter.spritePivot; tSpriteElement.action = SpriteAction.Update; tSpriteElement.type = 0; } else { // 存在しないため追加となる tSpriteElement = new SpriteElement(); tSpriteElement.texture = tTexture; tSpriteElement.metaData = new SpriteMetaData(); tSpriteElement.metaData.name = tName; tSpriteElement.metaData.border = tTextureImporter.spriteBorder; tSpriteElement.metaData.pivot = tTextureImporter.spritePivot; tSpriteElement.action = SpriteAction.Add; tSpriteElement.type = 0; tSpriteElementHash.Add(tName, tSpriteElement); } } else if (tTextureImporter.spriteImportMode == SpriteImportMode.Multiple) { // マルチプルタイプ foreach (SpriteMetaData tSpriteMetaData in tTextureImporter.spritesheet) { tName = tSpriteMetaData.name; if (tSpriteElementHash.TryGetValue(tName, out tSpriteElement)) { // 既に存在するのでアップデートになる tSpriteElement.texture = tTexture; tSpriteElement.metaData = tSpriteMetaData; tSpriteElement.action = SpriteAction.Update; tSpriteElement.type = 1; } else { // 存在しないため追加となる tSpriteElement = new SpriteElement(); tSpriteElement.texture = tTexture; tSpriteElement.metaData = tSpriteMetaData; tSpriteElement.action = SpriteAction.Add; tSpriteElement.type = 1; tSpriteElementHash.Add(tName, tSpriteElement); } } } } else { // テクスチャ扱い tName = tTexture.name; if (tSpriteElementHash.TryGetValue(tName, out tSpriteElement)) { // 既に存在するのでアップデートになる tSpriteElement.texture = tTexture; tSpriteElement.action = SpriteAction.Update; tSpriteElement.type = 0; } else { // 存在しないため追加となる tSpriteElement = new SpriteElement(); tSpriteElement.texture = tTexture; tSpriteElement.metaData = new SpriteMetaData(); tSpriteElement.metaData.name = tName; tSpriteElement.action = SpriteAction.Add; tSpriteElement.type = 0; tSpriteElementHash.Add(tName, tSpriteElement); } } } m_SpriteElementHash = tSpriteElementHash; }
public async Task <IEnumerable <DisplayElement> > GenerateUi(float width, float height) { try { var heightDiff = height / 1080f; var widthDiff = width / 1920f; var replies = new List <ImageElement>(); var image = await WebControl.GetImageData("/Assets/board.jpg", "jpg"); var background = new ImageElement(image); background.Width = (int)width; background.Height = (int)height; background.Style.Left = 0; background.Style.Top = 0; background.Style.ZIndex = -1; background.Style.Position = NativeWebView.HTML.CSS.Attributes.ElementPositions.position_absolute; replies.Add(background); image = await WebControl.GetImageData("/Assets/howtoplay.png", "png"); HelpScreen = new ImageElement(image); HelpScreen.Width = (int)width; HelpScreen.Height = (int)height; HelpScreen.Style.Left = 0; HelpScreen.Style.Top = 0; HelpScreen.Style.ZIndex = 99; HelpScreen.Style.Display = Display.none; HelpScreen.Style.Position = NativeWebView.HTML.CSS.Attributes.ElementPositions.position_absolute; replies.Add(HelpScreen); image = await WebControl.GetImageData("/Assets/gameover-win.png", "png"); WinScreen = new ImageElement(image); WinScreen.Width = (int)width; WinScreen.Height = (int)height; WinScreen.Style.Left = 0; WinScreen.Style.Top = 0; WinScreen.Style.ZIndex = 98; WinScreen.Style.Display = Display.none; WinScreen.Style.Position = NativeWebView.HTML.CSS.Attributes.ElementPositions.position_absolute; replies.Add(WinScreen); image = await WebControl.GetImageData("/Assets/gameover-lose.png", "png"); LoseScreen = new ImageElement(image); LoseScreen.Width = (int)width; LoseScreen.Height = (int)height; LoseScreen.Style.Left = 0; LoseScreen.Style.Top = 0; LoseScreen.Style.ZIndex = 98; LoseScreen.Style.Display = Display.none; LoseScreen.Style.Position = NativeWebView.HTML.CSS.Attributes.ElementPositions.position_absolute; replies.Add(LoseScreen); image = await WebControl.GetImageData("/Assets/wall.png", "png"); var nibble = 60 * widthDiff; wall = GenerateItem(image, (int)(width / 2), (int)(170 * heightDiff), (int)(width - (nibble * 2)), (int)(990 * heightDiff), 6);//new SpriteElement(".png", image, 6, 1800, 690); replies.Add(wall); int buttonWidth = (int)(50 * widthDiff); if (buttonWidth < 20) { buttonWidth = 20; } int villagerWidth = (int)(150 * widthDiff); int villagerHeight = (int)(3960 * heightDiff); var leftbutton = await WebControl.GetImageData("/Assets/button_left.png", "png"); var rightbutton = await WebControl.GetImageData("/Assets/button_right.png", "png"); var blue = await WebControl.GetImageData("/Assets/bluemeeples.png", "png"); var red = await WebControl.GetImageData("/Assets/redmeeples.png", "png"); var left = background.Width / 5; var top = background.Height / 2; var buttonTop = top + villagerHeight / 40; var center = left / 2; for (int i = 0; i < OUTLANDS_LOCATION; i++) { if (i > 0) { LeftButtons[i] = GenerateItem(leftbutton, center - villagerWidth, buttonTop, buttonWidth, buttonWidth); replies.Add(LeftButtons[i]); } if (i < OUTLANDS_LOCATION - 1) { RightButtons[i] = GenerateItem(rightbutton, center + villagerWidth, buttonTop, buttonWidth, buttonWidth); replies.Add(RightButtons[i]); } Villagers[i] = GenerateItem(blue, center, top, villagerWidth, villagerHeight, 20); replies.Add(Villagers[i]); EvilMinions[i] = GenerateItem(red, center, top, villagerWidth, villagerHeight, 20); replies.Add(EvilMinions[i]); center += left; } EvilMinions[OUTLANDS_LOCATION] = GenerateItem(red, center, top, villagerWidth, villagerHeight, 20); replies.Add(EvilMinions[OUTLANDS_LOCATION]); return(replies); } catch (System.Exception e) { Console.WriteLine(e.Message); //ToDo: log it //Windows.UI.Popups.MessageDialog tmp = new Windows.UI.Popups.MessageDialog(e.Message); //tmp.ShowAsync(); } return(new List <DisplayElement>()); }
static public bool AutoBuildAtlasFromListTexture(List <Texture2D> listTexture, List <DataAnimAnalytics> listJsonAnim, TrimType trimType, string texturePath, int pading) { float prog = 0.0f; EditorUtility.DisplayCancelableProgressBar("Collecting Textures", "Process...", prog); try { Dictionary <string, EAPInfoAttachment> dicPivot = new Dictionary <string, EAPInfoAttachment>(); for (int i = 0; i < listJsonAnim.Count; i++) { DataAnimAnalytics dataAnalytic = listJsonAnim[i]; foreach (KeyValuePair <string, EAPInfoAttachment> pair in dataAnalytic.jsonFinal.dicPivot) { dicPivot[pair.Value.spriteName] = pair.Value; } } List <SpriteElement> listSprite = new List <SpriteElement>(); for (int i = 0; i < listTexture.Count; i++) { Object obj = listTexture[i]; if (obj is Texture2D) { Texture2D tex = (Texture2D)obj; SpriteElement element = new SpriteElement(tex); if (trimType == TrimType.Trim2nTexture || trimType == TrimType.TrimMinimum) { if (!element.TrimTexture()) { element.CloneFromOriginTexture(); } } else { element.CloneFromOriginTexture(); } foreach (KeyValuePair <string, EAPInfoAttachment> pair in dicPivot) { if (pair.Value.spriteName == tex.name) { //Debug.LogError(pair.Value.spriteName); element.SetPivot(new Vector2(pair.Value.x, pair.Value.y)); break; } } listSprite.Add(element); prog = (float)(i + 1) / listTexture.Count; EditorUtility.DisplayCancelableProgressBar("Collecting Textures", "Process...", prog); } } if (listSprite.Count > 0) { bool result = BuildAtlas(trimType, listSprite, dicPivot, texturePath, pading); // GC memory for (int i = 0; i < listSprite.Count; i++) { GameObject.DestroyImmediate(listSprite[i].texture); listSprite[i] = null; } return(result); } return(false); } catch (System.Exception ex) { Debug.LogError("Error:" + ex.Message); EditorUtility.ClearProgressBar(); return(false); } }
//---------------------------------------------------------- // レイアウトを描画する private void OnGUI() { Texture2D tAtlas = null; // 保存先のパスの設定 GUILayout.BeginHorizontal(); { // 保存パスを選択する if (GUILayout.Button("Atlas Path", GUILayout.Width(80f)) == true) { if (Selection.objects != null && Selection.objects.Length == 0 && Selection.activeObject == null) { // ルート m_AtlasPath = "Assets/"; } else if (Selection.objects != null && Selection.objects.Length == 1 && Selection.activeObject != null) { string tPath = AssetDatabase.GetAssetPath(Selection.activeObject.GetInstanceID()); if (System.IO.Directory.Exists(tPath) == true) { // フォルダを指定しています // ファイルかどうか判別するには System.IO.File.Exists // 有効なフォルダ tPath = tPath.Replace("\\", "/"); m_AtlasPath = tPath + "/"; } else { // ファイルを指定しています tPath = tPath.Replace("\\", "/"); m_AtlasPath = tPath; // 拡張子を見てアセットバンドルであればファイル名まで置き変える // ただしこれを読み出して含まれるファイルの解析などは行わない // なぜなら違うプラットフォームの場合は読み出せずにエラーになってしまうから // 最後のフォルダ区切り位置を取得する int tIndex = m_AtlasPath.LastIndexOf('/'); if (tIndex >= 0) { m_AtlasPath = m_AtlasPath.Substring(0, tIndex) + "/"; } if (tPath.Length > 4) { if (tPath.Substring(tPath.Length - 4, 4) == ".png") { tPath = tPath.Substring(tIndex + 1, tPath.Length - (tIndex + 1)); m_AtlasName = tPath.Substring(0, tPath.Length - 4); } } } } } // 保存パス m_AtlasPath = EditorGUILayout.TextField(m_AtlasPath); // 名前 m_AtlasName = EditorGUILayout.TextField(m_AtlasName); } GUILayout.EndHorizontal(); // 指定しているパスのファイルがアトラスならばインスタンスを取得する string tAtlasFullPath = m_AtlasPath + m_AtlasName + ".png"; if (string.IsNullOrEmpty(tAtlasFullPath) == false) { TextureImporter tTextureImporter = AssetImporter.GetAtPath(tAtlasFullPath) as TextureImporter; if (tTextureImporter != null && tTextureImporter.textureType == TextureImporterType.Sprite) { tAtlas = AssetDatabase.LoadAssetAtPath <Texture2D>(tAtlasFullPath); } } GUILayout.Space(6f); //----------------------------------------------------- // アトラステクスチャ情報の表示を行う if (tAtlas != null) { GUILayout.BeginHorizontal(); { GUILayout.Label("Path", GUILayout.Width(36f)); GUI.color = Color.cyan; GUILayout.Label(tAtlasFullPath); GUI.color = Color.white; } GUILayout.EndHorizontal(); // アトラスが選択されている時のみ表示編集が可能となる GUILayout.BeginHorizontal(); { if (GUILayout.Button("Sprite", GUILayout.Width(76f))) { Selection.activeObject = tAtlas; } GUILayout.Label(" " + tAtlas.width + "x" + tAtlas.height); } GUILayout.EndHorizontal(); } //------------------------------------------ bool tClear = false; if (m_AtlasFullPath != tAtlasFullPath) { m_AtlasFullPath = tAtlasFullPath; tClear = true; } // リストを更新する UpdateList(tAtlas, tClear); //------------------------------------------------- bool tExecute = false; if (m_SpriteElementHash.Count > 0) { // マルチタイプのスプライトで要素が1以上存在する GUILayout.BeginHorizontal(); // 横一列開始 { GUILayout.Label("Padding", GUILayout.Width(76f)); m_Padding = Mathf.Clamp(EditorGUILayout.IntField(m_Padding, GUILayout.Width(50f)), 0, 10); } GUILayout.EndHorizontal(); // 横一列終了 GUILayout.BeginHorizontal(); { if (tAtlas == null) { // 新規作成 // 新規作成で生成可能 GUI.backgroundColor = Color.green; tExecute = GUILayout.Button("Create"); GUI.backgroundColor = Color.white; } else { // 維持更新 GUI.backgroundColor = Color.cyan; tExecute = GUILayout.Button("Update"); // 更新または追加 GUI.backgroundColor = Color.white; } } GUILayout.EndHorizontal(); // テクスチャ分解出力 if (tAtlas != null) { // テクスチャ分解出力パス GUILayout.BeginHorizontal(); { EditorGUIUtility.labelWidth = 140f; EditorGUIUtility.fieldWidth = 40f; m_OutputSourceTexture = EditorGUILayout.Toggle("Output Divided Sprite", m_OutputSourceTexture); EditorGUIUtility.labelWidth = 80f; EditorGUIUtility.fieldWidth = 50f; } GUILayout.EndHorizontal(); if (m_OutputSourceTexture == true) { // 保存先のパスの設定 GUILayout.BeginHorizontal(); { // 保存パスを選択する if (GUILayout.Button("Output Path", GUILayout.Width(100f)) == true) { if (Selection.objects != null && Selection.objects.Length == 0 && Selection.activeObject == null) { // ルート m_OutputSourceTexturePath = "Assets/"; } else if (Selection.objects != null && Selection.objects.Length == 1 && Selection.activeObject != null) { string tPath = AssetDatabase.GetAssetPath(Selection.activeObject.GetInstanceID()); if (System.IO.Directory.Exists(tPath) == true) { // フォルダを指定しています // ファイルかどうか判別するには System.IO.File.Exists // 有効なフォルダ tPath = tPath.Replace("\\", "/"); m_OutputSourceTexturePath = tPath + "/"; } else { // ファイルを指定しています tPath = tPath.Replace("\\", "/"); // 拡張子を見てアセットバンドルであればファイル名まで置き変える // ただしこれを読み出して含まれるファイルの解析などは行わない // なぜなら違うプラットフォームの場合は読み出せずにエラーになってしまうから // 最後のフォルダ区切り位置を取得する int tIndex = tPath.LastIndexOf('/'); m_OutputSourceTexturePath = tPath.Substring(0, tIndex) + "/"; } } } // 保存パス m_OutputSourceTexturePath = EditorGUILayout.TextField(m_OutputSourceTexturePath); if (string.IsNullOrEmpty(m_OutputSourceTexturePath) == false && tAtlas != null) { if (Directory.Exists(m_OutputSourceTexturePath) == true) { if (GUILayout.Button("Execute", GUILayout.Width(80f)) == true) { OutputDividedSprite(tAtlas, m_OutputSourceTexturePath); } } } } GUILayout.EndHorizontal(); } } } //------------------------------------------ // 素材情報のリストを表示する if (m_SpriteElementHash.Count > 0) { EditorGUILayout.Separator(); EditorGUILayout.LabelField("Target (" + m_SpriteElementHash.Count + ")"); GUILayout.BeginVertical(); { m_ScrollPosition = GUILayout.BeginScrollView(m_ScrollPosition); { foreach (KeyValuePair <string, SpriteElement> tSpriteElementKeyValue in m_SpriteElementHash) { string tName = tSpriteElementKeyValue.Key; SpriteElement tSpriteElement = tSpriteElementKeyValue.Value; GUILayout.BeginHorizontal("TextArea", GUILayout.MinHeight(20f)); // 横一列開始 { GUILayout.Label(tName, GUILayout.Height(20f)); switch (tSpriteElement.action) { // 通常状態 case SpriteAction.None: if (GUILayout.Button("Delete", GUILayout.Width(60f))) { tSpriteElement.action = SpriteAction.Delete; // 破棄対象にする } break; // 追加対象 case SpriteAction.Add: GUI.backgroundColor = Color.green; GUILayout.Box("Add", GUILayout.Width(60f)); GUI.backgroundColor = Color.white; break; // 更新対象 case SpriteAction.Update: GUI.backgroundColor = Color.yellow; GUILayout.Box("Update", GUILayout.Width(60f)); GUI.backgroundColor = Color.white; break; // 削除対象 case SpriteAction.Delete: GUI.backgroundColor = Color.red; if (GUILayout.Button("Delete", GUILayout.Width(60f))) { tSpriteElement.action = SpriteAction.None; } GUI.backgroundColor = Color.white; break; } } GUILayout.EndHorizontal(); // 横一列終了 } } GUILayout.EndScrollView(); } GUILayout.EndVertical(); } else { EditorGUILayout.HelpBox(GetMessage("SelectTexture"), MessageType.Info); } //------------------------------------------- if (tExecute == true) { // アトラスを生成する BuildAtlas(tAtlas); } }