/// <summary>
        /// Loads a Daggerfall texture as a billboard.
        /// </summary>
        /// <param name="archive">Texture archive.</param>
        /// <param name="record">Texture record.</param>
        /// <param name="flat">Flat data.</param>
        public void LoadBillboard(DaggerfallBlockComponent.BlockFlat flat)
        {
            // Get path to texture file
            string path = Path.Combine(
                core.MaterialManager.Arena2Path,
                TextureFile.IndexToFileName(flat.Archive));

            // Get size and scale of this texture
            System.Drawing.Size size  = TextureFile.QuickSize(path, flat.Record);
            System.Drawing.Size scale = TextureFile.QuickScale(path, flat.Record);

            // Set start size
            Vector2 startSize;

            startSize.X = size.Width;
            startSize.Y = size.Height;

            // Apply scale
            Vector2 finalSize;
            int     xChange = (int)(size.Width * (scale.Width / BlocksFile.ScaleDivisor));
            int     yChange = (int)(size.Height * (scale.Height / BlocksFile.ScaleDivisor));

            finalSize.X = (size.Width + xChange);
            finalSize.Y = (size.Height + yChange);
            finalSize  *= ModelManager.GlobalScale;

            // Load material
            this.material = core.MaterialManager.CreateDaggerfallMaterialEffect(
                flat.Archive,
                flat.Record,
                null,
                MaterialManager.DefaultBillboardFlags);

            // Save settings
            this.size = finalSize;

            // Calcuate offset for correct positioning in scene
            if (flat.Dungeon)
            {
                this.offset = Vector3.Zero;
            }
            else
            {
                this.offset = new Vector3(0, (finalSize.Y / 2) - (4 * ModelManager.GlobalScale), 0);
            }

            // Set bounding sphere
            BoundingSphere sphere;

            sphere.Center = Vector3.Zero;
            if (finalSize.X > finalSize.Y)
            {
                sphere.Radius = finalSize.X / 2;
            }
            else
            {
                sphere.Radius = finalSize.Y / 2;
            }
            this.BoundingSphere = sphere;
        }
