예제 #1
0
    Items()
    {
        if (Engine.EditorHint)
        {
            return;
        }

        TileShader = GD.Load <Shader>("res://World/Materials/TileShader.shader");

        //Assume that every item has a mesh, thumbnail, and texture. Will throw exception on game startup if not
        foreach (Items.ID Type in System.Enum.GetValues(typeof(ID)))
        {
            if (Type == Items.ID.NONE)
            {
                continue;
            }

            Meshes.Add(Type, GD.Load <Mesh>($"res://Items/Meshes/{Type}.obj"));
            Thumbnails.Add(Type, GD.Load <Texture>($"res://Items/Thumbnails/{Type}.png"));
            Textures.Add(Type, GD.Load <Texture>($"res://Items/Textures/{Type}.png"));
        }
    }
예제 #2
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            // Load textures
            Textures.Add("Grass", Content.Load <Texture2D>("Grass"));
            Textures.Add("Sky", Content.Load <Texture2D>("Sky"));
            Textures.Add("Smoke", Content.Load <Texture2D>("Smoke"));
            // Load models
            Models.Add("House", Content.Load <Model>("House"));
            Models.Add("PaperPlane", Content.Load <Model>("PaperPlane"));

            // ** Debug, reset the light to undo Content.Load<Model> switching them off...
            _effect.DirectionalLight0.DiffuseColor  = _effect.DirectionalLight0.DiffuseColor;
            _effect.DirectionalLight0.SpecularColor = _effect.DirectionalLight0.SpecularColor;
            // ** Debug, set the initial samplerstate to LinearWrap
            GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

            // Reset the game
            ResetGame();
        }
예제 #3
0
        internal override bool ParseNodeBodyElement(string id, VRMLParser parser)
        {
            int line = parser.Line;

            if (id == "textures")
            {
                List <X3DNode> nodes = parser.ParseSFNodeOrMFNodeValue();
                foreach (X3DNode node in nodes)
                {
                    X3DTexture2DNode texture2DNode = node as X3DTexture2DNode;
                    if (texture2DNode == null)
                    {
                        parser.ErrorParsingNode(VRMLReaderError.UnexpectedNodeType, this, id, node, line);
                    }
                    else
                    {
                        Textures.Add(texture2DNode);
                    }
                }
            }
            else if (id == "repeatS")
            {
                RepeatS = parser.ParseBoolValue();
            }
            else if (id == "repeatT")
            {
                RepeatT = parser.ParseBoolValue();
            }
            else if (id == "repeatR")
            {
                RepeatR = parser.ParseBoolValue();
            }
            else
            {
                return(false);
            }
            return(true);
        }
예제 #4
0
        protected virtual void InitTextures(ArchiveWorker aw = null)
        {
            if (Textures == null)
            {
                Textures = new List <TextureHandler>(TextureCount.Sum());
            }
            if (Textures.Count <= 0)
            {
                if (aw == null)
                {
                    aw = new ArchiveWorker(ArchiveString);
                }
                TEX tex;
                Scale = new Dictionary <uint, Vector2>(TextureCount.Sum());
                int b = 0;
                for (int j = 0; j < TextureCount.Length; j++)
                {
                    for (uint i = 0; i < TextureCount[j]; i++)
                    {
                        string path = aw.GetListOfFiles().First(x => x.ToLower().Contains(string.Format(TextureFilename[j], i + TextureStartOffset)));
                        tex = new TEX(ArchiveWorker.GetBinaryFile(ArchiveString, path));
                        if (TextureBigFilename != null && FORCE_ORIGINAL == false && b < TextureBigFilename.Length && b < TextureBigSplit.Length)
                        {
                            TextureHandler th = new TextureHandler(TextureBigFilename[b], tex, 2, TextureBigSplit[b++] / 2);

                            Textures.Add(th);
                            Scale[i] = Vector2.One;//th.GetScale();
                        }
                        else
                        {
                            TextureHandler th = new TextureHandler(path, tex);
                            Textures.Add(th);
                            Scale[i] = th.GetScale();
                        }
                    }
                }
            }
        }
예제 #5
0
        public Ilm(IlmHeader h, byte[] bytes, float scale)
        {
            Header = h;
            Scale  = scale;

            int textureBase      = (int)(Header.TexturePointer - Header.BaseAddress);
            int textureByteCount = sizeof(int) * 6;

            for (int i = 0; i < Header.TextureCount; i++)
            {
                int offset = textureBase + (textureByteCount * i);

                var    utf = new UTF8Encoding();
                string raw = utf.GetString(bytes, offset, textureByteCount);

                // Each texture listing is 6 32-bit words, and though they start
                // out padded with zeroes in their file on disk, once loaded in
                // RAM they have other, as yet undeciphered data after the name.
                int nullIndex = raw.IndexOf('\0');
                if (nullIndex >= 0)
                {
                    raw = raw.Remove(nullIndex);
                }
                Textures.Add(raw);
            }

            int submeshStartOffset      = textureBase + (textureByteCount * Header.TextureCount);
            int submeshListingByteCount = 16;

            for (int i = 0; i < Header.SubmeshCount; i++)
            {
                int offset = submeshStartOffset + (submeshListingByteCount * i);

                var mesh = new Submesh(bytes.Skip(offset).ToArray(), Header.BaseAddress + offset, Scale);

                Submeshes.Add(mesh);
            }
        }
예제 #6
0
        /// <summary>
        /// Load all the cells textures from (import),
        /// For all the rows of the current layer, create the cell,
        /// if the cell exist in the list "collideable", then add
        /// collision on it.
        /// </summary>
        public void LoadContent(ContentManager content)
        {
            Vector2 offset = new Vector2(0, 0);

            for (int i = 0; i < Import.Count; i++)
            {
                var tempTexture = new Texture2D(GraphicsManager.Instance.GraphicsDeviceManager.GraphicsDevice, 1, 1);
                tempTexture = content.Load <Texture2D>(Import[i]);
                Textures.Add(tempTexture);
            }

            for (int x = 0; x < Row.Count; x++)
            {
                string[] exclude = Row[x].Split("]");

                offset.X  = 0;
                offset.Y += 16;

                for (int y = 0; y < exclude.Length; y++)
                {
                    offset.X += 16;
                    if (exclude[y] != String.Empty && !exclude[y].Contains("_"))
                    {
                        exclude[y] = exclude[y].Replace("[", String.Empty);
                        int id = int.Parse(exclude[y].Substring(0, 1));

                        if (Collideable.Count > 1 && Collideable[id].Contains($"[{id}]"))
                        {
                            Cells.Add(new Cell(Textures[id], offset, true));
                        }
                        else
                        {
                            Cells.Add(new Cell(Textures[id], offset, false));
                        }
                    }
                }
            }
        }
예제 #7
0
        public void AddTexture()
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".tex";
            dlg.Filter     = "Texture file (*.tex)|*.tex";


            // Display OpenFileDialog by calling ShowDialog method
            Nullable <bool> result = dlg.ShowDialog();


            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                string  filename = dlg.FileName;
                Texture tex      = new Texture(filename);
                _textures.Add(tex);
                Textures.Add(new TextureViewModel(tex));
            }
        }
예제 #8
0
        private void LoadFromDirectory(string dir)
        {
            foreach (string path in Directory.GetFiles(dir))
            {
                // loading new image
                if (!Tiles.ContainsKey(Path.GetFileNameWithoutExtension(path)))
                {
                    if (IMAGE_EXTENSIONS.Contains(Path.GetExtension(path).ToUpper()) && Directory.Exists(path))
                    {
                        if (path.Contains(UriUtilities.URI_SEPARATOR))
                        {
                            Textures.Add(Path.GetFileNameWithoutExtension(path), AssetLoader.Load <Texture2D>(path));
                        }
                        else
                        {
                            Textures.Add(Path.GetFileNameWithoutExtension(path), AssetLoader.LoadUsingExtension(path) as Texture2D);
                        }

                        Tiles.Add(Path.GetFileNameWithoutExtension(path), new Rectangle());
                    }
                }
            }
        }
