Esempio n. 1
0
 public PatchLocation(int x, int y, int index, Patch patch)
 {
     X = x;
     Y = y;
     Index = index;
     Patch = patch;
 }
        protected override int Run(string command) {
            if (String.IsNullOrEmpty(name) && String.IsNullOrEmpty(path)) {
                Out.WriteLine("you must define either the name or the path of the assembly to check");
                return -1;
            }

            Assembly assembly = Tools.LoadAssembly(name, path);
            SnapShot assemblySettings = SnapShot.BuildFrom(assembly);
            SnapShot databaseSettings = SnapShot.GetFor(assembly);
            Patch patch = new Patch(databaseSettings, assemblySettings);

            if (patch.IsEmpty)
                Out.WriteLine("database is already in sync");

            if (!noPrompt) {
                Console.WriteLine(patch.ToString());
                Console.Write("apply the patch? (y)es > ");
                string responce = Console.ReadLine();
                if (!responce.ToLower().StartsWith("y"))
                    return 0;
            }

            patch.Apply(new Patch.ApplyOptions());
            return 0;
        }
Esempio n. 3
0
        public void downloadPatch(Patch patch)
        {
            string downloadURL = URLFormatter.format($"{serverToDownload.website}/{serverToDownload.downloadDirectory}/");
            using (WebClient webClient = new WebClient())
            {
                string patchDownloadURL = downloadURL + "/" + patch.fileName;
                if (!ResourceHelper.resourceExists(patchDownloadURL))
                {
                    form.downloadStatusLabel.Text = $"Status: Could not download {patch.fileName} - It does not exist";
                    return;
                }

                ApplicationStatus.downloading = true;

                string localPatchDirectory = $"{serverToDownload.clientDirectory}/Data/";
                string localPatchPath = localPatchDirectory + patch.fileName;

                if (!Directory.Exists(localPatchDirectory))
                    Directory.CreateDirectory(localPatchDirectory);

                webClient.DownloadProgressChanged += downloadPatchProgressChanged;
                webClient.DownloadFileAsync(new System.Uri(patchDownloadURL), localPatchPath);
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.downloadPatchCompleted);
                stopWatch.Start();

                patchesToDownload.Remove(patch);
            }
        }
 void WritePatch(StreamWriter writer, Patch patch)
 {
     writer.WriteLine("{");
     writer.WriteLine("patchDef2");
     writer.WriteLine("{");
     writer.WriteLine(patch.TextureName);
     writer.WriteLine(String.Format("( {0} {1} 0 0 0 )", patch.Rows, patch.Columns));
     writer.WriteLine("(");
     int patchIndex = 0;
     for (int i = 0; i < patch.Rows; ++i)
     {
         writer.Write("( ");
         for (int j = 0; j < patch.Columns; ++patchIndex)
         {
             writer.Write(String.Format("( {0} {1} {2} {3} {4} ) ",
                 patch.FlatVertices[patchIndex].Position.X,
                 patch.FlatVertices[patchIndex].Position.Y,
                 patch.FlatVertices[patchIndex].Position.Z,
                 patch.FlatVertices[patchIndex].UV.X,
                 patch.FlatVertices[patchIndex].UV.Y));
         }
         writer.Write(")\n");
     }
     writer.WriteLine(")");
     writer.WriteLine("}");
     writer.WriteLine("}");
 }
Esempio n. 5
0
 protected void GrabPatchButtonClicked(object sender, EventArgs e)
 {
     var usbTool = new UsbTool();
     var patch = new Patch(usbTool.GrabPatch().ToArray());
     Console.WriteLine(String.Format("Got Patch: {0}", patch));
     usbTool.Dispose();
 }
        protected override int Run(string command) {
            if (String.IsNullOrEmpty(assemblyName) && String.IsNullOrEmpty(assemblyPath) && String.IsNullOrEmpty(sectionName)) {
                Out.WriteLine("you must define either the assembly name, the path of the assembly, xor the section name to pull form the database");
                return -1;
            }

            Patch patch = null;

            if (!String.IsNullOrEmpty(sectionName)) {
                SnapShot current = SnapShot.GetFor(sectionName);
                patch = new Patch(current, Patch.Action.ActionType.Update);
            } else {

                Assembly assembly = Tools.LoadAssembly(assemblyName, assemblyPath);

                if (assembly == null) {
                    Out.WriteLine("could not load {0}{1}", assemblyName, assemblyPath);
                    return -1;
                }

                if (!assembly.HasSettings()) {
                    Out.WriteLine("{0} has not settings no patch to generate", assembly.FullName);
                    return 0;
                }

                SnapShot assemblySettings = SnapShot.BuildFrom(assembly);
                SnapShot databaseSettings = SnapShot.GetFor(assembly);
                patch = new Patch(databaseSettings, assemblySettings);
            }
            patch.ToXml().Save(output, SaveOptions.None);

            return 0;
        }
Esempio n. 7
0
 public void WriteMUOPatch(Patch patch)
 {
     Write((int)patch.FileId);
     Write((int)patch.BlockID);
     Write((int)patch.Extra);
     Write((int)patch.Length);
     Write(patch.Data);
 }
Esempio n. 8
0
 public PatchEntry(int offset, int length, Patch patch, PatchEntryChanges changes, IReadOnlyList<PatchHunk> hunks)
 {
     Offset = offset;
     Length = length;
     Patch = patch;
     Changes = changes;
     Hunks = hunks;
 }
Esempio n. 9
0
 public Animation(PictureBox image, Patch patch)
 {
     _image = image;
     _patch = patch;
     _frames = GetAnimation();
     _timer = new System.Timers.Timer(100);
     _timer.Elapsed += new ElapsedEventHandler(OnTick);
     _timer.Start();
 }
Esempio n. 10
0
 /// <summary>
 /// Initializes a new instance of LinkRequest.
 /// </summary>
 /// <param name="linkType">Type of the link.</param>
 /// <param name="patches">The patches.</param>
 /// <param name="symbolName">The symbol that is being patched.</param>
 /// <param name="symbolOffset">The symbol offset.</param>
 /// <param name="relativeBase">The base virtualAddress, if a relative link is required.</param>
 /// <param name="targetSymbol">The linker symbol to link against.</param>
 /// <param name="targetOffset">An offset to apply to the link target.</param>
 public LinkRequest(LinkType linkType, Patch[] patches, string symbolName, int symbolOffset, int relativeBase, string targetSymbol, long targetOffset)
 {
     this.SymbolName = symbolName;
     this.SymbolOffset = symbolOffset;
     this.LinkType = linkType;
     this.SymbolRelativeBase = relativeBase;
     this.TargetSymbol = targetSymbol;
     this.TargetOffset = targetOffset;
     this.Patches = patches;
 }
Esempio n. 11
0
        public static ulong GetFinalMask(Patch[] patches)
        {
            ulong final = 0;

            foreach (var patch in patches)
            {
                final = final | patch.GetResult(~(ulong)0);
            }

            return final;
        }
Esempio n. 12
0
        public static ulong GetResult(Patch[] patches, ulong value)
        {
            ulong final = 0;

            foreach (var patch in patches)
            {
                final = final | patch.GetResult(value);
            }

            return final;
        }
Esempio n. 13
0
        public static void CreateMUO(string path, Patch[] patches)
        {
            PatchWriter writer = new PatchWriter(File.Create(path), PatchFileType.MUO);

            writer.WriteMUOHeader();
            writer.WriteMUOMetaData(new string[] { "MUO", "Created with ConnectUO", "Jeff Boulanger" });
            writer.Write((int)patches.Length);

            for (int i = 0; i < patches.Length; i++)
                writer.WriteMUOPatch(patches[i]);

            writer.Close();
        }
Esempio n. 14
0
        public static void CreateUOP(string path, Patch[] patches)
        {
            PatchWriter writer = new PatchWriter(File.Create(path), PatchFileType.UOP);

            writer.WriteUOPHeader();
            writer.Write(patches.Length);
            writer.Write((int)0);//Unknown

            for (int i = 0; i < patches.Length; i++)
                writer.WriteUOPPatch(patches[i]);

            writer.Close();
        }
