public async Task <long> GetUnitPriceAsync(IChainContext chainContext)
        {
            var keys = _forkCache.Keys.ToArray();

            if (keys.Length == 0)
            {
                return(await GetUnitPriceAsync());
            }
            var  minHeight  = keys.Select(k => k.BlockHeight).Min();
            long?unitPrice  = null;
            var  blockIndex = new BlockIndex
            {
                BlockHash   = chainContext.BlockHash,
                BlockHeight = chainContext.BlockHeight
            };

            do
            {
                if (_forkCache.TryGetValue(blockIndex, out var value))
                {
                    unitPrice = value;
                }

                var link = _chainBlockLinkService.GetCachedChainBlockLink(blockIndex.BlockHash);
                blockIndex.BlockHash = link?.PreviousBlockHash;
                blockIndex.BlockHeight--;
            } while (blockIndex.BlockHash != null && blockIndex.BlockHeight >= minHeight);

            if (unitPrice == null)
            {
                unitPrice = await GetUnitPriceAsync();
            }
            Logger.LogTrace($"Get tx size fee unit price: {unitPrice.Value}");
            return(unitPrice.Value);
        }
Esempio n. 2
0
        public Task HandleAsync(Block block, TransactionResult transactionResult, LogEvent logEvent)
        {
            var eventData = new ExtraTokenListModified();

            eventData.MergeFrom(logEvent);
            var blockIndex = new BlockIndex
            {
                BlockHash   = block.GetHash(),
                BlockHeight = block.Height
            };

            if (eventData.SymbolListToPayTxSizeFee == null)
            {
                return(Task.CompletedTask);
            }
            var newTokenInfoList = new List <AvailableTokenInfoInCache>();

            foreach (var tokenInfo in eventData.SymbolListToPayTxSizeFee.SymbolsToPayTxSizeFee)
            {
                newTokenInfoList.Add(new AvailableTokenInfoInCache
                {
                    TokenSymbol      = tokenInfo.TokenSymbol,
                    AddedTokenWeight = tokenInfo.AddedTokenWeight,
                    BaseTokenWeight  = tokenInfo.BaseTokenWeight
                });
            }

            _symbolListToPayTxFeeService.SetExtraAcceptedTokenInfoToForkCache(blockIndex, newTokenInfoList);
            return(Task.CompletedTask);
        }
Esempio n. 3
0
    /// <summary>
    /// Casts the ray and does whatever the action is. (Template Method pattern)
    /// </summary>
    /// <returns>
    /// The ray and do.
    /// </returns>
    /// <param name='action'>
    /// If set to <c>true</c> action.
    /// </param>
    public bool CastRayAndDo( OnHit action )
    {
        RaycastHit hit;
        Ray cast = getRayCast();
        int mask = 1 << LayerMask.NameToLayer("Catwalk");
        if ( Physics.Raycast( cast, out hit, CastTestDist, mask ) )
        {
            var blockSpawner = Projectile.GetComponent<BlockSpawner>();

            if ( blockSpawner != null && hit.collider.gameObject.IsProjectile() == false )
            {
                var worldObj = GameObject.FindGameObjectWithTag("World");
                var World = worldObj.GetComponent<GenerateWorld>();
                //var createAt = cast.origin + (cast.direction * (hit.distance - 0.1f));
                var createAt = hit.point + (hit.normal *(0.5f));

                var playerPos = getRayCast().origin;
                var futureIndex = World.getIndexOfPoint( ref createAt);
                var playerIndexTop = World.getIndexOfPoint( ref playerPos);
                var playerIndexBottom = new BlockIndex(playerIndexTop.x, playerIndexTop.y-1, playerIndexTop.z);

                //Don't create on top of ourselves:
                if ( (playerIndexTop != futureIndex) && (playerIndexBottom != futureIndex) )
                {
                    Vector3 currentDirection = getRayCast().direction.normalized;
                    action(World, blockSpawner, hit, currentDirection, createAt, futureIndex);
                }
            }
            return true;
        }
        return false;
    }
        public int Complete(BlockIndex request, out PeerHash peer)
        {
            OmnibusReservation reservation;

            byBlock.TryGetValue(request, out reservation);

            if (reservation != null)
            {
                HashSet <OmnibusReservation> forPeer;
                HashSet <OmnibusReservation> forPiece;

                byPeer.TryGetValue(reservation.Peer, out forPeer);
                byPiece.TryGetValue(reservation.Request.Piece, out forPiece);

                forPeer.Remove(reservation);
                forPiece.Remove(reservation);
                byBlock.Remove(request);

                peer = reservation.Peer;
                return(forPeer.Count);
            }

            peer = null;
            return(0);
        }
        private async Task <BlockIndex> GetBlockIndexAsync(TransactionBlockIndex transactionBlockIndex,
                                                           Hash chainBranchBlockHash = null)
        {
            var chain = await _blockchainService.GetChainAsync();

            if (chainBranchBlockHash == null)
            {
                chainBranchBlockHash = chain.BestChainHash;
            }

            var previousBlockIndexList =
                transactionBlockIndex.PreviousExecutionBlockIndexList ?? new RepeatedField <BlockIndex>();
            var lastBlockIndex         = new BlockIndex(transactionBlockIndex.BlockHash, transactionBlockIndex.BlockHeight);
            var reversedBlockIndexList = previousBlockIndexList.Concat(new[] { lastBlockIndex }).Reverse().ToList();

            foreach (var blockIndex in reversedBlockIndexList)
            {
                var blockHash =
                    await _blockchainService.GetBlockHashByHeightAsync(chain, blockIndex.BlockHeight,
                                                                       chainBranchBlockHash);

                if (blockIndex.BlockHash == blockHash)
                {
                    // If TransactionBlockIndex exists, then read the result via TransactionBlockIndex
                    return(blockIndex);
                }
            }

            return(null);
        }
Esempio n. 6
0
        public void TestBlockIndex()
        {
            using var key = Key.Create(SignatureAlgorithm.Ed25519);
            var blockTree      = new BlockTree(Array.Empty <Byte>(), key);
            var verifiedBlocks = new List <Block>();

            for (var i = 0; i != 3; i++)
            {
                Assert.True(
                    blockTree.TryAdd(blockTree.Root, Encoding.UTF8.GetBytes($"Hello #{i}"), key, out var newBlock)
                    );
                verifiedBlocks.Add(newBlock !);
            }

            var blockIndex = new BlockIndex();

            foreach (var verifiedBlock in verifiedBlocks)
            {
                blockIndex.Add(verifiedBlock);
            }
            blockIndex.Add(blockTree.Root);

            var blocks     = blockIndex.GetAllBlocks();
            var blockTree2 = new BlockTree(blocks);
        }