예제 #9
0
        public void LoadTextures()
        {
            DirectoryInfo Folder = new DirectoryInfo(TextureLocation);

            if (Folder.Exists)
            {
                FileInfo[] ConfigFiles = Folder.GetFiles();

                foreach (FileInfo File in ConfigFiles)
                {
                    if (File.Extension.Equals(".png"))
                    {
                        FileStream FileStream = new FileStream(File.FullName.ToString(), FileMode.Open);
                        Textures.Add(File.Name.Remove(File.Name.Length - 4, 4), Texture2D.FromStream(Graphics, FileStream));
                        FileStream.Close();
                        FileStream.Dispose();
                        //call garbage collection after loading image
                        System.GC.Collect();
                        System.GC.WaitForPendingFinalizers();
                    }
                }
            }
        }
예제 #10
0
        public static int Load <T>(string assetName)
        {
            if (typeof(T) == typeof(Texture2D))
            {
                Textures.Add(Content.Load <Texture2D>(assetName));
                return(Textures.Count - 1);
            }
            else if (typeof(T) == typeof(SoundEffectInstance))
            {
                SoundEffectInstance sfxInstance = Content.Load <SoundEffect>(assetName).CreateInstance();

                SoundEffects.Add(sfxInstance);
                return(SoundEffects.Count - 1);
            }
            else if (typeof(T) == typeof(SoundEffect))
            {
                SoundEffectInstance sfxInstance = Content.Load <SoundEffect>(assetName).CreateInstance();

                Songs.Add(new LoopedSoundPlayer(Content.Load <SoundEffect>(assetName)));
                return(Songs.Count - 1);
            }

            return(-1);
        }
예제 #11
0
        /// <summary>
        /// Loads the file from the specified stream.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        public override void Load(Stream stream)
        {
            BinaryReader reader = new BinaryReader(stream, Encoding.GetEncoding("EUC-KR"));

            short textureCount = reader.ReadInt16();

            for (int i = 0; i < textureCount; i++)
            {
                SpriteTexture texture = new SpriteTexture();
                texture.FileName  = reader.ReadShortString();
                texture.ColourKey = reader.ReadInt32();

                Textures.Add(texture);
            }

            short totalSpriteCount = reader.ReadInt16();

            for (int i = 0; i < textureCount; i++)
            {
                short spriteCount = reader.ReadInt16();

                for (int j = 0; j < spriteCount; j++)
                {
                    Sprite sprite = new Sprite();
                    sprite.Texture = reader.ReadInt16();
                    sprite.X1      = reader.ReadInt32();
                    sprite.Y1      = reader.ReadInt32();
                    sprite.X2      = reader.ReadInt32();
                    sprite.Y2      = reader.ReadInt32();
                    sprite.Colour  = reader.ReadInt32();
                    sprite.ID      = reader.ReadString(32).TrimEnd('\0');

                    Sprites.Add(sprite);
                }
            }
        }
예제 #12
0
        private static Texture2D GetTexture(uint textureID, Surface surface = null, PaletteChanges paletteChanges = null, bool useCache = true)
        {
            //Console.WriteLine($"-> GetTexture({textureID:X8})");

            var texturePalette = new TexturePalette(textureID, paletteChanges);

            if (useCache && Textures.TryGetValue(texturePalette, out var cached))
            {
                return(cached);
            }

            var texture = LoadTexture(textureID, false, surface, paletteChanges);

            if (useCache)
            {
                Textures.Add(texturePalette, texture);
            }
            else
            {
                Uncached.Add(texture);
            }

            return(texture);
        }
예제 #13
0
        public T this[string name]
        {
            get
            {
                if (name == null)
                {
                    return(default(T));
                }
                if (!Textures.ContainsKey(name))
                {
                    var asset = Resources.Load <T>(path + name);

                    if (asset)
                    {
                        Textures.Add(name, asset);
                    }
                    else
                    {
                        throw new AssetNotFound("Asset not found:" + path + name);
                    }
                }
                return(Textures[name]);
            }
        }
예제 #14
0
        private void Read(BinaryReader br, Dictionary <string, BinaryReader> sequenceGroups)
        {
            Header = new Header
            {
                ID             = ID.Idst,
                Version        = Version.Goldsource,
                Name           = br.ReadFixedLengthString(Encoding.ASCII, 64),
                Size           = br.ReadInt32(),
                EyePosition    = br.ReadVector3(),
                HullMin        = br.ReadVector3(),
                HullMax        = br.ReadVector3(),
                BoundingBoxMin = br.ReadVector3(),
                BoundingBoxMax = br.ReadVector3(),
                Flags          = br.ReadInt32()
            };

            // Read all the nums/offsets from the header
            var sections = new int[(int)Section.NumSections][];

            for (var i = 0; i < (int)Section.NumSections; i++)
            {
                var sec = (Section)i;

                int indexNum;
                if (sec == Section.Texture || sec == Section.Skin)
                {
                    indexNum = 3;
                }
                else
                {
                    indexNum = 2;
                }

                sections[i] = new int[indexNum];
                for (var j = 0; j < indexNum; j++)
                {
                    sections[i][j] = br.ReadInt32();
                }
            }

            // Bones
            var num      = SeekToSection(br, Section.Bone, sections);
            var numBones = num;

            for (var i = 0; i < num; i++)
            {
                var bone = new Bone
                {
                    Name          = br.ReadFixedLengthString(Encoding.ASCII, 32),
                    Parent        = br.ReadInt32(),
                    Flags         = br.ReadInt32(),
                    Controllers   = br.ReadIntArray(6),
                    Position      = br.ReadVector3(),
                    Rotation      = br.ReadVector3(),
                    PositionScale = br.ReadVector3(),
                    RotationScale = br.ReadVector3()
                };
                Bones.Add(bone);
            }

            // Bone controllers
            num = SeekToSection(br, Section.BoneController, sections);
            for (var i = 0; i < num; i++)
            {
                var boneController = new BoneController
                {
                    Bone  = br.ReadInt32(),
                    Type  = br.ReadInt32(),
                    Start = br.ReadSingle(),
                    End   = br.ReadSingle(),
                    Rest  = br.ReadInt32(),
                    Index = br.ReadInt32()
                };
                BoneControllers.Add(boneController);
            }

            // Hitboxes
            num = SeekToSection(br, Section.Hitbox, sections);
            for (var i = 0; i < num; i++)
            {
                var hitbox = new Hitbox
                {
                    Bone  = br.ReadInt32(),
                    Group = br.ReadInt32(),
                    Min   = br.ReadVector3(),
                    Max   = br.ReadVector3()
                };
                Hitboxes.Add(hitbox);
            }

            // Sequence groups
            num = SeekToSection(br, Section.SequenceGroup, sections);
            for (var i = 0; i < num; i++)
            {
                var group = new SequenceGroup
                {
                    Label = br.ReadFixedLengthString(Encoding.ASCII, 32),
                    Name  = br.ReadFixedLengthString(Encoding.ASCII, 64)
                };
                br.ReadBytes(8); // unused
                SequenceGroups.Add(group);
            }

            // Sequences
            num = SeekToSection(br, Section.Sequence, sections);
            for (var i = 0; i < num; i++)
            {
                var sequence = new Sequence
                {
                    Name                  = br.ReadFixedLengthString(Encoding.ASCII, 32),
                    Framerate             = br.ReadSingle(),
                    Flags                 = br.ReadInt32(),
                    Activity              = br.ReadInt32(),
                    ActivityWeight        = br.ReadInt32(),
                    NumEvents             = br.ReadInt32(),
                    EventIndex            = br.ReadInt32(),
                    NumFrames             = br.ReadInt32(),
                    NumPivots             = br.ReadInt32(),
                    PivotIndex            = br.ReadInt32(),
                    MotionType            = br.ReadInt32(),
                    MotionBone            = br.ReadInt32(),
                    LinearMovement        = br.ReadVector3(),
                    AutoMovePositionIndex = br.ReadInt32(),
                    AutoMoveAngleIndex    = br.ReadInt32(),
                    Min            = br.ReadVector3(),
                    Max            = br.ReadVector3(),
                    NumBlends      = br.ReadInt32(),
                    AnimationIndex = br.ReadInt32(),
                    BlendType      = br.ReadIntArray(2),
                    BlendStart     = br.ReadSingleArray(2),
                    BlendEnd       = br.ReadSingleArray(2),
                    BlendParent    = br.ReadInt32(),
                    SequenceGroup  = br.ReadInt32(),
                    EntryNode      = br.ReadInt32(),
                    ExitNode       = br.ReadInt32(),
                    NodeFlags      = br.ReadInt32(),
                    NextSequence   = br.ReadInt32()
                };

                var seqGroup = SequenceGroups[sequence.SequenceGroup];

                // Only load seqence group 0 for now (others are in other files)
                if (sequence.SequenceGroup == 0)
                {
                    var pos = br.BaseStream.Position;
                    sequence.Blends        = LoadAnimationBlends(br, sequence, numBones);
                    br.BaseStream.Position = pos;
                }
                else if (sequenceGroups.ContainsKey(seqGroup.Name))
                {
                    var reader = sequenceGroups[seqGroup.Name];
                    sequence.Blends = LoadAnimationBlends(reader, sequence, numBones);
                }

                Sequences.Add(sequence);
            }

            // Textures
            num = SeekToSection(br, Section.Texture, sections);
            var firstTextureIndex = Textures.Count;

            for (var i = 0; i < num; i++)
            {
                var texture = new Texture
                {
                    Name   = br.ReadFixedLengthString(Encoding.ASCII, 64),
                    Flags  = (TextureFlags)br.ReadInt32(),
                    Width  = br.ReadInt32(),
                    Height = br.ReadInt32(),
                    Index  = br.ReadInt32()
                };
                Textures.Add(texture);
            }

            // Texture data
            for (var i = firstTextureIndex; i < firstTextureIndex + num; i++)
            {
                var t = Textures[i];
                br.BaseStream.Position = t.Index;
                t.Data      = br.ReadBytes(t.Width * t.Height);
                t.Palette   = br.ReadBytes(256 * 3);
                Textures[i] = t;
            }

            // Skins
            var skinSection     = sections[(int)Section.Skin];
            var numSkinRefs     = skinSection[0];
            var numSkinFamilies = skinSection[1];

            br.BaseStream.Seek(skinSection[2], SeekOrigin.Begin);
            for (var i = 0; i < numSkinFamilies; i++)
            {
                var skin = new SkinFamily
                {
                    Textures = br.ReadShortArray(numSkinRefs)
                };
                Skins.Add(skin);
            }

            // Body parts
            num = SeekToSection(br, Section.BodyPart, sections);
            for (var i = 0; i < num; i++)
            {
                var part = new BodyPart
                {
                    Name       = br.ReadFixedLengthString(Encoding.ASCII, 64),
                    NumModels  = br.ReadInt32(),
                    Base       = br.ReadInt32(),
                    ModelIndex = br.ReadInt32()
                };
                var pos = br.BaseStream.Position;
                part.Models            = LoadModels(br, part);
                br.BaseStream.Position = pos;
                BodyParts.Add(part);
            }

            // Attachments
            num = SeekToSection(br, Section.Attachment, sections);
            for (var i = 0; i < num; i++)
            {
                var attachment = new Attachment
                {
                    Name    = br.ReadFixedLengthString(Encoding.ASCII, 32),
                    Type    = br.ReadInt32(),
                    Bone    = br.ReadInt32(),
                    Origin  = br.ReadVector3(),
                    Vectors = br.ReadVector3Array(3)
                };
                Attachments.Add(attachment);
            }

            // Transitions

            // Sounds & Sound groups aren't used
        }
