Beispiel #1
0
 internal static IEnumerable <GameVersion> GetGen2Versions(LegalInfo Info, bool korean)
 {
     if (ParseSettings.AllowGen2Crystal(korean) && Info.Game.Contains(GameVersion.C))
     {
         yield return(GameVersion.C);
     }
     yield return(GameVersion.GS);
 }
Beispiel #2
0
        private static void InitializeCoreStrings()
        {
            var lang = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Substring(0, 2);

            Util.SetLocalization(typeof(LegalityCheckStrings), lang);
            Util.SetLocalization(typeof(MessageStrings), lang);
            RibbonStrings.ResetDictionary(GameInfo.Strings.ribbons);
            ParseSettings.ChangeLocalizationStrings(GameInfo.Strings.movelist, GameInfo.Strings.specieslist);
        }
Beispiel #3
0
        internal static IEnumerable <GameVersion> GetGen2Versions(LegalInfo Info)
        {
            if (ParseSettings.AllowGen2Crystal(Info.Korean) && Info.Game == GameVersion.C)
            {
                yield return(GameVersion.C);
            }

            // Any encounter marked with version GSC is for pokemon with the same moves in GS and C
            // it is sufficient to check just GS's case
            yield return(GameVersion.GS);
        }
Beispiel #4
0
        private static Result <Quantity, Error <QuantityError> > GetError(
            ParseSettings parseSettings,
            QuantityError quantityError,
            Lexemes lexemes)
        {
            var error = Error.From(quantityError, lexemes.Current);

            if (parseSettings.ThrowOnError)
            {
                throw new QuantityParseException(error);
            }

            return(Result.Error(error));
        }
Beispiel #5
0
    /// <summary>
    /// Initializes PKHeX's runtime strings to the specified language.
    /// </summary>
    /// <param name="lang">2-char language ID</param>
    /// <param name="sav">Save data (optional)</param>
    /// <param name="hax">Permit illegal things (items, only)</param>
    public static void InitializeStrings(string lang, SaveFile?sav = null, bool hax = false)
    {
        var str = GameInfo.Strings = GameInfo.GetStrings(lang);

        if (sav != null)
        {
            GameInfo.FilteredSources = new FilteredGameDataSource(sav, GameInfo.Sources, hax);
        }

        // Update Legality Analysis strings
        ParseSettings.ChangeLocalizationStrings(str.movelist, str.specieslist);

        // Update Legality Strings
        Task.Run(() =>
        {
            RibbonStrings.ResetDictionary(str.ribbons);
            LocalizationUtil.SetLocalization(typeof(LegalityCheckStrings), lang);
            LocalizationUtil.SetLocalization(typeof(MessageStrings), lang);
        });
    }
Beispiel #6
0
        /// <summary>
        /// Parses the specified quantity.
        /// </summary>
        /// <param name="lexemes">The lexemes.</param>
        /// <param name="parseSettings">The parse settings.</param>
        /// <returns>
        /// A <see cref="Quantity" />.
        /// </returns>
        /// <exception cref="QuantityParseException">Exception thrown when parsing fails.</exception>
        public Result <Quantity, Error <QuantityError> > Parse(Lexemes lexemes, ParseSettings parseSettings)
        {
            if (lexemes.AcceptTokenType(TokenType.Number, out var number))
            {
                var value  = double.Parse(number, parseSettings.CultureInfo);
                var result = this.expressionParser.Parse(
                    lexemes,
                    new ParseSettings(parseSettings.CultureInfo, false, false));

                if (parseSettings.AssertEnd && lexemes.AcceptTokenType(TokenType.End))
                {
                    return(GetError(parseSettings, QuantityError.EndOfDataNotFound, lexemes));
                }

                return(result.Convert(
                           expression => new Quantity(value, this.unitFactory.Create(expression)),
                           error => Error.From(QuantityError.UnitNotFound, lexemes.Current, error)));
            }

            return(GetError(parseSettings, QuantityError.NumberNotFound, lexemes));
        }
