// Handler for finding a new tag
 private static void TagHandler(MapElement element, bool actionargument, UniversalType type, ref int value, Dictionary <int, bool> usedtags)
 {
     if (value > 0)
     {
         usedtags[value] = true;                       //mxd
     }
 }
示例#2
0
 //mxd. This also sets up the association
 public void Set(Vector2D center, IEnumerable <int> tags, UniversalType type, int directlinktype)
 {
     this.tags           = new HashSet <int>(tags);  //mxd
     this.type           = type;
     this.center         = center;
     this.directlinktype = directlinktype;
 }
 // Constructor
 public TypeHandlerAttribute(UniversalType index, string name, bool customusable)
 {
     // Initialize
     this.index        = (int)index;
     this.name         = name;
     this.customusable = customusable;
 }
示例#4
0
        private void Setup(UniversalType mapelementtype)
        {
            elementtype = mapelementtype;

            // Collect used tags from appropriate element type...
            switch (elementtype)
            {
            case UniversalType.SectorTag:
                foreach (Sector s in General.Map.Map.Sectors)
                {
                    foreach (int tag in s.Tags)
                    {
                        if (tag == 0 || usedtags.Contains(tag))
                        {
                            continue;
                        }
                        usedtags.Add(tag);
                    }
                }
                break;

            case UniversalType.LinedefTag:
                if (General.Map.FormatInterface.HasLinedefTag)
                {
                    foreach (Linedef l in General.Map.Map.Linedefs)
                    {
                        foreach (int tag in l.Tags)
                        {
                            if (tag == 0 || usedtags.Contains(tag))
                            {
                                continue;
                            }
                            usedtags.Add(tag);
                        }
                    }
                }
                break;
            }

            // Now sort them in descending order
            usedtags.Sort((a, b) => - 1 * a.CompareTo(b));

            // Create tag infos
            foreach (int tag in usedtags)
            {
                if (General.Map.Options.TagLabels.ContainsKey(tag))                // Tag labels
                {
                    infos.Add(new TagInfo(tag, General.Map.Options.TagLabels[tag]));
                }
                else
                {
                    infos.Add(new TagInfo(tag, string.Empty));
                }
            }
            foreach (TagInfo info in infos)
            {
                tagpicker.Items.Add(info);
            }
            tagpicker.DropDownWidth = DoomBuilder.Geometry.Tools.GetDropDownWidth(tagpicker);
        }
 // This sets up the association
 public void Set(Vector2D center, int tag, int type)
 {
     this.tags = new HashSet <int> {
         tag
     };                                                //mxd
     this.type   = (UniversalType)type;
     this.center = center;
 }
示例#6
0
 // This sets up the association
 public Association(Vector2D center, int tag, UniversalType type)
 {
     this.tags = new HashSet <int> {
         tag
     };                                                //mxd
     this.type   = type;
     this.center = center;
 }
示例#7
0
        // Constructor
        public UniValue(UniversalType type, object value)
        {
            this.type  = (int)type;
            this.value = value;

            // We have no destructor
            GC.SuppressFinalize(this);
        }
示例#8
0
 public void Set(Vector2D center, int tag, UniversalType type, int directlinktype)
 {
     this.tags = new HashSet <int> {
         tag
     };                                                //mxd
     this.type           = type;
     this.center         = center;
     this.directlinktype = directlinktype;
 }
        // Constructor
        public UniValue(UniversalType type, object value)
        {
            // Value may only be a primitive type. Throwing exceptions in the constructor! Civil war!
            if ((!(value is int) && !(value is double) && !(value is string) && !(value is bool)) || (value == null))
            {
                throw new ArgumentException("Universal field values can only be of type int, double, string or bool.");
            }

            this.type  = (int)type;
            this.value = value;

            // We have no destructor
            GC.SuppressFinalize(this);
        }
示例#10
0
        // This sets up the form
        public void Setup()
        {
            General.Map.Map.ClearAllMarks(false);

            string modename = General.Editing.Mode.GetType().Name;

            if (modename == "SectorsMode")
            {
                selectiontype = UniversalType.SectorTag;
                ICollection <Sector> list = General.Map.Map.GetSelectedSectors(true);
                selectioncount = list.Count;
            }
            else if (modename == "LinedefsMode")
            {
                selectiontype = UniversalType.LinedefTag;
                ICollection <Linedef> list = General.Map.Map.GetSelectedLinedefs(true);
                selectioncount = list.Count;
            }
            else if (modename == "ThingsMode")
            {
                selectiontype = UniversalType.ThingTag;
                ICollection <Thing> list = General.Map.Map.GetSelectedThings(true);
                selectioncount = list.Count;
            }

            // Show number of selected items
            itemcountlabel.Text = selectioncount.ToString();

            // Find out which tags are used
            usedtags = new Dictionary <int, bool>();
            General.Map.Map.ForAllTags(TagHandler, false, usedtags);

            // Find the first unused tag to use as range start
            int starttag = General.Map.Map.GetNewTag();

            rangestart.Text = starttag.ToString();
        }
