Beispiel #1
0
        //page file
        private void parseImageFileName(string line, string fntFile)
        {
            //    //////////////////////////////////////////////////////////////////////////
            //// line to parse:
            //// page id=0 file="bitmapFontTest.png"
            ////////////////////////////////////////////////////////////////////////////

            // page ID. Sanity check
            int    index  = line.IndexOf('=') + 1;
            int    index2 = line.IndexOf(' ', index);
            string value  = line.Substring(index, index2 - index);

            try
            {
                int ivalue = int.Parse(value);
            }
            catch (Exception)
            {
                throw (new ContentLoadException("Invalid page ID for FNT descriptor. Line=" + line + ", value=" + value + ", indices=" + index + "," + index2));
            }
//            Debug.Assert(Convert.ToInt32(value) == 0, "LabelBMFont file could not be found");
            // file
            index  = line.IndexOf('"') + 1;
            index2 = line.IndexOf('"', index);
            value  = line.Substring(index, index2 - index);

            m_sAtlasName = CCFileUtils.FullPathFromRelativeFile(value, fntFile);
        }
        public void AddAnimationsWithFile(string plist)
        {
            Debug.Assert(!string.IsNullOrEmpty(plist), "Invalid texture file name");

            string path = CCFileUtils.FullPathFromRelativePath(plist);

            PlistDocument document = null;

            try
            {
                document = CCApplication.SharedApplication.Content.Load <PlistDocument>(path);
            }
            catch (System.Exception)
            {
                string xml = CCContent.LoadContentFile(path);
                if (xml != null)
                {
                    document = new PlistDocument(xml);
                }
            }
            if (document == null)
            {
                throw (new Microsoft.Xna.Framework.Content.ContentLoadException("Failed to load the particle definition file from " + path));
            }

            PlistDictionary dict = document.Root.AsDictionary;

            Debug.Assert(dict != null, "CCAnimationCache: File could not be found");

            AddAnimationsWithDictionary(dict);
        }
Beispiel #3
0
        public CCNode ReadNodeGraphFromFile(string fileName, object owner, CCSize parentSize)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(null);
            }

            string strCCBFileName = fileName;
            string strSuffix      = ".ccbi";

            // Add ccbi suffix
            if (!CCBReader.EndsWith(strCCBFileName, strSuffix))
            {
                strCCBFileName += strSuffix;
            }

            string strPath = CCFileUtils.FullPathFromRelativePath(strCCBFileName);

            var pBytes = CCFileUtils.GetFileBytes(strPath);

            byte[] data = pBytes;

            CCNode ret = ReadNodeGraphFromData(data, owner, parentSize);

            return(ret);
        }
Beispiel #4
0
        public CCTexture2D AddImage(string fileimage)
        {
            Debug.Assert(!String.IsNullOrEmpty(fileimage), "TextureCache: fileimage MUST not be NULL");

            CCTexture2D texture = null;

            var assetName = fileimage;

            if (Path.HasExtension(assetName))
            {
                assetName = CCFileUtils.RemoveExtension(assetName);
            }

            lock (m_pDictLock) {
                m_pTextures.TryGetValue(assetName, out texture);
            }
            if (texture == null)
            {
                texture = new CCTexture2D();

                if (texture.InitWithFile(fileimage))
                {
                    lock (m_pDictLock) {
                        m_pTextures[assetName] = texture;
                    }
                }
                else
                {
                    return(null);
                }
            }

            return(texture);
        }
        public bool InitWithFile(string plistFile)
        {
            bool bRet;

            m_sPlistFile = CCFileUtils.FullPathFromRelativePath(plistFile);

            PlistDocument doc = null;

            try
            {
                doc = CCApplication.SharedApplication.Content.Load <PlistDocument>(m_sPlistFile);
            }
            catch (Exception)
            {
                string xml = CCContent.LoadContentFile(m_sPlistFile);
                if (xml != null)
                {
                    doc = new PlistDocument(xml);
                }
            }
            if (doc == null)
            {
                throw (new Microsoft.Xna.Framework.Content.ContentLoadException("Failed to load the particle definition file from " + m_sPlistFile));
            }
            Debug.Assert(doc != null, "Particles: file not found");
            Debug.Assert(doc.Root != null, "Particles: file not found");

            bRet = InitWithDictionary(doc.Root.AsDictionary);

            return(bRet);
        }
Beispiel #6
0
        private void InternalInit(string tmxFileName, string resourcePath)
        {
            m_pTilesets = new List <CCTMXTilesetInfo>();
            m_pLayers   = new List <CCTMXLayerInfo>();

            if (tmxFileName != null)
            {
                m_sTMXFileName = CCFileUtils.FullPathFromRelativePath(tmxFileName);
            }

            if (resourcePath != null)
            {
                m_sResources = resourcePath;
            }

            m_pObjectGroups = new List <CCTMXObjectGroup>(4);

            m_pProperties     = new Dictionary <string, string>();
            m_pTileProperties = new Dictionary <uint, Dictionary <string, string> >();

            // tmp vars
            m_sCurrentString     = null;
            m_bStoringCharacters = false;
            m_nLayerAttribs      = (int)CCTMXLayerAttrib.None;
            m_nParentElement     = (int)CCTMXProperty.None;
            m_uCurrentFirstGID   = 0;
        }
