Example #1
0
        protected override void ReParseImpl()
        {
            var outputWindow = OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense);

            Stopwatch stopwatch = Stopwatch.StartNew();

            string        filename     = "<Unknown File>";
            ITextDocument textDocument = TextDocument;

            if (textDocument != null)
            {
                filename = textDocument.FilePath;
            }

            var snapshot = TextBuffer.CurrentSnapshot;
            var input    = new SnapshotCharStream(snapshot, new Span(0, snapshot.Length));
            var lexer    = new PhpLexer(input);

            lexer.TokenFactory = new SnapshotTokenFactory(snapshot, lexer);
            var tokens = new CommonTokenStream(lexer);
            var parser = new PhpParser(tokens);

            parser.BuildParseTree = true;

            List <ParseErrorEventArgs> errors = new List <ParseErrorEventArgs>();

            parser.AddErrorListener(new ErrorListener(filename, errors, outputWindow));
            var result = parser.compileUnit();

            NavigationTreesListener listener = new NavigationTreesListener();

            ParseTreeWalker.Default.Walk(listener, result);

            OnParseComplete(new PhpEditorNavigationParseResultEventArgs(snapshot, errors, stopwatch.Elapsed, tokens.GetTokens(), result, listener.NavigationTrees));
        }
 public bool Start()
 {
     if (Started)
     {
         return(false);
     }
     Timing = StopWatch.StartNew();
     return(true);
 }
Example #3
0
        protected override void ReParseImpl()
        {
            var outputWindow = OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense);

            Stopwatch stopwatch = Stopwatch.StartNew();

            var snapshot = TextBuffer.CurrentSnapshot;
            SnapshotCharStream         input  = new SnapshotCharStream(snapshot, new Span(0, snapshot.Length));
            AlloyLexer                 lexer  = new AlloyLexer(input);
            CommonTokenStream          tokens = new CommonTokenStream(lexer);
            AlloyParser                parser = new AlloyParser(tokens);
            List <ParseErrorEventArgs> errors = new List <ParseErrorEventArgs>();

            parser.ParseError += (sender, e) =>
            {
                errors.Add(e);

                string message = e.Message;

                ITextDocument document;
                if (TextBuffer.Properties.TryGetProperty(typeof(ITextDocument), out document) && document != null)
                {
                    string fileName = document.FilePath;
                    var    line     = snapshot.GetLineFromPosition(e.Span.Start);
                    message = string.Format("{0}({1},{2}): {3}", fileName, line.LineNumber + 1, e.Span.Start - line.Start.Position + 1, message);
                }

                if (message.Length > 100)
                {
                    message = message.Substring(0, 100) + " ...";
                }

                if (outputWindow != null)
                {
                    outputWindow.WriteLine(message);
                }

                if (errors.Count > 100)
                {
                    throw new OperationCanceledException();
                }
            };

            var result = parser.compilationUnit();

            OnParseComplete(new AntlrParseResultEventArgs(snapshot, errors, stopwatch.Elapsed, tokens.GetTokens(), result));
        }
Example #4
0
        protected override void ReParseImpl()
        {
            var outputWindow = OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense);

            Stopwatch stopwatch = Stopwatch.StartNew();

            var snapshot = TextBuffer.CurrentSnapshot;
            var input    = new SnapshotCharStream(snapshot, new Span(0, snapshot.Length));
            var lexer    = new AntlrErrorProvidingLexer(input);
            var tokens   = new AntlrParserTokenStream(lexer);
            var parser   = new AntlrErrorProvidingParser(tokens);

            lexer.Parser  = parser;
            tokens.Parser = parser;

            List <ParseErrorEventArgs> errors = new List <ParseErrorEventArgs>();

            parser.ParseError += (sender, e) =>
            {
                errors.Add(e);

                string message = e.Message;
                if (message.Length > 100)
                {
                    message = message.Substring(0, 100) + " ...";
                }

                if (outputWindow != null)
                {
                    outputWindow.WriteLine(message);
                }

                if (errors.Count > 100)
                {
                    throw new OperationCanceledException();
                }
            };

            AntlrTool.ToolPathRoot = typeof(AntlrTool).Assembly.Location;
            ErrorManager.SetErrorListener(new AntlrErrorProvidingParser.ErrorListener());
            Grammar g      = new Grammar();
            var     result = parser.grammar_(g);

            OnParseComplete(new AntlrParseResultEventArgs(snapshot, errors, stopwatch.Elapsed, tokens.GetTokens(), result));
        }
