Inheritance: MonoBehaviour
コード例 #1
1
		private void DrawSearchHighlight(DrawingContext dc, Block block)
		{
			foreach (var pair in _curSearchMatches)
			{
				int txtOffset = 0;
				double y = block.Y;

				for (int i = 0; i < block.Text.Length; i++)
				{
					int start = Math.Max(txtOffset, pair.Item1);
					int end = Math.Min(txtOffset + block.Text[i].Length, pair.Item2);

					if (end > start)
					{
						double x1 = block.Text[i].GetDistanceFromCharacterHit(new CharacterHit(start, 0)) + block.TextX;
						double x2 = block.Text[i].GetDistanceFromCharacterHit(new CharacterHit(end, 0)) + block.TextX;

						dc.DrawRectangle(_searchBrush.Value, null,
							new Rect(new Point(x1, y), new Point(x2, y + _lineHeight)));
					}

					y += _lineHeight;
					txtOffset += block.Text[i].Length;
				}
			}
		}
コード例 #2
1
ファイル: BlockUpdate.cs プロジェクト: fragmer/fCraft
 public BlockUpdate( Player origin, short x, short y, short z, Block blockType ) {
     Origin = origin;
     X = x;
     Y = y;
     Z = z;
     BlockType = blockType;
 }
コード例 #3
1
ファイル: BlockUpdate.cs プロジェクト: fragmer/fCraft
 public BlockUpdate( Player origin, Vector3I coord, Block blockType ) {
     Origin = origin;
     X = (short)coord.X;
     Y = (short)coord.Y;
     Z = (short)coord.Z;
     BlockType = blockType;
 }
コード例 #4
0
 /// <summary>
 /// Add block override
 /// </summary>
 /// <param name="block">Block to add</param>
 public override void AddBlock(Block block)
 {
     if (block is Constructor || block is Statement || block is Method)
         SubBlocks.Add(block);
     else
         Logger.Error(LocaString.Get("UnhandledError") +  " : CustomObject.cs #1");
 }
コード例 #5
0
ファイル: SandPhysics.cs プロジェクト: GlennMR/800craft
 public SandTask( World world, Vector3I position, Block Type )
     : base(world)
 {
     _pos = position;
     _nextPos = position.Z - 1;
     _type = Type;
 }
コード例 #6
0
ファイル: CopyState.cs プロジェクト: fragmer/fCraft
 public CopyState( Vector3I mark1, Vector3I mark2 ) {
     BoundingBox box = new BoundingBox( mark1, mark2 );
     Orientation = new Vector3I( mark1.X <= mark2.X ? 1 : -1,
                                 mark1.Y <= mark2.Y ? 1 : -1,
                                 mark1.Z <= mark2.Z ? 1 : -1 );
     Buffer = new Block[box.Width, box.Length, box.Height];
 }
コード例 #7
0
ファイル: UndoState.cs プロジェクト: Blingpancakeman/800craft
 public UndoBlock( Vector3I coord, Block block )
 {
     X = (short)coord.X;
     Y = (short)coord.Y;
     Z = (short)coord.Z;
     Block = block;
 }
コード例 #8
0
ファイル: StLdlocFixer.cs プロジェクト: GodLesZ/de4dot
		protected override bool Deobfuscate(Block block) {
			bool modified = false;
			var instructions = block.Instructions;
			for (int i = 0; i < instructions.Count; i++) {
				var instr = instructions[i];
				switch (instr.OpCode.Code) {
				// Xenocode generates stloc + ldloc (bool). Replace it with dup + stloc. It will eventually
				// become dup + pop and be removed.
				case Code.Stloc:
				case Code.Stloc_S:
				case Code.Stloc_0:
				case Code.Stloc_1:
				case Code.Stloc_2:
				case Code.Stloc_3:
					if (i + 1 >= instructions.Count)
						break;
					if (!instructions[i + 1].IsLdloc())
						break;
					var local = Instr.GetLocalVar(locals, instr);
					if (local.Type.ElementType != ElementType.Boolean)
						continue;
					if (local != Instr.GetLocalVar(locals, instructions[i + 1]))
						break;
					instructions[i] = new Instr(OpCodes.Dup.ToInstruction());
					instructions[i + 1] = instr;
					modified = true;
					break;

				default:
					break;
				}
			}

			return modified;
		}
コード例 #9
0
 public FireworkParticle(World world, Vector3I pos, Block block)
     : base(world)
 {
     _startingPos = pos;
     _nextZ = pos.Z - 1;
     _block = block;
 }
コード例 #10
0
    /// <summary>
    /// Generate a chunk and return it. The terrain object remains unmodified.
    /// </summary>
    /// <param name="terrain">The terrain.</param>
    /// <param name="chunkIndex">The chunk index.</param>
    /// <returns>The chunk.</returns>
    public Chunk GenerateChunk(Terrain terrain, Vector2I chunkIndex)
    {
        Chunk chunk = new Chunk();

        // Calculate the position of the chunk in world coordinates
        var chunkPos = new Vector2I(chunkIndex.X * Chunk.SizeX, chunkIndex.Y * Chunk.SizeY);

        // Get the surface heights for this chunk
        int[] surfaceHeights = this.GenerateSurfaceHeights(chunkPos);

        // For now, fill the terrain with mud under the surface
        for (int x = 0; x < Chunk.SizeX; x++)
        {
            int surfaceHeight = surfaceHeights[x];
            if (surfaceHeight > 0)
            {
                for (int y = 0; y < surfaceHeight; y++)
                {
                    chunk[x, y] = new Block(BlockType.Dirt);
                }
            }
        }

        return chunk;
    }
コード例 #11
0
ファイル: Chunk.cs プロジェクト: billy1234/TerrainGenMaster
    void Start()
    {
        filter = gameObject.GetComponent<MeshFilter>();
        coll = gameObject.GetComponent<MeshCollider>();

        //past here is just to set up an example chunk
        blocks = new Block[chunkSize, chunkSize, chunkSize];

        for (int x = 0; x < chunkSize; x++)
        {
            for (int y = 0; y < chunkSize; y++)
            {
                for (int z = 0; z < chunkSize; z++)
                {
                    blocks[x, y, z] = new BlockAir();
                }
            }
        }

        blocks[1, 1, 1] = new Block();
        blocks[1, 2, 1] = new Block();
        blocks[1, 2, 2] = new Block();
        blocks[2, 2, 2] = new Block();

        UpdateChunk();
    }
