Ejemplo n.º 1
0
        public void CompileSwitchBlock(SwitchBlock switchBlock)
        {
            XmlElement previousElement = currentElement;
            XmlElement tmpElement      = document.CreateElement("SwitchBlock");

            if (switchBlock.DefaultCase < int.MaxValue)
            {
                tmpElement.SetAttribute("DefaultCase", switchBlock.DefaultCase.ToString());
            }

            currentElement = document.CreateElement("Expression");
            switchBlock.Expression.AcceptCompiler(this);
            tmpElement.AppendChild(currentElement);

            if (switchBlock.Cases.Length > 0)
            {
                XmlElement casesElement = document.CreateElement("Cases");
                foreach (CaseLabel _case in switchBlock.Cases)
                {
                    ProcessSwitchCase(casesElement, _case);
                }
                tmpElement.AppendChild(casesElement);
            }

            currentElement = document.CreateElement("Statements");
            foreach (Statement statement in switchBlock.Statements)
            {
                statement.AcceptCompiler(this);
            }
            tmpElement.AppendChild(currentElement);

            previousElement.AppendChild(tmpElement);
            currentElement = previousElement;
        }
Ejemplo n.º 2
0
        public void SwitchBlock_NoDefaultBlock()
        {
            var sst = new SwitchBlock
            {
                Reference = SSTUtil.VariableReference("a"),
                Sections  =
                {
                    new CaseBlock
                    {
                        Label = new ConstantValueExpression{
                            Value = "1"
                        },
                        Body =    { new BreakStatement(),            new BreakStatement() }
                    },
                    new CaseBlock {
                        Label = new ConstantValueExpression{
                            Value = "2"
                        }, Body = { new BreakStatement() }
                    }
                }
            };

            AssertPrint(
                sst,
                "switch (a)",
                "{",
                "    case 1:",
                "        break;",
                "        break;",
                "    case 2:",
                "        break;",
                "}");
        }
 public void LinkSwitchToController(SwitchBlock negative, SwitchBlock positive)
 {
     negativeSwitch = negative;
     positiveSwitch = positive;
     negativeSwitch.BlockClickEvent += DetectBlockClick;
     positiveSwitch.BlockClickEvent += DetectBlockClick;
 }
Ejemplo n.º 4
0
        internal void EmitSwitch(object[] labels)
        {
            _emitState.AdjustStack(-1);
            int curStack = _emitState.CurStack;

            foreach (object label in labels)
            {
                LabelInfo ld;
                if (!_labelInfos.TryGetValue(label, out ld))
                {
                    _labelInfos.Add(label, new LabelInfo(curStack, true));
                }
                else
                {
                    Debug.Assert(ld.stack == curStack, "branches to same label with different stacks");

                    if (!ld.targetOfConditionalBranches)
                    {
                        _labelInfos[label] = ld.SetTargetOfConditionalBranches();
                    }
                }
            }

            SwitchBlock switchBlock = this.CreateSwitchBlock();

            switchBlock.BranchLabels = labels;
            this.EndBlock();
        }
            public SwitchBlock CreateSwitchBlock(ILBuilder builder)
            {
                SwitchBlock block = new SwitchBlock(builder, builder.EnclosingExceptionHandler);

                AddBlock(block);
                return(block);
            }
 public void DetectBlockClick(SwitchBlock block)
 {
     if (neighborController[0].isActivated || neighborController[1].isActivated)
     {
         return;
     }
     HandleWithSwitch(block, GetPrevSwitchState());
 }
Ejemplo n.º 7
0
        public void Equality_Default()
        {
            var a = new SwitchBlock();
            var b = new SwitchBlock();

            Assert.AreEqual(a, b);
            Assert.AreEqual(a.GetHashCode(), b.GetHashCode());
        }
Ejemplo n.º 8
0
        private SwitchBlock CreateSwitchBlock()
        {
            // end the current block
            EndBlock();

            SwitchBlock switchBlock = _scopeManager.CreateSwitchBlock(this);
            UpdatesForCreatedBlock(switchBlock);
            return switchBlock;
        }
