Exemplo n.º 1
0
        private IEnumerable <MaterialComponent> ProcessMaterialEntries(string[] materialEntries)
        {
            foreach (var textEntry in materialEntries.Where(s => !string.IsNullOrWhiteSpace(s)))
            {
                var entry = MaterialEntry.Parse(textEntry);

                if (!(entry.Amount > 0m))
                {
                    throw new ArgumentException($"Chybné množství {entry.Amount} - musí být větší než 0");
                }

                var material = m_materialRepository.GetMaterialByName(entry.MaterialName);
                if (material == null)
                {
                    throw new ArgumentException($"Materiál \"{entry.MaterialName}\" neexistuje");
                }

                var entryUnit = m_unitRepository.GetUnitBySymbol(entry.UnitName);
                if (entryUnit == null)
                {
                    throw new ArgumentException($"Neznámá jednotka \"{entry.UnitName}\"");
                }

                if (!m_unitConversionHelper.AreCompatible(material.NominalUnit.Id, entryUnit.Id))
                {
                    throw new ArgumentException($"Pro materiál \"{entry.MaterialName}\" nelze použít jednotku \"{entry.UnitName}\", protože není převoditelná na nominální jednotku materiálu \"{material.NominalUnit.Symbol}\"");
                }

                yield return(new MaterialComponent(entryUnit, material, entry.Amount, null));
            }
        }