Esempio n. 7
0
        /**
         * 循环搜索,直到出现第一个重复的MS窗口停止
         * 即便这样,如果在第一轮扫描中没有出现的窗口是无法被初始化的,需要在后续不断的作补充
         *
         */
        private void buildWindowsRanges()
        {
            jobInfo.log("Start getting windows", "Getting Windows");
            int      i        = 0;
            Spectrum spectrum = spectrumList.spectrum(0);

            while (spectrum.cvParamChild(CVID.MS_ms_level).value.ToString().Equals(MsLevel.MS2))
            {
                double mz          = getPrecursorIsolationWindowParams(spectrum, CVID.MS_isolation_window_target_m_z);
                double lowerOffset = getPrecursorIsolationWindowParams(spectrum, CVID.MS_isolation_window_lower_offset);
                double upperOffset = getPrecursorIsolationWindowParams(spectrum, CVID.MS_isolation_window_upper_offset);

                if (rangeMap.Contains(mz))
                {
                    break;
                }

                WindowRange range      = new WindowRange(mz - lowerOffset, mz + upperOffset, mz);
                BlockIndex  swathIndex = new BlockIndex();
                swathIndex.setWindowRange(range);
                rangeMap.Add(mz, swathIndex);
                ms2Map.Add(mz, ArrayList.Synchronized(new ArrayList()));

                i++;
                spectrum = spectrumList.spectrum(i);
            }
            jobInfo.log("Finished Getting Windows");
        }
        public async Task UpdateTransactionBlockIndicesByLibHeight_Test()
        {
            var blockHeader = await _blockchainService.GetBestChainLastBlockHeaderAsync();

            var txId       = HashHelper.ComputeFrom("Transaction");
            var blockIndex = new BlockIndex
            {
                BlockHash   = blockHeader.GetHash(),
                BlockHeight = blockHeader.Height
            };
            await _transactionBlockIndexService.AddBlockIndexAsync(new List <Hash> {
                txId
            }, blockIndex);

            await _transactionBlockIndexService.UpdateTransactionBlockIndicesByLibHeightAsync(blockHeader.Height);

            _transactionBlockIndexProvider.TryGetTransactionBlockIndex(txId, out var transactionBlockIndex);
            transactionBlockIndex.BlockHash.ShouldBe(blockHeader.GetHash());
            transactionBlockIndex.BlockHeight.ShouldBe(blockHeader.Height);

            await _transactionBlockIndexService.UpdateTransactionBlockIndicesByLibHeightAsync(
                blockHeader.Height + KernelConstants.ReferenceBlockValidPeriod);

            _transactionBlockIndexProvider.TryGetTransactionBlockIndex(txId, out transactionBlockIndex);
            transactionBlockIndex.ShouldBeNull();
        }
        public async Task <List <AvailableTokenInfoInCache> > GetExtraAcceptedTokensInfoAsync(
            IChainContext chainContext)
        {
            var keys = _cacheProvider.GetForkCacheKeys();

            if (keys.Length == 0)
            {
                return(await GetExtraAcceptedTokensInfoFromCacheAsync());
            }
            var blockIndex = new BlockIndex
            {
                BlockHash   = chainContext.BlockHash,
                BlockHeight = chainContext.BlockHeight
            };
            var minHeight = keys.Select(k => k.BlockHeight).Min();
            List <AvailableTokenInfoInCache> tokenInfoDic = null;

            do
            {
                if (_cacheProvider.TryGetExtraAcceptedTokensInfoFromForkCache(blockIndex, out var value))
                {
                    tokenInfoDic = value;
                    break;
                }

                var link = _chainBlockLinkService.GetCachedChainBlockLink(blockIndex.BlockHash);
                blockIndex.BlockHash = link?.PreviousBlockHash;
                blockIndex.BlockHeight--;
            } while (blockIndex.BlockHash != null && blockIndex.BlockHeight >= minHeight);

            return(tokenInfoDic ?? await GetExtraAcceptedTokensInfoFromCacheAsync());
        }
        public void AddSmartContractRegistration(Address address, Hash codeHash, BlockIndex blockIndex)
        {
            var smartContractRegistrationCache = new SmartContractRegistrationCache
            {
                Address     = address,
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight,
                SmartContractRegistration = new SmartContractRegistration
                {
                    CodeHash = codeHash
                }
            };

            //Add genesis block registration cache to lib cache directly
            if (blockIndex.BlockHeight == 1)
            {
                _addressSmartContractRegistrationMappingCache.TryAdd(address, smartContractRegistrationCache);
                return;
            }

            if (!_forkCache.TryGetValue(address, out var caches))
            {
                caches = new List <SmartContractRegistrationCache>();
                _forkCache[address] = caches;
            }

            caches.Add(smartContractRegistrationCache);
        }
        public async Task UpdateOneBlockIndexWithBestChain()
        {
            var previousBlockHeader = _kernelTestHelper.BestBranchBlockList.Last().Header;
            var block      = _kernelTestHelper.GenerateBlock(previousBlockHeader.Height, HashHelper.ComputeFrom("PreBlockHash"));
            var txId       = HashHelper.ComputeFrom("Transaction");
            var blockIndex = new BlockIndex
            {
                BlockHash   = block.GetHash(),
                BlockHeight = block.Height
            };
            await _transactionBlockIndexService.AddBlockIndexAsync(new List <Hash> {
                txId
            }, blockIndex);

            var chain = await _blockchainService.GetChainAsync();

            await AddBlockAsync(chain, block);
            await SetBestChain(chain, block);

            var actual = await _transactionBlockIndexService.GetTransactionBlockIndexAsync(txId);

            Assert.Equal(blockIndex, actual);

            var cacheInBestBranch = await _transactionBlockIndexService.GetTransactionBlockIndexAsync(txId);

            Assert.Equal(blockIndex, cacheInBestBranch);
        }