示例#11
0
        private static Dictionary <string, UniValue> ReadCustomFields(BinaryReader reader)
        {
            Dictionary <string, UniValue> fields = new Dictionary <string, UniValue>(StringComparer.Ordinal);
            int fieldscount = reader.ReadInt32();

            for (int f = 0; f < fieldscount; f++)
            {
                string        name      = ReadString(reader);
                UniversalType type      = (UniversalType)reader.ReadInt32();
                UniversalType valueType = (UniversalType)reader.ReadInt32();

                switch (valueType)
                {
                case UniversalType.Float:
                    fields.Add(name, new UniValue(type, reader.ReadSingle()));
                    break;

                case UniversalType.Boolean:
                    fields.Add(name, new UniValue(type, reader.ReadBoolean()));
                    break;

                case UniversalType.Integer:
                    fields.Add(name, new UniValue(type, reader.ReadInt32()));
                    break;

                case UniversalType.String:
                    fields.Add(name, new UniValue(type, ReadString(reader)));
                    break;

                default:                         //WOLOLO! ERRORS!
                    throw new Exception("Got unknown value type while reading custom fields from clipboard data! Field \"" + name + "\", type \"" + type + "\", primitive type \"" + valueType + "\"");
                }
            }

            return(fields);
        }
示例#12
0
        /// <summary>
        /// Sets the association to a map element. Only works with an instance of Thing, Sector, or Linedef.
        /// Also gets the forward and reverse associations
        /// </summary>
        /// <param name="element">An instance of Thing, Sector, or Linedef</param>
        public void Set(SelectableElement element)
        {
            this.element = element;
            things       = new List <Thing>();
            sectors      = new List <Sector>();
            linedefs     = new List <Linedef>();
            eventlines   = new Dictionary <string, List <Line3D> >();

            if (element is Sector)
            {
                Sector s = element as Sector;
                center = (s.Labels.Count > 0 ? s.Labels[0].position : new Vector2D(s.BBox.X + s.BBox.Width / 2, s.BBox.Y + s.BBox.Height / 2));

                type = UniversalType.SectorTag;
                tags = new HashSet <int>(s.Tags);
            }
            else if (element is Linedef)
            {
                Linedef ld = element as Linedef;
                center = ld.GetCenterPoint();

                type = UniversalType.LinedefTag;
                tags = new HashSet <int>(ld.Tags);
            }
            else if (element is Thing)
            {
                Thing t = element as Thing;
                center = t.Position;

                ThingTypeInfo ti = General.Map.Data.GetThingInfoEx(t.Type);

                if (ti != null)
                {
                    directlinktype = ti.ThingLink;
                }
                else
                {
                    directlinktype = 0;
                }

                type = UniversalType.ThingTag;
                tags = new HashSet <int>(new int[] { t.Tag });
            }

            // Remove the tag 0, because nothing sensible will come from it
            tags.Remove(0);

            // Get forward and reverse associations
            GetAssociations();

            // Cache width of label text and generate the labels
            textwidths = new Dictionary <string, Vector2D>(eventlines.Count);
            textlabels = new Dictionary <string, List <TextLabel> >(eventlines.Count);

            foreach (KeyValuePair <string, List <Line3D> > kvp in eventlines)
            {
                SizeF size = General.Interface.MeasureString(kvp.Key, font);
                textwidths[kvp.Key] = new Vector2D(size.Width, size.Height);

                // Create one label for each line. We might not need them all, but better
                // to have them all at the beginning than to generate them later
                textlabels[kvp.Key] = new List <TextLabel>(kvp.Value.Count);

                for (int i = 0; i < kvp.Value.Count; i++)
                {
                    // We don't need to set the position here, since it'll be done on the fly later
                    TextLabel l = new TextLabel();
                    l.AlignX          = TextAlignmentX.Center;
                    l.AlignY          = TextAlignmentY.Middle;
                    l.TransformCoords = true;
                    l.Text            = kvp.Key;

                    textlabels[kvp.Key].Add(l);
                }

                textwidths[kvp.Key] = new Vector2D(textlabels[kvp.Key][0].TextSize.Width, textlabels[kvp.Key][0].TextSize.Height);
            }

            SetEventLineColors();
        }
示例#13
0
 //mxd. This also sets up the association
 public void Set(Vector2D center, IEnumerable <int> tags, int type)
 {
     this.tags   = new HashSet <int>(tags);          //mxd
     this.type   = (UniversalType)type;
     this.center = center;
 }
示例#14
0
 // This sets up the association
 public void Set(int tag, UniversalType type)
 {
     this.tag  = tag;
     this.type = type;
 }
示例#15
0
 // This sets up the association
 public void Set(int tag, int type)
 {
     this.tag  = tag;
     this.type = (UniversalType)type;
 }
示例#16
0
 // This sets up the association
 public Association(int tag, int type)
 {
     this.tag  = tag;
     this.type = (UniversalType)type;
 }
示例#17
0
 //mxd. This also sets up the association
 public Association(Vector2D center, IEnumerable <int> tags, UniversalType type)
 {
     this.tags   = new HashSet <int>(tags);          //mxd
     this.type   = type;
     this.center = center;
 }