Пример #2
0
        public static Texture2D BytesToTexture(byte[] bytes)
        {
            var memStream = new MemoryStream();

            memStream.Write(bytes, 0, bytes.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            TextureFile t = new TextureFile();

            t.ToTextureFile(ref memStream);
            string newPath = AppDomain.CurrentDomain.BaseDirectory + Game1.self.Content.RootDirectory + "\\TempSkins\\" + t.fileName;

            newPath = t.fileName;
            var store = IsolatedStorageFile.GetUserStoreForApplication();
            var fs    = store.CreateFile(newPath);

            fs.Write(t.data, 0, t.dataLength);
            fs.Close();
            var fs2 = store.OpenFile(newPath, FileMode.Open);
            //FileStream fileStream = new FileStream(newPath, FileMode.Open);
            Texture2D texture = null;

            try
            {
                texture = Texture2D.FromStream(Game1.self.GraphicsDevice, fs2);
            }
            catch { }

            //fileStream.Close();
            //fileStream.Dispose();
            store.DeleteFile(newPath);
            store.Close();
            memStream.Close();
            memStream.Dispose();
            return(texture);
        }
Пример #3
0
        public static byte[] GetRawTextureBytes(TextureFile texFile, AssetsFileInstance inst)
        {
            string rootPath = Path.GetDirectoryName(inst.path);

            if (texFile.m_StreamData.size != 0 && texFile.m_StreamData.path != string.Empty)
            {
                string fixedStreamPath = texFile.m_StreamData.path;
                if (!Path.IsPathRooted(fixedStreamPath) && rootPath != null)
                {
                    fixedStreamPath = Path.Combine(rootPath, fixedStreamPath);
                }
                if (File.Exists(fixedStreamPath))
                {
                    Stream stream = File.OpenRead(fixedStreamPath);
                    stream.Position     = texFile.m_StreamData.offset;
                    texFile.pictureData = new byte[texFile.m_StreamData.size];
                    stream.Read(texFile.pictureData, 0, (int)texFile.m_StreamData.size);
                }
                else
                {
                    return(null);
                }
            }
            return(texFile.pictureData);
        }
Пример #4
0
        public EditTextureDialog(TextureFile tex, AssetTypeValueField texField)
        {
            InitializeComponent();
            this.tex      = tex;
            this.texField = texField;
            imgBytes      = null;

            var formats = Enum.GetValues(typeof(TextureFormat));

            foreach (var format in formats)
            {
                cboxTextureFormat.Items.Add(format);
            }

            tboxTextureName.Text            = tex.m_Name;
            cboxTextureFormat.SelectedIndex = tex.m_TextureFormat - 1;
            chboxHasMipMaps.Checked         = tex.m_MipMap;
            chboxIsReadable.Checked         = tex.m_IsReadable;
            cboxFilterMode.SelectedIndex    = tex.m_TextureSettings.m_FilterMode;
            tboxAniso.Text               = tex.m_TextureSettings.m_Aniso.ToString();
            tboxMipMapBias.Text          = tex.m_TextureSettings.m_MipBias.ToString(CultureInfo.CurrentCulture);
            cboxWrapU.SelectedIndex      = tex.m_TextureSettings.m_WrapU;
            cboxWrapV.SelectedIndex      = tex.m_TextureSettings.m_WrapV;
            tboxLightmapFormat.Text      = tex.m_LightmapFormat.ToString();
            cboxColorSpace.SelectedIndex = tex.m_ColorSpace;
        }
        private void ShowMeshTextures()
        {
            // Clear texture flow panel
            TexturesPanel.Controls.Clear();

            // Get the mesh data
            DFMesh mesh = arch3dFile.GetMesh(MeshIndexTrackBar.Value);

            // Loop through all submeshes
            foreach (DFMesh.DFSubMesh sm in mesh.SubMeshes)
            {
                // Load texture file
                string FileName = TextureFile.IndexToFileName(sm.TextureArchive);
                MyImageFileReader.LoadFile(FileName);

                // Get texture file
                DFImageFile textureFile = MyImageFileReader.ImageFile;

                // Get managed bitmap
                Bitmap bm = textureFile.GetManagedBitmap(sm.TextureRecord, 0, true, false);

                // Create a new picture box
                PictureBox pb = new PictureBox();
                pb.Width  = bm.Width;
                pb.Height = bm.Height;
                pb.Image  = bm;

                // Add picture box to flow panel
                TexturesPanel.Controls.Add(pb);
            }
        }
Пример #6
0
        public TextureViewer(AssetsFileInstance inst, AssetTypeValueField baseField)
        {
            InitializeComponent();

            loaded = false;
            TextureFile tf = TextureFile.ReadTextureFile(baseField);

            byte[] texDat = tf.GetTextureData(inst);
            if (texDat != null && texDat.Length > 0)
            {
                string fmtName = ((TextureFormat)tf.m_TextureFormat).ToString().Replace("_", " ");
                Text = $"Texture Viewer [{fmtName}]";

                image = new Bitmap(tf.m_Width, tf.m_Height, tf.m_Width * 4, PixelFormat.Format32bppArgb,
                                   Marshal.UnsafeAddrOfPinnedArrayElement(texDat, 0));
                image.RotateFlip(RotateFlipType.RotateNoneFlipY);

                x         = -image.Width / 2;
                y         = -image.Height / 2;
                width     = image.Width;
                height    = image.Height;
                sc        = 1f;
                mouseDown = false;

                DoubleBuffered = true;
                ClientSize     = new Size(width, height);

                loaded = true;
            }
        }
        /// <summary>
        /// Helper to get interior parts of cloak.
        /// This is not cached as only seen on paper doll during refresh.
        /// </summary>
        /// <param name="item">Item - must be a formal or casual cloak.</param>
        /// <returns>ImageData.</returns>
        public ImageData GetCloakInteriorImage(DaggerfallUnityItem item)
        {
            // Must be a formal or casual cloak
            if (!IsCloak(item))
            {
                return(new ImageData());
            }

            // Get colour
            int color = (int)item.dyeColor;

            // Cloak interior source is combination of player texture archive index and template record index
            int archive = item.InventoryTextureArchive;
            int record  = item.ItemTemplate.playerTextureRecord;

            // Load image data
            string    filename = TextureFile.IndexToFileName(archive);
            ImageData data     = ImageReader.GetImageData(filename, record, 0, true, false);

            if (data.type == ImageTypes.None)
            {
                throw new Exception("GetCloakBackImage() could not load image data.");
            }

            // Change dye
            data = ChangeDye(data, (DyeColors)color, DyeTargets.Clothing);

            return(data);
        }
Пример #8
0
        public static Texture2D BytesToTexture(byte[] bytes)
        {
            var memStream = new MemoryStream();

            memStream.Write(bytes, 0, bytes.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            TextureFile t = new TextureFile();

            t.ToTextureFile(ref memStream);
            string     newPath = AppDomain.CurrentDomain.BaseDirectory + Game1.self.Content.RootDirectory + "\\TempSkins\\" + t.fileName;
            FileStream fs      = new FileStream(newPath, FileMode.Create);

            fs.Write(t.data, 0, t.data.Length);
            fs.Close();
            fs.Dispose();
            Image image = Image.FromFile(newPath);

            image.Save(newPath + ".png", ImageFormat.Png);
            image.Dispose();
            FileStream fileStream = new FileStream(newPath + ".png", FileMode.Open);
            Texture2D  texture    = null;

            try
            {
                texture = Texture2D.FromStream(Game1.self.GraphicsDevice, fileStream);
            }
            catch { } //Todo when file is incorrect even though having proper format (probably size thing)
            fileStream.Close();
            fileStream.Dispose();
            File.Delete(newPath);
            File.Delete(newPath + ".png");
            memStream.Close();
            memStream.Dispose();
            return(texture);
        }
        /// <summary>
        /// Precalculate and cache billboard scale for every record.
        /// This will change based on animation state and orientation.
        /// Cache this to array so it only needs to be calculated once.
        /// Also store number of frames for state animations.
        /// </summary>
        /// <param name="dfUnity">DaggerfallUnity singleton. Required for content readers and settings.</param>
        /// <param name="archive">Texture archive index derived from type and gender.</param>
        private void CacheRecordSizesAndFrames(DaggerfallUnity dfUnity, int archive)
        {
            // Open texture file
            string      path        = Path.Combine(dfUnity.Arena2Path, TextureFile.IndexToFileName(archive));
            TextureFile textureFile = new TextureFile(path, FileUsage.UseMemory, true);

            // Cache size and scale for each record
            summary.RecordSizes  = new Vector2[textureFile.RecordCount];
            summary.RecordFrames = new int[textureFile.RecordCount];
            for (int i = 0; i < textureFile.RecordCount; i++)
            {
                // Get size and scale of this texture
                DFSize size  = textureFile.GetSize(i);
                DFSize scale = textureFile.GetScale(i);

                // Set start size
                Vector2 startSize;
                startSize.x = size.Width;
                startSize.y = size.Height;

                // Apply scale
                Vector2 finalSize;
                int     xChange = (int)(size.Width * (scale.Width / BlocksFile.ScaleDivisor));
                int     yChange = (int)(size.Height * (scale.Height / BlocksFile.ScaleDivisor));
                finalSize.x = (size.Width + xChange);
                finalSize.y = (size.Height + yChange);

                // Set optional scale
                TextureReplacement.SetBillboardScale(archive, i, ref finalSize);

                // Store final size and frame count
                summary.RecordSizes[i]  = finalSize * MeshReader.GlobalScale;
                summary.RecordFrames[i] = textureFile.GetFrameCount(i);
            }
        }
Пример #10
0
        protected override void SaveAndClose(EditorForm form, TextureFile textureFile, File file)
        {
            using (new WaitCursor(form))
            {
                var resourceFile = new ResourceFile();
                using (var ms = new MemoryStream(file.GetData()))
                {
                    resourceFile.Read(ms);
                }

                var msSystem = new MemoryStream(resourceFile.SystemMemData);
                var msGraphics = new MemoryStream(resourceFile.GraphicsMemData);

                try
                {
                    textureFile.Save(msSystem, msGraphics);
                }
                finally
                {
                    msSystem.Close();
                    msGraphics.Close();
                }

                using (var resMS = new MemoryStream())
                {
                    resourceFile.Write(resMS);
                    file.SetData(resMS.ToArray());
                }
            }

            form.Close();

        }
Пример #11
0
        /// <summary>
        /// Initialize predefined textures<para/>
        /// Инициализация предзаданных текстур
        /// </summary>
        public static void Init()
        {
            // Checking for extensions
            // Проверка расширений
            CompressionSupported = GLExtensions.Supported("GL_EXT_Texture_Compression_S3TC");
            FrameBufferSupported = GLExtensions.Supported("GL_ARB_Framebuffer_Object");

            // Load DAT-defined texture dictionaries
            // Загрузка предопределенных архивов текстур
            foreach (string TXD in FileManager.TextureFiles)
            {
                string      name = Path.GetFileNameWithoutExtension(TXD).ToLower();
                string      path = PathManager.GetAbsolute(TXD);
                TextureFile f    = new TextureFile(path, true);
                CachedFiles.TryAdd(name, f);
                TextureDictionary td = new TextureDictionary(f, true, true);
                Cached.TryAdd(name, td);
            }

            // Starting TextureFile thread
            // Запуск потока чтения TextureFile
            fileReaderThread = new Thread(FileLoaderProcess);
            fileReaderThread.IsBackground = true;
            fileReaderThread.Priority     = ThreadPriority.BelowNormal;
            fileReaderThread.Start();

            // Starting model builder thread
            // Запуск потока постройки Model
            textureBuilderThread = new Thread(TextureBuilderProcess);
            textureBuilderThread.IsBackground = true;
            textureBuilderThread.Priority     = ThreadPriority.BelowNormal;
            textureBuilderThread.Start();
        }
        /// <summary>
        /// Loads a Daggerfall flat (billboard).
        /// </summary>
        /// <param name="textureArchive">Texture archive index.</param>
        /// <param name="textureRecord">Texture record index.</param>
        /// <param name="textureFlags">Texture create flags.</param>
        /// <param name="material">Material.</param>
        /// <param name="startSize">Start size before scaling.</param>
        /// <param name="finalSize">Final size after scaling.</param>
        private void LoadDaggerfallFlat(
            int textureArchive,
            int textureRecord,
            MaterialManager.TextureCreateFlags textureFlags,
            out BaseMaterialEffect material,
            out Vector2 startSize,
            out Vector2 finalSize)
        {
            // Get path to texture file
            string path = Path.Combine(
                core.MaterialManager.Arena2Path,
                TextureFile.IndexToFileName(textureArchive));

            // Get size and scale of this texture
            System.Drawing.Size size  = TextureFile.QuickSize(path, textureRecord);
            System.Drawing.Size scale = TextureFile.QuickScale(path, textureRecord);

            // Set start size
            startSize.X = size.Width;
            startSize.Y = size.Height;

            // Apply scale
            int xChange = (int)(size.Width * (scale.Width / BlocksFile.ScaleDivisor));
            int yChange = (int)(size.Height * (scale.Height / BlocksFile.ScaleDivisor));

            finalSize.X = size.Width + xChange;
            finalSize.Y = size.Height + yChange;

            // Load material
            material = core.MaterialManager.CreateDaggerfallMaterialEffect(
                textureArchive,
                textureRecord,
                renderBillboards,
                MaterialManager.DefaultBillboardFlags);
        }
        /// <summary>
        /// Gets Unity Texture2D from Daggerfall texture with more options.
        /// </summary>
        /// <param name="archive">Archive index.</param>
        /// <param name="record">Record index.</param>
        /// <param name="frame">Frame index.</param>
        /// <param name="alphaIndex">Index to receive transparent alpha.</param>
        /// <param name="rectOut">Receives UV rect for texture inside border.</param>
        /// <param name="border">Number of pixels border to add around image.</param>
        /// <param name="dilate">Blend texture into surrounding empty pixels. Requires border.</param>
        /// <param name="copyToOppositeBorder">Copy texture edges to opposite border. Requires border, will overwrite dilate.</param>
        /// <returns>Texture2D or null.</returns>
        public Texture2D GetTexture2D(
            int archive,
            int record,
            int frame,
            int alphaIndex,
            out Rect rectOut,
            int border  = 0,
            bool dilate = false,
            bool copyToOppositeBorder = false,
            bool makeNoLongerReadable = true)
        {
            // Ready check
            if (!ReadyCheck())
            {
                rectOut = new Rect();
                return(null);
            }

            // Load texture file
            textureFile.Load(Path.Combine(Arena2Path, TextureFile.IndexToFileName(archive)), FileUsage.UseMemory, true);

            // Get Color32 array
            DFSize sz;

            Color32[] colors = textureFile.GetColors32(record, frame, alphaIndex, border, out sz);

            // Dilate edges
            if (border > 0 && dilate && !copyToOppositeBorder)
            {
                ImageProcessing.DilateColors(ref colors, sz);
            }

            // Copy to opposite border
            if (border > 0 && copyToOppositeBorder)
            {
                ImageProcessing.WrapBorder(ref colors, sz, border);
            }

            // Create Texture2D
            Texture2D texture;

            if (alphaIndex < 0)
            {
                texture = new Texture2D(sz.Width, sz.Height, TextureFormat.RGB24, MipMaps);
            }
            else
            {
                texture = new Texture2D(sz.Width, sz.Height, TextureFormat.RGBA32, MipMaps);
            }
            texture.SetPixels32(colors);
            texture.Apply(true, makeNoLongerReadable);

            // Shrink UV rect to compensate for internal border
            float ru = 1f / sz.Width;
            float rv = 1f / sz.Height;

            rectOut = new Rect(border * ru, border * rv, (sz.Width - border * 2) * ru, (sz.Height - border * 2) * rv);

            return(texture);
        }
Пример #14
0
        protected override void SaveAndClose(EditorForm form, TextureFile textureFile, File file)
        {
            using (new WaitCursor(form))
            {
                var resourceFile = new ResourceFile();
                using (var ms = new MemoryStream(file.GetData()))
                {
                    resourceFile.Read(ms);
                }

                var msSystem   = new MemoryStream(resourceFile.SystemMemData);
                var msGraphics = new MemoryStream(resourceFile.GraphicsMemData);

                try
                {
                    textureFile.Save(msSystem, msGraphics);
                }
                finally
                {
                    msSystem.Close();
                    msGraphics.Close();
                }

                using (var resMS = new MemoryStream())
                {
                    resourceFile.Write(resMS);
                    file.SetData(resMS.ToArray());
                }
            }

            form.Close();
        }
Пример #15
0
        /// <summary>
        /// Gets terrain albedo texture array containing each terrain tile in a seperate array slice.
        /// </summary>
        /// <param name="archive">Archive index.</param>
        /// <param name="stayReadable">Texture should stay readable.</param>
        /// <param name="nonAlphaFormat">Non-alpha TextureFormat.</param>
        /// <returns>Texture2DArray or null</returns>
        public Texture2DArray GetTerrainAlbedoTextureArray(
            int archive,
            bool stayReadable = false,
            SupportedNonAlphaTextureFormats nonAlphaFormat = SupportedNonAlphaTextureFormats.RGB24)
        {
            // Load texture file and check count matches terrain tiles
            TextureFile textureFile = new TextureFile(Path.Combine(Arena2Path, TextureFile.IndexToFileName(archive)), FileUsage.UseMemory, true);
            int         numSlices   = 0;

            if (textureFile.RecordCount == 56)
            {
                numSlices = textureFile.RecordCount;
            }
            else
            {
                return(null);
            }

            Texture2DArray textureArray;

            if (TextureReplacement.CustomTextureExist(archive, 0, 0))
            {
                Texture2D albedoMap = TextureReplacement.LoadCustomTexture(archive, 0, 0);
                textureArray = new Texture2DArray(albedoMap.width, albedoMap.height, numSlices, ParseTextureFormat(nonAlphaFormat), MipMaps);
            }
            else
            {
                textureArray = new Texture2DArray(textureFile.GetWidth(0), textureFile.GetWidth(1), numSlices, ParseTextureFormat(nonAlphaFormat), MipMaps);
            }

            // Rollout tiles into texture array
            for (int record = 0; record < textureFile.RecordCount; record++)
            {
                Color32[] albedo;

                if (TextureReplacement.CustomTextureExist(archive, record, 0))
                {
                    // Import custom texture
                    Texture2D albedoMap = TextureReplacement.LoadCustomTexture(archive, record, 0);
                    albedo = albedoMap.GetPixels32();
                }
                else
                {
                    // Create base image with gutter
                    DFSize sz;
                    albedo = textureFile.GetColor32(record, 0, -1, 0, out sz);
                }

                // Insert into texture array
                textureArray.SetPixels32(albedo, record, 0);
            }
            textureArray.Apply(true, !stayReadable);

            // Change settings for these textures
            textureArray.wrapMode   = TextureWrapMode.Clamp;
            textureArray.anisoLevel = 8;

            return(textureArray);
        }
Пример #16
0
        protected override void Modify(AssetTypeValueField baseField)
        {
            TextureFile texture = TextureFile.ReadTextureFile(baseField);

            GetNewTextureData(out byte[] bgra, out int width, out int height);
            SetTextureData(texture, bgra, width, height);
            texture.WriteTo(baseField);
        }
Пример #17
0
 private void DisplayAboutGUI()
 {
     EditorGUILayout.Space();
     ShowAboutBillboardFoldout = GUILayoutHelper.Foldout(ShowAboutBillboardFoldout, new GUIContent("About"), () =>
     {
         GUILayoutHelper.Indent(() =>
         {
             GUILayoutHelper.Horizontal(() =>
             {
                 EditorGUILayout.LabelField("File", GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                 EditorGUILayout.SelectableLabel(TextureFile.IndexToFileName(dfBillboard.Summary.Archive), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
             });
             GUILayoutHelper.Horizontal(() =>
             {
                 EditorGUILayout.LabelField("Index", GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                 EditorGUILayout.SelectableLabel(dfBillboard.Summary.Record.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
             });
             GUILayoutHelper.Horizontal(() =>
             {
                 EditorGUILayout.LabelField("In Dungeon", GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                 EditorGUILayout.SelectableLabel(dfBillboard.Summary.InDungeon.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
             });
             GUILayoutHelper.Horizontal(() =>
             {
                 EditorGUILayout.LabelField("Is Mobile", GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                 EditorGUILayout.SelectableLabel(dfBillboard.Summary.IsMobile.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
             });
             if (dfBillboard.Summary.InDungeon && dfBillboard.Summary.IsMobile)
             {
                 GUILayoutHelper.Horizontal(() =>
                 {
                     EditorGUILayout.LabelField("Gender", GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                     EditorGUILayout.SelectableLabel(((DFBlock.RdbFlatGenders)(dfBillboard.Summary.Gender)).ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
                 });
                 GUILayoutHelper.Horizontal(() =>
                 {
                     EditorGUILayout.LabelField("Type", GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                     EditorGUILayout.SelectableLabel(dfBillboard.Summary.FixedEnemyType.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
                 });
             }
             GUILayoutHelper.Horizontal(() =>
             {
                 EditorGUILayout.LabelField("Is Atlased", GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                 EditorGUILayout.SelectableLabel(dfBillboard.Summary.AtlasedMaterial.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
             });
             GUILayoutHelper.Horizontal(() =>
             {
                 EditorGUILayout.LabelField("Is Animated", GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                 EditorGUILayout.SelectableLabel(dfBillboard.Summary.AnimatedMaterial.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
             });
             GUILayoutHelper.Horizontal(() =>
             {
                 EditorGUILayout.LabelField("Current Frame", GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                 EditorGUILayout.SelectableLabel(dfBillboard.Summary.CurrentFrame.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
             });
         });
     });
 }
Пример #18
0
        public async Task <bool> SingleExport(Window win, AssetWorkspace workspace, List <AssetContainer> selection)
        {
            AssetContainer cont = selection[0];

            AssetTypeValueField texBaseField = TextureHelper.GetByteArrayTexture(workspace, cont).GetBaseField();
            TextureFile         texFile      = TextureFile.ReadTextureFile(texBaseField);
            SaveFileDialog      sfd          = new SaveFileDialog();

            sfd.Title   = "Save texture";
            sfd.Filters = new List <FileDialogFilter>()
            {
                new FileDialogFilter()
                {
                    Name = "PNG file", Extensions = new List <string>()
                    {
                        "png"
                    }
                }
            };
            sfd.InitialFileName = $"{texFile.m_Name}-{Path.GetFileName(cont.FileInstance.path)}-{cont.PathId}.png";

            string file = await sfd.ShowAsync(win);

            if (file != null && file != string.Empty)
            {
                string errorAssetName = $"{Path.GetFileName(cont.FileInstance.path)}/{cont.PathId}";

                //bundle resS
                if (!GetResSTexture(texFile, cont))
                {
                    string resSName = Path.GetFileName(texFile.m_StreamData.path);
                    await MessageBoxUtil.ShowDialog(win, "Error", $"[{errorAssetName}]: resS was detected but {resSName} was not found in bundle");

                    return(false);
                }

                byte[] data = TextureHelper.GetRawTextureBytes(texFile, cont.FileInstance);

                if (data == null)
                {
                    string resSName = Path.GetFileName(texFile.m_StreamData.path);
                    await MessageBoxUtil.ShowDialog(win, "Error", $"[{errorAssetName}]: resS was detected but {resSName} was not found on disk");

                    return(false);
                }

                bool success = TextureImportExport.ExportPng(data, file, texFile.m_Width, texFile.m_Height, (TextureFormat)texFile.m_TextureFormat);
                if (!success)
                {
                    string texFormat = ((TextureFormat)texFile.m_TextureFormat).ToString();
                    await MessageBoxUtil.ShowDialog(win, "Error", $"[{errorAssetName}]: Failed to decode texture format {texFormat}");
                }
                return(success);
            }
            return(false);
        }
Пример #19
0
        public void ReadEmbeddedResources(Stream systemMemory, Stream graphicsMemory)
        {
            if (TextureDictionaryOffset != 0)
            {
                systemMemory.Seek(TextureDictionaryOffset, SeekOrigin.Begin);

                TextureDictionary = new TextureFile();
                TextureDictionary.Open(systemMemory, graphicsMemory);
            }
        }
Пример #20
0
        public void ReadEmbeddedResources(Stream systemMemory, Stream graphicsMemory)
        {
            if (TextureDictionaryOffset != 0)
            {
                systemMemory.Seek(TextureDictionaryOffset, SeekOrigin.Begin);

                TextureDictionary = new TextureFile();
                TextureDictionary.Open(systemMemory, graphicsMemory);
            }
        }
Пример #21
0
        private static Texture FindTexture(TextureFile textures, string name)
        {
            if (textures == null)
            {
                return null;
            }

            var textureObj = textures.FindTextureByName(name);
            return textureObj;
        }
Пример #22
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

            if (!ShellViewModel.Loaded)
            {
                Task.Run(() => {
                                        #if MIKU1052
                    ShellViewModel.SetupShell("default");
                    ShellViewModel.LoadPMD(root, "/default", "/miku1052C-Re.pmd");
                                        #elif MIKU
                    ShellViewModel.SetupShell("default");
                    ShellViewModel.LoadPMD(root, "/default", "/miku.pmd");
                                        #elif LAT
                    ShellViewModel.SetupShell("Lat");
                    ShellViewModel.LoadPMD(root, "/Lat", "/LatVer2.3_White.pmd");
                                        #elif XSc
                    ShellViewModel.SetupShell("mikuXSc");
//				    ShellViewModel.ShellViewModel.LoadPMD (root, "/mikuXSc", "/mikuXS.pmd");
                    ShellViewModel.LoadPMF(root, "/mikuXSc", "/mikuXS.pmf");
                                        #elif XS
                    ShellViewModel.SetupShell("mikuXS");
                    ShellViewModel.LoadPMD(root, "/mikuXS", "/mikuXS.pmd");
                                        #else
                    ShellViewModel.SetupShell("zunko");
                    ShellViewModel.LoadPMF(root, "/zunko", "/zunko.pmf");
                                        #endif
                    ShellViewModel.LoadVMD(root, "/motion", "/stand_pose.vmd");
                    ShellViewModel.CommitShell();
                });
            }
            else
            {
                TextureFile.Reset();
            }

            var rootView = inflater.Inflate(Resource.Layout.ShellFragment, container, false);
            todayDate = rootView.FindViewById <TextView> (Resource.Id.TodayDate);
            todayDay  = rootView.FindViewById <TextView> (Resource.Id.TodayDay);
            todayTime = rootView.FindViewById <TextView> (Resource.Id.TodayTime);

            ShellViewModel.Data.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) => {
                handle.Post(() => {
                    todayDate.Text = ShellViewModel.Data.TodayDate;
                    todayDay.Text  = ShellViewModel.Data.TodayDay;
                    todayTime.Text = ShellViewModel.Data.TodayTime;
                });
            };


            var sv = rootView.FindViewById <ShellView> (Resource.Id.ShellView);
            sv.Holder.SetFormat(Android.Graphics.Format.Translucent);

            return(rootView);
        }
Пример #23
0
 public void WriteTo(Stream stream)
 {
     Name.WriteTo(stream);
     Id.WriteTo(stream);
     TextureFile.WriteTo(stream);
     if (Unknown1 != null)
     {
         BinaryWriter writer = new BinaryWriter(stream);
         writer.Write(Unknown1);
     }
 }
 public void Init(IReward_Slotitem rewardItem)
 {
     this._setRewardItem(rewardItem);
     this._uiRareBG.alpha       = 0f;
     this._uiRareBG.mainTexture = TextureFile.LoadRareBG(1);
     this._uiItem.alpha         = 0f;
     this._uiStarPar1.Stop();
     this._uiStarPar2.Stop();
     this._uiStarPar1.SetActive(false);
     this._uiStarPar2.SetActive(false);
 }
Пример #25
0
        private static Texture FindTexture(TextureFile textures, string name)
        {
            if (textures == null)
            {
                return(null);
            }

            var textureObj = textures.FindTextureByName(name);

            return(textureObj);
        }
 public void Init(IReward_Slotitem rewardItem)
 {
     _setRewardItem(rewardItem);
     _uiRareBG.alpha       = 0f;
     _uiRareBG.mainTexture = TextureFile.LoadRareBG(1);
     _uiItem.alpha         = 0f;
     _uiStarPar1.Stop();
     _uiStarPar2.Stop();
     ((Component)_uiStarPar1).SetActive(isActive: false);
     ((Component)_uiStarPar2).SetActive(isActive: false);
 }
Пример #27
0
        public static bool GetResSTexture(TextureFile texFile, AssetContainer cont)
        {
            var streamInfo = texFile.m_StreamData;

            if (!string.IsNullOrEmpty(streamInfo.path) && cont.FileInstance.parentBundle != null)
            {
                //some versions apparently don't use archive:/
                var searchPath = streamInfo.path;
                if (searchPath.StartsWith("archive:/"))
                {
                    searchPath = searchPath[9..];
Пример #28
0
 public void Play(Action callback)
 {
     _anim.Play("comp_GetShip");
     _actCallback = callback;
     _uiParStar1.Play();
     _uiParStar2.Play();
     _uiShip.alpha         = 1f;
     _uiRareBG.mainTexture = TextureFile.LoadRareBG(_clsRewardShip.Ship.Rare);
     _uiMessageBG.alpha    = 0.75f;
     _Se = SoundUtils.PlaySE(SEFIleInfos.RewardGet2);
 }
Пример #29
0
        public TextureFile GetTexturesFile()
        {
            if (texturesConverted)
            {
                return(texturesFile);
            }

            var atlasToTexturesConverter = new AtlasToTexturesConverter(AtlasFile, BuildFile, OutDir);

            texturesFile      = atlasToTexturesConverter.GetTexturesFile();
            texturesConverted = true;
            return(texturesFile);
        }
Пример #30
0
        /// <summary>
        /// Sets position for a gameobject that replaces a billboard, with the assumption that the origin is at the base of the model.
        /// </summary>
        private static void AlignToBase(Transform transform, Vector3 position, int archive, int record, bool inDungeon)
        {
            // Fix origin position for dungeon flats
            if (inDungeon)
            {
                int height = ImageReader.GetImageData(TextureFile.IndexToFileName(archive), record, createTexture: false).height;

                position.y -= height / 2 * MeshReader.GlobalScale;
            }

            // Assign position
            transform.localPosition = position;
        }
Пример #31
0
        public static byte[] TextureToBytes(Texture2D texture)
        {
            var         memStream = new MemoryStream();
            TextureFile t         = new TextureFile();

            t.data     = File.ReadAllBytes(Game1.self.SkinsPaths.Single(p => p.skin == texture).path);
            t.fileName = Path.GetFileName(Game1.self.SkinsPaths.Single(p => p.skin == texture).path);
            t.ToBytes(ref memStream);
            var z = memStream.ToArray();

            memStream.Close();
            memStream.Dispose();
            return(z);
        }
        public static ProdCutReceiveSlotItem Instantiate(ProdCutReceiveSlotItem prefab, Transform parent, IReward_Slotitem rewardItem, int nPanelDepth, KeyControl input)
        {
            ProdCutReceiveSlotItem prodCutReceiveSlotItem = UnityEngine.Object.Instantiate(prefab);

            prodCutReceiveSlotItem.transform.parent        = parent;
            prodCutReceiveSlotItem.transform.localScale    = Vector3.one;
            prodCutReceiveSlotItem.transform.localPosition = Vector3.zero;
            prodCutReceiveSlotItem._setRewardItem(rewardItem);
            prodCutReceiveSlotItem._uiRareBG.alpha                = 0f;
            prodCutReceiveSlotItem._uiRareBG.mainTexture          = TextureFile.LoadRareBG(1);
            prodCutReceiveSlotItem.GetComponent <UIPanel>().depth = nPanelDepth;
            prodCutReceiveSlotItem._clsInput = input;
            return(prodCutReceiveSlotItem);
        }
        public static ProdCutReceiveSlotItem Instantiate(ProdCutReceiveSlotItem prefab, Transform parent, IReward_Slotitem rewardItem, int nPanelDepth, KeyControl input)
        {
            ProdCutReceiveSlotItem prodCutReceiveSlotItem = Object.Instantiate <ProdCutReceiveSlotItem>(prefab);

            prodCutReceiveSlotItem.get_transform().set_parent(parent);
            prodCutReceiveSlotItem.get_transform().set_localScale(Vector3.get_one());
            prodCutReceiveSlotItem.get_transform().set_localPosition(Vector3.get_zero());
            prodCutReceiveSlotItem._setRewardItem(rewardItem);
            prodCutReceiveSlotItem._uiRareBG.alpha                = 0f;
            prodCutReceiveSlotItem._uiRareBG.mainTexture          = TextureFile.LoadRareBG(1);
            prodCutReceiveSlotItem.GetComponent <UIPanel>().depth = nPanelDepth;
            prodCutReceiveSlotItem._clsInput = input;
            return(prodCutReceiveSlotItem);
        }
Пример #34
0
        public virtual void LaunchEditor(FileSystem fs, File file)
        {
            var data = file.GetData();

            var ms = new MemoryStream(data);
            var textureFile = new TextureFile();
            try
            {
                textureFile.Open(ms);
            }
            finally
            {
                ms.Close();
            }

            ShowForm(file, textureFile);
        }
Пример #35
0
 private void TryLoadTexture(List<TextureFile> textureList, File file, string name)
 {
     var textureFileName = name + ".wtd";
     var textures = file.ParentDirectory.FindByName(textureFileName) as File;
     if (textures != null)
     {
         var textureFile = new TextureFile();
         var textureMS = new MemoryStream(textures.GetData());
         try
         {
             textureFile.Open(textureMS);
             textureList.Add(textureFile);
         }
         finally
         {
             textureMS.Close();
         }
     }
 }
Пример #36
0
        protected virtual void SaveAndClose(EditorForm form, TextureFile textureFile, File file)
        {
            using (new WaitCursor(form))
            {
                var msSave = new MemoryStream();
                try
                {
                    textureFile.Save(msSave);

                    file.SetData(msSave.ToArray());
                }
                finally
                {
                    msSave.Close();
                }
            }

            form.Close();
        }
Пример #37
0
        protected void ShowForm(File file, TextureFile textureFile)
        {
            var view = new TextureEditView();
            
            var controller = new TextureEditController(view);
            controller.TextureFile = textureFile;

            using (var form = new EditorForm())
            {
                form.SetFilename(file.Name);
                form.SetControl(view);

                controller.SaveAndClose += ((sender, e) => SaveAndClose(form, textureFile, file));

                form.ShowDialog();
            }

            textureFile.Dispose();
        }
Пример #38
0
        public Control GetView(RageLib.FileSystem.Common.File file)
        {
            var data = file.GetData();

            var ms = new MemoryStream(data);
            var textureFile = new TextureFile();
            try
            {
                textureFile.Open(ms);
            }
            finally
            {
                ms.Close();
            }

            var view = new TexturePreviewView();
            var controller = new TexturePreviewController(view);
            controller.TextureFile = textureFile;

            return view;
        }
Пример #39
0
        /*
        internal static Image CreateUVMapImage(DrawableModel drawable)
        {
            var bmp = new Bitmap(512, 512);
            var g = Graphics.FromImage(bmp);
            var pen = new System.Drawing.Pen(Color.Red);

            foreach (var geometryInfo in drawable.ModelCollection)
            {
                foreach (var dataInfo in geometryInfo.Geometries)
                {
                    for (var i = 0; i < dataInfo.FaceCount; i++)
                    {
                        var i1 = (dataInfo.IndexBuffer.IndexData[i * 3 + 0]);
                        var i2 = (dataInfo.IndexBuffer.IndexData[i * 3 + 1]);
                        var i3 = (dataInfo.IndexBuffer.IndexData[i * 3 + 2]);

                        var v1 = dataInfo.VertexBuffer.VertexData[i1];
                        var v2 = dataInfo.VertexBuffer.VertexData[i2];
                        var v3 = dataInfo.VertexBuffer.VertexData[i3];

                        g.DrawLine(pen, v1.TextureU * bmp.Width, v1.TextureV * bmp.Height, v2.TextureU * bmp.Width, v2.TextureV * bmp.Height);
                        g.DrawLine(pen, v1.TextureU * bmp.Width, v1.TextureV * bmp.Height, v3.TextureU * bmp.Width, v3.TextureV * bmp.Height);
                        g.DrawLine(pen, v2.TextureU * bmp.Width, v2.TextureV * bmp.Height, v3.TextureU * bmp.Width, v3.TextureV * bmp.Height);
                    }
                }
            }

            g.Dispose();

            return bmp;
        }
         */

        internal static ModelNode GenerateModel(FragTypeModel fragTypeModel, TextureFile[] textures)
        {
            var fragTypeGroup = new Model3DGroup();
            var fragTypeNode = new ModelNode { DataModel = fragTypeModel, Model3D = fragTypeGroup, Name = "FragType", NoCount = true };

            var parentDrawableNode = GenerateModel(fragTypeModel.Drawable, textures);
            parentDrawableNode.NoCount = false;
            fragTypeGroup.Children.Add(parentDrawableNode.Model3D);
            fragTypeNode.Children.Add(parentDrawableNode);

            foreach (var fragTypeChild in fragTypeModel.Children)
            {
                if (fragTypeChild.Drawable != null && fragTypeChild.Drawable.ModelCollection.Length > 0)
                {
                    var childDrawableNode = GenerateModel(fragTypeChild.Drawable, textures);
                    childDrawableNode.NoCount = false;
                    fragTypeGroup.Children.Add(childDrawableNode.Model3D);
                    fragTypeNode.Children.Add(childDrawableNode);                    
                }
            }

            return fragTypeNode;
        }
Пример #40
0
 internal static ModelNode GenerateModel(DrawableModelDictionary drawableModelDictionary, TextureFile[] textures)
 {
     var dictionaryTypeGroup = new Model3DGroup();
     var dictionaryTypeNode = new ModelNode { DataModel = drawableModelDictionary, Model3D = dictionaryTypeGroup, Name = "Dictionary", NoCount = true };
     foreach (var entry in drawableModelDictionary.Entries)
     {
         var drawableNode = GenerateModel(entry, textures);
         drawableNode.NoCount = false;
         dictionaryTypeGroup.Children.Add(drawableNode.Model3D);
         dictionaryTypeNode.Children.Add(drawableNode);                    
     }
     return dictionaryTypeNode;
 }
Пример #41
0
        internal static ModelNode GenerateModel(Drawable drawable, TextureFile[] textures)
        {
            var random = new Random();

            var materials = new Material[drawable.Materials.Count];
            for (int i = 0; i < materials.Length; i++)
            {
                Brush brush =
                    new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, (byte)random.Next(0, 255),
                                                                            (byte)random.Next(0, 255),
                                                                            (byte)random.Next(0, 255)));

                var drawableMat = drawable.Materials[i];
                var texture = drawableMat.Parameters[(int)ParamNameHash.Texture] as MaterialParamTexture;
                if (texture != null)
                {
                    // 1. Try looking in the embedded texture file (if any)
                    var textureObj = FindTexture(drawable.AttachedTexture, texture.TextureName);

                    // 2. Try looking in any attached external texture dictionaries
                    if (textureObj == null)
                    {
                        foreach (var file in textures)
                        {
                            textureObj = FindTexture(file, texture.TextureName);
                            if (textureObj != null)
                            {
                                break;
                            }
                        }
                    }

                    // Generate a brush if we were successful
                    if (textureObj != null)
                    {
                        var bitmap = textureObj.Decode() as Bitmap;

                        var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                            bitmap.GetHbitmap(),
                            IntPtr.Zero,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());

                        // For memory leak work around
                        bitmapSource.Freeze();

                        brush = new ImageBrush(bitmapSource);
                        (brush as ImageBrush).ViewportUnits = BrushMappingMode.Absolute;
                        (brush as ImageBrush).TileMode = TileMode.Tile;

                        bitmap.Dispose();
                    }
                }

                materials[i] = new DiffuseMaterial(brush);
            }

            var drawableModelGroup = new Model3DGroup();
            var drawableModelNode = new ModelNode {DataModel = drawable, Model3D = drawableModelGroup, Name = "Drawable", NoCount = true};
            foreach (var model in drawable.Models)
            {
                var modelGroup = new Model3DGroup();

                var modelNode = new ModelNode {DataModel = model, Model3D = modelGroup, Name = "Model"};
                drawableModelNode.Children.Add(modelNode);

                foreach (var geometry in model.Geometries)
                {
                    var geometryIndex = 0;
                    var geometryGroup = new Model3DGroup();

                    var geometryNode = new ModelNode { DataModel = geometry, Model3D = geometryGroup, Name = "Geometry" };
                    modelNode.Children.Add(geometryNode);

                    foreach (var mesh in geometry.Meshes)
                    {
                        var mesh3D = new MeshGeometry3D();

                        var meshNode = new ModelNode { DataModel = mesh, Model3D = null, Name = "Mesh" };
                        geometryNode.Children.Add(meshNode);

                        Data.Vertex[] vertices = mesh.DecodeVertexData();
                        foreach (var vertex in vertices)
                        {
                            mesh3D.Positions.Add(new Point3D(vertex.Position.X, vertex.Position.Y, vertex.Position.Z));
                            if (mesh.VertexHasNormal)
                            {
                                mesh3D.Normals.Add(new Vector3D(vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z));
                            }

                            if (mesh.VertexHasTexture)
                            {
                                mesh3D.TextureCoordinates.Add(new Point(vertex.TextureCoordinates[0].X, vertex.TextureCoordinates[0].Y));
                            }
                        }

                        ushort[] indices = mesh.DecodeIndexData();
                        for (int i = 0; i < mesh.FaceCount; i++)
                        {
                            mesh3D.TriangleIndices.Add(indices[i * 3 + 0]);
                            mesh3D.TriangleIndices.Add(indices[i * 3 + 1]);
                            mesh3D.TriangleIndices.Add(indices[i * 3 + 2]);
                        }

                        var material = materials[geometry.Meshes[geometryIndex].MaterialIndex];
                        var model3D = new GeometryModel3D(mesh3D, material);

                        geometryGroup.Children.Add(model3D);
                        meshNode.Model3D = model3D;

                        geometryIndex++;
                    }
                    modelGroup.Children.Add(geometryGroup);
                }
                drawableModelGroup.Children.Add(modelGroup);
            }
            return drawableModelNode;
        }
Пример #42
0
 public ModelNode GetModel(TextureFile[] textures)
 {
     return ModelGenerator.GenerateModel(File.Data, textures);
 }
 private void View_Disposed(object sender, EventArgs e)
 {
     // We handle this here instead of in the caller because the caller
     // doesn't know anything about the involved files...
     if (TextureFile != null)
     {
         TextureFile.Dispose();
         TextureFile = null;
     }
 }
Пример #44
0
 internal static ModelNode GenerateModel(DrawableModel drawableModel, TextureFile[] textures)
 {
     return GenerateModel(new Drawable(drawableModel), textures);
 }