Esempio n. 12
0
        private void parseAndStoreMS2Block()
        {
            jobInfo.log("Start Processing MS2 List");
            IZDPD izdpd;

            if (jobInfo.jobParams.useStackZDPD())
            {
                izdpd = new StackZDPD(this);
            }
            else
            {
                izdpd = new ZDPD(this);
            }

            foreach (double key in ms2Table.Keys)
            {
                List <TempIndex> tempIndexList = ms2Table[key] as List <TempIndex>;
                WindowRange      range         = rangeTable[key] as WindowRange;
                //为每一个key组创建一个SwathBlock
                BlockIndex index = new BlockIndex();
                index.level    = 2;
                index.startPtr = startPosition;
                index.setWindowRange(range);

                jobInfo.log(null, "MS2:" + progress + "/" + ms2Table.Keys.Count);
                progress++;
                izdpd.compressMS2(tempIndexList, index);
                index.endPtr = startPosition;
                indexList.Add(index);
                jobInfo.log("MS2 Group Finished:" + progress + "/" + ms2Table.Keys.Count);
            }
        }
Esempio n. 13
0
        public async Task UpdateOneBlockIndexWithoutBestChain()
        {
            var previousBlockHeader = _kernelTestHelper.BestBranchBlockList.Last().Header;
            var block = _kernelTestHelper.GenerateBlock(previousBlockHeader.Height, Hash.FromString("PreBlockHash"));
            var chain = await _blockchainService.GetChainAsync();

            await AddBlockAsync(chain, block);

            var txId       = Hash.FromString("Transaction");
            var blockIndex = new BlockIndex
            {
                BlockHash   = block.GetHash(),
                BlockHeight = block.Height
            };
            await _transactionBlockIndexService.AddBlockIndexAsync(new List <Hash> {
                txId
            }, blockIndex);

            var actual = await _transactionBlockIndexService.GetTransactionBlockIndexAsync(txId);

            Assert.Null(actual);

            var cacheInBestBranch = await _transactionBlockIndexService.GetTransactionBlockIndexAsync(txId);

            Assert.Null(cacheInBestBranch);

            var cacheInForkBranch =
                await _transactionBlockIndexService.ValidateTransactionBlockIndexExistsInBranchAsync(txId,
                                                                                                     block.GetHash());

            Assert.True(cacheInForkBranch);
        }
Esempio n. 14
0
        private async Task <Dictionary <int, ICalculateWay> > GetPieceWiseFuncUnderContextAsync()
        {
            var keys = _cacheCacheProvider.GetForkCacheKeys();

            if (keys.Length == 0)
            {
                return(await GetDefaultPieceWiseFunctionAsync());
            }
            var minHeight = keys.Select(k => k.BlockHeight).Min();
            Dictionary <int, ICalculateWay> algorithm = null;
            var blockIndex = new BlockIndex
            {
                BlockHash   = CalculateAlgorithmContext.BlockIndex.BlockHash,
                BlockHeight = CalculateAlgorithmContext.BlockIndex.BlockHeight
            };

            do
            {
                if (_cacheCacheProvider.TryGetPieceWiseFunctionFromForkCacheByBlockIndex(blockIndex, out var value))
                {
                    algorithm = value;
                    break;
                }

                var link = _chainBlockLinkService.GetCachedChainBlockLink(blockIndex.BlockHash);
                blockIndex.BlockHash = link?.PreviousBlockHash;
                blockIndex.BlockHeight--;
            } while (blockIndex.BlockHash != null && blockIndex.BlockHeight >= minHeight);

            return(algorithm ?? await GetDefaultPieceWiseFunctionAsync());
        }
Esempio n. 15
0
        public async Task <int> GetLimitAsync(IChainContext chainContext)
        {
            var keys = _forkCache.Keys.ToArray();

            if (keys.Length == 0)
            {
                return(await GetLimitAsync());
            }
            var minHeight  = keys.Select(k => k.BlockHeight).Min();
            int?limit      = null;
            var blockIndex = new BlockIndex
            {
                BlockHash   = chainContext.BlockHash,
                BlockHeight = chainContext.BlockHeight
            };

            do
            {
                if (_forkCache.TryGetValue(blockIndex, out var value))
                {
                    limit = value;
                    break;
                }

                var link = _chainBlockLinkService.GetCachedChainBlockLink(blockIndex.BlockHash);
                blockIndex.BlockHash = link?.PreviousBlockHash;
                blockIndex.BlockHeight--;
            } while (blockIndex.BlockHash != null && blockIndex.BlockHeight >= minHeight);

            return(limit ?? await GetLimitAsync());
        }
Esempio n. 16
0
        public async Task Net_Token_Fee_Calculate_After_Update_Piecewise_Function_Test()
        {
            await InitializeCoefficientAsync();

            var calculateNetCostStrategy = Application.ServiceProvider.GetRequiredService <ICalculateTrafficCostStrategy>();
            var ps = await GetCoefficientByType(FeeTypeEnum.Traffic);

            var apiParam = new CalculateFeeCoefficient
            {
                FeeType        = FeeTypeEnum.Traffic,
                FunctionType   = CalculateFunctionTypeEnum.Liner,
                PieceKey       = 1000000,
                CoefficientDic = { { "numerator", 1 }, { "denominator", 400 } }
            };
            var           blockIndex   = new BlockIndex();
            IChainContext chainContext = new ChainContext
            {
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight
            };
            var theOne = ps.Coefficients.SingleOrDefault(x => x.PieceKey == 1000000);

            ps.Coefficients.Remove(theOne);
            ps.Coefficients.Add(apiParam);
            await HandleTestAsync(ps, blockIndex);

            var size       = 10000;
            var updatedFee = await calculateNetCostStrategy.GetCostAsync(chainContext, size);

            updatedFee.ShouldBe(25_0000_0000);
        }