示例#18
0
文件: BER.cs 项目: fbaptiste/polymon
 public BERtag(UniversalType b) : this((byte)b)
 {
 }
        // This sets up the form
        public void Setup()
        {
            General.Map.Map.ClearAllMarks(false);

            switch (General.Editing.Mode.GetType().Name)
            {
            case "SectorsMode":
            {
                General.Map.Map.MarkSelectedSectors(true, true);                         //mxd
                selectiontype = UniversalType.SectorTag;
                ICollection <Sector> list = General.Map.Map.GetSelectedSectors(true);
                initialtags = new List <int>(list.Count);                        //mxd
                foreach (Sector element in list)
                {
                    initialtags.Add(element.Tag);                                                     //mxd
                }
                selectioncount = list.Count;
                this.Text      = "Create tag range for " + selectioncount + (selectioncount > 1 ? " sectors" : " sector");
            }
            break;

            case "LinedefsMode":
            {
                General.Map.Map.MarkSelectedLinedefs(true, true);                         //mxd
                selectiontype = UniversalType.LinedefTag;
                ICollection <Linedef> list = General.Map.Map.GetSelectedLinedefs(true);
                initialtags = new List <int>(list.Count);                        //mxd
                foreach (Linedef element in list)
                {
                    initialtags.Add(element.Tag);                                                      //mxd
                }
                selectioncount = list.Count;
                this.Text      = "Create tag range for " + selectioncount + (selectioncount > 1 ? " linedefs" : " linedef");
            }
            break;

            case "ThingsMode":
            {
                General.Map.Map.MarkSelectedThings(true, true);                         //mxd
                selectiontype = UniversalType.ThingTag;
                ICollection <Thing> list = General.Map.Map.GetSelectedThings(true);
                initialtags = new List <int>(list.Count);                        //mxd
                foreach (Thing element in list)
                {
                    initialtags.Add(element.Tag);                                                    //mxd
                }
                selectioncount = list.Count;
                this.Text      = "Create tag range for " + selectioncount + (selectioncount > 1 ? " things" : " thing");
            }
            break;
            }

            // Find out which tags are used
            usedtags = new Dictionary <int, bool>();
            General.Map.Map.ForAllTags(TagHandler, false, usedtags);

            // Find the first unused tag to use as range start
            int starttag = General.Map.Map.GetNewTag();

            rangestart.Text = starttag.ToString();

            //mxd. Apply saved settings
            rangestep.Text       = storedstep.ToString();
            relativemode.Checked = storedrelative;

            //mxd. Do useless stuff
            if (General.Random(0, 255) > 230)
            {
                bglabel.Text = "Creating tag ranges is fun! ^_^";
            }
        }
示例#20
0
 //mxd. This also sets up the association
 public void Set(Vector2D center, IEnumerable <int> tags, UniversalType type)
 {
     this.Set(center, tags, type, 0);
 }
示例#21
0
 // This sets up the association
 public void Set(Vector2D center, int tag, UniversalType type)
 {
     this.Set(center, tag, type, 0);
 }