Esempio n. 15
0
    static void Main()
    {
        Patch patch = new Patch();
        Type type = typeof(Patch);

        Console.WriteLine(type);

        object[] allAttributes = type.GetCustomAttributes(false);
        foreach (VersionAttribute attribute in allAttributes)
        {
            Console.WriteLine("{0} version is {1}", attribute, attribute.version);
        }
    }
        public PatchGrid( Terrain terrain, int gridWidth, int gridHeight )
        {
            int highestRes = Patch.GetLevelResolution( Patch.HighestDetailLod );
            highestRes *= highestRes;

            VertexBufferFormat format = new VertexBufferFormat( );
            format.Add( VertexFieldSemantic.Position, VertexFieldElementTypeId.Float32, 3 );
            m_Vb = RbGraphics.Factory.CreateVertexBuffer( );
            m_Vb.Create( format, gridWidth * gridHeight * highestRes );

            m_Patches = new Patch[ gridWidth, gridHeight ];

            float z = -PatchDepth * ( gridHeight / 2 );
            float xInc = PatchWidth;
            float zInc = PatchDepth;

            float maxWidth = gridWidth * PatchWidth;
            float maxHeight = gridWidth * PatchDepth;

            terrain.SetTerrainArea( maxWidth, maxHeight );

            int vbOffset = 0;

            for ( int row = 0; row < gridHeight; ++row, z += zInc )
            {
                float x = -PatchWidth * ( gridWidth / 2 );
                for ( int col = 0; col < gridWidth; ++col, x += xInc )
                {
                    Color c = ( ( col + row ) % 2 ) == 0 ? Color.Black : Color.White;

                    m_Patches[ col, row ] = new Patch( terrain, vbOffset, x, z, PatchWidth, PatchDepth, c );
                    vbOffset += highestRes;
                }
            }

            int maxCol = gridWidth - 1;
            int maxRow = gridHeight - 1;
            for ( int row = 0; row < gridHeight; ++row )
            {
                for ( int col = 0; col < gridWidth; ++col )
                {
                    Patch left	= ( col == 0 ) ? null : ( m_Patches[ col - 1, row ] );
                    Patch right	= ( col == maxCol ) ? null : ( m_Patches[ col + 1, row ] );
                    Patch up	= ( row == 0 ) ? null : ( m_Patches[ col, row - 1] );
                    Patch down	= ( row == maxRow ) ? null : ( m_Patches[ col, row + 1 ] );

                    m_Patches[ col, row ].Link( left, right, up, down );
                }
            }
        }
Esempio n. 17
0
        public Patch ReadMUOPatch()
        {
            Patch p = new Patch();

            p.FileId = ReadInt32();
            p.BlockID = ReadInt32();
            p.Extra = ReadInt32();
            p.Length = ReadInt32();

            if (p.Length >= 0)
                p.Data = ReadBytes(p.Length);
            else
                p.Data = new byte[0];

            return p;
        }
Esempio n. 18
0
 public void WritePatch(Patch patch)
 {
     switch (patchFileType)
     {
         case PatchFileType.MUO:
             {
                 WriteMUOPatch(patch);
                 break;
             }
         case PatchFileType.UOP:
             {
                 WriteUOPPatch(patch);
                 break;
             }
     }
 }
        private static void Testv1( ) {
            var folder = @"Resources\Assembly-1.0\ProviderTestLib.dll";
            var assembly = LoadAssembly(folder);

            var snapshot = SnapShot.BuildFrom(assembly);
            Assert.IsFalse(snapshot.IsEmpty);
            Assert.IsTrue(snapshot.Settings.Count == 1);
            Assert.IsTrue(snapshot.ConnectionStrings.Count == 0);

            var patch1 = new Patch(snapshot, Patch.Action.ActionType.Insert);
            patch1.Apply(new Patch.ApplyOptions());

            snapshot = SnapShot.GetFor(snapshot.Section);

            Assert.IsFalse(snapshot.IsEmpty);
            Assert.IsTrue(snapshot.Settings.Count == 1);
            Assert.IsTrue(snapshot.ConnectionStrings.Count == 0);
        }
Esempio n. 20
0
        public static PatchDocument Parse(Patch patch)
        {
            if (patch == null)
                return new PatchDocument(Array.Empty<PatchEntry>(), Array.Empty<PatchLine>());

            var lines = new List<PatchLine>();
            var entries = new List<PatchEntry>();

            foreach (var change in patch)
            {
                var changeLines = ParseLines(change.Patch);
                var entryOffset = lines.Count;
                var entryLength = changeLines.Count;
                lines.AddRange(changeLines);

                var hunks = new List<PatchHunk>();

                var hunkOffset = GetNextHunk(changeLines, -1);
                while (hunkOffset < changeLines.Count)
                {
                    var hunkEnd = GetNextHunk(changeLines, hunkOffset) - 1;
                    var hunkLength = hunkEnd - hunkOffset + 1;
                    var hunkLine = changeLines[hunkOffset].Text;

                    int oldStart;
                    int oldLength;
                    int newStart;
                    int newLength;
                    if (TryGetHunkInformation(hunkLine, out oldStart, out oldLength, out newStart, out newLength))
                    {
                        var hunk = new PatchHunk(entryOffset + hunkOffset, hunkLength, oldStart, oldLength, newStart, newLength);
                        hunks.Add(hunk);
                    }

                    hunkOffset = hunkEnd + 1;
                }

                var entry = new PatchEntry(entryOffset, entryLength, patch, change, hunks);
                entries.Add(entry);
            }

            return new PatchDocument(entries, lines);
        }
Esempio n. 21
0
File: U4Test.cs Progetto: mholub/u4
    // Use this for initialization
    void Start()
    {
        Patch p = new Patch();
        ValueNode<float> v1 = new ValueNode<float>();
        p.AddNode(v1);
        v1.Output.Value = 15;

        v2 = new ValueNode<float>();
        p.AddNode(v2);

        AddNode sum = new AddNode();
        p.AddNode(sum);

        p.Connect(v1.Output, sum.A);
        p.Connect(v2.Output, sum.B);

        patchEvaluator = new PatchEvaluator(p);
        patchEvaluator.Evaluate();
    }
        private void ObtainNewPatch()
        {
            if (bestCuts.Count < 1) return;

            int n = mesh.FaceCount;
            bool[] visited =  new bool[n];
            Isoline lastLine = this.bestCuts[bestCuts.Count - 1];
            foreach (FaceRecord fr in lastLine.faces)
            {
                visited[fr.face.index] = true;
            }

            /*	foreach (Patch pch in this.patches)
            {
                foreach (int f in pch.faces)
                    visited[f] = true;
            }
             * */

            int i = -1;
            foreach (List<int> flist in this.facesOnStrokes)
            {
                int f = flist[0];
                i = f;
                break;
            }
            if (i == -1)
            {
                Program.PrintText("Invalid source vertex!");
                return;
            }
            int index = this.all_patches.Count + 1;
            int pid = patchid[i];
            Patch p = new Patch(index);
            Queue<int> iQue = new Queue<int>();
            iQue.Enqueue(i);
            visited[i] = true;
            p.faces.Add(i);
            while(iQue.Count > 0)
            {
                int f = iQue.Dequeue();
                foreach (int adj in mesh.AdjFF[f])
                {
                    if (patchid[adj] == pid && !visited[adj])
                    {
                        iQue.Enqueue(adj);
                        visited[adj] = true;
                        p.faces.Add(adj);
                    }
                }
            }
            // --  assign faces on the isoline --
            foreach (FaceRecord fr in lastLine.faces)
            {
                int f = fr.face.index;
                p.faces.Add(f);
            }
            p.prev_label = pid;
            foreach (int f in p.faces)
                patchid[f] = (byte)index;
            this.all_patches.Add(p);
        }
        void ParsePatch(Entity entity, ref int line, List<string> lines)
        {
            //++line;
            string defLine = lines[line].ToLower();
            Patch patch = new Patch(defLine.Contains("mesh"));
            bool tFormat = defLine.Contains("mesh") || defLine.Contains("curve");

            // Skip the definition line, skip the {
            line += 2;

            if (!tFormat)
            {
                // Get the texture name
                patch.TextureName = lines[line].Trim();
                ++line;
                // Get the patch dimensions
                string[] sizeTerms = lines[line].Split(SPLIT_CHARS, StringSplitOptions.RemoveEmptyEntries);
                patch.Rows = int.Parse(sizeTerms[0]);
                patch.Columns = int.Parse(sizeTerms[1]);
                ++line;
            }
            else
            {
                for (; line < lines.Count; ++line)
                {
                    if (lines[line].Contains("lightmap") || lines[line].Contains("content"))
                        continue;
                    else
                    {
                        if (lines[line].Contains("("))
                        {
                            break;
                        }
                        string[] terms = lines[line].Trim().Split(' ');
                        if (terms.Length == 1)
                            patch.TextureName = terms[0];
                        else if (terms.Length == 4)
                        {
                            patch.Rows = int.Parse(terms[0]);
                            patch.Columns = int.Parse(terms[1]);
                        }
                    }
                }
            }

            int jumpCt = 0;
            for (; line < lines.Count; ++line)
            {
                string text = lines[line];
                string shortLine = lines[line].Trim();

                if (shortLine.Contains("}"))
                {
                    ++jumpCt;
                    if (jumpCt == 2) // Leave after second } encounters { patchDef { "content" } } <--
                        break;
                    continue;
                }
                else
                {
                    string[] terms = shortLine.Split(PATCH_SPLIT, StringSplitOptions.RemoveEmptyEntries);
                    if (tFormat)
                    {
                        if (shortLine.Contains('v'))
                        {
                            PatchVert vert = new PatchVert();
                            vert.Position = Face.ParseVec3(terms, 0);
                            // If we contain a color
                            if (shortLine.Contains('c'))
                            {
                                vert.Color = Face.ParseVec3(terms, 3);
                                vert.Alpha = float.Parse(terms[6]);
                                vert.UV = Face.ParseVec2(terms, 7);
                            }
                            else
                                vert.UV = Face.ParseVec2(terms, 3);
                            patch.FlatVertices.Add(vert);
                        }
                    }
                    else if (terms.Length > 0)
                    {
                        // Id format
                        if (shortLine.Count(c => c == '(') > 0)
                        {
                            List<PatchVert> rowVerts = new List<PatchVert>();
                            // ( (x y z u v) (x y z u v) (x y z u v) )
                            for (int i = 0; i < patch.Columns; ++i)
                            {
                                PatchVert vert = new PatchVert();
                                int startSub = i * 5;
                                // (x y z u v)
                                vert.Position = Face.ParseVec3(terms, startSub);
                                vert.UV = Face.ParseVec2(terms, startSub + 3);
                                rowVerts.Add(vert);
                                patch.FlatVertices.Add(vert);
                            }
                            patch.PatchVertices.Add(rowVerts);
                        }
                    }
                }
            }
            entity.Patches.Add(patch);
        }