Beispiel #7
0
        protected virtual CCNode ParsePropTypeCcbFile(CCNode node, CCNode parent, CCBReader reader)
        {
            string ccbFileName = reader.ReadCachedString();

            /* Change path extension to .ccbi. */
            string ccbFileWithoutPathExtension = CCBReader.DeletePathExtension(ccbFileName);

            ccbFileName = ccbFileWithoutPathExtension + ".ccbi";

            // Load sub file
            string path      = CCFileUtils.FullPathFromRelativePath(ccbFileName);
            var    ccbReader = new CCBReader(reader);

            byte[] pBytes = CCFileUtils.GetFileBytes(path);
            ccbReader.InitWithData(pBytes, reader.Owner);
            ccbReader.AnimationManager.RootContainerSize = parent.ContentSize;

            CCNode ccbFileNode = ccbReader.ReadFileWithCleanUp(false);

            if (ccbFileNode != null && ccbReader.AnimationManager.AutoPlaySequenceId != -1)
            {
                // Auto play animations
                ccbReader.AnimationManager.RunAnimations(ccbReader.AnimationManager.AutoPlaySequenceId, 0);
            }

            return(ccbFileNode);
        }
Beispiel #8
0
        public CCNode ReadNodeGraphFromFile(string fileName, object owner, CCSize parentSize, ref CCBAnimationManager animationManager)
        {
            string pPath = CCFileUtils.FullPathFromRelativePath(fileName);

            byte[] pBytes = CCFileUtils.GetFileBytes(pPath);
            CCNode ret    = ReadNodeGraphFromData(pBytes, owner, parentSize, ref animationManager);

            return(ret);
        }
Beispiel #9
0
        /// <summary>
        /// Create the dictionary key for this texture. Duplicate assets using different compression are not supported.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private string CreateAssetKey(string file)
        {
            var assetName = file;

            if (Path.HasExtension(assetName))
            {
                assetName = CCFileUtils.RemoveExtension(assetName);
            }
            return(assetName);
        }
Beispiel #10
0
        protected virtual CCTexture2D ParsePropTypeTexture(CCNode node, CCNode parent, CCBReader reader)
        {
            string spriteFile = reader.ReadCachedString();

            if (!String.IsNullOrEmpty(spriteFile))
            {
                return(CCTextureCache.SharedTextureCache.AddImage(CCFileUtils.RemoveExtension(spriteFile)));
            }
            return(null);
        }
Beispiel #11
0
        public void AddAnimationsWithFile(string plist)
        {
            Debug.Assert(!string.IsNullOrEmpty(plist), "Invalid texture file name");

            string path = CCFileUtils.FullPathFromRelativePath(plist);

            var             document = CCApplication.SharedApplication.Content.Load <PlistDocument>(path);
            PlistDictionary dict     = document.Root.AsDictionary;

            Debug.Assert(dict != null, "CCAnimationCache: File could not be found");

            AddAnimationsWithDictionary(dict);
        }
Beispiel #12
0
        public void RemoveTextureForKey(string textureKeyName)
        {
            if (String.IsNullOrEmpty(textureKeyName))
            {
                return;
            }

            if (Path.HasExtension(textureKeyName))
            {
                textureKeyName = CCFileUtils.RemoveExtension(textureKeyName);
            }

            m_pTextures.Remove(textureKeyName);
        }
Beispiel #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pszPlist"></param>
        /// <returns>The scope parameter derived from the pszPlist parameter.</returns>
        public string AddSpriteFramesWithFile(string pszPlist)
        {
            string pszPath = CCFileUtils.FullPathFromRelativePath(pszPlist);
            //Dictionary<string, Object> dict = CCFileUtils.dictionaryWithContentsOfFile(pszPath);
            PlistDictionary dict = CCApplication.SharedApplication.Content.Load <PlistDocument>(pszPlist).Root.AsDictionary;

            string          texturePath  = "";
            PlistDictionary metadataDict = dict.ContainsKey("metadata") ? dict["metadata"].AsDictionary : null;

            string framePrefix = string.Empty;

            if (metadataDict != null)
            {
                // try to read  texture file name from meta data
                if (metadataDict.ContainsKey("textureFileName"))
                {
                    texturePath = metadataDict["textureFileName"].AsString;
                    framePrefix = ExtractPrefix(texturePath);
                }
            }

            if (!string.IsNullOrEmpty(texturePath))
            {
                // build texture path relative to plist file
                texturePath = CCFileUtils.FullPathFromRelativeFile(texturePath, pszPath);
            }
            else
            {
                // build texture path by replacing file extension
                texturePath = pszPath;

                // remove .xxx
                texturePath = CCFileUtils.RemoveExtension(texturePath);

                CCLog.Log("cocos2d: CCSpriteFrameCache: Trying to use file {0} as texture", texturePath);
            }

            CCTexture2D pTexture = CCTextureCache.SharedTextureCache.AddImage(texturePath);

            if (pTexture != null)
            {
                AddSpriteFramesWithDictionary(dict, pTexture, framePrefix);
            }
            else
            {
                CCLog.Log("cocos2d: CCSpriteFrameCache: Couldn't load texture");
            }
            return(framePrefix);
        }
Beispiel #14
0
        public bool InitWithString(string theString, string fntFile)
        {
            string data = CCFileUtils.GetFileData(fntFile);

            PlistDocument doc  = new PlistDocument(data);
            var           dict = doc.Root as PlistDictionary;

            Debug.Assert(dict["version"].AsInt == 1, "Unsupported version. Upgrade cocos2d version");

            string textureFilename = dict["textureFilename"].AsString;
            int    width           = (int)Math.Ceiling(dict["itemWidth"].AsInt / CCMacros.CCContentScaleFactor());
            int    height          = (int)Math.Ceiling(dict["itemHeight"].AsInt / CCMacros.CCContentScaleFactor());
            var    startChar       = (char)dict["firstChar"].AsInt;

            return(InitWithString(theString, textureFilename, width, height, startChar));
        }