Exemplo n.º 2
0
        public MaterialSection(AAudioBinaryFile file, BinaryReader binaryReader)
        {
            var sectionDeclaration = file.GetSectionDeclaration(Magic_Mtrl);

            MaterialSectionOffset = file.InnerFileStartOffset + sectionDeclaration.OffsetInInnerFile;
            Users = new List <MaterialUser>();

            EntryAddressesSize = binaryReader.ReadUInt16At(MaterialSectionOffset + 0x02);

            var entryCount = binaryReader.ReadUInt16At(MaterialSectionOffset + 0x04);

            Entries = new List <MaterialEntry>();
            for (int songEntryIndex = 0; songEntryIndex < entryCount; songEntryIndex++)
            {
                var positionOfOffsetFromMaterialSectionOffset = MaterialSectionOffset + 0x10 + songEntryIndex * 0x04;
                var localEntryOffset = binaryReader.ReadUInt32At(positionOfOffsetFromMaterialSectionOffset);
                if (songEntryIndex == 0)
                {
                    InnerFilePositionOfFirstTracks = sectionDeclaration.OffsetInInnerFile + localEntryOffset;
                }

                var entry = new MaterialEntry();
                entry.Read(binaryReader, songEntryIndex, MaterialSectionOffset, positionOfOffsetFromMaterialSectionOffset);
                Entries.Add(entry);
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Edit(int id, [Bind("WorkTaskId,EntryDate,Description,QuantityUsed,CostPerUnit,Id")] MaterialEntry materialEntry)
        {
            if (id != materialEntry.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(materialEntry);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MaterialEntryExists(materialEntry.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["WorkTaskId"] = new SelectList(_context.WorkTasks, "Id", "Id", materialEntry.WorkTaskId);
            return(View(materialEntry));
        }
Exemplo n.º 4
0
        public static Material Register(Material baseMaterial, Hash128 hash, System.Action <Material, Graphic> onModifyMaterial, Graphic graphic)
        {
            if (!hash.isValid)
            {
                return(null);
            }

            MaterialEntry entry;

            if (!materialMap.TryGetValue(hash, out entry))
            {
                entry = new MaterialEntry()
                {
                    material = new Material(baseMaterial)
                    {
                        hideFlags = HideFlags.HideAndDontSave,
                    },
                };

                onModifyMaterial(entry.material, graphic);
                materialMap.Add(hash, entry);
            }

            entry.referenceCount++;
            return(entry.material);
        }
Exemplo n.º 5
0
        public void SaveRecipe(RecipeEditRequest rq)
        {
            if (string.IsNullOrWhiteSpace(rq.ProducedAmountText))
            {
                throw new InvalidOperationException("Vyráběné množství je třeba zadat");
            }

            if (string.IsNullOrWhiteSpace(rq.RecipeName))
            {
                throw new InvalidOperationException("Název receptury musí být zadán");
            }

            var recipeMaterial = m_materialRepository.GetMaterialById(rq.MaterialId).Ensure();
            var recipeAmount   = MaterialEntry.Parse(rq.ProducedAmountText, true).GetAmount(m_unitRepository);

            var items = new List <RecipeComponentModel>();

            foreach (var srcItem in rq.Items)
            {
                if (string.IsNullOrWhiteSpace(srcItem.Text))
                {
                    continue;
                }

                try
                {
                    var entry = MaterialEntry.Parse(srcItem.Text);

                    var componentMaterial = m_materialRepository.GetMaterialByName(entry.MaterialName);
                    if (componentMaterial == null)
                    {
                        throw new InvalidOperationException($"Neznámý materiál \"{entry.MaterialName}\"");
                    }

                    if (componentMaterial.Id == recipeMaterial.Id)
                    {
                        throw new InvalidOperationException($"Receptura nesmí obsahovat ve složení svůj vlastní výsledný materiál \"{entry.MaterialName}\"");
                    }

                    var model = new RecipeComponentModel
                    {
                        IsTransformationSource = srcItem.IsTransformationSource,
                        SortOrder  = items.Count,
                        MaterialId = componentMaterial.Id,
                        Amount     = entry.GetAmount(m_unitRepository)
                    };

                    items.Add(model);
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException($"Chybné zadání složky \"{srcItem.Text}\": {e.Message}", e);
                }
            }

            m_recipes.SaveRecipe(recipeMaterial.Id, rq.RecipeId, rq.RecipeName.Trim(), rq.ProductionPrice, recipeAmount,
                                 rq.Note?.Trim(), items);
        }
Exemplo n.º 6
0
        private void WriteSsbh(SsbhFile file, bool isLastWrite)
        {
            foreach (var prop in file.GetType().GetProperties())
            {
                // Some more matl hacks.
                if (ParseTag.ShouldSkipProperty(prop))
                {
                    continue;
                }

                // Check for types that use offsets.
                if (prop.PropertyType == typeof(string))
                {
                    // TODO: Is this check necessary?
                    if (prop.GetValue(file) == null)
                    {
                        // Write placeholder relative offset.
                        Write(0L);
                        continue;
                    }
                    objectWriteQueue.Enqueue(new ObjectWriteInfo(prop.GetValue(file), (uint)Position));
                    // Write placeholder relative offset.
                    Write(0L);
                }
                else if (prop.PropertyType.IsArray)
                {
                    var array = (prop.GetValue(file) as Array);
                    if (array.Length > 0)
                    {
                        objectWriteQueue.Enqueue(new ObjectWriteInfo(array, (uint)Position));
                    }
                    else
                    {
                        objectWriteQueue.Enqueue(new ObjectWriteInfo(array));
                    }

                    // Write placeholder relative offset.
                    Write(0L);
                    Write((long)array.Length);
                }
                else if (prop.PropertyType == typeof(SsbhOffset))
                {
                    // HACK: for materials
                    var dataObject = file.GetType().GetProperty("DataObject").GetValue(file);
                    var matEntry   = new MaterialEntry(dataObject);
                    objectWriteQueue.Enqueue(new ObjectWriteInfo(matEntry, (uint)Position));
                    // Write placeholder relative offset.
                    Write(0L);
                }
                else
                {
                    WriteProperty(prop.GetValue(file), isLastWrite);
                }
            }
        }
Exemplo n.º 7
0
    public UnityEngine.Material MaterialForName(string name)
    {
        if (MaterialByName.ContainsKey(name))
        {
            var matEntry = MaterialByName[name];
            if (matEntry.Material != null)
            {
                ++matEntry.ReferenceCount;
                return(matEntry.Material);
            }
            if (matEntry.Loaded)
            {
                // TaskLoad() completed
                matEntry.GenerateMaterial();
                ++matEntry.ReferenceCount;
                return(matEntry.Material);
            }
            // TaskLoad in progress

            /*
             * if ((matEntry.SGIReadJob != null) && matEntry.SGIReadJob.IsCompleted)
             * {
             *  matEntry.SGIReadJob.Complete();
             *  matEntry.Width = matEntry.SGIReadJob.Width;
             *  matEntry.Height = matEntry.SGIReadJob.Height;
             *  matEntry.Pixels = matEntry.SGIReadJob.Pixels;
             *  matEntry.GenerateMaterial();
             ++matEntry.ReferenceCount;
             *  return matEntry.Material;
             * }
             */

            return(null);
        }
        var newMatEntry = new MaterialEntry();

        MaterialByName[name] = newMatEntry;

        /*
         * if (Path.GetExtension(name) == ".rgb")
         * {
         *  newMatEntry.SGIReadJob = new Cognitics.Unity.SGIReadJob() { Filename = name };
         *  newMatEntry.SGIReadJob.Execute();
         *  return null;
         * }
         */


        var token = newMatEntry.TaskLoadToken.Token;

        Task.Run(() => { newMatEntry.TaskLoad(name); }, token);

        return(null);
    }
        protected override void OnElementChanged(ElementChangedEventArgs <Entry> e)
        {
            base.OnElementChanged(e);

            if (e?.NewElement != null)
            {
                this.ChangeCursorColor();
                _materialEntry = this.Element as MaterialEntry;
                this.SetControl();
            }
        }
Exemplo n.º 9
0
        private IMaterialUnit ValidateAmountUnit(MaterialEntry nominalAmountEntry)
        {
            var unit = m_unitRepository.GetUnitBySymbol(nominalAmountEntry.UnitName);

            if (unit == null)
            {
                throw new ArgumentException($"Jednotka \"{nominalAmountEntry.UnitName}\" neexistuje");
            }

            return(unit);
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Create([Bind("WorkTaskId,EntryDate,Description,QuantityUsed,CostPerUnit,Id")] MaterialEntry materialEntry)
        {
            if (ModelState.IsValid)
            {
                _context.Add(materialEntry);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["WorkTaskId"] = new SelectList(_context.WorkTasks, "Id", "Id", materialEntry.WorkTaskId);
            return(View(materialEntry));
        }
Exemplo n.º 11
0
    public SolidLayeredBrush(Material[] materials)
    {
        m_material_entries = new MaterialEntry[materials.Length];
        for (int i = 0; i < materials.Length; ++i)
        {
            m_material_entries[i] = new MaterialEntry
            {
                m_material = materials[i],
            };
        }
        ;

        RefreshLookupTable();
    }
Exemplo n.º 12
0
 public mat1(EndianBinaryReader er)
 {
     long startpos = er.BaseStream.Position;
     Signature = er.ReadString(Encoding.ASCII, 4);
     if (Signature != "mat1") throw new SignatureNotCorrectException(Signature, "mat1", er.BaseStream.Position - 4);
     SectionSize = er.ReadUInt32();
     NrMaterials = er.ReadUInt32();
     MaterialEntryOffsets = er.ReadUInt32s((int)NrMaterials);
     Materials = new MaterialEntry[NrMaterials];
     for (int i = 0; i < NrMaterials; i++)
     {
         er.BaseStream.Position = startpos + MaterialEntryOffsets[i];
         Materials[i] = new MaterialEntry(er);
     }
     er.BaseStream.Position = startpos + SectionSize;
 }
Exemplo n.º 13
0
 public static void MaterialEntryWriter(string filename, MaterialEntry entrytowrite)
 {
     try
     {
         using (BinaryWriter bw = new BinaryWriter(File.Open(filename, FileMode.Create)))
         {
             bw.Write(entrytowrite.UncompressedData);
             bw.Close();
         }
     }
     catch (UnauthorizedAccessException)
     {
         MessageBox.Show("Unable to access the file. Maybe it's already in use by another proccess?", "Cannot write this file.");
         return;
     }
 }
Exemplo n.º 14
0
 public static void MaterialEntryWriter(string filename, MaterialEntry entrytowrite)
 {
     try
     {
         using (BinaryWriter bw = new BinaryWriter(File.Open(filename, FileMode.Create)))
         {
             bw.Write(entrytowrite.UncompressedData);
             bw.Close();
         }
     }
     catch (Exception ex)
     {
         ExceptionCatchAll(ex);
         return;
     }
 }
Exemplo n.º 15
0
            public Material(BinaryReaderX br)
            {
                entryCount = br.ReadInt32();

                offsetList = new int[entryCount];
                for (int i = 0; i < entryCount; i++)
                {
                    offsetList[i] = br.ReadInt32();
                }

                maters = new MaterialEntry[entryCount];
                for (int i = 0; i < entryCount; i++)
                {
                    br.BaseStream.Position = offsetList[i] - 8;
                    maters[i] = new MaterialEntry(br);
                }
            }
Exemplo n.º 16
0
    private void ReleaseMaterial(Material orig)
    {
        MaterialEntry value = null;

        if (maskMaterials.TryGetValue(orig, out value))
        {
            value.refCount--;
            if (value.refCount == 0)
            {
                maskMaterials.Remove(orig);
                Object.Destroy(value.material);
            }
        }
        else
        {
            Object.Destroy(orig);
        }
    }
Exemplo n.º 17
0
    public Material GetMaterial(Material sourceMaterial)
    {
        InitAssets();

        MaterialEntry entry = null;

        foreach (MaterialEntry cur in materials)
        {
            if (cur.sourceMaterial == sourceMaterial)
            {
                entry = cur;
                break;
            }
        }

        if (entry == null)
        {
            entry = new MaterialEntry();
            entry.sourceMaterial = sourceMaterial;
            entry.material       = new Material(Shader.Find("Standard"));
            entry.material.name  = "zzz " + sourceMaterial.name;
            #if UNITY_EDITOR
            AssetDatabase.AddObjectToAsset(entry.material, AssetDatabase.GetAssetPath(this));
            materials.Add(entry);
            EditorUtility.SetDirty(this);
            #endif
        }

        Material material = entry.material;

        if (UpdateMateral)
        {
            material.SetColor("_Color", sourceMaterial.GetColor("_Color"));
            material.SetColor("_EmissionColor", sourceMaterial.GetColor("_Emission"));
            material.SetFloat("_Metallic", sourceMaterial.GetFloat("_Metallic"));
            material.SetFloat("_Glossiness", sourceMaterial.GetFloat("_Smoothness"));
            material.SetTexture("_MainTex", albedoTexture);
            material.SetTexture("_BumpMap", normalTexture);
            // material.SetTexture("_ParallaxMap", heighmapTexture);
            material.SetFloat("_BumpScale", 1.0f);
            material.name = "zzz Cube Material";
        }
        return(material);
    }
Exemplo n.º 18
0
        public RecipeInfoWithItems LoadRecipe(int recipeId)
        {
            var entity = m_database.SelectFrom <IRecipe>().Join(r => r.Components).Join(r => r.ProducedMaterial)
                         .Join(r => r.Components.Each().Material)
                         .Where(r => r.ProjectId == m_session.Project.Id && r.Id == recipeId).Execute().FirstOrDefault();

            if (entity == null)
            {
                return(null);
            }

            var model = new RecipeInfoWithItems()
            {
                IsActive        = entity.DeleteDateTime == null && entity.DeleteUserId == null,
                MaterialId      = entity.ProducedMaterialId,
                MaterialName    = entity.ProducedMaterial.Name,
                RecipeId        = entity.Id,
                RecipeName      = entity.RecipeName,
                Amount          = entity.RecipeProducedAmount,
                ProductionPrice = entity.ProductionPricePerUnit ?? 0,
                AmountUnit      = m_unitRepository.GetUnit(entity.ProducedAmountUnitId).Symbol,
                Note            = entity.Note
            };

            foreach (var c in entity.Components.OrderBy(c => c.SortOrder))
            {
                var me = new MaterialEntry()
                {
                    Amount       = c.Amount,
                    MaterialName = c.Material.Name,
                    UnitName     = m_unitRepository.GetUnit(c.UnitId).Symbol
                };

                model.Items.Add(new RecipeItem()
                {
                    IsTransformationSource = c.IsTransformationInput,
                    Text    = me.ToString(),
                    IsValid = true
                });
            }

            return(model);
        }
Exemplo n.º 19
0
        public RecipeEditRequest GetRecipe(int materialId, int recipeId)
        {
            var material = m_materialRepository.GetMaterialById(materialId).Ensure();
            var entity   = recipeId < 1 ? null : m_recipes.LoadRecipe(recipeId).Ensure();

            var model = new RecipeEditRequest
            {
                MaterialId   = material.Id,
                MaterialName = material.Name,
                Amount       = material.NominalAmount,
                IsActive     = true,
                RecipeName   = "Výroba",
                AmountUnit   = material.NominalUnit.Symbol
            };

            if (entity != null)
            {
                if (entity.MaterialId != model.MaterialId)
                {
                    throw new InvalidOperationException("Nelze zmenit material existujici receptury");
                }

                model.Amount          = entity.Amount;
                model.AmountUnit      = entity.AmountUnit;
                model.RecipeId        = entity.RecipeId;
                model.IsActive        = entity.IsActive;
                model.Note            = entity.Note;
                model.RecipeName      = entity.RecipeName;
                model.ProductionPrice = entity.ProductionPrice;

                model.Items.AddRange(entity.Items);
            }

            var mentry = new MaterialEntry()
            {
                Amount   = model.Amount,
                UnitName = model.AmountUnit
            };

            model.ProducedAmountText = mentry.ToString();

            return(model);
        }
Exemplo n.º 20
0
        public mat1(EndianBinaryReader er)
        {
            long startpos = er.BaseStream.Position;

            Signature = er.ReadString(Encoding.ASCII, 4);
            if (Signature != "mat1")
            {
                throw new SignatureNotCorrectException(Signature, "mat1", er.BaseStream.Position - 4);
            }
            SectionSize          = er.ReadUInt32();
            NrMaterials          = er.ReadUInt32();
            MaterialEntryOffsets = er.ReadUInt32s((int)NrMaterials);
            Materials            = new MaterialEntry[NrMaterials];
            for (int i = 0; i < NrMaterials; i++)
            {
                er.BaseStream.Position = startpos + MaterialEntryOffsets[i];
                Materials[i]           = new MaterialEntry(er);
            }
            er.BaseStream.Position = startpos + SectionSize;
        }
Exemplo n.º 21
0
        public void SetThreshold(int materialId, string thresholdText)
        {
            if (string.IsNullOrEmpty(thresholdText))
            {
                m_materialThresholdRepository.DeleteThreshold(materialId);
                return;
            }

            var thresholdEntry = MaterialEntry.Parse(thresholdText, true);

            var thresholdUnit = m_unitRepository.GetUnitBySymbol(thresholdEntry.UnitName);

            if (thresholdUnit == null)
            {
                throw new InvalidOperationException($"Neznámý symbol jednotky \"{thresholdEntry.UnitName}\"");
            }

            m_materialThresholdRepository.SaveThreshold(materialId,
                                                        thresholdEntry.Amount,
                                                        thresholdUnit.Id);
        }
    public static Material AddQueueMaterial(Material mat, int queue)
    {
        for (int i = 0; i < materialList.Count; i++)
        {
            var item = materialList[i];
            if (item.material == mat && item.queue == queue)
            {
                item.count++;
                return(item.queueMaterial);
            }
        }

        var newItem = new MaterialEntry();

        newItem.material                  = mat;
        newItem.queue                     = queue;
        newItem.queueMaterial             = new Material(mat);
        newItem.queueMaterial.renderQueue = queue;
        newItem.count                     = 1;
        materialList.Add(newItem);

        return(newItem.queueMaterial);
    }
Exemplo n.º 23
0
 private Material GetMaterial(Material orig, Shader shader)
 {
     //IL_0013: Unknown result type (might be due to invalid IL or missing references)
     //IL_0018: Expected O, but got Unknown
     //IL_001b: Unknown result type (might be due to invalid IL or missing references)
     //IL_002a: Expected O, but got Unknown
     if (!maskMaterials.TryGetValue(orig, out MaterialEntry value))
     {
         Material val = new Material(shader);
         try
         {
             val.set_mainTexture(orig.get_mainTexture());
         }
         catch (UnassignedReferenceException val2)
         {
             UnassignedReferenceException val3 = val2;
         }
         val.SetFloat("_Cutoff", cutoff);
         value = new MaterialEntry(val);
         maskMaterials.Add(orig, value);
     }
     value.refCount++;
     return(value.material);
 }
        private void Searchbar_TextChanged(object sender, EventArgs e)
        {
            MaterialEntry searchbar = (MaterialEntry)sender;

            _viewModel.searchByName(searchbar.Text);
        }
Exemplo n.º 25
0
 public App()
 {
     InitializeComponent();
     MaterialEntry.Init();
     MainPage = new NavigationPage(new ExampleApp.MainPage());
 }
            private void ParseLibMaterials()
            {
                MaterialEntry mat;
                while (_reader.BeginElement())
                {
                    if (_reader.Name.Equals("material", true))
                    {
                        mat = new MaterialEntry();
                        while (_reader.ReadAttribute())
                        {
                            if (_reader.Name.Equals("id", true))
                                mat._id = (string)_reader.Value;
                            else if (_reader.Name.Equals("name", true))
                                mat._name = (string)_reader.Value;
                        }

                        while (_reader.BeginElement())
                        {
                            if (_reader.Name.Equals("instance_effect", true))
                                while (_reader.ReadAttribute())
                                    if (_reader.Name.Equals("url", true))
                                        mat._effect = _reader.Value[0] == '#' ? (string)(_reader.Value + 1) : (string)_reader.Value;

                            _reader.EndElement();
                        }

                        _materials.Add(mat);
                    }

                    _reader.EndElement();
                }
            }
Exemplo n.º 27
0
        private void WriteSsbhFile(SsbhFile file)
        {
            foreach (var prop in file.GetType().GetProperties())
            {
                if (Skip(file, prop))
                {
                    continue;
                }

                if (prop.PropertyType == typeof(string))
                {
                    if (prop.GetValue(file) == null)
                    {
                        Write((long)0);
                        continue;
                    }
                    objectQueue.AddLast(prop.GetValue(file));
                    objectOffset.Add((uint)Position, prop.GetValue(file));
                    Write((long)0);
                }
                else if (prop.PropertyType.IsArray)
                {
                    var  array  = (prop.GetValue(file) as Array);
                    bool inline = false;
                    if (prop.GetCustomAttribute(typeof(ParseTag)) != null)
                    {
                        inline = ((ParseTag)prop.GetCustomAttribute(typeof(ParseTag))).InLine;
                    }

                    if (!inline)
                    {
                        if (array.Length > 0)
                        {
                            objectOffset.Add((uint)Position, array);
                        }
                        objectQueue.AddLast(array);
                        Write((long)0);
                        Write((long)array.Length);
                    }
                    else
                    {
                        // inline array
                        foreach (object o in array)
                        {
                            WriteProperty(o);
                        }
                    }
                }
                else if (prop.PropertyType == typeof(SsbhOffset))
                {
                    // HACK: for materials
                    var dataObject = file.GetType().GetProperty("DataObject").GetValue(file);
                    var matentry   = new MaterialEntry(dataObject);
                    objectOffset.Add((uint)Position, matentry);
                    objectQueue.AddLast(matentry);
                    Write((long)0);
                }
                else
                {
                    WriteProperty(prop.GetValue(file));
                }
            }


            // TODO: Post Write is only used for materials.
            file.PostWrite(this);
        }
Exemplo n.º 28
0
        private void btnROK_Click(object sender, EventArgs e)
        {
            string newname = txtRename.Text;

            //Checks for blank/null names.
            if (newname == null || newname == "")
            {
                MessageBox.Show("This must have a name and cannot be null!", "Ahem");
                return;
            }

            if (OriginalName == txtRename.Text)
            {
                DialogResult = DialogResult.OK;
                Hide();
                return;
            }

            //Checks for existing name in directory.
            foreach (TreeNode c in node_.Parent.Nodes)
            {
                ArcEntry ae = new ArcEntry();
                ArcEntry se = new ArcEntry();
                if (node_.Tag is ArcEntry)
                {
                    ae = node_.Tag as ArcEntry;
                }

                if (c.Tag is ArcEntry)
                {
                    se = c.Tag as ArcEntry;
                }

                /*
                 * //Checks the nodes in the same directory for existing name AND extension and will stop if there's a node with the same type in the same directory.
                 * if (c.Text == txtRename.Text && c.Tag as string != "MaterialChildTexture")
                 * {
                 *  if (ae != se && ae.FileExt == se.FileExt)
                 *  {
                 *      MessageBox.Show("That name already exists on a resource of the same type on the same level. \nTry a different name.", "Oh Boy");
                 *      return;
                 *  }
                 * }
                 */
            }

            //Changes the name to what was chosen. Should reflect on the Treeview.
            treeview.SelectedNode.Text = txtRename.Text;
            treeview.SelectedNode.Name = txtRename.Text;

            //Ensures the TrueName gets change so it gets reflected in the save.
            ArcEntry aey = new ArcEntry();

            if (treeview.SelectedNode.Tag is ArcEntry)
            {
                aey          = treeview.SelectedNode.Tag as ArcEntry;
                aey.TrueName = txtRename.Text;
            }
            else if (treeview.SelectedNode.Tag != null && treeview.SelectedNode.Tag as string == "Folder")
            {
            }
            else if (treeview.SelectedNode.Tag != null && treeview.SelectedNode.Tag is MaterialTextureReference)
            {
                //Goes about accessing and updating the data inside the material in a roundabout way.
                MaterialTextureReference texref = treeview.SelectedNode.Tag as MaterialTextureReference;
                MaterialEntry            mentry = new MaterialEntry();
                TreeNode parent = treeview.SelectedNode.Parent;
                TreeNode child  = treeview.SelectedNode;
                treeview.SelectedNode = parent;
                parent = treeview.SelectedNode.Parent;
                treeview.SelectedNode = parent;
                mentry = treeview.SelectedNode.Tag as MaterialEntry;
                if (mentry != null)
                {
                    //Now for the actual file update.
                    List <byte> NameToInject = new List <byte>();
                    NameToInject.AddRange(Encoding.ASCII.GetBytes(txtRename.Text));
                    int OffsetToUse;
                    OffsetToUse = 64 + (88 * (texref.Index - 1));
                    byte[] NewName = new byte[64];
                    Array.Copy(NameToInject.ToArray(), 0, NewName, 0, NameToInject.ToArray().Length);
                    Array.Copy(NewName, 0, mentry.UncompressedData, OffsetToUse, NewName.Length);
                    mentry.CompressedData     = Zlibber.Compressor(mentry.UncompressedData);
                    treeview.SelectedNode.Tag = mentry;
                }
                treeview.SelectedNode = child;
            }

            Mainfrm.OpenFileModified = true;

            //Closes form with changes made above.
            DialogResult = DialogResult.OK;
            Hide();
        }
Exemplo n.º 29
0
        public static ArcFile LoadArc(TreeView tree, string filename, List<string> foldernames, bool IsBigEndian, bool Verifier = false,Type filetype = null, int arcsize = -1)
        {
            
            ArcFile arcfile = new ArcFile();
            byte[] Bytes = File.ReadAllBytes(filename);

            using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
            {

                arcsize = Bytes.Length;
                int Totalsize = arcsize;
                arcfile.FileLength = arcsize;
                arcfile.Tempname = filename;

                br.BaseStream.Position = 0;
                byte[] HeaderMagic = br.ReadBytes(4);
                //Checks file signature/Endianess.
                if (HeaderMagic[0] == 0x00 && HeaderMagic[1] == 0x43 && HeaderMagic[2] == 0x52 && HeaderMagic[3] == 0x41)
                {
                    /*
                    MessageBox.Show("This .arc file is not in the kind of endian I can deal with right now, so these will be in read only.\nDon't expect save to work... or for the program to be stable", "Just so you know....");

                    IsBigEndian = true;
                    arcfile.HeaderMagic = HeaderMagic;
                    arcfile.MaterialCount = 0;
                    arcfile.arctable = new List<ArcEntry>();
                    arcfile.arcfiles = new List<object>();
                    arcfile.FileList = new List<string>();
                    arcfile.TypeHashes = new List<string>();

                    br.BaseStream.Position = 4;
                    var data = br.ReadBytes(2);
                    Array.Reverse(data);
                    arcfile.UnknownFlag = br.ReadByte();



                    return arcfile;

                    
                     
                    */

                    MessageBox.Show("This .arc file is not in the kind of endian I can deal with right now. Closing.", "Just so you know....");
                    br.Close();
                    return null;

                }

                if (HeaderMagic[0] != 0x41 && HeaderMagic[1] != 0x52 && HeaderMagic[2] != 0x43 && HeaderMagic[3] != 0x00)
                {
                    MessageBox.Show("This .arc file is either not the correct kind or is not properly extracted, so I'm closing it.", "Oh dear");
                    br.Close();
                    return null;
                }

                #region PC Arc
                IsBigEndian = false;
                arcfile.HeaderMagic = HeaderMagic;
                arcfile.MaterialCount = 0;
                arcfile.arctable = new List<ArcEntry>();
                arcfile.arcfiles = new List<object>();
                arcfile.FileList = new List<string>();
                arcfile.TypeHashes = new List<string>();

                br.BaseStream.Position = 4;
                arcfile.UnknownFlag = br.ReadByte();

                br.BaseStream.Position = 6;
                arcfile.FileCount = BitConverter.ToInt16((br.ReadBytes(2)), 0);
                arcfile.Version = arcfile.UnknownFlag;

                List<String> filenames = new List<String>();

                List<string> subdref = new List<string>();
                foldernames = subdref;


                //byte[] BytesTemp;
                //BytesTemp = new byte[] { };
                List<byte> BytesTemp = new List<byte>();
                byte[] HTTemp = new byte[] { };
                int j = 8;
                int l = 64;
                int m = 80;
                int n = 4;

                //Iterates through the header/first part of the arc to get all the filenames and occupy the filename list.
                for (int i = 0; i < arcfile.FileCount; i++)
                {
                    BytesTemp.Clear();
                    BytesTemp.TrimExcess();
                    j = 8 + (m * i);
                    //Copies the specified range to isolate the bytes containing a filename.
                    br.BaseStream.Position = j;
                    BytesTemp.AddRange(br.ReadBytes(l));
                    BytesTemp.RemoveAll(ByteUtilitarian.IsZeroByte);
                    filenames.Add(ByteUtilitarian.BytesToStringL(BytesTemp));
                    //For The Typehashes.
                    n = 72 + (m * i);

                    br.BaseStream.Position = n;
                    HTTemp = br.ReadBytes(4);
                    Array.Reverse(HTTemp);
                    arcfile.TypeHashes.Add(ByteUtilitarian.HashBytesToString(HTTemp));

                }

                //Fills in each file as an ArcEntry or TextureEntry as needed. 
                j = 8;
                int IDCounter = 0;
                for (int i = 0; i < arcfile.FileCount; i++)
                {
                    j = 8 + (80 * i);
                    switch (arcfile.TypeHashes[i])
                    {
                        //Texture Files.
                        case "241F5DEB":
                            TextureEntry newtexen = TextureEntry.FillTexEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(newtexen);
                            arcfile.FileList.Add(newtexen.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;

                        //Resource Path Lists.
                        case "357EF6D4":
                            ResourcePathListEntry newplen = ResourcePathListEntry.FillRPLEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(newplen);
                            arcfile.FileList.Add(newplen.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;


                        //Materials. Incomplete.                        
                        case "2749C8A8":
                            MaterialEntry Maten = MaterialEntry.FillMatEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(Maten);
                            arcfile.FileList.Add(Maten.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            arcfile.MaterialCount++;
                            break;
                            

                        //LMT Files.
                        case "76820D81":
                            LMTEntry LMTen = LMTEntry.FillLMTEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(LMTen);
                            arcfile.FileList.Add(LMTen.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;
                        
                        //MSD Files.
                        case "5B55F5B1":
                            MSDEntry newmsden = MSDEntry.FillMSDEntry(filename, foldernames, tree, br, Bytes, j, IDCounter);
                            arcfile.arcfiles.Add(newmsden);
                            arcfile.FileList.Add(newmsden.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;

                        //CST Files.
                        case "326F732E":
                            ChainListEntry CSTen = ChainListEntry.FillCSTEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(CSTen);
                            arcfile.FileList.Add(CSTen.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;

                        //CHN Files.
                        case "3E363245":
                            ChainEntry CHNen = ChainEntry.FillChainEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(CHNen);
                            arcfile.FileList.Add(CHNen.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;

                        //CCL Files.
                        case "0026E7FF":
                            ChainCollisionEntry CCLen = ChainCollisionEntry.FillChainCollEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(CCLen);
                            arcfile.FileList.Add(CCLen.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;

                        //MOD Files.
                        case "58A15856":
                            ModelEntry MODen = ModelEntry.FillModelEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(MODen);
                            arcfile.FileList.Add(MODen.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;

                        case "361EA2A5":
                            MissionEntry MISen = MissionEntry.FillMissionEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(MISen);
                            arcfile.FileList.Add(MISen.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;

                        //Gem Files.
                        case "448BBDD4":
                           GemEntry GEMen = GemEntry.FillGEMEntry(filename, foldernames, tree, br, j, IDCounter);
                           arcfile.arcfiles.Add(GEMen);
                           arcfile.FileList.Add(GEMen.EntryName);
                           foldernames.Clear();
                           IDCounter++;
                           break;

                        //EFL Files.
                        case "6D5AE854":
                           EffectListEntry EFLen = EffectListEntry.FillEFLEntry(filename, foldernames, tree, br, j, IDCounter);
                           arcfile.arcfiles.Add(EFLen);
                           arcfile.FileList.Add(EFLen.EntryName);
                           foldernames.Clear();
                           IDCounter++;
                           break;
                        

                        //New Formats go like this!   
                        /*
                        case "********":
                           *****Entry ****en = *****Entry.Fill*****Entry(filename, foldernames, tree, br, j, IDCounter);
                           arcfile.arcfiles.Add(*****en);
                           arcfile.FileList.Add(*****.EntryName);
                           foldernames.Clear();
                           IDCounter++;
                           break;
                        */

                        default:
                            //Everything not listed above.
                            ArcEntry newentry = ArcEntry.FillArcEntry(filename, foldernames, tree, br, j, IDCounter);
                            arcfile.arcfiles.Add(newentry);
                            arcfile.FileList.Add(newentry.EntryName);
                            foldernames.Clear();
                            IDCounter++;
                            break;
                    }
                }

                arcfile._FileAmount = Convert.ToUInt16(IDCounter);                

                br.Close();
            }

            return arcfile;

            #endregion

        }
Exemplo n.º 30
0
    /// Material::probe() looks up the current position's material configuration in
    /// the material hash table. It returns a pointer to the Entry if the position
    /// is found. Otherwise a new Entry is computed and stored there, so we don't
    /// have to recompute all when the same material configuration occurs again.
    internal static MaterialEntry probe(Position pos)
    {
        var key = pos.material_key();
        MaterialEntry e;
        if (!pos.this_thread().materialTable.TryGetValue(key, out e))
        {
            e = new MaterialEntry();
            pos.this_thread().materialTable.Add(key, e);
        }
        else if (e.key == key)
        {
            return e;
        }

        e.reset();

        e.key = key;
        e.factor[Color.WHITE] = e.factor[Color.BLACK] = (ushort) ScaleFactor.SCALE_FACTOR_NORMAL;
        e.gamePhase = pos.game_phase();

        // Let's look if we have a specialized evaluation function for this particular
        // material configuration. Firstly we look for a fixed configuration one, then
        // for a generic one if the previous search failed.
        if ((e.evaluationFunction = pos.this_thread().endgames.probeEndgameValue(key)) != null)
        {
            return e;
        }

        foreach (var c in Color.AllColors)
        {
            if (is_KXK(pos, c))
            {
                e.evaluationFunction = EvaluateKXK[c];
                return e;
            }
        }

        // OK, we didn't find any special evaluation function for the current material
        // configuration. Is there a suitable specialized scaling function?
        EndgameScaleFactor sf;

        if ((sf = pos.this_thread().endgames.probeEndgameScaleFactor(key)) != null)
        {
            e.scalingFunction[sf.strong_side()] = sf; // Only strong color assigned
            return e;
        }

        // We didn't find any specialized scaling function, so fall back on generic
        // ones that refer to more than one material distribution. Note that in this
        // case we don't return after setting the function.
        foreach (var c in Color.AllColors)
        {
            if (is_KBPsKs(pos, c))
            {
                e.scalingFunction[c] = ScaleKBPsK[c];
            }
            else if (is_KQKRPs(pos, c))
            {
                e.scalingFunction[c] = ScaleKQKRPs[c];
            }
        }

        var npm_w = pos.non_pawn_material(Color.WHITE);
        var npm_b = pos.non_pawn_material(Color.BLACK);

        if (npm_w + npm_b == Value.VALUE_ZERO && (pos.pieces_Pt(PieceType.PAWN) != 0)) // Only pawns on the board
        {
            if (pos.count(PieceType.PAWN, Color.BLACK) == 0)
            {
                Debug.Assert(pos.count(PieceType.PAWN, Color.WHITE) >= 2);

                e.scalingFunction[Color.WHITE] = ScaleKPsK[Color.WHITE];
            }
            else if (pos.count(PieceType.PAWN, Color.WHITE) == 0)
            {
                Debug.Assert(pos.count(PieceType.PAWN, Color.BLACK) >= 2);

                e.scalingFunction[Color.BLACK] = ScaleKPsK[Color.BLACK];
            }
            else if (pos.count(PieceType.PAWN, Color.WHITE) == 1 && pos.count(PieceType.PAWN, Color.BLACK) == 1)
            {
                // This is a special case because we set scaling functions
                // for both colors instead of only one.
                e.scalingFunction[Color.WHITE] = ScaleKPKP[Color.WHITE];
                e.scalingFunction[Color.BLACK] = ScaleKPKP[Color.BLACK];
            }
        }

        // Zero or just one pawn makes it difficult to win, even with a small material
        // advantage. This catches some trivial draws like KK, KBK and KNK and gives a
        // drawish scale factor for cases such as KRKBP and KmmKm (except for KBBKN).
        if (pos.count(PieceType.PAWN, Color.WHITE) == 0 && npm_w - npm_b <= Value.BishopValueMg)
        {
            e.factor[Color.WHITE] =
                (ushort)
                    (npm_w < Value.RookValueMg
                        ? (ushort) ScaleFactor.SCALE_FACTOR_DRAW
                        : npm_b <= Value.BishopValueMg ? 4 : 14);
        }

        if (pos.count(PieceType.PAWN, Color.BLACK) == 0 && npm_b - npm_w <= Value.BishopValueMg)
        {
            e.factor[Color.BLACK] =
                (ushort)
                    (npm_b < Value.RookValueMg
                        ? (ushort) ScaleFactor.SCALE_FACTOR_DRAW
                        : npm_w <= Value.BishopValueMg ? 4 : 14);
        }

        if (pos.count(PieceType.PAWN, Color.WHITE) == 1 && npm_w - npm_b <= Value.BishopValueMg)
        {
            e.factor[Color.WHITE] = (ushort) ScaleFactor.SCALE_FACTOR_ONEPAWN;
        }

        if (pos.count(PieceType.PAWN, Color.BLACK) == 1 && npm_b - npm_w <= Value.BishopValueMg)
        {
            e.factor[Color.BLACK] = (ushort) ScaleFactor.SCALE_FACTOR_ONEPAWN;
        }

        // Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
        // for the bishop pair "extended piece", which allows us to be more flexible
        // in defining bishop pair bonuses.
        int[][] PieceCount =
        {
            new[]
            {
                pos.count(PieceType.BISHOP, Color.WHITE) > 1 ? 1 : 0,
                pos.count(PieceType.PAWN, Color.WHITE), pos.count(PieceType.KNIGHT, Color.WHITE),
                pos.count(PieceType.BISHOP, Color.WHITE), pos.count(PieceType.ROOK, Color.WHITE),
                pos.count(PieceType.QUEEN, Color.WHITE)
            },
            new[]
            {
                pos.count(PieceType.BISHOP, Color.BLACK) > 1 ? 1 : 0,
                pos.count(PieceType.PAWN, Color.BLACK), pos.count(PieceType.KNIGHT, Color.BLACK),
                pos.count(PieceType.BISHOP, Color.BLACK), pos.count(PieceType.ROOK, Color.BLACK),
                pos.count(PieceType.QUEEN, Color.BLACK)
            }
        };

        e.value = (short) ((imbalance(Color.WHITE, PieceCount) - imbalance(Color.BLACK, PieceCount))/16);
        return e;
    }
Exemplo n.º 31
0
        private void btnReplaceReplace_Click(object sender, EventArgs e)
        {
            if (AllFiles == true)
            {
                //Checks All filenames for searched term. Gets to the parent node, checks all the children nodes, their tags, filenames, etc. for the term.

                //Goes to top node to begin iteration.
                TreeNode tn = Mainfrm.FindRootNode(Mainfrm.TreeSource.SelectedNode);
                Mainfrm.TreeSource.SelectedNode = tn;

                List <TreeNode> Nodes = new List <TreeNode>();
                Mainfrm.AddChildren(Nodes, Mainfrm.TreeSource.SelectedNode);

                Mainfrm.TreeSource.BeginUpdate();

                int RenameCount = 0;

                foreach (TreeNode tno in Nodes)
                {
                    //Gets the node as a ArcEntryWrapper to allow access to all the variables and data.
                    ArcEntryWrapper awrapper = tno as ArcEntryWrapper;

                    if (awrapper != null)
                    {
                        if (awrapper.Tag as MaterialTextureReference == null || awrapper.Tag as LMTM3AEntry == null || awrapper.Tag as ModelBoneEntry == null ||
                            awrapper.Tag as MaterialMaterialEntry == null || awrapper.Tag as ModelGroupEntry == null || awrapper.Tag as Mission == null ||
                            awrapper.Tag as EffectNode == null)
                        {
                            {
                                if (awrapper.Tag as string != null)
                                {
                                    //Replaces the Term in the folder.
                                    string FolderName = awrapper.Tag as string;
                                    FolderName = FolderName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    tno.Text   = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    tno.Name   = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    RenameCount++;
                                }
                                else
                                {
                                    //Goes through the treenode to replace all the names of the node.
                                    ArcEntry              enty     = new ArcEntry();
                                    TextureEntry          tenty    = new TextureEntry();
                                    ResourcePathListEntry lrpenty  = new ResourcePathListEntry();
                                    MSDEntry              msdenty  = new MSDEntry();
                                    MaterialEntry         matent   = new MaterialEntry();
                                    LMTEntry              lmtenty  = new LMTEntry();
                                    ChainListEntry        cstenty  = new ChainListEntry();
                                    ChainEntry            chnenty  = new ChainEntry();
                                    ChainCollisionEntry   cclentry = new ChainCollisionEntry();
                                    ModelEntry            mdlentry = new ModelEntry();
                                    MissionEntry          misenty  = new MissionEntry();
                                    GemEntry              gementy  = new GemEntry();
                                    EffectListEntry       eflenty  = new EffectListEntry();

                                    if (tno.Tag as ArcEntry != null)
                                    {
                                        enty           = tno.Tag as ArcEntry;
                                        enty.EntryName = enty.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        enty.TrueName  = enty.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        enty.FileName  = enty.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag        = enty;
                                        tno.Text       = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name       = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as TextureEntry != null)
                                    {
                                        tenty           = tno.Tag as TextureEntry;
                                        tenty.EntryName = tenty.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tenty.TrueName  = tenty.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tenty.FileName  = tenty.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag         = tenty;
                                        tno.Text        = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name        = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as ResourcePathListEntry != null)
                                    {
                                        lrpenty           = tno.Tag as ResourcePathListEntry;
                                        lrpenty.EntryName = lrpenty.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        lrpenty.TrueName  = lrpenty.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        lrpenty.FileName  = lrpenty.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag           = lrpenty;
                                        tno.Text          = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name          = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as LMTEntry != null)
                                    {
                                        lmtenty           = tno.Tag as LMTEntry;
                                        lmtenty.EntryName = lmtenty.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        lmtenty.TrueName  = lmtenty.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        lmtenty.FileName  = lmtenty.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag           = lmtenty;
                                        tno.Text          = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name          = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as MaterialEntry != null)
                                    {
                                        matent           = tno.Tag as MaterialEntry;
                                        matent.EntryName = matent.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        matent.TrueName  = matent.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        matent.FileName  = matent.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag          = matent;
                                        tno.Text         = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name         = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as MSDEntry != null)
                                    {
                                        msdenty           = tno.Tag as MSDEntry;
                                        msdenty.EntryName = msdenty.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        msdenty.TrueName  = msdenty.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        msdenty.FileName  = msdenty.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag           = msdenty;
                                        tno.Text          = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name          = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as ChainListEntry != null)
                                    {
                                        cstenty           = tno.Tag as ChainListEntry;
                                        cstenty.EntryName = cstenty.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        cstenty.TrueName  = cstenty.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        cstenty.FileName  = cstenty.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag           = cstenty;
                                        tno.Text          = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name          = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as ChainEntry != null)
                                    {
                                        chnenty           = tno.Tag as ChainEntry;
                                        chnenty.EntryName = chnenty.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        chnenty.TrueName  = chnenty.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        chnenty.FileName  = chnenty.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag           = chnenty;
                                        tno.Text          = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name          = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as ChainCollisionEntry != null)
                                    {
                                        cclentry           = tno.Tag as ChainCollisionEntry;
                                        cclentry.EntryName = cclentry.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        cclentry.TrueName  = cclentry.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        cclentry.FileName  = cclentry.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag            = cclentry;
                                        tno.Text           = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name           = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as ModelEntry != null)
                                    {
                                        mdlentry           = tno.Tag as ModelEntry;
                                        mdlentry.EntryName = mdlentry.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        mdlentry.TrueName  = mdlentry.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        mdlentry.FileName  = mdlentry.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag            = mdlentry;
                                        tno.Text           = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name           = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as MissionEntry != null)
                                    {
                                        misenty           = tno.Tag as MissionEntry;
                                        misenty.EntryName = misenty.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        misenty.TrueName  = misenty.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        misenty.FileName  = misenty.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag           = misenty;
                                        tno.Text          = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name          = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as GemEntry != null)
                                    {
                                        gementy           = tno.Tag as GemEntry;
                                        gementy.EntryName = gementy.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        gementy.TrueName  = gementy.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        gementy.FileName  = gementy.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag           = gementy;
                                        tno.Text          = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name          = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }
                                    else if (tno.Tag as EffectListEntry != null)
                                    {
                                        eflenty           = tno.Tag as EffectListEntry;
                                        eflenty.EntryName = eflenty.EntryName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        eflenty.TrueName  = eflenty.TrueName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        eflenty.FileName  = eflenty.FileName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Tag           = eflenty;
                                        tno.Text          = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                        tno.Name          = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                                    }

                                    RenameCount++;
                                }
                            }
                        }
                    }

                    if (tno.Tag as string != null && tno.Tag as string == "Folder")
                    {
                        //Replaces the Term in the folder.
                        string FolderName = tno.Text as string;
                        FolderName = FolderName.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                        tno.Text   = tno.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                        tno.Name   = tno.Name.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                        RenameCount++;
                    }
                }

                Mainfrm.TreeSource.Update();

                Mainfrm.TreeSource.EndUpdate();

                MessageBox.Show("Replaced " + txtReplaceFind.Text + " with " + txtReplaceReplace.Text + " in " + RenameCount + " file and folder names.");

                Mainfrm.OpenFileModified = true;
                RenameCount = 0;
            }
            else
            {
                if (Mainfrm.TreeSource.SelectedNode.Tag is ResourcePathListEntry)
                {
                    //Gets the text, then replaces every instance of the search term with the new term.
                    string text = Mainfrm.txtRPList.Text;
                    text = text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                    Mainfrm.txtRPList.Text = text;
                }
                else if (Mainfrm.TreeSource.SelectedNode.Tag is MaterialEntry)
                {
                    TreeNodeCollection TNoCollection = Mainfrm.TreeSource.SelectedNode.Nodes;

                    foreach (TreeNode node in TNoCollection)
                    {
                        if (node.Tag as string != null)
                        {
                            if (node.Text as string == "Textures")
                            {
                                Mainfrm.TreeSource.SelectedNode = node;
                                break;
                            }
                        }
                    }

                    TNoCollection = Mainfrm.TreeSource.SelectedNode.Nodes;
                    Mainfrm.TreeSource.BeginUpdate();

                    foreach (TreeNode node in TNoCollection)
                    {
                        string Namer = node.Name as string;
                        node.Text = node.Text.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                        Namer     = Namer.Replace(txtReplaceFind.Text, txtReplaceReplace.Text);
                        node.Name = Namer;
                    }

                    Mainfrm.TreeSource.SelectedNode = Mainfrm.TreeSource.SelectedNode.Parent;

                    //Now to update the Material file with all these, Whether they're changed or not.
                    TreeNode                 Parentnode    = Mainfrm.TreeSource.SelectedNode;
                    MaterialEntry            ParentMateial = Parentnode.Tag as MaterialEntry;
                    MaterialTextureReference texref        = new MaterialTextureReference();
                    string TermToInject = "";
                    //int count = 0;

                    for (int i = 0; i < TNoCollection.Count; i++)
                    {
                        texref = TNoCollection[i].Tag as MaterialTextureReference;

                        TermToInject = TNoCollection[i].Text;

                        //Now for the actual file update.
                        List <byte> NameToInject = new List <byte>();
                        NameToInject.AddRange(Encoding.ASCII.GetBytes(TermToInject));
                        int OffsetToUse;
                        OffsetToUse = 64 + (88 * (texref.Index - 1));
                        byte[] NewName = new byte[64];
                        Array.Copy(NameToInject.ToArray(), 0, NewName, 0, NameToInject.ToArray().Length);
                        Array.Copy(NewName, 0, ParentMateial.UncompressedData, OffsetToUse, NewName.Length);
                        ParentMateial.CompressedData = Zlibber.Compressor(ParentMateial.UncompressedData);
                    }

                    Mainfrm.TreeSource.SelectedNode.Tag = ParentMateial;

                    Mainfrm.OpenFileModified = true;
                    Mainfrm.TreeSource.Update();
                    Mainfrm.TreeSource.EndUpdate();
                }
            }
        }
Exemplo n.º 32
0
        public IExtendedMaterialModel ProcessMaterialEditRequest(int?materialId,
                                                                 string name,
                                                                 string nominalAmountText,
                                                                 int materialInventoryId,
                                                                 bool automaticBatches,
                                                                 bool requiresPrice,
                                                                 bool requiresProductionPrice,
                                                                 bool requiresIncvoice,
                                                                 bool requiresSupplierReference,
                                                                 bool autofinalize,
                                                                 bool canBeDigital,
                                                                 IEnumerable <string> components,
                                                                 string thresholdText
                                                                 )
        {
            name = name?.Trim();

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new InvalidOperationException("Materiál musí mít název");
            }

            if (string.IsNullOrWhiteSpace(nominalAmountText))
            {
                throw new ArgumentException("Materiál musí mít vlastní množství a jednotku");
            }

            var nominalAmountEntry = MaterialEntry.Parse(nominalAmountText, true);

            var nominalUnit = ValidateAmountUnit(nominalAmountEntry);

            using (var tx = m_database.OpenTransaction())
            {
                var material = m_materialRepository.UpsertMaterial(
                    materialId,
                    name,
                    nominalAmountEntry.Amount,
                    nominalUnit.Id,
                    materialInventoryId,
                    automaticBatches,
                    requiresPrice,
                    requiresProductionPrice,
                    requiresIncvoice,
                    requiresSupplierReference, autofinalize, canBeDigital);

                if (thresholdText == null)
                {
                    m_materialThresholdRepository.DeleteThreshold(material.Id);
                }
                else
                {
                    try
                    {
                        var thresholdEntry = MaterialEntry.Parse(thresholdText, true);

                        var thresholdUnit = m_unitRepository.GetUnitBySymbol(thresholdEntry.UnitName);
                        if (thresholdUnit == null)
                        {
                            throw new InvalidOperationException($"Neznámý symbol jednotky \"{thresholdEntry.UnitName}\"");
                        }

                        m_materialThresholdRepository.SaveThreshold(material.Id,
                                                                    thresholdEntry.Amount,
                                                                    thresholdUnit.Id);
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException($"Nelze nastavit sledování minimálního množství - {ex.Message}", ex);
                    }
                }

                tx.Commit();
                m_virtualProductRepository.CleanCache();
                m_materialRepository.CleanCache();
                return(m_materialRepository.GetMaterialById(material.Id));
            }
        }