Esempio n. 24
0
 public void SetNeighbors(Patch l,Patch r,Patch t,Patch b)
 {
     Left=l;
     Right=r;
     Top=t;
     Bottom=b;
 }
Esempio n. 25
0
 public void Remove()
 {
     Patch.Remove();
 }
Esempio n. 26
0
        public void AddPopulationResultForSpecies(Species species, Patch patch, int newPopulation)
        {
            MakeSureResultExistsForSpecies(species);

            results[species].NewPopulationInPatches[patch] = Math.Max(newPopulation, 0);
        }
Esempio n. 27
0
 public void AddMigrationResultForSpecies(Species species, Patch fromPatch, Patch toPatch, int populationAmount)
 {
     AddMigrationResultForSpecies(species, new SpeciesMigration(fromPatch, toPatch, populationAmount));
 }
Esempio n. 28
0
 public void Init()
 {
     _pd    = new Pd(_inputs, _outputs, _sampleRate);
     _patch = _pd.LoadPatch("../../test_csharp.pd");
 }
Esempio n. 29
0
        private void LoadConfiguration(string configFilePath)
        {
            XPathNavigator navigator            = GetNavigator(configFilePath);
            string         overallTimeoutString = navigator.SelectSingleNode(OverallTimeoutValueXPath).Value;

            if (string.IsNullOrEmpty(overallTimeoutString) || (!int.TryParse(overallTimeoutString, out _overallTimeoutSeconds)))
            {
                LogUtils.WriteTrace(DateTime.UtcNow, "OverallTimeout value is not defined or is not a valid integer value. OverallTimeout = " +
                                    (string.IsNullOrEmpty(overallTimeoutString) ? "null" : overallTimeoutString));

                throw new InvalidOperationException(
                          "OverallTimeout value is not defined or is not a valid integer value. OverallTimeout = " +
                          (string.IsNullOrEmpty(overallTimeoutString) ? "null" : overallTimeoutString));
            }

            if (_overallTimeoutSeconds < 0)
            {
                LogUtils.WriteTrace(DateTime.UtcNow, "OverallTimeout value cannot be less than 0. OverallTimeout = " +
                                    overallTimeoutString);

                throw new InvalidOperationException(
                          "OverallTimeout value cannot be less than 0. OverallTimeout = " +
                          overallTimeoutString);
            }

            // Loop through all patches
            XPathNodeIterator nodeIterator = navigator.Select(PatchXPath);

            while (nodeIterator.MoveNext())
            {
                Patch patch = new Patch();

                // Read name
                if (nodeIterator.Current.SelectSingleNode("@name") == null)
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, "name attribute needed for Patch element");

                    throw new InvalidOperationException("name attribute needed for Patch element");
                }

                patch.Name = nodeIterator.Current.SelectSingleNode("@name").Value.Trim();
                if (string.IsNullOrEmpty(patch.Name))
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, "name attribute can't be empty for Patch element");

                    throw new InvalidOperationException("name attribute can't be empty for Patch element");
                }

                if (_patchMap.ContainsKey(patch.Name))
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, string.Format(CultureInfo.InvariantCulture, "Patch '{0}' is defined in multiple places.", patch.Name));

                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Patch '{0}' is defined in multiple places.", patch.Name));
                }

                // Read OS versions the patch applies to and check whether it is applicable to current OS version
                if (nodeIterator.Current.SelectSingleNode("@appliesToOsVersion") != null)
                {
                    string osVersionAppliesTo = string.Empty;

                    try
                    {
                        bool invalidVersionFormat = false;
                        osVersionAppliesTo = nodeIterator.Current.SelectSingleNode("@appliesToOsVersion").Value.Trim();

                        Version currentOsVersion = Environment.OSVersion.Version;

                        char[]   versionDelimiter           = new char[] { '.' };
                        string[] versionComponents          = osVersionAppliesTo.Split(versionDelimiter);
                        string[] currentOsVersionComponents = currentOsVersion.ToString().Split(versionDelimiter);

                        // OS version the patch applies to should have four components: major.minor.build.revision
                        if (versionComponents.Length != 4)
                        {
                            invalidVersionFormat = true;
                        }
                        else
                        {
                            // Each version component should be an integer or a wildcard character '*'
                            foreach (string t in versionComponents)
                            {
                                int versionComponent;
                                if (t.Equals("*", StringComparison.OrdinalIgnoreCase) || int.TryParse(t, out versionComponent))
                                {
                                    continue;
                                }
                                invalidVersionFormat = true;
                                break;
                            }
                        }

                        if (invalidVersionFormat)
                        {
                            LogUtils.WriteTrace(DateTime.UtcNow, string.Format(
                                                    @"PathUtil: Invalid version format for OS version patch {0} applies to : {1}; the patch will be installed",
                                                    patch.Name,
                                                    osVersionAppliesTo));
                        }
                        else
                        {
                            bool skipPatch = false;
                            for (int i = 0; i < Math.Min(versionComponents.Length, currentOsVersionComponents.Length); i++)
                            {
                                if (!versionComponents[i].Equals("*", StringComparison.OrdinalIgnoreCase) &&
                                    !versionComponents[i].Equals(currentOsVersionComponents[i], StringComparison.OrdinalIgnoreCase))
                                {
                                    skipPatch = true;
                                }
                            }

                            // If the patch is not applicable to current OS version, skip it
                            if (skipPatch)
                            {
                                LogUtils.WriteTrace(DateTime.UtcNow, string.Format(
                                                        @"PatchUtil: Patch {0} will be skipped since it is only applicable to OS version {1} while current OS version is {2}",
                                                        patch.Name,
                                                        osVersionAppliesTo,
                                                        currentOsVersion));

                                continue;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LogUtils.WriteTrace(DateTime.UtcNow, string.Format(
                                                @"PathUtil: Exception occurred when checking whether patch {0} (applicable to OS version {1}) is applicable to current OS version, skip version checking and continue installing : {2}",
                                                patch.Name,
                                                osVersionAppliesTo,
                                                e));
                    }
                }

                // Read command line.
                if (nodeIterator.Current.SelectSingleNode(CommandLineXPath) == null)
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, string.Format(CultureInfo.InvariantCulture, "Command value attribute needed for Patch '{0}'.", patch.Name));

                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Command value attribute needed for Patch '{0}'.", patch.Name));
                }

                patch.CommandLine = nodeIterator.Current.SelectSingleNode(CommandLineXPath).Value.Trim();

                if (string.IsNullOrEmpty(patch.CommandLine))
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, string.Format(CultureInfo.InvariantCulture, "Command value can't be empty for Patch '{0}'.", patch.Name));

                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Command value can't be empty for Patch '{0}'.", patch.Name));
                }

                // Read log path (optional element).
                patch.LogFolderPath = null;
                if (nodeIterator.Current.SelectSingleNode(LogFolderPathXPath) != null)
                {
                    string logFolderPath = nodeIterator.Current.SelectSingleNode(LogFolderPathXPath).Value.Trim();

                    if (!string.IsNullOrEmpty(logFolderPath))
                    {
                        patch.LogFolderPath = logFolderPath;
                    }
                }

                // Read registry settings
                List <PatchRegistry> registrySettings = new List <PatchRegistry>();
                XPathNodeIterator    iterator         = nodeIterator.Current.Select(PatchRegistryXPath);
                while (iterator.MoveNext())
                {
                    string keyName       = ReadPatchRegistryAttribute(iterator, patch.Name, RegistryKeyNameAttribute, true);
                    string valueName     = ReadPatchRegistryAttribute(iterator, patch.Name, RegistryValueNameAttribute, true);
                    string expectedValue = ReadPatchRegistryAttribute(iterator, patch.Name, RegistryExpectedValueAttribute, false);

                    PatchRegistry registrySetting = new PatchRegistry
                    {
                        RegistryKeyName   = keyName,
                        RegistryValueName = valueName,
                        ExpectedValue     = expectedValue,
                    };
                    registrySettings.Add(registrySetting);
                }

                // We need at least one registry setting to confirm the patch is installed.
                if (!registrySettings.Any())
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, string.Format(CultureInfo.InvariantCulture, "There is no registry setting found for Patch '{0}'", patch.Name));

                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "There is no registry setting found for Patch '{0}'", patch.Name));
                }

                patch.RegistrySettings = registrySettings;
                _patchMap.Add(patch.Name, patch);
            }
        }