Example #5
0
    public IEnumerator generateBlocking()
    {
        var timer = Stopwatch.StartNew();

        InProgress = true;
        var allText = string.Empty;

        try
        {
            allText = File.ReadAllText(InputTextPath);
        }
        catch (System.Exception e)
        {
            Debug.LogError("Problem with reading the text file");
            Debug.LogError(e.ToString());
            InProgress = false;
            yield break;
        }
        Debug.Log("Read the file");

        var separated = allText.Trim().Split(SeparatorCharacters.ToArray(), StringSplitOptions.RemoveEmptyEntries);

        Debug.Log($"Text is split. {separated.Length} words detected." +
                  $"Max Length of word: {separated.Max(x => x.Length)}");

        wordTextures.ForEach(x => DestroyImmediate(x));
        wordTextures.Clear();

        texturesMetaData.Clear();

        var rand = new System.Random(RandomSeed);

        for (int i = 0; i < separated.Length; i++)
        {
            Label.text = separated[i];
            Label.font = Fonts[rand.Next(0, Fonts.Length)];
            wordTextures.Add(CopyToTexture());
            texturesMetaData.Add(new MetaData()
            {
                Word = Label.text, Font = Label.font.name, FontSize = Label.fontSize
            });

            Progress = (float)i / (float)separated.Length;
            if (i % 100 == 0)
            {
                yield return(null);
            }

            if (i > 19200)
            {
                break;
            }
        }

        Debug.Log("Textures Generated");

        string extension = null;

        switch (ImageFormat)
        {
        case ImageType.JPG:
            extension = "jpg";
            break;

        case ImageType.PNG:
            extension = "png";
            break;
        }

        if (SaveInSeparateImages)
        {
            for (int i = 0; i < separated.Length; i++)
            {
                byte[] bytes = null;
                switch (ImageFormat)
                {
                case ImageType.JPG:
                    bytes = wordTextures[i].EncodeToJPG();
                    break;

                case ImageType.PNG:
                    bytes = wordTextures[i].EncodeToPNG();
                    break;
                }

                string fileName = $"TextAtlas{i:000000000}.{extension}";
                File.WriteAllBytes(System.IO.Path.Combine(DestinationFolder, fileName), bytes);
                this.texturesMetaData[i].Rect     = new Rect(0, 0, wordTextures[i].width, wordTextures[i].height);
                this.texturesMetaData[i].FileName = fileName;
            }
        }
        else
        {
            var atlas = new Texture2D(8192, 8192, TextureFormat.RGBA32, false);
            Debug.Log("Packing textures");
            var packerTimer = Stopwatch.StartNew();
            rects = atlas.PackTextures(wordTextures.ToArray(), 2, 8192);

            Debug.Log($"Textures packed ({packerTimer.ElapsedMilliseconds}ms)");

            byte[] bytes = null;
            switch (ImageFormat)
            {
            case ImageType.JPG:
                bytes = atlas.EncodeToJPG();
                break;

            case ImageType.PNG:
                bytes = atlas.EncodeToPNG();
                break;
            }

            File.WriteAllBytes(System.IO.Path.Combine(DestinationFolder, $"TextAtlas.{extension}"), bytes);

            for (int i = 0; i < rects.Length; i++)
            {
                var temp = rects[i];
                this.texturesMetaData[i].Rect = new Rect((int)(temp.x * atlas.width),
                                                         (int)(temp.y * atlas.height),
                                                         (int)(temp.width * atlas.width),
                                                         (int)(temp.height * atlas.height));
                this.texturesMetaData[i].FileName = $"TextAtlas.{extension}";
            }
        }
        var json = JsonUtility.ToJson(new MetaDataList(texturesMetaData), true);

        File.WriteAllText(System.IO.Path.Combine(DestinationFolder, $"MetaData.json"), json);

        InProgress = false;
        timer.Stop();
        Debug.Log($"Time Elapsed {timer.ElapsedMilliseconds}ms");
    }
Example #6
0
        /// <inheritdoc />
        public async Task HandleNotificationAsync(MessageReceivedNotification notification, CancellationToken cancellationToken = default)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            if (!(notification.Message is IUserMessage userMessage) ||
                (userMessage.Author is null))
            {
                return;
            }

            if (!(userMessage.Author is IGuildUser author) ||
                (author.Guild is null) ||
                author.IsBot ||
                author.IsWebhook)
            {
                return;
            }

            var argPos = 0;

            if (!userMessage.HasCharPrefix('!', ref argPos) && !userMessage.HasMentionPrefix(DiscordClient.CurrentUser, ref argPos))
            {
                return;
            }

            if (userMessage.Content.Length <= 1)
            {
                return;
            }

            var commandContext = new CommandContext(DiscordClient, userMessage);

            await AuthorizationService.OnAuthenticatedAsync(author);

            IResult commandResult = null;
            var     commandTimer  = Stopwatch.StartNew();

            try
            {
                commandResult = await CommandService.ExecuteAsync(commandContext, argPos, ServiceProvider);
            }
            finally
            {
                commandTimer.Stop();
                var duration = commandTimer.ElapsedMilliseconds;

                if (!(_stats is null) && (commandResult.IsSuccess || !string.Equals(commandResult.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase)))
                {
                    var commandInfo = CommandService.Search(commandContext, argPos).Commands.FirstOrDefault();
                    var name        = commandInfo.Command?.Name.ToLowerInvariant();

                    _stats?.Timer("command_duration_ms", duration,
                                  tags: new[] { $"guild:{commandContext.Guild.Name}", $"success:{commandResult.IsSuccess}", $"command:{name}" });
                }
            }

            if (!commandResult.IsSuccess)
            {
                var error = $"{commandResult.Error}: {commandResult.ErrorReason}";

                if (string.Equals(commandResult.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase))
                {
                    Log.Error(error);
                }
                else
                {
                    Log.Warning(error);
                }

                if (commandResult.Error == CommandError.Exception)
                {
                    await commandContext.Channel.SendMessageAsync($"Error: {FormatUtilities.SanitizeEveryone(commandResult.ErrorReason)}");
                }
                else
                {
                    await CommandErrorHandler.AssociateError(userMessage, error);
                }
            }

            stopwatch.Stop();
            Log.Information($"Command took {stopwatch.ElapsedMilliseconds}ms to process: {commandContext.Message}");
        }
Example #7
0
    void DDD()
    {
        Stopwatch time = Stopwatch.StartNew();

        List <int> list = new List <int>(10);

        for (int i = 0; i < ents; i++)
        {
            list.Add(i);
        }

        for (int j = 0; j < 10000; j++)
        {
            for (int i = 0; i < list.Count; i++)
            {
                list.Contains(i);
            }
        }

        Debug.Log("Contains on " + time.ElapsedMilliseconds);


        EntityBase Ent = null;


        int k = 0;

        while (Ent == null)
        {
            Ent = EntityBase.GetEntity(k++);
        }

        int entity = Ent.entity;

        time = Stopwatch.StartNew();

        for (int j = 0; j < 10000; j++)
        {
            for (int i = 0; i < comps; i++)
            {
                Storage.ContainsComponent <CompTest1>(entity);
            }
        }

        Debug.Log("ContainsComponent on " + time.ElapsedMilliseconds);



        time = Stopwatch.StartNew();

        for (int j = 0; j < 10000; j++)
        {
            if (ents * ents / comps < 520)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    list.Contains(i);
                }
            }
            else
            {
                for (int i = 0; i < comps; i++)
                {
                    Storage.ContainsComponent <CompTest1>(entity);
                }
            }
        }
        Debug.Log("super on " + time.ElapsedMilliseconds);
    }