Beispiel #15
0
        public void AddSpriteFramesWithFile(string pszPlist)
        {
            PlistDocument document = CCContentManager.SharedContentManager.Load <PlistDocument>(pszPlist);

            PlistDictionary dict         = document.Root.AsDictionary;
            string          texturePath  = "";
            PlistDictionary metadataDict = dict.ContainsKey("metadata") ? dict["metadata"].AsDictionary : null;

            if (metadataDict != null)
            {
                // try to read  texture file name from meta data
                if (metadataDict.ContainsKey("textureFileName"))
                {
                    texturePath = metadataDict["textureFileName"].AsString;
                }
            }

            if (!string.IsNullOrEmpty(texturePath))
            {
                // build texture path relative to plist file
                texturePath = CCFileUtils.FullPathFromRelativeFile(texturePath, pszPlist);
            }
            else
            {
                // build texture path by replacing file extension
                texturePath = pszPlist;

                // remove .xxx
                texturePath = CCFileUtils.RemoveExtension(texturePath);

                // append .png
                texturePath = texturePath + ".png";

                CCLog.Log("cocos2d: CCSpriteFrameCache: Trying to use file {0} as texture", texturePath);
            }

            CCTexture2D pTexture = CCTextureCache.SharedTextureCache.AddImage(texturePath);

            if (pTexture != null)
            {
                AddSpriteFramesWithDictionary(dict, pTexture);
            }
            else
            {
                CCLog.Log("cocos2d: CCSpriteFrameCache: Couldn't load texture");
            }
        }
        public bool InitWithFile(string plistFile)
        {
            bool bRet;

            m_sPlistFile = CCFileUtils.FullPathFromRelativePath(plistFile);

            //var content = CCApplication.SharedApplication.content.Load<CCContent>(m_sPlistFile);
            //PlistDocument dict = PlistDocument.Create(content.Content);

            var dict = CCApplication.SharedApplication.Content.Load <PlistDocument>(m_sPlistFile);

            Debug.Assert(dict != null, "Particles: file not found");
            Debug.Assert(dict.Root != null, "Particles: file not found");

            bRet = InitWithDictionary(dict.Root.AsDictionary);

            return(bRet);
        }
Beispiel #17
0
        public CCTexture2D TextureForKey(string key)
        {
            CCTexture2D texture = null;

            try
            {
                if (Path.HasExtension(key))
                {
                    key = CCFileUtils.RemoveExtension(key);
                }

                m_pTextures.TryGetValue(key, out texture);
            }
            catch (ArgumentNullException)
            {
                CCLog.Log("Texture of key {0} is not exist.", key);
            }

            return(texture);
        }
Beispiel #18
0
        protected virtual CCSpriteFrame ParsePropTypeSpriteFrame(CCNode node, CCNode parent, CCBReader reader, string propertyName)
        {
            string spriteSheet = reader.ReadCachedString();
            string spriteFile  = reader.ReadCachedString();

            CCSpriteFrame spriteFrame = null;

            if (spriteFile.Length != 0)
            {
                if (spriteSheet.Length == 0)
                {
                    CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage(CCFileUtils.RemoveExtension(spriteFile));
                    var         bounds  = new CCRect(0, 0, texture.ContentSize.Width, texture.ContentSize.Height);
                    spriteFrame = new CCSpriteFrame(texture, bounds);
                }
                else
                {
                    CCSpriteFrameCache frameCache = CCSpriteFrameCache.SharedSpriteFrameCache;

                    // Load the sprite sheet only if it is not loaded
                    if (!reader.LoadedSpriteSheet.Contains(spriteSheet))
                    {
                        frameCache.AddSpriteFramesWithFile(spriteSheet);
                        reader.LoadedSpriteSheet.Add(spriteSheet);
                    }

                    spriteFrame = frameCache.SpriteFrameByName(spriteFile);
                }

                if (reader.AnimatedProperties.Contains(propertyName))
                {
                    reader.AnimationManager.SetBaseValue(spriteFrame, node, propertyName);
                }
            }

            return(spriteFrame);
        }
Beispiel #19
0
        private void LoadTgAfile(string file)
        {
            Debug.Assert(!string.IsNullOrEmpty(file), "file must be non-nil");

            m_pTGAInfo = ImageTGA.Load(CCFileUtils.FullPathFromRelativePath(file));
        }