Esempio n. 30
0
 public Ward(Model model, Patch patch)
 {
     this.model = model;
     this.patch = patch;
 }
Esempio n. 31
0
 public static float rateLocation(Model model, Patch patch)
 {
     return(0);
 }
Esempio n. 32
0
 public TestPatch(Patch patch, string patchOutput)
 {
     Patch       = patch;
     PatchOutput = patchOutput;
 }
Esempio n. 33
0
 protected record PatchInfo(Patch Patch, long Offset);
Esempio n. 34
0
    /// <summary>
    ///   Combined old editor init and activate method
    /// </summary>
    private void InitEditor()
    {
        // For now we only show a loading screen if auto-evo is not ready yet
        if (!CurrentGame.GameWorld.IsAutoEvoFinished())
        {
            ready = false;
            gui.SetLoadingStatus(true);
            gui.SetLoadingText("Loading Microbe Editor", CurrentGame.GameWorld.GetAutoEvoRun().Status);
        }
        else
        {
            OnEditorReady();
        }

        MutationPoints          = Constants.BASE_MUTATION_POINTS;
        editedMicrobeOrganelles = new OrganelleLayout <OrganelleTemplate>(
            OnOrganelleAdded, OnOrganelleRemoved);

        organelleRot = 0;

        Symmetry = 0;
        gui.ResetSymmetryButton();

        UpdateUndoRedoButtons();

        // The world is reset each time so these are gone
        placedHexes  = new List <MeshInstance>();
        placedModels = new List <SceneDisplayer>();

        // Check generation and set it here.

        CurrentGame.SetBool("edited_microbe", true);

        if (CurrentGame.FreeBuild)
        {
            GD.Print("Editor going to freebuild mode because player has activated freebuild");
            FreeBuilding = true;
        }
        else
        {
            // Make sure freebuilding doesn't get stuck on
            FreeBuilding = false;
        }

        // Sent freebuild value to GUI
        gui.NotifyFreebuild(FreeBuilding);

        playerPatchOnEntry = CurrentGame.GameWorld.Map.CurrentPatch;

        // Send info to the GUI about the organelle effectiveness in the current patch
        CalculateOrganelleEffectivenessInPatch();

        // Reset this, GUI will tell us to enable it again
        ShowHover   = false;
        targetPatch = null;

        canStillMove = true;

        UpdatePatchBackgroundImage();

        gui.SetMap(CurrentGame.GameWorld.Map);

        var playerSpecies = CurrentGame.GameWorld.PlayerSpecies;

        SetupEditedSpecies(playerSpecies as MicrobeSpecies);

        gui.UpdateGlucoseReduction(Constants.GLUCOSE_REDUCTION_RATE);
    }
Esempio n. 35
0
 public PatchingHook(IMemory memory, IntPtr targetAddress, byte[] redirection)
 {
     Patch = new Patch(memory, targetAddress, redirection);
 }
        public void LoadSegmentation(StreamReader sr)
        {
            this.all_patches.Clear();

            this.patchid = new byte[mesh.FaceCount];

            //char[] delimiters = { ' ', '\t' };
            string s = "";

            //s = sr.ReadLine();
            //string[] tokens = s.Split(delimiters);
            //int count = int.Parse(tokens[0]);

            // Use patchid as read buffer
            // Keep the max label to find number of patches
            int maxLabel = 0;
            for (int faceId = 0; faceId < this.patchid.Length; faceId++ )
            {
                s = sr.ReadLine();
                int label = int.Parse(s);
                if (maxLabel < label) maxLabel = label;
                this.patchid[faceId] = (byte)label;
            }

            for (int i = 1; i <= maxLabel; ++i)
            {
                Patch p = new Patch(i);
                all_patches.Add(p);
            }

            for (int i = 0; i < this.patchid.Length; i++)
            {
                // For in-patch faces, assign them into corresponding patches
                if (this.patchid[i] < maxLabel)
                {
                    all_patches[patchid[i]].faces.Add(i);
                }
            }
                /*
                while (sr.Peek() > -1)
                {
                    s = sr.ReadLine();
                    tokens = s.Split(delimiters);
                    int index = int.Parse(tokens[1]);
                    int f = int.Parse(tokens[0]);
                    all_patches[index].faces.Add(f);

                    this.patchid[f] = (byte)index;
                }
                */
                this.AssignPatchColors();

            this.displayMode = EnumDisplayMode.Segmentation;
        }
 private void InitPatches()
 {
     _leftPatch = new Patch()
     {
         ImageMatrix = _leftFiltered,
         Rows = _patchSize,
         Cols = _patchSize
     };
     _rightPatch = new Patch()
     {
         ImageMatrix = _rightFiltered,
         Rows = _patchSize,
         Cols = _patchSize
     };
 }
Esempio n. 38
0
 public PatchRequest(Patch patch, RequestCallback callback) : base(patch.Filename, callback)
 {
     this.patch = patch;
 }
Esempio n. 39
0
 public override void Draw(GdxSpriteBatch spriteBatch, float x, float y, float width, float height)
 {
     Patch.Draw(spriteBatch, x, y, width, height);
 }
Esempio n. 40
0
 /// <summary>
 ///   variant of GetGlobalPopulation for a single patch
 /// </summary>
 public int GetPopulationInPatch(Species species, Patch patch)
 {
     return(Math.Max(results[species].NewPopulationInPatches[patch], 0));
 }
Esempio n. 41
0
 public void AppendDiffLine(string line, Encoding fileEncoding)
 {
     Patch.AppendTextLine(line);
     PatchOutput.Append(GitModule.ReEncodeString(line, fileEncoding, GitModule.LosslessEncoding));
     PatchOutput.Append("\n");
 }
Esempio n. 42
0
        private bool Find(ITableRepository tableRepository, IPatcher patcher, ICheckNotifier notifier)
        {
            //if it's not configured
            if (tableRepository == null)
            {
                DatabaseFound(this, new PlatformDatabaseFoundEventArgs(null, patcher, RDMPPlatformDatabaseStatus.Unreachable));
                return(false);
            }

            //check we can reach it
            var db = tableRepository.DiscoveredServer.GetCurrentDatabase();

            notifier.OnCheckPerformed(new CheckEventArgs(string.Format("Connecting to {0} on {1}", db.GetRuntimeName(), db.Server.Name), CheckResult.Success));

            //is it reachable
            try
            {
                tableRepository.TestConnection();
            }
            catch (Exception ex)
            {
                //no
                DatabaseFound(this, new PlatformDatabaseFoundEventArgs(tableRepository, patcher, RDMPPlatformDatabaseStatus.Unreachable, ex));
                return(false);
            }


            Patch.PatchingState patchingRequired;
            try
            {
                //is it up-to-date on patches?
                Version databaseVersion;
                Patch[] patchesInDatabase;
                SortedDictionary <string, Patch> allPatchesInAssembly;

                patchingRequired = Patch.IsPatchingRequired(tableRepository.DiscoveredServer.GetCurrentDatabase(), patcher, out databaseVersion, out patchesInDatabase, out allPatchesInAssembly);
            }
            catch (Exception e)
            {
                //database is broken (maybe the version of the db is ahead of the host assembly?)
                DatabaseFound(this, new PlatformDatabaseFoundEventArgs(tableRepository, patcher, RDMPPlatformDatabaseStatus.Broken, e));
                return(false);
            }

            switch (patchingRequired)
            {
            case Patch.PatchingState.NotRequired:
                DatabaseFound(this, new PlatformDatabaseFoundEventArgs(tableRepository, patcher, RDMPPlatformDatabaseStatus.Healthy));
                break;

            case Patch.PatchingState.Required:
                DatabaseFound(this, new PlatformDatabaseFoundEventArgs(tableRepository, patcher, RDMPPlatformDatabaseStatus.RequiresPatching));
                break;

            case Patch.PatchingState.SoftwareBehindDatabase:
                DatabaseFound(this, new PlatformDatabaseFoundEventArgs(tableRepository, patcher, RDMPPlatformDatabaseStatus.SoftwareOutOfDate));
                break;

            default: throw new ArgumentOutOfRangeException("patchingRequired");
            }

            return(true);
        }
 /// <inheritdoc />
 public DigitalPartialsEditorViewModel(Patch patch)
 {
     Items.Add(new DigitalPartialViewModel(patch.PartialOne, "Partial 1"));
     Items.Add(new DigitalPartialViewModel(patch.PartialTwo, "Partial 2"));
     Items.Add(new DigitalPartialViewModel(patch.PartialThree, "Partial 3"));
 }
