Ejemplo n.º 1
0
		} // DiffText

		public static ProcessedResult DiffTextProcessed(string[] listA, string[] listB)
		{
			var result = new ProcessedResult();

			var diff = new Diff();

			int lastpos = 0;
			foreach (var v in diff.DiffText(listA, listB))
			{
				for (int i = lastpos; i < v.StartA; i++)
				{
					//writefln(" %s", listA[i]);
					result.Items.Add(new ProcessedItem()
					{
						LineNumber = i,
						Line = listA[i],
						Action = ProcessedItem.ActionEnum.Keep,
					});
				}

				//writefln("lastpos(%d) : %s", lastpos, v);

				for (int i = 0; i < v.deletedA; i++)
				{
					result.Items.Add(new ProcessedItem()
					{
						LineNumber = v.StartA + i,
						Line = listA[v.StartA + i],
						Action = ProcessedItem.ActionEnum.Delete,
					});
				}

				for (int i = 0; i < v.insertedB; i++)
				{
					result.Items.Add(new ProcessedItem()
					{
						LineNumber = v.StartB + i,
						Line = listB[v.StartB + i],
						Action = ProcessedItem.ActionEnum.Insert,
					});
				}

				lastpos = v.StartA;
				lastpos += v.deletedA;
			}

			for (int i = lastpos; i < listA.Length; i++)
			{
				result.Items.Add(new ProcessedItem()
				{
					LineNumber = i,
					Line = listA[i],
					Action = ProcessedItem.ActionEnum.Keep,
				});
			}

			return result;
		}
Ejemplo n.º 2
0
        /// <summary>
        /// Generates the compiled type.
        /// </summary>
        private static IGenerator GenerateType(ProcessedResult result)
        {
            // Create the code using the template file.
            string template = null;

            using (var reader = new StreamReader("Compiler/CompiledLayerTemplate.cs"))
                template = reader.ReadToEnd();
            var final = template
                        .Replace("/****** %CODE% ******/", result.ProcessedCode)
                        .Replace("/****** %RETURN% ******/", "return " + result.OutputVariableName + ";")
                        .Replace("/****** %DECLS% ******/", result.Declarations)
                        .Replace("/****** %USING% ******/",
                                 result.UsingStatements
                                 .Where(v => v != "System" && v != "Tychaia.ProceduralGeneration")
                                 .Select(v => "using " + v + ";")
                                 .DefaultIfEmpty("")
                                 .Aggregate((a, b) => a + "\n" + b));

            // Create the type.
            var parameters = new CompilerParameters(new string[]
            {
                "Tychaia.ProceduralGeneration.dll",
                "System.Core.dll"
            });

            parameters.GenerateExecutable      = false;
            parameters.GenerateInMemory        = true;
            parameters.IncludeDebugInformation = false;
            parameters.CompilerOptions         = "/optimize";
            var compiler = CSharpCodeProvider.CreateProvider("CSharp");
            var results  = compiler.CompileAssemblyFromSource(parameters, final);

            using (var writer = new StreamWriter("code.tmp.cs"))
            {
                //int i = 1;
                foreach (var line in final.Split('\n'))
                {
                    //i++.ToString().PadLeft(4) + ":  " +
                    writer.WriteLine(line);
                }
            }
            if (results.Errors.HasErrors)
            {
                foreach (var error in results.Errors)
                {
                    Console.WriteLine(error);
                }
                Console.WriteLine();
                throw new InvalidOperationException("Unable to compile code for layer generation.  Compiled code contained errors.");
            }
            var assembly = results.CompiledAssembly;
            var newType  = assembly.GetType("CompiledLayer");

            return(newType.GetConstructor(Type.EmptyTypes).Invoke(null) as IGenerator);
        }