Beispiel #20
0
        public void StartElement(object ctx, string name, string[] atts)
        {
            CCTMXMapInfo pTMXMapInfo   = this;
            string       elementName   = name;
            var          attributeDict = new Dictionary <string, string>();

            if (atts != null && atts[0] != null)
            {
                for (int i = 0; i + 1 < atts.Length; i += 2)
                {
                    string key   = atts[i];
                    string value = atts[i + 1];
                    attributeDict.Add(key, value);
                }
            }
            if (elementName == "map")
            {
                string version = attributeDict["version"];
                if (version != "1.0")
                {
                    CCLog.Log("cocos2d: TMXFormat: Unsupported TMX version: {0}", version);
                }
                string orientationStr = attributeDict["orientation"];
                if (orientationStr == "orthogonal")
                {
                    pTMXMapInfo.Orientation = (int)(CCTMXOrientation.Ortho);
                }
                else if (orientationStr == "isometric")
                {
                    pTMXMapInfo.Orientation = (int)(CCTMXOrientation.Iso);
                }
                else if (orientationStr == "hexagonal")
                {
                    pTMXMapInfo.Orientation = (int)(CCTMXOrientation.Hex);
                }
                else
                {
                    CCLog.Log("cocos2d: TMXFomat: Unsupported orientation: {0}", pTMXMapInfo.Orientation);
                }

                CCSize sMapSize;
                sMapSize.Width      = CCUtils.CCParseFloat(attributeDict["width"]);
                sMapSize.Height     = CCUtils.CCParseFloat(attributeDict["height"]);
                pTMXMapInfo.MapSize = sMapSize;

                CCSize sTileSize;
                sTileSize.Width      = CCUtils.CCParseFloat(attributeDict["tilewidth"]);
                sTileSize.Height     = CCUtils.CCParseFloat(attributeDict["tileheight"]);
                pTMXMapInfo.TileSize = sTileSize;

                // The parent element is now "map"
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.Map;
            }
            else if (elementName == "tileset")
            {
                // If this is an external tileset then start parsing that

                if (attributeDict.Keys.Contains("source"))
                {
                    string externalTilesetFilename = attributeDict["source"];

                    externalTilesetFilename = CCFileUtils.FullPathFromRelativeFile(externalTilesetFilename, pTMXMapInfo.TMXFileName);

                    m_uCurrentFirstGID = uint.Parse(attributeDict["firstgid"]);

                    pTMXMapInfo.ParseXmlFile(externalTilesetFilename);
                }
                else
                {
                    var tileset = new CCTMXTilesetInfo();

                    tileset.m_sName = attributeDict["name"];

                    if (m_uCurrentFirstGID == 0)
                    {
                        tileset.m_uFirstGid = uint.Parse(attributeDict["firstgid"]);
                    }
                    else
                    {
                        tileset.m_uFirstGid = m_uCurrentFirstGID;
                        m_uCurrentFirstGID  = 0;
                    }

                    if (attributeDict.Keys.Contains("spacing"))
                    {
                        tileset.m_uSpacing = int.Parse(attributeDict["spacing"]);
                    }

                    if (attributeDict.Keys.Contains("margin"))
                    {
                        tileset.m_uMargin = int.Parse(attributeDict["margin"]);
                    }

                    CCSize s;
                    s.Width             = CCUtils.CCParseFloat(attributeDict["tilewidth"]);
                    s.Height            = CCUtils.CCParseFloat(attributeDict["tileheight"]);
                    tileset.m_tTileSize = s;

                    pTMXMapInfo.Tilesets.Add(tileset);
                }
            }
            else if (elementName == "tile")
            {
                CCTMXTilesetInfo info = pTMXMapInfo.Tilesets.LastOrDefault();
                var dict = new Dictionary <string, string>();
                pTMXMapInfo.ParentGID = (info.m_uFirstGid + uint.Parse(attributeDict["id"]));
                pTMXMapInfo.TileProperties.Add(pTMXMapInfo.ParentGID, dict);

                pTMXMapInfo.ParentElement = (int)CCTMXProperty.Tile;
            }
            else if (elementName == "layer")
            {
                var layer = new CCTMXLayerInfo();
                layer.Name = attributeDict["name"];

                CCSize s;
                s.Width         = CCUtils.CCParseFloat(attributeDict["width"]);
                s.Height        = CCUtils.CCParseFloat(attributeDict["height"]);
                layer.LayerSize = s;

                layer.Tiles = new uint[(int)s.Width * (int)s.Height];

                if (attributeDict.Keys.Contains("visible"))
                {
                    string visible = attributeDict["visible"];
                    layer.Visible = !(visible == "0");
                }
                else
                {
                    layer.Visible = true;
                }

                if (attributeDict.Keys.Contains("opacity"))
                {
                    string opacity = attributeDict["opacity"];
                    layer.Opacity = (byte)(255 * CCUtils.CCParseFloat(opacity));
                }
                else
                {
                    layer.Opacity = 255;
                }

                float x = attributeDict.Keys.Contains("x") ? CCUtils.CCParseFloat(attributeDict["x"]) : 0;
                float y = attributeDict.Keys.Contains("y") ? CCUtils.CCParseFloat(attributeDict["y"]) : 0;
                layer.Offset = new CCPoint(x, y);

                pTMXMapInfo.Layers.Add(layer);

                // The parent element is now "layer"
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.Layer;
            }
            else if (elementName == "objectgroup")
            {
                var objectGroup = new CCTMXObjectGroup();
                objectGroup.GroupName = attributeDict["name"];

                CCPoint positionOffset = CCPoint.Zero;
                if (attributeDict.ContainsKey("x"))
                {
                    positionOffset.X = CCUtils.CCParseFloat(attributeDict["x"]) * pTMXMapInfo.TileSize.Width;
                }
                if (attributeDict.ContainsKey("y"))
                {
                    positionOffset.Y = CCUtils.CCParseFloat(attributeDict["y"]) * pTMXMapInfo.TileSize.Height;
                }
                objectGroup.PositionOffset = positionOffset;

                pTMXMapInfo.ObjectGroups.Add(objectGroup);

                // The parent element is now "objectgroup"
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.ObjectGroup;
            }
            else if (elementName == "image")
            {
                CCTMXTilesetInfo tileset = pTMXMapInfo.Tilesets.LastOrDefault();

                // build full path
                string imagename = attributeDict["source"];
                tileset.m_sSourceImage = CCFileUtils.FullPathFromRelativeFile(imagename, pTMXMapInfo.TMXFileName);
            }
            else if (elementName == "data")
            {
                string encoding    = attributeDict.ContainsKey("encoding") ? attributeDict["encoding"] : "";
                string compression = attributeDict.ContainsKey("compression") ? attributeDict["compression"] : "";

                if (encoding == "base64")
                {
                    int layerAttribs = pTMXMapInfo.LayerAttribs;
                    pTMXMapInfo.LayerAttribs      = layerAttribs | (int)CCTMXLayerAttrib.Base64;
                    pTMXMapInfo.StoringCharacters = true;

                    if (compression == "gzip")
                    {
                        layerAttribs             = pTMXMapInfo.LayerAttribs;
                        pTMXMapInfo.LayerAttribs = layerAttribs | (int)CCTMXLayerAttrib.Gzip;
                    }
                    else if (compression == "zlib")
                    {
                        layerAttribs             = pTMXMapInfo.LayerAttribs;
                        pTMXMapInfo.LayerAttribs = layerAttribs | (int)CCTMXLayerAttrib.Zlib;
                    }
                    Debug.Assert(compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method");
                }
                Debug.Assert(pTMXMapInfo.LayerAttribs != (int)CCTMXLayerAttrib.None,
                             "TMX tile map: Only base64 and/or gzip/zlib maps are supported");
            }
            else if (elementName == "object")
            {
                CCTMXObjectGroup objectGroup = pTMXMapInfo.ObjectGroups.LastOrDefault();

                // The value for "type" was blank or not a valid class name
                // Create an instance of TMXObjectInfo to store the object and its properties
                var dict = new Dictionary <string, string>();

                var pArray = new[] { "name", "type", "width", "height", "gid" };

                for (int i = 0; i < pArray.Length; i++)
                {
                    string key = pArray[i];
                    if (attributeDict.ContainsKey(key))
                    {
                        dict.Add(key, attributeDict[key]);
                    }
                }

                // But X and Y since they need special treatment
                // X

                int x = int.Parse(attributeDict["x"]) + (int)objectGroup.PositionOffset.X;
                dict.Add("x", x.ToString());

                int y = int.Parse(attributeDict["y"]) + (int)objectGroup.PositionOffset.Y;
                // Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
                y = (int)(pTMXMapInfo.MapSize.Height * pTMXMapInfo.TileSize.Height) - y -
                    (attributeDict.ContainsKey("height") ? int.Parse(attributeDict["height"]) : 0);
                dict.Add("y", y.ToString());

                // Add the object to the objectGroup
                objectGroup.Objects.Add(dict);

                // The parent element is now "object"
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.Object;
            }
            else if (elementName == "property")
            {
                if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.None)
                {
                    CCLog.Log("TMX tile map: Parent element is unsupported. Cannot add property named '{0}' with value '{1}'",
                              attributeDict["name"], attributeDict["value"]);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.Map)
                {
                    // The parent element is the map
                    string value = attributeDict["value"];
                    string key   = attributeDict["name"];
                    pTMXMapInfo.Properties.Add(key, value);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.Layer)
                {
                    // The parent element is the last layer
                    CCTMXLayerInfo layer = pTMXMapInfo.Layers.LastOrDefault();
                    string         value = attributeDict["value"];
                    string         key   = attributeDict["name"];
                    // Add the property to the layer
                    layer.Properties.Add(key, value);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.ObjectGroup)
                {
                    // The parent element is the last object group
                    CCTMXObjectGroup objectGroup = pTMXMapInfo.ObjectGroups.LastOrDefault();
                    string           value       = attributeDict["value"];
                    string           key         = attributeDict["name"];
                    objectGroup.Properties.Add(key, value);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.Object)
                {
                    // The parent element is the last object
                    CCTMXObjectGroup            objectGroup = pTMXMapInfo.ObjectGroups.LastOrDefault();
                    Dictionary <string, string> dict        = objectGroup.Objects.LastOrDefault();

                    string propertyName  = attributeDict["name"];
                    string propertyValue = attributeDict["value"];
                    dict.Add(propertyName, propertyValue);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.Tile)
                {
                    Dictionary <string, string> dict = pTMXMapInfo.TileProperties[pTMXMapInfo.ParentGID];

                    string propertyName  = attributeDict["name"];
                    string propertyValue = attributeDict["value"];
                    dict.Add(propertyName, propertyValue);
                }
            }
            else if (elementName == "polygon")
            {
                // find parent object's dict and add polygon-points to it
                CCTMXObjectGroup objectGroup = m_pObjectGroups.LastOrDefault();
                var dict = objectGroup.Objects.LastOrDefault();

                // get points value string
                var value = attributeDict["points"];
                if (!String.IsNullOrEmpty(value))
                {
                    var pPointsArray = new List <CCPoint>();
                    var pointPairs   = value.Split(' ');

                    foreach (var pontPair in pointPairs)
                    {
                        //TODO: Parse points
                        //CCPoint point;
                        //point.X = x + objectGroup.PositionOffset.X;
                        //point.Y = y + objectGroup.PositionOffset.Y;

                        //pPointsArray.Add(point);
                    }

                    //dict.Add("points", pPointsArray);
                }
            }
            else if (elementName == "polyline")
            {
                // find parent object's dict and add polyline-points to it
                // CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)m_pObjectGroups->lastObject();
                // CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();
                // TODO: dict->setObject:[attributeDict objectForKey:@"points"] forKey:@"polylinePoints"];
            }
        }