예제 #15
0
        /// <summary>
        /// Loads the file from the specified stream.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        public override void Load(Stream stream)
        {
            BinaryReader reader = new BinaryReader(stream, Encoding.GetEncoding("us-ascii"));

            int blockCount = reader.ReadInt32();

            for (int i = 0; i < blockCount; i++)
            {
                ZoneBlock type   = (ZoneBlock)reader.ReadInt32();
                int       offset = reader.ReadInt32();

                long nextBlock = stream.Position;
                stream.Seek(offset, SeekOrigin.Begin);

                switch (type)
                {
                case ZoneBlock.Info:
                    Type          = (ZoneType)reader.ReadInt32();
                    Width         = reader.ReadInt32();
                    Height        = reader.ReadInt32();
                    GridCount     = reader.ReadInt32();
                    GridSize      = reader.ReadSingle();
                    StartPosition = new IntVector2(reader.ReadInt32(), reader.ReadInt32());

                    for (int w = 0; w < Width; w++)
                    {
                        for (int h = 0; h < Height; h++)
                        {
                            Positions[w, h].IsUsed   = reader.ReadBoolean();
                            Positions[w, h].Position = reader.ReadVector2();
                        }
                    }
                    break;

                case ZoneBlock.SpawnPoints:
                    int spawnCount = reader.ReadInt32();

                    for (int j = 0; j < spawnCount; j++)
                    {
                        SpawnPoint spawnPoint = new SpawnPoint();
                        spawnPoint.Position = reader.ReadVector3();
                        spawnPoint.Name     = reader.ReadByteString();

                        SpawnPoints.Add(spawnPoint);
                    }
                    break;

                case ZoneBlock.Textures:
                    int textureCount = reader.ReadInt32();

                    for (int j = 0; j < textureCount; j++)
                    {
                        Textures.Add(reader.ReadByteString());
                    }
                    break;

                case ZoneBlock.Tiles:
                    int tileCount = reader.ReadInt32();

                    for (int j = 0; j < tileCount; j++)
                    {
                        ZoneTile tile = new ZoneTile();
                        tile.Layer1          = reader.ReadInt32();
                        tile.Layer2          = reader.ReadInt32();
                        tile.Offset1         = reader.ReadInt32();
                        tile.Offset2         = reader.ReadInt32();
                        tile.BlendingEnabled = reader.ReadInt32() != 0;
                        tile.Rotation        = (TileRotation)reader.ReadInt32();
                        tile.TileType        = reader.ReadInt32();

                        Tiles.Add(tile);
                    }
                    break;

                case ZoneBlock.Economy:
                    Name                    = reader.ReadByteString();
                    IsUnderground           = reader.ReadInt32() != 0;
                    BackgroundMusicFilePath = reader.ReadByteString();
                    SkyFilePath             = reader.ReadByteString();
                    EconomyCheckRate        = reader.ReadInt32();
                    PopulationBase          = reader.ReadInt32();
                    PopulationGrowthRate    = reader.ReadInt32();
                    MetalConsumption        = reader.ReadInt32();
                    StoneConsumption        = reader.ReadInt32();
                    WoodConsumption         = reader.ReadInt32();
                    LeatherConsumption      = reader.ReadInt32();
                    ClothConsumption        = reader.ReadInt32();
                    AlchemyConsumption      = reader.ReadInt32();
                    ChemicalConsumption     = reader.ReadInt32();
                    IndustrialConsumption   = reader.ReadInt32();
                    MedicineConsumption     = reader.ReadInt32();
                    FoodConsumption         = reader.ReadInt32();
                    break;
                }

                if (i < blockCount - 1)
                {
                    stream.Seek(nextBlock, SeekOrigin.Begin);
                }
            }
        }