Esempio n. 17
0
        /// <summary>
        /// Specific API
        /// 从Aird文件中读取,但是不要将m/z数组的从Integer改为Float
        /// <para>
        /// Read from aird, but not convert the m/z array from integer to float
        ///
        /// </para>
        /// </summary>
        /// <param name="index">      索引序列号 block index </param>
        /// <param name="rt">         光谱产出时刻 retention time for the spectrum </param>
        /// <param name="compressor"> 压缩方式 compression method 0: ZDPD 1: S-ZDPD, default compressor = 0 </param>
        /// <returns> 该时刻产生的光谱信息, 其中mz数据以int类型返回 the target rt's spectrum with integer mz array </returns>
        public virtual MzIntensityPairs getSpectrumAsInteger(BlockIndex index, float rt, int compressor)
        {
            if (compressor == 0)
            {
                return(getSpectrumAsInteger(index, rt));
            }
            else if (compressor == 1)
            {
                IList <float>    rts              = index.rts;
                int              position         = rts.IndexOf(rt);
                MzIntensityPairs mzIntensityPairs = getSpectrumByIndex(index, position);
                int[]            mzArray          = new int[mzIntensityPairs.getMzArray().Length];
                for (int i = 0; i < mzArray.Length; i++)
                {
                    mzArray[i] = (int)(mzIntensityPairs.getMzArray()[i] * mzPrecision);
                }
                return(new MzIntensityPairs(mzArray, mzIntensityPairs.getIntensityArray()));
            }
            else
            {
                Console.WriteLine("No such compressor.");
            }

            return(null);
        }
Esempio n. 18
0
        /// <summary>
        /// 从一个完整的Swath Block块中取出一条记录
        /// 查询条件: 1. block索引号 2. rt
        /// <para>
        /// Read a spectrum from aird with block index and target rt
        ///
        /// </para>
        /// </summary>
        /// <param name="index"> block index </param>
        /// <param name="rt">    retention time of the target spectrum </param>
        /// <returns> the target spectrum </returns>
        public virtual MzIntensityPairs getSpectrumByRt(BlockIndex index, float rt)
        {
            IList <float> rts      = index.rts;
            int           position = rts.IndexOf(rt);

            return(getSpectrumByIndex(index, position));
        }
Esempio n. 19
0
 public void compressMS2(List <TempIndex> tempIndexList, BlockIndex index)
 {
     if (converter.jobInfo.jobParams.threadAccelerate)
     {
         Hashtable table = Hashtable.Synchronized(new Hashtable());
         //使用多线程处理数据提取与压缩
         Parallel.For(0, tempIndexList.Count, (i, ParallelLoopState) =>
         {
             TempIndex tempIndex = tempIndexList[i];
             TempScan ts         = new TempScan(tempIndex.num, tempIndex.rt, tempIndex.tic);
             if (converter.jobInfo.jobParams.includeCV)
             {
                 ts.cvs = tempIndex.cvList;
             }
             converter.compress(converter.spectrumList.spectrum(tempIndex.num, true), ts);
             table.Add(i, ts);
         });
         converter.outputWithOrder(table, index);
     }
     else
     {
         foreach (TempIndex tempIndex in tempIndexList)
         {
             TempScan ts = new TempScan(tempIndex.num, tempIndex.rt, tempIndex.tic);
             if (converter.jobInfo.jobParams.includeCV)
             {
                 ts.cvs = tempIndex.cvList;
             }
             converter.compress(converter.spectrumList.spectrum(tempIndex.num, true), ts);
             converter.addToIndex(index, ts);
         }
     }
 }
Esempio n. 20
0
        private void save_Click(object sender, RoutedEventArgs e)
        {
            var doc = this.BlockIndex.Document as HTMLDocument;

            xml           = (string)BlockIndex.InvokeScript("save", null);
            CodeView.Text = xml;
            Debug.WriteLine(xml);
        }
        public async Task ProcessConfigurationAsync(ByteString byteString, BlockIndex blockIndex)
        {
            var executionObserverBranchThreshold = new ExecutionObserverThreshold();

            executionObserverBranchThreshold.MergeFrom(byteString);
            await _executionObserverThresholdProvider.SetExecutionObserverThresholdAsync(blockIndex,
                                                                                         executionObserverBranchThreshold);
        }
Esempio n. 22
0
        public TableSourceGC(TableSource tableSource)
        {
            this.tableSource = tableSource;
            deletedRows      = new BlockIndex <int>();

            // lastSuccess = DateTime.UtcNow;
            // lastTry = null;
        }
Esempio n. 23
0
        public TableSourceGC(TableSource tableSource)
        {
            this.tableSource = tableSource;
            deletedRows = new BlockIndex<int>();

            // lastSuccess = DateTime.UtcNow;
            // lastTry = null;
        }
        private void CheckBlockExecutedDataCache(BlockIndex blockIndex, Chain chain,
                                                 TransactionResult transactionResult, Dictionary <string, Transaction> transactionDic, bool existChangeHeight,
                                                 bool existExecutedData)
        {
            {
                _chainBlockchainExecutedDataCacheProvider
                .TryGetChangeHeight(GetBlockExecutedDataKey <Chain>(), out var chainChangeHeight)
                .ShouldBe(existChangeHeight);
                if (existChangeHeight)
                {
                    chainChangeHeight.ShouldBe(blockIndex.BlockHeight);
                }

                _chainBlockchainExecutedDataCacheProvider
                .TryGetBlockExecutedData(GetBlockExecutedDataKey <Chain>(), out var chainExecutedData)
                .ShouldBe(existExecutedData);
                if (existExecutedData)
                {
                    chainExecutedData.ShouldBe(chain);
                }
            }

            {
                _transactionResultBlockchainExecutedDataCacheProvider
                .TryGetChangeHeight(GetBlockExecutedDataKey <TransactionResult>(transactionResult.TransactionId),
                                    out var transactionResultChangeHeight).ShouldBe(existChangeHeight);
                if (existChangeHeight)
                {
                    transactionResultChangeHeight.ShouldBe(blockIndex.BlockHeight);
                }
                _transactionResultBlockchainExecutedDataCacheProvider
                .TryGetBlockExecutedData(
                    GetBlockExecutedDataKey <TransactionResult>(transactionResult.TransactionId),
                    out var transactionResultExecutedData).ShouldBe(existExecutedData);
                if (existExecutedData)
                {
                    transactionResultExecutedData.ShouldBe(transactionResult);
                }
            }

            foreach (var transaction in transactionDic)
            {
                _transactionBlockchainExecutedDataCacheProvider
                .TryGetChangeHeight(transaction.Key, out var transactionChangeHeight)
                .ShouldBe(existChangeHeight);
                if (existChangeHeight)
                {
                    transactionChangeHeight.ShouldBe(blockIndex.BlockHeight);
                }
                _transactionBlockchainExecutedDataCacheProvider
                .TryGetBlockExecutedData(transaction.Key, out var transactionExecutedData)
                .ShouldBe(existExecutedData);
                if (existExecutedData)
                {
                    transactionExecutedData.ShouldBe(transaction.Value);
                }
            }
        }