Example #8
0
    private void PerformRandomWalk(Random random, GenerationConfig config)
    {
        var sw            = Stopwatch.StartNew();
        int mainDirection = random.Next(4);

        int[] baseWeights = new int[4];
        int[] altWeights  = new int[4];
        for (int i = 0; i < 4; i++)
        {
            int value;
            if (i == mainDirection)
            {
                value = config.increasedWeight;
            }
            else
            {
                value = config.baseWeight;
            }
            baseWeights[i] = value;
            altWeights[i]  = value;
        }
        baseWeights[(mainDirection + 5) % 4] = config.increasedWeight;
        altWeights[(mainDirection + 3) % 4]  = config.increasedWeight;

        var walkers = new List <Walker>()
        {
            new Walker(Vector2Int.zero, random.PickFromParams(baseWeights, altWeights))
        };

        map.Clear();
        map.SetTile(Vector2Int.zero, TileType.Ground);

        while (map.TileCount + walkers.Count <= config.cellsLimit)
        {
            for (int i = walkers.Count - 1; i >= 0; i--)
            {
                Walker walker = walkers[i];
                walker.MakeStep(random, map);

                if (walker.Steps == config.stepsToBranch)
                {
                    if (i == 0)
                    {
                        walker.ResetStepCounter();
                        walker.Weights = random.PickFromParams(baseWeights, altWeights);

                        if (random.NextDouble() < config.branchChance)
                        {
                            var weights = walker.Weights == baseWeights ? altWeights : baseWeights;
                            walkers.Add(new Walker(walker.Position, weights));
                        }
                    }
                    else
                    {
                        walkers.RemoveAt(i);
                    }
                }
            }
        }
        sw.Stop();
        Debug.Log($"Random walk completed in {sw.ElapsedMilliseconds} ms, {map.TileCount} tiles placed.");
    }