예제 #16
0
        protected override void InitializeCore()
        {
            RegisterReplaceHandler <TextureSet>(BinaryFile.Load <TextureSet>);
            RegisterExportHandler <TextureSet>((path) =>
            {
                // Assume it's being exported for F2nd PS3
                if (BinaryFormatUtilities.IsClassic(Data.Format) && path.EndsWith(".txd", StringComparison.OrdinalIgnoreCase))
                {
                    Data.Format     = BinaryFormat.F2nd;
                    Data.Endianness = Endianness.BigEndian;
                }

                // Or reverse
                else if (BinaryFormatUtilities.IsModern(Data.Format) && path.EndsWith(".bin", StringComparison.OrdinalIgnoreCase))
                {
                    Data.Format     = BinaryFormat.DT;
                    Data.Endianness = Endianness.LittleEndian;
                }

                Data.Save(path);
            });
            RegisterImportHandler <Texture>((path) =>
            {
                var texture = TextureEncoder.Encode(path);
                var node    = DataNodeFactory.Create <Texture>(Path.GetFileNameWithoutExtension(path), texture);
                Textures.Add(node);
            });
            RegisterImportHandler <Bitmap>((path) =>
            {
                var texture = TextureEncoder.Encode(path);
                var node    = DataNodeFactory.Create <Texture>(Path.GetFileNameWithoutExtension(path), texture);
                Textures.Add(node);
            });
            RegisterCustomHandler("Export All", () =>
            {
                using (var saveFileDialog = new SaveFileDialog())
                {
                    saveFileDialog.AutoUpgradeEnabled = true;
                    saveFileDialog.CheckPathExists    = true;
                    saveFileDialog.Title    = "Select a folder to export textures to.";
                    saveFileDialog.FileName = "Enter into a directory and press Save";

                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        var outputDirectory = Path.GetDirectoryName(saveFileDialog.FileName);
                        foreach (var texture in Data.Textures)
                        {
                            if (!TextureFormatUtilities.IsCompressed(texture.Format) || texture.IsYCbCr)
                            {
                                TextureDecoder.DecodeToPNG(texture, Path.Combine(outputDirectory, texture.Name + ".png"));
                            }
                            else
                            {
                                TextureDecoder.DecodeToDDS(texture, Path.Combine(outputDirectory, texture.Name + ".dds"));
                            }
                        }
                    }
                }
            }, Keys.Control | Keys.Shift | Keys.E);
            RegisterDataUpdateHandler(() =>
            {
                var data        = new TextureSet();
                data.Format     = Format;
                data.Endianness = Endianness;
                data.Textures.AddRange(Textures.Data);
                return(data);
            });
        }
예제 #17
0
        private void LoadAnim(TexPatternAnim anim)
        {
            CanReplace = true;
            CanExport  = true;
            CanDelete  = true;
            CanRename  = true;

            Text = anim.Name;

            TexPatternAnim = anim;
            FrameCount     = anim.FrameCount;

            Materials.Clear();
            Textures.Clear();
            if (anim.TextureRefNames != null)
            {
                foreach (var tex in anim.TextureRefNames)
                {
                    Textures.Add(tex.Name);
                }
            }

            if (anim.TextureRefs != null)
            {
                foreach (var tex in anim.TextureRefs)
                {
                    Textures.Add(tex.Key);
                }
            }


            foreach (TexPatternMatAnim matanim in anim.TexPatternMatAnims)
            {
                var mat = new MaterialAnimEntry(matanim.Name);
                mat.TexPatternMatAnim = matanim;
                Materials.Add(mat);

                foreach (PatternAnimInfo SamplerInfo in matanim.PatternAnimInfos)
                {
                    BfresSamplerAnim sampler = new BfresSamplerAnim(SamplerInfo.Name, this);
                    mat.Samplers.Add(sampler);

                    int textureIndex = 0;

                    if (SamplerInfo.SubBindIndex != -1)
                    {
                        textureIndex = SamplerInfo.SubBindIndex;

                        sampler.Keys.Add(new Animation.KeyFrame()
                        {
                            Frame = 0, Value = textureIndex
                        });
                        sampler.Constant = true;
                    }
                    if (SamplerInfo.CurveIndex != -1)
                    {
                        int index = (int)SamplerInfo.CurveIndex;

                        Animation.KeyGroup keyGroup = CurveHelper.CreateTrackWiiU(matanim.Curves[index]);
                        sampler.AnimDataOffset = matanim.Curves[index].AnimDataOffset;
                        sampler.Keys           = keyGroup.Keys;

                        foreach (var ind in keyGroup.Keys)
                        {
                            Console.WriteLine($"{SamplerInfo.Name} {ind.Value}");
                        }
                    }
                }
            }
        }
예제 #18
0
	// METHODS
	public static Textures createLump(byte[] data, mapType type) {
		int numElements = -1; // For Quake and Source, which use nonconstant struct lengths
		int[] offsets = new int[0]; // For Quake, which stores offsets to each texture definition structure, which IS a constant length
		int structLength = 0;
		switch (type) {
			case mapType.TYPE_NIGHTFIRE: 
				structLength = 64;
				break;
			case mapType.TYPE_QUAKE3: 
			case mapType.TYPE_RAVEN: 
			case mapType.TYPE_COD: 
			case mapType.TYPE_COD2: 
			case mapType.TYPE_COD4: 
				structLength = 72;
				break;
			case mapType.TYPE_QUAKE2: 
			case mapType.TYPE_DAIKATANA: 
			case mapType.TYPE_SOF: 
			case mapType.TYPE_STEF2: 
			case mapType.TYPE_STEF2DEMO: 
			case mapType.TYPE_FAKK: 
				structLength = 76;
				break;
			case mapType.TYPE_MOHAA: 
				structLength = 140;
				break;
			case mapType.TYPE_SIN: 
				structLength = 180;
				break;
			case mapType.TYPE_SOURCE17: 
			case mapType.TYPE_SOURCE18: 
			case mapType.TYPE_SOURCE19: 
			case mapType.TYPE_SOURCE20: 
			case mapType.TYPE_SOURCE21: 
			case mapType.TYPE_SOURCE22: 
			case mapType.TYPE_SOURCE23: 
			case mapType.TYPE_SOURCE27: 
			case mapType.TYPE_TACTICALINTERVENTION: 
			case mapType.TYPE_VINDICTUS: 
			case mapType.TYPE_DMOMAM: 
				numElements = 0;
				for (int i = 0; i < data.Length; i++) {
					if (data[i] == 0x00) {
						numElements++;
					}
				}
				break;
			case mapType.TYPE_QUAKE: 
				numElements = DataReader.readInt(data[0], data[1], data[2], data[3]);
				offsets = new int[numElements];
				for (int i = 0; i < numElements; i++) {
					offsets[i] = DataReader.readInt(data[((i + 1) * 4)], data[((i + 1) * 4) + 1], data[((i + 1) * 4) + 2], data[((i + 1) * 4) + 3]);
				}
				structLength = 40;
				break;
		}
		Textures lump;
		if (numElements == - 1) {
			int offset = 0;
			//elements = new Texture[data.Length / structLength];
			lump = new Textures(new List<Texture>(data.Length / structLength), data.Length, structLength);
			byte[] bytes = new byte[structLength];
			for (int i = 0; i < data.Length / structLength; i++) {
				for (int j = 0; j < structLength; j++) {
					bytes[j] = data[offset + j];
				}
				lump.Add(new Texture(bytes, type));
				offset += structLength;
			}
		} else {
			lump = new Textures(new List<Texture>(numElements), data.Length, structLength);
			if (offsets.Length != 0) {
				// Quake/GoldSrc
				for (int i = 0; i < numElements; i++) {
					int offset = offsets[i];
					byte[] bytes = new byte[structLength];
					for (int j = 0; j < structLength; j++) {
						bytes[j] = data[offset + j];
					}
					lump.Add(new Texture(bytes, type));
					offset += structLength;
				}
			} else {
				// Source
				int offset = 0;
				int current = 0;
				byte[] bytes = new byte[0];
				for (int i = 0; i < data.Length; i++) {
					if (data[i] == (byte) 0x00) {
						// They are null-terminated strings, of non-constant length (not padded)
						lump.Add(new Texture(bytes, type));
						bytes = new byte[0];
						current++;
					} else {
						byte[] newList = new byte[bytes.Length + 1];
						for (int j = 0; j < bytes.Length; j++) {
							newList[j] = bytes[j];
						}
						newList[bytes.Length] = data[i];
						bytes = newList;
					}
					offset++;
				}
			}
		}
		return lump;
	}