コード例 #12
0
        public TwitterClient(IRestClient client, string consumerKey, string consumerSecret, string callback)
            : base(client)
        {
            Encode = true;
            Statuses = new Statuses(this);
            Account = new Account(this);
            DirectMessages = new DirectMessages(this);
            Favourites = new Favourites(this);
            Block = new Block(this);
            Friendships = new Friendship(this);
            Lists = new List(this);
            Search = new Search(this);
            Users = new Users(this);
            FriendsAndFollowers = new FriendsAndFollowers(this);

            OAuthBase = "https://api.twitter.com/oauth/";
            TokenRequestUrl = "request_token";
            TokenAuthUrl = "authorize";
            TokenAccessUrl = "access_token";
            Authority = "https://api.twitter.com/";
            Version = "1";

#if !SILVERLIGHT
            ServicePointManager.Expect100Continue = false;
#endif
            Credentials = new OAuthCredentials
            {
                ConsumerKey = consumerKey,
                ConsumerSecret = consumerSecret,
            };

            if (!string.IsNullOrEmpty(callback))
                ((OAuthCredentials)Credentials).CallbackUrl = callback;
        }
コード例 #13
0
ファイル: WaterPhysics.cs プロジェクト: venofox/AtomicCraft
 public BlockFloat(World world, Vector3I position, Block Type)
     : base(world)
 {
     _pos = position;
     _nextPos = position.Z + 1;
     type = Type;
 }
コード例 #14
0
ファイル: GenerateCity.cs プロジェクト: ManuelKers/shady
	private Block[] subDivideBlock(Block originBlock) {

	
		bool xSpace = Mathf.Abs(originBlock.c3.x-originBlock.c1.x) > minimumBlockSize * 2.1;
		bool ySpace = Mathf.Abs(originBlock.c3.y-originBlock.c1.y) > minimumBlockSize * 2.1;
        float roadWidth = Random.Range(roadWidthMin, roadWidthMax);
		if (!xSpace && !ySpace) { 
			Block b1 = new Block ();
			Block b2 = new Block ();
			Debug.Assert (b1.IsNull);
			Debug.Assert (b2.IsNull);
			return new Block[2]{new Block(), new Block()}; 
		}

		bool xSplit = (xSpace && Random.value < 0.5f) || !ySpace;
		float splitPlace;
		if (xSplit) {
			splitPlace = Random.Range (originBlock.c1.x+minimumBlockSize, originBlock.c3.x-minimumBlockSize);
			Block block1 = new Block (originBlock.c1, new Vector2(splitPlace-roadWidth/2, originBlock.c3.y));
			Block block2 = new Block (new Vector2(splitPlace+roadWidth/2, originBlock.c1.y), originBlock.c3);
			return new Block[2]{block1,block2};
					
		} else {
			splitPlace = Random.Range (originBlock.c1.y+minimumBlockSize, originBlock.c3.y-minimumBlockSize);
			Block block1 = new Block (originBlock.c1, new Vector2(originBlock.c3.x, splitPlace-roadWidth/2));
			Block block2 = new Block (new Vector2(originBlock.c1.x, splitPlace+roadWidth/2), originBlock.c3);
			return new Block[2]{block1,block2};
		}
	}
コード例 #15
0
ファイル: GenerateCity.cs プロジェクト: ManuelKers/shady
	private void recursiveBlockDivision(Block block, ArrayList blocks, int loopsLeft) {
		if (loopsLeft < 0) {
			return;
		}
		float currentMagnitude = (block.c3 - block.c1).magnitude;
		Block[] newBlocks = subDivideBlock (block);
		bool subDivide;
		if (Mathf.Max ((block.c2 - block.c1).magnitude, (block.c4 - block.c1).magnitude) > maximumBlockSize) { //block too large, subdivide			
			subDivide = true;
		} else if (newBlocks [0].IsNull) { //block can be  subdivided, keep it like this			
			subDivide = false;
			blocks.Add (block);
		} else {
			if (currentMagnitude < minimumBlockSize * 6 && Random.value <= 0.2) {
				subDivide = false;
			} else if (Random.value <= 0.2) {				
				subDivide = false;
				blocks.Add (block);
			} else {
				subDivide = true;
			}
		}

		if (subDivide) {
			recursiveBlockDivision (newBlocks [0], blocks, loopsLeft - 1);
			recursiveBlockDivision (newBlocks [1], blocks, loopsLeft - 1);
		}
	}
コード例 #16
0
 private static Block AddColumn4(Block block)
 {
     block = block.AddRight(Brushes.White, 96);
     Block inner = block.AddInner(Brushes.Red, 390 - 357, 444 - 416, 33, 70);
     inner.AddBelow(Brushes.Yellow, 15);
     return block;
 }
コード例 #17
0
ファイル: revcomp.cs プロジェクト: kjk/kjkpub
 static void Main(string[] args)
 {
     InitComplements();
       var seq = new List<byte[]>();
       var b = new Block { Count = -1 };
       Index line = Index.None, start = Index.None, end = Index.None;
       using (var r = new BinaryReader(Console.OpenStandardInput())) {
      using (var w = Console.OpenStandardOutput()) {
         while (b.Read(r) > 0) {
            seq.Add(b.Data);
            if (line.Pos < 0) line = b.IndexOf(Gt, 0);
            while (line.Pos >= 0) {
               if (start.Pos < 0) {
                  var off = line.InBlock(b) ? line.Pos : 0;
                  start = b.IndexOf(Lf, off);
                  if (start.Pos < 0) {
                      w.Write(b.Data, off, b.Data.Length - off);
                      seq.Clear(); break;
                  }
                  w.Write(b.Data, off, start.Pos + 1 - off);
               }
               if (end.Pos < 0) {
                  end = b.IndexOf(Gt, start.InBlock(b) ? start.Pos : 0);
                  if (end.Pos < 0) break;
               }
               w.Reverse(start.Pos, end.Pos, seq);
               if (seq.Count > 1) seq.RemoveRange(0, seq.Count - 1);
               line = end; end = Index.None; start = Index.None;
            }
         }
         if (start.Pos >= 0 && end.Pos < 0)
            w.Reverse(start.Pos, seq[seq.Count -1].Length, seq);
      }
       }
 }
