Inheritance: UnrealBuildTool.ModuleRules
Example #1
0
    /// <returns>The atlas or null if it could not be loaded.</returns>
    public Atlas GetAtlas()
    {
        if (atlasFile == null) {
            Debug.LogWarning("Atlas file not set for atlas asset: " + name, this);
            Clear();
            return null;
        }

        if (material == null) {
            Debug.LogWarning("Material not set for atlas asset: " + name, this);
            Clear();
            return null;
        }

        if (atlas != null)
            return atlas;

        try {
            atlas = new Atlas(new StringReader(atlasFile.text), "", new SingleTextureLoader(material));
            return atlas;
        } catch (Exception ex) {
            Debug.Log("Error reading atlas file for atlas asset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, this);
            return null;
        }
    }
Example #2
0
    /// <returns>The atlas or null if it could not be loaded.</returns>
    public Atlas GetAtlas()
    {
        if (atlasFile == null) {
            Debug.LogWarning("Atlas file not set for atlas asset: " + name, this);
            Clear();
            return null;
        }

        if (material == null) {
            Debug.LogWarning("Material not set for atlas asset: " + name, this);
            Clear();
            return null;
        }

        if (atlas != null)
            return atlas;

        try {
            atlas = new Atlas(new StringReader(atlasFile.text), material, material.mainTexture.width, material.mainTexture.height);
            return atlas;
        } catch (Exception) {
            Debug.LogException(new Exception("Error reading atlas file for atlas asset: " + name), this);
            return null;
        }
    }
Example #3
0
    /// <returns>The atlas or null if it could not be loaded.</returns>
    public Atlas GetAtlas()
    {
        if (atlasFile == null) {
            Debug.LogError("Atlas file not set for atlas asset: " + name, this);
            Clear();
            return null;
        }

        if (materials == null || materials.Length == 0) {
            Debug.LogError("Materials not set for atlas asset: " + name, this);
            Clear();
            return null;
        }

        if (atlas != null)
            return atlas;

        try {
            atlas = new Atlas(new StringReader(atlasFile.text), "", new MaterialsTextureLoader(this));
            atlas.FlipV();
            return atlas;
        } catch (Exception ex) {
            Debug.LogError("Error reading atlas file for atlas asset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, this);
            return null;
        }
    }
Example #4
0
    void Awake()
    {
#if UNITY_EDITOR
        if (Application.isPlaying)
        {
            Assert.IsNotNull(relativeImage, gameObject.name + ": the image extension relative a null image");
            Assert.IsNotNull(relativeAtlas, gameObject.name + ": the image extension relative a null Atlas");
        }
        else
        {
            if (relativeImage == null)
                relativeImage = GetComponent<Image>();

            if (relativeAtlas == null && relativeImage != null)
                relativeAtlas = EditorAtlasUtilites.GetAtlas(relativeImage.sprite);
        }
#endif
    }
Example #5
0
    /**
     * DrawBlockEditor draws and handles editing a single block
     */
    private static void DrawBlockEditor(Block block, BlockSet blockSet)
    {
        string name = EditorGUILayout.TextField("Name", block.GetName());

        block.SetName(name);

        Atlas[]  atlases    = blockSet.GetAtlases();
        string[] atlasNames = new string[atlases.Length];
        for (int i = 0; i < atlasNames.Length; i++)
        {
            Atlas tAtlas = atlases[i];
            atlasNames[i] = tAtlas != null ? tAtlas.name : "null";
        }
        int index = ArrayUtility.IndexOf(atlases, block.GetAtlas());

        index = EditorGUILayout.Popup("Atlas", index, atlasNames);
        block.SetAtlas(SafeGet(atlases, index));

        /**
         * For now all blocks have the same light values as a default
         * int light = EditorGUILayout.IntField("Light", block.GetLight());
         * light = Mathf.Clamp(light, 0, 15);
         * block.SetLight((byte)light);
         */

        bool breakable = EditorGUILayout.Toggle("Breakable", block.IsBreakable());

        block.SetBreakable(breakable);

        Atlas atlas = block.GetAtlas();

        if (atlas == null || atlas.GetMaterial() == null || atlas.GetMaterial().mainTexture == null)
        {
            return;
        }
        if (block is Cube)
        {
            DrawCubeBlockEditor((Cube)block, atlas);
        }
        if (block is Cross)
        {
            DrawCrossBlockEditor((Cross)block, atlas);
        }
    }
Example #6
0
    public void LoadContent(ContentManager contentManager)
    {
        skeletonRenderer = new SkeletonMeshRenderer(App.graphicsDevice);
        skeletonRenderer.PremultipliedAlpha = App.GV.Alpha;

        atlas = new Atlas(App.GV.SelectFile, new XnaTextureLoader(App.graphicsDevice));

        json         = new SkeletonJson(atlas);
        json.Scale   = App.GV.Scale;
        skeletonData = json.ReadSkeletonData(Common.GetJsonPath(App.GV.SelectFile));


        skeleton = new Skeleton(skeletonData);

        if (App.isNew)
        {
            App.GV.PosX = Convert.ToSingle(App.GV.FrameWidth / 2f);
            App.GV.PosY = Convert.ToSingle((skeleton.Data.Height + App.GV.FrameHeight) / 2f);
        }
        App.GV.FileHash = skeleton.Data.Hash;

        stateData = new AnimationStateData(skeleton.Data);

        state = new AnimationState(stateData);

        App.GV.AnimeList = state.Data.skeletonData.Animations.Select(x => x.Name).ToList();
        App.GV.SkinList  = state.Data.skeletonData.Skins.Select(x => x.Name).ToList();


        if (App.GV.SelectAnimeName != "")
        {
            state.SetAnimation(0, App.GV.SelectAnimeName, App.GV.IsLoop);
        }
        else
        {
            state.SetAnimation(0, state.Data.skeletonData.animations[0].name, App.GV.IsLoop);
        }

        if (App.isNew)
        {
            MainWindow.SetCBAnimeName();
        }
        App.isNew = false;
    }
        private static bool TryLoadSkeletonBinary(Wz_Node atlasNode, Atlas atlas, out SkeletonData data)
        {
            data = null;

            if (atlasNode == null || atlasNode.ParentNode == null || atlas == null)
            {
                return(false);
            }

            var m = Regex.Match(atlasNode.Text, @"^(.+)\.atlas$", RegexOptions.IgnoreCase);

            if (!m.Success)
            {
                return(false);
            }

            var node = atlasNode.ParentNode.FindNodeByPath(m.Result("$1"));
            var uol  = node.GetValueEx <Wz_Uol>(null);

            if (uol != null)
            {
                node = uol.HandleUol(node);
            }
            var skeletonSource = node.GetValueEx <Wz_Sound>(null);

            if (skeletonSource == null || skeletonSource.SoundType != Wz_SoundType.Binary)
            {
                return(false);
            }

            byte[] buffer = new byte[skeletonSource.DataLength];
            skeletonSource.WzFile.FileStream.Seek(skeletonSource.Offset, SeekOrigin.Begin);
            if (skeletonSource.WzFile.FileStream.Read(buffer, 0, buffer.Length) != buffer.Length)
            {
                return(false);
            }
            MemoryStream ms = new MemoryStream(buffer);

            SkeletonBinary binary = new SkeletonBinary(atlas);

            data = binary.ReadSkeletonData(ms);
            return(true);
        }
Example #8
0
        private void RecallSpell()
        {
            RunebookEntry e = Atlas.Entries[Selected];

            if (RunebookGump.HasSpell(User, 31))
            {
                string coords = ToCoordinates(e.Location, e.Map);

                if (coords != "unknown")
                {
                    User.SendMessage(ToCoordinates(e.Location, e.Map));
                }

                Atlas.OnTravel();
                new RecallSpell(User, null, e, null).Cast();
            }

            Atlas.Openers.Remove(User);
        }
Example #9
0
    private void CubeDown(int x, int y, int z, Atlas.ID block)
    {
        _newVerts.Add(new Vector3(x, y - 1, z));
        _newVerts.Add(new Vector3(x + 1, y - 1, z));
        _newVerts.Add(new Vector3(x + 1, y - 1, z + 1));
        _newVerts.Add(new Vector3(x, y - 1, z + 1));

        Atlas.Dir dir   = Atlas.Dir.Down;
        Color     color = Color.white;

        _newColors.Add(color);
        _newColors.Add(color);
        _newColors.Add(color);
        _newColors.Add(color);

        Vector2 texturePos = Atlas.GetTexture(block, dir);

        Cube(texturePos);
    }
Example #10
0
        /// <summary>
        /// Renders a string to the screen.
        /// </summary>
        /// <param name="font">The font to render using.</param>
        /// <param name="textSize">The size to render in.</param>
        /// <param name="text">The text to render.</param>
        /// <param name="position">The position to render to.</param>
        /// <param name="color">The color to render in.</param>
        public void RenderString(Font font, uint textSize, string text, Vector3 position, Color color)
        {
            // Flush the buffer.
            RenderFlush();

            // Add the string's model matrix.
            MatrixStack.Push(Matrix4.CreateTranslation(position));

            // Queue letters.
            Rectangle[] uvs   = new Rectangle[text.Length];
            Atlas       atlas = font.GetFontAtlas(textSize);

            float penX = 0;
            float penY = 0;

            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] == '\n')
                {
                    penX  = 0;
                    penY += atlas.LineSpacing;
                    continue;
                }

                if (i > 0)
                {
                    penX += atlas.GetKerning(text[i - 1], text[i]);
                }

                Glyph g = atlas.Glyphs[text[i]];

                Vector3 renderPos = new Vector3(g.MinX + penX, penY + g.YBearing, position.Z);
                uvs[i] = new Rectangle(g.X, g.Y, g.Width, g.Height);
                RenderQueue(renderPos, uvs[i].Size, color, atlas.Texture, uvs[i]);
                penX += g.Advance;
            }

            // Render the whole string.
            RenderFlush();

            // Remove the model matrix.
            MatrixStack.Pop();
        }
 private void Frame_MouseWheel(object sender, MouseWheelEventArgs e)
 {
     if (e.Delta > 0)
     {
         App.GV.Scale += 0.02f;
     }
     else
     {
         if (App.GV.Scale > 0.04f)
         {
             App.GV.Scale -= 0.02f;
         }
     }
     atlas        = new Atlas(App.GV.SelectFile, new XnaTextureLoader(_graphicsDevice));
     json         = new SkeletonJson(atlas);
     json.Scale   = App.GV.Scale;
     skeletonData = json.ReadSkeletonData(Common.GetJsonPath(App.GV.SelectFile));
     skeleton     = new Skeleton(skeletonData);
 }