Esempio n. 44
0
 public void Apply()
 {
     Patch.Apply();
 }
Esempio n. 45
0
    Dictionary <int, Note> lookupTbl = new Dictionary <int, Note>(); //Dictionary of active notes. Makes for faster lookup.

    public Channel(double sample_rate = 44100)
    {
        patch = new Patch(sample_rate);
        patch.FromString(glue.INIT_PATCH, true);
    }
Esempio n. 46
0
        /// <summary>
        /// Gets a sound effect from the sound effects cache.
        /// </summary>
        /// <param name="Patch">A Patch instance containing the file location or ID.</param>
        /// <returns>The sound effect.</returns>
        public SoundEffect GetSFX(Patch patch)
        {
            if (patch == null)
            {
                return(null);
            }
            var InstanceID = patch.FileID;

            if (SFXCache.ContainsKey(InstanceID))
            {
                return(SFXCache[InstanceID]);
            }
            byte filetype = 0;

            byte[] data = GetAudioFrom(InstanceID, TSOAudio, out filetype);
            if (data == null)
            {
                data = GetAudioFrom(InstanceID, tsov2, out filetype);
            }
            if (data == null)
            {
                data = GetAudioFrom(InstanceID, Stings, out filetype);
            }
            if (data == null)
            {
                data = GetAudioFrom(InstanceID, EP5Samps, out filetype);
            }
            if (data == null)
            {
                data = GetAudioFrom(InstanceID, EP2, out filetype);
            }
            if (data == null)
            {
                string source;
                if (NightclubSounds.TryGetValue(InstanceID, out source))
                {
                    data = new XAFile(source).DecompressedData;
                }
            }

            if (data != null)
            {
                var stream = new MemoryStream(data);

                var sfx = SoundEffect.FromStream(stream);
                stream.Close();
                SFXCache.Add(InstanceID, sfx);
                switch (filetype)
                {
                case 2:
                    sfx.Name = "VOX";
                    break;

                case 3:
                    sfx.Name = "MUSIC";
                    break;

                default:
                    sfx.Name = "FX";
                    break;
                }
                return(sfx); //remember to clear the sfx cache between lots!
            }
            else
            {
                //GCHandle pinnedArray = GCHandle.Alloc(new byte[1], GCHandleType.Weak);
                return(null);// pinnedArray; //we couldn't find anything! can't return null so do this... not the best idea tbh
            }
        }
Esempio n. 47
0
 public void AppendHeaderLine(string line)
 {
     Patch.AppendTextLine(line);
     PatchOutput.Append(GitModule.ReEncodeString(line, GitModule.SystemEncoding, GitModule.LosslessEncoding));
     PatchOutput.Append("\n");
 }
Esempio n. 48
0
 public void ViewStagingPatch(Patch patch)
 {
     ViewPatch(patch);
     Reset(true, true, true);
 }
Esempio n. 49
0
        static void UpdatePatch(bool updatePreview = false)
        {
            Console.WriteLine("Updating Patch csv...");
            if (!File.Exists(@"patch_new.csv"))
            {
                Decompress(@"patch_new.csv.lz4");
            }
            var patches = ReadFile <Patch>(@"patch_new.csv");

            var songInfo     = GetFileInfo(SONG_PATH);
            var songDescInfo = GetFileInfo(SONG_DESC_PATH);
            var ptInfo       = GetFileInfo(PATTERN_PATH);
            var piInfo       = GetFileInfo(PRODUCT_ITEM_PATH);
            var ppInfo       = GetFileInfo(PRODUCT_PRODUCT_PATH);
            var caInfo       = GetFileInfo(CATEGORY_PRODUCT_PATH);
            var idInfo       = GetFileInfo(ITEM_DESC_PATH);

            foreach (Patch patch in patches)
            {
                if (patch.file_name.Contains("song_desc_"))
                {
                    UpdateField(patch, songDescInfo);
                }
                if (patch.file_name.Contains("song_song.csv"))
                {
                    UpdateField(patch, songInfo);
                }
                if (patch.file_name.Contains("song_songPattern.csv"))
                {
                    UpdateField(patch, ptInfo);
                }
                if (patch.file_name.Contains("product_item.csv"))
                {
                    UpdateField(patch, piInfo);
                }
                if (patch.file_name.Contains("product_product.csv"))
                {
                    UpdateField(patch, ppInfo);
                }
                if (patch.file_name.Contains("category_categoryproduct.csv"))
                {
                    UpdateField(patch, caInfo);
                }
                if (patch.file_name.Contains("item_desc_"))
                {
                    UpdateField(patch, idInfo);
                }
            }

            if (updatePreview)
            {
                foreach (string file in Directory.EnumerateFiles("preview", "*.opus"))
                {
                    Console.WriteLine("Updating preview info ... {0}", file);
                    Compress(file);
                    var   info     = GetFileInfo(file);
                    var   fileName = file.Replace("\\", "/");
                    var   result   = patches.Where(x => x.file_name.Contains(fileName));
                    Patch patch;
                    if (result.Any())
                    {
                        patch = result.First();
                    }
                    else
                    {
                        patch                   = new Patch();
                        patch.file_name         = fileName;
                        patch.acquire_on_demand = 0;
                        patch.compressed        = 1;
                        patch.platform          = "";
                        patch.tag               = "";
                        patch.unused            = "";
                        patches.AddLast(patch);
                    }
                    patch.checksum             = info.checksum;
                    patch.file_size            = info.file_size;
                    patch.compressed_checksum  = info.compressed_checksum;
                    patch.compressed_file_size = info.compressed_file_size;
                }
            }

            WriteFile(patches.ToList(), PATCH_HEADER, @"patch_new.csv");
            Compress(@"patch_new.csv");
        }
Esempio n. 50
0
        public void ViewPatch(Patch patch)
        {
            string text = patch != null ? patch.Text : "";

            ViewPatch(text);
        }
Esempio n. 51
0
        protected void Init(IHeightMap heightmap,Texture color,Texture detail)
        {
            Height=heightmap;
            if(Height.Size.X!=Height.Size.Y)
                throw new Exception("map.Size.X!=map.Size.Y");
            if(IsPowerOf2(Height.Size.X-1))
            {
                PatchCount=(Height.Size.X-1)/(PatchSize-1);
            }
            else if(IsPowerOf2(Height.Size.X))
            {
                PatchCount=(Height.Size.X)/(PatchSize-1);
            }
            else
                throw new Exception("!IsPowerOf2(map.Size.X-1)");
            if(Height.Size.X<PatchSize)
                throw new Exception("map.Size.X<patchvertexsize");
            Levels=(int)Math.Log(PatchSize-1,2)+1;

            Patches=new Patch[PatchCount][];
            for(int x=0;x<PatchCount;++x)
            {
                Patches[x]=new Patch[PatchCount];
                for(int y=0;y<PatchCount;++y)
                {
                    Patch p=new Patch(this,x,y);
                    Patches[x][y]=p;
                }
            }
            for(int x=0;x<PatchCount;++x)
            {
                for(int y=0;y<PatchCount;++y)
                {
                    Patches[y][x].SetNeighbors(x>0 ? Patches[y][x-1] : null,
                        x<PatchCount-1 ? Patches[y][x+1] : null,
                        y>0 ? Patches[y-1][x] : null,
                        y<PatchCount-1 ? Patches[y+1][x] : null);

                    Patches[y][x].Generate();
                }
            }
            /*for(int x=0;x<PatchCount;++x)
            {
                for(int y=0;y<PatchCount;++y)
                {
                    Patches[y][x].Generate();
                }
            }*/
            Material=new Material();
            Material.diffusemap=color;
            Material.DetailMap=detail;

            HighDetail = 1 * PatchScale;
            LowDetail = HighDetail + Levels * PatchScale * 1.2f;
            //Color=color;
            //Detail=detail;
            Tree=new QuadTree(new Vector3(0,HeightScale/2,0),new Vector3(PatchScale*(float)PatchCount,HeightScale,PatchScale*(float)PatchCount),(int)Math.Log(PatchCount,2)+1,new Point(PatchCount,PatchCount));

            //collision
            /*Ode.dVector3[] verts=new Ode.dVector3[heightmap.Size.X*heightmap.Size.Y];
            int[] inds=new int[(heightmap.Size.X-1)*(heightmap.Size.Y-1)*2*3];
            int i=0;
            int j=0;
            for(int y=0;y<heightmap.Size.Y;++y)
            {
                for(int x=0;x<heightmap.Size.X;++x)
                {
                    float h=((float)Height.GetHeight(x,y)/255)*HeightScale;
                    verts[i].X = (float)(x - heightmap.Size.X / 2) * PatchScale;
                    verts[i].Y = h;
                    verts[i].Z = (float)(y - heightmap.Size.Y / 2) * PatchScale;
                    if (x < heightmap.Size.X - 1 && y < heightmap.Size.Y - 1)
                    {
                        inds[j++] = y * heightmap.Size.X + x;
                        inds[j++] = y * heightmap.Size.X + x +1;
                        inds[j++] = (y+1) * heightmap.Size.X + x;

                        inds[j++] = (y + 1) * heightmap.Size.X + x;
                        inds[j++] = y * heightmap.Size.X + x + 1;
                        inds[j++] = (y + 1) * heightmap.Size.X + x +1;
                    }
                    i++;
                }
            }

            CollisionMesh = new OdeTriMeshData(verts,inds);*/
            //CollisionMesh.
        }