Ejemplo n.º 9
0
        internal void BirdCounting3()
        {
            double               noise        = 0.2;
            int                  maxBirds     = 8;
            Range                numBirdRange = new Range(maxBirds + 1).Named("numBirdRange");
            Variable <int>       numBirds     = Variable.DiscreteUniform(numBirdRange).Named("numBirds");
            SwitchBlock          block        = Variable.Switch(numBirds);
            Range                bird         = new Range(maxBirds).Named("bird");
            VariableArray <bool> isMale       = Variable.Array <bool>(bird).Named("isMale");

            isMale[bird] = Variable.Bernoulli(0.5).ForEach(bird);
            Variable <int>       numObserved  = Variable.New <int>().Named("numObserved");
            Range                observedBird = new Range(numObserved).Named("observedBird");
            VariableArray <bool> observedMale = Variable.Array <bool>(observedBird).Named("observedMale");

            //VariableArray<int> birdIndices = Variable.Array<int>(observedBird).Named("birdIndices");
            using (Variable.ForEach(observedBird))
            {
                //birdIndices[observedBird] = Variable.DiscreteUniform(numBirds);
                //Variable<int> birdIndex = birdIndices[observedBird];
                Variable <int> birdIndex = Variable.DiscreteUniform(bird, numBirds).Named("birdIndex");
                using (Variable.Switch(birdIndex))
                {
#if true
                    //Variable.ConstrainEqual(observedMale[observedBird], isMale[birdIndex]);
                    observedMale[observedBird] = (isMale[birdIndex] == Variable.Bernoulli(1 - noise));
#else
                    using (Variable.If(isMale[birdIndex])) {
                        observedMale[observedBird] = Variable.Bernoulli(0.8);
                    }
                    using (Variable.IfNot(isMale[birdIndex])) {
                        observedMale[observedBird] = Variable.Bernoulli(0.2);
                    }
#endif
                }
            }
            block.CloseBlock();

            InferenceEngine engine = new InferenceEngine();
            for (int numObservedInt = 6; numObservedInt <= 10; numObservedInt++)
            {
                Console.WriteLine("numObserved = {0}", numObservedInt);
                // weird behavior with 1 different out of >=9 obs, no obs noise
                bool[] data            = new bool[numObservedInt];
                int    numObservedMale = 0;
                for (int i = 0; i < data.Length; i++)
                {
                    data[i] = (i < numObservedMale);
                }
                numObserved.ObservedValue  = data.Length;
                observedMale.ObservedValue = data;
                //Console.WriteLine("birdIndices = {0}", engine.Infer(birdIndices));
                Console.WriteLine("isMale = {0}", engine.Infer(isMale));
                Console.WriteLine("numBirds = {0}", engine.Infer(numBirds));
                Console.WriteLine("   exact = {0}", BallCountingExact(maxBirds, numObservedInt, numObservedMale, noise));
            }
        }
Ejemplo n.º 10
0
        public void Equality_DifferentReference()
        {
            var a = new SwitchBlock {
                Reference = SomeVarRef("a")
            };
            var b = new SwitchBlock();

            Assert.AreNotEqual(a, b);
            Assert.AreNotEqual(a.GetHashCode(), b.GetHashCode());
        }
Ejemplo n.º 11
0
        public void Equality_DifferentSections()
        {
            var a = new SwitchBlock();

            a.Sections.Add(new CaseBlock());
            var b = new SwitchBlock();

            Assert.AreNotEqual(a, b);
            Assert.AreNotEqual(a.GetHashCode(), b.GetHashCode());
        }
Ejemplo n.º 12
0
        SwitchBlock GetSwitchBlock()
        {
            SwitchBlock switchBlk = GetBlock() as SwitchBlock;

            if (switchBlk == null)
            {
                throw new InvalidOperationException("Statement can be used only in a switch block");
            }
            return(switchBlk);
        }