Ejemplo n.º 3
0
        private static ProcessedResult ProcessRuntimeLayer(RuntimeLayer layer)
        {
            // Create our own processed result; a copy of our own state plus
            // somewhere to accumulate code.
            var result = new ProcessedResult();

            result.ProcessedCode = "";

            // Get a reference to the algorithm that the runtime layer is using.
            var algorithm = layer.Algorithm;

            if (algorithm == null)
            {
                throw new InvalidOperationException("Attempted to compile null runtime layer!");
            }

            // Use RangedLayer to work out the metrics.
            var        ranged = new RangedLayer(layer);
            Expression ix, iy, iz, iwidth, iheight, idepth, iouterx, ioutery, iouterz;

            RangedLayer.FindMaximumBounds(ranged, out ix, out iy, out iz, out iwidth, out iheight, out idepth, out iouterx, out ioutery, out iouterz);

            // Add __cwidth, __cheight and __cdepth declarations.
            result.Declarations += "int __cx = (int)((x - (" + ix.GetText(null) + ")));\n";
            result.Declarations += "int __cy = (int)((y - (" + iy.GetText(null) + ")));\n";
            result.Declarations += "int __cz = (int)((z - (" + iz.GetText(null) + ")));\n";
            result.Declarations += "int __cwidth = " + iwidth.GetText(null) + ";\n";
            result.Declarations += "int __cheight = " + iheight.GetText(null) + ";\n";
            result.Declarations += "int __cdepth = " + idepth.GetText(null) + ";\n";

            // Create the for loop that our calculations are done within.
            result.ProcessedCode += @"for (var k = (int)((" + iz.GetText(null) + ") - z); k < " + iouterz.GetText(null) + @"; k++)
for (var i = (int)((" + ix.GetText(null) + ") - x); i < " + iouterx.GetText(null) + @"; i++)
for (var j = (int)((" + iy.GetText(null) + ") - y); j < " + ioutery.GetText(null) + @"; j++)
{
";

            // Now add the code for the layer.
            var inputResult = CompileRuntimeLayer(layer, ranged, null);

            result.ProcessedCode     += inputResult.ProcessedCode;
            result.OutputVariableName = inputResult.OutputVariableName;
            result.OutputVariableType = inputResult.OutputVariableType;
            result.Declarations      += inputResult.Declarations;

            // Terminate the for loop and return the result.
            result.ProcessedCode += "}";
            return(result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Runs the sequence coverage calculation.
        /// </summary>
        private async Task RunImpl()
        {
            var processor = new ResultProcessor(this.IonTypeFactoryViewModel.IonTypeFactory);

            try
            {
                var results = await processor.ProcessAsync(
                    this.RawFileSelector.FilePath,
                    this.MzIdFileSelector.FilePath,
                    this.cancellationToken.Token,
                    this.progressReporter);

                if (results.Count > 0)
                {
                    await ProcessedResult.WriteToFile(results, this.OutputFileSelector.FilePath);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            this.progressReporter.Report(new ProgressData());
        }
Ejemplo n.º 5
0
    private static bool TryGetNotificationInputs(ProcessedResult result, [NotNullWhen(true)] out string?message)
    {
        message = null;

        try
        {
            bool  isSpent            = result.NewlySpentCoins.Any();
            bool  isReceived         = result.NewlyReceivedCoins.Any();
            bool  isConfirmedReceive = result.NewlyConfirmedReceivedCoins.Any();
            bool  isConfirmedSpent   = result.NewlyConfirmedReceivedCoins.Any();
            Money miningFee          = result.Transaction.Transaction.GetFee(result.SpentCoins.Select(x => x.Coin).ToArray());

            if (isReceived || isSpent)
            {
                Money  receivedSum      = result.NewlyReceivedCoins.Sum(x => x.Amount);
                Money  spentSum         = result.NewlySpentCoins.Sum(x => x.Amount);
                Money  incoming         = receivedSum - spentSum;
                Money  receiveSpentDiff = incoming.Abs();
                string amountString     = receiveSpentDiff.ToFormattedString();

                if (result.Transaction.Transaction.IsCoinBase)
                {
                    message = $"{amountString} BTC received as Coinbase reward";
                }
                else if (isSpent && receiveSpentDiff == miningFee)
                {
                    message = $"Self transfer. Fee: {amountString} BTC";
                }
                else if (incoming > Money.Zero)
                {
                    message = $"{amountString} BTC received";
                }
                else if (incoming < Money.Zero)
                {
                    var sentAmount = receiveSpentDiff - miningFee;
                    message = $"{sentAmount.ToFormattedString()} BTC sent";
                }
            }
            else if (isConfirmedReceive || isConfirmedSpent)
            {
                Money  receivedSum      = result.ReceivedCoins.Sum(x => x.Amount);
                Money  spentSum         = result.SpentCoins.Sum(x => x.Amount);
                Money  incoming         = receivedSum - spentSum;
                Money  receiveSpentDiff = incoming.Abs();
                string amountString     = receiveSpentDiff.ToFormattedString();

                if (isConfirmedSpent && receiveSpentDiff == miningFee)
                {
                    message = $"Self transfer confirmed. Fee: {amountString} BTC";
                }
                else if (incoming > Money.Zero)
                {
                    message = $"Receiving {amountString} BTC has been confirmed";
                }
                else if (incoming < Money.Zero)
                {
                    var sentAmount = receiveSpentDiff - miningFee;
                    message = $"{sentAmount.ToFormattedString()} BTC sent got confirmed";
                }
            }
        }
        catch (Exception ex)
        {
            Logger.LogWarning(ex);
        }

        return(message is { });
Ejemplo n.º 6
0
        private static ProcessedResult CompileRuntimeLayer(RuntimeLayer layer, RangedLayer ranged, IAlgorithm parent)
        {
            // Create our own processed result; a copy of our own state plus
            // somewhere to accumulate code.
            var result = new ProcessedResult();

            result.ProcessedCode = "";

            // Get a reference to the algorithm that the runtime layer is using.
            var algorithm = layer.Algorithm;

            if (algorithm == null)
            {
                throw new InvalidOperationException("Attempted to compile null runtime layer!");
            }
            var algorithmType = algorithm.GetType();

            // If the runtime layer has inputs, we need to process them first.
            if (layer.Algorithm.InputTypes.Length > 0)
            {
                var inputs = layer.GetInputs();
                result.InputVariableNames = new string[inputs.Length];
                for (var i = 0; i < inputs.Length; i++)
                {
                    var inputResult = CompileRuntimeLayer(inputs[i], ranged.Inputs[i], layer.Algorithm);
                    result.ProcessedCode        += inputResult.ProcessedCode;
                    result.InputVariableNames[i] = inputResult.OutputVariableName;
                    result.Declarations         += inputResult.Declarations;
                }
            }

            // Create the storage array.
            result.OutputVariableName = GenerateRandomIdentifier();
            result.OutputVariableType = algorithm.OutputType.FullName;
            result.Declarations      += result.OutputVariableType + "[] " + result.OutputVariableName +
                                        " = new " + result.OutputVariableType + "[__cwidth * __cheight * __cdepth];\n";

            Console.WriteLine(ranged.ToString());

            // Add the conditional container.
            string code = "if (k >= (int)((" + ranged.Z.GetText(null) + ") - z) && i >= (int)((" + ranged.X.GetText(null) + ") - x) && j >= (int)((" + ranged.Y.GetText(null) + ") - y)" +
                          " && k < " + ranged.OuterZ.GetText(null) + " && i < " + ranged.OuterX.GetText(null) + " && j < " + ranged.OuterY.GetText(null) + @")
{
";

            /*result.Declarations += "Console.WriteLine(\"COMPILED: \" + " +
             *  "" + ranged.X + " + \" \" + " +
             *  "" + ranged.Y + " + \" \" + " +
             *  "" + ranged.Z + " + \" \" + " +
             *  "" + ranged.Width + " + \" \" + " +
             *  "" + ranged.Height + " + \" \" + " +
             *  "" + ranged.Depth + ");";*/

            // Refactor the method.
            AstBuilder astBuilder;
            var        method = DecompileUtil.GetAlgorithmCode(algorithmType, out astBuilder);

            AlgorithmRefactorer.InlineMethod(algorithm, method, result.OutputVariableName, result.InputVariableNames,
                                             "__cx", "__cy", "__cz",
                                             "__cwidth", "__cheight", "__cdepth");
            AlgorithmRefactorer.RemoveUsingStatements(astBuilder.CompilationUnit, result.UsingStatements);
            code += method.Body.GetText();

            // Terminate the conditional container and return.
            code += "computations += 1;";
            code += "}\n";
            result.ProcessedCode += code;
            return(result);
        }
Ejemplo n.º 7
0
        private async void TransactionProcessor_WalletRelevantTransactionProcessedAsync(object sender, ProcessedResult e)
        {
            try
            {
                foreach (var coin in e.NewlySpentCoins.Concat(e.ReplacedCoins).Concat(e.SuccessfullyDoubleSpentCoins).Distinct())
                {
                    ChaumianClient.ExposedLinks.TryRemove(coin.GetTxoRef(), out _);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            try
            {
                IEnumerable <SmartCoin> newCoins = e.NewlyReceivedCoins.Concat(e.RestoredCoins).Distinct();
                if (newCoins.Any())
                {
                    if (ChaumianClient.State.Contains(e.Transaction.Transaction.Inputs.Select(x => x.PrevOut.ToTxoRef())))
                    {
                        var coinsToQueue = new HashSet <SmartCoin>();
                        foreach (var newCoin in newCoins)
                        {
                            // If it's being mixed and anonset is not sufficient, then queue it.
                            if (newCoin.Unspent && ChaumianClient.HasIngredients &&
                                newCoin.AnonymitySet < ServiceConfiguration.MixUntilAnonymitySet)
                            {
                                coinsToQueue.Add(newCoin);
                            }
                        }

                        await ChaumianClient.QueueCoinsToMixAsync(coinsToQueue).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }
        private void WalletManager_WalletRelevantTransactionProcessed(object sender, ProcessedResult e)
        {
            try
            {
                // If there are no news, then don't bother.
                if (!e.IsNews || (sender as Wallet).State != WalletState.Started)
                {
                    return;
                }

                // ToDo
                // Double spent.
                // Anonymity set gained?
                // Received dust

                bool  isSpent            = e.NewlySpentCoins.Any();
                bool  isReceived         = e.NewlyReceivedCoins.Any();
                bool  isConfirmedReceive = e.NewlyConfirmedReceivedCoins.Any();
                bool  isConfirmedSpent   = e.NewlyConfirmedReceivedCoins.Any();
                Money miningFee          = e.Transaction.Transaction.GetFee(e.SpentCoins.Select(x => x.GetCoin()).ToArray());
                if (isReceived || isSpent)
                {
                    Money  receivedSum      = e.NewlyReceivedCoins.Sum(x => x.Amount);
                    Money  spentSum         = e.NewlySpentCoins.Sum(x => x.Amount);
                    Money  incoming         = receivedSum - spentSum;
                    Money  receiveSpentDiff = incoming.Abs();
                    string amountString     = receiveSpentDiff.ToString(false, true);

                    if (e.Transaction.Transaction.IsCoinBase)
                    {
                        _notificationManager.NotifyAndLog($"{amountString} BTC", "Mined", NotificationType.Success, e);
                    }
                    else if (isSpent && receiveSpentDiff == miningFee)
                    {
                        _notificationManager.NotifyAndLog($"Mining Fee: {amountString} BTC", "Self Spend", NotificationType.Information, e);
                    }
                    else if (isSpent && receiveSpentDiff.Almost(Money.Zero, Money.Coins(0.01m)) && e.IsLikelyOwnCoinJoin)
                    {
                        _notificationManager.NotifyAndLog($"CoinJoin Completed!", "", NotificationType.Success, e);
                    }
                    else if (incoming > Money.Zero)
                    {
                        if (e.Transaction.IsRBF && e.Transaction.IsReplacement)
                        {
                            _notificationManager.NotifyAndLog($"{amountString} BTC", "Received Replaceable Replacement Transaction", NotificationType.Information, e);
                        }
                        else if (e.Transaction.IsRBF)
                        {
                            _notificationManager.NotifyAndLog($"{amountString} BTC", "Received Replaceable Transaction", NotificationType.Success, e);
                        }
                        else if (e.Transaction.IsReplacement)
                        {
                            _notificationManager.NotifyAndLog($"{amountString} BTC", "Received Replacement Transaction", NotificationType.Information, e);
                        }
                        else
                        {
                            _notificationManager.NotifyAndLog($"{amountString} BTC", "Received", NotificationType.Success, e);
                        }
                    }
                    else if (incoming < Money.Zero)
                    {
                        _notificationManager.NotifyAndLog($"{amountString} BTC", "Sent", NotificationType.Information, e);
                    }
                }
                else if (isConfirmedReceive || isConfirmedSpent)
                {
                    Money  receivedSum      = e.ReceivedCoins.Sum(x => x.Amount);
                    Money  spentSum         = e.SpentCoins.Sum(x => x.Amount);
                    Money  incoming         = receivedSum - spentSum;
                    Money  receiveSpentDiff = incoming.Abs();
                    string amountString     = receiveSpentDiff.ToString(false, true);

                    if (isConfirmedSpent && receiveSpentDiff == miningFee)
                    {
                        _notificationManager.NotifyAndLog($"Mining Fee: {amountString} BTC", "Self Spend Confirmed", NotificationType.Information, e);
                    }
                    else if (isConfirmedSpent && e.IsLikelyOwnCoinJoin)
                    {
                        _notificationManager.NotifyAndLog($"CoinJoin Confirmed!", "", NotificationType.Information, e);
                    }
                    else if (incoming > Money.Zero)
                    {
                        _notificationManager.NotifyAndLog($"{amountString} BTC", "Receive Confirmed", NotificationType.Information, e);
                    }
                    else if (incoming < Money.Zero)
                    {
                        _notificationManager.NotifyAndLog($"{amountString} BTC", "Send Confirmed", NotificationType.Information, e);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex);
            }
        }
Ejemplo n.º 9
0
        public IActionResult Index()

        {
            string reqUrl           = "http://ivivaanywhere.ivivacloud.com/api/Asset/Asset/All?apikey=SC:ivivademo:8d756202d6159375&max=100&last=0";
            var    httpWebRequestQR = (HttpWebRequest)WebRequest.Create(reqUrl);

            httpWebRequestQR.ContentType = "application/json";
            httpWebRequestQR.Method      = "GET";


            var httpResponseQR = (HttpWebResponse)httpWebRequestQR.GetResponse();

            using (var streamReader = new StreamReader(httpResponseQR.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                //string jsonStringsign = resultQR;
                //var json = new JavaScriptSerializer().Serialize(jsonStringsign);
                //JsonData json = JsonMapper.ToObject(jsonStringsign);
                //Console.WriteLine(json);
                Console.WriteLine(result);
                var jsonResult = JsonConvert.DeserializeObject <Result[]>(result);

                int operationalCount   = 0;
                int nonOperatinalCount = 0;

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

                foreach (Result x in jsonResult)
                {
                    if (x.OperationalStatus.Equals("Operational"))
                    {
                        operationalCount++;
                    }
                    else
                    {
                        nonOperatinalCount++;
                    }
                    asset.Add(x.AssetCategoryID);
                }

                var           g       = asset.GroupBy(i => i);
                List <string> keyList = new List <string>();

                Dictionary <string, int> hash = new Dictionary <string, int>();
                foreach (var grp in g)
                {
                    hash.Add(grp.Key, grp.Count());
                    keyList.Add(grp.Key);
                }

                Console.WriteLine("===========================================");

                Console.WriteLine(hash[keyList[0]]);

                var processedResult = new ProcessedResult();
                processedResult.operatinalCount    = operationalCount;
                processedResult.nonOperatinalCount = nonOperatinalCount;
                processedResult.keyValues          = hash;
                processedResult.keys = keyList;

                return(View(processedResult));
            }
        }
        public async Task <IActionResult> Create([Bind("Id,RegNo,Semester,Session,Level,GPA,CGPA,ProcessedBy,DateProcessed")] ProcessedResult processedResult)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    double gradePointAverage            = 0.0F;
                    double cummulativeGradePointAverage = 0.0F;
                    var    regNo           = string.Empty;
                    var    sem             = processedResult.Semester;
                    var    sess            = processedResult.Session;
                    var    level           = processedResult.Level;
                    var    totalCreditUnit = 0;
                    var    totalGradePoint = 0.0;
                    var    enteredRegNo    = "";

                    List <string> getReNos = await GetRegNos(sem, sess, level);

                    for (var index = 0; index <= getReNos.Count - 1; index++)
                    {
                        regNo = getReNos[index];

                        if (regNo == enteredRegNo)
                        {
                            return(RedirectToAction(nameof(Index)));
                        }


                        int id = index + 1;

                        List <ScoreViewModel> scoreViews = await ScoresAndUnit(regNo, sem, sess, level);

                        foreach (var s in scoreViews)
                        {
                            var unit = s.Unit;
                            //var score = s.Score;
                            var grade = s.Grade;

                            totalCreditUnit += unit;
                            var gradePoint = Utility.GradePoint(grade, unit);

                            totalGradePoint += gradePoint;
                        }
                        //Retrieve the previous GPA from database by RegNo
                        double previousGPA = GetPreviousCGPA(regNo);

                        gradePointAverage = totalGradePoint / totalCreditUnit;
                        gradePointAverage = Math.Round(gradePointAverage, 2);

                        // Determine new Semester
                        if (previousGPA == 0.0)
                        {
                            cummulativeGradePointAverage = gradePointAverage;
                        }
                        else
                        {
                            // Compute the Cummulative Grade Point Average by adding the previous GPA to current GPA and divide by 2
                            cummulativeGradePointAverage = (gradePointAverage + previousGPA) / 2;
                        }

                        //cummulativeGradePointAverage = gpa;

                        var processedBy   = User.Identity.Name;
                        var processedDate = DateTime.Now;

                        processedResult.GPA  = gradePointAverage;
                        processedResult.CGPA = cummulativeGradePointAverage;

                        processedResult.DateProcessed   = processedDate;
                        processedResult.ProcessedBy     = processedBy;
                        processedResult.TotalCreditUnit = totalCreditUnit;
                        processedResult.TotalGradePoint = Math.Round(totalGradePoint);
                        processedResult.RegNo           = regNo;
                        processedResult.Id = id;
                        _context.Add(processedResult);
                        await _context.SaveChangesAsync();

                        enteredRegNo    = regNo;
                        totalCreditUnit = 0;
                        totalGradePoint = 0.0;
                    }


                    return(RedirectToAction(nameof(Index)));
                }
                catch (Exception ex)
                {
                    ViewBag.Error = "Something happened. " + Environment.NewLine + ex.Message;

                    throw ex;
                }
            }
            return(View(processedResult));
        }
Ejemplo n.º 11
0
        private static ProcessedResult CompileRuntimeLayer(RuntimeLayer layer, RangedLayer ranged, IAlgorithm parent)
        {
            // Create our own processed result; a copy of our own state plus
            // somewhere to accumulate code.
            var result = new ProcessedResult();
            result.ProcessedCode = string.Empty;
            result.InitializationCode = string.Empty;

            // Get a reference to the algorithm that the runtime layer is using.
            var algorithm = layer.Algorithm;
            if (algorithm == null)
                throw new InvalidOperationException("Attempted to compile null runtime layer!");
            var algorithmType = algorithm.GetType();

            // If the runtime layer has inputs, we need to process them first.
            var inputs = layer.GetInputs();
            result.InputVariableNames = new string[inputs.Length];
            for (var i = 0; i < inputs.Length; i++)
            {
                var inputResult = CompileRuntimeLayer(inputs[i], ranged.Inputs[i], layer.Algorithm);
                result.ProcessedCode += inputResult.ProcessedCode;
                result.InitializationCode += inputResult.InitializationCode;
                result.InputVariableNames[i] = inputResult.OutputVariableName;
                result.Declarations += inputResult.Declarations;
                result.UsingStatements.AddRange(inputResult.UsingStatements);
            }

            // Create the storage array.
            result.OutputVariableName = GenerateRandomIdentifier();
            result.OutputVariableType = algorithm.OutputType.FullName;
            result.Declarations += result.OutputVariableType + "[] " + result.OutputVariableName +
                                   " = new " + result.OutputVariableType + "[__cwidth * __cheight * __cdepth];\n";

            // Add the conditional container.
            var code = "if (i >= " + ranged.CalculationStartI.GetText(null) + " && " +
                       "    j >= " + ranged.CalculationStartJ.GetText(null) + " && " +
                       "    k >= " + ranged.CalculationStartK.GetText(null) + " && " +
                       "    i <= " + ranged.CalculationEndI.GetText(null) + " && " +
                       "    j <= " + ranged.CalculationEndJ.GetText(null) + " && " +
                       "    k <= " + ranged.CalculationEndK.GetText(null) + ") {";

            // Refactor the method.
            AstBuilder astBuilder;
            var method = DecompileUtil.GetMethodCode(algorithmType, out astBuilder, "ProcessCell");
            MethodDeclaration initialize = null;
            try
            {
                initialize = DecompileUtil.GetMethodCode(algorithmType, out astBuilder, "Initialize");
            }
            catch (MissingMethodException)
            {
            }

            AlgorithmRefactorer.InlineMethod(
                algorithm,
                method,
                result.OutputVariableName,
                result.InputVariableNames,
                new ParenthesizedExpression(
                    new BinaryOperatorExpression(
                        new BinaryOperatorExpression(
                            new IdentifierExpression("x"),
                            BinaryOperatorType.Add,
                            ranged.OffsetX.Clone()),
                        BinaryOperatorType.Add,
                        new BinaryOperatorExpression(
                            new IdentifierExpression("i"),
                            BinaryOperatorType.Add,
                            ranged.OffsetI.Clone()))),
                new ParenthesizedExpression(
                    new BinaryOperatorExpression(
                        new BinaryOperatorExpression(
                            new IdentifierExpression("y"),
                            BinaryOperatorType.Add,
                            ranged.OffsetY.Clone()),
                        BinaryOperatorType.Add,
                        new BinaryOperatorExpression(
                            new IdentifierExpression("j"),
                            BinaryOperatorType.Add,
                            ranged.OffsetJ.Clone()))),
                new ParenthesizedExpression(
                    new BinaryOperatorExpression(
                        new BinaryOperatorExpression(
                            new IdentifierExpression("z"),
                            BinaryOperatorType.Add,
                            ranged.OffsetZ.Clone()),
                        BinaryOperatorType.Add,
                        new BinaryOperatorExpression(
                            new IdentifierExpression("k"),
                            BinaryOperatorType.Add,
                            ranged.OffsetK.Clone()))),
                new ParenthesizedExpression(
                    new BinaryOperatorExpression(
                        new IdentifierExpression("i"),
                        BinaryOperatorType.Add,
                        ranged.OffsetI.Clone())),
                new ParenthesizedExpression(
                    new BinaryOperatorExpression(
                        new IdentifierExpression("j"),
                        BinaryOperatorType.Add,
                        ranged.OffsetJ.Clone())),
                new ParenthesizedExpression(
                    new BinaryOperatorExpression(
                        new IdentifierExpression("k"),
                        BinaryOperatorType.Add,
                        ranged.OffsetK.Clone())),
                new IdentifierExpression("__cwidth"),
                new IdentifierExpression("__cheight"),
                new IdentifierExpression("__cdepth"),
                new PrimitiveExpression(0),
                new PrimitiveExpression(0),
                new PrimitiveExpression(0));
            if (initialize != null)
                AlgorithmRefactorer.InlineInitialize(algorithm, initialize);
            AlgorithmRefactorer.RemoveUsingStatements(astBuilder.CompilationUnit, result.UsingStatements);
            AlgorithmRefactorer.FactorOutAlgorithmFields(algorithmType, method, initialize, ref result.Declarations);
            code += method.Body.GetText();

            // Terminate the conditional container and return.
            code += "computations += 1;";
            code += "}\n";
            result.ProcessedCode += code;
            if (initialize != null)
                result.InitializationCode += initialize.Body.GetText();
            return result;
        }
Ejemplo n.º 12
0
        private static ProcessedResult ProcessRuntimeLayer(RuntimeLayer layer)
        {
            // Create our own processed result; a copy of our own state plus
            // somewhere to accumulate code.
            var result = new ProcessedResult();
            result.ProcessedCode = string.Empty;
            result.InitializationCode = string.Empty;

            // Get a reference to the algorithm that the runtime layer is using.
            var algorithm = layer.Algorithm;
            if (algorithm == null)
                throw new InvalidOperationException("Attempted to compile null runtime layer!");

            // Use RangedLayer to work out the metrics.
            var ranged = new RangedLayer(layer);
            Expression ix, iy, iz, iwidth, iheight, idepth, iouterx, ioutery, iouterz;
            RangedLayer.FindMaximumBounds(
                ranged,
                out ix,
                out iy,
                out iz,
                out iwidth,
                out iheight,
                out idepth,
                out iouterx,
                out ioutery,
                out iouterz);

            // Add __cwidth, __cheight and __cdepth declarations.
            result.Declarations += "int __cx = (int)(" + ix.GetText(null) + ");\n";
            result.Declarations += "int __cy = (int)(" + iy.GetText(null) + ");\n";
            result.Declarations += "int __cz = (int)(" + iz.GetText(null) + ");\n";
            result.Declarations += "int __cwidth = " + iwidth.GetText(null) + ";\n";
            result.Declarations += "int __cheight = " + iheight.GetText(null) + ";\n";
            result.Declarations += "int __cdepth = " + idepth.GetText(null) + ";\n";

            // Create the for loop that our calculations are done within.
            result.ProcessedCode +=
                "for (var k = 0; k < " + idepth.GetText(null) + @"; k++)" +
                "for (var i = 0; i < " + iwidth.GetText(null) + @"; i++)" +
                "for (var j = 0; j < " + iheight.GetText(null) + @"; j++)" +
                "{";

            // Now add the code for the layer.
            var inputResult = CompileRuntimeLayer(layer, ranged, null);
            result.ProcessedCode += inputResult.ProcessedCode;
            result.InitializationCode += inputResult.InitializationCode;
            result.OutputVariableName = inputResult.OutputVariableName;
            result.OutputVariableType = inputResult.OutputVariableType;
            result.Declarations += inputResult.Declarations;
            result.UsingStatements.AddRange(inputResult.UsingStatements);

            // Terminate the for loop and return the result.
            result.ProcessedCode += "}";
            return result;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Generates the compiled type.
        /// </summary>
        private static IGenerator GenerateType(ProcessedResult result, bool optimize = true)
        {
            var final = GenerateCode(result, optimize);

            // Create the type.
            var parameters = new CompilerParameters(new[]
            {
                Assembly.GetExecutingAssembly().Location,
                typeof(PerlinNoise).Assembly.Location,
                typeof(InlineTaskPipeline<>).Assembly.Location,
                "System.Core.dll"
            });
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;
            parameters.IncludeDebugInformation = false;
            parameters.CompilerOptions = "/optimize";
            var compiler = CodeDomProvider.CreateProvider("CSharp");
            var results = compiler.CompileAssemblyFromSource(parameters, final);
            if (results.Errors.HasErrors)
            {
                foreach (var error in results.Errors)
                    Console.WriteLine(error);
                Console.WriteLine();
                throw new InvalidOperationException(
                    "Unable to compile code for layer generation.  Compiled code contained errors.");
            }

            var assembly = results.CompiledAssembly;
            var newType = assembly.GetType("CompiledLayer");
            return newType.GetConstructor(Type.EmptyTypes).Invoke(null) as IGenerator;
        }
Ejemplo n.º 14
0
        private static string GenerateCode(ProcessedResult result, bool optimize)
        {
            // Create the code using the template file.
            var templateName = "Tychaia.ProceduralGeneration.Compiler.CompiledLayerTemplate.cs";
            var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(templateName);
            string template = null;
            using (var reader = new StreamReader(stream))
                template = reader.ReadToEnd();
            var final = template
                .Replace("/****** %CODE% ******/", result.ProcessedCode)
                .Replace("/****** %INIT% ******/", result.InitializationCode)
                .Replace("/****** %OUTPUT_VAR% ******/", result.OutputVariableName)
                .Replace("/****** %OUTPUT_TYPE% ******/", result.OutputVariableType)
                .Replace("/****** %DECLS% ******/", result.Declarations)
                .Replace("/****** %USING% ******/",
                result.UsingStatements
                    .Where(v => v != "System" && v != "Tychaia.ProceduralGeneration")
                    .Select(v => "using " + v + ";")
                    .DefaultIfEmpty(string.Empty)
                    .Aggregate((a, b) => a + "\n" + b));
            var parser = new CSharpParser();
            var tree = parser.Parse(final, "layer.cs");
            if (optimize)
            {
                AstHelpers.OptimizeCompilationUnit(tree);
            }

            var stringWriter = new StringWriter();
            var formatter = FormattingOptionsFactory.CreateMono();
            formatter.SpaceBeforeMethodCallParentheses = false;
            formatter.SpaceBeforeIndexerDeclarationBracket = false;
            tree.AcceptVisitor(new CSharpOutputVisitor(
                new TextWriterOutputFormatter(stringWriter)
            {
                IndentationString = "  "
            },
            formatter));
            final = stringWriter.ToString();
            return final;
        }