Esempio n. 25
0
    public GameObject this[BlockIndex key]
    {
        get
        {
            if ( Cells.ContainsKey(key) )
            {
                return Cells[key];
            }

            return null;
        }

        set
        {
            bool needsAdd = true;

            if ( value == null )
            {
                if (Cells.ContainsKey(key))
                {
                    var current = Cells[key];
                    var removeHandler = CellRemoved;
                    if ( removeHandler != null ) { removeHandler(new VoxelArgs(key, current)); }
                    Cells.Remove(key);
                }
                return;
            }

            if ( Cells.ContainsKey(key) )
            {
                var current = Cells[key];
                if ( current != value)
                {
                    var removeHandler = CellRemoved;
                    if ( removeHandler != null ) { removeHandler(new VoxelArgs(key, current)); }
                }
                else
                {
                    needsAdd = false;
                }
            }

            if ( needsAdd )
            {
                Cells[key] = value;
                var block = value.GetBlock();
                if ( block != null )
                {
                    block.Index = key;
                }

                var addHandler = CellAdded;
                if ( addHandler != null ) { addHandler(new VoxelArgs(key, value)); }
            }

        }
    }
Esempio n. 26
0
 public static void CallBlockRead(this RepositoryHooks hooks, FileHash hash, BlockIndex block, DataBlock payload)
 {
     hooks.OnBlockRead?.Invoke(new BlockRead
     {
         Hash    = hash,
         Block   = block,
         Payload = payload
     });
 }
Esempio n. 27
0
        public void AddAlgorithmByBlock(BlockIndex blockIndex, IList <ICalculateWay> allFunc)
        {
            var funcDic = new Dictionary <int, ICalculateWay>();

            foreach (var func in allFunc)
            {
                funcDic[func.PieceKey] = func;
            }
            _cacheCacheProvider.SetPieceWiseFunctionToForkCache(blockIndex, funcDic);
        }
Esempio n. 28
0
 public override string ToString()
 {
     return(string.Format(
                "Blocks\tBlockIndex:{0},StartPosition:{1},BlockSize:{2},CompletedPosition:{3},FilePath:{4}",
                BlockIndex.ToString(),
                StartPosition.ToString(),
                BlockSize.ToString(),
                CompletedPosition.ToString(),
                FilePath));
 }
Esempio n. 29
0
        public int CompareTo(BookBlockIndices other)
        {
            int result = BookIndex.CompareTo(other.BookIndex);

            if (result == 0)
            {
                result = BlockIndex.CompareTo(other.BlockIndex);
            }
            return(result);
        }
Esempio n. 30
0
        public void SendPiece(PeerHash peer, BlockIndex block, DataBlock payload)
        {
            CoordinatorEntry entry = context.Collection.Find(peer);
            Piece            piece = new Piece(block, payload);

            if (entry != null)
            {
                context.Hooks.SendPiece(entry.Peer, piece);
            }
        }
Esempio n. 31
0
        public void outputWithOrder(Hashtable table, BlockIndex index)
        {
            ArrayList keys = new ArrayList(table.Keys);

            keys.Sort();
            foreach (int key in keys)
            {
                addToIndex(index, table[key]);
            }
        }
Esempio n. 32
0
        public void SendRequest(PeerHash peer, BlockIndex block)
        {
            CoordinatorEntry entry   = context.Collection.Find(peer);
            Request          request = new Request(block);

            if (entry != null)
            {
                context.Hooks.SendRequest(entry.Peer, request);
            }
        }
Esempio n. 33
0
    public Quaternion ComputeRotationForPlacement( GenerateWorld World, BlockSpawner spawner, Vector3 normalOfPlacementSurface, Vector3 curDir, BlockIndex futureIndex)
    {
        Quaternion output = Quaternion.identity;

        //Gets the block prefab so we can check its properties:
        var block = spawner.SpawnType;

        //We only care about the direction, not the inclination:
        curDir.y = 0;
        curDir.Normalize();

        //Due to gimbal lock that can happen along a wall, we use a different axis and then rotate into the axis we want!
        //Thus the 270 rotation.

        Quaternion wallDirectionAxis = Quaternion.FromToRotation( Vector3.up, normalOfPlacementSurface);
        Quaternion upDirectionAxis = Quaternion.FromToRotation( Vector3.right, normalOfPlacementSurface) * Quaternion.Euler(0,270,0);
        Quaternion rotationTowardDown = wallDirectionAxis * upDirectionAxis ;

        //Is it going on the floor/ceiling: 0.2f episilon
        if ( normalOfPlacementSurface.y < -0.2f || normalOfPlacementSurface.y > 0.2f)
        {
            float angle = Vector3.Angle(Vector3.forward, curDir);
            var side = Vector3.Cross( Vector3.up, curDir);
            angle *= (side.z < 0) ? 1 : -1;

            upDirectionAxis = Quaternion.AngleAxis( angle, normalOfPlacementSurface);
            var upDirEuler = upDirectionAxis.eulerAngles;

            rotationTowardDown = wallDirectionAxis * upDirectionAxis ;

            //This adds the special rotation that the object gets when its on the floor or ceiling.
            //This exists because different objects act differently when placed.  This covers most cases!
            if ( block.SpecialRotateX90) { rotationTowardDown = rotationTowardDown  * Quaternion.Euler(90,0,0); }
            if ( block.SpecialRotateY90) { rotationTowardDown = rotationTowardDown  * Quaternion.Euler(0,90,0); }
            if ( block.SpecialRotateZ90) { rotationTowardDown = rotationTowardDown  * Quaternion.Euler(0,0,0); }

            if ( block.SpecialRotateX270) { rotationTowardDown = rotationTowardDown  * Quaternion.Euler(270,0,0); }
            if ( block.SpecialRotateY270) { rotationTowardDown = rotationTowardDown  * Quaternion.Euler(0,270,0); }
            if ( block.SpecialRotateZ270) { rotationTowardDown = rotationTowardDown  * Quaternion.Euler(0,0,270); }

        }

        Vector3 rot = rotationTowardDown.eulerAngles;

        //If the object is designed to sit only on the floor remove the x and z rotations:
        if( block.RotatesTowardWalls == false )
        {
            //Take only the y rotation.
            rot.x = 0;
            rot.z = 0;
        }

        output = Quaternion.Euler(rot);
        return output;
    }