예제 #19
0
        /// <summary>
        /// Loads a batch renderer for a doodad in a render context
        /// </summary>
        /// <param name="mgr">The render context</param>
        /// <param name="doodadName">Name of the doodad (case insensitive)</param>
        public M2BatchRender(string doodadName)
        {
            Intersector = new ModelIntersector(this);
            ModelName   = doodadName;
            M2Info inf = Game.GameManager.M2ModelCache.GetInfo(doodadName);

            mModelInfo = inf;
            Game.GameManager.GraphicsThread.CallOnThread(
                () =>
            {
                for (int i = 0; i < inf.Passes.Count; ++i)
                {
                    Models.MDX.M2RenderPass pass = inf.Passes[i];
                    Mesh mesh = new Mesh(
                        Game.GameManager.GraphicsThread.GraphicsManager.Device,
                        pass.Vertices.Length / 3,
                        pass.Vertices.Length,
                        MeshFlags.Managed,
                        MdxVertex.FVF
                        );

                    VertexBuffer vb = new VertexBuffer(Game.GameManager.GraphicsThread.GraphicsManager.Device, pass.Vertices.Length * Marshal.SizeOf(typeof(Models.MDX.MdxVertex)), Usage.None,
                                                       Models.MDX.MdxVertex.FVF, Pool.Managed);
                    DataStream strm = vb.Lock(0, 0, LockFlags.None);
                    strm.WriteRange(pass.Vertices);
                    vb.Unlock();

                    strm = mesh.VertexBuffer.Lock(0, 0, LockFlags.None);
                    strm.WriteRange(pass.Vertices);
                    mesh.VertexBuffer.Unlock();

                    IndexBuffer ib = new IndexBuffer(Game.GameManager.GraphicsThread.GraphicsManager.Device, pass.Vertices.Length * 2, Usage.None, Pool.Managed, true);
                    strm           = ib.Lock(0, 0, LockFlags.None);
                    for (int j = 0; j < pass.Vertices.Length; ++j)
                    {
                        strm.Write((short)j);
                    }
                    ib.Unlock();

                    strm = mesh.IndexBuffer.Lock(0, 0, LockFlags.None);
                    for (int j = 0; j < pass.Vertices.Length; ++j)
                    {
                        strm.Write((short)j);
                    }
                    mesh.IndexBuffer.Unlock();

                    try
                    {
                        Textures.Add(Video.TextureManager.GetTexture(pass.Texture));
                    }
                    catch (Exception)
                    {
                        Textures.Add(Video.TextureManager.Default.ErrorTexture);
                    }
                    NumTriangles.Add(pass.Vertices.Length / 3);
                    Indices.Add(ib);
                    Meshes.Add(vb);
                    mMeshPasses.Add(mesh);
                }
            }
                );
            InstanceDeclaration = new VertexDeclaration(Game.GameManager.GraphicsThread.GraphicsManager.Device, ElemDecl);
            InstanceLoader      = new M2InstanceLoader(this);

            Game.GameManager.GraphicsThread.OnFrame += new Game.VideoThread.FrameRenderDelegate(_OnFrame);
        }
예제 #20
0
 public void AddTexture(string name)
 {
     Textures.Add(_UI.Store_Texture.Get(name));
 }
예제 #21
0
        private void LoadAnim(MaterialAnim anim)
        {
            Initialize();

            MaterialAnim = anim;
            FrameCount   = MaterialAnim.FrameCount;
            Text         = anim.Name;

            Textures.Clear();
            if (anim.TextureNames != null)
            {
                foreach (var name in anim.TextureNames)
                {
                    Textures.Add(name);
                }
            }

            Materials.Clear();
            foreach (var matanim in anim.MaterialAnimDataList)
            {
                var mat = new MaterialAnimEntry(matanim.Name);
                mat.MaterialAnimData = matanim;
                Materials.Add(mat);

                foreach (var param in matanim.ParamAnimInfos)
                {
                    FSHU.BfresParamAnim paramInfo = new FSHU.BfresParamAnim(param.Name);
                    mat.Params.Add(paramInfo);

                    paramInfo.Type = AnimationType.ShaderParam;

                    //There is no better way to determine if the param is a color type afaik
                    if (param.Name.Contains("Color") || param.Name.Contains("color") || param.Name == "multi_tex_reg2")
                    {
                        paramInfo.Type = AnimationType.Color;
                    }
                    else if (AnimType == AnimationType.TexturePattern)
                    {
                        paramInfo.Type = AnimationType.TexturePattern;
                    }
                    else if (AnimType == AnimationType.TextureSrt)
                    {
                        paramInfo.Type = AnimationType.TextureSrt;
                    }
                    else
                    {
                        paramInfo.Type = AnimationType.ShaderParam;
                    }

                    //Get constant anims
                    for (int constant = 0; constant < param.ConstantCount; constant++)
                    {
                        int index = constant + param.BeginConstant;

                        Animation.KeyGroup keyGroup = new Animation.KeyGroup();
                        keyGroup.Keys.Add(new Animation.KeyFrame()
                        {
                            InterType = InterpolationType.CONSTANT,
                            Frame     = 0,
                            Value     = matanim.Constants[index].Value,
                        });

                        paramInfo.Values.Add(new Animation.KeyGroup()
                        {
                            AnimDataOffset = matanim.Constants[index].AnimDataOffset,
                            Keys           = keyGroup.Keys,
                        });
                    }

                    for (int curve = 0; curve < param.FloatCurveCount + param.IntCurveCount; curve++)
                    {
                        int index = curve + param.BeginCurve;

                        Animation.KeyGroup keyGroup = CurveHelper.CreateTrack(matanim.Curves[index]);
                        keyGroup.AnimDataOffset = matanim.Curves[index].AnimDataOffset;

                        paramInfo.Values.Add(new Animation.KeyGroup()
                        {
                            AnimDataOffset = keyGroup.AnimDataOffset,
                            Keys           = keyGroup.Keys,
                        });
                    }
                }

                foreach (TexturePatternAnimInfo SamplerInfo in matanim.TexturePatternAnimInfos)
                {
                    BfresSamplerAnim sampler = new BfresSamplerAnim(SamplerInfo.Name, this, mat);
                    mat.Samplers.Add(sampler);


                    int textureIndex = 0;

                    if (SamplerInfo.BeginConstant != 65535)
                    {
                        textureIndex = matanim.Constants[SamplerInfo.BeginConstant].Value;

                        sampler.Keys.Add(new Animation.KeyFrame()
                        {
                            Frame = 0, Value = textureIndex
                        });
                        sampler.Constant       = true;
                        sampler.AnimDataOffset = matanim.Constants[SamplerInfo.BeginConstant].AnimDataOffset;
                    }
                    if (SamplerInfo.CurveIndex != 65535)
                    {
                        int index = (int)SamplerInfo.CurveIndex;

                        Animation.KeyGroup keyGroup = CurveHelper.CreateTrack(matanim.Curves[index]);

                        sampler.AnimDataOffset = matanim.Curves[index].AnimDataOffset;
                        sampler.Keys           = keyGroup.Keys;
                    }
                }
            }
        }
예제 #22
0
        /*
         * public byte[] GetBuffer(int bufferIndex)
         * {
         *  return FileChunks[bufferIndex + 1].Data;
         * }
         */

        public void ParseJSON(string JSONstring)
        {
            var json = JsonConvert.DeserializeObject <dynamic>(JSONstring);

            foreach (var bufferViewJSON in json.bufferViews)
            {
                GLBBufferView bufferView = new GLBBufferView();

                bufferView.Buffer     = FileChunks[(int)bufferViewJSON.buffer + 1].Data;
                bufferView.ByteOffset = bufferViewJSON.byteOffset;
                bufferView.ByteLength = bufferViewJSON.byteLength;
                bufferView.Target     = bufferViewJSON.target;

                BufferViews.Add(bufferView);
            }

            foreach (var accessorJSON in json.accessors)
            {
                GLBAccessor accessor = new GLBAccessor();

                accessor.BufferView    = BufferViews[(int)accessorJSON.bufferView];
                accessor.ComponentType = accessorJSON.componentType;
                accessor.Count         = accessorJSON.count;
                accessor.Type          = accessorJSON.type;

                Accessors.Add(accessor);
            }

            foreach (var imageJSON in json.images)
            {
                GLBImage image = new GLBImage();

                image.BufferView = BufferViews[(int)imageJSON.bufferView];
                image.MimeType   = imageJSON.mimeType;

                Images.Add(image);
            }

            foreach (var samplerJSON in json.samplers)
            {
                GLBSampler sampler = new GLBSampler();

                sampler.MinFilter = samplerJSON.minFilter;
                sampler.MagFilter = samplerJSON.magFilter;
                sampler.WrapS     = samplerJSON.wrapS;
                sampler.WrapT     = samplerJSON.wrapT;

                Samplers.Add(sampler);
            }

            foreach (var textureJSON in json.textures)
            {
                GLBTexture texture = new GLBTexture();

                texture.Source  = Images[(int)textureJSON.source];
                texture.Sampler = Samplers[(int)textureJSON.sampler];

                Textures.Add(texture);
            }

            foreach (var materialJSON in json.materials)
            {
                GLBMaterial material = new GLBMaterial();

                material.Name = materialJSON.name;

                Materials.Add(material);
            }

            foreach (var meshJSON in json.meshes)
            {
                GLBMesh mesh = new GLBMesh();

                mesh.Name = meshJSON.name;

                foreach (var primitiveJSON in meshJSON.primitives)
                {
                    GLBPrimitive primitive = new GLBPrimitive();

                    GLBAttributes attributes = new GLBAttributes();

                    attributes.Position = Accessors[(int)primitiveJSON.attributes.POSITION];
                    attributes.Normal   = Accessors[(int)primitiveJSON.attributes.NORMAL];

                    primitive.Attributes = attributes;
                    primitive.Indices    = Accessors[(int)primitiveJSON.indices];
                    primitive.Material   = Materials[(int)primitiveJSON.material];

                    mesh.Primitives.Add(primitive);
                }

                Meshes.Add(mesh);
            }
        }