Example #12
0
        public async void Unjail(JailCase jailCase)
        {
            Atlas.DetachTickHandler(OnTick);

            if (jailCase.HasEscaped)
            {
                return;
            }

            API.DoScreenFadeOut(0);

            await Cache.Entity.Teleport(ReleasePosition);

            await BaseScript.Delay(3000);

            API.DoScreenFadeIn(5000);

            LastJailCase = null;
        }
Example #13
0
        /// <summary>
        ///  换装备并且合并材质球
        /// </summary>
        /// <param name="skeletonAnimation">spine 组件</param>
        /// <param name="atlasAsset"> 图片+atlas 生成的图集文件 </param>
        /// <param name="regionName">  图集文件中的具体的一张图片 最好一个图片一个图集  </param>
        /// <param name="e"> 装备类型 </param>
        public void ExchangeEquipmentAndMerge(SkeletonAnimation skeletonAnimation, List <EquipmentItem> infos)
        {
            for (int i = 0; i < infos.Count; i++)
            {
                EquipmentItem      info               = infos[i];
                string             regionName         = info.equipmentImageName;
                string             defaultSkinName    = info.defaultSkinName;
                string             spineEquipmentType = info.spineEquipmentTypeName;
                AssetBundlePackage assetbundle        = HFResourceManager.Instance.LoadAssetBundleFromFile(info.equipmentAssetbundleName);
                AtlasAsset         atlasAsset         = assetbundle.LoadAssetWithCache <AtlasAsset>(info.equipmentAtlasAssetName);
                float       scale              = skeletonAnimation.skeletonDataAsset.scale;
                Atlas       atlas              = atlasAsset.GetAtlas();
                AtlasRegion region             = atlas.FindRegion(regionName);
                Slot        slot               = skeletonAnimation.skeleton.FindSlot(info.slotName);
                Attachment  originalAttachment = slot.Attachment;
                if (region == null)
                {
                    slot.Attachment = null;
                }
                else if (originalAttachment != null)
                {
                    slot.Attachment = originalAttachment.GetRemappedClone(region, true, true, 1);
                }
                else
                {
                    var newRegionAttachment = region.ToRegionAttachment(region.name, scale);
                    slot.Attachment = newRegionAttachment;
                }
                slot.Skeleton.Skin.SetAttachment(slot.Data.Index, info.slotPlaceholderName, slot.Attachment);
            }

            Skin repackedSkin = new Skin(RepackConst);

            repackedSkin.Append(skeletonAnimation.Skeleton.Data.DefaultSkin); // Include the "default" skin. (everything outside of skin placeholders)
            repackedSkin.Append(skeletonAnimation.Skeleton.Skin);             // Include your new custom skin.
            Texture2D runtimeAtlas    = null;
            Material  runtimeMaterial = null;

            repackedSkin = repackedSkin.GetRepackedSkin(RepackConst, skeletonAnimation.SkeletonDataAsset.atlasAssets[0].materials[0], out runtimeMaterial, out runtimeAtlas); // Pack all the items in the skin.
            skeletonAnimation.Skeleton.SetSkin(repackedSkin);                                                                                                                 // Assign the repacked skin to your Skeleton.
            skeletonAnimation.skeleton.SetSlotsToSetupPose();                                                                                                                 // Use the pose from setup pose.
            skeletonAnimation.Update(0);                                                                                                                                      // Use the pose in the currently active animation.
        }
Example #14
0
        private void SacredJourney()
        {
            RunebookEntry e = Atlas.Entries[Selected];

            if (RunebookGump.HasSpell(User, 209))
            {
                SendLocationMessage(e, User);

                Atlas.OnTravel();
                new SacredJourneySpell(User, null, e, null).Cast();
                Atlas.NextUse = DateTime.UtcNow;
            }
            else
            {
                User.SendLocalizedMessage(500015); // You do not have that spell!
            }

            Atlas.Openers.Remove(User);
        }