Esempio n. 34
0
        protected new void outputWithOrder(Hashtable table, BlockIndex index)
        {
            ArrayList keys = new ArrayList(table.Keys);

            keys.Sort();
            foreach (int key in keys)
            {
                TempScan tempScan = (TempScan)table[key];
                addToIndex(index, tempScan);
            }
        }
Esempio n. 35
0
    public bool CreateBlockAt( Vector3 pos, string blockId, Vector3 eulerRotation)
    {
        Vector3 cellPos = new Vector3(pos.x * 0.5f, pos.y * 0.5f, pos.z * 0.5f);
        var index = WorldCubeData.GetCellIndex(ref cellPos);
        SnapRotationToGrid(ref eulerRotation);
        Vector3 gridPos = new Vector3(index.x * 2, index.y * 2, index.z * 2);

        var playerPos = GameObject.FindGameObjectWithTag("MainCamera").transform.position;
        var playerIndexTop = getIndexOfPoint( ref playerPos);
        var playerIndexBottom = new BlockIndex(playerIndexTop.x, playerIndexTop.y-1, playerIndexTop.z);

        //Don't create on top of ourselves:
        if ( (playerIndexTop != index) && (playerIndexBottom != index) )
        {
            //WorldCubeData[index] = new Block(spawnType, (int)eulerRotation.x, (int)eulerRotation.y, (int)eulerRotation.z);
            GameObject clone = Instantiate(BlockTypes[blockId], gridPos, Quaternion.Euler(eulerRotation)) as GameObject;
            clone.name = blockId + " " + index.x + ", " + index.y + "," + index.z;

            Transform parent = findBestParent(blockId);

            clone.transform.parent = parent;
            WorldCubeData[index] = clone;
            clone.GetBlock().ConfigureSubType();
            SaveLevel("Level.txt");

            var onChanged = OnWorldChanged;
            if ( onChanged != null )
            {
                onChanged(index, clone);
            }

            return true;
        }

        return false;
    }
Esempio n. 36
0
 /// <summary>
 /// Gets the block at the given index;
 /// </summary>
 /// <returns>The block at index.</returns>
 /// <param name="index">Index.</param>
 public GameObject getBlockAtIndex( BlockIndex index )
 {
     return WorldCubeData[index];
 }
Esempio n. 37
0
    public void Rotate( BlockIndex index )
    {
        if ( Cells.ContainsKey(index) )
        {
            var current = Cells[index];
            current.transform.Rotate(0, 90, 0);

            var rotationHandler = CellChanged;
            if ( rotationHandler != null ) { rotationHandler( new VoxelArgs(index, current) ); }

        }
    }
Esempio n. 38
0
    public GameObject this[Vector3 index]
    {
        get
        {
            int x = (int)Math.Round(index.x);
            int y = (int)Math.Round(index.y);
            int z = (int)Math.Round(index.z);
            BlockIndex key = new BlockIndex(x,y,z);

            if ( Cells.ContainsKey(key) )
            {
                return Cells[key];
            }

            return null;
        }

        set {
            int x = (int)Math.Round(index.x);
            int y = (int)Math.Round(index.y);
            int z = (int)Math.Round(index.z);
            BlockIndex key = new BlockIndex(x,y,z);
            bool needsAdd = true;

            if ( value == null )
            {
                if (Cells.ContainsKey(key))
                {
                    var current = Cells[key];
                    var removeHandler = CellRemoved;
                    if ( removeHandler != null ) { removeHandler(new VoxelArgs(key, current)); }
                    Cells.Remove(key);
                }
                return;
            }

            if ( Cells.ContainsKey(key) )
            {
                var current = Cells[key];
                if ( current != value)
                {
                    var removeHandler = CellRemoved;
                    if ( removeHandler != null ) { removeHandler(new VoxelArgs(key, current)); }
                }
                else
                {
                    needsAdd = false;
                }
            }

            if ( needsAdd )
            {
                Cells[key] = value;
                var addHandler = CellAdded;
                if ( addHandler != null ) { addHandler(new VoxelArgs(key, value)); }
            }

        }
    }
Esempio n. 39
0
 public VoxelArgs(BlockIndex index, GameObject Block)
 {
     this.Index = index;
     this.Block = Block;
 }
Esempio n. 40
0
    // Use this for initialization
    void Start()
    {
        OptimizedChunk = new GameObject();
        OptimizedChunk.transform.parent = this.transform.parent;
        OptimizedChunk.name = this.name + "_CHUNKS";

        meshFilters = this.gameObject.FindInChildren<MeshFilter>();
        renderers = this.gameObject.FindInChildren<MeshRenderer>();

        RecalculateMesh();
        dirty = false;

        GenerateWorld.World.OnWorldChanged += (BlockIndex index, GameObject block) => {

            var pos = block.transform.position;
            BlockIndex chunkIndex = new BlockIndex( (int)(pos.x / ChunkSize), (int)(pos.y / ChunkSize), (int)(pos.z / ChunkSize));
            dirtyIndices.Add(chunkIndex);

            this.dirty = true;
        };
    }