示例#22
0
        }                                                                              //mxd

        #endregion

        #region ================== Constructor / Disposer

        // Constructor
        internal ActorStructure(DecorateParser parser, DecorateCategoryInfo catinfo)
        {
            // Initialize
            this.catinfo = catinfo;             //mxd
            flags        = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);
            props        = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase);
            states       = new Dictionary <string, StateStructure>(StringComparer.OrdinalIgnoreCase);
            uservars     = new Dictionary <string, UniversalType>(StringComparer.OrdinalIgnoreCase); //mxd
            bool done = false;                                                                       //mxd

            // Always define a game property, but default to 0 values
            props["game"] = new List <string>();

            inheritclass = "actor";
            replaceclass = null;
            baseclass    = null;
            skipsuper    = false;

            // First next token is the class name
            parser.SkipWhitespace(true);
            classname = parser.StripTokenQuotes(parser.ReadToken(ACTOR_CLASS_SPECIAL_TOKENS));

            if (string.IsNullOrEmpty(classname))
            {
                parser.ReportError("Expected actor class name");
                return;
            }

            //mxd. Fail on duplicates
            if (parser.ActorsByClass.ContainsKey(classname.ToLowerInvariant()))
            {
                parser.ReportError("Actor \"" + classname + "\" is double-defined");
                return;
            }

            // Parse tokens before entering the actor scope
            while (parser.SkipWhitespace(true))
            {
                string token = parser.ReadToken();
                if (!string.IsNullOrEmpty(token))
                {
                    token = token.ToLowerInvariant();

                    switch (token)
                    {
                    case ":":
                        // The next token must be the class to inherit from
                        parser.SkipWhitespace(true);
                        inheritclass = parser.StripTokenQuotes(parser.ReadToken());
                        if (string.IsNullOrEmpty(inheritclass))
                        {
                            parser.ReportError("Expected class name to inherit from");
                            return;
                        }

                        // Find the actor to inherit from
                        baseclass = parser.GetArchivedActorByName(inheritclass);
                        break;

                    case "replaces":
                        // The next token must be the class to replace
                        parser.SkipWhitespace(true);
                        replaceclass = parser.StripTokenQuotes(parser.ReadToken());
                        if (string.IsNullOrEmpty(replaceclass))
                        {
                            parser.ReportError("Expected class name to replace");
                            return;
                        }
                        break;

                    case "native":
                        // Igore this token
                        break;

                    case "{":
                        // Actor scope begins here,
                        // break out of this parse loop
                        done = true;
                        break;

                    case "-":
                        // This could be a negative doomednum (but our parser sees the - as separate token)
                        // So read whatever is after this token and ignore it (negative doomednum indicates no doomednum)
                        parser.ReadToken();
                        break;

                    default:
                        //mxd. Property begins with $? Then the whole line is a single value
                        if (token.StartsWith("$"))
                        {
                            // This is for editor-only properties such as $sprite and $category
                            props[token] = new List <string> {
                                (parser.SkipWhitespace(false) ? parser.ReadLine() : "")
                            };
                            continue;
                        }

                        if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out doomednum))                                // Check if numeric
                        {
                            // Not numeric!
                            parser.ReportError("Expected editor number or start of actor scope while parsing \"" + classname + "\"");
                            return;
                        }

                        //mxd. Range check
                        if ((doomednum < General.Map.FormatInterface.MinThingType) || (doomednum > General.Map.FormatInterface.MaxThingType))
                        {
                            // Out of bounds!
                            parser.ReportError("Actor \"" + classname + "\" has invalid editor number. Editor number must be between "
                                               + General.Map.FormatInterface.MinThingType + " and " + General.Map.FormatInterface.MaxThingType);
                            return;
                        }
                        break;
                    }

                    if (done)
                    {
                        break;                          //mxd
                    }
                }
                else
                {
                    parser.ReportError("Unexpected end of structure");
                    return;
                }
            }

            // Now parse the contents of actor structure
            string previoustoken = "";

            done = false;             //mxd
            while (parser.SkipWhitespace(true))
            {
                string token = parser.ReadToken();
                token = token.ToLowerInvariant();

                switch (token)
                {
                case "+":
                case "-":
                    // Next token is a flag (option) to set or remove
                    bool flagvalue = (token == "+");
                    parser.SkipWhitespace(true);
                    string flagname = parser.ReadToken();
                    if (!string.IsNullOrEmpty(flagname))
                    {
                        // Add the flag with its value
                        flagname        = flagname.ToLowerInvariant();
                        flags[flagname] = flagvalue;
                    }
                    else
                    {
                        parser.ReportError("Expected flag name");
                        return;
                    }
                    break;

                case "action":
                case "native":
                    // We don't need this, ignore up to the first next ;
                    while (parser.SkipWhitespace(true))
                    {
                        string t = parser.ReadToken();
                        if (string.IsNullOrEmpty(t) || t == ";")
                        {
                            break;
                        }
                    }
                    break;

                case "skip_super":
                    skipsuper = true;
                    break;

                case "states":
                    // Now parse actor states until we reach the end of the states structure
                    while (parser.SkipWhitespace(true))
                    {
                        string statetoken = parser.ReadToken();
                        if (!string.IsNullOrEmpty(statetoken))
                        {
                            // Start of scope?
                            if (statetoken == "{")
                            {
                                // This is fine
                            }
                            // End of scope?
                            else if (statetoken == "}")
                            {
                                // Done with the states,
                                // break out of this parse loop
                                break;
                            }
                            // State label?
                            else if (statetoken == ":")
                            {
                                if (!string.IsNullOrEmpty(previoustoken))
                                {
                                    // Parse actor state
                                    StateStructure st = new StateStructure(this, parser);
                                    if (parser.HasError)
                                    {
                                        return;
                                    }
                                    states[previoustoken.ToLowerInvariant()] = st;
                                }
                                else
                                {
                                    parser.ReportError("Expected actor state name");
                                    return;
                                }
                            }
                            else
                            {
                                // Keep token
                                previoustoken = statetoken;
                            }
                        }
                        else
                        {
                            parser.ReportError("Unexpected end of structure");
                            return;
                        }
                    }
                    break;

                case "var":                         //mxd
                    // Type
                    parser.SkipWhitespace(true);
                    string        typestr = parser.ReadToken().ToUpperInvariant();
                    UniversalType type    = UniversalType.EnumOption;                          // There is no Unknown type, so let's use something impossiburu...
                    switch (typestr)
                    {
                    case "INT": type = UniversalType.Integer; break;

                    case "FLOAT": type = UniversalType.Float; break;

                    default: parser.LogWarning("Unknown user variable type"); break;
                    }

                    // Name
                    parser.SkipWhitespace(true);
                    string name = parser.ReadToken();
                    if (string.IsNullOrEmpty(name))
                    {
                        parser.ReportError("Expected User Variable name");
                        return;
                    }
                    if (!name.StartsWith("user_", StringComparison.OrdinalIgnoreCase))
                    {
                        parser.ReportError("User Variable name must start with \"user_\" prefix");
                        return;
                    }
                    if (uservars.ContainsKey(name))
                    {
                        parser.ReportError("User Variable \"" + name + "\" is double defined");
                        return;
                    }
                    if (!skipsuper && baseclass != null && baseclass.uservars.ContainsKey(name))
                    {
                        parser.ReportError("User variable \"" + name + "\" is already defined in one of the parent classes");
                        return;
                    }

                    // Rest
                    parser.SkipWhitespace(true);
                    string next = parser.ReadToken();
                    if (next == "[")                            // that's User Array. Let's skip it...
                    {
                        int arrlen = -1;
                        if (!parser.ReadSignedInt(ref arrlen))
                        {
                            parser.ReportError("Expected User Array length");
                            return;
                        }
                        if (arrlen < 1)
                        {
                            parser.ReportError("User Array length must be a positive value");
                            return;
                        }
                        if (!parser.NextTokenIs("]") || !parser.NextTokenIs(";"))
                        {
                            return;
                        }
                    }
                    else if (next != ";")
                    {
                        parser.ReportError("Expected \";\", but got \"" + next + "\"");
                        return;
                    }
                    else
                    {
                        // Add to collection
                        uservars.Add(name, type);
                    }
                    break;

                case "}":
                    //mxd. Get user vars from the BaseClass, if we have one
                    if (!skipsuper && baseclass != null && baseclass.uservars.Count > 0)
                    {
                        foreach (var group in baseclass.uservars)
                        {
                            uservars.Add(group.Key, group.Value);
                        }
                    }

                    // Actor scope ends here, break out of this parse loop
                    done = true;
                    break;

                // Monster property?
                case "monster":
                    // This sets certain flags we are interested in
                    flags["shootable"]      = true;
                    flags["countkill"]      = true;
                    flags["solid"]          = true;
                    flags["canpushwalls"]   = true;
                    flags["canusewalls"]    = true;
                    flags["activatemcross"] = true;
                    flags["canpass"]        = true;
                    flags["ismonster"]      = true;
                    break;

                // Projectile property?
                case "projectile":
                    // This sets certain flags we are interested in
                    flags["noblockmap"]     = true;
                    flags["nogravity"]      = true;
                    flags["dropoff"]        = true;
                    flags["missile"]        = true;
                    flags["activateimpact"] = true;
                    flags["activatepcross"] = true;
                    flags["noteleport"]     = true;
                    break;

                // Clearflags property?
                case "clearflags":
                    // Clear all flags
                    flags.Clear();
                    break;

                // Game property?
                case "game":
                    // Include all tokens on the same line
                    List <string> games = new List <string>();
                    while (parser.SkipWhitespace(false))
                    {
                        string v = parser.ReadToken();
                        if (string.IsNullOrEmpty(v))
                        {
                            parser.ReportError("Expected \"Game\" property value");
                            return;
                        }
                        if (v == "\n")
                        {
                            break;
                        }
                        if (v == "}")
                        {
                            return;                                          //mxd
                        }
                        if (v != ",")
                        {
                            games.Add(v.ToLowerInvariant());
                        }
                    }
                    props[token] = games;
                    break;

                // Property
                default:
                    // Property begins with $? Then the whole line is a single value
                    if (token.StartsWith("$"))
                    {
                        // This is for editor-only properties such as $sprite and $category
                        props[token] = new List <string> {
                            (parser.SkipWhitespace(false) ? parser.ReadLine() : "")
                        };
                    }
                    else
                    {
                        // Next tokens up until the next newline are values
                        List <string> values = new List <string>();
                        while (parser.SkipWhitespace(false))
                        {
                            string v = parser.ReadToken();
                            if (string.IsNullOrEmpty(v))
                            {
                                parser.ReportError("Unexpected end of structure");
                                return;
                            }
                            if (v == "\n")
                            {
                                break;
                            }
                            if (v == "}")
                            {
                                return;                                              //mxd
                            }
                            if (v != ",")
                            {
                                values.Add(v);
                            }
                        }

                        //mxd. Translate scale to xscale and yscale
                        if (token == "scale")
                        {
                            props["xscale"] = values;
                            props["yscale"] = values;
                        }
                        else
                        {
                            props[token] = values;
                        }
                    }
                    break;
                }

                if (done)
                {
                    break;                      //mxd
                }
                // Keep token
                previoustoken = token;
            }

            //mxd. Check if baseclass is valid
            if (inheritclass.ToLowerInvariant() != "actor" && doomednum > -1 && baseclass == null)
            {
                //check if this class inherits from a class defined in game configuration
                Dictionary <int, ThingTypeInfo> things = General.Map.Config.GetThingTypes();
                string inheritclasscheck = inheritclass.ToLowerInvariant();

                foreach (KeyValuePair <int, ThingTypeInfo> ti in things)
                {
                    if (!string.IsNullOrEmpty(ti.Value.ClassName) && ti.Value.ClassName.ToLowerInvariant() == inheritclasscheck)
                    {
                        //states
                        if (states.Count == 0 && !string.IsNullOrEmpty(ti.Value.Sprite))
                        {
                            states.Add("spawn", new StateStructure(ti.Value.Sprite.Substring(0, 5)));
                        }

                        //flags
                        if (ti.Value.Hangs && !flags.ContainsKey("spawnceiling"))
                        {
                            flags["spawnceiling"] = true;
                        }

                        if (ti.Value.Blocking > 0 && !flags.ContainsKey("solid"))
                        {
                            flags["solid"] = true;
                        }

                        //properties
                        if (!props.ContainsKey("height"))
                        {
                            props["height"] = new List <string> {
                                ti.Value.Height.ToString()
                            }
                        }
                        ;

                        if (!props.ContainsKey("radius"))
                        {
                            props["radius"] = new List <string> {
                                ti.Value.Radius.ToString()
                            }
                        }
                        ;

                        return;
                    }
                }

                parser.LogWarning("Unable to find \"" + inheritclass + "\" class to inherit from, while parsing \"" + classname + ":" + doomednum + "\"");
            }
        }
        internal ZScriptActorStructure(ZDTextParser zdparser, DecorateCategoryInfo catinfo, string _classname, string _replacesname, string _parentname)
        {
            this.catinfo = catinfo; //mxd

            parser           = (ZScriptParser)zdparser;
            stream           = parser.DataStream;
            tokenizer        = new ZScriptTokenizer(parser.DataReader);
            parser.tokenizer = tokenizer;

            classname    = _classname;
            replaceclass = _replacesname;
            //baseclass = parser.GetArchivedActorByName(_parentname); // this is not guaranteed to work here

            mixins = new List <string>();

            ZScriptToken cls_open = tokenizer.ExpectToken(ZScriptTokenType.OpenCurly);

            if (cls_open == null || !cls_open.IsValid)
            {
                parser.ReportError("Expected {, got " + ((Object)cls_open ?? "<null>").ToString());
                return;
            }

            // this dict holds temporary user settings per field (function, etc)
            Dictionary <string, List <string> > var_props = new Dictionary <string, List <string> >();

            // in the class definition, we can have the following:
            // - Defaults block
            // - States block
            // - method signature: [native] [action] <type [, type [...]]> <name> (<arguments>);
            // - method: <method signature (except native)> <block>
            // - field declaration: [native] <type> <name>;
            // - enum definition: enum <name> <block>;
            // we are skipping everything, except Defaults and States.
            while (true)
            {
                var_props.Clear();
                while (true)
                {
                    ZScriptToken tt = tokenizer.ExpectToken(ZScriptTokenType.Whitespace, ZScriptTokenType.BlockComment, ZScriptTokenType.LineComment, ZScriptTokenType.Newline);
                    if (tt == null || !tt.IsValid)
                    {
                        break;
                    }

                    if (tt.Type == ZScriptTokenType.LineComment)
                    {
                        ParseGZDBComment(var_props, tt.Value);
                    }
                }

                //tokenizer.SkipWhitespace();
                long         ocpos = stream.Position;
                ZScriptToken token = tokenizer.ExpectToken(ZScriptTokenType.Identifier, ZScriptTokenType.CloseCurly);
                if (token == null || !token.IsValid)
                {
                    parser.ReportError("Expected identifier, got " + ((Object)cls_open ?? "<null>").ToString());
                    return;
                }
                if (token.Type == ZScriptTokenType.CloseCurly) // end of class
                {
                    break;
                }

                string b_lower = token.Value.ToLowerInvariant();
                switch (b_lower)
                {
                case "default":
                    if (!ParseDefaultBlock())
                    {
                        return;
                    }
                    continue;

                case "states":
                    if (!ParseStatesBlock())
                    {
                        return;
                    }
                    continue;

                case "enum":
                    if (!parser.ParseEnum())
                    {
                        return;
                    }
                    continue;

                case "const":
                    if (!parser.ParseConst())
                    {
                        return;
                    }
                    continue;

                // apparently we can have a struct inside a class, but not another class.
                case "struct":
                    if (!parser.ParseClassOrStruct(true, false, false, null))
                    {
                        return;
                    }
                    continue;

                // new properties syntax
                case "property":
                    if (!ParseProperty())
                    {
                        return;
                    }
                    continue;

                // new flags syntax
                case "flagdef":
                    if (!ParseFlagdef())
                    {
                        return;
                    }
                    continue;

                // mixins
                case "mixin":
                    if (!ParseMixin())
                    {
                        return;
                    }
                    continue;

                default:
                    stream.Position = ocpos;
                    break;
                }

                // try to read in a variable/method.
                bool                bmethod            = false;
                string[]            availablemodifiers = new string[] { "static", "native", "action", "readonly", "protected", "private", "virtual", "override", "meta", "transient", "deprecated", "final", "play", "ui", "clearscope", "virtualscope", "version", "const" };
                string[]            versionedmodifiers = new string[] { "version", "deprecated" };
                string[]            methodmodifiers    = new string[] { "action", "virtual", "override", "final" };
                HashSet <string>    modifiers          = new HashSet <string>();
                List <string>       types         = new List <string>();
                List <List <int> >  typearraylens = new List <List <int> >();
                List <string>       names         = new List <string>();
                List <List <int> >  arraylens     = new List <List <int> >();
                List <ZScriptToken> args          = null; // this is for the future
                //List<ZScriptToken> body = null;

                while (true)
                {
                    tokenizer.SkipWhitespace();
                    long cpos = stream.Position;
                    token = tokenizer.ExpectToken(ZScriptTokenType.Identifier);
                    if (token == null || !token.IsValid)
                    {
                        parser.ReportError("Expected modifier or name, got " + ((Object)cls_open ?? "<null>").ToString());
                        return;
                    }

                    b_lower = token.Value.ToLowerInvariant();
                    if (availablemodifiers.Contains(b_lower))
                    {
                        if (modifiers.Contains(b_lower))
                        {
                            parser.ReportError("Field/method modifier '" + b_lower + "' was specified twice");
                            return;
                        }

                        if (methodmodifiers.Contains(b_lower))
                        {
                            bmethod = true;
                        }

                        if (versionedmodifiers.Contains(b_lower))
                        {
                            string version = ParseVersion(b_lower == "version"); // deprecated doesn't require version string for historical reasons. (compatibility with old gzdoom.pk3)
                            if (version == null && b_lower == "version")
                            {
                                return;
                            }
                        }

                        modifiers.Add(b_lower);
                    }
                    else
                    {
                        stream.Position = cpos;
                        break;
                    }
                }

                // read in the type name(s)
                // type name can be:
                //  - identifier
                //  - identifier<identifier>
                while (true)
                {
                    tokenizer.SkipWhitespace();
                    string typename = ParseTypeName();
                    if (typename == null)
                    {
                        return;
                    }

                    types.Add(typename.ToLowerInvariant());
                    typearraylens.Add(null);
                    long cpos = stream.Position;
                    tokenizer.SkipWhitespace();
                    token = tokenizer.ExpectToken(ZScriptTokenType.Comma, ZScriptTokenType.Identifier, ZScriptTokenType.OpenSquare);

                    if (token != null && !token.IsValid)
                    {
                        parser.ReportError("Expected comma, identifier or array dimensions, got " + ((Object)token ?? "<null>").ToString());
                        return;
                    }

                    if (token == null || token.Type != ZScriptTokenType.Comma)
                    {
                        stream.Position = cpos;
                        if (token.Type == ZScriptTokenType.OpenSquare)
                        {
                            List <int> typelens = ParseArrayDimensions();
                            if (typelens == null) // error
                            {
                                return;
                            }
                            typearraylens[typearraylens.Count - 1] = typelens;
                        }
                        break;
                    }
                }

                while (true)
                {
                    string     name = null;
                    List <int> lens = null;

                    // read in the method/field name
                    tokenizer.SkipWhitespace();
                    token = tokenizer.ExpectToken(ZScriptTokenType.Identifier);
                    if (token == null || !token.IsValid)
                    {
                        parser.ReportError("Expected field/method name, got " + ((Object)token ?? "<null>").ToString());
                        return;
                    }
                    name = token.Value.ToLowerInvariant();

                    // check the token. if it's a (, then it's a method. if it's a ;, then it's a field, if it's a [ it's an array field.
                    // if it's a field and bmethod=true, report error.
                    tokenizer.SkipWhitespace();
                    long cpos = stream.Position;
                    token = tokenizer.ExpectToken(ZScriptTokenType.Comma, ZScriptTokenType.OpenParen, ZScriptTokenType.OpenSquare, ZScriptTokenType.Semicolon);
                    if (token == null || !token.IsValid)
                    {
                        parser.ReportError("Expected comma, ;, [, or argument list, got " + ((Object)token ?? "<null>").ToString());
                        return;
                    }

                    if (token.Type == ZScriptTokenType.OpenParen)
                    {
                        // if we have multiple names
                        if (names.Count > 0)
                        {
                            parser.ReportError("Cannot have multiple names in a method");
                            return;
                        }

                        bmethod = true;
                        // now, I could parse this properly, but it won't be used anyway, so I'll do it as a fake expression.
                        args  = parser.ParseExpression(true);
                        token = tokenizer.ExpectToken(ZScriptTokenType.CloseParen);
                        if (token == null || !token.IsValid)
                        {
                            parser.ReportError("Expected ), got " + ((Object)token ?? "<null>").ToString());
                            return;
                        }

                        // also get the body block, if any.
                        tokenizer.SkipWhitespace();
                        cpos  = stream.Position;
                        token = tokenizer.ExpectToken(ZScriptTokenType.Semicolon, ZScriptTokenType.OpenCurly, ZScriptTokenType.Identifier);
                        if (token == null || !token.IsValid)
                        {
                            parser.ReportError("Expected 'const', ; or {, got " + ((Object)token ?? "<null>").ToString());
                            return;
                        }

                        //
                        if (token.Type == ZScriptTokenType.Identifier)
                        {
                            if (token.Value.ToLowerInvariant() != "const")
                            {
                                parser.ReportError("Expected 'const', got " + ((Object)token ?? "<null>").ToString());
                                return;
                            }

                            tokenizer.SkipWhitespace();
                            cpos  = stream.Position;
                            token = tokenizer.ExpectToken(ZScriptTokenType.Semicolon, ZScriptTokenType.OpenCurly);
                            if (token == null || !token.IsValid)
                            {
                                parser.ReportError("Expected ; or {, got " + ((Object)token ?? "<null>").ToString());
                                return;
                            }
                        }

                        if (token.Type == ZScriptTokenType.OpenCurly)
                        {
                            stream.Position = cpos;
                            parser.SkipBlock();
                            //body = parser.ParseBlock(false);
                        }

                        break; // end method parsing
                    }
                    else
                    {
                        if (bmethod)
                        {
                            parser.ReportError("Cannot have virtual, override or action fields");
                            return;
                        }

                        // array
                        if (token.Type == ZScriptTokenType.OpenSquare)
                        {
                            stream.Position = cpos;
                            lens            = ParseArrayDimensions();
                            if (lens == null) // error
                            {
                                return;
                            }


                            tokenizer.SkipWhitespace();
                            ZScriptTokenType[] expectTokens;
                            if (modifiers.Contains("static"))
                            {
                                expectTokens = new ZScriptTokenType[] { ZScriptTokenType.Semicolon, ZScriptTokenType.Comma, ZScriptTokenType.OpAssign }
                            }
                            ;
                            else
                            {
                                expectTokens = new ZScriptTokenType[] { ZScriptTokenType.Semicolon, ZScriptTokenType.Comma }
                            };
                            token = tokenizer.ExpectToken(expectTokens);
                            if (token == null || !token.IsValid)
                            {
                                parser.ReportError("Expected ;, =, or comma, got " + ((Object)token ?? "<null>").ToString());
                                return;
                            }

                            // "static int A[] = {1, 2, 3};"
                            if (token.Type == ZScriptTokenType.OpAssign)
                            {
                                // read in array data
                                tokenizer.SkipWhitespace();
                                parser.SkipBlock(false);
                                tokenizer.SkipWhitespace();
                                token = tokenizer.ExpectToken(ZScriptTokenType.Semicolon, ZScriptTokenType.Comma);
                                if (token == null || !token.IsValid)
                                {
                                    parser.ReportError("Expected ; or comma, got " + ((Object)token ?? "<null>").ToString());
                                    return;
                                }
                            }
                        }
                    }

                    names.Add(name);
                    arraylens.Add(lens);

                    if (token.Type != ZScriptTokenType.Comma) // next name
                    {
                        break;
                    }
                }

                // validate modifiers here.
                // protected and private cannot be combined.
                if (bmethod)
                {
                    if (modifiers.Contains("protected") && modifiers.Contains("private"))
                    {
                        parser.ReportError("Cannot have protected and private on the same method");
                        return;
                    }
                    // virtual and override cannot be combined.
                    int cvirtual = modifiers.Contains("virtual") ? 1 : 0;
                    cvirtual += modifiers.Contains("override") ? 1 : 0;
                    cvirtual += modifiers.Contains("final") ? 1 : 0;
                    if (cvirtual > 1)
                    {
                        parser.ReportError("Cannot have virtual, override and final on the same method");
                        return;
                    }
                    // meta (what the f**k is that?) probably cant be on a method
                    if (modifiers.Contains("meta"))
                    {
                        parser.ReportError("Cannot have meta on a method");
                        return;
                    }
                }

                // finished method or field parsing.

                /*for (int i = 0; i < names.Count; i++)
                 * {
                 *  string name = names[i];
                 *  int arraylen = arraylens[i];
                 *
                 *  string _args = "";
                 *  if (args != null) _args = " (" + ZScriptTokenizer.TokensToString(args) + ")";
                 *  else if (arraylen != -1) _args = " [" + arraylen.ToString() + "]";
                 *  parser.LogWarning(string.Format("{0} {1} {2}{3}", string.Join(" ", modifiers.ToArray()), string.Join(", ", types.ToArray()), name, _args));
                 * }*/

                // update 08.02.17: add user variables from ZScript actors.
                if (args == null && types.Count == 1) // it's a field
                {
                    // we support:
                    //  - float
                    //  - int
                    //  - double
                    //  - bool
                    string        type = types[0];
                    UniversalType utype;
                    object        udefault = null;
                    switch (type)
                    {
                    case "int":
                    case "int8":
                    case "int16":
                    case "uint":
                    case "uint8":
                    case "uint16":
                        utype = UniversalType.Integer;
                        break;

                    case "float":
                    case "double":
                        utype = UniversalType.Float;
                        break;

                    case "bool":
                        utype = UniversalType.Boolean;
                        break;

                    case "string":
                        utype = UniversalType.String;
                        break;

                    // todo test if class names and colors will work
                    default:
                        continue;     // go read next field
                    }

                    UniversalType utype_reinterpret = utype;
                    if (var_props.ContainsKey("$userreinterpret"))
                    {
                        string sp = var_props["$userreinterpret"][0].Trim().ToLowerInvariant();
                        switch (sp)
                        {
                        case "color":
                            if (utype != UniversalType.Integer)
                            {
                                parser.LogWarning("Cannot use $UserReinterpret Color with non-integers");
                                break;
                            }
                            utype_reinterpret = UniversalType.Color;
                            break;
                        }
                    }

                    if (var_props.ContainsKey("$userdefaultvalue"))
                    {
                        string sp = var_props["$userdefaultvalue"][0];
                        switch (utype)
                        {
                        case UniversalType.String:
                            if (sp[0] == '"' && sp[sp.Length - 1] == '"')
                            {
                                sp = sp.Substring(1, sp.Length - 2);
                            }
                            udefault = sp;
                            break;

                        case UniversalType.Float:
                            double d;
                            if (!double.TryParse(sp, out d))
                            {
                                parser.LogWarning("Incorrect float default from string \"" + sp + "\"");
                                break;
                            }
                            udefault = d;
                            break;

                        case UniversalType.Integer:
                            int i;
                            if (!int.TryParse(sp, out i))
                            {
                                if (utype_reinterpret == UniversalType.Color)
                                {
                                    sp = sp.ToLowerInvariant();
                                    Rendering.PixelColor pc;
                                    if (!ZDTextParser.GetColorFromString(sp, out pc))
                                    {
                                        parser.LogWarning("Incorrect color default from string \"" + sp + "\"");
                                        break;
                                    }
                                    udefault = pc.ToInt() & 0xFFFFFF;
                                    break;
                                }
                            }
                            udefault = i;
                            break;

                        case UniversalType.Boolean:
                            sp = sp.ToLowerInvariant();
                            if (sp == "true")
                            {
                                udefault = true;
                            }
                            else if (sp == "false")
                            {
                                udefault = false;
                            }
                            else
                            {
                                parser.LogWarning("Incorrect boolean default from string \"" + sp + "\"");
                            }
                            break;
                        }
                    }

                    for (int i = 0; i < names.Count; i++)
                    {
                        string name = names[i];
                        if (arraylens[i] != null || typearraylens[0] != null)
                        {
                            continue; // we don't process arrays
                        }
                        if (!name.StartsWith("user_"))
                        {
                            continue; // we don't process non-user_ fields (because ZScript won't pick them up anyway)
                        }
                        // parent class is not guaranteed to be loaded already, so handle collisions later
                        uservars.Add(name, utype_reinterpret);
                        if (udefault != null)
                        {
                            uservar_defaults.Add(name, udefault);
                        }
                    }
                }
            }

            // parsing done, process thing arguments
            ParseCustomArguments();
        }
    }
示例#24
0
 // This sets up the association
 public Association(int tag, UniversalType type)
 {
     this.tag  = tag;
     this.type = type;
 }