Esempio n. 52
0
 /// <summary>
 /// No longer needed since press is included in enemy damage rando table
 /// </summary>
 public static void EnablePressDamage(Patch Patch)
 {
     Patch.Add(EDmgVsEnemy.DamageP + EDmgVsEnemy.Offset.Press, 0x01, "Buster Damage Against Press");
 }
Esempio n. 53
0
 public PatchEvaluator(Patch p)
 {
     patch = p;
     createEvaluators();
 }
Esempio n. 54
0
    /// <remarks>
    ///   TODO: this function should be cleaned up by generalizing the adding
    ///   the increase or decrease icons in order to remove the duplicated
    ///   logic here
    /// </remarks>
    private void UpdateConditionDifferencesBetweenPatches(Patch selectedPatch, Patch currentPatch)
    {
        var nextCompound = selectedPatch.Biome.AverageTemperature;

        if (nextCompound > currentPatch.Biome.AverageTemperature)
        {
            patchTemperatureSituation.Texture = IncreaseIcon;
        }
        else if (nextCompound < currentPatch.Biome.AverageTemperature)
        {
            patchTemperatureSituation.Texture = DecreaseIcon;
        }
        else
        {
            patchTemperatureSituation.Texture = null;
        }

        nextCompound = selectedPatch.Biome.Compounds["sunlight"].Dissolved;

        if (nextCompound > currentPatch.Biome.Compounds["sunlight"].Dissolved)
        {
            patchLightSituation.Texture = IncreaseIcon;
        }
        else if (nextCompound < currentPatch.Biome.Compounds["sunlight"].Dissolved)
        {
            patchLightSituation.Texture = DecreaseIcon;
        }
        else
        {
            patchLightSituation.Texture = null;
        }

        nextCompound = selectedPatch.Biome.Compounds["hydrogensulfide"].Density *
                       selectedPatch.Biome.Compounds["hydrogensulfide"].Amount + GetPatchChunkTotalCompoundAmount(
            selectedPatch, "hydrogensulfide");

        if (nextCompound > currentPatch.Biome.Compounds["hydrogensulfide"].Density *
            currentPatch.Biome.Compounds["hydrogensulfide"].Amount + GetPatchChunkTotalCompoundAmount(
                currentPatch, "hydrogensulfide"))
        {
            patchHydrogenSulfideSituation.Texture = IncreaseIcon;
        }
        else if (nextCompound < currentPatch.Biome.Compounds["hydrogensulfide"].Density *
                 currentPatch.Biome.Compounds["hydrogensulfide"].Amount + GetPatchChunkTotalCompoundAmount(
                     currentPatch, "hydrogensulfide"))
        {
            patchHydrogenSulfideSituation.Texture = DecreaseIcon;
        }
        else
        {
            patchHydrogenSulfideSituation.Texture = null;
        }

        nextCompound = selectedPatch.Biome.Compounds["glucose"].Density *
                       selectedPatch.Biome.Compounds["glucose"].Amount + GetPatchChunkTotalCompoundAmount(
            selectedPatch, "glucose");

        if (nextCompound > currentPatch.Biome.Compounds["glucose"].Density *
            currentPatch.Biome.Compounds["glucose"].Amount + GetPatchChunkTotalCompoundAmount(
                currentPatch, "glucose"))
        {
            patchGlucoseSituation.Texture = IncreaseIcon;
        }
        else if (nextCompound < currentPatch.Biome.Compounds["glucose"].Density *
                 currentPatch.Biome.Compounds["glucose"].Amount + GetPatchChunkTotalCompoundAmount(
                     currentPatch, "glucose"))
        {
            patchGlucoseSituation.Texture = DecreaseIcon;
        }
        else
        {
            patchGlucoseSituation.Texture = null;
        }

        nextCompound = GetPatchChunkTotalCompoundAmount(selectedPatch, "iron");

        if (nextCompound > GetPatchChunkTotalCompoundAmount(currentPatch, "iron"))
        {
            patchIronSituation.Texture = IncreaseIcon;
        }
        else if (nextCompound < GetPatchChunkTotalCompoundAmount(currentPatch, "iron"))
        {
            patchIronSituation.Texture = DecreaseIcon;
        }
        else
        {
            patchIronSituation.Texture = null;
        }

        nextCompound = selectedPatch.Biome.Compounds["ammonia"].Density *
                       selectedPatch.Biome.Compounds["ammonia"].Amount + GetPatchChunkTotalCompoundAmount(
            selectedPatch, "ammonia");

        if (nextCompound > currentPatch.Biome.Compounds["ammonia"].Density *
            currentPatch.Biome.Compounds["ammonia"].Amount + GetPatchChunkTotalCompoundAmount(
                currentPatch, "ammonia"))
        {
            patchAmmoniaSituation.Texture = IncreaseIcon;
        }
        else if (nextCompound < currentPatch.Biome.Compounds["ammonia"].Density *
                 currentPatch.Biome.Compounds["ammonia"].Amount + GetPatchChunkTotalCompoundAmount(
                     currentPatch, "ammonia"))
        {
            patchAmmoniaSituation.Texture = DecreaseIcon;
        }
        else
        {
            patchAmmoniaSituation.Texture = null;
        }

        nextCompound = selectedPatch.Biome.Compounds["phosphates"].Density *
                       selectedPatch.Biome.Compounds["phosphates"].Amount + GetPatchChunkTotalCompoundAmount(
            selectedPatch, "phosphates");

        if (nextCompound > currentPatch.Biome.Compounds["phosphates"].Density *
            currentPatch.Biome.Compounds["phosphates"].Amount + GetPatchChunkTotalCompoundAmount(
                currentPatch, "phosphates"))
        {
            patchPhosphateSituation.Texture = IncreaseIcon;
        }
        else if (nextCompound < currentPatch.Biome.Compounds["phosphates"].Density *
                 currentPatch.Biome.Compounds["phosphates"].Amount + GetPatchChunkTotalCompoundAmount(
                     currentPatch, "phosphates"))
        {
            patchPhosphateSituation.Texture = DecreaseIcon;
        }
        else
        {
            patchPhosphateSituation.Texture = null;
        }
    }
        private void patch_type_decompose()
        {
            int n = mesh.FaceCount;
            for (int i = 0; i < n; ++i) // -- reset the labels --
                fnode[i].label = -1;
            // -- label seed faces --
            bool[] visited = new bool[n];
            bool[] labeled = new bool[n];
            if (patchid == null) patchid = new byte[n];
            List<int> sources = new List<int>();
            List<int> targets = new List<int>();
            foreach (List<int> flist in this.facesOnStrokes)
            {
                if (flist.Count < 1) continue;
                sources.Add(flist[0]);
                targets.Add(flist[flist.Count - 1]);
            }
            byte pid = patchid[sources[0]]; // -- the patch strokes lies on --
            foreach (int f in sources)
            {
                fnode[f].label = 0;
                visited[f] = true;
                labeled[f] = true;
            }
            int label = 1;
            foreach (int f in targets)
            {
                fnode[f].label = label;
                visited[f] = true;
                labeled[f] = true;
            }
            // -- region growing --
            PriorityQueue iQue = new PriorityQueue();
            foreach (int f in sources)
            {
                foreach (int adj in mesh.AdjFF[f])
                {
                    if (patchid[adj] != pid) continue;
                    fnode[adj].label = fnode[f].label;
                    fnode[adj].dis = Face_wij(f, adj);
                    iQue.Insert(fnode[adj]);
                    visited[adj] = true;
                }
            }
            foreach (int f in targets)
            {
                foreach (int adj in mesh.AdjFF[f])
                {
                    if (patchid[adj] != pid) continue;
                    fnode[adj].label = fnode[f].label;
                    fnode[adj].dis = Face_wij(f, adj);
                    iQue.Insert(fnode[adj]);
                    visited[adj] = true;
                }
            }
            while (!iQue.IsEmpty())
            {
                GraphNode node = iQue.DeleteMin() as GraphNode;

                int f = node.index;
                labeled[f] = true;
                foreach (int adj in mesh.AdjFF[f])
                {
                    if (patchid[adj] != pid) continue;
                    if (labeled[adj])
                    {
                        continue;
                    }
                    else if (visited[adj])
                    {
                        double wij = Face_wij(f, adj);
                        if (fnode[adj].dis > wij)
                        {
                            fnode[adj].label = fnode[f].label;
                            fnode[adj].dis = wij;
                            iQue.Update(fnode[adj]);
                        }
                    }
                    else
                    {
                        fnode[adj].label = fnode[f].label;
                        fnode[adj].dis = Face_wij(f, adj);
                        iQue.Insert(fnode[adj]);
                        visited[adj] = true;
                    }
                }
            }
            // -- patch the results --
            int index = this.all_patches.Count+1;
            Patch p = new Patch(index);
            p.prev_label = (int)pid;
            for (int i = 0; i < n; ++i)
            {
                if (fnode[i].label == 0)
                {
                    patchid[i] = (byte)index;
                    p.faces.Add(i);
                }
            }
            this.patches.Add(p);
            this.all_patches.Add(p);	// -- global patches --
        }