Example #15
0
            public static object Process(string assetNameFull, object asset)
            {
                if (DumpOnLoad)
                {
                    Dump(assetNameFull, asset);
                }

                string assetName = assetNameFull;

                if (assetName.StartsWith(PathContentOrig))
                {
                    assetName = assetName.Substring(PathContentOrig.Length + 1);
                }

                int loadedIndex = LoadedAssetPaths.IndexOf(assetName);

                if (loadedIndex == -1)
                {
                    LoadedAssetPaths.Add(assetName);
                    LoadedAssetFullPaths.Add(assetNameFull);
                    LoadedAssets.Add(new WeakReference(asset));
                }
                else
                {
                    LoadedAssets[loadedIndex] = new WeakReference(asset);
                }

                if (asset is Atlas)
                {
                    Atlas atlas = asset as Atlas;

                    AssetMetadata mapping = Get(assetName, true);
                    if (mapping == null || mapping.AssetType != typeof(AssetTypeDirectory))
                    {
                        return(asset);
                    }

                    atlas.Ingest(mapping);
                }

                // TODO: Allow mods to process the asset at runtime.
                return(asset);
            }
    void OnSceneGUI()
    {
        // get tilemap as target object
        var targetTilemap = target as TileMap;

        // only process edit mode input if tilemap is selected
        if (targetTilemap != null)
        {
            int controlID = GUIUtility.GetControlID(FocusType.Passive);
            if (Event.current.GetTypeForControl(controlID) == EventType.MouseDown)
            {
                GUIUtility.hotControl = controlID;

                // manipulate current event's mouse position on screen
                Vector2 mousePosition = Event.current.mousePosition;

                // flip y-axis mouse position information
                mousePosition.y = SceneView.currentDrawingSceneView.camera.pixelHeight - mousePosition.y;

                // translate screen click to world point
                Vector2 worldPoint = SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(mousePosition);

                // shift world point using tilemap transform position
                worldPoint.x -= targetTilemap.transform.position.x;
                worldPoint.y -= targetTilemap.transform.position.y;

                // get x and y in tiles
                Atlas atlas = targetTilemap.GetComponent <Atlas>();
                int   tileX = Mathf.FloorToInt((worldPoint.x * 100) / atlas.tileWidth);
                int   tileY = Mathf.FloorToInt((worldPoint.y * 100) / atlas.tileHeight);

                Debug.Log("Tile: " + tileX + ", " + tileY);

                // use TileMap method to draw tile to TileMap
                if (targetTilemap.DrawTile(tileX, tileY, atlas.selected) == null)
                {
                    // switch control back to the Editor if clicking outside of TileMap
                    GUIUtility.hotControl = 0;
                }
            }
        }
    }
        /// <summary>
        /// スプライトポップアップを描画します.
        /// </summary>
        /// <param name="atlas">アトラス.</param>
        /// <param name="spriteName">スプライト名.</param>
        /// <param name="onChange">変更された時のコールバック.</param>
        public static void DrawSpritePopup(GUIContent label, Atlas atlas, string spriteName, UnityAction <string> onChange)
        {
            int controlID = GUIUtility.GetControlID(FocusType.Passive);

            EditorGUI.BeginDisabledGroup(!atlas);
            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.PrefixLabel(label);

            Texture2D tex = atlas ? atlas.atlasTexture : null;

            string assetLabel = tex ? tex.name.Replace(" ", "_") : "";

            if (GUILayout.Button(string.IsNullOrEmpty(spriteName) ? "-" : spriteName, "minipopup"))
            {
                //オブジェクトピッカーで表示させるオブジェクトを制限するために、アトラステクスチャに対して一時的にラベルを設定します.
                //オブジェクトピッカーには、アトラス内スプライトのみが表示されます.
                AssetDatabase.SetLabels(tex, AssetDatabase.GetLabels(tex).Union(new [] { assetLabel }).ToArray());
                EditorGUIUtility.ShowObjectPicker <Sprite>(atlas.GetSprite(spriteName), false, "l:" + assetLabel, controlID);
            }

            EditorGUILayout.EndHorizontal();
            EditorGUI.EndDisabledGroup();

            //現在のオブジェクトピッカーであれば、イベント処理.
            if (controlID == EditorGUIUtility.GetObjectPickerControlID())
            {
                string commandName = Event.current.commandName;
                //選択オブジェクト更新イベント
                if (commandName == "ObjectSelectorUpdated")
                {
                    UnityEngine.Object picked = EditorGUIUtility.GetObjectPickerObject();
                    onChange(picked ? picked.name : "");
                }
                //クローズイベント
                else if (commandName == "ObjectSelectorClosed")
                {
                    //アトラステクスチャの一時的なラベルを除外します.
                    AssetDatabase.SetLabels(tex, AssetDatabase.GetLabels(tex).Except(new [] { assetLabel }).ToArray());
                }
            }
        }
Example #18
0
            /// <summary>
            /// Process an asset and register it for further reprocessing in the future.
            /// Apply any mod-related changes to the asset based on the existing mod asset meta map.
            /// </summary>
            /// <param name="asset">The asset to process.</param>
            /// <param name="assetNameFull">The "full name" of the asset, preferable the relative asset path.</param>
            /// <returns>The processed asset.</returns>
            public static object Process(object asset, string assetNameFull)
            {
                if (DumpOnLoad)
                {
                    Dump(assetNameFull, asset);
                }

                string assetName = assetNameFull;

                if (assetName.StartsWith(PathContentOrig))
                {
                    assetName = assetName.Substring(PathContentOrig.Length + 1);
                }

                int loadedIndex = LoadedAssetPaths.IndexOf(assetName);

                if (loadedIndex == -1)
                {
                    LoadedAssetPaths.Add(assetName);
                    LoadedAssetFullPaths.Add(assetNameFull);
                    LoadedAssets.Add(new WeakReference(asset));
                }
                else
                {
                    LoadedAssets[loadedIndex] = new WeakReference(asset);
                }

                if (asset is Atlas)
                {
                    Atlas atlas = asset as Atlas;

                    ModAsset mapping = Get(assetName, true);
                    if (mapping == null || mapping.AssetType != typeof(AssetTypeDirectory))
                    {
                        return(asset);
                    }

                    atlas.Ingest(mapping);
                }

                return(OnProcess?.InvokePassing(asset, assetNameFull) ?? asset);
            }
 public void Init(Ust ust, Atlas atlas)
 {
     Atlas  = atlas;
     Ust    = ust;
     Parser = new Parser(Atlas, Ust);
     Settings.MinLengthDefault = 110 * (int)Ust.Tempo / 120;
     Settings.MinLength        = Settings.MinLengthDefault;
     textBoxMinLength.Text     = Settings.MinLength.ToString();
     ImportDict();
     comboBoxLanguage.Items.Clear();
     comboBoxLanguage.Items.AddRange(Lang.Languages);
     comboBoxLanguage.SelectedItem = Lang.Current;
     SetLyric();
     buttonSetText.Enabled = false;
     SetTextWindow         = new SetTextWindow(Atlas, Ust);
     if (Singer.Current.IsLoaded)
     {
         checkBoxLengthByOto.Checked = true;
     }
 }
Example #20
0
    private static XmlNode WriteAtlas(Atlas atlas, XmlDocument document)
    {
        XmlNode node = document.CreateElement("Atlas");

        FieldInfo[] fields = GetFields(atlas.GetType());
        foreach (FieldInfo field in fields)
        {
            if (field.FieldType.IsSubclassOf(typeof(UnityEngine.Object)))
            {
                XmlNode childNode = WriteAssetField(field, atlas, document);
                node.AppendChild(childNode);
            }
            else
            {
                XmlNode childNode = WriteField(field, atlas, document);
                node.AppendChild(childNode);
            }
        }
        return(node);
    }
        public CCSkeleton(string skeletonDataFile, string atlasFile, float scale = 0)
        {
            Initialize();

            using (StreamReader atlasStream = new StreamReader(CCFileUtils.GetFileStream(atlasFile)))
            {
                atlas = new Atlas(atlasStream, "", new CocosSharpTextureLoader());
            }

            SkeletonJson json = new SkeletonJson(atlas);

            json.Scale = scale == 0 ? 1 : scale;

            using (StreamReader skeletonDataStream = new StreamReader(CCFileUtils.GetFileStream(skeletonDataFile)))
            {
                SkeletonData skeletonData = json.ReadSkeletonData(skeletonDataStream);
                skeletonData.Name = skeletonDataFile;
                SetSkeletonData(skeletonData, true);
            }
        }
    public static void SaveAtlas(Atlas atlas, string name)
    {
        if (atlas == null || atlas.texture == null)
        {
            return;
        }

        var bytes = atlas.texture.EncodeToPNG();

        if (!System.IO.Directory.Exists("./Debug/"))
        {
            System.IO.Directory.CreateDirectory("./Debug/");
        }

        //string name = Time.realtimeSinceStartup.ToString().Replace(".", "-"); //DateTime.UtcNow.ToString().Replace("/", "_").Replace(" ", "_").Replace("\\", "_");
        string file = "./Debug/" + name + ".png";

        System.IO.File.WriteAllBytes(file, bytes);
        Debug.Log("SAVE TO: " + file);
    }
        /// <summary>
        /// Loads skeleton
        /// </summary>
        /// <param name="atlasNode"></param>
        /// <param name="textureLoader"></param>
        /// <returns></returns>
        public static SkeletonData LoadSkeleton(WzStringProperty atlasNode, TextureLoader textureLoader)
        {
            string atlasData = atlasNode.GetString();

            if (string.IsNullOrEmpty(atlasData))
            {
                return(null);
            }
            StringReader atlasReader = new StringReader(atlasData);

            Atlas        atlas = new Atlas(atlasReader, string.Empty, textureLoader);
            SkeletonData skeletonData;

            if (!TryLoadSkeletonJsonOrBinary(atlasNode, atlas, out skeletonData))
            {
                atlas.Dispose();
                return(null);
            }
            return(skeletonData);
        }
