static List<OpCodeHandlerInfo> ReadV1(BinaryReader reader) { int numHandlers = reader.ReadInt32(); var list = new List<OpCodeHandlerInfo>(numHandlers); for (int i = 0; i < numHandlers; i++) { var typeCode = (HandlerTypeCode)reader.ReadInt32(); int numInfos = reader.ReadInt32(); var sigInfo = new MethodSigInfo(); for (int j = 0; j < numInfos; j++) { var info = new BlockInfo(); info.Hash = reader.ReadBytes(reader.ReadInt32()); if (info.Hash.Length == 0) info.Hash = null; int numTargets = reader.ReadInt32(); for (int k = 0; k < numTargets; k++) info.Targets.Add(reader.ReadInt32()); sigInfo.BlockInfos.Add(info); } list.Add(new OpCodeHandlerInfo(typeCode, sigInfo)); } return list; }
/// <summary> /// ブロック生成 /// </summary> /// <param name="xPosition"></param> /// <param name="yPosition"></param> private GameObject CreateBlock(BlockInfo info) { GameObject blockPrefab = Resources.Load("Prefabs/Core/Block_new") as GameObject; GameObject blockInstance = (GameObject)Instantiate(blockPrefab, info.Position, transform.rotation); // Sprite Setting Block block = blockInstance.GetComponent<Block>(); //Sprite spriteResource = sprites[Random.Range(0, sprites.Keys.Count)]; Sprite spriteResource = sprites[Random.Range(0, 3)]; blockInstance.GetComponent<SpriteRenderer>().sprite = spriteResource; block.blockName = spriteResource.name; // Effect Setting GameObject explosionEffect = Resources.Load("Prefabs/Fx/MagicEffects/prefab/skillAttack2") as GameObject; block.DestroyEffect = explosionEffect.GetComponent<ParticleSystem>(); info.reSpawnDelay = 1.5f; info.isChecked = false; block.info = info; blocks.Add(blockInstance); blocksArray[info.Coordinate.X, info.Coordinate.Y] = blockInstance; return blockInstance; }
protected override void DrawPlayerModel( Player p ) { graphics.Texturing = true; graphics.AlphaTest = true; block = Byte.Parse( p.ModelName ); if( block == 0 ) { blockHeight = 1; return; } graphics.BindTexture( game.TerrainAtlas.TexId ); blockHeight = game.BlockInfo.Height[block]; atlas = game.TerrainAtlas; BlockInfo = game.BlockInfo; if( BlockInfo.IsSprite[block] ) { XQuad( 0f, TileSide.Right, false ); ZQuad( 0f, TileSide.Back, false ); } else { YQuad( blockHeight, TileSide.Top ); XQuad( -0.5f, TileSide.Right, false ); XQuad( 0.5f, TileSide.Left, true ); ZQuad( -0.5f, TileSide.Front, true ); ZQuad( 0.5f, TileSide.Back, false ); YQuad( 0f, TileSide.Bottom ); } }
public Physics( Game game ) { this.game = game; map = game.Map; info = game.BlockInfo; game.Events.OnNewMapLoaded += ResetMap; }
public void Init( Game game ) { this.game = game; map = game.World; graphics = game.Graphics; info = game.BlockInfo; weatherVb = graphics.CreateDynamicVb( VertexFormat.P3fT2fC4b, vertices.Length ); }
int GetDraw( BlockInfo info, byte id) { if( info.IsTranslucent[id] ) return 3; if( info.IsAir[id] ) return 4; if( info.IsTransparent[id] ) return info.CullWithNeighbours[id] ? 1 : 2; return 0; }
public Physics( Game game ) { this.game = game; map = game.World; info = game.BlockInfo; game.WorldEvents.OnNewMapLoaded += ResetMap; enabled = Options.GetBool( OptionsKey.SingleplayerPhysics, true ); }
public static void BeginBlock( Mobile m, int bonus ) { EndBlock( m ); BlockInfo info = new BlockInfo( m, bonus ); info.m_Timer = new InternalTimer( m ); m_Table[m] = info; }
public int CalcMaxUsedRow( TerrainAtlas2D atlas2D, BlockInfo info ) { int maxVerSize = Math.Min( 4096, graphics.MaxTextureDimensions ); int verElements = maxVerSize / atlas2D.elementSize; int totalElements = GetMaxUsedRow( info.textures ) * TerrainAtlas2D.ElementsPerRow; Utils.LogDebug( "Used atlases: " + Utils.CeilDiv( totalElements, verElements ) ); return Utils.CeilDiv( totalElements, verElements ); }
static BlockInfoM() { // Creating a BlockInfo (or BlockInfoEx) will also automatically register the // block ID, lighting, and opacity data with internal tables in the BlockInfo // static class, making them available to GetInfo() calls. LightSensor = new BlockInfo(BlockTypeM.LIGHT_SENSOR, "Light Sensor").SetOpacity(0).SetState(BlockState.NONSOLID); // You can redefine already-registered blocks at any time by creating a new // BlockInfo object with the given ID. }
public LocalBlockInfo ToLocal(BlockInfo block) { FsFile<AbsPath> descriptor = (FsFile<AbsPath>) GetFile(block.RelFilePath); long position = ExchUtils.GetInFilePosition(block); int currentBlockSize = (int) (descriptor.Size - position); if (currentBlockSize > ExchUtils.StandardBlockSize) { throw new Exception("blockSize == " + currentBlockSize); } // var path = Path.ToFull(descriptor.Path); return new LocalBlockInfo(descriptor.Path, position, currentBlockSize); }
internal static void SetBlockDraw( BlockInfo info, byte block, byte blockDraw ) { if( blockDraw == 1 ) { info.IsTransparent[block] = true; } else if( blockDraw == 2 ) { info.IsTransparent[block] = true; info.CullWithNeighbours[block] = false; } else if( blockDraw == 3 ) { info.IsTranslucent[block] = true; } else if( blockDraw == 4 ) { info.IsTransparent[block] = true; info.IsAir[block] = true; } if( info.IsOpaque[block] ) info.IsOpaque[block] = blockDraw == 0; }
private BoundingBox? BoundingBox(BlockInfo info) { switch (info.Metadata) { case (byte)Orientation.FacingNorth: return new BoundingBox(new Vector3(0,0,1-0.125), Vector3.One); case (byte)Orientation.FacingSouth: return new BoundingBox(Vector3.Zero, new Vector3(1,1,0.125)); case (byte)Orientation.FacingWest: return new BoundingBox(new Vector3(1-0.125,0,0), Vector3.One); case (byte)Orientation.FacingEast: return new BoundingBox(Vector3.Zero, new Vector3(0.125,1,1)); default: return null; } }
public void DumpBlocks(uint offset, int chunk) { uint magic = GetUInt(offset); uint bsize = GetUInt(offset + 4); uint compressed = GetUInt(offset + 8); uint uncompressed = GetUInt(offset + 12); uint blockc = (uncompressed % bsize == 0) ? uncompressed / bsize : uncompressed / bsize + 1; List<BlockInfo> blocks = new List<BlockInfo>(); for (int i = 0; i < blockc; i++) { BlockInfo b = new BlockInfo(); b.csize = GetUInt((uint)(offset + 16 + i * 8)); b.ucsize = GetUInt((uint)(offset + 20 + i * 8)); //println("\t" + i + " Compressed: 0x" + b.csize.ToString("X4") + " Uncompressed: 0x" + b.ucsize.ToString("X4")); blocks.Add(b); } uint off2 = offset + 16 + blockc * 8; string loc = Path.GetDirectoryName(Application.ExecutablePath); MemoryStream m = new MemoryStream(); for (int i = 0; i < blockc; i++) { if (File.Exists(loc + "\\exec\\script.bms")) File.Delete(loc + "\\exec\\script.bms"); if (File.Exists(loc + "\\exec\\temp.bin")) File.Delete(loc + "\\exec\\temp.bin"); FileStream fs = new FileStream(loc + "\\exec\\temp.bin", FileMode.Create, FileAccess.Write); fs.Write(buffer, (int)off2, (int)blocks[i].csize); fs.Close(); string[] lines = { "ComType lzo1x", "Clog \"out.bin\" 0 0x" + blocks[i].csize.ToString("X4") + " 0x" + blocks[i].ucsize.ToString("X4") }; System.IO.File.WriteAllLines(loc + "\\exec\\script.bms", lines); RunShell(loc + "\\exec\\quickbms.exe", "-o script.bms temp.bin"); if (File.Exists(loc + "\\exec\\out.bin")) { fs = new FileStream(loc + "\\exec\\out.bin", FileMode.Open, FileAccess.Read); byte[] buffout = new byte[(int)fs.Length]; int count; int sum = 0; while ((count = fs.Read(buffout, sum, (int)fs.Length - sum)) > 0) sum += count; fs.Close(); m.Write(buffout, 0, (int)buffout.Length); } off2 += blocks[i].csize; } temp.Write(m.ToArray(), 0, (int)m.Length); }
public ChunkUpdater( Game game, MapRenderer renderer ) { this.game = game; this.renderer = renderer; info = game.BlockInfo; builder = new ChunkMeshBuilder( game ); api = game.Graphics; game.Events.TerrainAtlasChanged += TerrainAtlasChanged; game.WorldEvents.OnNewMap += OnNewMap; game.WorldEvents.OnNewMapLoaded += OnNewMapLoaded; game.WorldEvents.EnvVariableChanged += EnvVariableChanged; game.Events.BlockDefinitionChanged += BlockDefinitionChanged; game.Events.ViewDistanceChanged += ViewDistanceChanged; game.Events.ProjectionChanged += ProjectionChanged; }
protected override void DrawPlayerModel( Player p ) { // TODO: using 'is' is ugly, but means we can avoid creating // a string every single time held block changes. if( p is FakePlayer ) { Vector3I eyePos = Vector3I.Floor( game.LocalPlayer.EyePosition ); FastColour baseCol = game.Map.IsLit( eyePos ) ? game.Map.Sunlight : game.Map.Shadowlight; col = FastColour.Scale( baseCol, 0.8f ); block = ((FakePlayer)p).Block; } else { block = Byte.Parse( p.ModelName ); } if( block == 0 ) { blockHeight = 1; return; } graphics.BindTexture( game.TerrainAtlas.TexId ); blockHeight = game.BlockInfo.Height[block]; atlas = game.TerrainAtlas; BlockInfo = game.BlockInfo; if( BlockInfo.IsSprite[block] ) { float offset = TerrainAtlas2D.invElementSize / 2; XQuad( 0f, TileSide.Right, -scale, 0, 0, -offset, false ); ZQuad( 0f, TileSide.Back, 0, scale, offset, 0, false ); XQuad( 0f, TileSide.Right, 0, scale, offset, 0, false ); ZQuad( 0f, TileSide.Back, -scale, 0, 0, -offset, false ); } else { YQuad( 0f, TileSide.Bottom ); XQuad( scale, TileSide.Left, -scale, scale, 0, 0, true ); ZQuad( -scale, TileSide.Front, -scale, scale, 0, 0, true ); ZQuad( scale, TileSide.Back, -scale, scale, 0, 0, true ); YQuad( blockHeight, TileSide.Top ); XQuad( -scale, TileSide.Right, -scale, scale, 0, 0, true ); } graphics.UpdateDynamicIndexedVb( DrawMode.Triangles, cache.vb, cache.vertices, index, index * 6 / 4 ); }
public List<BaseBlock> Sort() { if (validBlocks.Count == 0) return new List<BaseBlock>(); if (skipFirstBlock) firstBlock = validBlocks[0]; foreach (var block in validBlocks) { if (block != firstBlock) blockToInfo[block] = new BlockInfo(block); } sorted = new List<BaseBlock>(validBlocks.Count); var finalList = new List<BaseBlock>(validBlocks.Count); if (firstBlock is Block) { foreach (var target in GetTargets(firstBlock)) { Visit(target); finalList.AddRange(sorted); sorted.Clear(); } } foreach (var bb in validBlocks) { Visit(bb); finalList.AddRange(sorted); sorted.Clear(); } if (stack.Count > 0) throw new ApplicationException("Stack isn't empty"); if (firstBlock != null) finalList.Insert(0, firstBlock); else if (validBlocks[0] != finalList[0]) { // Make sure the original first block is first int index = finalList.IndexOf(validBlocks[0]); finalList.RemoveAt(index); finalList.Insert(0, validBlocks[0]); } return finalList; }
public ChunkUpdater( Game game, MapRenderer renderer ) { this.game = game; this.renderer = renderer; info = game.BlockInfo; renderer._1DUsed = game.TerrainAtlas1D.CalcMaxUsedRow( game.TerrainAtlas, info ); renderer.totalUsed = new int[game.TerrainAtlas1D.TexIds.Length]; RecalcBooleans( true ); builder = new ChunkMeshBuilder( game ); api = game.Graphics; elementsPerBitmap = game.TerrainAtlas1D.elementsPerBitmap; game.Events.TerrainAtlasChanged += TerrainAtlasChanged; game.WorldEvents.OnNewMap += OnNewMap; game.WorldEvents.OnNewMapLoaded += OnNewMapLoaded; game.WorldEvents.EnvVariableChanged += EnvVariableChanged; game.Events.BlockDefinitionChanged += BlockDefinitionChanged; game.Events.ViewDistanceChanged += ViewDistanceChanged; game.Events.ProjectionChanged += ProjectionChanged; }
public UnbufferedFileStream(string path, FileMode mode, FileAccess access, FileShare share, FileOptions options, BufferManager bufferManager) { _path = path; _bufferManager = bufferManager; { const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000; _stream = new FileStream(path, mode, access, share, 8, options | FileFlagNoBuffering); } _blockInfo = new BlockInfo(); { _blockInfo.IsUpdated = false; _blockInfo.Position = -1; _blockInfo.Offset = 0; _blockInfo.Count = 0; _blockInfo.Value = _bufferManager.TakeBuffer(SectorSize); } _position = _stream.Position; _length = _stream.Length; }
public void LoadMaps(List <ushort> toload = null) { MapsByID = new Dictionary <ushort, MapInfo>(); MapsByName = new Dictionary <string, MapInfo>(); DataTable mapDataInf = null; DataTable linktableData = null; DataTable shineNpcData = null; using (var dbClient = Program.DatabaseManager.GetClient()) { mapDataInf = dbClient.ReadDataTable("SELECT *FROM mapinfo"); linktableData = dbClient.ReadDataTable("SELECT *FROM LinkTable"); shineNpcData = dbClient.ReadDataTable("SELECT *FROM ShineNpc"); } if (mapDataInf != null) { foreach (DataRow row in mapDataInf.Rows) { var info = MapInfo.Load(row); info.NPCs = new List <ShineNpc>(); if (MapsByID.ContainsKey(info.ID)) { Log.WriteLine(LogLevel.Debug, "Duplicate map ID {0} ({1})", info.ID, info.FullName); MapsByID.Remove(info.ID); MapsByName.Remove(info.ShortName); } if (toload == null || toload.Contains(info.ID)) { MapsByID.Add(info.ID, info); MapsByName.Add(info.ShortName, info); } } } Blocks = new Dictionary <ushort, BlockInfo>(); foreach (var map in MapsByID.Values) { DataTable blockData = null; using (var dbClient = Program.DatabaseManager.GetClient()) { blockData = dbClient.ReadDataTable("SELECT *FROM blockinfo WHERE MapID='" + map.ID + "'"); } if (blockData != null) { if (blockData.Rows.Count > 0) { foreach (DataRow row in blockData.Rows) { var info = new BlockInfo(row, map.ID); Blocks.Add(map.ID, info); } } else { Log.WriteLine(LogLevel.Warn, "No BlockInfo for Map {0}", map.ShortName); } } } NpcLinkTable = new Dictionary <string, LinkTable>(); if (linktableData != null) { foreach (DataRow row in linktableData.Rows) { var link = LinkTable.Load(row); if (Program.IsLoaded(GetMapidFromMapShortName(link.MapClient))) { NpcLinkTable.Add(link.argument, link); } } } if (shineNpcData != null) { foreach (DataRow row in shineNpcData.Rows) { var npc = ShineNpc.Load(row); MapInfo mi = null; if (Program.IsLoaded(GetMapidFromMapShortName(npc.Map)) && MapsByName.TryGetValue(npc.Map, out mi)) { mi.NPCs.Add(npc); } } } Log.WriteLine(LogLevel.Info, "Loaded {0} maps.", MapsByID.Count); }
private BoundingBox? BoundingBox(BlockInfo info) { return null; }
public AllocationResult RunPass( ControlFlowGraph cfg, StackAllocator stackAlloc, RegisterMasks regMasks) { int intUsedRegisters = 0; int vecUsedRegisters = 0; int intFreeRegisters = regMasks.IntAvailableRegisters; int vecFreeRegisters = regMasks.VecAvailableRegisters; BlockInfo[] blockInfo = new BlockInfo[cfg.Blocks.Count]; List <LocalInfo> locInfo = new List <LocalInfo>(); for (int index = cfg.PostOrderBlocks.Length - 1; index >= 0; index--) { BasicBlock block = cfg.PostOrderBlocks[index]; int intFixedRegisters = 0; int vecFixedRegisters = 0; bool hasCall = false; for (Node node = block.Operations.First; node != null; node = node.ListNext) { if (node is Operation operation && operation.Instruction == Instruction.Call) { hasCall = true; } for (int srcIndex = 0; srcIndex < node.SourcesCount; srcIndex++) { Operand source = node.GetSource(srcIndex); if (source.Kind == OperandKind.LocalVariable) { locInfo[source.AsInt32() - 1].SetBlockIndex(block.Index); } else if (source.Kind == OperandKind.Memory) { MemoryOperand memOp = (MemoryOperand)source; if (memOp.BaseAddress != null) { locInfo[memOp.BaseAddress.AsInt32() - 1].SetBlockIndex(block.Index); } if (memOp.Index != null) { locInfo[memOp.Index.AsInt32() - 1].SetBlockIndex(block.Index); } } } for (int dstIndex = 0; dstIndex < node.DestinationsCount; dstIndex++) { Operand dest = node.GetDestination(dstIndex); if (dest.Kind == OperandKind.LocalVariable) { LocalInfo info; if (dest.Value != 0) { info = locInfo[dest.AsInt32() - 1]; } else { dest.NumberLocal(locInfo.Count + 1); info = new LocalInfo(dest.Type, UsesCount(dest)); locInfo.Add(info); } info.SetBlockIndex(block.Index); } else if (dest.Kind == OperandKind.Register) { if (dest.Type.IsInteger()) { intFixedRegisters |= 1 << dest.GetRegister().Index; } else { vecFixedRegisters |= 1 << dest.GetRegister().Index; } } } } blockInfo[block.Index] = new BlockInfo(hasCall, intFixedRegisters, vecFixedRegisters); } int sequence = 0; for (int index = cfg.PostOrderBlocks.Length - 1; index >= 0; index--) { BasicBlock block = cfg.PostOrderBlocks[index]; BlockInfo blkInfo = blockInfo[block.Index]; int intLocalFreeRegisters = intFreeRegisters & ~blkInfo.IntFixedRegisters; int vecLocalFreeRegisters = vecFreeRegisters & ~blkInfo.VecFixedRegisters; int intCallerSavedRegisters = blkInfo.HasCall ? regMasks.IntCallerSavedRegisters : 0; int vecCallerSavedRegisters = blkInfo.HasCall ? regMasks.VecCallerSavedRegisters : 0; int intSpillTempRegisters = SelectSpillTemps( intCallerSavedRegisters & ~blkInfo.IntFixedRegisters, intLocalFreeRegisters); int vecSpillTempRegisters = SelectSpillTemps( vecCallerSavedRegisters & ~blkInfo.VecFixedRegisters, vecLocalFreeRegisters); intLocalFreeRegisters &= ~(intSpillTempRegisters | intCallerSavedRegisters); vecLocalFreeRegisters &= ~(vecSpillTempRegisters | vecCallerSavedRegisters); for (Node node = block.Operations.First; node != null; node = node.ListNext) { int intLocalUse = 0; int vecLocalUse = 0; void AllocateRegister(Operand source, MemoryOperand memOp, int srcIndex) { LocalInfo info = locInfo[source.AsInt32() - 1]; info.UseCount++; Debug.Assert(info.UseCount <= info.Uses); if (info.Register != -1) { Operand reg = Register(info.Register, source.Type.ToRegisterType(), source.Type); if (memOp != null) { if (srcIndex == 0) { memOp.BaseAddress = reg; } else /* if (srcIndex == 1) */ { memOp.Index = reg; } } else { node.SetSource(srcIndex, reg); } if (info.UseCount == info.Uses && !info.PreAllocated) { if (source.Type.IsInteger()) { intLocalFreeRegisters |= 1 << info.Register; } else { vecLocalFreeRegisters |= 1 << info.Register; } } } else { Operand temp = info.Temp; if (temp == null || info.Sequence != sequence) { temp = source.Type.IsInteger() ? GetSpillTemp(source, intSpillTempRegisters, ref intLocalUse) : GetSpillTemp(source, vecSpillTempRegisters, ref vecLocalUse); info.Sequence = sequence; info.Temp = temp; } if (memOp != null) { if (srcIndex == 0) { memOp.BaseAddress = temp; } else /* if (srcIndex == 1) */ { memOp.Index = temp; } } else { node.SetSource(srcIndex, temp); } Operation fillOp = new Operation(Instruction.Fill, temp, Const(info.SpillOffset)); block.Operations.AddBefore(node, fillOp); } } for (int srcIndex = 0; srcIndex < node.SourcesCount; srcIndex++) { Operand source = node.GetSource(srcIndex); if (source.Kind == OperandKind.LocalVariable) { AllocateRegister(source, null, srcIndex); } else if (source.Kind == OperandKind.Memory) { MemoryOperand memOp = (MemoryOperand)source; if (memOp.BaseAddress != null) { AllocateRegister(memOp.BaseAddress, memOp, 0); } if (memOp.Index != null) { AllocateRegister(memOp.Index, memOp, 1); } } } int intLocalAsg = 0; int vecLocalAsg = 0; for (int dstIndex = 0; dstIndex < node.DestinationsCount; dstIndex++) { Operand dest = node.GetDestination(dstIndex); if (dest.Kind != OperandKind.LocalVariable) { continue; } LocalInfo info = locInfo[dest.AsInt32() - 1]; if (info.UseCount == 0 && !info.PreAllocated) { int mask = dest.Type.IsInteger() ? intLocalFreeRegisters : vecLocalFreeRegisters; if (info.IsBlockLocal && mask != 0) { int selectedReg = BitUtils.LowestBitSet(mask); info.Register = selectedReg; if (dest.Type.IsInteger()) { intLocalFreeRegisters &= ~(1 << selectedReg); intUsedRegisters |= 1 << selectedReg; } else { vecLocalFreeRegisters &= ~(1 << selectedReg); vecUsedRegisters |= 1 << selectedReg; } } else { info.Register = -1; info.SpillOffset = stackAlloc.Allocate(dest.Type.GetSizeInBytes()); } } info.UseCount++; Debug.Assert(info.UseCount <= info.Uses); if (info.Register != -1) { node.SetDestination(dstIndex, Register(info.Register, dest.Type.ToRegisterType(), dest.Type)); } else { Operand temp = info.Temp; if (temp == null || info.Sequence != sequence) { temp = dest.Type.IsInteger() ? GetSpillTemp(dest, intSpillTempRegisters, ref intLocalAsg) : GetSpillTemp(dest, vecSpillTempRegisters, ref vecLocalAsg); info.Sequence = sequence; info.Temp = temp; } node.SetDestination(dstIndex, temp); Operation spillOp = new Operation(Instruction.Spill, null, Const(info.SpillOffset), temp); block.Operations.AddAfter(node, spillOp); node = spillOp; } } sequence++; intUsedRegisters |= intLocalAsg | intLocalUse; vecUsedRegisters |= vecLocalAsg | vecLocalUse; } } return(new AllocationResult(intUsedRegisters, vecUsedRegisters, stackAlloc.TotalSize)); }
bool useLiquidGravity = false; // used by BlockDefinitions. #endregion Fields #region Constructors public PhysicsComponent( Game game, Entity entity ) { this.game = game; this.entity = entity; info = game.BlockInfo; }
internal void SetStartingPoint(BlockInfo StartingPoint) { this.e.SetStartingPoint(StartingPoint); }
protected FlowProducerDefinitionBase(BlockInfo blockInfo, FlowProducerSettings settings, Type actionType) : base(blockInfo, actionType, BlockType.Producer) { Settings = settings; }
void DrawCodeSegmentBorder (Gdk.GC gc, Cairo.Context ctx, double x, int width, BlockInfo firstBlock, BlockInfo lastBlock, string[] lines, Gtk.Widget widget, Gdk.Drawable window) { int shadowSize = 2; int spacing = 4; int bottomSpacing = (lineHeight - spacing) / 2; ctx.Rectangle (x + shadowSize + 0.5, firstBlock.YStart + bottomSpacing + spacing - shadowSize + 0.5, width - shadowSize*2, shadowSize); ctx.Color = new Cairo.Color (0.9, 0.9, 0.9); ctx.LineWidth = 1; ctx.Fill (); ctx.Rectangle (x + shadowSize + 0.5, lastBlock.YEnd + bottomSpacing + 0.5, width - shadowSize*2, shadowSize); ctx.Color = new Cairo.Color (0.9, 0.9, 0.9); ctx.Fill (); ctx.Rectangle (x + 0.5, firstBlock.YStart + bottomSpacing + spacing + 0.5, width, lastBlock.YEnd - firstBlock.YStart - spacing); ctx.Color = new Cairo.Color (0.7,0.7,0.7); ctx.Stroke (); string text = lines[firstBlock.FirstLine].Replace ("@","").Replace ("-",""); text = "<span size='x-small'>" + text.Replace ("+","</span><span size='small'>➜</span><span size='x-small'> ") + "</span>"; layout.SetText (""); layout.SetMarkup (text); int tw,th; layout.GetPixelSize (out tw, out th); th--; int dy = (lineHeight - th) / 2; ctx.Rectangle (x + 2 + LeftPaddingBlock - 1 + 0.5, firstBlock.YStart + dy - 1 + 0.5, tw + 2, th + 2); ctx.LineWidth = 1; ctx.Color = widget.Style.Base (Gtk.StateType.Normal).ToCairoColor (); ctx.FillPreserve (); ctx.Color = new Cairo.Color (0.7, 0.7, 0.7); ctx.Stroke (); window.DrawLayout (gc, (int)(x + 2 + LeftPaddingBlock), firstBlock.YStart + dy, layout); }
public static void BeginBlock(Mobile m, int bonus) { EndBlock(m); m_Table[m] = new BlockInfo(m, bonus); }
protected override void OnPopulateMesh(VertexHelper vh) { blockInfos.Clear(); vh.Clear(); if (dicingTexture == null) { return; } if (sourceTexture == null) { return; } if (string.IsNullOrEmpty(currentTextureName)) { return; } var rect = GetPixelAdjustedRect(); if (rect.width <= 0 || rect.height <= 0) { return; } var pos = new Vector3(rect.x, rect.y); var textureWidth = (float)dicingTexture.Texture.width; var textureHeight = (float)dicingTexture.Texture.height; for (var by = 0; by < sourceTexture.yblock; by++) { var vertexSizeY = 0f; for (var bx = 0; bx < sourceTexture.xblock; bx++) { var block = dicingTexture.GetBlockData(currentTextureName, bx, by); if (block == null) { continue; } var vertexSizeX = rect.width * ((float)block.w / sourceTexture.width); vertexSizeY = rect.height * ((float)block.h / sourceTexture.height); // 左上 var lt = UIVertex.simpleVert; lt.position = new Vector3(pos.x, pos.y, 0); lt.uv0 = new Vector2(block.x / textureWidth, block.y / textureHeight); lt.color = color; // 右上 var rt = UIVertex.simpleVert; rt.position = new Vector3(pos.x + vertexSizeX, pos.y, 0); rt.uv0 = new Vector2((block.x + block.w) / textureWidth, block.y / textureHeight); rt.color = color; // 右下 var rb = UIVertex.simpleVert; rb.position = new Vector3(pos.x + vertexSizeX, pos.y + vertexSizeY, 0); rb.uv0 = new Vector2((block.x + block.w) / textureWidth, (block.y + block.h) / textureHeight); rb.color = color; // 左下 var lb = UIVertex.simpleVert; lb.position = new Vector3(pos.x, pos.y + vertexSizeY, 0); lb.uv0 = new Vector2(block.x / textureWidth, (block.y + block.h) / textureHeight); lb.color = color; vh.AddUIVertexQuad(new UIVertex[] { lb, rb, rt, lt }); // クロスフェード. if (CrossFade && !string.IsNullOrEmpty(crossFadeTextureName)) { DrawCrossFade(vh, bx, by, pos, textureWidth, textureHeight, vertexSizeX, vertexSizeY); } pos.x += vertexSizeX; // ブロック情報更新. var blockInfo = new BlockInfo() { Rect = new Rect(lt.position, new Vector2(vertexSizeX, vertexSizeY)), BlockData = block, }; blockInfos.Add(blockInfo); } pos.x = rect.x; pos.y += vertexSizeY; } }
public override unsafe void CodeImage(IntPtr Scan0, Rectangle ScanArea, Size ImageSize, PixelFormat Format, Stream outStream) { if (ImageSize.Width == 0 || ImageSize.Height == 0) { throw new ArgumentException("The width and height must be 1 or higher"); } if (ImageSize.Width < BlockCount || ImageSize.Height < BlockCount) { throw new Exception("The Image size Width/Height must be bigger then the Block Count " + BlockCount + "x" + BlockCount); } int PixelSize = 0; switch (Format) { case PixelFormat.Format24bppRgb: PixelSize = 3; break; case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: PixelSize = 4; break; default: throw new NotSupportedException(Format.ToString()); } int Stride = ImageSize.Width * PixelSize; int RawLength = Stride * ImageSize.Height; if (EncodedFrames == 0) { this.EncodedFormat = Format; this.EncodedWidth = ImageSize.Width; this.EncodedHeight = ImageSize.Height; byte[] temp = null; using (Bitmap TmpBmp = new Bitmap(ImageSize.Width, ImageSize.Height, Stride, Format, Scan0)) { temp = base.jpgCompression.Compress(TmpBmp); } outStream.Write(BitConverter.GetBytes(temp.Length), 0, 4); outStream.Write(temp, 0, temp.Length); double size = (double)ImageSize.Width / (double)BlockCount; //fix floating point here for (int i = 0, j = 0; i < BlockCount; i++, j += (int)size) { Offsets[i] = new Rectangle(j, 0, (int)size, 1); } EncodeBuffer = new SortedList <int, SortedList <int, uint> >(); for (int y = 0; y < ImageSize.Height; y++) { for (int i = 0; i < Offsets.Length; i++) { if (!EncodeBuffer.ContainsKey(y)) { EncodeBuffer.Add(y, new SortedList <int, uint>()); } if (!EncodeBuffer[y].ContainsKey(Offsets[i].X)) { EncodeBuffer[y].Add(Offsets[i].X, 0); //0=hash } } } EncodedFrames++; return; } long oldPos = outStream.Position; outStream.Write(new byte[4], 0, 4); int TotalDataLength = 0; List <HashBlock> ImageOffsets = new List <HashBlock>(); List <uint> ImageHashes = new List <uint>(); byte *pScan0 = (byte *)Scan0.ToInt32(); for (int i = 0; i < Offsets.Length; i++) { for (int y = 0; y < ImageSize.Height; y++) { Rectangle ScanRect = Offsets[i]; ScanRect.Y = y; int offset = (y * Stride) + (ScanRect.X * PixelSize); if (offset + Stride > Stride * ImageSize.Height) { break; } uint Hash = hasher.Hash(pScan0 + offset, (int)Stride); uint BlockOffset = Hash % HashBlockCount; BlockInfo blockInfo = EncodeHashBlocks[BlockOffset]; if (EncodeBuffer[y][ScanRect.X] != Hash) { if (!blockInfo.Hashes.ContainsKey(Hash)) { int index = ImageOffsets.Count - 1; if (ImageOffsets.Count > 0 && ImageOffsets[index].Location.Y + 1 == ScanRect.Y) { Rectangle rect = ImageOffsets[index].Location; ImageOffsets[index].Location = new Rectangle(rect.X, rect.Y, rect.Width, rect.Height + 1); } else { ImageOffsets.Add(new HashBlock(Hash, false, new Rectangle(ScanRect.X, y, ScanRect.Width, 1))); } blockInfo.Hashes.Add(Hash, new HashBlock(Hash, false, new Rectangle(ScanRect.X, y, ScanRect.Width, 1))); ImageHashes.Add(Hash); } EncodeBuffer[y][ScanRect.X] = Hash; } } } if (ImageOffsets.Count > 0) { for (int i = 0; i < Offsets.Length; i++) { Rectangle TargetOffset = Offsets[i]; int Height = GetOffsetHeight(ImageOffsets, TargetOffset); Bitmap TmpBmp = new Bitmap(TargetOffset.Width, Height, Format); BitmapData TmpData = TmpBmp.LockBits(new Rectangle(0, 0, TmpBmp.Width, TmpBmp.Height), ImageLockMode.ReadWrite, TmpBmp.PixelFormat); int blockStride = PixelSize * TargetOffset.Width; List <HashBlock> UsedOffsets = new List <HashBlock>(); for (int j = 0; j < ImageOffsets.Count; j++) { Rectangle rect = ImageOffsets[j].Location; if (rect.Width != TargetOffset.Width || rect.X != TargetOffset.X) { continue; //error in 1440p, did not tested futher } for (int o = 0, offset = 0; o < rect.Height; o++) { int blockOffset = (Stride * (rect.Y + o)) + (PixelSize * rect.X); NativeMethods.memcpy((byte *)TmpData.Scan0.ToPointer() + offset, pScan0 + blockOffset, (uint)blockStride); //copy-changes offset += blockStride; UsedOffsets.Add(ImageOffsets[j]); } } TmpBmp.UnlockBits(TmpData); TmpBmp.Dispose(); outStream.Write(BitConverter.GetBytes((short)UsedOffsets.Count), 0, 2); if (UsedOffsets.Count > 0) { outStream.Write(BitConverter.GetBytes((short)UsedOffsets[0].Location.X), 0, 2); for (int j = 0; j < UsedOffsets.Count; j++) { outStream.Write(BitConverter.GetBytes((short)UsedOffsets[j].Location.Y), 0, 2); outStream.Write(BitConverter.GetBytes((short)UsedOffsets[j].Location.Height), 0, 2); outStream.Write(BitConverter.GetBytes(UsedOffsets[j].Hash), 0, 4); } byte[] CompressedImg = base.jpgCompression.Compress(TmpBmp); outStream.Write(BitConverter.GetBytes(CompressedImg.Length), 0, 4); outStream.Write(CompressedImg, 0, CompressedImg.Length); } //TotalDataLength += (int)length + (4 * 5); } } EncodedFrames++; }
//检查是否能看到该位置 private bool InView(Vector3 s, Vector3 e) { VoxelBlocks map = GameObject.Find("Voxel Map").GetComponent <VoxelBlocks> (); Vector3 next = s; int deltCol = (int)(e.x - s.x); int deltRow = (int)(e.y - s.y); int stepCol, stepRow; int fraction; //初始化路径数组 stepCol = (int)Mathf.Sign(deltCol); //获取x轴上的前进方向 stepRow = (int)Mathf.Sign(deltRow); //获取z轴上的前进方向 deltRow = Mathf.Abs(deltRow * 2); deltCol = Mathf.Abs(deltCol * 2); if (deltCol > deltRow) { fraction = deltRow * 2 - deltCol; while (next.x != e.x) { if (fraction >= 0) { next.y += stepRow; fraction = fraction - 2 * deltCol; } next.x += stepCol; fraction = fraction + deltRow; BlockInfo bi = map.GetBlockByLogicPos(next); if (bi == null) { return(false); } BasicEntity entity = bi.entity; if (entity != null && entity.GetComponent <BlockInfoComponent> ().m_blockType == BlockType.Wall) { return(false); } } } else { fraction = deltCol * 2 - deltRow; while (next.y != e.y) { if (fraction >= 0) { next.x += stepCol; fraction = fraction - 2 * deltRow; } next.y += stepRow; fraction = fraction + deltCol; BlockInfo bi = map.GetBlockByLogicPos(next); if (bi == null) { return(false); } BasicEntity entity = bi.entity; if (entity != null && entity.GetComponent <BlockInfoComponent> ().m_blockType == BlockType.Wall) { return(false); } } } return(true); }
public World(Game game) { Env = new WorldEnv(game); this.game = game; info = game.BlockInfo; }
public Task <ResultWrapper <ForkchoiceUpdatedV1Result> > Handle(ForkchoiceStateV1 forkchoiceState, PayloadAttributes?payloadAttributes) { string requestStr = $"{forkchoiceState} {payloadAttributes}"; if (_logger.IsInfo) { _logger.Info($"Received: {requestStr}"); } if (_invalidChainTracker.IsOnKnownInvalidChain(forkchoiceState.HeadBlockHash, out Keccak? lastValidHash)) { if (_logger.IsInfo) { _logger.Info($" FCU - Invalid - {requestStr} {forkchoiceState.HeadBlockHash} is known to be a part of an invalid chain."); } return(ForkchoiceUpdatedV1Result.Invalid(lastValidHash)); } Block?newHeadBlock = GetBlock(forkchoiceState.HeadBlockHash); if (newHeadBlock is null) // if a head is unknown we are syncing { if (_blockCacheService.BlockCache.TryGetValue(forkchoiceState.HeadBlockHash, out Block? block)) { StartNewBeaconHeaderSync(forkchoiceState, block, requestStr); return(ForkchoiceUpdatedV1Result.Syncing); } if (_logger.IsInfo) { _logger.Info($"Syncing... Unknown forkchoiceState head hash... Request: {requestStr}."); } return(ForkchoiceUpdatedV1Result.Syncing); } BlockInfo blockInfo = _blockTree.GetInfo(newHeadBlock.Number, newHeadBlock.GetOrCalculateHash()).Info; if (!blockInfo.WasProcessed) { BlockHeader?blockParent = _blockTree.FindHeader(newHeadBlock.ParentHash !); if (blockParent == null) { if (_logger.IsDebug) { _logger.Debug($"Parent of block not available. Starting new beacon header. sync."); } StartNewBeaconHeaderSync(forkchoiceState, newHeadBlock !, requestStr); return(ForkchoiceUpdatedV1Result.Syncing); } if (!blockInfo.IsBeaconMainChain && blockInfo.IsBeaconInfo) { ReorgBeaconChainDuringSync(newHeadBlock !, blockInfo); } int processingQueueCount = _processingQueue.Count; if (processingQueueCount == 0) { _peerRefresher.RefreshPeers(newHeadBlock !.Hash !, newHeadBlock.ParentHash !, forkchoiceState.FinalizedBlockHash); _blockCacheService.FinalizedHash = forkchoiceState.FinalizedBlockHash; _mergeSyncController.StopBeaconModeControl(); if (_logger.IsInfo) { _logger.Info($"Syncing beacon headers... Request: {requestStr}."); } } else { if (_logger.IsInfo) { _logger.Info($"Processing {_processingQueue.Count} blocks... Request: {requestStr}."); } } _beaconPivot.ProcessDestination ??= newHeadBlock !.Header; return(ForkchoiceUpdatedV1Result.Syncing); } if (_logger.IsInfo) { _logger.Info($"FCU - block {newHeadBlock} was processed."); } BlockHeader?finalizedHeader = ValidateBlockHash(forkchoiceState.FinalizedBlockHash, out string?finalizationErrorMsg); if (finalizationErrorMsg is not null) { if (_logger.IsWarn) { _logger.Warn($"Invalid finalized block hash {finalizationErrorMsg}. Request: {requestStr}."); } return(ForkchoiceUpdatedV1Result.Error(finalizationErrorMsg, MergeErrorCodes.InvalidForkchoiceState)); } ValidateBlockHash(forkchoiceState.SafeBlockHash, out string?safeBlockErrorMsg); if (safeBlockErrorMsg is not null) { if (_logger.IsWarn) { _logger.Warn($"Invalid safe block hash {finalizationErrorMsg}. Request: {requestStr}."); } return(ForkchoiceUpdatedV1Result.Error(safeBlockErrorMsg, MergeErrorCodes.InvalidForkchoiceState)); } if ((newHeadBlock.TotalDifficulty ?? 0) != 0 && (_poSSwitcher.MisconfiguredTerminalTotalDifficulty() || _poSSwitcher.BlockBeforeTerminalTotalDifficulty(newHeadBlock.Header))) { if (_logger.IsWarn) { _logger.Warn($"Invalid terminal block. Nethermind TTD {_poSSwitcher.TerminalTotalDifficulty}, NewHeadBlock TD: {newHeadBlock.Header.TotalDifficulty}. Request: {requestStr}."); } // https://github.com/ethereum/execution-apis/blob/main/src/engine/specification.md#specification // {status: INVALID, latestValidHash: 0x0000000000000000000000000000000000000000000000000000000000000000, validationError: errorMessage | null} if terminal block conditions are not satisfied return(ForkchoiceUpdatedV1Result.Invalid(Keccak.Zero)); } Block[]? blocks = EnsureNewHead(newHeadBlock, out string?setHeadErrorMsg); if (setHeadErrorMsg is not null) { if (_logger.IsWarn) { _logger.Warn($"Invalid new head block {setHeadErrorMsg}. Request: {requestStr}."); } return(ForkchoiceUpdatedV1Result.Error(setHeadErrorMsg, ErrorCodes.InvalidParams)); } if (_blockTree.IsOnMainChainBehindHead(newHeadBlock)) { if (_logger.IsInfo) { _logger.Info($"Valid. ForkchoiceUpdated ignored - already in canonical chain. Request: {requestStr}."); } return(ForkchoiceUpdatedV1Result.Valid(null, forkchoiceState.HeadBlockHash)); } EnsureTerminalBlock(forkchoiceState, blocks); bool newHeadTheSameAsCurrentHead = _blockTree.Head !.Hash == newHeadBlock.Hash; bool shouldUpdateHead = !newHeadTheSameAsCurrentHead && blocks is not null; if (shouldUpdateHead) { _blockTree.UpdateMainChain(blocks !, true, true); } if (IsInconsistent(forkchoiceState.FinalizedBlockHash)) { string errorMsg = $"Inconsistent forkchoiceState - finalized block hash. Request: {requestStr}"; if (_logger.IsWarn) { _logger.Warn(errorMsg); } return(ForkchoiceUpdatedV1Result.Error(errorMsg, MergeErrorCodes.InvalidForkchoiceState)); } if (IsInconsistent(forkchoiceState.SafeBlockHash)) { string errorMsg = $"Inconsistent forkchoiceState - safe block hash. Request: {requestStr}"; if (_logger.IsWarn) { _logger.Warn(errorMsg); } return(ForkchoiceUpdatedV1Result.Error(errorMsg, MergeErrorCodes.InvalidForkchoiceState)); } bool nonZeroFinalizedBlockHash = forkchoiceState.FinalizedBlockHash != Keccak.Zero; // bool nonZeroSafeBlockHash = forkchoiceState.SafeBlockHash != Keccak.Zero; if (nonZeroFinalizedBlockHash) { _manualBlockFinalizationManager.MarkFinalized(newHeadBlock.Header, finalizedHeader !); } if (shouldUpdateHead) { _poSSwitcher.ForkchoiceUpdated(newHeadBlock.Header, forkchoiceState.FinalizedBlockHash); if (_logger.IsInfo) { _logger.Info($"Block {forkchoiceState.HeadBlockHash} was set as head."); } } string?payloadId = null; if (payloadAttributes is not null) { payloadAttributes.GasLimit = null; if (newHeadBlock.Timestamp >= payloadAttributes.Timestamp) { if (_logger.IsWarn) { _logger.Warn($"Invalid payload attributes timestamp {payloadAttributes.Timestamp}, block timestamp {newHeadBlock.Timestamp}. Request: {requestStr}."); } return(ForkchoiceUpdatedV1Result.Error( $"Invalid payload attributes timestamp {payloadAttributes.Timestamp}, block timestamp {newHeadBlock.Timestamp}. Request: {requestStr}", MergeErrorCodes.InvalidPayloadAttributes)); } else { payloadId = _payloadPreparationService.StartPreparingPayload(newHeadBlock.Header, payloadAttributes); } } if (_logger.IsInfo) { _logger.Info($"Valid. Request: {requestStr}."); } _blockTree.ForkChoiceUpdated(forkchoiceState.FinalizedBlockHash, forkchoiceState.SafeBlockHash); return(ForkchoiceUpdatedV1Result.Valid(payloadId, forkchoiceState.HeadBlockHash)); }
public static List <BlockInfo> Blocks(ref string _content, string _templateTag, string _aTag, string _bTag, int _targetBlockIndex = -1, string _searchBeforeTag = "", string _replaceHolderTemplateTag = "", ForeachATagPredicate _foreachATagPredicate = null) { _aTag = string.Format(_templateTag, _aTag); _bTag = string.Format(_templateTag, _bTag); int aTagLength = _aTag.Length; int bTagLength = _bTag.Length; int aTagIndex = 0; int bTagIndex = 0; int blockIndex = -1; bool hasReplaceHolderTemplateTag = !String.IsNullOrEmpty(_replaceHolderTemplateTag); string replaceHolderTemplateTagTmp = ""; List <BlockInfo> tag_templates = new List <BlockInfo>(); aTagIndex = _content.IndexOf(_aTag); if (aTagIndex == -1) { return(tag_templates); } if (!String.IsNullOrEmpty(_searchBeforeTag)) { _searchBeforeTag = string.Format(_templateTag, _searchBeforeTag); if (aTagIndex >= _content.IndexOf(_searchBeforeTag)) { return(tag_templates); } } Template.Position tagPosition = new Position(ref _content, ref _aTag, ref _bTag); //bTagIndex = content.IndexOf(bTag, aTagIndex + 1); // //int tmpATagIndex = aTagIndex; // bTagIndex = tagPosition.GetEndPoint(aTagIndex); //string tmpBlockStr = ""; while (aTagIndex != -1 && bTagIndex != -1 && (bTagIndex + bTagLength) <= _content.Length) { if (_foreachATagPredicate != null) { if (!_foreachATagPredicate(aTagIndex, ref _content)) { aTagIndex = _content.IndexOf(_aTag, bTagIndex + 1); bTagIndex = tagPosition.GetEndPoint(ref _content, aTagIndex); continue; } } blockIndex++; BlockInfo blockInfo = new BlockInfo(); blockInfo.Value = _content.Substring(aTagIndex + aTagLength, bTagIndex - (aTagIndex + aTagLength)); if (!hasReplaceHolderTemplateTag) { /* * [o1]<!-- Template_TABLE -->[i1] * {Tag} * [i2]<!-- Template_TABLE -->[o2] */ // [i1] <-> [i2] <==> InnerAIndex <-> InnerBIndex // blockInfo.InnerAIndex = aTagIndex + aTagLength; blockInfo.InnerBIndex = bTagIndex - 1; // [o1](<...) <-> [o2](...>) <==> OuterAIndex ( < index ) <-> OuterBIndex ( > index ) // blockInfo.OuterAIndex = aTagIndex; blockInfo.OuterBIndex = bTagIndex + bTagLength - 1; } if (hasReplaceHolderTemplateTag) { replaceHolderTemplateTagTmp = string.Format(_replaceHolderTemplateTag, blockIndex); _content = _content.Substring(0, aTagIndex) + replaceHolderTemplateTagTmp + _content.Substring(bTagIndex + bTagLength); bTagIndex = _content.IndexOf(replaceHolderTemplateTagTmp, aTagIndex); if (bTagIndex == -1) { throw new ArgumentException("Block : ReplaceHolderTemplateTag Not Found"); } bTagIndex += replaceHolderTemplateTagTmp.Length - 1; blockInfo.ReplaceHolderTemplateTag = replaceHolderTemplateTagTmp; } //if (_fillTagInfos) //{ // // # DATA Item & Template.TagInfo # // // // blockInfo.FillTagInfos(); //} tag_templates.Add(blockInfo); if (_targetBlockIndex == blockIndex) { break; } aTagIndex = _content.IndexOf(_aTag, bTagIndex + 1); // //bTagIndex = content.IndexOf(bTag, aTagIndex + 1); // //tmpATagIndex = aTagIndex + 1; // //tmpATagIndex = aTagIndex; // bTagIndex = tagPosition.GetEndPoint(ref _content, aTagIndex); } return(tag_templates); }
int GetShape( BlockInfo info, byte id ) { return info.IsSprite[id] ? 0 : (byte)(info.MaxBB[id].Y * 16); }
void DrawChangeSymbol (Cairo.Context ctx, Widget widget, double x, int width, BlockInfo block) { if (!IsChangeBlock (block.Type)) return; if (block.Type == BlockType.Added) { var ix = x + (LeftPaddingBlock/2) - (gutterAdded.Width / 2); var iy = block.YStart + ((block.YEnd - block.YStart) / 2 - gutterAdded.Height / 2); ctx.DrawImage (widget, gutterAdded, ix, iy); } else { var ix = x + (LeftPaddingBlock/2) - (gutterRemoved.Width / 2); var iy = block.YStart + ((block.YEnd - block.YStart) / 2 - gutterRemoved.Height / 2); ctx.DrawImage (widget, gutterRemoved, ix, iy); } }
public void SetCurrentItem(BlockInfo blockInfo) { //this method will help the slot to fill itself up this.blockInfo = blockInfo; }
void DrawChangeSymbol (Cairo.Context ctx, double x, int width, BlockInfo block) { if (!IsChangeBlock (block.Type)) return; Gdk.Color color = block.Type == BlockType.Added ? baseAddColor : baseRemoveColor; int ssize = 8; int barSize = 3; if (ssize - 2 > lineHeight) ssize = lineHeight - 2; if (ssize <= 0) return; double inSize = (ssize / 2) - (barSize / 2); double py = block.YStart + ((block.YEnd - block.YStart) / 2 - ssize / 2) + 0.5; double px = x + (LeftPaddingBlock/2) - (ssize / 2) + 0.5; if (block.Type == BlockType.Added) { ctx.MoveTo (px + inSize, py); ctx.RelLineTo (barSize, 0); ctx.RelLineTo (0, inSize); ctx.RelLineTo (inSize, 0); ctx.RelLineTo (0, barSize); ctx.RelLineTo (-inSize, 0); ctx.RelLineTo (0, inSize); ctx.RelLineTo (-barSize, 0); ctx.RelLineTo (0, -inSize); ctx.RelLineTo (-inSize, 0); ctx.RelLineTo (0, -barSize); ctx.RelLineTo (inSize, 0); ctx.RelLineTo (0, -inSize); ctx.ClosePath (); } else { ctx.MoveTo (px, py + inSize); ctx.RelLineTo (ssize, 0); ctx.RelLineTo (0, barSize); ctx.RelLineTo (-ssize, 0); ctx.RelLineTo (0, -barSize); ctx.ClosePath (); } ctx.Color = color.ToCairoColor (); ctx.FillPreserve (); ctx.Color = color.AddLight (-0.2).ToCairoColor ();; ctx.LineWidth = 1; ctx.Stroke (); }
public static X86Block[] Create(int bitness, NativeCodeBlock[] blocks) { var targets = new Dictionary <ulong, TargetKind>(); var instrInfo = new List <(Instruction instruction, int block, ArraySegment <byte> code)>(); for (int blockIndex = 0; blockIndex < blocks.Length; blockIndex++) { var block = blocks[blockIndex]; var reader = new ByteArrayCodeReader(block.Code); var decoder = Decoder.Create(bitness, reader); decoder.InstructionPointer = block.Address; while (reader.CanReadByte) { decoder.Decode(out var instr); instrInfo.Add((instr, blockIndex, GetBytes(block.Code, block.Address, ref instr))); switch (instr.FlowControl) { case FlowControl.Next: case FlowControl.Interrupt: break; case FlowControl.UnconditionalBranch: Add(targets, instr.NextIP64, TargetKind.Unknown); if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64) { Add(targets, instr.NearBranchTarget, TargetKind.Branch); } break; case FlowControl.ConditionalBranch: case FlowControl.XbeginXabortXend: if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64) { Add(targets, instr.NearBranchTarget, TargetKind.Branch); } break; case FlowControl.Call: if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64) { Add(targets, instr.NearBranchTarget, TargetKind.Call); } break; case FlowControl.IndirectBranch: Add(targets, instr.NextIP64, TargetKind.Unknown); // Unknown target break; case FlowControl.IndirectCall: // Unknown target break; case FlowControl.Return: case FlowControl.Exception: Add(targets, instr.NextIP64, TargetKind.Unknown); break; default: Debug.Fail($"Unknown flow control: {instr.FlowControl}"); break; } var baseReg = instr.MemoryBase; if (baseReg == Register.RIP || baseReg == Register.EIP) { int opCount = instr.OpCount; for (int i = 0; i < opCount; i++) { if (instr.GetOpKind(i) == OpKind.Memory) { if (IsCodeAddress(blocks, instr.IPRelativeMemoryAddress)) { Add(targets, instr.IPRelativeMemoryAddress, TargetKind.Branch); } break; } } } else if (instr.MemoryDisplSize >= 2) { ulong displ; switch (instr.MemoryDisplSize) { case 2: case 4: displ = instr.MemoryDisplacement; break; case 8: displ = (ulong)(int)instr.MemoryDisplacement; break; default: Debug.Fail($"Unknown mem displ size: {instr.MemoryDisplSize}"); goto case 8; } if (IsCodeAddress(blocks, displ)) { Add(targets, displ, TargetKind.Branch); } } } } foreach (var block in blocks) { if (targets.TryGetValue(block.Address, out var origKind)) { if (origKind < TargetKind.BlockStart && origKind != TargetKind.Unknown) { targets[block.Address] = TargetKind.BlockStart; } } else { targets.Add(block.Address, TargetKind.Unknown); } } var newBlocks = new List <BlockInfo>(); BlockInfo currentBlock = default; int labelIndex = 0, methodIndex = 0; for (int i = 0; i < instrInfo.Count; i++) { var info = instrInfo[i]; ref var instr = ref info.instruction; if (targets.TryGetValue(instr.IP64, out var targetKind)) { var origBlock = blocks[info.block]; currentBlock = new BlockInfo(targetKind, origBlock.Kind, instr.IP64, origBlock.Address == instr.IP64 ? origBlock.Comment : null); newBlocks.Add(currentBlock); } currentBlock.Instructions.Add(new X86InstructionInfo(info.code, instr)); }
public Group(BlockInfo _blockTemplate) { this.tGroup = new System.Collections.Generic.Dictionary <int, TGroup <T> >(); this.tGroup.Add(0, new TGroup <T>(_blockTemplate)); }
public Project Load(string filename) { var idx = 0; bytes = File.ReadAllBytes(filename); var id = Encoding.ASCII.GetString(bytes, idx, FileHeaderId.Length); idx += FileHeaderId.Length; if (id != FileHeaderId) { Log.LogMessage(LogSeverity.Error, "Invalid FTM file ID."); return(null); } var version = BitConverter.ToUInt32(bytes, idx); idx += sizeof(uint); if (version < MinVersion || version > MaxVersion) { Log.LogMessage(LogSeverity.Error, "Unsupported file version. Only FTM version 0.4.4 to 0.4.6 are supported."); return(null); } var blockToc = new Dictionary <string, BlockInfo>(); while (bytes[idx + 0] != 'E' || bytes[idx + 1] != 'N' || bytes[idx + 2] != 'D') { var blockId = Encoding.ASCII.GetString(bytes, idx, BlockNameLength).TrimEnd('\0'); idx += BlockNameLength; var blockVer = BitConverter.ToInt32(bytes, idx); idx += sizeof(uint); var blockSize = BitConverter.ToInt32(bytes, idx); idx += sizeof(uint); blockToc[blockId] = new BlockInfo() { offset = idx, version = blockVer, size = blockSize }; idx += blockSize; } // We read block in a specific order to minimize the amound of bookeeping we need to do. var blocksToRead = new Dictionary <string, ReadBlockDelegate> { { "PARAMS", ReadParams }, { "INFO", ReadInfo }, { "HEADER", ReadHeader }, { "DPCM SAMPLES", ReadDpcmSamples }, { "SEQUENCES", ReadSequences }, { "SEQUENCES_VRC6", ReadSequencesVrc6 }, { "SEQUENCES_N163", ReadSequencesN163 }, { "INSTRUMENTS", ReadInstruments }, { "FRAMES", ReadFrames }, { "PATTERNS", ReadPatterns }, }; project = new Project(); project.TempoMode = TempoType.FamiTracker; foreach (var kv in blocksToRead) { var blockName = kv.Key; var blockFunc = kv.Value; if (blockToc.TryGetValue(blockName, out var info)) { blockSize = info.size; blockVersion = info.version; if (!blockFunc(info.offset)) { return(null); } } } FinishImport(); return(project); }
protected override Expression VisitTry(TryExpression node) { // Visit finally/fault block first BlockInfo block = new BlockInfo { InFinally = true }; _blocks.Push(block); Expression @finally = Visit(node.Finally); Expression fault = Visit(node.Fault); block.InFinally = false; LabelTarget finallyEnd = block.FlowLabel; if (finallyEnd != null) { // Make a new target, which will be emitted after the try block.FlowLabel = Expression.Label(); } Expression @try = Visit(node.Body); IList <CatchBlock> handlers = Visit(node.Handlers, VisitCatchBlock); _blocks.Pop(); if (@try == node.Body && handlers == node.Handlers && @finally == node.Finally && fault == node.Fault) { return(node); } if (!block.HasFlow) { return(Expression.MakeTry(null, @try, @finally, fault, handlers)); } if (node.Type != typeof(void)) { // This is not hard to support in principle, but not needed by anyone yet. throw new NotSupportedException("FinallyFlowControlExpression does not support TryExpressions of non-void type."); } // If there is a control flow in finally, emit outer: // try { // // try block body and all catch handling // } catch (Exception all) { // saved = all; // } finally { // finally_body // if (saved != null) { // throw saved; // } // } // // If we have a fault handler we turn this into the better: // try { // // try block body and all catch handling // } catch (Exception all) { // fault_body // throw all // } if (handlers.Count > 0) { @try = Expression.MakeTry(null, @try, null, null, handlers); } var saved = Expression.Variable(typeof(Exception), "$exception"); var all = Expression.Variable(typeof(Exception), "e"); if (@finally != null) { handlers = new[] { Expression.Catch( all, Expression.Block( Expression.Assign(saved, all), Utils.Default(node.Type) ) ) }; @finally = Expression.Block( @finally, Expression.Condition( Expression.NotEqual(saved, AstUtils.Constant(null, saved.Type)), Expression.Throw(saved), Utils.Empty() ) ); if (finallyEnd != null) { @finally = Expression.Label(finallyEnd, @finally); } } else { Debug.Assert(fault != null); fault = Expression.Block(fault, Expression.Throw(all)); if (finallyEnd != null) { fault = Expression.Label(finallyEnd, fault); } handlers = new[] { Expression.Catch(all, fault) }; fault = null; } // Emit flow control return(Expression.Block( new[] { saved }, Expression.MakeTry(null, @try, @finally, fault, handlers), Expression.Label(block.FlowLabel), MakeFlowControlSwitch(block) )); }
private void CompleteBlock(BlockInfo block) { this.data.CompleteBlock(block.Hash); }
BlockInfo PackInt(int slen) { int p = slen / 124; int r = slen % 124; if (r > 0) { p++; } int len = p * 4 + slen; BlockInfo block = MemoryRequest(len + 8); block.DataCount = len + 8; unsafe { byte *tar = block.Addr; tar[0] = 255; tar[1] = 255; tar[2] = 255; tar[3] = 255; int o = len + 4; tar[o] = 255; o++; tar[o] = 255; o++; tar[o] = 255; o++; tar[o] = 254; int s = 0; int t = 4; for (int j = 0; j < p; j++) { int a = 0; int st = t; t += 4; for (int i = 0; i < 31; i++) { byte b = tmpBuffer[s]; if (b > 127) { a |= 1 << i; b -= 128; } tar[t] = b; t++; s++; if (s >= slen) { break; } tar[t] = tmpBuffer[s]; t++; s++; if (s >= slen) { break; } tar[t] = tmpBuffer[s]; t++; s++; if (s >= slen) { break; } tar[t] = tmpBuffer[s]; t++; s++; if (s >= slen) { break; } } tar[st] = (byte)a; a >>= 8; tar[st + 1] = (byte)a; a >>= 8; tar[st + 2] = (byte)a; a >>= 8; tar[st + 3] = (byte)a; } } return(block); }
} = true; // no need to sync it at the moment public async Task LoadBlocksFromDb( CancellationToken cancellationToken, UInt256?startBlockNumber = null, int batchSize = DbLoadBatchSize, int maxBlocksToLoad = int.MaxValue) { try { CanAcceptNewBlocks = false; byte[] deletePointer = _blockInfoDb.Get(DeletePointerAddressInDb); if (deletePointer != null) { Keccak deletePointerHash = new Keccak(deletePointer); if (_logger.IsInfo) { _logger.Info($"Cleaning invalid blocks starting from {deletePointer}"); } CleanInvalidBlocks(deletePointerHash); } if (startBlockNumber == null) { startBlockNumber = Head?.Number ?? 0; } else { Head = startBlockNumber == 0 ? null : FindBlock(startBlockNumber.Value - 1)?.Header; } BigInteger blocksToLoad = BigInteger.Min(FindNumberOfBlocksToLoadFromDb(), maxBlocksToLoad); if (blocksToLoad == 0) { if (_logger.IsInfo) { _logger.Info("Found no blocks to load from DB."); } } else { if (_logger.IsInfo) { _logger.Info($"Found {blocksToLoad} blocks to load from DB starting from current head block {Head?.ToString(BlockHeader.Format.Short)}."); } } UInt256 blockNumber = startBlockNumber.Value; for (int i = 0; i < blocksToLoad; i++) { if (cancellationToken.IsCancellationRequested) { break; } ChainLevelInfo level = LoadLevel(blockNumber); if (level == null) { break; } BigInteger maxDifficultySoFar = 0; BlockInfo maxDifficultyBlock = null; for (int blockIndex = 0; blockIndex < level.BlockInfos.Length; blockIndex++) { if (level.BlockInfos[blockIndex].TotalDifficulty > maxDifficultySoFar) { maxDifficultyBlock = level.BlockInfos[blockIndex]; maxDifficultySoFar = maxDifficultyBlock.TotalDifficulty; } } level = null; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (level != null) // ReSharper disable once HeuristicUnreachableCode { // ReSharper disable once HeuristicUnreachableCode throw new InvalidOperationException("just be aware that this level can be deleted by another thread after here"); } if (maxDifficultyBlock == null) { throw new InvalidOperationException($"Expected at least one block at level {blockNumber}"); } Block block = FindBlock(maxDifficultyBlock.BlockHash, false); if (block == null) { if (_logger.IsError) { _logger.Error($"Could not find block {maxDifficultyBlock.BlockHash}. DB load cancelled."); } _dbBatchProcessed?.SetResult(null); break; } BestSuggested = block.Header; NewBestSuggestedBlock?.Invoke(this, new BlockEventArgs(block)); if (i % batchSize == batchSize - 1 && !(i == blocksToLoad - 1) && (Head.Number + (UInt256)batchSize) < blockNumber) { if (_logger.IsInfo) { _logger.Info($"Loaded {i + 1} out of {blocksToLoad} blocks from DB into processing queue, waiting for processor before loading more."); } _dbBatchProcessed = new TaskCompletionSource <object>(); using (cancellationToken.Register(() => _dbBatchProcessed.SetCanceled())) { _currentDbLoadBatchEnd = blockNumber - (UInt256)batchSize; await _dbBatchProcessed.Task; } } blockNumber++; } if (cancellationToken.IsCancellationRequested) { _logger.Info($"Canceled loading blocks from DB at block {blockNumber}"); } if (_logger.IsInfo) { _logger.Info($"Completed loading blocks from DB at block {blockNumber}"); } } finally { CanAcceptNewBlocks = true; } }
public void RegisterMethod(string methodName, BlockAttributes attribute, DataType returnType, DataType[] argTypes, bool system) { BlockInfo bi = new BlockInfo(methodName, attribute, returnType, argTypes); blockInfos[methodName] = bi; if (system) { systemBlockInfos[methodName] = bi; } }
public AddBlockResult SuggestBlock(Block block) { #if DEBUG /* this is just to make sure that we do not fall into this trap when creating tests */ if (block.StateRoot == null && !block.IsGenesis) { throw new InvalidDataException($"State root is null in {block.ToString(Block.Format.Short)}"); } #endif if (!CanAcceptNewBlocks) { return(AddBlockResult.CannotAccept); } if (_invalidBlocks.ContainsKey(block.Number) && _invalidBlocks[block.Number].Contains(block.Hash)) { return(AddBlockResult.InvalidBlock); } if (block.Number == 0) { if (BestSuggested != null) { throw new InvalidOperationException("Genesis block should be added only once"); // TODO: make sure it cannot happen } } else if (IsKnownBlock(block.Number, block.Hash)) { if (_logger.IsTrace) { _logger.Trace($"Block {block.Hash} already known."); } return(AddBlockResult.AlreadyKnown); } else if (!IsKnownBlock(block.Number - 1, block.Header.ParentHash)) { if (_logger.IsTrace) { _logger.Trace($"Could not find parent ({block.Header.ParentHash}) of block {block.Hash}"); } return(AddBlockResult.UnknownParent); } _blockDb.Set(block.Hash, Rlp.Encode(block).Bytes); // _blockCache.Set(block.Hash, block); // TODO: when reviewing the entire data chain need to look at the transactional storing of level and block SetTotalDifficulty(block); SetTotalTransactions(block); BlockInfo blockInfo = new BlockInfo(block.Hash, block.TotalDifficulty.Value, block.TotalTransactions.Value); try { _blockInfoLock.EnterWriteLock(); UpdateOrCreateLevel(block.Number, blockInfo); } finally { _blockInfoLock.ExitWriteLock(); } if (block.IsGenesis || block.TotalDifficulty > (BestSuggested?.TotalDifficulty ?? 0)) { BestSuggested = block.Header; NewBestSuggestedBlock?.Invoke(this, new BlockEventArgs(block)); } return(AddBlockResult.Added); }
public SyncBlockTransactionsOperation BuildFromClientData(BlockInfo blockInfo, Block block) { return(new SyncBlockTransactionsOperation { BlockInfo = blockInfo, Transactions = block.Transactions }); }
internal IndexBTreeFileEnumerator(IndexBTreeFile File, bool Locked, IndexRecords RecordHandler, BlockInfo StartingPoint) { this.file = File; this.locked = Locked; this.recordHandler = RecordHandler; this.provider = this.file.ObjectFile.Provider; this.hasCurrent = false; this.currentObjectId = Guid.Empty; this.current = default(T); this.currentSerializer = null; this.timeoutMilliseconds = File.IndexFile.TimeoutMilliseconds; this.e = new ObjectBTreeFileEnumerator <object>(this.file.IndexFile, Locked, RecordHandler, StartingPoint); }
/// <summary> /// Get the BlockBehaviour based on the block info's GUID /// </summary> /// <param name="blockInfo">block info</param> /// <returns></returns> public static BlockBehaviour GetBlock(BlockInfo blockInfo) { return(GetBlock(blockInfo.Guid)); }
/// <summary> /// Updates an object in the file. /// </summary> /// <param name="ObjectId">Object ID</param> /// <param name="OldObject">Object that is being changed.</param> /// <param name="NewObject">New version of object.</param> /// <param name="Serializer">Object serializer.</param> /// <returns>If the object was saved in the index (true), or if the index property values of the object did not exist, or were too big to fit in an index record.</returns> internal async Task <bool> UpdateObject(Guid ObjectId, object OldObject, object NewObject, IObjectSerializer Serializer) { byte[] OldBin = this.recordHandler.Serialize(ObjectId, OldObject, Serializer, MissingFieldAction.Null); if (OldBin != null && OldBin.Length > this.indexFile.InlineObjectSizeLimit) { return(false); } byte[] NewBin = this.recordHandler.Serialize(ObjectId, NewObject, Serializer, MissingFieldAction.Null); if (NewBin != null && NewBin.Length > this.indexFile.InlineObjectSizeLimit) { return(false); } if (OldBin == null && NewBin == null) { return(false); } int i, c; if ((c = OldBin.Length) == NewBin.Length) { for (i = 0; i < c; i++) { if (OldBin[i] != NewBin[i]) { break; } } if (i == c) { return(true); } } await this.indexFile.Lock(); try { if (OldBin != null) { try { await this.indexFile.DeleteObjectLocked(OldBin, false, true, Serializer, null); } catch (KeyNotFoundException) { // Ignore. } } if (NewBin != null) { BlockInfo Leaf = await this.indexFile.FindLeafNodeLocked(NewBin); await this.indexFile.InsertObjectLocked(Leaf.BlockIndex, Leaf.Header, Leaf.Block, NewBin, Leaf.InternalPosition, 0, 0, true, Leaf.LastObject); } } finally { await this.indexFile.Release(); } return(true); }
void DrawBlockBg (Cairo.Context ctx, double x, int width, BlockInfo block) { if (!IsChangeBlock (block.Type)) return; var color = block.Type == BlockType.Added ? Styles.LogView.DiffAddBackgroundColor : Styles.LogView.DiffRemoveBackgroundColor; double y = block.YStart; int height = block.YEnd - block.YStart; double markerx = x + LeftPaddingBlock; double rd = RoundedSectionRadius; if (block.SectionStart) { ctx.Arc (x + rd, y + rd, rd, 180 * (Math.PI / 180), 270 * (Math.PI / 180)); ctx.LineTo (markerx, y); } else { ctx.MoveTo (markerx, y); } ctx.LineTo (markerx, y + height); if (block.SectionEnd) { ctx.LineTo (x + rd, y + height); ctx.Arc (x + rd, y + height - rd, rd, 90 * (Math.PI / 180), 180 * (Math.PI / 180)); } else { ctx.LineTo (x, y + height); } if (block.SectionStart) { ctx.LineTo (x, y + rd); } else { ctx.LineTo (x, y); } ctx.SetSourceColor (color.AddLight (0.1).ToCairoColor ()); ctx.Fill (); ctx.Rectangle (markerx, y, width - markerx, height); // FIXME: VV: Remove gradient features using (Cairo.Gradient pat = new Cairo.LinearGradient (x, y, x + width, y)) { pat.AddColorStop (0, color.AddLight (0.21).ToCairoColor ()); pat.AddColorStop (1, color.AddLight (0.3).ToCairoColor ()); ctx.SetSource (pat); ctx.Fill (); } }
private BoundingBox?BoundingBox(BlockInfo info) { return(null); }
protected override void Render (Drawable window, Widget widget, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, Gdk.Rectangle expose_area, CellRendererState flags) { if (isDisposed) return; if (diffMode) { if (path.Equals (selctedPath)) { selectedLine = -1; selctedPath = null; } int w, maxy; window.GetSize (out w, out maxy); if (DrawLeft) { cell_area.Width += cell_area.X - leftSpace; cell_area.X = leftSpace; } var treeview = widget as FileTreeView; var p = treeview != null? treeview.CursorLocation : null; cell_area.Width -= RightPadding; window.DrawRectangle (widget.Style.BaseGC (Gtk.StateType.Normal), true, cell_area.X, cell_area.Y, cell_area.Width - 1, cell_area.Height); Gdk.GC normalGC = widget.Style.TextGC (StateType.Normal); Gdk.GC removedGC = new Gdk.GC (window); removedGC.Copy (normalGC); removedGC.RgbFgColor = baseRemoveColor.AddLight (-0.3); Gdk.GC addedGC = new Gdk.GC (window); addedGC.Copy (normalGC); addedGC.RgbFgColor = baseAddColor.AddLight (-0.3); Gdk.GC infoGC = new Gdk.GC (window); infoGC.Copy (normalGC); infoGC.RgbFgColor = widget.Style.Text (StateType.Normal).AddLight (0.2); Cairo.Context ctx = CairoHelper.Create (window); Gdk.Color bgColor = new Gdk.Color (0,0,0); // Rendering is done in two steps: // 1) Get a list of blocks to render // 2) render the blocks int y = cell_area.Y + 2; // cline keeps track of the current source code line (the one to jump to when double clicking) int cline = 1; bool inHeader = true; BlockInfo currentBlock = null; List<BlockInfo> blocks = new List<BlockInfo> (); for (int n=0; n<lines.Length; n++, y += lineHeight) { string line = lines [n]; if (line.Length == 0) { currentBlock = null; y -= lineHeight; continue; } char tag = line [0]; if (line.StartsWith ("---") || line.StartsWith ("+++")) { // Ignore this part of the header. currentBlock = null; y -= lineHeight; continue; } if (tag == '@') { int l = ParseCurrentLine (line); if (l != -1) cline = l - 1; inHeader = false; } else if (tag != '-' && !inHeader) cline++; BlockType type; bool hasBg = false; switch (tag) { case '-': type = BlockType.Removed; break; case '+': type = BlockType.Added; break; case '@': type = BlockType.Info; break; default: type = BlockType.Unchanged; break; } if (currentBlock == null || type != currentBlock.Type) { if (y > maxy) break; // Starting a new block. Mark section ends between a change block and a normal code block if (currentBlock != null && IsChangeBlock (currentBlock.Type) && !IsChangeBlock (type)) currentBlock.SectionEnd = true; currentBlock = new BlockInfo () { YStart = y, FirstLine = n, Type = type, SourceLineStart = cline, SectionStart = (blocks.Count == 0 || !IsChangeBlock (blocks[blocks.Count - 1].Type)) && IsChangeBlock (type) }; blocks.Add (currentBlock); } // Include the line in the current block currentBlock.YEnd = y + lineHeight; currentBlock.LastLine = n; } // Now render the blocks // The y position of the highlighted line int selectedLineRowTop = -1; BlockInfo lastCodeSegmentStart = null; BlockInfo lastCodeSegmentEnd = null; foreach (BlockInfo block in blocks) { if (block.Type == BlockType.Info) { // Finished drawing the content of a code segment. Now draw the segment border and label. if (lastCodeSegmentStart != null) DrawCodeSegmentBorder (infoGC, ctx, cell_area.X, cell_area.Width, lastCodeSegmentStart, lastCodeSegmentEnd, lines, widget, window); lastCodeSegmentStart = block; } lastCodeSegmentEnd = block; if (block.YEnd < 0) continue; // Draw the block background DrawBlockBg (ctx, cell_area.X + 1, cell_area.Width - 2, block); // Get all text for the current block StringBuilder sb = new StringBuilder (); for (int n=block.FirstLine; n <= block.LastLine; n++) { string s = ProcessLine (lines [n]); if (sb.Length > 0) sb.Append ('\n'); if (block.Type != BlockType.Info && s.Length > 0) sb.Append (s, 1, s.Length - 1); else sb.Append (s); } // Draw a special background for the selected line if (block.Type != BlockType.Info && p.HasValue && p.Value.X >= cell_area.X && p.Value.X <= cell_area.Right && p.Value.Y >= block.YStart && p.Value.Y <= block.YEnd) { int row = (p.Value.Y - block.YStart) / lineHeight; double yrow = block.YStart + lineHeight * row + 0.5; double xrow = cell_area.X + LeftPaddingBlock + 0.5; int wrow = cell_area.Width - 1 - LeftPaddingBlock; if (block.Type == BlockType.Added) ctx.Color = baseAddColor.AddLight (0.1).ToCairoColor (); else if (block.Type == BlockType.Removed) ctx.Color = baseRemoveColor.AddLight (0.1).ToCairoColor (); else { ctx.Color = widget.Style.Base (Gtk.StateType.Prelight).AddLight (0.1).ToCairoColor (); xrow -= LeftPaddingBlock; wrow += LeftPaddingBlock; } ctx.Rectangle (xrow, yrow, wrow, lineHeight); ctx.Fill (); selectedLine = block.SourceLineStart + row; selctedPath = path; selectedLineRowTop = (int)yrow; } // Draw the line text. Ignore header blocks, since they are drawn as labels in DrawCodeSegmentBorder if (block.Type != BlockType.Info) { layout.SetMarkup (""); layout.SetText (sb.ToString ()); Gdk.GC gc; switch (block.Type) { case BlockType.Removed: gc = removedGC; break; case BlockType.Added: gc = addedGC; break; case BlockType.Info: gc = infoGC; break; default: gc = normalGC; break; } window.DrawLayout (gc, cell_area.X + 2 + LeftPaddingBlock, block.YStart, layout); } // Finally draw the change symbol at the left margin DrawChangeSymbol (ctx, cell_area.X + 1, cell_area.Width - 2, block); } // Finish the drawing of the code segment if (lastCodeSegmentStart != null) DrawCodeSegmentBorder (infoGC, ctx, cell_area.X, cell_area.Width, lastCodeSegmentStart, lastCodeSegmentEnd, lines, widget, window); // Draw the source line number at the current selected line. It must be done at the end because it must // be drawn over the source code text and segment borders. if (selectedLineRowTop != -1) DrawLineBox (normalGC, ctx, ((Gtk.TreeView)widget).VisibleRect.Right - 4, selectedLineRowTop, selectedLine, widget, window); ((IDisposable)ctx).Dispose (); removedGC.Dispose (); addedGC.Dispose (); infoGC.Dispose (); } else { // Rendering a normal text row int y = cell_area.Y + (cell_area.Height - height)/2; window.DrawLayout (widget.Style.TextGC (GetState(flags)), cell_area.X, y, layout); } }
public void AddBlock(BlockInfo blockInfo) { _blocks.Add(blockInfo); }
void DrawBlockBg (Cairo.Context ctx, double x, int width, BlockInfo block) { if (!IsChangeBlock (block.Type)) return; x += 0.5; Gdk.Color color = block.Type == BlockType.Added ? baseAddColor : baseRemoveColor; double y = block.YStart + 0.5; int height = block.YEnd - block.YStart; double markerx = x + LeftPaddingBlock - 0.5; double rd = RoundedSectionRadius; if (block.SectionStart) { ctx.Arc (x + rd, y + rd, rd, 180 * (Math.PI / 180), 270 * (Math.PI / 180)); ctx.LineTo (markerx, y); } else { ctx.MoveTo (markerx, y); } ctx.LineTo (markerx, y + height); if (block.SectionEnd) { ctx.LineTo (x + rd, y + height); ctx.Arc (x + rd, y + height - rd, rd, 90 * (Math.PI / 180), 180 * (Math.PI / 180)); } else { ctx.LineTo (x, y + height); } if (block.SectionStart) { ctx.LineTo (x, y + rd); } else { ctx.LineTo (x, y); } ctx.Color = color.AddLight (0.1).ToCairoColor (); ctx.Fill (); ctx.Rectangle (markerx, y, width - markerx, height); Cairo.Gradient pat = new Cairo.LinearGradient (x, y, x + width, y); pat.AddColorStop (0, color.AddLight (0.21).ToCairoColor ()); pat.AddColorStop (1, color.AddLight (0.3).ToCairoColor ()); ctx.Pattern = pat; ctx.Fill (); }
protected override void Render(Drawable window, Widget widget, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, Gdk.Rectangle expose_area, CellRendererState flags) { if (isDisposed) { return; } if (diffMode) { if (path.Equals(selctedPath)) { selectedLine = -1; selctedPath = null; } int w, maxy; window.GetSize(out w, out maxy); if (DrawLeft) { cell_area.Width += cell_area.X - leftSpace; cell_area.X = leftSpace; } var treeview = widget as FileTreeView; var p = treeview != null? treeview.CursorLocation : null; cell_area.Width -= RightPadding; window.DrawRectangle(widget.Style.BaseGC(Gtk.StateType.Normal), true, cell_area.X, cell_area.Y, cell_area.Width - 1, cell_area.Height); Gdk.GC normalGC = widget.Style.TextGC(StateType.Normal); Gdk.GC removedGC = new Gdk.GC(window); removedGC.Copy(normalGC); removedGC.RgbFgColor = Styles.LogView.DiffRemoveBackgroundColor.AddLight(-0.3).ToGdkColor(); Gdk.GC addedGC = new Gdk.GC(window); addedGC.Copy(normalGC); addedGC.RgbFgColor = Styles.LogView.DiffAddBackgroundColor.AddLight(-0.3).ToGdkColor(); Gdk.GC infoGC = new Gdk.GC(window); infoGC.Copy(normalGC); infoGC.RgbFgColor = widget.Style.Text(StateType.Normal).AddLight(0.2); Cairo.Context ctx = CairoHelper.Create(window); // Rendering is done in two steps: // 1) Get a list of blocks to render // 2) render the blocks int y = cell_area.Y + 2; // cline keeps track of the current source code line (the one to jump to when double clicking) int cline = 1; bool inHeader = true; BlockInfo currentBlock = null; List <BlockInfo> blocks = new List <BlockInfo> (); for (int n = 0; n < lines.Length; n++, y += lineHeight) { string line = lines [n]; if (line.Length == 0) { currentBlock = null; y -= lineHeight; continue; } char tag = line [0]; if (line.StartsWith("---", StringComparison.Ordinal) || line.StartsWith("+++", StringComparison.Ordinal)) { // Ignore this part of the header. currentBlock = null; y -= lineHeight; continue; } if (tag == '@') { int l = ParseCurrentLine(line); if (l != -1) { cline = l - 1; } inHeader = false; } else if (tag == '+' && !inHeader) { cline++; } BlockType type; switch (tag) { case '-': type = BlockType.Removed; break; case '+': type = BlockType.Added; break; case '@': type = BlockType.Info; break; default: type = BlockType.Unchanged; break; } if (currentBlock == null || type != currentBlock.Type) { if (y > maxy) { break; } // Starting a new block. Mark section ends between a change block and a normal code block if (currentBlock != null && IsChangeBlock(currentBlock.Type) && !IsChangeBlock(type)) { currentBlock.SectionEnd = true; } currentBlock = new BlockInfo() { YStart = y, FirstLine = n, Type = type, SourceLineStart = cline, SectionStart = (blocks.Count == 0 || !IsChangeBlock(blocks[blocks.Count - 1].Type)) && IsChangeBlock(type) }; blocks.Add(currentBlock); } // Include the line in the current block currentBlock.YEnd = y + lineHeight; currentBlock.LastLine = n; } // Now render the blocks // The y position of the highlighted line int selectedLineRowTop = -1; BlockInfo lastCodeSegmentStart = null; BlockInfo lastCodeSegmentEnd = null; foreach (BlockInfo block in blocks) { if (block.Type == BlockType.Info) { // Finished drawing the content of a code segment. Now draw the segment border and label. if (lastCodeSegmentStart != null) { DrawCodeSegmentBorder(infoGC, ctx, cell_area.X, cell_area.Width, lastCodeSegmentStart, lastCodeSegmentEnd, lines, widget, window); } lastCodeSegmentStart = block; } lastCodeSegmentEnd = block; if (block.YEnd < 0) { continue; } // Draw the block background DrawBlockBg(ctx, cell_area.X + 1, cell_area.Width - 2, block); // Get all text for the current block StringBuilder sb = new StringBuilder(); for (int n = block.FirstLine; n <= block.LastLine; n++) { string s = ProcessLine(lines [n]); if (n > block.FirstLine) { sb.Append('\n'); } if ((block.Type == BlockType.Added || block.Type == BlockType.Removed) && s.Length > 0) { sb.Append(' '); sb.Append(s, 1, s.Length - 1); } else { sb.Append(s); } } // Draw a special background for the selected line if (block.Type != BlockType.Info && p.HasValue && p.Value.X >= cell_area.X && p.Value.X <= cell_area.Right && p.Value.Y >= block.YStart && p.Value.Y <= block.YEnd) { int row = (p.Value.Y - block.YStart) / lineHeight; double yrow = block.YStart + lineHeight * row; double xrow = cell_area.X + LeftPaddingBlock; int wrow = cell_area.Width - 1 - LeftPaddingBlock; if (block.Type == BlockType.Added) { ctx.SetSourceColor(Styles.LogView.DiffAddBackgroundColor.AddLight(0.1).ToCairoColor()); } else if (block.Type == BlockType.Removed) { ctx.SetSourceColor(Styles.LogView.DiffRemoveBackgroundColor.AddLight(0.1).ToCairoColor()); } else { ctx.SetSourceColor(Styles.LogView.DiffHighlightColor.ToCairoColor()); xrow -= LeftPaddingBlock; wrow += LeftPaddingBlock; } ctx.Rectangle(xrow, yrow, wrow, lineHeight); ctx.Fill(); selectedLine = block.SourceLineStart + row; selctedPath = path; selectedLineRowTop = (int)yrow; } // Draw the line text. Ignore header blocks, since they are drawn as labels in DrawCodeSegmentBorder if (block.Type != BlockType.Info) { layout.SetMarkup(""); layout.SetText(sb.ToString()); Gdk.GC gc; switch (block.Type) { case BlockType.Removed: gc = removedGC; break; case BlockType.Added: gc = addedGC; break; case BlockType.Info: gc = infoGC; break; default: gc = normalGC; break; } window.DrawLayout(gc, cell_area.X + 2 + LeftPaddingBlock, block.YStart, layout); } // Finally draw the change symbol at the left margin DrawChangeSymbol(ctx, widget, cell_area.X + 1, cell_area.Width - 2, block); } // Finish the drawing of the code segment if (lastCodeSegmentStart != null) { DrawCodeSegmentBorder(infoGC, ctx, cell_area.X, cell_area.Width, lastCodeSegmentStart, lastCodeSegmentEnd, lines, widget, window); } // Draw the source line number at the current selected line. It must be done at the end because it must // be drawn over the source code text and segment borders. if (selectedLineRowTop != -1) { DrawLineBox(normalGC, ctx, ((Gtk.TreeView)widget).VisibleRect.Right - 4, selectedLineRowTop, selectedLine, widget, window); } ((IDisposable)ctx).Dispose(); removedGC.Dispose(); addedGC.Dispose(); infoGC.Dispose(); } else { // Rendering a normal text row int y = cell_area.Y + (cell_area.Height - height) / 2; window.DrawLayout(widget.Style.TextGC(GetState(widget, flags)), cell_area.X, y, layout); } }
public PickingRenderer( Game window ) { graphics = window.Graphics; vb = graphics.CreateDynamicVb( VertexFormat.Pos3fCol4b, verticesCount ); info = window.BlockInfo; }
void DrawCodeSegmentBorder(Gdk.GC gc, Cairo.Context ctx, double x, int width, BlockInfo firstBlock, BlockInfo lastBlock, string[] lines, Gtk.Widget widget, Gdk.Drawable window) { int shadowSize = 2; int spacing = 4; int bottomSpacing = (lineHeight - spacing) / 2; ctx.Rectangle(x + shadowSize + 0.5, firstBlock.YStart + bottomSpacing + spacing - shadowSize + 0.5, width - shadowSize * 2, shadowSize); ctx.SetSourceColor(Styles.LogView.DiffBoxSplitterColor.ToCairoColor()); ctx.LineWidth = 1; ctx.Fill(); ctx.Rectangle(x + shadowSize + 0.5, lastBlock.YEnd + bottomSpacing + 0.5, width - shadowSize * 2, shadowSize); ctx.SetSourceColor(Styles.LogView.DiffBoxSplitterColor.ToCairoColor()); ctx.Fill(); ctx.Rectangle(x + 0.5, firstBlock.YStart + bottomSpacing + spacing + 0.5, width, lastBlock.YEnd - firstBlock.YStart - spacing); ctx.SetSourceColor(Styles.LogView.DiffBoxBorderColor.ToCairoColor()); ctx.Stroke(); string text = lines[firstBlock.FirstLine].Replace("@", "").Replace("-", ""); text = "<span size='x-small'>" + text.Replace("+", "</span><span size='small'>➜</span><span size='x-small'> ") + "</span>"; layout.SetText(""); layout.SetMarkup(text); int tw, th; layout.GetPixelSize(out tw, out th); th--; int dy = (lineHeight - th) / 2; ctx.Rectangle(x + 2 + LeftPaddingBlock - 1 + 0.5, firstBlock.YStart + dy - 1 + 0.5, tw + 2, th + 2); ctx.LineWidth = 1; ctx.SetSourceColor(widget.Style.Base(StateType.Normal).ToCairoColor()); ctx.FillPreserve(); ctx.SetSourceColor(Styles.LogView.DiffBoxBorderColor.ToCairoColor()); ctx.Stroke(); window.DrawLayout(gc, (int)(x + 2 + LeftPaddingBlock), firstBlock.YStart + dy, layout); }
protected abstract Task HandleMessageAsync(BlockInfo message, BasicDeliverEventArgs eventArgs, IRmqConsumer consumer);
public void ScanDbInformation(string redishost, string rpcUrl) { //Rpc Info analyze RpcAPI ra = new RpcAPI(rpcUrl); ConcurrentQueue <BlockInfo> blockCollection = new ConcurrentQueue <BlockInfo>(); int height = ra.GetCurrentHeight(); var rh = new RedisHelper(redishost); var ktm = new KeyTypeManager(rh); List <Task> blockTasks = new List <Task>(); //Redis Info analyze blockTasks.Add(Task.Run(() => { ktm.GetAllKeyInfoCollection(); ktm.PrintSummaryInfo(false); })); //Get Block info Logger.WriteInfo("Get current block height information, current total height: {0}.", height); int reqHeight = 0; object obj = new object(); for (int i = 0; i < 8; i++) { blockTasks.Add(Task.Run(() => { while (true) { try { int threadHeight = 0; lock (obj) { reqHeight++; threadHeight = reqHeight; } if (threadHeight >= height) { break; } var jsonInfo = ra.GetBlockInfo(threadHeight); var block = new BlockInfo(threadHeight, jsonInfo); blockCollection.Enqueue(block); Thread.Sleep(50); } catch (Exception e) { Logger.WriteError("Get block info got exception: {0}", e.Message); } } })); } Task.WaitAll(blockTasks.ToArray <Task>()); //Analyze keys in collection Logger.WriteInfo("Begin analyze block information by multi tasks."); List <Task> contractTasks = new List <Task>(); Logger.WriteInfo("Begin print block info by height"); Logger.WriteInfo("-------------------------------------------------------------------------------------------------------------"); for (int i = 0; i < 8; i++) { contractTasks.Add(Task.Run(() => { while (true) { StringBuilder sb = new StringBuilder(); BlockInfo block = null; try { if (!blockCollection.TryDequeue(out block)) { break; } sb.AppendLine($"Block Height: {block.Height}, TxCount:{block.Transactions.Count}"); List <Task> analyzeTasks = new List <Task>(); //Analyze Block Hash analyzeTasks.Add(Task.Run(() => { var keyinfoList = ktm.HashList["Hash"] .FindAll(o => o.ValueInfo.ToString().Contains(block.BlockHash)); if (keyinfoList?.Count != 0) { foreach (var keyinfo in keyinfoList) { keyinfo.Checked = true; sb.AppendLine(keyinfo.ToString()); } } })); //Analyze BlockBody analyzeTasks.Add(Task.Run(() => { var blockBody = ktm.HashList["BlockBody"] .FirstOrDefault(o => o.ValueInfo.ToString().Contains(block.BlockHash)); if (blockBody != null) { blockBody.Checked = true; sb.AppendLine(blockBody.ToString()); } })); //Analyze PreviousBlockHash analyzeTasks.Add(Task.Run(() => { var blockHeader = ktm.HashList["BlockHeader"] .FirstOrDefault(o => o.ValueInfo.ToString().Contains(block.PreviousBlockHash)); if (blockHeader != null) { blockHeader.Checked = true; sb.AppendLine(blockHeader.ToString()); } })); //Analyze Transactions analyzeTasks.Add(Task.Run(() => { foreach (var transaction in block.Transactions) { //Transaction var txResult = ra.GetTxResult(transaction.Trim()); string incrementId = txResult["result"]["result"]["tx_info"]["IncrementId"].ToString(); string checkStr = $"\"IncrementId\": \"{incrementId}\""; var transactionInfo = ktm.HashList["Transaction"] .FirstOrDefault(o => o.ValueInfo.ToString().Contains(checkStr)); if (transactionInfo != null) { transactionInfo.Checked = true; sb.AppendLine(transactionInfo.ToString()); } //Transaction Result var transactionResult = ktm.HashList["TransactionResult"] .FirstOrDefault(o => o.ValueInfo.ToString().Contains(transaction.Trim())); if (transactionResult != null) { transactionResult.Checked = true; sb.AppendLine(transactionResult.ToString()); } } })); Task.WaitAll(analyzeTasks.ToArray <Task>()); } catch (Exception e) { Logger.WriteError("Analyze block height={0} info get exception: {1}", block?.Height, e.Message); } finally { sb.AppendLine( "-------------------------------------------------------------------------------------------------------------"); Logger.WriteInfo(sb.ToString()); } } })); } Task.WaitAll(contractTasks.ToArray <Task>()); //Print Unchecked key item info Logger.WriteInfo(string.Empty); Logger.WriteInfo("Print unchecked key info"); foreach (var item in ktm.HashList.Keys) { var listCollection = ktm.HashList[item].FindAll(o => o.Checked == false); Logger.WriteInfo($"Category:{item}, Unchecked count:{listCollection.Count}"); foreach (var keyinfo in listCollection) { Logger.WriteInfo(keyinfo.ToString()); } Logger.WriteInfo(string.Empty); } //Summary info Logger.WriteInfo("Summary basic type info"); foreach (var item in ktm.HashList.Keys) { int total = ktm.HashList[item].Count; int checkCount = ktm.HashList[item].FindAll(o => o.Checked == true).Count; int uncheckCount = total - checkCount; Logger.WriteInfo($"Category:{item}, Total:{total}, Checked:{checkCount}, Unchecked:{uncheckCount}"); } //Summary hash info Logger.WriteInfo(string.Empty); Logger.WriteInfo("Summary hash type info"); ktm.ConvertHashType(); foreach (var item in ktm.ProtoHashList.Keys) { int total = ktm.ProtoHashList[item].Count; int checkCount = ktm.ProtoHashList[item].FindAll(o => o.Checked == true).Count; int uncheckCount = total - checkCount; Logger.WriteInfo($"Category:{item}, Total:{total}, Checked:{checkCount}, Unchecked:{uncheckCount}"); } Logger.WriteInfo("Complete redis db content analyze."); }