Ejemplo n.º 13
0
        SwitchBlock GetSwitchBlock()
        {
            SwitchBlock switchBlk = GetBlock() as SwitchBlock;

            if (switchBlk == null)
            {
                throw new InvalidOperationException(Properties.Messages.ErrInvalidSwitchStatement);
            }
            return(switchBlk);
        }
Ejemplo n.º 14
0
        public void Equality_DifferentDefaultSection()
        {
            var a = new SwitchBlock();

            a.DefaultSection.Add(new ReturnStatement());
            var b = new SwitchBlock();

            Assert.AreNotEqual(a, b);
            Assert.AreNotEqual(a.GetHashCode(), b.GetHashCode());
        }
Ejemplo n.º 15
0
        public void DefaultValues()
        {
            var sut = new SwitchBlock();

            Assert.AreEqual(new VariableReference(), sut.Reference);
            Assert.AreEqual(Lists.NewList <IStatement>(), sut.Sections);
            Assert.AreEqual(Lists.NewList <IStatement>(), sut.DefaultSection);
            Assert.AreNotEqual(0, sut.GetHashCode());
            Assert.AreNotEqual(1, sut.GetHashCode());
        }
Ejemplo n.º 16
0
    public void RegisterSwitchBlock(SwitchBlock switchBlock)
    {
        if (switchBlock.Color == GameColor.None)
        {
#if SWITCH_BLOCK_MANAGER
            Debug.LogFormat(switchBlock, "Switch Block {0} has color None, cannot be registered by SwitchBlockManager.",
                            switchBlock);
#endif
            return;
        }

        m_SwitchBlocksDict[switchBlock.Color].Add(switchBlock);
    }
Ejemplo n.º 17
0
        private static void MarkReachableFromSwitch(ArrayBuilder <BasicBlock> reachableBlocks, BasicBlock block)
        {
            SwitchBlock switchBlock = (SwitchBlock)block;
            ArrayBuilder <BasicBlock> blockBuilder = ArrayBuilder <BasicBlock> .GetInstance();

            switchBlock.GetBranchBlocks(blockBuilder);

            foreach (BasicBlock targetBlock in blockBuilder)
            {
                PushReachableBlockToProcess(reachableBlocks, targetBlock);
            }

            blockBuilder.Free();
        }
Ejemplo n.º 18
0
        public void ChildrenIdentity()
        {
            var sut = new SwitchBlock
            {
                Reference      = SomeVarRef("a"),
                Sections       = { new CaseBlock() },
                DefaultSection =
                {
                    new ReturnStatement()
                }
            };

            AssertChildren(sut, sut.Reference, sut.DefaultSection.First());
        }
Ejemplo n.º 19
0
        public override void VisitSwitchStatement(ISwitchStatement block, IList <IStatement> body)
        {
            AddIf(block, CompletionCase.EmptyCompletionBefore, body);

            var switchBlock = new SwitchBlock {
                Reference = _exprVisitor.ToVariableRef(block.Condition, body)
            };

            foreach (var section in block.Sections)
            {
                IKaVEList <IStatement> currentSection = null;

                foreach (var label in section.CaseLabels)
                {
                    currentSection = new KaVEList <IStatement>();
                    if (label.IsDefault)
                    {
                        switchBlock.DefaultSection = currentSection;
                    }
                    else
                    {
                        switchBlock.Sections.Add(
                            new CaseBlock
                        {
                            Label = _exprVisitor.ToSimpleExpression(label.ValueExpression, body),
                            Body  = currentSection
                        });
                    }
                    AddIf(label, CompletionCase.InBody, currentSection);
                }

                AddIf(section, CompletionCase.InBody, currentSection);
                foreach (var statement in section.Statements)
                {
                    statement.Accept(this, currentSection);
                }

                switch (1)
                {
                case 1 * 2:
                case 0:
                    break;
                }
            }

            body.Add(switchBlock);

            AddIf(block, CompletionCase.EmptyCompletionAfter, body);
        }
    private void SetSwitchBlock()
    {
        for (int i = 0; i < axisIndex; i++) //axisIndex(0 -> x) axisIndex(1 -> y)axisIndex(2 -> z)
        {
            GameObject  blockUnder          = Instantiate(swithBlockPrefab) as GameObject;
            SwitchBlock switchBlockNegative = blockUnder.GetComponent <SwitchBlock>();
            switchBlockNegative.Initialize(i, blockSize, 0);
            switchArray[i, 0] = switchBlockNegative;

            GameObject  blockUpper          = Instantiate(swithBlockPrefab) as GameObject;
            SwitchBlock switchBlockPositive = blockUpper.GetComponent <SwitchBlock>();
            switchBlockPositive.Initialize(i, blockSize, blockSize);
            switchArray[i, 1] = switchBlockPositive;
        }
    }