Beispiel #21
0
        public void InitWithFile(string fileName)
        {
            PlistDocument document = CCContentManager.SharedContentManager.Load <PlistDocument>(fileName);

            var dict        = document.Root.AsDictionary;
            var texturePath = string.Empty;

            plistFilePath = string.Empty;

            plistType = GetPlistType(dict);

            if (plistType == PlistType.SpriteKit)
            {
                var images = dict.ContainsKey("images") ? dict ["images"].AsArray : null;

                var imageDict = images [0].AsDictionary;

                if (imageDict != null)
                {
                    // try to read  texture file name from meta data
                    if (imageDict.ContainsKey("path"))
                    {
                        texturePath = imageDict ["path"].AsString;
                    }
                }
            }
            else
            {
                var metadataDict = dict.ContainsKey("metadata") ? dict ["metadata"].AsDictionary : null;

                if (metadataDict != null)
                {
                    // try to read  texture file name from meta data
                    if (metadataDict.ContainsKey("textureFileName"))
                    {
                        texturePath = metadataDict ["textureFileName"].AsString;
                    }
                }
            }

            if (!string.IsNullOrEmpty(texturePath))
            {
                // build texture path relative to plist file
                texturePath = CCFileUtils.FullPathFromRelativeFile(texturePath, fileName);
            }
            else
            {
                // build texture path by replacing file extension
                texturePath = fileName;

                // remove .xxx
                texturePath = CCFileUtils.RemoveExtension(texturePath);

                CCLog.Log("cocos2d: CCSpriteFrameCache: Trying to use file {0} as texture", texturePath);
            }

            plistFilePath = Path.GetDirectoryName(texturePath);

            CCTexture2D pTexture = CCTextureCache.SharedTextureCache.AddImage(texturePath);

            if (pTexture != null)
            {
                InitWithDictionary(dict, pTexture);
            }
            else
            {
                CCLog.Log("CCSpriteSheet: Couldn't load texture");
            }
        }