Beispiel #7
0
    /// <summary>
    /// Checks if a Gen1 trade evolution must have occurred.
    /// </summary>
    private static bool IsTradeEvolutionRequired(LegalityAnalysis data, IEncounterTemplate enc)
    {
        // There is no way to prevent a Gen1 trade evolution, as held items (Everstone) did not exist.
        // Machoke, Graveler, Haunter and Kadabra captured in the second phase evolution, excluding in-game trades, are already checked
        var pk      = data.Entity;
        var species = pk.Species;

        // This check is only applicable if it's a trade evolution that has not been evolved.
        if (!GBRestrictions.Trade_Evolution1.Contains(enc.Species) || enc.Species != species)
        {
            return(false);
        }

        // Context check is only applicable to gen1/2; transferring to Gen2 is a trade.
        // Stadium 2 can transfer across game/generation boundaries without initiating a trade.
        // Ignore this check if the environment's loaded trainer is not from Gen1/2 or is from GB Era.
        if (ParseSettings.ActiveTrainer.Generation >= 3 || ParseSettings.AllowGBCartEra)
        {
            return(false);
        }

        // Gen2 stuff can be traded between Gen2 games holding an Everstone, assuming it hasn't been transferred to Gen1 for special moves.
        if (enc.Generation == 2)
        {
            return(data.Info.Moves.Any(z => z.Generation != 2));
        }
        // Gen1 stuff can only be un-evolved if it was never traded from the OT.
        if (data.Info.Moves.Any(z => z.Generation != 1))
        {
            return(true); // traded to Gen2 for special moves
        }
        if (pk.Format != 1)
        {
            return(true);                               // traded to Gen2 (current state)
        }
        return(!ParseSettings.IsFromActiveTrainer(pk)); // not with OT
    }