Ejemplo n.º 21
0
        public void CompileSwitchBlock(SwitchBlock switchBlock)
        {
            textWriter.Write("switch (");
            switchBlock.Expression.AcceptCompiler(this);
            textWriter.WriteLine(")");
            textWriter.WriteLine("{");
            ++textWriter.Indentation;

            int counter = 0;

            while (counter < switchBlock.Statements.Length)
            {
                foreach (CaseLabel caseLabel in switchBlock.Cases)
                {
                    if (caseLabel.Address != counter)
                    {
                        continue;
                    }

                    textWriter.Write("case ");
                    DumpDynamic(caseLabel.Value);
                    textWriter.WriteLine(":");
                }

                if (counter == switchBlock.DefaultCase)
                {
                    textWriter.WriteLine("default:");
                }

                foreach (var pair in switchBlock.Labels)
                {
                    if (pair.Value.Address != counter)
                    {
                        continue;
                    }

                    ++textWriter.Indentation;
                    textWriter.WriteLine("{0}:", SafeName(pair.Key));
                    --textWriter.Indentation;
                }

                MayBeIndent(switchBlock.Statements[counter]);
                ++counter;
            }

            --textWriter.Indentation;
            textWriter.WriteLine("}");
        }
Ejemplo n.º 22
0
        public void SettingValues()
        {
            var sut = new SwitchBlock
            {
                Reference      = SomeVarRef("a"),
                Sections       = { new CaseBlock() },
                DefaultSection =
                {
                    new ReturnStatement()
                }
            };

            Assert.AreEqual(SomeVarRef("a"), sut.Reference);
            Assert.AreEqual(Lists.NewList(new CaseBlock()), sut.Sections);
            Assert.AreEqual(Lists.NewList(new ReturnStatement()), sut.DefaultSection);
        }
Ejemplo n.º 23
0
        // Build a switch block statement
        public static void BuildSwitchBlock(IronyParser parser, Root root, Expression parentExpression, ParseTreeNode currentNode)
        {
            var s = new SwitchBlock(parentExpression, currentNode.Token.Convert());

            parentExpression.ChildExpressions.Add(s);

            // Get the expression being tested
            parser.ConsumeParseTree(root, s.Variable, currentNode.ChildNodes[1]);

            // Build each case block
            if (currentNode.ChildNodes[2].ChildNodes.Count > 0)
            {
                foreach (var node in currentNode.ChildNodes[2].ChildNodes[0].ChildNodes)
                {
                    BuildCaseBlock(parser, root, s, node);
                }
            }
        }