Esempio n. 56
0
			/// <summary>Create patch wrapper object used for sorting</summary>
			/// <param name="patch">Patch to wrap</param>
			internal PatchSortingWrapper(Patch patch)
			{
				innerPatch = patch;
				before = new HashSet<PatchSortingWrapper>();
				after = new HashSet<PatchSortingWrapper>();
			}
 private void CGI_Cut()
 {
     // -- mark verteices on strokes --
     int n = mesh.VertexCount, label = 0;
     bool[] labeled = new bool[n];
     bool[] tag = new bool[n];
     foreach (int v in this.sourceVertices)
     {
         vnode[v].label = label;
         labeled[v] = true;
         tag[v] = true;
     }
     label = 1;
     foreach (int v in this.sinkVertices)
     {
         vnode[v].label = label;
         labeled[v] = true;
         tag[v] = true;
     }
     // -- push to priority queue --
     PriorityQueue iQue = new PriorityQueue();
     foreach (int v in this.sourceVertices)
     {
         foreach (int adj in mesh.AdjVV[v])
         {
             GraphNode node = vnode[adj];
             node.label = vnode[v].label;
             node.dis = Vrt_wij(v, adj);
             tag[adj] = true;
             iQue.Insert(node);
         }
     }
     foreach (int v in this.sinkVertices)
     {
         foreach (int adj in mesh.AdjVV[v])
         {
             GraphNode node = vnode[adj];
             node.label = vnode[v].label;
             node.dis = Vrt_wij(v, adj);
             tag[adj] = true;
             iQue.Insert(node);
         }
     }
     // -- region growing --
     while (!iQue.IsEmpty())
     {
         GraphNode node = iQue.DeleteMin() as GraphNode;
         int v = node.index;
         labeled[v] = true;
         foreach (int adj in mesh.AdjVV[v])
         {
             if (labeled[adj])  // -- already labeled --
             {
                 continue;
             }
             else
             {
                 double cost = Vrt_wij(v, adj);
                 GraphNode adjNode = vnode[adj];
                 adjNode.label = node.label;
                 if (tag[adj]) // -- already in the queue --
                 {
                     if (adjNode.dis > cost)
                     {
                         adjNode.dis = cost;
                         iQue.Update(adjNode);
                     }
                 }
                 else // -- a fresh vertex --
                 {
                     adjNode.dis = cost;
                     tag[adj] = true;
                     iQue.Insert(adjNode);
                 }
             }
         }
     }
     // -- convert to facets --
     List<int> risidual = new List<int>();
     for (int i = 0, j = 0; i < mesh.FaceCount; ++i, j+=3)
     {
         int c0 = mesh.FaceIndex[j];
         int c1 = mesh.FaceIndex[j+1];
         int c2 = mesh.FaceIndex[j+2];
         if (vnode[c0].label == vnode[c1].label &&
             vnode[c0].label == vnode[c2].label)
         {
             fnode[i].label = vnode[c0].label;
         }
         else
         {
             fnode[i].label = -1;
             risidual.Add(i);
         }
     }
     // -- deal with boundary faces --
     while (risidual.Count > 0)
     {
         List<int> vlist = new List<int>();
         vlist.AddRange(risidual);
         risidual.Clear();
         foreach (int f in vlist)
         {
             double min = double.MaxValue; int minid = -1;
             foreach (int adj in mesh.AdjFF[f])
             {
                 if (fnode[adj].label < 0) continue;
                 double c = Face_wij1(f, adj);
                 if (c < min)
                 {
                     min = c;
                     minid = adj;
                 }
             }
             if (minid != -1)
                 fnode[f].label = fnode[minid].label;
             else
                 risidual.Add(f);
         }
     }
     // -- patch the results --
     int index = this.patches.Count + 1;
     Patch p = new Patch(index);
     if (patchid == null) patchid = new byte[mesh.FaceCount];
     for (int i = 0; i < mesh.FaceCount; ++i)
     {
         if (fnode[i].label == 0)
         {
             patchid[i] = (byte)index;
             p.faces.Add(i);
         }
     }
     this.all_patches.Add(p);
 }
Esempio n. 58
0
 public Farm(Model model, Patch patch) : base(model, patch)
 {
 }