Beispiel #22
0
        private void LoadAppleDictionary(PlistDictionary dict, CCTexture2D texture)
        {
            var version = dict.ContainsKey("version") ? dict ["version"].AsInt : 0;

            if (version != 1)
            {
                throw (new NotSupportedException("Binary PList version " + version + " is not supported."));
            }


            var images = dict.ContainsKey("images") ? dict ["images"].AsArray : null;

            foreach (var imageEntry in images)
            {
                // we only support one image for now
                var imageDict = imageEntry.AsDictionary;

                var path = imageDict ["path"].AsString;

                path = Path.Combine(plistFilePath, CCFileUtils.RemoveExtension(path));

                if (!CCTextureCache.SharedTextureCache.Contains(path))
                {
                    texture = CCTextureCache.SharedTextureCache.AddImage(path);
                }
                else
                {
                    texture = CCTextureCache.SharedTextureCache[path];
                }



                // size not used right now
                //var size = CCSize.Parse(imageDict ["size"].AsString);

                var subImages = imageDict ["subimages"].AsArray;

                foreach (var subImage in subImages)
                {
                    CCSpriteFrame spriteFrame = null;

                    var subImageDict  = subImage.AsDictionary;
                    var name          = subImageDict ["name"].AsString;
                    var alias         = subImageDict ["alias"].AsString;
                    var isFullyOpaque = true;

                    if (subImageDict.ContainsKey("isFullyOpaque"))
                    {
                        isFullyOpaque = subImageDict ["isFullyOpaque"].AsBool;
                    }

                    var textureRect  = CCRect.Parse(subImageDict ["textureRect"].AsString);
                    var spriteOffset = CCPoint.Parse(subImageDict ["spriteOffset"].AsString);

                    // We are going to override the sprite offset for now to be 0,0
                    // It seems the offset is calculated off of the original size but if
                    // we pass this offset it throws our center position calculations off.
                    spriteOffset = CCPoint.Zero;

                    var textureRotated = false;
                    if (subImageDict.ContainsKey("textureRotated"))
                    {
                        textureRotated = subImageDict ["textureRotated"].AsBool;
                    }
                    var spriteSourceSize = CCSize.Parse(subImageDict ["spriteSourceSize"].AsString);
                    var frameRect        = textureRect;
                    if (textureRotated)
                    {
                        frameRect = new CCRect(textureRect.Origin.X, textureRect.Origin.Y, textureRect.Size.Height, textureRect.Size.Width);
                    }

#if DEBUG
                    CCLog.Log("texture {0} rect {1} rotated {2} offset {3}, sourcesize {4}", name, textureRect, textureRotated, spriteOffset, spriteSourceSize);
#endif

                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        texture,
                        frameRect,
                        textureRotated,
                        spriteOffset,
                        spriteSourceSize
                        );


                    _spriteFrames [name] = spriteFrame;
                }
            }
            AutoCreateAliasList();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="pszPlist"></param>
        /// <returns>The scope parameter derived from the pszPlist parameter.</returns>
        public string AddSpriteFramesWithFile(string pszPlist)
        {
            string path = CCFileUtils.FullPathFromRelativePath(pszPlist);
            //Dictionary<string, Object> dict = CCFileUtils.dictionaryWithContentsOfFile(pszPath);
            PlistDocument document = null;

            try
            {
                document = CCApplication.SharedApplication.Content.Load <PlistDocument>(path);
            }
            catch (System.Exception)
            {
                string xml = CCContent.LoadContentFile(path);
                if (xml != null)
                {
                    document = new PlistDocument(xml);
                }
            }
            if (document == null)
            {
                throw (new Microsoft.Xna.Framework.Content.ContentLoadException("Failed to load the particle definition file from " + path));
            }

            PlistDictionary dict         = document.Root.AsDictionary;
            string          texturePath  = "";
            PlistDictionary metadataDict = dict.ContainsKey("metadata") ? dict["metadata"].AsDictionary : null;

            string framePrefix = string.Empty;

            if (metadataDict != null)
            {
                // try to read  texture file name from meta data
                if (metadataDict.ContainsKey("textureFileName"))
                {
                    texturePath = metadataDict["textureFileName"].AsString;
                    framePrefix = ExtractPrefix(texturePath);
                }
            }

            if (!string.IsNullOrEmpty(texturePath))
            {
                // build texture path relative to plist file
                texturePath = CCFileUtils.FullPathFromRelativeFile(texturePath, path);
            }
            else
            {
                // build texture path by replacing file extension
                texturePath = path;

                // remove .xxx
                texturePath = CCFileUtils.RemoveExtension(texturePath);

                CCLog.Log("cocos2d: CCSpriteFrameCache: Trying to use file {0} as texture", texturePath);
            }

            CCTexture2D pTexture = CCTextureCache.SharedTextureCache.AddImage(texturePath);

            if (pTexture != null)
            {
                AddSpriteFramesWithDictionary(dict, pTexture, framePrefix);
            }
            else
            {
                CCLog.Log("cocos2d: CCSpriteFrameCache: Couldn't load texture");
            }
            return(framePrefix);
        }