Ejemplo n.º 24
0
        public void BallCounting2()
        {
            double         noise    = 0.2;
            int            maxBalls = 8;
            Range          ball     = new Range(maxBalls).Named("ball");
            Variable <int> numBalls = Variable.DiscreteUniform(maxBalls + 1).Named("numBalls");

            numBalls.SetValueRange(new Range(maxBalls + 1));
            SwitchBlock          block        = Variable.Switch(numBalls);
            Variable <int>       numTrue      = Variable.Binomial(numBalls, 0.5).Named("numTrue");
            Variable <int>       numObserved  = Variable.New <int>().Named("numObserved");
            Range                observedBall = new Range(numObserved).Named("observedBall");
            VariableArray <bool> observedTrue = Variable.Array <bool>(observedBall).Named("observedTrue");

            using (Variable.ForEach(observedBall))
            {
                Variable <int> ballIndex = Variable.DiscreteUniform(ball, numBalls).Named("ballIndex");
                observedTrue[observedBall] = ((ballIndex < numTrue) == Variable.Bernoulli(1 - noise));
            }
            block.CloseBlock();

            InferenceEngine engine = new InferenceEngine();

            for (int numObservedInt = 10; numObservedInt <= 10; numObservedInt++)
            {
                Console.WriteLine("numObserved = {0}", numObservedInt);
                // weird behavior with 1 different out of >=9 obs, no obs noise
                bool[] data            = new bool[numObservedInt];
                int    numObservedTrue = 0;
                for (int i = 0; i < data.Length; i++)
                {
                    data[i] = (i < numObservedTrue);
                }
                numObserved.ObservedValue  = data.Length;
                observedTrue.ObservedValue = data;
                //Console.WriteLine("numTrue = {0}", engine.Infer(numTrue));
                Discrete numBallsActual = engine.Infer <Discrete>(numBalls);
                Console.WriteLine("numBalls = {0}", numBallsActual);
                Discrete numBallsExpected = BallCountingExact(maxBalls, numObservedInt, numObservedTrue, noise);
                Console.WriteLine("   exact = {0}", numBallsExpected);
                Assert.True(numBallsExpected.MaxDiff(numBallsActual) < 1e-10);
            }
        }
Ejemplo n.º 25
0
        // Generate a series of codedom if statements representing a switch block.
        // (Codedom doesn't support switch)
        public static CodeStatement Emit(SwitchBlock switchBlock)
        {
            // Create the expression for whatever we're switching on.
            var codeVar = CodeDomEmitter.EmitCodeExpression(switchBlock.Variable.ChildExpressions[0]);

            // Store the first and previous if statements here, since it's needed on future loops.
            CodeConditionStatement codeIf = null;
            CodeConditionStatement lastIf = null;

            foreach (var e in switchBlock.ChildExpressions)
            {
                // Get the value being compared to: the right operand.
                var right = CodeDomEmitter.EmitCodeExpression((e as CaseBlock).Variable.ChildExpressions[0]);

                // Create the next if statement.
                var nestedIf = new CodeConditionStatement();

                // Each case block will compare codeVar (left) to the right operand.
                nestedIf.Condition = new CodeBinaryOperatorExpression(codeVar, CodeBinaryOperatorType.ValueEquality, right);
                nestedIf.TrueStatements.Add(new CodeCommentStatement("If condition is true, execute these statements."));
                foreach (var s in e.ChildExpressions)
                {
                    nestedIf.TrueStatements.Add(CodeDomEmitter.EmitCodeStatement(s));
                }
                nestedIf.FalseStatements.Add(new CodeCommentStatement("If condition is false, execute these statements."));
                // if codeIf is null, this is the first if statement.
                if (codeIf == null)
                {
                    codeIf = nestedIf;
                }
                else // It's not the first if statement, so attach it to the previous one.
                {
                    lastIf.FalseStatements.Add(nestedIf);
                }


                // Store the last if block for the next iteration.
                lastIf = nestedIf;
            }

            return(codeIf);
        }
Ejemplo n.º 26
0
        public void Equality_ReallyTheSame()
        {
            var a = new SwitchBlock
            {
                Reference      = SomeVarRef("a"),
                Sections       = { new CaseBlock() },
                DefaultSection =
                {
                    new ReturnStatement()
                }
            };
            var b = new SwitchBlock
            {
                Reference      = SomeVarRef("a"),
                Sections       = { new CaseBlock() },
                DefaultSection =
                {
                    new ReturnStatement()
                }
            };

            Assert.AreEqual(a, b);
            Assert.AreEqual(a.GetHashCode(), b.GetHashCode());
        }
Ejemplo n.º 27
0
    internal void updateSwitch(int switchID)
    {
        if (switchTargets == null)
        {
            switchTargets = new Dictionary <int, HashSet <MapObject> >();
        }

        if (targetSwitches == null)
        {
            targetSwitches = new Dictionary <MapObject, HashSet <int> >();
        }

        SwitchBlock switchBlock = switchMap[switchID];

        if (switchTargets.ContainsKey(switchID))
        {
            //this switch has targets
            foreach (MapObject mo in switchTargets[switchID])
            {
                //for each of this switches targets, check their state
                switchBlock.updateObject(mo);
            }
        }
    }