Example #24
0
    public Atlas GetAtlas()
    {
        if (this.atlasFile == null)
        {
            Debug.LogError("Atlas file not set for atlas asset: " + base.get_name(), this);
            this.Reset();
            return(null);
        }
        if (this.materials == null || this.materials.Length == 0)
        {
            Debug.LogError("Materials not set for atlas asset: " + base.get_name(), this);
            this.Reset();
            return(null);
        }
        if (this.atlas != null)
        {
            return(this.atlas);
        }
        Atlas result;

        try
        {
            this.atlas = new Atlas(new StringReader(this.atlasFile.get_text()), string.Empty, new MaterialsTextureLoader(this));
            this.atlas.FlipV();
            result = this.atlas;
        }
        catch (Exception ex)
        {
            Debug.LogError(string.Concat(new string[]
            {
                "Error reading atlas file for atlas asset: ",
                base.get_name(),
                "\n",
                ex.get_Message(),
                "\n",
                ex.get_StackTrace()
            }), this);
            result = null;
        }
        return(result);
    }
Example #25
0
        public void Start()
        {
            //读取GamePlay的MTexture文件
            Debug.Log("==读取GamePlay的Texture");
            Gfx.Game        = Atlas.FromAtlas(Path.Combine("Graphics", "Atlases", "Gameplay"), Atlas.AtlasDataFormat.Packer);
            Gfx.BGAutotiler = new Autotiler(Path.Combine("Graphics", "BackgroundTiles.xml"));
            Gfx.FGAutotiler = new Autotiler(Path.Combine("Graphics", "ForegroundTiles.xml"));

            //Gfx.SceneryTiles = new Tileset(Gfx.Game["tilesets/scenery"], 8, 8);
            //Gfx.AnimatedTilesBank = new AnimatedTilesBank();
            //foreach (XmlElement xml in (XmlNode)XmlUtils.LoadContentXML(Path.Combine("Graphics", "AnimatedTiles.xml"))["Data"])
            //{
            //    if (xml != null)
            //        Gfx.AnimatedTilesBank.Add(xml.Attr("name"), xml.AttrFloat("delay", 0.0f), xml.AttrVector2("posX", "posY", Vector2.zero), xml.AttrVector2("origX", "origY", Vector2.zero), Gfx.Game.GetAtlasSubtextures(xml.Attr("path")));
            //}
            Debug.Log("==加载AreaData文件");
            SaveData.Start(new SaveData
            {
                Name        = "test001",
                AssistMode  = true,
                VariantMode = true
            }, 0);
            //加载区域
            AreaData.Load();

            Debug.Log("==创建Session,读取关卡地图");
            Session session = new Session(new AreaKey(0, AreaMode.Normal), null, null);
            bool    flag    = level != null && session.MapData.Get(level) != null;

            if (flag)
            {
                session.Level      = level;
                session.FirstLevel = false;
            }

            Debug.Log("==加载关卡LevelLoad");
            LevelLoader loader = new LevelLoader(session, null);

            //StartCoroutine(DrawTiles(loader.Level.BgTiles.Tiles));
            StartCoroutine(DrawTiles(loader.solidTiles.Tiles));
        }
Example #26
0
        /// <summary>
        /// Gets the particle.
        /// </summary>
        /// <returns>
        /// A new particle.
        /// </returns>
        public override IParticle GetParticle()
        {
            var frameDelay = MathsHelper.Random(7, 15);
            var particle   = Atlas.GetAnimatedParticle(
                "gameplay",
                "ReverseSmallCrossSparkle",
                this,
                this.GetBoundPosition(),
                Vector2.Zero,
                0f,
                0f,
                this.Scale,
                recycle: true,
                fadeIn: true,
                fadeOut: true,
                frameDelay: frameDelay,
                trackParent: false,
                shrink: false);

            return(particle);
        }
    /// <summary>
    /// Releases all textures with provided names in atlas.
    /// When the last user releases texture from atlas than it is marked as unused, and can be run over by other texture.
    /// Requires:
    /// Every name in provided list is unique in that list.
    /// </summary>
    /// <param name="textureNames">Names of textures that will be released.</param>
    public void Release(List <string> textureNames)
    {
        if (textureNames != null && textureNames.Count > 0 && atlas != null)
        {
            // If sprite's OnDestroy method is called after DynamicAtlasManager's OnApplicationQuit
            // calling Atlas property would cause creating new GameObject; Because it was previously deleted from DynamicAtlasManager.

            for (int i = 0; i < textureNames.Count; i++)
            {
                var spriteData = Atlas.GetSprite(textureNames[i]) as DynamicSpriteData;
                if (spriteData != null && spriteData.IsUsed())
                {
                    spriteData.Release();
                    if (!spriteData.IsUsed())
                    {
                        numberOfUnused++;
                    }
                }
            }
        }
    }
Example #28
0
        public static byte curWESlotGroup;         // Tracks which wheel menu is currently selected (relevant for the Utility Bar).

        public WE_UI(WEScene scene)
        {
            this.scene = scene;
            this.atlas = Systems.mapper.atlas[(byte)AtlasGroup.World];

            // UI Components
            this.gridUI     = new GridOverlay(null, (byte)WorldmapEnum.TileWidth, (byte)WorldmapEnum.TileHeight);
            this.utilityBar = new WEUtilityBar(null, this.scene, (byte)WorldmapEnum.TileWidth, (short)(Systems.screen.viewHeight - (byte)WorldmapEnum.TileHeight));
            this.scroller   = new WEScroller(null, this.scene, (short)(Systems.screen.viewWidth - (byte)WorldmapEnum.TileWidth), 0);
            this.statusText = new UIStatusText(null, (short)Systems.screen.viewHalfWidth, 5);

            // Tab Menu - WorldTileTool Listings
            this.weMenu = new WEMenu(null, (short)(Systems.screen.viewWidth * 0.5f), (short)(Systems.screen.viewHeight * 0.5f), 4, 2);

            this.weMenu.SetMenuOption((byte)1, Systems.mapper.atlas[(byte)AtlasGroup.World], "Mud/b1", "Terrain");
            this.weMenu.SetMenuOption((byte)2, Systems.mapper.atlas[(byte)AtlasGroup.World], "Desert/p7", "Detail");
            this.weMenu.SetMenuOption((byte)3, Systems.mapper.atlas[(byte)AtlasGroup.World], "MountainBrown/s", "Coverage");
            this.weMenu.SetMenuOption((byte)4, Systems.mapper.atlas[(byte)AtlasGroup.World], "Objects/Pyramid1", "Objects");
            this.weMenu.SetMenuOption((byte)5, Systems.mapper.atlas[(byte)AtlasGroup.World], "Objects/NodeStrict", "Nodes");
            this.weMenu.SetMenuOption((byte)6, UIHandler.atlas, "Move", "Resize");
        }
Example #29
0
    void OnSelectAtlas(Object obj)
    {
        if (obj == null)
        {
            return;
        }

        //if _mAtlas been destroyed, need to do a check
        if (_mAtlas == null)
        {
            _mAtlas = null;
        }

        if (_mAtlas != obj)
        {
            _mAtlas = obj as Atlas;
            InitSerializedProperties();
        }

        Repaint();
    }
    static public Sprite LoadSheet(string Path)
    {
        //Debug.Log(Path);

        string[] Array = Path.Split("/" [0]);

        Atlas Atlas = AddNewAtlas(Array[0]);

        for (int i = 0; i < Atlas.SpriteList.Length; i++)
        {
            //Debug.Log(Atlas.SpriteList[i].name);

            if (Atlas.SpriteList[i].name == Array[1])
            {
                return(Atlas.SpriteList[i]);
            }
        }

        Debug.Log(Array[1] + " doesn't exist on " + Array[0]);
        return(Atlas.SpriteList[0]);
    }
	void Apply (SkeletonRenderer skeletonRenderer) {
		atlas = atlasAsset.GetAtlas();

		AtlasAttachmentLoader loader = new AtlasAttachmentLoader(atlas);

		float scaleMultiplier = skeletonRenderer.skeletonDataAsset.scale;

		var enumerator = attachments.GetEnumerator();
		while (enumerator.MoveNext()) {
			var entry = (SlotRegionPair)enumerator.Current;
			var regionAttachment = loader.NewRegionAttachment(null, entry.region, entry.region);
			regionAttachment.Width = regionAttachment.RegionOriginalWidth * scaleMultiplier;
			regionAttachment.Height = regionAttachment.RegionOriginalHeight * scaleMultiplier;

			regionAttachment.SetColor(new Color(1, 1, 1, 1));
			regionAttachment.UpdateOffset();

			var slot = skeletonRenderer.skeleton.FindSlot(entry.slot);
			slot.Attachment = regionAttachment;
		}
	}