Esempio n. 59
0
        public void ImportMusic(Patch p, Random r)
        {
            List <Song> songs      = new List <Song>();
            List <Song> stageSongs = new List <Song>();

            string[] lines = Properties.Resources.music.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

            // Read songs from file, parse and add to list
            foreach (string line in lines)
            {
                if (line.StartsWith("#"))
                {
                    continue;                       // Ignore comment lines
                }
                string[] lineParts = line.Split(',');

                // Add song to list of songs
                Song song = new Song(lineParts[0], lineParts[1], lineParts[2]);
                songs.Add(song);

                // DEBUG ONLY: TEST ONE SONG AT A TIME
                //for (int i = 0; i < 10; i++)
                //{
                //    songs.Add(new Song(lineParts[0], lineParts[1], lineParts[2]));
                //}
            }
            debug.AppendLine($"{songs.Count} stage songs loaded.");

            // Create a shuffled list of songs
            bool      checkBytes = true;
            const int numTracks  = 11;

            while (checkBytes)
            {
                // Shuffle and get first 11 songs
                songs.Shuffle(r);
                stageSongs = songs.GetRange(0, numTracks);

                // Count bytes
                int totalBytes = 0;
                int i          = 0;
                foreach (Song song in stageSongs)
                {
                    totalBytes += song.SongHeader.Count;
                    totalBytes += song.SongData.Count;
                    i++;
                }

                // Break if within limit (Redo shuffle if over limit)
                // DEBUG DEBUG
                if (totalBytes <= StageSongsSize)
                {
                    checkBytes = false;
                    debug.AppendLine($"{numTracks} songs selected. {totalBytes} bytes used out of {StageSongsSize} limit.");
                }
                else
                {
                    debug.AppendLine($"{numTracks} songs selected. {totalBytes} bytes, greater than {StageSongsSize} limit. Reshuffled songs.");
                }
            }

            // Write the songs and song info
            int songStartRom = 0x030AE6;
            int TblPtrOffset = 0x30A60; // Start of address pairs which point to song locations

            for (int k = 0; k < stageSongs.Count; k++)
            {
                Song song = stageSongs[k];

                // Calculate start addresses from song lengths and write to address table
                int    addressTwoBytes = songStartRom - 0x30010 + 0x8000;
                string addressHex      = addressTwoBytes.ToString("X");
                song.SongStartPtr1stByte = byte.Parse(addressHex.Substring(0, 2), NumberStyles.HexNumber);
                song.SongStartPtr2ndByte = byte.Parse(addressHex.Substring(2, 2), NumberStyles.HexNumber);

                if (k >= 10) // Must use a different location for the 11th track; use Stage Select at 0x30A78
                {
                    p.Add(0x30A78, song.SongStartPtr2ndByte, $"Song {k} Pointer Offset Byte 1");
                    p.Add(0x30A79, song.SongStartPtr1stByte, $"Song {k} Pointer Offset Byte 2");

                    byte songIndex = 0x0C; // Wily 5 will play the song at the Stage Select address
                    p.Add(0x0381EC, songIndex, $"Wily 5 Song");
                    debug.AppendLine($"{Enum.GetName(typeof(EMusicID), (EMusicID)songIndex)} stage song: {song.SongName}, {song.OriginalStartAddress}");
                }
                else
                {
                    p.Add(TblPtrOffset++, song.SongStartPtr2ndByte, $"Song {k} Pointer Offset Byte 1");
                    p.Add(TblPtrOffset++, song.SongStartPtr1stByte, $"Song {k} Pointer Offset Byte 2");
                    debug.AppendLine($"{Enum.GetName(typeof(EMusicID), (EMusicID)k)} stage song: {song.SongName}, {song.OriginalStartAddress}");
                }

                // Header: Calculate 4 channel addresses and vibrato address
                byte origChannel1ByteSmall = song.SongHeader[1];
                byte origChannel1ByteLarge = song.SongHeader[2];
                int  origChannel1Offset    = origChannel1ByteSmall + (origChannel1ByteLarge * 256);
                int  relChannel1Offset     = origChannel1Offset - song.OriginalStartAddressInt;
                int  newChannel1Offset     = addressTwoBytes + relChannel1Offset;
                song.SongHeader[1] = (byte)(newChannel1Offset % 256);
                song.SongHeader[2] = (byte)(newChannel1Offset / 256);

                byte origChannel2ByteSmall = song.SongHeader[3];
                byte origChannel2ByteLarge = song.SongHeader[4];
                int  origChannel2Offset    = origChannel2ByteSmall + (origChannel2ByteLarge * 256);
                int  relChannel2Offset     = origChannel2Offset - song.OriginalStartAddressInt;
                int  newChannel2Offset     = addressTwoBytes + relChannel2Offset;
                song.SongHeader[3] = (byte)(newChannel2Offset % 256);
                song.SongHeader[4] = (byte)(newChannel2Offset / 256);

                byte origChannel3ByteSmall = song.SongHeader[5];
                byte origChannel3ByteLarge = song.SongHeader[6];
                int  origChannel3Offset    = origChannel3ByteSmall + (origChannel3ByteLarge * 256);
                int  relChannel3Offset     = origChannel3Offset - song.OriginalStartAddressInt;
                int  newChannel3Offset     = addressTwoBytes + relChannel3Offset;
                song.SongHeader[5] = (byte)(newChannel3Offset % 256);
                song.SongHeader[6] = (byte)(newChannel3Offset / 256);

                byte origChannel4ByteSmall = song.SongHeader[7];
                byte origChannel4ByteLarge = song.SongHeader[8];
                if (origChannel4ByteSmall > 0 || origChannel4ByteLarge > 0)
                {
                    int origChannel4Offset = origChannel4ByteSmall + (origChannel4ByteLarge * 256);
                    int relChannel4Offset  = origChannel4Offset - song.OriginalStartAddressInt;
                    int newChannel4Offset  = addressTwoBytes + relChannel4Offset;
                    song.SongHeader[7] = (byte)(newChannel4Offset % 256);
                    song.SongHeader[8] = (byte)(newChannel4Offset / 256);

                    if (relChannel4Offset > song.TotalLength || relChannel4Offset < 0)
                    {
                        debug.AppendLine($"WARNING: Song {song.SongName} channel 4 points to a shared location.");
                    }
                }

                byte origVibratoByteSmall = song.SongHeader[9];
                byte origVibratoByteLarge = song.SongHeader[10];
                int  origVibratoOffset    = origVibratoByteSmall + (origVibratoByteLarge * 256);
                int  relVibratoOffset     = origVibratoOffset - song.OriginalStartAddressInt;
                int  newVibratoOffset     = addressTwoBytes + relVibratoOffset;
                song.SongHeader[9]  = (byte)(newVibratoOffset % 256);
                song.SongHeader[10] = (byte)(newVibratoOffset / 256);

                if (relChannel1Offset > song.TotalLength || relChannel1Offset < 0)
                {
                    debug.AppendLine($"WARNING: Song {song.SongName} channel 1 points to a shared location.");
                }
                if (relChannel2Offset > song.TotalLength || relChannel2Offset < 0)
                {
                    debug.AppendLine($"WARNING: Song {song.SongName} channel 2 points to a shared location.");
                }
                if (relChannel3Offset > song.TotalLength || relChannel3Offset < 0)
                {
                    debug.AppendLine($"WARNING: Song {song.SongName} channel 3 points to a shared location.");
                }
                if (relVibratoOffset > song.TotalLength || relVibratoOffset < 0)
                {
                    debug.AppendLine($"WARNING: Song {song.SongName} vibrato points to a shared location.");
                }


                // Write song header
                foreach (byte b in song.SongHeader)
                {
                    p.Add(songStartRom, b, $"Song Header Byte for {song.SongName}");
                    songStartRom++;
                }

                // Song Data: Traverse stream and change loop pointers
                for (int i = 0; i < song.SongData.Count; i++)
                {
                    //Do not parse loop pointers for vibrato
                    //TODO: Check the length of the vibrato string, or even better, use separate lists for

                    //each channel!
                    if (i >= song.VibratoIndex && i < song.VibratoLength)
                    {
                        continue;
                    }

                    byte b0 = song.SongData[i];

                    // Bisqwit is awesome.
                    // http://www.romhacking.net/forum/index.php?topic=16383.0
                    // http://bisqwit.iki.fi/jutut/megamansource/mm2music.txt
                    switch (b0)
                    {
                    case 0x00:     // Two-byte encoding $00 n.  Song speed is set as n frames per tick.
                        i += 1;
                        break;

                    case 0x01:     // Two-byte encoding $01 n. Adjusts vibrato parameters by n. Affects all following notes.
                        i += 1;
                        break;

                    case 0x02:     // Two-byte encoding $02 n. Selects duty cycle settings. Valid values for n: $00,$40,$80,$C0. Only applicable for squarewave channels.
                        i += 1;
                        break;

                    case 0x03:     // Two-byte encoding $03 n. Selects volume and envelope settings. Value n is passed directly to the soundchip; Affects all following notes.
                        i += 1;
                        break;

                    case 0x04:     // Four-byte encoding $04 n w. Ends a loop. If n=0, loop is infinite. Otherwise the marked section plays for n+1 times. w is a 16-bit pointer to the beginning of the loop. Finite loops cannot be nested.
                        byte origLoopPtrSmall = song.SongData[i + 2];
                        byte origLoopPtrLarge = song.SongData[i + 3];

                        // Get the loop destination pointer by converting the two bytes to a 16-bit int
                        int origLoopOffset = origLoopPtrSmall + (origLoopPtrLarge * 256);
                        // Find index of destination of the loop with respect to the start of the song
                        int relLoopOffset = origLoopOffset - song.OriginalStartAddressInt;
                        // Make new loop destination with respect to the new starting location of this song
                        int newLoopOffset = addressTwoBytes + relLoopOffset;

                        // Put new hex bytes back into song data array
                        song.SongData[i + 2] = (byte)(newLoopOffset % 256);
                        song.SongData[i + 3] = (byte)(newLoopOffset / 256);

                        if (relLoopOffset > song.TotalLength || relLoopOffset < 0)
                        {
                            debug.AppendLine($"WARNING: Song {song.SongName} has external loop point.");
                        }

                        i += 3;
                        break;

                    case 0x05:     // Two-byte encoding $05 n. Sets note base to n. Value n is added to the note index for any notes (excluding pauses) played on this channel from now.
                        i += 1;
                        break;

                    case 0x06:     // One-byte encoding $06. Dotted note: The next note will be played 50% longer than otherwise, i.e. 3/2 of its stated duration.
                        break;

                    case 0x07:     // Three-byte encoding $07 n m. Sets volume curve settings. Byte n controls the attack, and byte m controls the decay. Affects all following notes.
                        i += 2;
                        break;

                    case 0x08:     // Two-byte encoding $08 n. Select vibrato entry n from the vibrato table referred to by the song header. Affects all following notes.
                        i += 1;
                        break;

                    case 0x09:     // One-byte encoding $09. Ends the track. Can be omitted if the track ends in an infinite loop instead.
                        break;

                    default:
                        // One - byte encoding $20 + n.Note delay(n = 0 - 7): Delays the next note by n ticks, without affecting its overall timing. (I.e.plays silence for the first n ticks of the note.)
                        // One - byte encoding $30.Triplet: The next note will be played at 2 / 3 of its stated duration.
                        // One - byte encoding: m * 0x20 + n.Play note(m = 2..7).If n = 0, plays pause. Otherwise plays note n(note base is added to n). The lowest note that can be played is C - 0(n + base = 0).Note or pause length is 2m−1 ticks, possibly altered by the triplet / dotted modifiers.The next event will be read only after this note/pause is done playing.
                        break;
                    }
                }

                // Write song data
                foreach (byte b in song.SongData)
                {
                    p.Add(songStartRom, b, $"Song Data Byte for {song.SongName}");
                    songStartRom++;
                }
            }

            // Play a random stage song during the credits
            Song creditsSong = stageSongs[r.Next(numTracks)];

            p.Add(0x30A88, creditsSong.SongStartPtr2ndByte, $"Song Credits 2 Byte 0 ({creditsSong.SongName})");
            p.Add(0x30A89, creditsSong.SongStartPtr1stByte, $"Song Credits 2 Byte 1 ({creditsSong.SongName})");
            debug.AppendLine($"Credits song: {creditsSong.SongName}");
        }
        public static string ProcessSubmodulePatch(GitModule module, string fileName, Patch patch)
        {
            string text   = patch?.Text;
            var    status = GitCommandHelpers.ParseSubmoduleStatus(text, module, fileName);

            if (status == null)
            {
                return("");
            }

            return(ProcessSubmoduleStatus(module, status));
        }