Esempio n. 41
0
    public void RecalculateMesh()
    {
        Material[] mats = null;
        meshFilters = this.gameObject.FindInChildren<MeshFilter>();
        renderers = this.gameObject.FindInChildren<MeshRenderer>();

        if ( renderers.Count > 0 )
        {
            var myRender = this.GetComponent<MeshRenderer>();
            mats = myRender.materials = renderers[renderers.Count-1].materials;
        }

        CombineInstance[] combine = null;

        for ( int i = 0; i < dirtyIndices.Count; i++ )
        {
            if ( batches.ContainsKey(dirtyIndices[i]) ) {
                batches[dirtyIndices[i]].MeshFilters.Clear();
            }
        }

        for (var i = 0; i < meshFilters.Count; i++){
            if ( meshFilters[i] == this.GetComponent<MeshFilter>() )
            {
                continue;
            }

            var pos = meshFilters[i].transform.position;
            BlockIndex index = new BlockIndex( (int)(pos.x / ChunkSize), (int)(pos.y / ChunkSize), (int)(pos.z / ChunkSize));

            if ( dirtyIndices.Count > 0 && dirtyIndices.Contains(index) == false )
            {
                continue;
            }

            ChunkContext context = null;

            if ( batches.ContainsKey( index ) == false )
            {
                context = new ChunkContext();
                context.Chunk = new GameObject();
                context.Chunk.AddComponent<MeshFilter>();
                context.Chunk.AddComponent<MeshRenderer>().materials = mats;
                context.Chunk.transform.parent = OptimizedChunk.transform;
                context.Chunk.name = this.name + "_CHUNK_" + (index.x + "_" +index.y + "_"  +index.z );
                batches[index] = context;
                indices.Add(index);

            } else {
                context = batches[index];
            }

            context.MeshFilters.Add(meshFilters[i]);
        }

        var indexList = (dirtyIndices.Count == 0) ? indices : dirtyIndices;

        for ( int i = 0; i < indexList.Count; i++ )
        {
            BlockIndex index = indexList[i];

            if ( batches.ContainsKey(index) == false )
            {
                //Might have been a diff kinda block.
                continue;
            }

            ChunkContext context = batches[index];

            combine = new CombineInstance[ context.MeshFilters.Count ];
            for ( int j = 0; j < context.MeshFilters.Count; j++)
            {
                combine[j].mesh = context.MeshFilters[j].sharedMesh;
                combine[j].transform = context.MeshFilters[j].transform.localToWorldMatrix;
                context.MeshFilters[j].gameObject.active = false;
            }

            if ( combine.Length > 0 )
            {
                context.Chunk.transform.GetComponent<MeshFilter>().mesh = new Mesh();
                context.Chunk.transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine);
                context.Chunk.transform.gameObject.active = true;
            }
        }

        dirtyIndices.Clear();
        meshFilters.Clear();
        renderers.Clear();
        dirty = false;
    }
Esempio n. 42
0
        /// <summary>
        /// This implements the <c>in</c> command.
        /// </summary>
        /// <param name="table"></param>
        /// <param name="other"></param>
        /// <param name="column1"></param>
        /// <param name="column2"></param>
        /// <returns>
        /// Returns the rows selected from <paramref name="table1"/>.
        /// </returns>
        public static IEnumerable<int> SelectRowsIn(this ITable table, ITable other, int column1, int column2)
        {
            // First pick the the smallest and largest table.  We only want to iterate
            // through the smallest table.
            // NOTE: This optimisation can't be performed for the 'not_in' command.

            ITable smallTable;
            ITable largeTable;
            int smallColumn;
            int largeColumn;

            if (table.RowCount < other.RowCount) {
                smallTable = table;
                largeTable = other;

                smallColumn = column1;
                largeColumn = column2;

            } else {
                smallTable = other;
                largeTable = table;

                smallColumn = column2;
                largeColumn = column1;
            }

            // Iterate through the small table's column.  If we can find identical
            // cells in the large table's column, then we should include the row in our
            // final result.

            var resultRows = new BlockIndex<int>();
            var op = SqlExpressionType.Equal;

            foreach (var row in smallTable) {
                var cell = row.GetValue(smallColumn);

                var selectedSet = largeTable.SelectRows(largeColumn, op, cell).ToList();

                // We've found cells that are IN both columns,

                if (selectedSet.Count > 0) {
                    // If the large table is what our result table will be based on, append
                    // the rows selected to our result set.  Otherwise add the index of
                    // our small table.  This only works because we are performing an
                    // EQUALS operation.

                    if (largeTable == table) {
                        // Only allow unique rows into the table set.
                        int sz = selectedSet.Count;
                        bool rs = true;
                        for (int i = 0; rs && i < sz; ++i) {
                            rs = resultRows.UniqueInsertSort(selectedSet[i]);
                        }
                    } else {
                        // Don't bother adding in sorted order because it's not important.
                        resultRows.Add(row.RowId.RowNumber);
                    }
                }
            }

            return resultRows.ToList();
        }
Esempio n. 43
0
        public static IEnumerable<int> Search(this ITable table, int column, string pattern, char escapeChar)
        {
            var colType = table.TableInfo[column].ColumnType;

            // If the column type is not a string type then report an error.
            if (!(colType is StringType))
                throw new InvalidOperationException("Unable to perform a pattern search on a non-String type column.");

            // First handle the case that the column has an index that supports text search
            var index = table.GetIndex(column);
            if (index != null && index.HandlesTextSearch)
                return index.SelectLike(DataObject.String(pattern));

            var colStringType = (StringType)colType;

            // ---------- Pre Search ----------

            // First perform a 'pre-search' on the head of the pattern.  Note that
            // there may be no head in which case the entire column is searched which
            // has more potential to be expensive than if there is a head.

            StringBuilder prePattern = new StringBuilder();
            int i = 0;
            bool finished = i >= pattern.Length;
            bool lastIsEscape = false;

            while (!finished) {
                char c = pattern[i];
                if (lastIsEscape) {
                    lastIsEscape = true;
                    prePattern.Append(c);
                } else if (c == escapeChar) {
                    lastIsEscape = true;
                } else if (!PatternSearch.IsWildCard(c)) {
                    prePattern.Append(c);

                    ++i;
                    if (i >= pattern.Length) {
                        finished = true;
                    }

                } else {
                    finished = true;
                }
            }

            // This is set with the remaining search.
            string postPattern;

            // This is our initial search row set.  In the second stage, rows are
            // eliminated from this vector.
            IEnumerable<int> searchCase;

            if (i >= pattern.Length) {
                // If the pattern has no 'wildcards' then just perform an EQUALS
                // operation on the column and return the results.

                var cell = new DataObject(colType, new SqlString(pattern));
                return SelectRows(table, column, SqlExpressionType.Equal, cell);
            }

            if (prePattern.Length == 0 ||
                colStringType.Locale != null) {

                // No pre-pattern easy search :-(.  This is either because there is no
                // pre pattern (it starts with a wild-card) or the locale of the string
                // is non-lexicographical.  In either case, we need to select all from
                // the column and brute force the search space.

                searchCase = table.SelectAllRows(column);
                postPattern = pattern;
            } else {

                // Criteria met: There is a pre_pattern, and the column locale is
                // lexicographical.

                // Great, we can do an upper and lower bound search on our pre-search
                // set.  eg. search between 'Geoff' and 'Geofg' or 'Geoff ' and
                // 'Geoff\33'

                var lowerBounds = prePattern.ToString();
                int nextChar = prePattern[i - 1] + 1;
                prePattern[i - 1] = (char)nextChar;
                var upperBounds = prePattern.ToString();

                postPattern = pattern.Substring(i);

                var cellLower = new DataObject(colType, new SqlString(lowerBounds));
                var cellUpper = new DataObject(colType, new SqlString(upperBounds));

                // Select rows between these two points.

                searchCase = table.SelectRowsBetween(column, cellLower, cellUpper);
            }

            // ---------- Post search ----------

            int preIndex = i;

            // Now eliminate from our 'search_case' any cells that don't match our
            // search pattern.
            // Note that by this point 'post_pattern' will start with a wild card.
            // This follows the specification for the 'PatternMatch' method.
            // EFFICIENCY: This is a brute force iterative search.  Perhaps there is
            //   a faster way of handling this?

            var iList = new BlockIndex<int>(searchCase);
            var enumerator = iList.GetEnumerator(0, iList.Count - 1);

            while (enumerator.MoveNext()) {
                // Get the expression (the contents of the cell at the given column, row)

                bool patternMatches = false;
                var cell = table.GetValue(enumerator.Current, column);
                // Null values doesn't match with anything
                if (!cell.IsNull) {
                    string expression = cell.AsVarChar().Value.ToString();
                    // We must remove the head of the string, which has already been
                    // found from the pre-search section.
                    expression = expression.Substring(preIndex);
                    patternMatches = PatternSearch.PatternMatch(postPattern, expression, escapeChar);
                }
                if (!patternMatches) {
                    // If pattern does not match then remove this row from the search.
                    enumerator.Remove();
                }
            }

            return iList.ToList();
        }