예제 #23
0
        protected override void _Read(BinaryReader reader)
        {
            Offset = (uint)reader.BaseStream.Position;

            Identifier = reader.ReadUInt32();
            if (!IsValid(Identifier))
            {
                return;
            }

            Size            = reader.ReadUInt32();
            FirstNodeOffset = reader.ReadUInt32();
            TextureCount    = reader.ReadUInt32();

            //Read texture entries if there are any
            for (uint i = 0; i < TextureCount; i++)
            {
                TextureEntries.Add(new TextureEntry(reader));
            }
            foreach (TextureEntry entry in TextureEntries)
            {
                entry.ReadTextureID(reader);
            }

            //If we are not at the first node yet, we still have an node offset table to read
            if (reader.BaseStream.Position != FirstNodeOffset)
            {
                NodeOffsetTableSize = reader.ReadUInt32();
                for (int i = 0; i < NodeOffsetTableSize; i++)
                {
                    NodeOffsetTable.Add(reader.ReadUInt32());
                }
            }

            //Read first node and as an result create the whole node tree structure
            reader.BaseStream.Seek(Offset + FirstNodeOffset, SeekOrigin.Begin);
            RootNode = new MT7Node(reader, null);


            //Search for optional extra sections until EOF
            while (reader.BaseStream.Position < reader.BaseStream.Length - 4)
            {
                uint identifier = reader.ReadUInt32();
                if (FACE.IsValid(identifier))
                {
                    reader.BaseStream.Seek(-4, SeekOrigin.Current);
                    FACE = new FACE(reader);
                }
                else if (CLSG.IsValid(identifier))
                {
                    reader.BaseStream.Seek(-4, SeekOrigin.Current);
                    CLSG = new CLSG(reader);
                }
                else if (TXT7.IsValid(identifier))
                {
                    reader.BaseStream.Seek(-4, SeekOrigin.Current);
                    TXT7 = new TXT7(reader);
                }
            }

            //Filling the texture entries with the actual textures
            if (TXT7 != null)
            {
                foreach (TextureEntry entry in TextureEntries)
                {
                    entry.Texture = TXT7.GetTexture(entry.TextureID);
                }
            }

            if (SearchTexturesOneDirUp)
            {
                FileStream fileStream = (FileStream)reader.BaseStream;
                string     dir        = Path.GetDirectoryName(Path.GetDirectoryName(fileStream.Name));
                TextureDatabase.SearchDirectory(dir);
            }

            if (MT7.UseTextureDatabase)
            {
                foreach (TextureEntry entry in TextureEntries)
                {
                    if (entry.Texture != null)
                    {
                        continue;
                    }

                    TEXN texture = TextureDatabase.FindTexture(entry.TextureID.Data);
                    if (texture == null)
                    {
                        Console.WriteLine("Couldn't find texture: {0}", entry.TextureID.Name);
                        continue;
                    }
                    entry.Texture           = new Texture();
                    entry.Texture.TextureID = new TextureID(texture.TextureID);
                    entry.Texture.Image     = texture.Texture;
                }
            }


            //Populate base class textures
            foreach (TextureEntry entry in TextureEntries)
            {
                if (entry.Texture == null)
                {
                    entry.Texture           = new Texture();
                    entry.Texture.TextureID = entry.TextureID;
                }
                Textures.Add(entry.Texture);
            }

            //Resolve the textures in the faces
            RootNode.ResolveFaceTextures(Textures);
        }
예제 #24
0
        public void Read(Stream stream)
        {
            BinaryReader br;

            br = new BinaryReader(stream);
            HAMDataReader bm = new HAMDataReader();

            int sig = br.ReadInt32();

            if (sig != 0x214D4148)
            {
                br.Dispose();
                throw new InvalidDataException("HAMFile::Read: HAM file has bad header.");
            }
            Version = br.ReadInt32();
            if (Version < 2 || Version > 3)
            {
                br.Dispose();
                throw new InvalidDataException(string.Format("HAMFile::Read: HAM file has bad version. Got {0}, but expected \"2\" or \"3\"", Version));
            }
            int sndptr = 0;

            if (Version == 2)
            {
                sndptr = br.ReadInt32();
            }

            int NumBitmaps = br.ReadInt32();

            for (int x = 0; x < NumBitmaps; x++)
            {
                Textures.Add(br.ReadUInt16());
            }
            for (int x = 0; x < NumBitmaps; x++)
            {
                TMapInfo.Add(bm.ReadTMAPInfo(br));
                TMapInfo[x].ID = x;
            }

            int NumSounds = br.ReadInt32();

            if (NumSounds > 254)
            {
                throw new InvalidDataException("HAM file specifies more than 254 sounds.");
            }

            for (int x = 0; x < NumSounds; x++)
            {
                Sounds[x] = br.ReadByte();
            }
            for (int x = 0; x < NumSounds; x++)
            {
                AltSounds[x] = br.ReadByte();
            }

            int NumVClips = br.ReadInt32();

            for (int x = 0; x < NumVClips; x++)
            {
                VClips.Add(bm.ReadVClip(br));
                VClips[x].ID = x;
            }

            int NumEClips = br.ReadInt32();

            for (int x = 0; x < NumEClips; x++)
            {
                EClips.Add(bm.ReadEClip(br));
                EClips[x].ID = x;
            }

            int NumWallAnims = br.ReadInt32();

            for (int x = 0; x < NumWallAnims; x++)
            {
                WClips.Add(bm.ReadWClip(br));
            }

            int NumRobots = br.ReadInt32();

            for (int x = 0; x < NumRobots; x++)
            {
                Robots.Add(bm.ReadRobot(br));
                Robots[x].ID = x;
            }

            int NumLoadJoints = br.ReadInt32();

            for (int x = 0; x < NumLoadJoints; x++)
            {
                JointPos joint = new JointPos();
                joint.JointNum = br.ReadInt16();
                joint.Angles.P = br.ReadInt16();
                joint.Angles.B = br.ReadInt16();
                joint.Angles.H = br.ReadInt16();
                Joints.Add(joint);
            }

            int NumWeaponTypes = br.ReadInt32();

            for (int x = 0; x < NumWeaponTypes; x++)
            {
                if (Version >= 3)
                {
                    Weapons.Add(bm.ReadWeapon(br));
                }
                else
                {
                    Weapons.Add(bm.ReadWeaponInfoVersion2(br));
                }
                Weapons[x].ID = x;
            }

            int NumPowerups = br.ReadInt32();

            for (int x = 0; x < NumPowerups; x++)
            {
                Powerup powerup = new Powerup();
                powerup.VClipNum = br.ReadInt32();
                powerup.HitSound = br.ReadInt32();
                powerup.Size     = new Fix(br.ReadInt32());
                powerup.Light    = new Fix(br.ReadInt32());
                powerup.ID       = x;
                Powerups.Add(powerup);
            }

            int NumPolygonModels = br.ReadInt32();

            for (int x = 0; x < NumPolygonModels; x++)
            {
                Models.Add(bm.ReadPolymodelInfo(br));
                Models[x].ID = x;
            }

            for (int x = 0; x < NumPolygonModels; x++)
            {
                Models[x].InterpreterData = br.ReadBytes(Models[x].ModelIDTASize);
                //PolymodelData.Add(modeldata);
            }
            for (int x = 0; x < NumPolygonModels; x++)
            {
                Models[x].DyingModelnum = br.ReadInt32();
            }
            for (int x = 0; x < NumPolygonModels; x++)
            {
                Models[x].DeadModelnum = br.ReadInt32();
            }
            int gagueCount = br.ReadInt32();

            for (int x = 0; x < gagueCount; x++)
            {
                Gauges.Add(br.ReadUInt16());
            }
            for (int x = 0; x < gagueCount; x++)
            {
                GaugesHires.Add(br.ReadUInt16());
            }

            int bitmapCount = br.ReadInt32();

            for (int x = 0; x < bitmapCount; x++)
            {
                ObjBitmaps.Add(br.ReadUInt16());
            }
            ushort value;

            for (int x = 0; x < bitmapCount; x++)
            {
                value = br.ReadUInt16();
                if ((value + 1) > NumObjBitmaps)
                {
                    NumObjBitmaps = (value + 1);
                }
                ObjBitmapPointers.Add(value);
            }

            PlayerShip                   = new Ship();
            PlayerShip.ModelNum          = br.ReadInt32();
            PlayerShip.DeathVClipNum     = br.ReadInt32();
            PlayerShip.Mass              = new Fix(br.ReadInt32());
            PlayerShip.Drag              = new Fix(br.ReadInt32());
            PlayerShip.MaxThrust         = new Fix(br.ReadInt32());
            PlayerShip.ReverseThrust     = new Fix(br.ReadInt32());
            PlayerShip.Brakes            = new Fix(br.ReadInt32());
            PlayerShip.Wiggle            = new Fix(br.ReadInt32());
            PlayerShip.MaxRotationThrust = new Fix(br.ReadInt32());
            for (int x = 0; x < 8; x++)
            {
                PlayerShip.GunPoints[x] = FixVector.FromRawValues(br.ReadInt32(), br.ReadInt32(), br.ReadInt32());
            }

            int NumCockpits = br.ReadInt32();

            for (int x = 0; x < NumCockpits; x++)
            {
                Cockpits.Add(br.ReadUInt16());
            }
            //Build a table of all multiplayer bitmaps, to inject into the object bitmap table
            FirstMultiBitmapNum = br.ReadInt32();

            int NumReactors = br.ReadInt32();

            for (int x = 0; x < NumReactors; x++)
            {
                Reactor reactor = new Reactor();
                reactor.ModelNum = br.ReadInt32();
                reactor.NumGuns  = br.ReadInt32();
                for (int y = 0; y < 8; y++)
                {
                    reactor.GunPoints[y] = FixVector.FromRawValues(br.ReadInt32(), br.ReadInt32(), br.ReadInt32());
                }
                for (int y = 0; y < 8; y++)
                {
                    reactor.GunDirs[y] = FixVector.FromRawValues(br.ReadInt32(), br.ReadInt32(), br.ReadInt32());
                }
                Reactors.Add(reactor);
            }
            PlayerShip.MarkerModel = br.ReadInt32();
            //2620
            if (Version < 3)
            {
                ExitModelnum          = br.ReadInt32();
                DestroyedExitModelnum = br.ReadInt32();
            }
            for (int x = 0; x < 2620; x++)
            {
                try
                {
                    BitmapXLATData[x] = br.ReadUInt16();
                }
                catch (EndOfStreamException) //Descent 2's official HAM files have only 2600 XLAT entries, but later versions of the game attempt to read 2620.
                {
                    break;
                }
            }

            if (Version < 3)
            {
                br.BaseStream.Seek(sndptr, SeekOrigin.Begin);
                int dataToRead = (int)(br.BaseStream.Length - br.BaseStream.Position);
                sounddata = br.ReadBytes(dataToRead);
            }

            hasRead = true;
            //br.Dispose();
        }