Beispiel #24
0
        private CCBKeyframe ReadKeyframe(CCBPropType type)
        {
            var keyframe = new CCBKeyframe();

            keyframe.Time = ReadFloat();

            var    easingType = (CCBKeyframeEasing)ReadInt(false);
            float  easingOpt  = 0;
            object value      = null;

            if (easingType == CCBKeyframeEasing.CubicIn ||
                easingType == CCBKeyframeEasing.CubicOut ||
                easingType == CCBKeyframeEasing.CubicInOut ||
                easingType == CCBKeyframeEasing.ElasticIn ||
                easingType == CCBKeyframeEasing.ElasticOut ||
                easingType == CCBKeyframeEasing.ElasticInOut)
            {
                easingOpt = ReadFloat();
            }
            keyframe.EasingType = easingType;
            keyframe.EasingOpt  = easingOpt;

            if (type == CCBPropType.Check)
            {
                value = new CCBValue(ReadBool());
            }
            else if (type == CCBPropType.Byte)
            {
                value = new CCBValue(ReadByte());
            }
            else if (type == CCBPropType.Color3)
            {
                byte r = ReadByte();
                byte g = ReadByte();
                byte b = ReadByte();

                var c = new CCColor3B(r, g, b);
                value = new CCColor3BWapper(c);
            }
            else if (type == CCBPropType.Degrees)
            {
                value = new CCBValue(ReadFloat());
            }
            else if (type == CCBPropType.ScaleLock || type == CCBPropType.Position)
            {
                float a = ReadFloat();
                float b = ReadFloat();

                value = new List <CCBValue>
                {
                    new CCBValue(a),
                    new CCBValue(b)
                };
            }
            else if (type == CCBPropType.SpriteFrame)
            {
                string spriteSheet = ReadCachedString();
                string spriteFile  = ReadCachedString();

                CCSpriteFrame spriteFrame;

                if (String.IsNullOrEmpty(spriteSheet))
                {
                    CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage(CCFileUtils.RemoveExtension(spriteFile));
                    var         bounds  = new CCRect(0, 0, texture.ContentSize.Width, texture.ContentSize.Height);
                    spriteFrame = new CCSpriteFrame(texture, bounds);
                }
                else
                {
                    CCSpriteFrameCache frameCache = CCSpriteFrameCache.SharedSpriteFrameCache;

                    // Load the sprite sheet only if it is not loaded
                    if (!mLoadedSpriteSheets.Contains(spriteSheet))
                    {
                        frameCache.AddSpriteFramesWithFile(spriteSheet);
                        mLoadedSpriteSheets.Add(spriteSheet);
                    }

                    spriteFrame = frameCache.SpriteFrameByName(spriteFile);
                }
                value = spriteFrame;
            }

            keyframe.Value = value;

            return(keyframe);
        }
        public bool InitWithDictionary(PlistDictionary dictionary)
        {
            bool bRet = false;

            do
            {
                int maxParticles = dictionary["maxParticles"].AsInt;
                // self, not super
                if (InitWithTotalParticles(maxParticles))
                {
                    // angle
                    m_fAngle    = dictionary["angle"].AsFloat;
                    m_fAngleVar = dictionary["angleVariance"].AsFloat;

                    // duration
                    m_fDuration = dictionary["duration"].AsFloat;

                    // blend function
                    m_tBlendFunc.Source      = dictionary["blendFuncSource"].AsInt;
                    m_tBlendFunc.Destination = dictionary["blendFuncDestination"].AsInt;

                    // color
                    m_tStartColor.R = dictionary["startColorRed"].AsFloat;
                    m_tStartColor.G = dictionary["startColorGreen"].AsFloat;
                    m_tStartColor.B = dictionary["startColorBlue"].AsFloat;
                    m_tStartColor.A = dictionary["startColorAlpha"].AsFloat;

                    m_tStartColorVar.R = dictionary["startColorVarianceRed"].AsFloat;
                    m_tStartColorVar.G = dictionary["startColorVarianceGreen"].AsFloat;
                    m_tStartColorVar.B = dictionary["startColorVarianceBlue"].AsFloat;
                    m_tStartColorVar.A = dictionary["startColorVarianceAlpha"].AsFloat;

                    m_tEndColor.R = dictionary["finishColorRed"].AsFloat;
                    m_tEndColor.G = dictionary["finishColorGreen"].AsFloat;
                    m_tEndColor.B = dictionary["finishColorBlue"].AsFloat;
                    m_tEndColor.A = dictionary["finishColorAlpha"].AsFloat;

                    m_tEndColorVar.R = dictionary["finishColorVarianceRed"].AsFloat;
                    m_tEndColorVar.G = dictionary["finishColorVarianceGreen"].AsFloat;
                    m_tEndColorVar.B = dictionary["finishColorVarianceBlue"].AsFloat;
                    m_tEndColorVar.A = dictionary["finishColorVarianceAlpha"].AsFloat;

                    // particle size
                    m_fStartSize    = dictionary["startParticleSize"].AsFloat;
                    m_fStartSizeVar = dictionary["startParticleSizeVariance"].AsFloat;
                    m_fEndSize      = dictionary["finishParticleSize"].AsFloat;
                    m_fEndSizeVar   = dictionary["finishParticleSizeVariance"].AsFloat;

                    // position
                    float x = dictionary["sourcePositionx"].AsFloat;
                    float y = dictionary["sourcePositiony"].AsFloat;
                    Position    = new CCPoint(x, y);
                    m_tPosVar.X = dictionary["sourcePositionVariancex"].AsFloat;
                    m_tPosVar.Y = dictionary["sourcePositionVariancey"].AsFloat;

                    // Spinning
                    m_fStartSpin    = dictionary["rotationStart"].AsFloat;
                    m_fStartSpinVar = dictionary["rotationStartVariance"].AsFloat;
                    m_fEndSpin      = dictionary["rotationEnd"].AsFloat;
                    m_fEndSpinVar   = dictionary["rotationEndVariance"].AsFloat;

                    m_nEmitterMode = (CCEmitterMode)dictionary["emitterType"].AsInt;

                    // Mode A: Gravity + tangential accel + radial accel
                    if (m_nEmitterMode == CCEmitterMode.kCCParticleModeGravity)
                    {
                        // gravity
                        modeA.gravity.X = dictionary["gravityx"].AsFloat;
                        modeA.gravity.Y = dictionary["gravityy"].AsFloat;

                        // speed
                        modeA.speed    = dictionary["speed"].AsFloat;
                        modeA.speedVar = dictionary["speedVariance"].AsFloat;

                        // radial acceleration
                        modeA.radialAccel    = dictionary["radialAcceleration"].AsFloat;
                        modeA.radialAccelVar = dictionary["radialAccelVariance"].AsFloat;

                        // tangential acceleration
                        modeA.tangentialAccel    = dictionary["tangentialAcceleration"].AsFloat;
                        modeA.tangentialAccelVar = dictionary["tangentialAccelVariance"].AsFloat;
                    }

                    // or Mode B: radius movement
                    else if (m_nEmitterMode == CCEmitterMode.kCCParticleModeRadius)
                    {
                        modeB.startRadius        = dictionary["maxRadius"].AsFloat;
                        modeB.startRadiusVar     = dictionary["maxRadiusVariance"].AsFloat;
                        modeB.endRadius          = dictionary["minRadius"].AsFloat;
                        modeB.endRadiusVar       = 0.0f;
                        modeB.rotatePerSecond    = dictionary["rotatePerSecond"].AsFloat;
                        modeB.rotatePerSecondVar = dictionary["rotatePerSecondVariance"].AsFloat;
                    }
                    else
                    {
                        Debug.Assert(false, "Invalid emitterType in config file");
                        break;
                    }

                    // life span
                    m_fLife    = dictionary["particleLifespan"].AsFloat;
                    m_fLifeVar = dictionary["particleLifespanVariance"].AsFloat;

                    // emission Rate
                    m_fEmissionRate = m_uTotalParticles / m_fLife;

                    //don't get the internal texture if a batchNode is used
                    if (m_pBatchNode == null)
                    {
                        // Set a compatible default for the alpha transfer
                        m_bOpacityModifyRGB = false;

                        // texture
                        // Try to get the texture from the cache
                        string textureName = dictionary["textureFileName"].AsString;
                        string fullpath    = CCFileUtils.FullPathFromRelativeFile(textureName, m_sPlistFile);

                        CCTexture2D tex = null;

                        if (!string.IsNullOrEmpty(textureName))
                        {
                            // set not pop-up message box when load image failed
                            bool bNotify = CCFileUtils.IsPopupNotify;
                            CCFileUtils.IsPopupNotify = false;
                            try
                            {
                                tex = CCTextureCache.SharedTextureCache.AddImage(fullpath);
                            }
                            catch (Exception)
                            {
                                tex = null;
                            }

                            // reset the value of UIImage notify
                            CCFileUtils.IsPopupNotify = bNotify;
                        }

                        if (tex != null)
                        {
                            Texture = tex;
                        }
                        else
                        {
                            string textureData = dictionary["textureImageData"].AsString;
                            Debug.Assert(textureData != null && textureData.Length > 0, string.Format("CCParticleSystem: textureData does not exist : {0}", textureName));

                            int dataLen = textureData.Length;
                            if (dataLen != 0)
                            {
                                var dataBytes = Convert.FromBase64String(textureData);
                                Debug.Assert(dataBytes != null, string.Format("CCParticleSystem: error decoding textureImageData : {0}", textureName));

                                var imageBytes = Inflate(dataBytes);
                                Debug.Assert(imageBytes != null, string.Format("CCParticleSystem: error init image with Data for texture : {0}", textureName));

                                using (var imageStream = new MemoryStream(imageBytes))
                                {
                                    try
                                    {
                                        Texture = CCTextureCache.SharedTextureCache.AddImage(imageStream, textureName);
                                    }
                                    catch (Exception ex)
                                    {
                                        CCLog.Log(ex.ToString());
                                        throw (new NotSupportedException("Embedded textureImageData is a format that this platform does not understand. Use PNG, GIF, or JPEG for your particle systems."));
                                    }
                                }
                            }
                        }
                        Debug.Assert(Texture != null, string.Format("CCParticleSystem: error loading the texture : {0}", textureName));
                    }
                    bRet = true;
                }
            } while (false);

            return(bRet);
        }
        public bool InitWithFile(string file)
        {
            m_bManaged = false;

            Texture2D texture = null;

            m_CacheInfo.CacheType = CCTextureCacheType.AssetFile;
            m_CacheInfo.Data      = file;

            try
            {
                texture = CCApplication.SharedApplication.Content.Load <Texture2D>(file);
                //????????????????????????????
                return(InitWithTexture(texture, DefaultAlphaPixelFormat, true, true));
            }
            catch (Exception)
            {
            }

            if (texture == null)
            {
                string srcfile = file;

                if (srcfile.IndexOf('.') > -1)
                {
                    // Remove the extension
                    srcfile = srcfile.Substring(0, srcfile.LastIndexOf('.'));
                }

                try
                {
                    texture = CCApplication.SharedApplication.Content.Load <Texture2D>(srcfile);
                    //????????????????????????????
                    return(InitWithTexture(texture, DefaultAlphaPixelFormat, true, true));
                }
                catch (Exception)
                {
                    if (!srcfile.EndsWith("-hd"))
                    {
                        srcfile = srcfile + "-hd";
                        try
                        {
                            texture    = CCApplication.SharedApplication.Content.Load <Texture2D>(srcfile);
                            m_bManaged = true;
                            //????????????????????????????
                            return(InitWithTexture(texture, DefaultAlphaPixelFormat, true, true));
                        }
                        catch (Exception)
                        {
                            try
                            {
                                var stream = CCFileUtils.GetFileStream(file);
                                return(InitWithStream(stream, DefaultAlphaPixelFormat));
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }

            CCLog.Log("Texture {0} was not found.", file);
            return(false);
        }