コード例 #18
0
        public PixelwiseOrientationField(int[,] bytes, int blockSize)
        {
            BlockSize = blockSize;
            int maxX = bytes.GetUpperBound(1) + 1;
            int maxY = bytes.GetUpperBound(0) + 1;
            double[,] filterX = new double[,] { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
            double[,] filterY = new double[,] { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };
            double[,] doubleBytes = new double[maxY, maxX];
            for (int row = 0; row < maxY; row++)
            {
                for (int column = 0; column < maxX; column++)
                {
                    doubleBytes[row, column] = (double)bytes[row, column];
                }
            }
            // градиенты
            double[,] Gx = ConvolutionHelper.Convolve(doubleBytes, filterX);
            double[,] Gy = ConvolutionHelper.Convolve(doubleBytes, filterY);

            // рассчет направления для каждого пикселя
            _orientation = new double[maxY, maxX];
            // только один блок - персональный для каждого пикселя
            for (int centerRow = 0; centerRow < maxY; centerRow++)
            {
                for (int centerColumn = 0; centerColumn < maxX; centerColumn++)
                {
                    _block = new Block(_orientation, BlockSize, Gx, Gy, centerRow, centerColumn);
                }
            }
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: mjmoura/tesseractdotnet
        private static void DrawBlock(Graphics grph, Block block)
        {
            foreach (Paragraph para in block.Paragraphs)
                DrawParagraph(grph, para);

            block.Draw(grph);
        }
コード例 #20
0
		bool IsSwitchType2(Block switchBlock) {
			Local local = null;
			foreach (var instr in switchBlock.Instructions) {
				if (!instr.IsLdloc())
					continue;
				local = Instr.GetLocalVar(blocks.Locals, instr);
				break;
			}
			if (local == null)
				return false;

			foreach (var source in switchBlock.Sources) {
				var instrs = source.Instructions;
				for (int i = 1; i < instrs.Count; i++) {
					var ldci4 = instrs[i - 1];
					if (!ldci4.IsLdcI4())
						continue;
					var stloc = instrs[i];
					if (!stloc.IsStloc())
						continue;
					if (Instr.GetLocalVar(blocks.Locals, stloc) != local)
						continue;

					return true;
				}
			}

			return false;
		}
コード例 #21
0
ファイル: AudioManager.cs プロジェクト: Thanhvx-dth/Tanks
		public static void PlaySoundPlayer(AudioClip clip, bool loop, Block player,
			PlayerAudioType type)
		{
			if (clip == null)
				return;

			var audio = _instance.PlayerAudioSource;
			if (!audio.enabled)
				return;

			if (player == Block.Player1)
				_instance._player1 = type;
			else if (player == Block.Player2)
				_instance._player2 = type;

			if (type == PlayerAudioType.Idle)
				if (_instance._player1 == PlayerAudioType.Move ||
					_instance._player2 == PlayerAudioType.Move)
					return;

			if (audio.clip == clip && audio.isPlaying)
				return;

			audio.loop = loop;
			audio.clip = clip;
			audio.Play();
		}
コード例 #22
0
ファイル: World.cs プロジェクト: dk0x/newhope
		public void SetBlock (Block block, int x, int y, int z)
		{
				Chunk chunk = GetChunkWorldPos (x, z);
				if (chunk.generated) {
						chunk.SetBlockWorldPos (block, x, y, z);
				}
		}
コード例 #23
0
ファイル: BuildGreed.cs プロジェクト: RatushnenkoV/TheGame
    public void Build(Vector3 pos, int width, int height)
    {
        for (int i = -10; i < width + 10; i++)
        {
            for (int j = -10; j < height + 10; j++)
            {
                GameObject cell = Resources.Load("Cell", typeof(GameObject)) as GameObject;

                float x = i * dx, y = j * dy;
                if (j % 2 != 0) {
                    x += dx/2;
                }

                cell.transform.position = pos + new Vector3(x, y, 0);
                GameObject cellClone = Instantiate(cell);

                cellClone.GetComponent<CellPosition>().Set(i, j);
                Entity e;
                if (i < 0 || i >= width || j < 0 || j > height)
                    e = new Block(Block.BlockType.Water);
                else
                    e = Entity.getRandom();

                cellClone.GetComponent<CellContent>().SetEntity(e);

                if (i == 0 && j == 0)
                    Camera.main.GetComponent<CameraMotion>().minpos = cellClone.transform.position;
                if (i == width-1 && j == height-1)
                    Camera.main.GetComponent<CameraMotion>().maxpos = cellClone.transform.position;
            }
        }
    }
コード例 #24
0
ファイル: Mixin.cs プロジェクト: moonwa/jade.net
 internal Mixin(string name, string args, Block block, bool call)
 {
     Name = name;
     // Args = args;
     Block = block;
     // Call = call;
 }
コード例 #25
0
ファイル: Zombie.cs プロジェクト: CheeseSoftware/DynamicEEBot
 public Zombie(int x, int y)
     : base(x, y)
 {
     updateTimer.Start();
     lagTimer.Start();
     zombieBlock = Block.CreateBlock(0, xBlock, yBlock, 32, 0);
 }
コード例 #26
0
ファイル: WorldService.cs プロジェクト: KylerM/CupCake
        private WorldBlock[, ,] GetEmptyWorld(int sizeX, int sizeY, Block fillBlock, Block borderBlock)
        {
            var blockArray = new WorldBlock[2, sizeX, sizeY];

            int maxX = sizeX - 1;
            int maxY = sizeY - 1;

            // Fill the middle with GravityNothing blocks
            for (var l = Layer.Background; l >= Layer.Foreground; l += -1)
                for (int x = 0; x <= maxX; x++)
                    for (int y = 0; y <= maxY; y++)
                        NewBlock(blockArray, l, x, y, fillBlock);

            // Border drawing
            for (int y = 0; y <= maxY; y++)
            {
                blockArray[0, 0, y].SetBlock(borderBlock);
                blockArray[0, maxX, y].SetBlock(borderBlock);
            }

            for (int x = 0; x <= maxX; x++)
            {
                blockArray[0, x, 0].SetBlock(borderBlock);
                blockArray[0, x, maxY].SetBlock(borderBlock);
            }

            return blockArray;
        }
コード例 #27
0
ファイル: Physics.cs プロジェクト: venofox/AtomicCraft
 public static bool CanFloat(Block block)
 {
     switch (block)
     {
         case Block.Red:
         case Block.Orange:
         case Block.Yellow:
         case Block.Lime:
         case Block.Green:
         case Block.Teal:
         case Block.Aqua:
         case Block.Cyan:
         case Block.Blue:
         case Block.Indigo:
         case Block.Violet:
         case Block.Magenta:
         case Block.Pink:
         case Block.Black:
         case Block.Gray:
         case Block.White:
         case Block.Sponge:
         case Block.Wood:
         case Block.Leaves:
             return true;
         default:
             return false;
     }
 }
コード例 #28
0
		public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
		{
			switch (type) {
			case BranchingType.Exception:
			case BranchingType.Labeled:
			case BranchingType.Toplevel:
			case BranchingType.TryCatch:
				throw new InvalidOperationException ();

			case BranchingType.Switch:
				return new FlowBranchingBreakable (parent, type, SiblingType.SwitchSection, block, loc);

			case BranchingType.Block:
				return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);

			case BranchingType.Loop:
				return new FlowBranchingBreakable (parent, type, SiblingType.Conditional, block, loc);

			case BranchingType.Embedded:
				return new FlowBranchingContinuable (parent, type, SiblingType.Conditional, block, loc);

			default:
				return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
			}
		}
コード例 #29
0
ファイル: Player.cs プロジェクト: Cendrb/Arman
 public Player(Arman game, PositionInGrid positionInGrid, Texture2D texture, Block[,] gameArray, int oneBlockSize, int timeForMove, List<Entity> movableObjects, GameArea gameArea, Controls controls)
     : base(game, positionInGrid, texture, gameArray, oneBlockSize, timeForMove, movableObjects)
 {
     this.gameArea = gameArea;
     this.controls = controls;
     spawnPoint = positionInGrid;
 }
        /// <summary>
        /// Get formatting object for body element
        /// </summary>
        /// <param name="regionId"></param>
        /// <param name="tick"></param>
        /// <returns></returns>
        public override FormattingObject GetFormattingObject(TimeCode tick)
        {

            Block block = null;

            if (TemporallyActive(tick))
            {
                block = new Block(this);

                foreach (var child in Children)
                {
                    if (child is DivElement)
                    {
                        var fo = (child as DivElement).GetFormattingObject(tick);
                        if (fo != null)
                        {
                            fo.Parent = block;
                            block.Children.Add(fo);
                        }
                    }

                    if (child is SetElement)
                    {
                        var fo = ((child as SetElement).GetFormattingObject(tick)) as Animation;
                        if (fo != null)
                        {
                            // fo.Parent = block;
                            block.Animations.Add(fo);
                        }
                    }
                }
            }
            return block;
        }
コード例 #31
0
        public virtual void ExecuteBlock(ContextInformation context, TaskScheduler taskScheduler)
        {
            this.logger.LogTrace("()");

            Block            block = context.BlockResult.Block;
            ChainedBlock     index = context.BlockResult.ChainedBlock;
            DeploymentFlags  flags = context.Flags;
            UnspentOutputSet view  = context.Set;

            this.PerformanceCounter.AddProcessedBlocks(1);
            taskScheduler = taskScheduler ?? TaskScheduler.Default;
            if (flags.EnforceBIP30)
            {
                foreach (Transaction tx in block.Transactions)
                {
                    UnspentOutputs coins = view.AccessCoins(tx.GetHash());
                    if ((coins != null) && !coins.IsPrunable)
                    {
                        this.logger.LogTrace("(-)[BAD_TX_BIP_30]");
                        ConsensusErrors.BadTransactionBIP30.Throw();
                    }
                }
            }

            long  nSigOpsCost = 0;
            Money nFees       = Money.Zero;
            List <Task <bool> > checkInputs = new List <Task <bool> >();

            for (int txIndex = 0; txIndex < block.Transactions.Count; txIndex++)
            {
                this.PerformanceCounter.AddProcessedTransactions(1);
                Transaction tx = block.Transactions[txIndex];
                if (!tx.IsCoinBase && (!context.IsPoS || (context.IsPoS && !tx.IsCoinStake)))
                {
                    int[] prevheights;

                    if (!view.HaveInputs(tx))
                    {
                        this.logger.LogTrace("(-)[BAD_TX_NO_INPUT]");
                        ConsensusErrors.BadTransactionMissingInput.Throw();
                    }

                    prevheights = new int[tx.Inputs.Count];
                    // Check that transaction is BIP68 final.
                    // BIP68 lock checks (as opposed to nLockTime checks) must
                    // be in ConnectBlock because they require the UTXO set.
                    for (int j = 0; j < tx.Inputs.Count; j++)
                    {
                        prevheights[j] = (int)view.AccessCoins(tx.Inputs[j].PrevOut.Hash).Height;
                    }

                    if (!tx.CheckSequenceLocks(prevheights, index, flags.LockTimeFlags))
                    {
                        this.logger.LogTrace("(-)[BAD_TX_NON_FINAL]");
                        ConsensusErrors.BadTransactionNonFinal.Throw();
                    }
                }
                // GetTransactionSigOpCost counts 3 types of sigops:
                // * legacy (always),
                // * p2sh (when P2SH enabled in flags and excludes coinbase),
                // * witness (when witness enabled in flags and excludes coinbase).
                nSigOpsCost += this.GetTransactionSigOpCost(tx, view, flags);
                if (nSigOpsCost > this.consensusOptions.MaxBlockSigopsCost)
                {
                    ConsensusErrors.BadBlockSigOps.Throw();
                }

                // TODO: Simplify this condition.
                if (!tx.IsCoinBase && (!context.IsPoS || (context.IsPoS && !tx.IsCoinStake)))
                {
                    this.CheckInputs(tx, view, index.Height);
                    nFees += view.GetValueIn(tx) - tx.TotalOut;
                    Transaction localTx = tx;
                    PrecomputedTransactionData txData = new PrecomputedTransactionData(tx);
                    for (int inputIndex = 0; inputIndex < tx.Inputs.Count; inputIndex++)
                    {
                        this.PerformanceCounter.AddProcessedInputs(1);
                        TxIn  input          = tx.Inputs[inputIndex];
                        int   inputIndexCopy = inputIndex;
                        TxOut txout          = view.GetOutputFor(input);
                        var   checkInput     = new Task <bool>(() =>
                        {
                            if (this.UseConsensusLib)
                            {
                                Script.BitcoinConsensusError error;
                                return(Script.VerifyScriptConsensus(txout.ScriptPubKey, tx, (uint)inputIndexCopy, flags.ScriptFlags, out error));
                            }
                            else
                            {
                                var checker      = new TransactionChecker(tx, inputIndexCopy, txout.Value, txData);
                                var ctx          = new ScriptEvaluationContext();
                                ctx.ScriptVerify = flags.ScriptFlags;
                                return(ctx.VerifyScript(input.ScriptSig, txout.ScriptPubKey, checker));
                            }
                        });
                        checkInput.Start(taskScheduler);
                        checkInputs.Add(checkInput);
                    }
                }

                this.UpdateCoinView(context, tx);
            }

            this.CheckBlockReward(context, nFees, index, block);

            bool passed = checkInputs.All(c => c.GetAwaiter().GetResult());

            if (!passed)
            {
                this.logger.LogTrace("(-)[BAD_TX_SCRIPT]");
                ConsensusErrors.BadTransactionScriptError.Throw();
            }

            this.logger.LogTrace("(-)");
        }
コード例 #32
0
        public virtual void CheckBlockReward(ContextInformation context, Money nFees, ChainedBlock chainedBlock, Block block)
        {
            this.logger.LogTrace("()");

            Money blockReward = nFees + this.GetProofOfWorkReward(chainedBlock.Height);

            if (block.Transactions[0].TotalOut > blockReward)
            {
                this.logger.LogTrace("(-)[BAD_COINBASE_AMOUNT]");
                ConsensusErrors.BadCoinbaseAmount.Throw();
            }

            this.logger.LogTrace("(-)");
        }
コード例 #33
0
 protected override bool CanRewrite(Block block)
 {
     return(block.Type == BlockType.Expression && Parent != null);
 }
コード例 #34
0
 /// <summary>
 /// Add a physicsblock to the custom block list
 /// </summary>
 /// <param name="b"></param>
 public static void Add(PhysicsBlock b)
 {
     Block.Add(b);
 }
コード例 #35
0
        public virtual void ContextualCheckBlock(ContextInformation context)
        {
            this.logger.LogTrace("()");

            Block           block           = context.BlockResult.Block;
            DeploymentFlags deploymentFlags = context.Flags;

            int nHeight = context.BestBlock == null ? 0 : context.BestBlock.Height + 1;

            // Start enforcing BIP113 (Median Time Past) using versionbits logic.
            DateTimeOffset nLockTimeCutoff = deploymentFlags.LockTimeFlags.HasFlag(Transaction.LockTimeFlags.MedianTimePast) ?
                                             context.BestBlock.MedianTimePast :
                                             block.Header.BlockTime;

            // Check that all transactions are finalized.
            foreach (Transaction transaction in block.Transactions)
            {
                if (!transaction.IsFinal(nLockTimeCutoff, nHeight))
                {
                    this.logger.LogTrace("(-)[TX_NON_FINAL]");
                    ConsensusErrors.BadTransactionNonFinal.Throw();
                }
            }

            // Enforce rule that the coinbase starts with serialized block height.
            if (deploymentFlags.EnforceBIP34)
            {
                Script expect = new Script(Op.GetPushOp(nHeight));
                Script actual = block.Transactions[0].Inputs[0].ScriptSig;
                if (!this.StartWith(actual.ToBytes(true), expect.ToBytes(true)))
                {
                    this.logger.LogTrace("(-)[BAD_COINBASE_HEIGHT]");
                    ConsensusErrors.BadCoinbaseHeight.Throw();
                }
            }

            // Validation for witness commitments.
            // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
            //   coinbase (where 0x0000....0000 is used instead).
            // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
            // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
            // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
            //   {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
            //   multiple, the last one is used.
            bool fHaveWitness = false;

            if (deploymentFlags.ScriptFlags.HasFlag(ScriptVerify.Witness))
            {
                int commitpos = this.GetWitnessCommitmentIndex(block);
                if (commitpos != -1)
                {
                    bool    malleated   = false;
                    uint256 hashWitness = this.BlockWitnessMerkleRoot(block, ref malleated);

                    // The malleation check is ignored; as the transaction tree itself
                    // already does not permit it, it is impossible to trigger in the
                    // witness tree.
                    WitScript witness = block.Transactions[0].Inputs[0].WitScript;
                    if ((witness.PushCount != 1) || (witness.Pushes.First().Length != 32))
                    {
                        this.logger.LogTrace("(-)[BAD_WITNESS_NONCE_SIZE]");
                        ConsensusErrors.BadWitnessNonceSize.Throw();
                    }

                    byte[] hashed = new byte[64];
                    Buffer.BlockCopy(hashWitness.ToBytes(), 0, hashed, 0, 32);
                    Buffer.BlockCopy(witness.Pushes.First(), 0, hashed, 32, 32);
                    hashWitness = Hashes.Hash256(hashed);

                    if (!this.EqualsArray(hashWitness.ToBytes(), block.Transactions[0].Outputs[commitpos].ScriptPubKey.ToBytes(true).Skip(6).ToArray(), 32))
                    {
                        this.logger.LogTrace("(-)[WITNESS_MERKLE_MISMATCH]");
                        ConsensusErrors.BadWitnessMerkleMatch.Throw();
                    }

                    fHaveWitness = true;
                }
            }

            if (!fHaveWitness)
            {
                for (int i = 0; i < block.Transactions.Count; i++)
                {
                    if (block.Transactions[i].HasWitness)
                    {
                        this.logger.LogTrace("(-)[UNEXPECTED_WITNESS]");
                        ConsensusErrors.UnexpectedWitness.Throw();
                    }
                }
            }

            // After the coinbase witness nonce and commitment are verified,
            // we can check if the block weight passes (before we've checked the
            // coinbase witness, it would be possible for the weight to be too
            // large by filling up the coinbase witness, which doesn't change
            // the block hash, so we couldn't mark the block as permanently
            // failed).
            if (this.GetBlockWeight(block) > this.consensusOptions.MaxBlockWeight)
            {
                this.logger.LogTrace("(-)[BAD_BLOCK_WEIGHT]");
                ConsensusErrors.BadBlockWeight.Throw();
            }

            this.logger.LogTrace("(-)[OK]");
        }
コード例 #36
0
ファイル: PlayerBot.cs プロジェクト: xeons/MCSong
        public PlayerBot(string n, Level l, ushort x, ushort y, ushort z, byte rotx, byte roty)
        {
            name  = n;
            color = "&1";
            id    = FreeId();

            level = l;
            pos   = new ushort[3] {
                x, y, z
            }; rot = new byte[2] {
                rotx, roty
            };
            GlobalSpawn();

            foreach (Player p in Player.players)
            {
                if (p.level == level)
                {
                    Player.SendMessage(p, color + name + Server.DefaultColor + ", the bot, has been added.");
                }
            }

            botTimer.Elapsed += delegate
            {
                int    currentNum, foundNum = (32 * 75);
                Random rand = new Random();

                x = (ushort)Math.Round((decimal)pos[0] / (decimal)32);
                y = (ushort)((pos[1] - 33) / 32);
                z = (ushort)Math.Round((decimal)pos[2] / (decimal)32);

                if (kill)
                {
                    foreach (Player p in Player.players)
                    {
                        if ((ushort)(p.pos[0] / 32) == x)
                        {
                            if (Math.Abs((ushort)(p.pos[1] / 32) - y) < 2)
                            {
                                if ((ushort)(p.pos[2] / 32) == z)
                                {
                                    p.HandleDeath(Block.Zero);
                                }
                            }
                        }
                    }
                }

                if (Waypoints.Count < 1)
                {
                    if (hunt)
                    {
                        Player.players.ForEach(delegate(Player p)
                        {
                            if (p.level == level && !p.invincible)
                            {
                                currentNum = Math.Abs(p.pos[0] - pos[0]) + Math.Abs(p.pos[1] - pos[1]) + Math.Abs(p.pos[2] - pos[2]);
                                if (currentNum < foundNum)
                                {
                                    foundNum = currentNum;
                                    foundPos = p.pos;
                                    foundRot = p.rot;
                                    movement = true;
                                    rot[1]   = (byte)(255 - foundRot[1]);
                                    if (foundRot[0] < 128)
                                    {
                                        rot[0] = (byte)(foundRot[0] + 128);
                                    }
                                    else
                                    {
                                        rot[0] = (byte)(foundRot[0] - 128);
                                    }
                                }
                            }
                        });
                    }
                }
                else
                {
                    bool skip = false;
                    movement = false;

                    retry : switch (Waypoints[currentPoint].type)
                    {
                    case "walk" :
                        foundPos[0] = Waypoints[currentPoint].x;
                        foundPos[1] = Waypoints[currentPoint].y;
                        foundPos[2] = Waypoints[currentPoint].z;
                        movement    = true;

                        if ((ushort)(pos[0] / 32) == (ushort)(Waypoints[currentPoint].x / 32))
                        {
                            if ((ushort)(pos[2] / 32) == (ushort)(Waypoints[currentPoint].z / 32))
                            {
                                rot[0] = Waypoints[currentPoint].rotx;
                                rot[1] = Waypoints[currentPoint].roty;
                                currentPoint++;
                                movement = false;

                                if (currentPoint == Waypoints.Count)
                                {
                                    currentPoint = 0;
                                }
                                if (!skip)
                                {
                                    skip = true; goto retry;
                                }
                            }
                        }
                        break;

                    case "teleport":
                        pos[0] = Waypoints[currentPoint].x;
                        pos[1] = Waypoints[currentPoint].y;
                        pos[2] = Waypoints[currentPoint].z;
                        rot[0] = Waypoints[currentPoint].rotx;
                        rot[1] = Waypoints[currentPoint].roty;
                        currentPoint++;
                        if (currentPoint == Waypoints.Count)
                        {
                            currentPoint = 0;
                        }
                        return;

                    case "wait":
                        if (countdown != 0)
                        {
                            countdown--;
                            if (countdown == 0)
                            {
                                currentPoint++;
                                if (currentPoint == Waypoints.Count)
                                {
                                    currentPoint = 0;
                                }
                                if (!skip)
                                {
                                    skip = true; goto retry;
                                }
                            }
                        }
                        else
                        {
                            countdown = Waypoints[currentPoint].seconds;
                        }
                        return;

                    case "nod":
                        if (countdown != 0)
                        {
                            countdown--;

                            if (nodUp)
                            {
                                if (rot[1] > 32 && rot[1] < 128)
                                {
                                    nodUp = !nodUp;
                                }
                                else
                                {
                                    if (rot[1] + (byte)Waypoints[currentPoint].rotspeed > 255)
                                    {
                                        rot[1] = 0;
                                    }
                                    else
                                    {
                                        rot[1] += (byte)Waypoints[currentPoint].rotspeed;
                                    }
                                }
                            }
                            else
                            {
                                if (rot[1] > 128 && rot[1] < 224)
                                {
                                    nodUp = !nodUp;
                                }
                                else
                                {
                                    if (rot[1] - (byte)Waypoints[currentPoint].rotspeed < 0)
                                    {
                                        rot[1] = 255;
                                    }
                                    else
                                    {
                                        rot[1] -= (byte)Waypoints[currentPoint].rotspeed;
                                    }
                                }
                            }

                            if (countdown == 0)
                            {
                                currentPoint++;
                                if (currentPoint == Waypoints.Count)
                                {
                                    currentPoint = 0;
                                }
                                if (!skip)
                                {
                                    skip = true; goto retry;
                                }
                            }
                        }
                        else
                        {
                            countdown = Waypoints[currentPoint].seconds;
                        }
                        return;

                    case "spin":
                        if (countdown != 0)
                        {
                            countdown--;

                            if (rot[0] + (byte)Waypoints[currentPoint].rotspeed > 255)
                            {
                                rot[0] = 0;
                            }
                            else if (rot[0] + (byte)Waypoints[currentPoint].rotspeed < 0)
                            {
                                rot[0] = 255;
                            }
                            else
                            {
                                rot[0] += (byte)Waypoints[currentPoint].rotspeed;
                            }

                            if (countdown == 0)
                            {
                                currentPoint++;
                                if (currentPoint == Waypoints.Count)
                                {
                                    currentPoint = 0;
                                }
                                if (!skip)
                                {
                                    skip = true; goto retry;
                                }
                            }
                        }
                        else
                        {
                            countdown = Waypoints[currentPoint].seconds;
                        }
                        return;

                    case "speed":
                        movementSpeed = (int)Math.Round((decimal)((decimal)24 / (decimal)100 * (decimal)Waypoints[currentPoint].seconds));
                        if (movementSpeed == 0)
                        {
                            movementSpeed = 1;
                        }

                        currentPoint++;
                        if (currentPoint == Waypoints.Count)
                        {
                            currentPoint = 0;
                        }
                        if (!skip)
                        {
                            skip = true; goto retry;
                        }
                        return;

                    case "reset":
                        currentPoint = 0;
                        return;

                    case "remove":
                        removeBot();
                        return;

                    case "linkscript":
                        if (File.Exists("bots/" + Waypoints[currentPoint].newscript))
                        {
                            Command.all.Find("botset").Use(null, this.name + " " + Waypoints[currentPoint].newscript);
                            return;
                        }

                        currentPoint++;
                        if (currentPoint == Waypoints.Count)
                        {
                            currentPoint = 0;
                        }
                        if (!skip)
                        {
                            skip = true; goto retry;
                        }
                        return;

                    case "jump":
                        jumpTimer.Elapsed += delegate
                        {
                            currentjump++;
                            switch (currentjump)
                            {
                            case 1:
                            case 2: pos[1] += 24; break;

                            case 3: break;

                            case 4: pos[1] -= 24; break;

                            case 5: pos[1] -= 24; jumping = false; currentjump = 0; jumpTimer.Stop(); break;
                            }
                        };
                        jumpTimer.Start();

                        currentPoint++;
                        if (currentPoint == Waypoints.Count)
                        {
                            currentPoint = 0;
                        }
                        if (!skip)
                        {
                            skip = true; goto retry;
                        }
                        break;
                    }

                    if (currentPoint == Waypoints.Count)
                    {
                        currentPoint = 0;
                    }
                }

                if (!movement)
                {
                    if (rot[0] < 245)
                    {
                        rot[0] += 8;
                    }
                    else
                    {
                        rot[0] = 0;
                    }

                    if (rot[1] > 32 && rot[1] < 64)
                    {
                        rot[1] = 224;
                    }
                    else if (rot[1] > 250)
                    {
                        rot[1] = 0;
                    }
                    else
                    {
                        rot[1] += 4;
                    }
                }
            };

            botTimer.Start();

            moveTimer.Elapsed += delegate
            {
                moveTimer.Interval = Server.updateTimer.Interval / movementSpeed;
                if (!movement)
                {
                    return;
                }
                int newNum; Random rand = new Random();

                if ((pos[1] - 19) % 32 != 0 && !jumping)
                {
                    pos[1] = (ushort)((pos[1] + 19) - (pos[1] % 32));
                }

                x = (ushort)Math.Round((decimal)(pos[0] - 16) / (decimal)32);
                y = (ushort)((pos[1] - 64) / 32);
                z = (ushort)Math.Round((decimal)(pos[2] - 16) / (decimal)32);

                byte b = Block.Convert(level.GetTile(x, y, z));
                byte b1, b2, b3;//, b4;

                if (Block.Walkthrough(b) && !jumping)
                {
                    pos[1] = (ushort)(pos[1] - 32);
                }

                y = (ushort)((pos[1] - 64) / 32);   //Block below feet

                newNum = level.PosToInt((ushort)(x + Math.Sign(foundPos[0] - pos[0])), y, (ushort)(z + Math.Sign(foundPos[2] - pos[2])));
                b      = Block.Convert(level.GetTile(newNum));
                b1     = Block.Convert(level.GetTile(level.IntOffset(newNum, 0, 1, 0)));
                b2     = Block.Convert(level.GetTile(level.IntOffset(newNum, 0, 2, 0)));
                b3     = Block.Convert(level.GetTile(level.IntOffset(newNum, 0, 3, 0)));

                if (Block.Walkthrough(b2) && Block.Walkthrough(b3) && !Block.Walkthrough(b1))
                {     //Get ready to go up step
                    pos[0] += (ushort)Math.Sign(foundPos[0] - pos[0]);
                    pos[1] += (ushort)32;
                    pos[2] += (ushort)Math.Sign(foundPos[2] - pos[2]);
                }
                else if (Block.Walkthrough(b1) && Block.Walkthrough(b2))
                {                        //Stay on current level
                    pos[0] += (ushort)Math.Sign(foundPos[0] - pos[0]);
                    pos[2] += (ushort)Math.Sign(foundPos[2] - pos[2]);
                }
                else if (Block.Walkthrough(b) && Block.Walkthrough(b1))
                {                         //Drop a level
                    pos[0] += (ushort)Math.Sign(foundPos[0] - pos[0]);
                    pos[1] -= (ushort)32;
                    pos[2] += (ushort)Math.Sign(foundPos[2] - pos[2]);
                }

                x = (ushort)Math.Round((decimal)(pos[0] - 16) / (decimal)32);
                y = (ushort)((pos[1] - 64) / 32);
                z = (ushort)Math.Round((decimal)(pos[2] - 16) / (decimal)32);

                b1 = Block.Convert(level.GetTile(x, (ushort)(y + 1), z));
                b2 = Block.Convert(level.GetTile(x, (ushort)(y + 2), z));
                b3 = Block.Convert(level.GetTile(x, y, z));

                /*
                 * if ((ushort)(foundPos[1] / 32) > y) {
                 *  if (b1 == Block.water || b1 == Block.waterstill || b1 == Block.lava || b1 == Block.lavastill) {
                 *      if (Block.Walkthrough(b2)) {
                 *          pos[1] = (ushort)(pos[1] + (Math.Sign(foundPos[1] - pos[1])));
                 *      }
                 *  } else if (b2 == Block.water || b2 == Block.waterstill || b2 == Block.lava || b2 == Block.lavastill) {
                 *      pos[1] = (ushort)(pos[1] + (Math.Sign(foundPos[1] - pos[1])));
                 *  }
                 * } else if ((ushort)(foundPos[1] / 32) < y) {
                 *  if (b3 == Block.water || b3 == Block.waterstill || b3 == Block.lava || b3 == Block.lavastill) {
                 *      pos[1] = (ushort)(pos[1] + (Math.Sign(foundPos[1] - pos[1])));
                 *  }
                 * }*/
            };
            moveTimer.Start();
        }
コード例 #37
0
        public void PersistBlock(Block blockToPersist, bool shouldHandleTriplesBeforePersisting)
        {
            HashSet <Triple> blockHeaderTriplesToPersist = new HashSet <Triple>();

            BlockHeader  blockHeader  = blockToPersist.BlockHeader;
            BlockContent blockContent = blockToPersist.BlockContent;

            Iri blockIri = new Iri(blockToPersist.BlockIri);

            blockHeaderTriplesToPersist.Add(new Triple(
                                                blockIri,
                                                RDF.type,
                                                GCO.Block
                                                ));
            if (blockToPersist.IsGenesisBlock)
            {
                blockHeaderTriplesToPersist.Add(new Triple(
                                                    blockIri,
                                                    RDF.type,
                                                    GCO.GenesisBlock
                                                    ));
            }
            blockHeaderTriplesToPersist.Add(new Triple(
                                                blockIri,
                                                RDF.type,
                                                OWL.NamedIndividual
                                                ));
            blockHeaderTriplesToPersist.Add(new Triple(
                                                blockIri,
                                                GCO.hasDataGraphIri,
                                                new Literal(blockHeader.DataGraphIri, XMLSchema.AnyURI)
                                                ));
            blockHeaderTriplesToPersist.Add(new Triple(
                                                blockIri,
                                                GCO.hasDataHash,
                                                new Literal(blockHeader.DataHash)
                                                ));
            blockHeaderTriplesToPersist.Add(new Triple(
                                                blockIri,
                                                GCO.hasHash,
                                                new Literal(blockHeader.Hash)
                                                ));
            blockHeaderTriplesToPersist.Add(new Triple(
                                                blockIri,
                                                GCO.hasIndex,
                                                new Literal(blockHeader.Index, XMLSchema.Decimal)
                                                ));
            blockHeaderTriplesToPersist.Add(new Triple(
                                                blockIri,
                                                GCO.hasPreviousBlock,
                                                new Iri(blockHeader.PreviousBlock)
                                                ));
            blockHeaderTriplesToPersist.Add(new Triple(
                                                blockIri,
                                                GCO.hasPreviousHash,
                                                new Literal(blockHeader.PreviousHash)
                                                ));
            blockHeaderTriplesToPersist.Add(new Triple(
                                                blockIri,
                                                GCO.hasTimeStamp,
                                                new Literal(blockHeader.Timestamp, XMLSchema.Decimal)
                                                ));
            HashSet <Triple> blockContentTriplesToPersist;

            if (shouldHandleTriplesBeforePersisting)
            {
                blockContentTriplesToPersist = _hashingService.HandleTriplesBeforePersisting(blockContent.Triples);
            }
            else
            {
                blockContentTriplesToPersist = blockContent.Triples;
            }
            // TODO: The following invocations should be in the same transaction.
            _repository.PersistTriples(_chainGraphIri, blockHeaderTriplesToPersist);
            _repository.PersistTriples(blockContent.DataGraphIri, blockContentTriplesToPersist);
        }
コード例 #38
0
        public virtual void CheckBlock(ContextInformation context)
        {
            this.logger.LogTrace("()");

            Block block = context.BlockResult.Block;

            bool    mutated         = false;
            uint256 hashMerkleRoot2 = this.BlockMerkleRoot(block, ref mutated);

            if (context.CheckMerkleRoot && (block.Header.HashMerkleRoot != hashMerkleRoot2))
            {
                this.logger.LogTrace("(-)[BAD_MERKLE_ROOT]");
                ConsensusErrors.BadMerkleRoot.Throw();
            }

            // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
            // of transactions in a block without affecting the merkle root of a block,
            // while still invalidating it.
            if (mutated)
            {
                this.logger.LogTrace("(-)[BAD_TX_DUP]");
                ConsensusErrors.BadTransactionDuplicate.Throw();
            }

            // All potential-corruption validation must be done before we do any
            // transaction validation, as otherwise we may mark the header as invalid
            // because we receive the wrong transactions for it.
            // Note that witness malleability is checked in ContextualCheckBlock, so no
            // checks that use witness data may be performed here.

            // Size limits.
            if ((block.Transactions.Count == 0) || (block.Transactions.Count > this.consensusOptions.MaxBlockBaseSize) || (this.GetSize(block, TransactionOptions.None) > this.consensusOptions.MaxBlockBaseSize))
            {
                this.logger.LogTrace("(-)[BAD_BLOCK_LEN]");
                ConsensusErrors.BadBlockLength.Throw();
            }

            // First transaction must be coinbase, the rest must not be
            if ((block.Transactions.Count == 0) || !block.Transactions[0].IsCoinBase)
            {
                this.logger.LogTrace("(-)[NO_COINBASE]");
                ConsensusErrors.BadCoinbaseMissing.Throw();
            }

            for (int i = 1; i < block.Transactions.Count; i++)
            {
                if (block.Transactions[i].IsCoinBase)
                {
                    this.logger.LogTrace("(-)[MULTIPLE_COINBASE]");
                    ConsensusErrors.BadMultipleCoinbase.Throw();
                }
            }

            // Check transactions
            foreach (Transaction tx in block.Transactions)
            {
                this.CheckTransaction(tx);
            }

            long nSigOps = 0;

            foreach (Transaction tx in block.Transactions)
            {
                nSigOps += this.GetLegacySigOpCount(tx);
            }

            if ((nSigOps * this.consensusOptions.WitnessScaleFactor) > this.consensusOptions.MaxBlockSigopsCost)
            {
                this.logger.LogTrace("(-)[BAD_BLOCK_SIGOPS]");
                ConsensusErrors.BadBlockSigOps.Throw();
            }

            this.logger.LogTrace("(-)[OK]");
        }