예제 #25
0
 public void RequireTexture(string name) => Textures.Add(name);
예제 #26
0
        private void setTextures(IntermediateNode textureLibraryNode)
        {
            foreach (IntermediateNode textureNode in textureLibraryNode)
            {
                LeafNode child     = null;
                bool     isTexture = true;
                bool     isTgaMips = false;
                if (textureNode.Count == 1)
                {
                    child = textureNode[0] as LeafNode;
                }
                else
                {
                    //TODO: Mipmapping
                    foreach (var node in textureNode)
                    {
                        var n = node.Name.ToLowerInvariant().Trim();
                        if (n == "mip0")
                        {
                            child     = node as LeafNode;
                            isTgaMips = true;
                        }
                        if (n == "mips")
                        {
                            child     = node as LeafNode;
                            isTgaMips = false;
                            break;
                        }
                        if (n == "fps")
                        {
                            isTexture = false;
                            break;
                        }
                    }
                }
                if (isTexture)
                {
                    if (child == null)
                    {
                        throw new Exception("Invalid texture library");
                    }

                    TextureData data = new TextureData(child, textureNode.Name, isTgaMips);
                    if (isTgaMips)
                    {
                        foreach (var node in textureNode)
                        {
                            data.SetLevel(node);
                        }
                    }
                    if (data == null)
                    {
                        throw new Exception("Invalid texture library");
                    }

                    string key = textureNode.Name;
                    if (Textures.ContainsKey(key))
                    {
                        FLLog.Error("Txm", "Duplicate texture " + key + " in texture library");
                    }
                    else
                    {
                        Textures.Add(key, data);
                    }
                }
                else
                {
                    Animations.Add(textureNode.Name, new TexFrameAnimation(textureNode));
                }
            }
        }
예제 #27
0
        //---------------------------------------------------------------------
        // READING
        //---------------------------------------------------------------------

        /// <summary>
        /// Converts all the base file's data classes into the editor class for that type.
        /// </summary>
        public void CreateLocalLists()
        {
            //TODO: This is just passthrough for now, need "editor" classes
            foreach (ushort texture in BaseFile.Textures)
            {
                Textures.Add(texture);
            }
            foreach (TMAPInfo tmapInfo in BaseFile.TMapInfo)
            {
                TMapInfo.Add(tmapInfo);
            }

            Array.Copy(BaseFile.Sounds, Sounds, 254);
            Array.Copy(BaseFile.AltSounds, AltSounds, 254);

            foreach (VClip clip in BaseFile.VClips)
            {
                VClips.Add(clip);
            }
            foreach (EClip clip in BaseFile.EClips)
            {
                EClips.Add(clip);
            }
            foreach (WClip clip in BaseFile.WClips)
            {
                WClips.Add(clip);
            }
            foreach (Robot robot in BaseFile.Robots)
            {
                Robots.Add(robot);
            }
            foreach (JointPos joint in BaseFile.Joints)
            {
                Joints.Add(joint);
            }
            foreach (Weapon weapon in BaseFile.Weapons)
            {
                Weapons.Add(weapon);
            }
            foreach (Polymodel model in BaseFile.Models)
            {
                Models.Add(model);
            }
            foreach (ushort gauge in BaseFile.Gauges)
            {
                Gauges.Add(gauge);
            }
            foreach (ushort gauge in BaseFile.GaugesHires)
            {
                GaugesHires.Add(gauge);
            }
            PlayerShip = BaseFile.PlayerShip;
            foreach (ushort cockpit in BaseFile.Cockpits)
            {
                Cockpits.Add(cockpit);
            }
            foreach (Reactor reactor in BaseFile.Reactors)
            {
                Reactors.Add(reactor);
            }
            foreach (Powerup powerup in BaseFile.Powerups)
            {
                Powerups.Add(powerup);
            }
            FirstMultiBitmapNum = BaseFile.FirstMultiBitmapNum;
            for (int i = 0; i < 2620; i++)
            {
                BitmapXLATData[i] = BaseFile.BitmapXLATData[i];
            }
            foreach (ushort bm in BaseFile.ObjBitmaps)
            {
                ObjBitmaps.Add(bm);
            }
            foreach (ushort bm in BaseFile.ObjBitmapPointers)
            {
                ObjBitmapPointers.Add(bm);
            }
        }