Ejemplo n.º 28
0
 public SwitchStatement(IApexNode parenthesizedExpression56, SwitchBlock switchBlockLabels57)
 {
     // TODO: Complete member initialization
     this.parenthesizedExpression56 = parenthesizedExpression56;
     this.switchBlockLabels57       = switchBlockLabels57;
 }
Ejemplo n.º 29
0
	public void AddSwtichBlock(SwitchBlock block){
		switchBlocks.Add (block);
	}
Ejemplo n.º 30
0
        private void RealizeBlocks()
        {
            // drop dead code.
            // We do not want to deal with unreachable code even when not optimizing.
            // sometimes dead code may have subtle verification violations
            // for example illegal fall-through in unreachable code is still illegal,
            // but compiler will not enforce returning from dead code.
            // it is easier to just remove dead code than make sure it is all valid
            MarkReachableBlocks();
            RewriteSpecialBlocks();
            DropUnreachableBlocks();

            if (_optimizations == OptimizationLevel.Release && OptimizeLabels())
            {
                // redo unreachable code elimination if some labels were optimized
                // as that could result in more dead code.
                MarkAllBlocksUnreachable();
                MarkReachableBlocks();
                DropUnreachableBlocks();
            }

            // some gotos must become leaves
            RewriteBranchesAcrossExceptionHandlers();

            // now we can compute block offsets and adjust branches
            while (ComputeOffsetsAndAdjustBranches())
            {
                // if branches were optimized, we may have more unreachable code
                // redo unreachable code elimination and if anything was dropped redo adjusting.
                MarkAllBlocksUnreachable();
                MarkReachableBlocks();
                if (!DropUnreachableBlocks())
                {
                    // nothing was dropped, we are done adjusting
                    break;
                }
            }

            // Now linearize everything with computed offsets.
            Cci.PooledBlobBuilder writer = Cci.PooledBlobBuilder.GetInstance();

            for (BasicBlock block = leaderBlock; block != null; block = block.NextBlock)
            {
                // If the block has any IL markers, we can calculate their real IL offsets now
                int blockFirstMarker = block.FirstILMarker;
                if (blockFirstMarker >= 0)
                {
                    int blockLastMarker = block.LastILMarker;
                    Debug.Assert(blockLastMarker >= blockFirstMarker);
                    for (int i = blockFirstMarker; i <= blockLastMarker; i++)
                    {
                        int blockOffset    = _allocatedILMarkers[i].BlockOffset;
                        int absoluteOffset = writer.Count + blockOffset;
                        _allocatedILMarkers[i] = new ILMarker()
                        {
                            BlockOffset = blockOffset, AbsoluteOffset = absoluteOffset
                        };
                    }
                }

                block.RegularInstructions?.WriteContentTo(writer);

                switch (block.BranchCode)
                {
                case ILOpCode.Nop:
                    break;

                case ILOpCode.Switch:
                    // switch (N, t1, t2... tN)
                    //  IL ==> ILOpCode.Switch < unsigned int32 > < int32 >... < int32 >

                    WriteOpCode(writer, ILOpCode.Switch);

                    SwitchBlock switchBlock = (SwitchBlock)block;
                    writer.WriteUInt32(switchBlock.BranchesCount);

                    int switchBlockEnd = switchBlock.Start + switchBlock.TotalSize;

                    ArrayBuilder <BasicBlock> blockBuilder = ArrayBuilder <BasicBlock> .GetInstance();

                    switchBlock.GetBranchBlocks(blockBuilder);

                    foreach (BasicBlock branchBlock in blockBuilder)
                    {
                        writer.WriteInt32(branchBlock.Start - switchBlockEnd);
                    }

                    blockBuilder.Free();

                    break;

                default:
                    WriteOpCode(writer, block.BranchCode);

                    if (block.BranchLabel != null)
                    {
                        int target      = block.BranchBlock.Start;
                        int curBlockEnd = block.Start + block.TotalSize;
                        int offset      = target - curBlockEnd;

                        if (block.BranchCode.GetBranchOperandSize() == 1)
                        {
                            sbyte btOffset = (sbyte)offset;
                            Debug.Assert(btOffset == offset);
                            writer.WriteSByte(btOffset);
                        }
                        else
                        {
                            writer.WriteInt32(offset);
                        }
                    }

                    break;
                }
            }

            this.RealizedIL = writer.ToImmutableArray();
            writer.Free();

            RealizeSequencePoints();

            this.RealizedExceptionHandlers = _scopeManager.GetExceptionHandlerRegions();
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Deserializes the world blocks from an Everybody Edits world based on a <see cref="Message"/> object.
        /// </summary>
        /// <param name="m">The Message object that contains the data about the Everybody Edits world.</param>
        /// <param name="worldWidth">The width of the Everybody Edits world.</param>
        /// <param name="worldHeight">The height of the Everybody Edits world.</param>
        /// <returns>
        /// A 3-dimensional array of type <see cref="Block"/>. The first dimension represents layer, the second represents horizontal coordinate, and the third represents
        /// vertical coordinate.
        /// </returns>
        public static Block[,,] DeserializeBlocks(Message m, int worldWidth, int worldHeight)
        {
            if (!CanDeserializeBlocks(m))
            {
                throw new Exception($"Can not deserialize world blocks from \"{m.Type}\" message.");
            }

            Block[,,] worldBlocks = InitalizeWorldBlocksArray(2, worldWidth, worldHeight);
            uint currentBlockChunk = GetWorldStart(m) + 1;

            while (m[currentBlockChunk] as string != EverybodyEditsMessage.WorldEnd)
            {
                int    blockId       = m.GetInt(currentBlockChunk);
                int    layer         = m.GetInt(currentBlockChunk + 1);
                byte[] xPositions    = m.GetByteArray(currentBlockChunk + 2);
                byte[] yPositions    = m.GetByteArray(currentBlockChunk + 3);
                uint   chunkArgsRead = 4;

                for (int i = 0; i < xPositions.Length; i += 2)
                {
                    int x = (xPositions[i] << 8) | (xPositions[i + 1]);
                    int y = (yPositions[i] << 8) | (yPositions[i + 1]);

                    switch (blockId)
                    {
                    case 77:
                    case 83:
                    case 1520:
                    {
                        int soundId = m.GetInt(currentBlockChunk + 4);
                        worldBlocks[layer, x, y] = new MusicBlock(blockId, soundId);

                        chunkArgsRead = 5;
                    }
                    break;

                    case 113:
                    case 184:
                    case 185:
                    case 467:
                    case 1619:
                    case 1620:
                    case 1079:
                    case 1080:
                    {
                        uint switchId = m.GetUInt(currentBlockChunk + 4);
                        worldBlocks[layer, x, y] = new SwitchBlock(blockId, switchId);

                        chunkArgsRead = 5;
                    }
                    break;

                    case 242:
                    case 381:
                    {
                        int portalId   = m.GetInt(currentBlockChunk + 4);
                        int targetId   = m.GetInt(currentBlockChunk + 5);
                        int rotationId = m.GetInt(currentBlockChunk + 6);
                        worldBlocks[layer, x, y] = new PortalBlock(blockId, portalId, targetId, rotationId);

                        chunkArgsRead = 7;
                    }
                    break;

                    case 1582:
                    {
                        int spawnId = m.GetInt(currentBlockChunk + 4);
                        worldBlocks[layer, x, y] = new WorldPortalSpawnBlock(blockId, spawnId);

                        chunkArgsRead = 5;
                    }
                    break;

                    case 374:
                    {
                        string targetWorldId = m.GetString(currentBlockChunk + 4);
                        int    targetSpawn   = m.GetInt(currentBlockChunk + 5);
                        worldBlocks[layer, x, y] = new WorldPortalBlock(blockId, targetWorldId, targetSpawn);

                        chunkArgsRead = 6;
                    }
                    break;

                    case 385:
                    {
                        string text       = m.GetString(currentBlockChunk + 4);
                        int    rotationId = m.GetInt(currentBlockChunk + 5);
                        worldBlocks[layer, x, y] = new SignBlock(blockId, text, rotationId);

                        chunkArgsRead = 6;
                    }
                    break;

                    case 417:
                    case 418:
                    case 419:
                    case 420:
                    case 423:
                    case 453:
                    case 461:
                    case 1517:
                    case 1584:
                    {
                        int effectId = m.GetInt(currentBlockChunk + 4);
                        worldBlocks[layer, x, y] = new EffectBlock(blockId, effectId);

                        chunkArgsRead = 5;
                    }
                    break;

                    case 421:
                    case 422:
                    {
                        int duration = m.GetInt(currentBlockChunk + 4);
                        worldBlocks[layer, x, y] = new TimedEffectBlock(blockId, duration);

                        chunkArgsRead = 5;
                    }
                    break;

                    case 1550:
                    case 1551:
                    case 1552:
                    case 1553:
                    case 1554:
                    case 1556:
                    case 1557:
                    case 1558:
                    case 1571:
                    case 1572:
                    case 1573:
                    case 1576:
                    case 1579:
                    {
                        string   name     = m.GetString(currentBlockChunk + 4);
                        string[] messages = { m.GetString(currentBlockChunk + 5), m.GetString(currentBlockChunk + 6), m.GetString(currentBlockChunk + 7) };
                        worldBlocks[layer, x, y] = new NonPlayableCharacterBlock(blockId, name, messages);

                        chunkArgsRead = 8;
                    }
                    break;

                    case 273:
                    case 275:
                    case 276:
                    case 277:
                    case 279:
                    case 280:
                    case 327:
                    case 328:
                    case 329:
                    case 338:
                    case 339:
                    case 340:
                    case 361:
                    case 376:
                    case 377:
                    case 378:
                    case 379:
                    case 380:
                    case 438:
                    case 439:
                    case 440:
                    case 447:
                    case 448:
                    case 449:
                    case 451:
                    case 452:
                    case 456:
                    case 457:
                    case 458:
                    case 464:
                    case 465:
                    case 471:
                    case 499:
                    case 1001:
                    case 1002:
                    case 1003:
                    case 1004:
                    case 1116:
                    case 1117:
                    case 1118:
                    case 1119:
                    case 1120:
                    case 1121:
                    case 1122:
                    case 1123:
                    case 1124:
                    case 1125:
                    case 1041:
                    case 1042:
                    case 1043:
                    case 1052:
                    case 1053:
                    case 1054:
                    case 1055:
                    case 1056:
                    case 1092:
                    case 1134:
                    case 1135:
                    case 1140:
                    case 1141:
                    case 1500:
                    case 1502:
                    case 1506:
                    case 1507:
                    case 1535:
                    case 1536:
                    case 1537:
                    case 1538:
                    case 1155:
                    case 1160:
                    case 1581:
                    case 1587:
                    case 1588:
                    case 1592:
                    case 1593:
                    case 1594:
                    case 1595:
                    case 1596:
                    case 1597:
                    case 1605:
                    case 1606:
                    case 1607:
                    case 1608:
                    case 1609:
                    case 1610:
                    case 1611:
                    case 1612:
                    case 1613:
                    case 1614:
                    case 1615:
                    case 1616:
                    case 1617:
                    case 1633:
                    {
                        int morphId = m.GetInt(currentBlockChunk + 4);
                        worldBlocks[layer, x, y] = new MorphableBlock(blockId, morphId);

                        chunkArgsRead = 5;
                    }
                    break;

                    default:
                    {
                        worldBlocks[layer, x, y] = new Block(blockId);

                        chunkArgsRead = 4;
                    }
                    break;
                    }
                }

                currentBlockChunk += chunkArgsRead;
            }

            return(worldBlocks);
        }