Example #32
0
        /// <summary>
        /// Unpacks any texture atlases that needs to be loaded.
        /// </summary>
        public static void UnpackAtlases()
        {
            GFX.Gameplay = Atlas.FromAtlas(Path.Combine(Settings.CelesteDirectory, "Content", "Graphics", "Atlases", "Gameplay"), AtlasFormat.Packer);
            GFX.Empty    = new DrawableTexture(GFX.Gameplay.Sources[0], 4094, 4094, 1, 1);
            GFX.Pixel    = new DrawableTexture(GFX.Gameplay.Sources[0], 13, 13, 1, 1);
            GFX.Scenery  = new Tileset(GFX.Gameplay["tilesets/scenery"], 8, 8);

            // PICO-8 font loading
            DrawableTexture font = GFX.Gameplay["pico8/font"];

            GFX.Font = new DrawableTexture[font.Width / 4 * (font.Height / 6)];
            for (int i = 0; i < font.Height / 6; i++)
            {
                for (int j = 0; j < font.Width / 4; j++)
                {
                    GFX.Font[j + i * (font.Width / 4)] = new DrawableTexture(font, j * 4, i * 6, 4, 6);
                }
            }

            Finished = true;
        }
        public SimpleTileLayerTest()
        {
            var tilesetMock0 = new Mock <TilesetTable>();

            tilesetMock0.Setup(x => x.TileNumber(It.IsAny <string>())).Returns(0);
            var tilesetMock1 = new Mock <TilesetTable>();

            tilesetMock1.Setup(x => x.TileNumber(It.IsAny <string>())).Returns(1);

            var mockTile1 = new Mock <Tile>(MockBehavior.Default, tilesetMock0.Object);
            var mockTile2 = new Mock <Tile>(MockBehavior.Default, tilesetMock1.Object);
            var tile0     = mockTile1.Object;
            var tile1     = mockTile2.Object;

            Tile[] row0 = new Tile[] { tile0, tile1, tile1 };
            Tile[] row1 = new Tile[] { tile1, tile1, tile0 };
            Tile[] row2 = new Tile[] { tile0, tile1, tile0 };

            m_tileArray = new[]
            {
                row0, row1, row2
            };

            m_tileSequenceArray = new Tile[] {
                row0[0], row1[0], row2[0],
                row0[1], row1[1], row2[1],
                row0[2], row1[2], row2[2],
            };

            m_simpleTileLayer = new SimpleTileLayer(LayerType.Obstacle, 3, 3)
            {
                Tiles = m_tileArray
            };

            var atlas = new Atlas();

            atlas.IncrementTime(new TimeSpan(atlas.YearLength.Ticks / 2)); // Set summer
            m_simpleTileLayer.UpdateTileStates(atlas);
        }
Example #34
0
        private static Dictionary <string, Sprite> GetSpriteAtlas(SpriteManager.Group groupKey)
        {
            if (!SpriteManager.mapping.TryGetValue(groupKey, out string atlasName))
            {
                Logger.Error($"SpritePatcher was unable to find a sprite mapping for {nameof(SpriteManager.Group)}.{groupKey}");
                return(null);
            }
#if SUBNAUTICA
            var atlas = Atlas.GetAtlas(atlasName);
            if (atlas?.nameToSprite != null)
            {
                return(atlas.nameToSprite);
            }
#elif BELOWZERO
            if (SpriteManager.atlases.TryGetValue(atlasName, out var spriteGroup))
            {
                return(spriteGroup);
            }
#endif
            Logger.Error($"SpritePatcher was unable to find a sprite atlas for {nameof(SpriteManager.Group)}.{groupKey}");
            return(null);
        }
        public virtual ActionResult SelectContinent(int?selectedContinentId)
        {
            var countries = selectedContinentId.HasValue
                ? this._continentRepository.Find(selectedContinentId.Value).Countries
                : null;

            Atlas atlas = new Atlas
            {
                SelectedContinentId = selectedContinentId,
                Continents          = this._continentRepository.All,
                Countries           = countries
            };

            if (Request.IsAjaxRequest( ))
            {
                return(PartialView(MVC.CascadingDropDownLists.DropDownAjaxPost.Views._Countries, atlas));
            }
            else
            {
                return(View(MVC.CascadingDropDownLists.DropDownAjaxPost.Views.Index, atlas));
            }
        }
        public SimpleTileLayerTest()
        {
            var tilesetMock0 = new Mock<ITilesetTable>();
            tilesetMock0.Setup(x => x.TileNumber(It.IsAny<string>())).Returns(0);
            var tilesetMock1 = new Mock<ITilesetTable>();
            tilesetMock1.Setup(x => x.TileNumber(It.IsAny<string>())).Returns(1);

            var mockTile1 = new Mock<Tile>(MockBehavior.Default, tilesetMock0.Object);
            var mockTile2 = new Mock<Tile>(MockBehavior.Default, tilesetMock1.Object);
            var tile0 = mockTile1.Object;
            var tile1 = mockTile2.Object;

            Tile[] row0 = new Tile[] { tile0, tile1, tile1 };
            Tile[] row1 = new Tile[] { tile1, tile1, tile0 };
            Tile[] row2 = new Tile[] { tile0, tile1, tile0 };

            m_tileArray = new[]
                {
                    row0, row1, row2
                };

            m_tileSequenceArray = new Tile[] {
                row0[0], row1[0], row2[0],
                row0[1], row1[1], row2[1],
                row0[2], row1[2], row2[2],
                };

            m_simpleTileLayer = new SimpleTileLayer(LayerType.Obstacle, 3, 3)
            {
                Tiles = m_tileArray
            };

            var atlas = new Atlas();
            atlas.IncrementTime(new TimeSpan(atlas.YearLength.Ticks / 2)); // Set summer
            m_simpleTileLayer.UpdateTileStates(atlas);
        }
    public static void SaveAtlas(Atlas atlas, string name)
    {
        if (atlas == null || atlas.texture == null)
            return;

        var bytes = atlas.texture.EncodeToPNG();

        if (!System.IO.Directory.Exists(Application.persistentDataPath + "/Debug/"))
            System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/Debug/");

        //string name = Time.realtimeSinceStartup.ToString().Replace(".", "-"); //DateTime.UtcNow.ToString().Replace("/", "_").Replace(" ", "_").Replace("\\", "_");
        string file = Application.persistentDataPath + "/Debug/" + name + ".png";

        System.IO.File.WriteAllBytes(file, bytes);
        //Debug.LogError("SAVE TO: " + file);
    }
Example #38
0
 public AtlasItem(Atlas atlas, Bitmap bitmap)
 {
     this.atlas = atlas;
     this.bitmap = bitmap;
 }