예제 #28
0
        private void Read(BinaryReader br)
        {
            Header = new Header
            {
                Version = (Version)br.ReadInt32(),
                Lumps   = new Lump[Lump.NumLumps]
            };

            if (Header.Version != Version.Goldsource)
            {
                throw new NotSupportedException("Only Goldsource (v30) BSP files are supported.");
            }

            for (var i = 0; i < Header.Lumps.Length; i++)
            {
                Header.Lumps[i] = new Lump
                {
                    Offset = br.ReadInt32(),
                    Length = br.ReadInt32()
                };
            }

            // Entities
            var lump = Header.Lumps[Lump.Entities];

            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            EntityBlock = Encoding.ASCII.GetString(br.ReadBytes(lump.Length));

            // Planes
            lump = Header.Lumps[Lump.Planes];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            while (br.BaseStream.Position < lump.Offset + lump.Length)
            {
                Planes.Add(new Plane
                {
                    Normal   = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()),
                    Distance = br.ReadSingle(),
                    Type     = br.ReadInt32()
                });
            }

            // Textures
            lump = Header.Lumps[Lump.Textures];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);

            var numTextures = br.ReadUInt32();
            var offsets     = new int[numTextures];

            for (var i = 0; i < numTextures; i++)
            {
                offsets[i] = br.ReadInt32();
            }
            foreach (var offset in offsets)
            {
                br.BaseStream.Seek(lump.Offset + offset, SeekOrigin.Begin);
                var tex = Wad.WadFile.ReadMipTexture(br);
                Textures.Add(tex);
            }

            // Vertices
            lump = Header.Lumps[Lump.Vertices];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            while (br.BaseStream.Position < lump.Offset + lump.Length)
            {
                Vertices.Add(new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()));
            }

            // Visibility
            lump = Header.Lumps[Lump.Visibility];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            VisData = br.ReadBytes(lump.Length);
            //TODO: decompress vis data

            // Nodes
            lump = Header.Lumps[Lump.Nodes];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            while (br.BaseStream.Position < lump.Offset + lump.Length)
            {
                var node = new Node
                {
                    Plane    = br.ReadUInt32(),
                    Children = new short[2],
                    Mins     = new short[3],
                    Maxs     = new short[3]
                };
                for (var i = 0; i < 2; i++)
                {
                    node.Children[i] = br.ReadInt16();
                }
                for (var i = 0; i < 3; i++)
                {
                    node.Mins[i] = br.ReadInt16();
                }
                for (var i = 0; i < 3; i++)
                {
                    node.Maxs[i] = br.ReadInt16();
                }
                node.FirstFace = br.ReadUInt16();
                node.NumFaces  = br.ReadUInt16();
                Nodes.Add(node);
            }

            // Texinfo
            lump = Header.Lumps[Lump.Texinfo];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            while (br.BaseStream.Position < lump.Offset + lump.Length)
            {
                var info = new TextureInfo
                {
                    S          = new Vector4(br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle()),
                    T          = new Vector4(br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle()),
                    MipTexture = br.ReadInt32(),
                    Flags      = br.ReadInt32()
                };
                TextureInfos.Add(info);
            }

            // Faces
            lump = Header.Lumps[Lump.Faces];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            while (br.BaseStream.Position < lump.Offset + lump.Length)
            {
                var face = new Face
                {
                    Plane          = br.ReadInt16(),
                    Side           = br.ReadInt16(),
                    FirstEdge      = br.ReadInt32(),
                    NumEdges       = br.ReadInt16(),
                    TextureInfo    = br.ReadInt16(),
                    Styles         = br.ReadBytes(Face.MaxLightmaps),
                    LightmapOffset = br.ReadInt32()
                };
                Faces.Add(face);
            }

            // Lighting
            lump = Header.Lumps[Lump.Lighting];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            Lightmap = br.ReadBytes(lump.Length);

            // Clipnodes
            lump = Header.Lumps[Lump.Clipnodes];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            while (br.BaseStream.Position < lump.Offset + lump.Length)
            {
                var clip = new Clipnode
                {
                    Plane    = br.ReadInt32(),
                    Children = new[] { br.ReadInt16(), br.ReadInt16() }
                };
                Clipnodes.Add(clip);
            }

            // Leaves
            lump = Header.Lumps[Lump.Leaves];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            while (br.BaseStream.Position < lump.Offset + lump.Length)
            {
                var leaf = new Leaf
                {
                    Contents         = (Contents)br.ReadInt32(),
                    VisOffset        = br.ReadInt32(),
                    Mins             = new [] { br.ReadInt16(), br.ReadInt16(), br.ReadInt16() },
                    Maxs             = new [] { br.ReadInt16(), br.ReadInt16(), br.ReadInt16() },
                    FirstMarkSurface = br.ReadUInt16(),
                    NumMarkSurfaces  = br.ReadUInt16(),
                    AmbientLevels    = br.ReadBytes(Leaf.MaxNumAmbientLevels)
                };
                Leaves.Add(leaf);
            }

            // Marksurfaces
            lump = Header.Lumps[Lump.Marksurfaces];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            MarkSurfaces = new ushort[lump.Length / sizeof(ushort)];
            for (var i = 0; i < MarkSurfaces.Length; i++)
            {
                MarkSurfaces[i] = br.ReadUInt16();
            }

            // Edges
            lump = Header.Lumps[Lump.Edges];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            while (br.BaseStream.Position < lump.Offset + lump.Length)
            {
                var edge = new Edge
                {
                    Start = br.ReadUInt16(),
                    End   = br.ReadUInt16()
                };
                Edges.Add(edge);
            }

            // Surfedges
            lump = Header.Lumps[Lump.Surfedges];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            SurfaceEdges = new int[lump.Length / sizeof(int)];
            for (var i = 0; i < SurfaceEdges.Length; i++)
            {
                SurfaceEdges[i] = br.ReadInt32();
            }

            // Models
            lump = Header.Lumps[Lump.Models];
            br.BaseStream.Seek(lump.Offset, SeekOrigin.Begin);
            while (br.BaseStream.Position < lump.Offset + lump.Length)
            {
                var model = new Model
                {
                    Mins      = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()),
                    Maxs      = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()),
                    Origin    = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()),
                    HeadNodes = new [] { br.ReadInt32(), br.ReadInt32(), br.ReadInt32(), br.ReadInt32() },
                    VisLeaves = br.ReadInt32(),
                    FirstFace = br.ReadInt32(),
                    NumFaces  = br.ReadInt32()
                };
                Models.Add(model);
            }

            ParseEntities();
        }
예제 #29
0
 // AddTexture
 public void AddTexture(string name, ref Vector2 puv, ref Vector2 suv)
 {
     Textures.Add(new SpriteTexture(name, ref puv, ref suv));
 }
예제 #30
0
        public void Load(bool loadEmpty = false)
        {
            if (!m_HasInited)
            {
                Debug.LogError("TextureIndex needs to be Initialized first!");
                return;
            }

            if (loadEmpty)
            {
                return;
            }

            List <Texture2D> atlasTextures = new List <Texture2D>();

            atlasTextures.AddRange(m_NormalTextures);

            if (m_ConnectedTextures.Count != 0)
            {
                atlasTextures.AddRange(ConnectedTextures.GenerateConnectedTextures(m_ConnectedTextures));
            }

            m_Atlas = new Texture2D(8192, 8192)
            {
                filterMode = FilterMode.Point
            };

            Rect[] rects = m_Atlas.PackTextures(atlasTextures.ToArray(), 0, 8192, false);

            for (int i = 0; i < atlasTextures.Count; i++)
            {
                if (!atlasTextures[i])
                {
                    continue;
                }

                string[] fileName = atlasTextures[i].name.ToString().Split('-');
                Rect     texture  = rects[i];

                string textureName          = fileName[0];
                int    connectedTextureType = -1;

                for (int n = 0; n < fileName.Length; n++)
                {
                    switch (fileName[n][0])
                    {
                    case 'c':
                        int.TryParse(fileName[n].Substring(1), out connectedTextureType);
                        break;

                    default:
                        break;
                    }
                }

                TextureCollection collection;
                if (!Textures.TryGetValue(textureName, out collection))
                {
                    collection = new TextureCollection(textureName);
                    Textures.Add(textureName, collection);
                }

                collection.AddTexture(texture, connectedTextureType);
            }
        }
예제 #31
0
 public void AddTexture(string name, float pu, float pv, float su, float sv)
 {
     Textures.Add(new SpriteTexture(name, pu, pv, su, sv));
 }