Esempio n. 44
0
        public void Collect(bool force)
        {
            try {
                int checkCount = 0;
                int deleteCount = 0;

                // Synchronize over the master data table source so no other threads
                // can interfere when we collect this information.
                lock (tableSource) {
                    if (tableSource.IsClosed)
                        return;

                    // If root is locked, or has transaction changes pending, then we
                    // can't delete any rows marked as deleted because they could be
                    // referenced by transactions or result sets.
                    if (force ||
                        (!tableSource.IsRootLocked &&
                         !tableSource.HasChangesPending)) {

                        // lastSuccess = DateTime.Now;
                        // lastTry = null;

                        // Are we due a full sweep?
                        if (fullSweep) {
                            int rawRowCount = tableSource.RawRowCount;
                            for (int i = 0; i < rawRowCount; ++i) {
                                // Synchronized in dataSource.
                                if (tableSource.HardCheckAndReclaimRow(i))
                                    ++deleteCount;

                                ++checkCount;
                            }

                            fullSweep = false;
                        } else {
                            // Are there any rows marked as deleted?
                            int size = deletedRows.Count;
                            if (size > 0) {
                                // Go remove all rows marked as deleted.
                                foreach (int rowIndex in deletedRows) {
                                    // Synchronized in dataSource.
                                    tableSource.HardRemoveRow(rowIndex);
                                    ++deleteCount;
                                    ++checkCount;
                                }
                            }

                            deletedRows = new BlockIndex<int>();
                        }

                        if (checkCount > 0) {
                            // TODO: Emit the information to the system
                        }

                    } // if not roots locked and not transactions pending

                } // lock
            } catch (IOException) {
                // TODO: Log the error to the system
            }
        }
Esempio n. 45
0
 /// <summary>
 /// Gets the world position of the index, rounded properly to the grid unit.
 /// </summary>
 /// <returns>The position of point.</returns>
 /// <param name="index">Index.</param>
 public Vector3 getPositionOfPoint( ref BlockIndex index )
 {
     return new Vector3(index.x * 2, index.y * 2, index.z * 2);
 }
Esempio n. 46
0
    public void LoadLevel()
    {
        var levelName = LevelToLoad;

        #if UNITY_WEBPLAYER
        bool levelOkay = PlayerPrefs.HasKey("LevelData");
        #else
        bool levelOkay = File.Exists(levelName);
        #endif

        if ( EditorMode)
        {
            Stack<GameObject> stack = new Stack<GameObject>();
            stack.Push(this.gameObject);

            while (stack.Count > 0 )
            {
                var top = stack.Pop();
                var block = top.GetComponent<BlockObject>();
                if ( block != null )
                {
                    var blockPos = top.transform.position;
                    BlockIndex index = getIndexOfPoint(ref blockPos);
                    WorldCubeData[index] = block.gameObject;
                }

                for ( int i = 0; i < top.transform.childCount; i++ )
                {
                    stack.Push(top.transform.GetChild(i).gameObject);
                }
            }

            var assetPath = Application.dataPath;
            var fileName = assetPath + System.IO.Path.DirectorySeparatorChar + "DefaultLevel.txt";
            #if UNITY_EDITOR
            fileName = null;
            #endif

            SaveLevel(fileName);
            Application.LoadLevel("MainMenu");

        }
        else if ( levelOkay )
        {
            #if UNITY_WEBPLAYER
                string[] data = PlayerPrefs.GetString("LevelData").Split('\n');
            #else
                string[] data = File.ReadAllLines(levelName);
            #endif

            foreach( string line in data)
            {
                string[] parts = line.Split(' ');
                if ( parts.Length > 6)
                {
                    int x = int.Parse(parts[0]);
                    int y = int.Parse(parts[1]);
                    int z = int.Parse(parts[2]);
                    string type = parts[3];
                    int rX = int.Parse(parts[4]);
                    int rY = int.Parse(parts[5]);
                    int rZ = int.Parse(parts[6]);
                    int subType = 0;

                    if ( parts.Length > 7 )
                    {
                        subType = int.Parse(parts[7]);
                    }

                    var index = new BlockIndex( x,y,z);
                    GameObject obj = null;
                    if ( BlockTypes.ContainsKey(type) )
                    {
                        obj = BlockTypes[type];
                    }

                    if ( obj != null )
                    {
                        GameObject clone = Instantiate(obj, new Vector3(x*2,y*2,z*2), Quaternion.Euler(rX, rY, rZ)) as GameObject;
                        clone.name = type + " " + x + ", " + y + "," + z;

                        var parent = findBestParent(type);
                        clone.transform.parent = parent;

                        WorldCubeData[index] = clone;
                        clone.GetBlock().SubType = subType;
                    }
                    else
                    {
                        Debug.LogError("Missing: " + type);
                    }
                }
            }
        }
    }