Example #39
0
	public void Reset () {
		atlas = null;
	}
    public SkeletonData GetSkeletonData(bool quiet)
    {
        if (atlasAssets == null) {
            atlasAssets = new AtlasAsset[0];
            if (!quiet)
                Debug.LogError("Atlas not set for SkeletonData asset: " + name, this);
            Reset();
            return null;
        }

        if (skeletonJSON == null) {
            if (!quiet)
                Debug.LogError("Skeleton JSON file not set for SkeletonData asset: " + name, this);
            Reset();
            return null;
        }

        #if !SPINE_TK2D
        if (atlasAssets.Length == 0) {
            Reset();
            return null;
        }
        #else
        if (atlasAssets.Length == 0 && spriteCollection == null) {
            Reset();
            return null;
        }
        #endif

        Atlas[] atlasArr = new Atlas[atlasAssets.Length];
        for (int i = 0; i < atlasAssets.Length; i++) {
            if (atlasAssets[i] == null) {
                Reset();
                return null;
            }
            atlasArr[i] = atlasAssets[i].GetAtlas();
            if (atlasArr[i] == null) {
                Reset();
                return null;
            }
        }

        if (skeletonData != null)
            return skeletonData;

        AttachmentLoader attachmentLoader;
        float skeletonDataScale;

        #if !SPINE_TK2D
        attachmentLoader = new AtlasAttachmentLoader(atlasArr);
        skeletonDataScale = scale;
        #else
        if (spriteCollection != null) {
            attachmentLoader = new SpriteCollectionAttachmentLoader(spriteCollection);
            skeletonDataScale = (1.0f / (spriteCollection.invOrthoSize * spriteCollection.halfTargetHeight) * scale);
        } else {
            if (atlasArr.Length == 0) {
                Reset();
                if (!quiet) Debug.LogError("Atlas not set for SkeletonData asset: " + name, this);
                return null;
            }
            attachmentLoader = new AtlasAttachmentLoader(atlasArr);
            skeletonDataScale = scale;
        }
        #endif

        try {
            //var stopwatch = new System.Diagnostics.Stopwatch();
            if (skeletonJSON.name.ToLower().Contains(".skel")) {
                var input = new MemoryStream(skeletonJSON.bytes);
                var binary = new SkeletonBinary(attachmentLoader);
                binary.Scale = skeletonDataScale;
                //stopwatch.Start();
                skeletonData = binary.ReadSkeletonData(input);
            } else {
                var input = new StringReader(skeletonJSON.text);
                var json = new SkeletonJson(attachmentLoader);
                json.Scale = skeletonDataScale;
                //stopwatch.Start();
                skeletonData = json.ReadSkeletonData(input);
            }
            //stopwatch.Stop();
            //Debug.Log(stopwatch.Elapsed);
        } catch (Exception ex) {
            if (!quiet)
                Debug.LogError("Error reading skeleton JSON file for SkeletonData asset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, this);
            return null;
        }

        stateData = new AnimationStateData(skeletonData);
        FillStateData();

        return skeletonData;
    }
    static void UpdateVertexCache(tk2dSpriteCollection gen, Atlas.AtlasData[] packers, tk2dSpriteCollectionData coll, List<SCGE.SpriteLut> spriteLuts)
    {
        float scale = 2.0f * gen.targetOrthoSize / gen.targetHeight;
        int padAmount = GetPadAmount(gen);

        for (int i = 0; i < sourceTextures.Length; ++i)
        {
            SCGE.SpriteLut _lut = null;
            for (int j = 0; j < spriteLuts.Count; ++j)
            {
                if (spriteLuts[j].source == i)
                {
                    _lut = spriteLuts[j];
                    break;
                }
            }

            tk2dSpriteCollectionDefinition thisTexParam = gen.textureParams[i];
            Atlas.AtlasData packer = null;
            Atlas.AtlasEntry atlasEntry = null;
            int atlasIndex = 0;
            foreach (var p in packers)
            {
                if ((atlasEntry = p.FindEntryWithIndex(_lut.atlasIndex)) != null)
                {
                    packer = p;
                    break;
                }
                ++atlasIndex;
            }
            float fwidth = packer.width;
            float fheight = packer.height;

            int tx = atlasEntry.x + padAmount, ty = atlasEntry.y + padAmount, tw = atlasEntry.w - padAmount * 2, th = atlasEntry.h - padAmount * 2;
            int sd_y = packer.height - ty - th;

            float uvOffsetX = 0.001f / fwidth;
            float uvOffsetY = 0.001f / fheight;

            Vector2 v0 = new Vector2(tx / fwidth + uvOffsetX, 1.0f - (sd_y + th) / fheight + uvOffsetY);
            Vector2 v1 = new Vector2((tx + tw) / fwidth - uvOffsetX, 1.0f - sd_y / fheight - uvOffsetY);

            Mesh mesh = null;
            Transform meshTransform = null;
            GameObject instantiated = null;

            if (thisTexParam.overrideMesh)
            {
                // Disabled
                instantiated = GameObject.Instantiate(thisTexParam.overrideMesh) as GameObject;
                MeshFilter meshFilter = instantiated.GetComponentInChildren<MeshFilter>();
                if (meshFilter == null)
                {
                    Debug.LogError("Unable to find mesh");
                    GameObject.DestroyImmediate(instantiated);
                }
                else
                {
                    mesh = meshFilter.sharedMesh;
                    meshTransform = meshFilter.gameObject.transform;
                }
            }

            if (mesh)
            {
                coll.spriteDefinitions[i].positions = new Vector3[mesh.vertices.Length];
                coll.spriteDefinitions[i].uvs = new Vector2[mesh.vertices.Length];
                for (int j = 0; j < mesh.vertices.Length; ++j)
                {
                    coll.spriteDefinitions[i].positions[j] = meshTransform.TransformPoint(mesh.vertices[j]);
                    coll.spriteDefinitions[i].uvs[j] = new Vector2(v0.x + (v1.x - v0.x) * mesh.uv[j].x, v0.y + (v1.y - v0.y) * mesh.uv[j].y);
                }
                coll.spriteDefinitions[i].indices = new int[mesh.triangles.Length];
                for (int j = 0; j < mesh.triangles.Length; ++j)
                {
                    coll.spriteDefinitions[i].indices[j] = mesh.triangles[j];
                }
                coll.spriteDefinitions[i].material = gen.atlasMaterials[atlasIndex];

                GameObject.DestroyImmediate(instantiated);
            }
            else
            {
                Texture2D thisTextureRef = sourceTextures[i];

                float texHeight = thisTextureRef?thisTextureRef.height:2;
           			float texWidth = thisTextureRef?thisTextureRef.width:2;

                float h = thisTextureRef?thisTextureRef.height:64;
                float w = thisTextureRef?thisTextureRef.width:64;
                h *= thisTexParam.scale.x;
                w *= thisTexParam.scale.y;

                float scaleX = w * scale;
                float scaleY = h * scale;

                Vector3 pos0 = new Vector3(-0.5f * scaleX, 0, -0.5f * scaleY);
                switch (thisTexParam.anchor)
                {
                    case tk2dSpriteCollectionDefinition.Anchor.LowerLeft: pos0 = new Vector3(0, 0, 0); break;
                    case tk2dSpriteCollectionDefinition.Anchor.LowerCenter: pos0 = new Vector3(-0.5f * scaleX, 0, 0); break;
                    case tk2dSpriteCollectionDefinition.Anchor.LowerRight: pos0 = new Vector3(-scaleX, 0, 0); break;

                    case tk2dSpriteCollectionDefinition.Anchor.MiddleLeft: pos0 = new Vector3(0, 0, -0.5f * scaleY); break;
                    case tk2dSpriteCollectionDefinition.Anchor.MiddleCenter: pos0 = new Vector3(-0.5f * scaleX, 0, -0.5f * scaleY); break;
                    case tk2dSpriteCollectionDefinition.Anchor.MiddleRight: pos0 = new Vector3(-scaleX, 0, -0.5f * scaleY); break;

                    case tk2dSpriteCollectionDefinition.Anchor.UpperLeft: pos0 = new Vector3(0, 0, -scaleY); break;
                    case tk2dSpriteCollectionDefinition.Anchor.UpperCenter: pos0 = new Vector3(-0.5f * scaleX, 0, -scaleY); break;
                    case tk2dSpriteCollectionDefinition.Anchor.UpperRight: pos0 = new Vector3(-scaleX, 0, -scaleY); break;

                    case tk2dSpriteCollectionDefinition.Anchor.Custom:
                        {
                            pos0 = new Vector3(-thisTexParam.anchorX * thisTexParam.scale.x * scale, 0, -(h - thisTexParam.anchorY * thisTexParam.scale.y) * scale);
                        }
                        break;
                }

                Vector3 pos1 = pos0 + new Vector3(scaleX, 0, scaleY);

                List<Vector3> positions = new List<Vector3>();
                List<Vector2> uvs = new List<Vector2>();

                // build mesh
                if (_lut.isSplit)
                {
                    for (int j = 0; j < spriteLuts.Count; ++j)
                    {
                        if (spriteLuts[j].source == i)
                        {
                            _lut = spriteLuts[j];

                            int thisAtlasIndex = 0;
                            foreach (var p in packers)
                            {
                                if ((atlasEntry = p.FindEntryWithIndex(_lut.atlasIndex)) != null)
                                {
                                    packer = p;
                                    break;
                                }
                                ++thisAtlasIndex;
                            }

                            if (thisAtlasIndex != atlasIndex)
                            {
                                // This is a serious problem, dicing is not supported when multi atlas output is selected
                                Debug.Break();
                            }

                            fwidth = packer.width;
                            fheight = packer.height;

                            tx = atlasEntry.x + padAmount;
                            ty = atlasEntry.y + padAmount;
                            tw = atlasEntry.w - padAmount * 2;
                            th = atlasEntry.h - padAmount * 2;

                            sd_y = packer.height - ty - th;
                            v0 = new Vector2(tx / fwidth + uvOffsetX, 1.0f - (sd_y + th) / fheight + uvOffsetY);
                            v1 = new Vector2((tx + tw) / fwidth - uvOffsetX, 1.0f - sd_y / fheight - uvOffsetY);

                            float x0 = _lut.rx / texWidth;
                            float y0 = _lut.ry / texHeight;
                            float x1 = (_lut.rx + _lut.rw) / texWidth;
                            float y1 = (_lut.ry + _lut.rh) / texHeight;

                            Vector3 dpos0 = new Vector3(Mathf.Lerp(pos0.x, pos1.x, x0), 0.0f, Mathf.Lerp(pos0.z, pos1.z, y0));
                            Vector3 dpos1 = new Vector3(Mathf.Lerp(pos0.x, pos1.x, x1), 0.0f, Mathf.Lerp(pos0.z, pos1.z, y1));

                            positions.Add(new Vector3(dpos0.x, dpos0.z, 0));
                            positions.Add(new Vector3(dpos1.x, dpos0.z, 0));
                            positions.Add(new Vector3(dpos0.x, dpos1.z, 0));
                            positions.Add(new Vector3(dpos1.x, dpos1.z, 0));

                            if (atlasEntry.flipped)
                            {
                                uvs.Add(new Vector2(v0.x,v0.y));
                                uvs.Add(new Vector2(v0.x,v1.y));
                                uvs.Add(new Vector2(v1.x,v0.y));
                                uvs.Add(new Vector2(v1.x,v1.y));
                            }
                            else
                            {
                                uvs.Add(new Vector2(v0.x,v0.y));
                                uvs.Add(new Vector2(v1.x,v0.y));
                                uvs.Add(new Vector2(v0.x,v1.y));
                                uvs.Add(new Vector2(v1.x,v1.y));
                            }
                        }
                    }
                }
                else
                {
                    float x0 = _lut.rx / texWidth;
                    float y0 = _lut.ry / texHeight;
                    float x1 = (_lut.rx + _lut.rw) / texWidth;
                    float y1 = (_lut.ry + _lut.rh) / texHeight;

                    Vector3 dpos0 = new Vector3(Mathf.Lerp(pos0.x, pos1.x, x0), 0.0f, Mathf.Lerp(pos0.z, pos1.z, y0));
                    Vector3 dpos1 = new Vector3(Mathf.Lerp(pos0.x, pos1.x, x1), 0.0f, Mathf.Lerp(pos0.z, pos1.z, y1));

                    positions.Add(new Vector3(dpos0.x, dpos0.z, 0));
                    positions.Add(new Vector3(dpos1.x, dpos0.z, 0));
                    positions.Add(new Vector3(dpos0.x, dpos1.z, 0));
                    positions.Add(new Vector3(dpos1.x, dpos1.z, 0));

                    if (atlasEntry.flipped)
                    {
                        uvs.Add(new Vector2(v0.x,v0.y));
                        uvs.Add(new Vector2(v0.x,v1.y));
                        uvs.Add(new Vector2(v1.x,v0.y));
                        uvs.Add(new Vector2(v1.x,v1.y));
                    }
                    else
                    {
                        uvs.Add(new Vector2(v0.x,v0.y));
                        uvs.Add(new Vector2(v1.x,v0.y));
                        uvs.Add(new Vector2(v0.x,v1.y));
                        uvs.Add(new Vector2(v1.x,v1.y));
                    }
                }

                // build sprite definition
                coll.spriteDefinitions[i].indices = new int[ 6 * (positions.Count / 4) ];
                for (int j = 0; j < positions.Count / 4; ++j)
                {
                    coll.spriteDefinitions[i].indices[j * 6 + 0] = j * 4 + 0;
                    coll.spriteDefinitions[i].indices[j * 6 + 1] = j * 4 + 3;
                    coll.spriteDefinitions[i].indices[j * 6 + 2] = j * 4 + 1;
                    coll.spriteDefinitions[i].indices[j * 6 + 3] = j * 4 + 2;
                    coll.spriteDefinitions[i].indices[j * 6 + 4] = j * 4 + 3;
                    coll.spriteDefinitions[i].indices[j * 6 + 5] = j * 4 + 0;
                }

                coll.spriteDefinitions[i].positions = new Vector3[positions.Count];
                coll.spriteDefinitions[i].uvs = new Vector2[uvs.Count];
                for (int j = 0; j < positions.Count; ++j)
                {
                    coll.spriteDefinitions[i].positions[j] = positions[j];
                    coll.spriteDefinitions[i].uvs[j] = uvs[j];
                }

                coll.spriteDefinitions[i].material = gen.atlasMaterials[atlasIndex];
            }

            Vector3 boundsMin = new Vector3(1.0e32f, 1.0e32f, 1.0e32f);
            Vector3 boundsMax = new Vector3(-1.0e32f, -1.0e32f, -1.0e32f);
            foreach (Vector3 v in coll.spriteDefinitions[i].positions)
            {
                boundsMin = Vector3.Min(boundsMin, v);
                boundsMax = Vector3.Max(boundsMax, v);
            }

            coll.spriteDefinitions[i].boundsData = new Vector3[2];
            coll.spriteDefinitions[i].boundsData[0] = (boundsMax + boundsMin) / 2.0f;
            coll.spriteDefinitions[i].boundsData[1] = (boundsMax - boundsMin);
            coll.spriteDefinitions[i].name = gen.textureParams[i].name;
        }
    }
Example #42
0
        //private Cb4aCollisionMeshSoupFaceEdge BuildBspCollisionFaceSoupFaceEdge(BspCollisionFaceSoupFaceEdge e)
        //{
        //    return new Cb4aCollisionMeshSoupFaceEdge() { Normal = GetVec3Fixed(e.Normal), Distance = (int)e.Distance * AirplaySDKMath.IW_GEOM_ONE };
        //}
        private void BuildLightmapAtlas(BspDocument bsp)
        {
            Dictionary<Bitmap, bool> lightmaps = new Dictionary<Bitmap, bool>();
            CollectAllLightmaps(lightmaps);
            //TODO: Make multiple atlases 128x128 istead one huge atlas. The reason is that there is only 4096 steps in UV coordinate!
            Atlas atlas = new Atlas();
            foreach (var l in lightmaps.Keys)
            {
                atlas.Add(l);
            }

            commonLightmap = new BspEmbeddedTexture() { Name = bsp.Name + "_lightmap", mipMaps = new Bitmap[] { atlas.Bitmap } };
            UpdateLightmap(commonLightmap, atlas);

            //
            //    Bitmap Lightmap = new Bitmap(128,128);
            //    using (var g = Graphics.FromImage(Lightmap))
            //    {
            //        g.Clear(Color.Red);
            //    }
            //    BspEmbeddedTexture lm = new BspEmbeddedTexture() { Name = "lightmap", mipMaps = new Bitmap[1] { Lightmap } };
            //    foreach (var l in leaves)
            //    {
            //        if (l.Geometry != null)
            //            foreach (var f in l.Geometry.Faces)
            //                if (f.Lightmap != null)
            //                    f.Lightmap = lm;
            //    }
        }
Example #43
0
 private void UpdateLightmap(BspTexture result, Atlas atlas)
 {
     foreach (var geo in allClusters)
     {
         Size dstSize = new Size(atlas.Bitmap.Width, atlas.Bitmap.Height);
         for (int i = 0; i < geo.Faces.Count; ++i)
         {
             var f = geo.Faces[i];
             if (f.Lightmap != null)
             {
                 if (f.Lightmap.Equals(result))
                     continue;
                 var item = atlas.GetItem(((BspEmbeddedTexture)f.Lightmap).mipMaps[0]);
                 var ff = new BspGeometryFace() { Texture = f.Texture, Lightmap = result };
                 ff.Vertex0 = CorrectLightmapCoords(f.Vertex0, dstSize, item);
                 ff.Vertex1 = CorrectLightmapCoords(f.Vertex1, dstSize, item);
                 ff.Vertex2 = CorrectLightmapCoords(f.Vertex2, dstSize, item);
                 geo.Faces[i] = ff;
             }
         }
     }
 }
Example #44
0
    public SkeletonData GetSkeletonData(bool quiet)
    {
        if (atlasAssets == null) {
            atlasAssets = new AtlasAsset[0];
            if (!quiet)
                Debug.LogError("Atlas not set for SkeletonData asset: " + name, this);
            Reset();
            return null;
        }

        if (skeletonJSON == null) {
            if (!quiet)
                Debug.LogError("Skeleton JSON file not set for SkeletonData asset: " + name, this);
            Reset();
            return null;
        }

        #if !SPINE_TK2D
        if (atlasAssets.Length == 0) {
            Reset();
            return null;
        }
        #else
        if (atlasAssets.Length == 0 && spriteCollection == null) {
            Reset();
            return null;
        }
        #endif

        Atlas[] atlasArr = new Atlas[atlasAssets.Length];
        for (int i = 0; i < atlasAssets.Length; i++) {
            if (atlasAssets[i] == null) {
                Reset();
                return null;
            }
            atlasArr[i] = atlasAssets[i].GetAtlas();
            if (atlasArr[i] == null) {
                Reset();
                return null;
            }
        }

        if (skeletonData != null)
            return skeletonData;

        SkeletonJson json;

        #if !SPINE_TK2D
        json = new SkeletonJson(atlasArr);
        json.Scale = scale;
        #else
        if (spriteCollection != null) {
            json = new SkeletonJson(new SpriteCollectionAttachmentLoader(spriteCollection));
            json.Scale = (1.0f / (spriteCollection.invOrthoSize * spriteCollection.halfTargetHeight) * scale) * 100f;
        } else {
            if (atlasArr.Length == 0) {
                Reset();
                if (!quiet)
                    Debug.LogError("Atlas not set for SkeletonData asset: " + name, this);
                return null;
            }
            json = new SkeletonJson(atlasArr);
            json.Scale = scale;
        }
        #endif

        try {
            skeletonData = json.ReadSkeletonData(new StringReader(skeletonJSON.text));
        } catch (Exception ex) {
            if (!quiet)
                Debug.LogError("Error reading skeleton JSON file for SkeletonData asset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, this);
            return null;
        }

        stateData = new AnimationStateData(skeletonData);
        FillStateData();

        return skeletonData;
    }
Example #45
0
        public SkillPanel()
        {
            try
            {
                _skillPanel = XmlUtilities<Atlas>.Deserialize("skillpanel_atlas.xml");
                _skillTree = XmlUtilities<Atlas>.Deserialize("skilltree_atlas.xml");
                _inventoryPanel = XmlUtilities<Atlas>.Deserialize("wsinventory_atlas.xml");

                _skillPanelBmp = new Bitmap(_skillPanel.file.Replace(@"data\uix\", string.Empty));
                _skillPanelBmp.MakeTransparent(Color.White);

                _skillTreeBmp = new Bitmap(_skillTree.file.Replace(@"data\uix\", string.Empty));
                //_skillTreeBmp.MakeTransparent(Color.White);

                _inventoryPanelBmp = new Bitmap(_inventoryPanel.file.Replace(@"data\uix\", string.Empty));
                _inventoryPanelBmp.MakeTransparent(Color.White);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SkillPanel");
            }
        }
    public static Atlas[] CreateAtlas(string name, Texture2D[] textures, Atlas startWith = null)
    {
        List<Texture2D> toProcess = new List<Texture2D>();
        toProcess.AddRange(textures);
        int index = toProcess.Count - 1;
        toProcess.Reverse(); // Because we index backwards

        List<Atlas> result = new List<Atlas>();

        int insertIndex = 0;
        if (startWith != null) {
            insertIndex = startWith.root.sortIndex;
        }

        while(index >= 0) {
            Atlas _atlas = startWith;
            if (_atlas == null) {
                _atlas = new Atlas();
                _atlas.texture = new Texture2D(AtlasSize, AtlasSize, TextureFormat.RGBA32, false);
                _atlas.root = new AtlasNode();
                _atlas.root.rc = new Rect(0, 0, AtlasSize, AtlasSize);
            }
            startWith = null;

            while (index >= 0 && (_atlas.root.Contains(toProcess[index].name) || _atlas.root.Insert(toProcess[index], insertIndex++) != null)) {
                index -= 1;
            }
            result.Add(_atlas);
            _atlas.root.sortIndex = insertIndex;
            insertIndex = 0;
            _atlas = null;
        }

        foreach(Atlas atlas in result) {
            atlas.root.Build(atlas.texture);
            List<AtlasNode> nodes = new List<AtlasNode>();
            atlas.root.GetBounds(ref nodes);
            nodes.Sort(delegate (AtlasNode x, AtlasNode y) {
                if (x.sortIndex == y.sortIndex) return 0;
                if (y.sortIndex > x.sortIndex) return -1;
                return 1;
            });

            List<Rect> rects = new List<Rect>();
            foreach(AtlasNode node in nodes) {
                Rect normalized = new Rect(node.rc.xMin / atlas.root.rc.width, node.rc.yMin / atlas.root.rc.height, node.rc.width / atlas.root.rc.width, node.rc.height / atlas.root.rc.height);
                // bunp everything over by half a pixel to avoid floating errors
                normalized.x += 0.5f / atlas.root.rc.width;
                normalized.width -= 1.0f / atlas.root.rc.width;
                normalized.y += 0.5f / atlas.root.rc.height;
                normalized.height -= 1.0f / atlas.root.rc.height;
                rects.Add(normalized);
            }

            atlas.uvRects = new AtlasDescriptor[rects.Count];
            for (int i = 0; i < rects.Count; i++) {
                atlas.uvRects[i] = new AtlasDescriptor();
                atlas.uvRects[i].width = (int)nodes[i].rc.width;
                atlas.uvRects[i].height = (int)nodes[i].rc.height;
                atlas.uvRects[i].name = nodes[i].name;
                atlas.uvRects[i].uvRect = rects[i];
            }

            atlas.root.Clear();
            #if DEBUG_ATLASES
            atlas.texture.Apply(false, false);
            SaveAtlas(atlas, name);
            #else
            if (atlas != result[result.Count - 1])
                atlas.texture.Apply(false, true);
            else
                atlas.texture.Apply(false, false);
            #endif
        }

        return result.ToArray();
    }
Example #47
0
 void Awake()
 {
     _Atlas = new Atlas();
     _Atlas.LoadAtlas(_AtlasScript);
     _QR = new QuadRender(null,300,this.GetComponent<MeshFilter>().mesh);
 }
Example #48
0
 public void Clear()
 {
     atlas = null;
 }
Example #49
0
 public void  SetAtlas(Atlas atlas)
 {
     this.atlas = atlas;
 }
    public SkeletonData GetSkeletonData(bool quiet)
    {
        if (atlasAssets == null) {
            atlasAssets = new AtlasAsset[0];
            if (!quiet)
                Debug.LogError("Atlas not set for SkeletonData asset: " + name, this);
            Reset();
            return null;
        }

        if (skeletonJSON == null) {
            if (!quiet)
                Debug.LogError("Skeleton JSON file not set for SkeletonData asset: " + name, this);
            Reset();
            return null;
        }

        if (atlasAssets.Length == 0) {
            Reset();
            return null;
        }

        Atlas[] atlasArr = new Atlas[atlasAssets.Length];
        for (int i = 0; i < atlasAssets.Length; i++) {
            if (atlasAssets[i] == null) {
                Reset();
                return null;
            }
            atlasArr[i] = atlasAssets[i].GetAtlas();
            if (atlasArr[i] == null) {
                Reset();
                return null;
            }
        }

        if (skeletonData != null)
            return skeletonData;

        SkeletonJson json = new SkeletonJson(atlasArr);
        json.Scale = scale;
        try {
            skeletonData = json.ReadSkeletonData(new StringReader(skeletonJSON.text));
        } catch (Exception ex) {
            if (!quiet)
                Debug.LogError("Error reading skeleton JSON file for SkeletonData asset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, this);
            return null;
        }

        stateData = new AnimationStateData(skeletonData);
        FillStateData();

        return skeletonData;
    }