Beispiel #8
0
        private static void ParseWithManualSettings()
        {
            try
            {
                var askUserDialog = new ParseSettings
                {
                    MainLabel    = { Text = "Manually enter values for parsing CSV\n\nUse this if detection fails" },
                    txbQuoteChar = { Text = Main.Settings.DefaultQuoteChar.ToString() },
                    txbSep       = { Text = Main.Settings.DefaultSeparator }
                };
                if (askUserDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                var csvSettings = askUserDialog.Settings;
                QueryWindowVisible(true, true);
                QueryWindow.StartParse(csvSettings);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Error: " + e.Message);
            }
        }
Beispiel #9
0
 /// <summary>
 /// Gets the specified unit.
 /// </summary>
 /// <param name="unit">The unit.</param>
 /// <param name="parseSettings">The parse settings.</param>
 /// <returns>
 /// An <see cref="IUnit" />.
 /// </returns>
 public static Result <IUnit, Error <ExpressionError> > GetUnitFrom(string unit, ParseSettings parseSettings)
 {
     EnsureInitialization();
     return(Instance.GetUnit(unit, parseSettings));
 }
Beispiel #10
0
    public static IesConfig Parse(string[] lines, ParseSettings setting)
    {
        if (lines == null)
        {
            throw new Exception("Empty input.");
        }

        if (lines.Length < 3)
        {
            throw new Exception("Invalid IES file lines.");
        }

        string formatInfo = lines[0];

        if (!setting.ignoreHeaderAndKeyword)
        {
            // check ies format header.
            if (string.IsNullOrEmpty(formatInfo) || !formatInfo.Contains(iesHeaderFlag))
            {
                throw new Exception("Invalid format header.");
            }
        }

        IesConfig result = new IesConfig(setting.ignoreHeaderAndKeyword ? "" : formatInfo);

        int tiltLineIndex = -1;

        for (int i = 0; i < lines.Length; ++i)
        {
            if (lines[i].Contains(tiltInfoFlag))
            {
                tiltLineIndex = i;
                break;
            }
        }

        if (tiltLineIndex == -1)
        {
            throw new Exception("Cannot find TILT information.");
        }

        // Parse Keyword:
        if (!setting.ignoreHeaderAndKeyword)
        {
            for (int i = 1; i < tiltLineIndex; ++i)
            {
                string keywordLine    = lines[i];
                int    leftSqrBrIndex = keywordLine.IndexOf('[');
                if (leftSqrBrIndex >= 0)
                {
                    int rightSqrBrIndex = keywordLine.IndexOf(']');
                    int keywordLength   = rightSqrBrIndex - leftSqrBrIndex - 1;
                    if (keywordLength > 0)
                    {
                        string keyword            = keywordLine.Substring(leftSqrBrIndex + 1, keywordLength);
                        string keywordValue       = "";
                        int    keywordValueLength = keywordLine.Length - rightSqrBrIndex - 1;
                        if (keywordValueLength > 0)
                        {
                            keywordValue = keywordLine.Substring(rightSqrBrIndex + 1, keywordValueLength).Trim();
                        }

                        result[keyword] = keywordValue;
                    }
                }
            }
        }

        // parse tilt:
        string tiltInfoLine = lines[tiltLineIndex];

        if (string.IsNullOrEmpty(tiltInfoLine))
        {
            throw new Exception("TILT infomation is invalid.");
        }

        string tiltTypeValue = "";

        try
        {
            tiltTypeValue = tiltInfoLine.Substring(tiltInfoLine.IndexOf('=') + 1).Trim();
        }
        catch (Exception)
        {
            tiltTypeValue = "";
        }

        if (tiltTypeValue == tiltInfoNoneStr)
        {
            result.SetTiltInfo(IesConfig.TiltInfoType.NONE);
        }
        else if (tiltTypeValue == tiltInfoIncludeStr)
        {
            // Inlcude tilt information will parse later
            result.SetTiltInfo(IesConfig.TiltInfoType.INCLUDE, null, null);
        }
        else if (tiltTypeValue.Length > 0)
        {
            result.SetTiltInfo(IesConfig.TiltInfoType.FILE, null, tiltTypeValue);
        }
        else
        {
            throw new Exception("TILT type is invalide.");
        }

        /// Parse digit values:
        List <string> digitValue = new List <string>();

        // separate strings with ' '
        int digitLine = tiltLineIndex + 1;

        if (digitLine >= lines.Length)
        {
            throw new Exception("Cannot find any digit information.");
        }

        char[] delimiterChars = { ' ', '\t' };
        for (int i = digitLine; i < lines.Length; ++i)
        {
            string line = lines[i];
            digitValue.AddRange(line.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries));
        }
        int totalValueCount = digitValue.Count;
        int valueIndex      = 0;

        // parse tilt data:
        if (result.tiltType == IesConfig.TiltInfoType.INCLUDE)
        {
            IesConfig.TiltInfo tiltInfo = new IesConfig.TiltInfo();

            if (valueIndex + 2 > totalValueCount)
            {
                throw new Exception("Invalid tilt data count.");
            }

            string lampToLuminaireGeometryStr = digitValue[valueIndex];
            valueIndex++;
            string numberOfTiltAnglesStr = digitValue[valueIndex];
            valueIndex++;

            // lampToLuminaireGeometry
            if (!int.TryParse(lampToLuminaireGeometryStr, out tiltInfo.lampToLuminaireGeometry))
            {
                throw new Exception("Parse lampToLuminaireGeometry error");
            }

            // numberOfTiltAngles
            int numberOfTiltAngles = -1;
            if (!int.TryParse(numberOfTiltAnglesStr, out numberOfTiltAngles))
            {
                throw new Exception("Parse numberOfTiltAngles error");
            }

            tiltInfo.SetNumberOfTiltAngles(numberOfTiltAngles);

            // there should be at least numberOfTiltAngles values for <angles>
            if (valueIndex + numberOfTiltAngles > totalValueCount)
            {
                throw new Exception("Invalid tilt angles data count.");
            }

            // following <angles> there should be at least numberOfTiltAngles values for <multiplying factors>
            if (valueIndex + numberOfTiltAngles + numberOfTiltAngles > totalValueCount)
            {
                throw new Exception("Invalid tilt multiplying factors data count.");
            }

            // parse angles:
            for (int i = 0; i < numberOfTiltAngles; ++i)
            {
                string angleStr = digitValue[valueIndex];
                valueIndex++;

                double angles = 0d;
                if (!double.TryParse(angleStr, out angles))
                {
                    throw new Exception("Parse tileAngle <" + angleStr + "> failed.");
                }
                tiltInfo.SetAngle(i, angles);
                // TODO: check range.
            }

            // parse multiplying factors:
            for (int i = 0; i < numberOfTiltAngles; ++i)
            {
                string factorStr = digitValue[valueIndex];
                valueIndex++;

                double factor = 0d;
                if (!double.TryParse(factorStr, out factor))
                {
                    throw new Exception("Parse multiplying factors <" + factorStr + "> failed.");
                }
                tiltInfo.SetMultiplyingFactor(i, factor);
            }

            result.SetTiltInfo(IesConfig.TiltInfoType.INCLUDE, tiltInfo);
        }

        /// parse values:
        // based on IESNA:LM-63-2002, there should be at least 13 numbers to create the ies file, witch are:

        /*
         * <number of lamps> <lumens per lamp> <candela multiplier>
         * <number of vertical angles> <number of horizontal angles>
         * <photometric type>
         * <units type>
         * <width> <length> <height>
         * <ballast factor> <future use> <input watts>
         * */
        int iesNumValueCount = 13;

        if (valueIndex + iesNumValueCount > totalValueCount)
        {
            throw new Exception("There should be at least 13 numbers.");
        }

        // TODO: value validation check

        // number of lamps:
        string valueStr = digitValue[valueIndex];

        valueIndex++;
        if (!int.TryParse(valueStr, out result.numberOfLamps))
        {
            throw new Exception("Invalid number of lamps value.");
        }

        // lumens per lamp:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!double.TryParse(valueStr, out result.lumenPerLamp))
        {
            throw new Exception("Invalid lumens per lamp value.");
        }

        // candela multiplier:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!double.TryParse(valueStr, out result.candelaMultiplier))
        {
            throw new Exception("Invalid candela multiplier value.");
        }

        // number of vertical angles:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!int.TryParse(valueStr, out result.numberOfVerticalAngles))
        {
            throw new Exception("Invalid number of vertical angles value.");
        }

        // number of horizontal angles:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!int.TryParse(valueStr, out result.numberOfHorizontalAngles))
        {
            throw new Exception("Invalid number of horizontal angles value.");
        }

        // photometric type:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!int.TryParse(valueStr, out result.photometricType))
        {
            throw new Exception("Invalid photometric type value.");
        }

        // units type:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!int.TryParse(valueStr, out result.unitsType))
        {
            throw new Exception("Invalid units type value.");
        }

        // width:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!double.TryParse(valueStr, out result.width))
        {
            throw new Exception("Invalid width value.");
        }

        // length:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!double.TryParse(valueStr, out result.length))
        {
            throw new Exception("Invalid length value.");
        }

        // height:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!double.TryParse(valueStr, out result.height))
        {
            throw new Exception("Invalid height value.");
        }

        // ballast factor:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!double.TryParse(valueStr, out result.ballastFactor))
        {
            throw new Exception("Invalid ballast factor value.");
        }

        // future use:
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!double.TryParse(valueStr, out result.futureUse))
        {
            throw new Exception("Invalid future use value.");
        }

        // input watts
        valueStr = digitValue[valueIndex];
        valueIndex++;
        if (!double.TryParse(valueStr, out result.inputWatts))
        {
            throw new Exception("Invalid input watts value.");
        }

        /// Parse Angle value and intensity value:
        // based on IESNA:LM-63-2002, angle and intensity data are stored as follow:

        /*
         * <vertical angles>
         * <horizontal angles>
         * <candela values for all vertical angles at 1st horizontal angle>
         * <candela values for all vertical angles as 2nd horizontal angle>
         * ...
         * <candela values for all vertical angles at last horizontal angle>
         * */

        int angleIntensityDataCount = result.numberOfVerticalAngles + result.numberOfHorizontalAngles
                                      + result.numberOfHorizontalAngles * result.numberOfVerticalAngles;

        if (valueIndex + angleIntensityDataCount > totalValueCount)
        {
            throw new Exception("Angle Intensity data count is invalid.");
        }

        // vertical angles:
        double[] verticalAngles = new double[result.numberOfVerticalAngles];
        for (int i = 0; i < result.numberOfVerticalAngles; ++i)
        {
            valueStr = digitValue[valueIndex];
            valueIndex++;
            double angle = 0d;
            if (!double.TryParse(valueStr, out angle))
            {
                throw new Exception("Invalid vertical angle data.");
            }
            verticalAngles[i] = angle;
        }

        // honrizontal angles:
        double[] horizontalAngles = new double[result.numberOfHorizontalAngles];
        for (int i = 0; i < result.numberOfHorizontalAngles; ++i)
        {
            valueStr = digitValue[valueIndex];
            valueIndex++;
            double angle = 0d;
            if (!double.TryParse(valueStr, out angle))
            {
                throw new Exception("Invalid horizontal angle data.");
            }
            horizontalAngles[i] = angle;
        }

        result.SetVerticalAngles(verticalAngles, false);
        result.SetHorizontalAngles(horizontalAngles, false);

        // raw intensity:
        List <double[]> rawIntensity = new List <double[]>();

        for (int h = 0; h < result.numberOfHorizontalAngles; ++h)
        {
            double[] verticalIntensity = new double[result.numberOfVerticalAngles];
            for (int v = 0; v < result.numberOfVerticalAngles; ++v)
            {
                valueStr = digitValue[valueIndex];
                valueIndex++;

                double intensity;
                if (!double.TryParse(valueStr, out intensity))
                {
                    throw new Exception("Parse intensity data error.");
                }

                verticalIntensity[v] = intensity;
            }
            rawIntensity.Add(verticalIntensity);
        }
        result.SetRawIntensityData(rawIntensity);

        return(result);
    }
        /// <summary>
        /// Gets the unit.
        /// </summary>
        /// <param name="unit">The unit as a string.</param>
        /// <param name="parseSettings">The parse settings.</param>
        /// <returns>
        /// An <see cref="IUnit" /> based on the specified <see cref="string" />.
        /// </returns>
        public Result <IUnit, Error <ExpressionError> > GetUnit(string unit, ParseSettings parseSettings)
        {
            var result = this.ParseExpression(unit, parseSettings);

            return(result.ConvertValue(this.GetUnit));
        }
        internal Result <Expression, Error <ExpressionError> > ParseExpression(string unit, ParseSettings parseSettings)
        {
            var analysisResult = this.lexicalAnalyzer.Analyze(unit, parseSettings.ThrowOnError);

            if (analysisResult)
            {
                return(this.expressionParser.Parse(analysisResult.Value, parseSettings));
            }

            return(Result.Error(Error.From(ExpressionError.LexicalAnalysisFailed, null, analysisResult.Error)));
        }
Beispiel #13
0
 private void ParseSettingsToolStripMenuItem_Click(object sender, EventArgs e)
 {
     ParseSettings.BringToFront();
 }