Example #9
0
        private List <LabelInfo> FindLabelsInScope(SnapshotPoint triggerPoint)
        {
            List <LabelInfo> labels = new List <LabelInfo>();

            /* use the experimental model to locate and process the expression */
            Stopwatch stopwatch = Stopwatch.StartNew();

            // lex the entire document
            var currentSnapshot = triggerPoint.Snapshot;
            var input           = new SnapshotCharStream(currentSnapshot, new Span(0, currentSnapshot.Length));
            var lexer           = new ANTLRLexer(input);
            var tokens          = new CommonTokenStream(lexer);

            tokens.Fill();

            // locate the last token before the trigger point
            while (true)
            {
                IToken nextToken = tokens.LT(1);
                if (nextToken.Type == CharStreamConstants.EndOfFile)
                {
                    break;
                }

                if (nextToken.StartIndex > triggerPoint.Position)
                {
                    break;
                }

                tokens.Consume();
            }

            bool   inAction     = false;
            IToken triggerToken = tokens.LT(-1);

            switch (triggerToken.Type)
            {
            case ANTLRLexer.RULE_REF:
            case ANTLRLexer.TOKEN_REF:
            case ANTLRLexer.DOLLAR:
                break;

            case ANTLRLexer.ACTION:
            case ANTLRLexer.FORCED_ACTION:
            case ANTLRLexer.SEMPRED:
            case ANTLRLexer.ARG_ACTION:
                inAction = true;
                break;

            default:
                return(labels);
            }

            NetworkInterpreter interpreter = CreateNetworkInterpreter(tokens);

            while (interpreter.TryStepBackward())
            {
                if (interpreter.Contexts.Count == 0 || interpreter.Contexts.Count > 4000)
                {
                    break;
                }

                if (interpreter.Contexts.All(context => context.BoundedStart))
                {
                    break;
                }
            }

            if (interpreter.Failed)
            {
                interpreter.Contexts.Clear();
            }

            interpreter.CombineBoundedStartContexts();

            HashSet <IToken> labelTokens = new HashSet <IToken>(TokenIndexEqualityComparer.Default);

            foreach (var context in interpreter.Contexts)
            {
                var tokenTransitions = context.Transitions.Where(i => i.TokenIndex != null).ToList();
                for (int i = 1; i < tokenTransitions.Count - 1; i++)
                {
                    if (tokenTransitions[i].Symbol != ANTLRLexer.TOKEN_REF && tokenTransitions[i].Symbol != ANTLRLexer.RULE_REF)
                    {
                        continue;
                    }

                    // we add explicit labels, plus implicit labels if we're in an action
                    if (tokenTransitions[i + 1].Symbol == ANTLRLexer.ASSIGN || tokenTransitions[i + 1].Symbol == ANTLRLexer.PLUS_ASSIGN)
                    {
                        RuleBinding rule = interpreter.Network.StateRules[tokenTransitions[i + 1].Transition.SourceState.Id];
                        if (rule.Name == AntlrAtnBuilder.RuleNames.TreeRoot || rule.Name == AntlrAtnBuilder.RuleNames.ElementNoOptionSpec)
                        {
                            labelTokens.Add(tokenTransitions[i].Token);
                        }
                    }
                    else if (inAction && tokenTransitions[i - 1].Symbol != ANTLRLexer.ASSIGN && tokenTransitions[i - 1].Symbol != ANTLRLexer.PLUS_ASSIGN)
                    {
                        RuleBinding rule = interpreter.Network.StateRules[tokenTransitions[i].Transition.SourceState.Id];
                        if (rule.Name == AntlrAtnBuilder.RuleNames.Terminal || rule.Name == AntlrAtnBuilder.RuleNames.NotTerminal || rule.Name == AntlrAtnBuilder.RuleNames.RuleRef)
                        {
                            labelTokens.Add(tokenTransitions[i].Token);
                        }
                    }
                }
            }

            foreach (var token in labelTokens)
            {
                labels.Add(new LabelInfo(token.Text, "(label) " + token.Text, new SnapshotSpan(triggerPoint.Snapshot, Span.FromBounds(token.StartIndex, token.StopIndex + 1)), StandardGlyphGroup.GlyphGroupField, Enumerable.Empty <LabelInfo>()));
            }

            /* add scopes */
            if (inAction)
            {
                /* add global scopes */
                IList <IToken> tokensList = tokens.GetTokens();
                for (int i = 0; i < tokensList.Count - 1; i++)
                {
                    var token = tokensList[i];

                    /* all global scopes appear before the first rule. before the first rule, the only place a ':' can appear is
                     * in the form '::' for things like @lexer::namespace{}
                     */
                    if (token.Type == ANTLRLexer.COLON && tokensList[i + 1].Type == ANTLRLexer.COLON)
                    {
                        break;
                    }

                    if (token.Type == ANTLRLexer.SCOPE)
                    {
                        var nextToken = tokensList.Skip(i + 1).FirstOrDefault(t => t.Channel == TokenChannels.Default);
                        if (nextToken != null && (nextToken.Type == ANTLRLexer.RULE_REF || nextToken.Type == ANTLRLexer.TOKEN_REF))
                        {
                            // TODO: parse scope members
                            IToken actionToken = tokensList.Skip(nextToken.TokenIndex + 1).FirstOrDefault(t => t.Channel == TokenChannels.Default);
                            IEnumerable <LabelInfo> members = Enumerable.Empty <LabelInfo>();

                            if (actionToken != null && actionToken.Type == ANTLRLexer.ACTION)
                            {
                                IEnumerable <IToken> scopeMembers = ExtractScopeAttributes(nextToken);
                                members = scopeMembers.Select(member =>
                                {
                                    string name              = member.Text;
                                    SnapshotSpan definition  = new SnapshotSpan(triggerPoint.Snapshot, Span.FromBounds(member.StartIndex, member.StopIndex + 1));
                                    StandardGlyphGroup glyph = StandardGlyphGroup.GlyphGroupField;
                                    IEnumerable <LabelInfo> nestedMembers = Enumerable.Empty <LabelInfo>();
                                    return(new LabelInfo(name, string.Empty, definition, glyph, nestedMembers));
                                });
                            }

                            labels.Add(new LabelInfo(nextToken.Text, "(global scope) " + nextToken.Text, new SnapshotSpan(triggerPoint.Snapshot, Span.FromBounds(nextToken.StartIndex, nextToken.StopIndex + 1)), StandardGlyphGroup.GlyphGroupNamespace, members));
                        }
                    }
                }

                /* add rule scopes */
                // todo
            }

            /* add arguments and return values */
            if (inAction)
            {
                HashSet <IToken> argumentTokens = new HashSet <IToken>(TokenIndexEqualityComparer.Default);
                foreach (var context in interpreter.Contexts)
                {
                    var tokenTransitions = context.Transitions.Where(i => i.TokenIndex != null).ToList();
                    for (int i = 1; i < tokenTransitions.Count; i++)
                    {
                        if (tokenTransitions[i].Symbol == ANTLRLexer.RETURNS || tokenTransitions[i].Symbol == ANTLRLexer.COLON)
                        {
                            break;
                        }

                        if (tokenTransitions[i].Symbol == ANTLRLexer.ARG_ACTION)
                        {
                            argumentTokens.Add(tokenTransitions[i].Token);
                        }
                    }
                }

                foreach (var token in argumentTokens)
                {
                    IEnumerable <IToken> arguments = ExtractArguments(token);
                    foreach (var argument in arguments)
                    {
                        labels.Add(new LabelInfo(argument.Text, "(parameter) " + argument.Text, new SnapshotSpan(triggerPoint.Snapshot, Span.FromBounds(argument.StartIndex, argument.StopIndex + 1)), StandardGlyphGroup.GlyphGroupVariable, Enumerable.Empty <LabelInfo>()));
                    }
                }
            }

            /* add return values */
            if (inAction)
            {
                HashSet <IToken> returnTokens = new HashSet <IToken>(TokenIndexEqualityComparer.Default);
                foreach (var context in interpreter.Contexts)
                {
                    var tokenTransitions = context.Transitions.Where(i => i.TokenIndex != null).ToList();
                    for (int i = 1; i < tokenTransitions.Count - 1; i++)
                    {
                        if (tokenTransitions[i].Symbol == ANTLRLexer.COLON)
                        {
                            break;
                        }

                        if (tokenTransitions[i].Symbol == ANTLRLexer.RETURNS)
                        {
                            if (tokenTransitions[i + 1].Symbol == ANTLRLexer.ARG_ACTION)
                            {
                                returnTokens.Add(tokenTransitions[i + 1].Token);
                            }

                            break;
                        }
                    }
                }

                foreach (var token in returnTokens)
                {
                    IEnumerable <IToken> returnValues = ExtractArguments(token);
                    foreach (var returnValue in returnValues)
                    {
                        labels.Add(new LabelInfo(returnValue.Text, "(return value) " + returnValue.Text, new SnapshotSpan(triggerPoint.Snapshot, Span.FromBounds(returnValue.StartIndex, returnValue.StopIndex + 1)), StandardGlyphGroup.GlyphGroupVariable, Enumerable.Empty <LabelInfo>()));
                    }
                }
            }

            /* add intrinsic labels ($start, $type, $text, $enclosingRuleName) */
            IToken           ruleNameToken           = null;
            HashSet <IToken> enclosingRuleNameTokens = new HashSet <IToken>(TokenIndexEqualityComparer.Default);

            foreach (var context in interpreter.Contexts)
            {
                var tokenTransitions = context.Transitions.Where(i => i.Symbol == ANTLRLexer.RULE_REF || i.Symbol == ANTLRLexer.TOKEN_REF).ToList();
                if (!tokenTransitions.Any())
                {
                    continue;
                }

                ruleNameToken = tokenTransitions.First().Token;
                if (ruleNameToken != null)
                {
                    enclosingRuleNameTokens.Add(ruleNameToken);
                }
            }

            foreach (var token in enclosingRuleNameTokens)
            {
                // TODO: add members
                labels.Add(new LabelInfo(token.Text, "(enclosing rule) " + token.Text, new SnapshotSpan(triggerPoint.Snapshot, Span.FromBounds(token.StartIndex, token.StopIndex + 1)), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
            }

            GrammarType grammarType = GrammarType.None;

            int mark = tokens.Mark();

            try
            {
                tokens.Seek(0);
                bool hasGrammarType = false;
                while (!hasGrammarType)
                {
                    int la1 = tokens.LA(1);
                    switch (la1)
                    {
                    case ANTLRLexer.GRAMMAR:
                        IToken previous = tokens.LT(-1);
                        if (previous == null)
                        {
                            grammarType = GrammarType.Combined;
                        }
                        else if (previous.Type == ANTLRLexer.LEXER)
                        {
                            grammarType = GrammarType.Lexer;
                        }
                        else if (previous.Type == ANTLRLexer.PARSER)
                        {
                            grammarType = GrammarType.Parser;
                        }
                        else if (previous.Type == ANTLRLexer.TREE)
                        {
                            grammarType = GrammarType.TreeParser;
                        }
                        else
                        {
                            grammarType = GrammarType.None;
                        }

                        hasGrammarType = true;
                        break;

                    case CharStreamConstants.EndOfFile:
                        hasGrammarType = true;
                        break;

                    default:
                        break;
                    }

                    tokens.Consume();
                }
            }
            finally
            {
                tokens.Rewind(mark);
            }

            if (inAction)
            {
                switch (grammarType)
                {
                case GrammarType.Combined:
                    if (ruleNameToken == null)
                    {
                        goto default;
                    }
                    if (ruleNameToken.Type == ANTLRLexer.RULE_REF)
                    {
                        goto case GrammarType.Parser;
                    }
                    else
                    {
                        goto case GrammarType.Lexer;
                    }

                case GrammarType.Lexer:
                    labels.Add(new LabelInfo("text", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("type", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("line", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("index", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("pos", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("channel", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("start", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("stop", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("int", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    break;

                case GrammarType.Parser:
                    labels.Add(new LabelInfo("text", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("start", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("stop", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("tree", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("st", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    break;

                case GrammarType.TreeParser:
                    labels.Add(new LabelInfo("text", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("start", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("tree", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("st", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    break;

                default:
                    // if we're unsure about the grammar type, include all the possible options to make sure we're covered
                    labels.Add(new LabelInfo("text", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("type", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("line", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("index", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("pos", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("channel", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("start", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("stop", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("int", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("tree", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    labels.Add(new LabelInfo("st", string.Empty, new SnapshotSpan(), StandardGlyphGroup.GlyphGroupIntrinsic, Enumerable.Empty <LabelInfo>()));
                    break;
                }
            }

            return(labels);
        }
 private TimedRect(Rect rect)
 {
     _rect      = rect;
     _stopwatch = Stopwatch.StartNew();
 }
Example #11
0
    void PerformanceTest()
    {
        long test_time = 0;

        group1 = Group.Create(new ComponentsList <CompTest1, CompTest2, CompTest3, CompTest4, CompTest5, CompTest6>());
        group2 = Group.Create(new ComponentsList <CompTest1, CompTest2>(), new ComponentsList <CompTest3, CompTest4, CompTest5, CompTest6>());

        groups = new List <Group> {
            group1, group2
        };
        gameObjects = new List <GameObject>();


        for (int i = 0; i < 10; i++)
        {
            gameObjects.Add(new GameObject());
        }

        Debug.LogWarning("начат тест производительности фреймворка");
        //Stopwatch time = Stopwatch.StartNew();

        foreach (GameObject obj in gameObjects)
        {
            obj.AddComponent <TestEntity3>();
        }

        int dif = 100;

        test_time += TestContains(dif);
        test_time += TestIEnumerator(dif);
        test_time += TestAddRemoveComponent(dif);
        test_time += TestAddRemoveGroup(dif);

        for (int i = 0; i < gameObjects.Count; i++)
        {
            Destroy(gameObjects[i]);
        }

        Debug.Log("Тест закончен за " + test_time + " ms");

        long TestContains(int difficult)
        {
            Stopwatch time = Stopwatch.StartNew();

            for (int i = 0; i < difficult; i++)
            {
                foreach (Group group in groups)
                {
                    foreach (int ent in group)
                    {
                        group.Contains(ent);
                    }
                }
            }

            long total_time = time.ElapsedMilliseconds;

            Debug.Log("Contains test complete for " + total_time + " ms");

            return(total_time);
        }

        long TestIEnumerator(int difficult)
        {
            Stopwatch time = Stopwatch.StartNew();

            for (int i = 0; i < difficult; i++)
            {
                foreach (Group group in groups)
                {
                    foreach (int ent in group)
                    {
                        ;
                    }
                }
            }

            long total_time = time.ElapsedMilliseconds;

            Debug.Log("IEnumerator test complete for " + total_time + " ms");

            return(total_time);
        }

        long TestAddRemoveComponent(int difficult)
        {
            GameObject testObj = new GameObject();

            Stopwatch time = Stopwatch.StartNew();

            testObj.AddComponent <TestEntity4>();
            EntityBase entityBase = testObj.GetComponent <EntityBase>();

            for (int i = 0; i < difficult; i++)
            {
                entityBase.RemoveCmp <CompTest1>();
                entityBase.AddCmp <CompTest1>();
            }

            long total_time = time.ElapsedMilliseconds;

            Debug.Log("AddRemoveComponent test complete for " + total_time + " ms");

            Destroy(testObj);

            return(total_time);
        }

        long TestAddRemoveGroup(int difficult)
        {
            GameObject testObj = new GameObject();

            Stopwatch time = Stopwatch.StartNew();

            testObj.AddComponent <TestEntity4>();
            EntityBase entityBase = testObj.GetComponent <EntityBase>();

            for (int i = 0; i < difficult; i++)
            {
                entityBase.RemoveCmp <CompTest3>();
                entityBase.RemoveCmp <CompTest4>();
                entityBase.RemoveCmp <CompTest5>();
                entityBase.RemoveCmp <CompTest6>();

                entityBase.AddCmp <CompTest3>();
                entityBase.AddCmp <CompTest4>();
                entityBase.AddCmp <CompTest5>();
                entityBase.AddCmp <CompTest6>();
            }

            long total_time = time.ElapsedMilliseconds;

            Debug.Log("AddRemoveGroup test complete for " + total_time + " ms");

            Destroy(testObj);

            return(total_time);
        }
    }
Example #12
0
    void FullTest()
    {
        Debug.LogWarning("Начат тест фреймворка");
        Stopwatch time        = Stopwatch.StartNew();
        bool      successfull = true;

        group1 = Group.Create(new ComponentsList <CompTest1, CompTest2>());
        group2 = Group.Create(new ComponentsList <CompTest1, CompTest2>());
        group3 = Group.Create(new ComponentsList <CompTest1>(), new ComponentsList <CompTest1>());
        group4 = Group.Create(new ComponentsList <CompTest1>(), new ComponentsList <CompTest2>());
        group5 = Group.Create(new ComponentsList <CompTest1>());
        group6 = Group.Create(new ComponentsList <CompTest7>());
        group8 = Group.Create(new ComponentsList(), new ComponentsList <CompTest1>());

        gameObjects = new List <GameObject>(); // лист всех GameObject задействованных в тесте
        groups      = new List <Group>()
        {
            group1, group2, group3, group4, group5, group6
        };                                                                             // лист всех Group задействованных в тесте


        if (group1.entities_count + group2.entities_count + group3.entities_count + group4.entities_count + group5.entities_count != 0)
        {
            SendErrorMessage("При начале теста в группах находятся сущности");
        }

        #region correct add component test

        GameObject ent1 = new GameObject();
        gameObjects.Add(ent1);
        ent1.AddComponent <TestEntity1>();
        if (ent1.GetComponent <TestEntity1>().GetEntityComponent <CompTest1>() == null)
        {
            SendErrorMessage("Компонент не был добавлен");
        }
        if (ent1.GetComponent <TestEntity1>().GetEntityComponent <CompTest2>() != null)
        {
            SendErrorMessage("Ошибочное добавление компонента");
        }
        if (ent1.GetComponent <TestEntity1>().GetEntityComponent <CompTest3>() != null)
        {
            SendErrorMessage("Ошибочное добавление компонента");
        }
        if (ent1.GetComponent <TestEntity1>().GetEntityComponent <CompTest4>() != null)
        {
            SendErrorMessage("Ошибочное добавление компонента");
        }

        GameObject ent2 = new GameObject();
        gameObjects.Add(ent2);
        ent2.AddComponent <TestEntity2>();
        if (ent2.GetComponent <TestEntity2>().GetEntityComponent <CompTest1>() == null)
        {
            SendErrorMessage("Компонент не был добавлен");
        }
        if (ent2.GetComponent <TestEntity2>().GetEntityComponent <CompTest2>() == null)
        {
            SendErrorMessage("Компонент не был добавлен");
        }
        if (ent2.GetComponent <TestEntity2>().GetEntityComponent <CompTest3>() == null)
        {
            SendErrorMessage("Компонент не был добавлен");
        }
        if (ent2.GetComponent <TestEntity2>().GetEntityComponent <CompTest4>() == null)
        {
            SendErrorMessage("Компонент не был добавлен");
        }

        GameObject ent3 = new GameObject();
        gameObjects.Add(ent3);
        ent3.AddComponent <TestEntity3>();
        if (ent3.GetComponent <TestEntity3>().GetEntityComponent <CompTest1>() == null)
        {
            SendErrorMessage("Компонент не был добавлен");
        }
        if (ent3.GetComponent <TestEntity3>().GetEntityComponent <CompTest2>() == null)
        {
            SendErrorMessage("Компонент не был добавлен");
        }
        if (ent3.GetComponent <TestEntity3>().GetEntityComponent <CompTest3>() == null)
        {
            SendErrorMessage("Компонент не был добавлен");
        }
        if (ent3.GetComponent <TestEntity3>().GetEntityComponent <CompTest4>() == null)
        {
            SendErrorMessage("Компонент не был добавлен");
        }

        #endregion correct add component test

        #region correct num of entityes in group test

        if (group1.entities_count != 2)
        {
            SendErrorMessage("Неправильное количество сущностей в группе.");
        }
        if (group2.entities_count != 2)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }
        if (group3.entities_count != 0)
        {
            SendErrorMessage("Игнорирование исключений");
        }
        if (group4.entities_count != 1)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }
        if (group5.entities_count != 3)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }

        if (ent1.GetComponent <TestEntity1>().GetAllComponents().Count != 1)
        {
            SendErrorMessage("Добавление повторяющихся компонентов");
        }

        if (ent2.GetComponent <TestEntity2>().GetAllComponents().Count != 4)
        {
            SendErrorMessage("Неправильное добавление компонентов");
        }

        ent2.GetComponent <EntityBase>().RemoveCmp <CompTest2>();
        if (group5.entities_count != 3)
        {
            SendErrorMessage("Некорректное поведение групп при удалении компонента");
        }
        ent2.GetComponent <EntityBase>().AddCmp <CompTest2>();


        ent1.GetComponent <EntityBase>().AddCmp <CompTest2>();
        if (group1.entities_count != 3)
        {
            SendErrorMessage("Некорректное поведение групп при добавлении компонента");
        }
        ent1.GetComponent <EntityBase>().RemoveCmp <CompTest2>();

        GameObject ent4 = new GameObject();
        gameObjects.Add(ent4);
        ent4.AddComponent <TestEntity1>();

        if (group1.entities_count != 2)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }
        if (group2.entities_count != 2)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }
        if (group3.entities_count != 0)
        {
            SendErrorMessage("Игнорирование исключений");
        }
        if (group4.entities_count != 2)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }
        if (group5.entities_count != 4)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }

        ent1.GetComponent <TestEntity1>().RemoveCmp(typeof(CompTest1));
        if (ent1.GetComponent <TestEntity1>().GetEntityComponent <CompTest1>() != null)
        {
            SendErrorMessage("Некорректное удаление компонента");
        }

        if (group1.entities_count != 2)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }
        if (group2.entities_count != 2)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }
        if (group3.entities_count != 0)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }
        if (group4.entities_count != 1)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }
        if (group5.entities_count != 3)
        {
            SendErrorMessage("Неправильное количество сущностей в группе");
        }

        #endregion correct num of entityes in group test

        #region Pooling test
        // пока что отключен

        /*
         * ent1.GetComponent<EntityBase>().Add<PoolComponent>();
         * GameObject ent11 = Instantiate(ent1);
         *
         * ent11.GetComponent<EntityBase>().GetEntityComponent<CompTest1>().ammo1 = 10;
         * ent11.GetComponent<EntityBase>().GetEntityComponent<CompTest1>().health1 = 10;
         * PoolManager.DestroyS(ent11);
         * ent11 = PoolManager.InstantiateS(ent1);
         * gameObjects.Add(ent11);
         *
         * if (ent11.GetComponent<EntityBase>().GetEntityComponent<CompTest1>().health1 == 10 || ent11.GetComponent<EntityBase>().GetEntityComponent<CompTest1>().ammo1 == 10)
         *  SendErrorMessage("Компоненты не возвращаються в исходное состояние");
         */
        #endregion Pooling test

        #region Enable/Disable Test

        if (group6.entities_count != 0)
        {
            SendErrorMessage("Некорректное поведение группы");
        }

        int start_count = group8.entities_count;

        GameObject ent7 = new GameObject();
        gameObjects.Add(ent7);
        ent7.AddComponent <TestEntity7>();

        //Debug.Log("group No" + group8.GetHashCode() % 1631);

        if (group8.entities_count != start_count + 1)
        {
            SendErrorMessage("Некорректное поведение группы при пустом листе компонентов ");
        }
        group8.Delete(); // должна быть здесь

        if (group6.entities_count != 1)
        {
            SendErrorMessage("Некорректное поведение группы");
        }

        ent7.SetActive(false);

        if (group6.entities_count != 0)
        {
            SendErrorMessage("Некорректное поведение при деактивации объекта");
        }

        if (Storage.GetComponent <CompTest7>(ent7.GetComponent <EntityBase>().entity) != null)
        {
            SendErrorMessage("Некорректное поведение при деактивации объекта");
        }

        ent7.SetActive(true);

        if (Storage.GetComponent <CompTest7>(ent7.GetComponent <EntityBase>().entity) == null)
        {
            SendErrorMessage("Некорректное поведение при повторной активации объекта");
        }

        #endregion Enable/Disable Test

        #region CreateGroupInRuntime

        Group group7 = Group.Create(new ComponentsList <CompTest1, CompTest2, CompTest3, CompTest4>());
        groups.Add(group7);
        if (group7.entities_count == 0)
        {
            SendErrorMessage("Ошибки при создании группы в рантайме");
        }

        #endregion CreateGroupInRuntime

        #region DeleteGameObjects

        for (int i = 0; i < gameObjects.Count; i++)
        {
            Destroy(gameObjects[i]);
        }



        #endregion DeleteGameObjects

        #region Others

        int count = 0;
        for (int i = 0; i < groups.Count; i++)
        {
            count += groups[i].entities_count;
        }

        if (count != 0)
        {
            string mes = "";
            for (int i = 0; i < groups.Count; i++)
            {
                mes += groups[i].entities_count;
            }

            SendErrorMessage("при окончании теста в группах находятся сущности " + mes);
        }

        #endregion Others

        #region DeleteGroups

        for (int i = 0; i < groups.Count; i++)
        {
            groups[i].Delete();
        }

        #endregion DeleteGroups

        if (successfull)
        {
            Debug.Log("тест закончен успешно за " + time.ElapsedMilliseconds + " ms");
            PerformanceTest();
        }
        else
        {
            Debug.LogError("тест закончен с ошибками за " + time.ElapsedMilliseconds + " ms");
        }

        void SendErrorMessage(string message)
        {
            successfull = false;
            Debug.LogError(message);
        }
    }
Example #13
0
    private void Start()
    {
        // Dialog played when adventure is finished.
        string finishedDialog = "The game is now completed. All the trials of friendship and endurance are now over,\nand the team faces the age-old question.\nWHAT DO WE DO NOW? (hint: press Enter)";

        // Responses sent upon invalid answer.
        string[] wrongAnswerDialogs = new string[]
        {
            "Wrong answer!",
            "Try that again, please!"
        };

        // Adventure nodes.
        List <TextNode> nodes = new List <TextNode>()
        {
            new TextNode(
                "A group of four engineer students, Pidgin, Siquel, Bab and Eeneku have arrived at the game jam site in Kajaani.\nA mighty task lies ahead of them, for they must be able to complete a video game in mere 48 hours!\nAfter a while of planning, the group gets to work on their game. Hours pass, and the team is making good progress.\nSoon however, a wild bug appears in the code!\nThe error is not critical, but it could hamper their progress later.\nWhat should the team do?\n\n- solve\n- ignore\n",
                new string[] { "The engineers decide that their time is too important to waste on something so small, and ignore the problem.\n", "The clever engineers realise how this small issue might bite their asses later, and they decide to spend a few hours working on the problem.\n" },
                AdventureBuilder.CreateAnswers()
                .AddAnswer("ignore", 1)
                .AddAnswer("solve", 2)),

            new TextNode(
                "Several hours later everyone on the team is happily coding away, when suddenly all the computers crash simultaneously!\nThe poor engineers are shocked. They wonder if all their hard earned progress is now lost.\nThe situation looks dire, what should the team do?\n\n- give up\n- try to save data\n",
                new string[] { "Their morale has been crushed, and the team decides to give up on the game jam. However, some of the members disagree on the matter.\n", "Even though it seems hopeless, Siquel proves himself as the hero, and restores all of their data from the hard drives.\n" },
                AdventureBuilder.CreateAnswers()
                .AddAnswer("give up", 3)
                .AddAnswer("try to save data", 4)),

            new TextNode(
                "The bug is crushed and development of the game is going smoothly. The team is sure that their game will absolutely be game of the year material.\nIt's late at night, and the classroom is getting quiet. One of the engineers, Siquel, decides to go get a cup of water.\nOn the way back however, he trips on a bag and the water splashes all over a nearby computer!\nThe computer short circuits, and soon smoke is filling the classroom!\nA fire alarm is activated, and everyone is racing to evacuate the building.\nWill the team risk losing the data, or risk themselves trying to save it from destruction?\n\n- try to save data\n- get out safely\n",
                new string[] { "The data is too important to lose, and Pidgin heroically puts out the flames with a fire extinguisher.\n", "The engineers decide that since their life is more important than a simple jam game, it's better to just escape from the potential danger while they can.\n " },
                AdventureBuilder.CreateAnswers()
                .AddAnswer("try to save data", 5)
                .AddAnswer("get out safely", 3)),

            new TextNode(
                "A while later the team is sitting in the lounge, trying to figure out how to continue their project.\nAfter the data was lost, some arguments started to rise between the members. Especially Pidgin and Siquel.\nThis argument soon grew into loud bickering and name-calling, and the others had to step in before things got out of hand. It's obvious that the team needs a new direction, but who will be the one to win the argument?\n\n- Siquel\n- Pidgin\n",
                new string[] { "Siquel wins the argument, and the team gets back to work on their game.\n", "Pidgin wins the argument, and the team gets back to work on their game.\n" },
                AdventureBuilder.CreateAnswers()
                .AddAnswer("Siquel", 4)
                .AddAnswer("Pidgin", 5)),

            new TextNode(
                "With Siquel's ideas the team finally gets back on track with their game.\nEverything is working great, and the team is happy to get along with each other again.\nSoon, the final lines of code are written, and the team is happy with their achievement.\n\n- finish game",
                new string[] { "" },
                AdventureBuilder.CreateAnswers()
                .AddAnswer("finish game", 10)),

            new TextNode(
                "With Pidgin's clever ideas, the team is soon back on track with their jam game.\nThe game looks incredible, with next gen graphics and several hundreds of hours worth of content.\nEverything is working great, but the team is still angry with each other.\nEven after all of their accomplishments, there is still some tension left in the air.\n\n- finish game",
                new string[] { "" },
                AdventureBuilder.CreateAnswers()
                .AddAnswer("finish game", 10)),
        };

        adventure = new TextAdventure(nodes, wrongAnswerDialogs, finishedDialog);

        // Terminal lines.
        adventure = new TextAdventure(nodes, wrongAnswerDialogs, finishedDialog);

        lines = new List <string>()
        {
            "AT THE GLOBAL GAME JAM 2015, FINLAND, KAJAANI...",
            adventure.CurrentNode.EnterDialog
        };

        // Input style.
        inputTextStyle = new GUIStyle();
        inputTextStyle.normal.textColor = Color.green;
        inputTextStyle.fontSize         = 20;

        // Output style.
        outputTextStyle = new GUIStyle();
        outputTextStyle.normal.textColor = Color.white;
        outputTextStyle.fontSize         = 20;

        inputTimer = Stopwatch.StartNew();

        maxLines = (int)(Screen.height / inputTextStyle.CalcSize(new GUIContent(" ")).y) - 2;

        currentLine = string.Empty;
    }
Example #14
0
    private void OnGUI()
    {
        int index = 0;

        List <string> parsedLines = new List <string>();

        foreach (string str in lines)
        {
            if (str.Contains("\n"))
            {
                string[] newLines = str.Split(new string[] { "\n" }, System.StringSplitOptions.RemoveEmptyEntries);

                if (newLines.Length > 0)
                {
                    parsedLines.AddRange(newLines);
                }

                continue;
            }

            parsedLines.Add(str);
        }

        foreach (string str in parsedLines)
        {
            GUIStyle textStyle = str.StartsWith(">") ? outputTextStyle : inputTextStyle;

            GUIContent line = new GUIContent(str);

            Vector2 textSize = textStyle.CalcSize(line);

            Rect textRect = new Rect(
                left: transform.position.x,
                top: transform.position.y + index * textSize.y,
                width: textSize.x,
                height: textSize.y);

            GUI.Label(textRect, line, textStyle);

            index++;
        }

        string input = Input.inputString;

        float height = inputTextStyle.CalcSize(new GUIContent(" ")).y;

        Rect textAreaRect = new Rect(
            left: transform.position.x,
            top: Screen.height - height,
            width: Screen.width,
            height: height);

        if (!string.IsNullOrEmpty(input) && inputTimer.ElapsedMilliseconds > 25)
        {
            inputTimer = Stopwatch.StartNew();

            currentLine += input;

            GUI.Label(textAreaRect, currentLine, inputTextStyle);
        }

        if (!string.IsNullOrEmpty(currentLine))
        {
            GUI.Label(textAreaRect, currentLine);
        }
    }
Example #15
0
        protected override void ReParseImpl()
        {
            var outputWindow = OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense);

            try
            {
                Stopwatch stopwatch = Stopwatch.StartNew();

                var snapshot = TextBuffer.CurrentSnapshot;
                SnapshotCharStream         input  = new SnapshotCharStream(snapshot, new Span(0, snapshot.Length));
                GroupLexer                 lexer  = new GroupLexer(input);
                CommonTokenStream          tokens = new CommonTokenStream(lexer);
                GroupParserWrapper         parser = new GroupParserWrapper(tokens);
                List <ParseErrorEventArgs> errors = new List <ParseErrorEventArgs>();
                parser.ParseError += (sender, e) =>
                {
                    errors.Add(e);

                    string message = e.Message;

                    ITextDocument document;
                    if (TextBuffer.Properties.TryGetProperty(typeof(ITextDocument), out document) && document != null)
                    {
                        string fileName = document.FilePath;
                        var    line     = snapshot.GetLineFromPosition(e.Span.Start);
                        message = string.Format("{0}({1},{2}): {3}", fileName, line.LineNumber + 1, e.Span.Start - line.Start.Position + 1, message);
                    }

                    if (message.Length > 100)
                    {
                        message = message.Substring(0, 100) + " ...";
                    }

                    if (outputWindow != null)
                    {
                        outputWindow.WriteLine(message);
                    }

                    if (errors.Count > 100)
                    {
                        throw new OperationCanceledException();
                    }
                };

                TemplateGroupWrapper group = new TemplateGroupWrapper('<', '>');
                parser.group(group, "/");
                TemplateGroupRuleReturnScope returnScope = BuiltAstForGroupTemplates(group);

                // Also parse the input using the V4 lexer/parser for downstream operations that make use of it
                IList <Antlr4.Runtime.IToken>   v4tokens;
                TemplateParser.GroupFileContext v4result = ParseWithAntlr4(snapshot, out v4tokens);

                OnParseComplete(new StringTemplateParseResultEventArgs(snapshot, errors, stopwatch.Elapsed, tokens.GetTokens(), returnScope, v4tokens, v4result));
            }
            catch (Exception e) when(!ErrorHandler.IsCriticalException(e))
            {
                try
                {
                    if (outputWindow != null)
                    {
                        outputWindow.WriteLine(e.Message);
                    }
                }
                catch (Exception ex2) when(!ErrorHandler.IsCriticalException(ex2))
                {
                }
            }
        }
Example #16
0
    private void OnNodeClick(ushort inNodeId)
    {
        Stopwatch timer = Stopwatch.StartNew();

        Pathfinder.AStar(m_NodeGraph, ref m_PathBuffer, m_CurrentNode, inNodeId, Pathfinder.ManhattanDistanceHeuristic, default, Pathfinder.Flags.ReturnClosestPath);