Beispiel #1
0
        /// <summary>Saves the specified file.</summary>
        /// <param name="file">The file.</param>
        public void Save(string file)
        {
            var dirPath = Path.GetDirectoryName(file);

            // If output directory doesn't exist, we can create it
            if (dirPath != null && !Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            using (var stream = new NativeFileStream(file, NativeFileMode.Create, NativeFileAccess.Write, NativeFileShare.ReadWrite)) Save(stream);
        }
        public Stream Open(IncludeType type, string fileName, Stream parentStream)
        {
            Debug.WriteLine(fileName);

            // Include dynamic (:D) constants
            if (fileName.ToLower().Equals("raymarchengine"))
            {
                return(GetShaderConstantsStream());
            }

            string currentDirectory = CurrentDirectory.Peek();

            if (currentDirectory == null)
            {
#if NETFX_CORE
                currentDirectory = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
#else
                currentDirectory = Environment.CurrentDirectory;
#endif
            }

            string filePath = fileName;

            if (!Path.IsPathRooted(filePath))
            {
                var directoryToSearch = new List <string> {
                    currentDirectory
                };
                directoryToSearch.AddRange(IncludeDirectories);
                foreach (string dirPath in directoryToSearch)
                {
                    string selectedFile = Path.GetFullPath(Path.Combine(dirPath, fileName));
                    if (NativeFile.Exists(selectedFile))
                    {
                        filePath = selectedFile;
                        break;
                    }
                }
            }

            if (filePath == null || !NativeFile.Exists(filePath))
            {
                throw new FileNotFoundException(String.Format("Unable to find file [{0}]", filePath ?? fileName));
            }

            NativeFileStream fs = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read);
            CurrentDirectory.Push(Path.GetDirectoryName(filePath));
            return(fs);
        }
        private AudioBufferAndMetaData GetBuffer(string soundfile)
        {
            var nativefilestream = new NativeFileStream(soundfile, NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read);
            var soundstream      = new SoundStream(nativefilestream);
            var buffer           = new AudioBufferAndMetaData
            {
                Stream             = soundstream.ToDataStream(),
                AudioBytes         = (int)soundstream.Length,
                Flags              = BufferFlags.EndOfStream,
                WaveFormat         = soundstream.Format,
                DecodedPacketsInfo = soundstream.DecodedPacketsInfo
            };

            return(buffer);
        }
Beispiel #4
0
        public void Register(string filepath)
        {
            CheckSupported();
            if (sounds.ContainsKey(filepath))
            {
                return;
            }
            var nfs     = new NativeFileStream(filepath, NativeFileMode.Open, NativeFileAccess.Read);
            var decoder = new AudioDecoder(nfs);

            lock (sounds) sounds.Add(filepath, decoder);

            var freelist = new Queue <SourceVoice>();

            voices.Add(decoder, freelist);
        }
Beispiel #5
0
        public static Image2D LoadFromFile(string path, Canvas canvas)
        {
            ImagingFactory   imagingFactory = new ImagingFactory();
            NativeFileStream fileStream     = new NativeFileStream(path,
                                                                   NativeFileMode.Open, NativeFileAccess.Read);
            BitmapDecoder     bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand);
            BitmapFrameDecode frame         = bitmapDecoder.GetFrame(0);
            FormatConverter   converter     = new FormatConverter(imagingFactory);

            converter.Initialize(frame, PixelFormatWic.Format32bppPRGBA);

            var result = new Image2D();

            result.nativeBitmap = Bitmap2D.FromWicBitmap(canvas.NativeDeviceContext, converter);
            return(result);
        }
Beispiel #6
0
        public void LoadAssetList(string assetListFile)
        {
            var serializer = new Serializer();

            serializer.Settings.RegisterTagMapping("Asset", typeof(AssetIdentifier));
            serializer.Settings.RegisterTagMapping("Assets", typeof(AssetIdentifier[]));
            AssetIdentifier[] assetList;
            using (var nativeStream = new NativeFileStream(assetListFile, NativeFileMode.Open, NativeFileAccess.Read))
                assetList = serializer.Deserialize <AssetIdentifier[]>(nativeStream);

            foreach (AssetIdentifier assetIdentifier in assetList)
            {
                LoadAsset(assetIdentifier);
            }

            OnAssetsLoaded(new AssetsLoadedEventArgs(assetListFile));
        }
        // Reads a sound and puts it in the dictionary
        public AudioBuffer AddWave(string key, string filepath)
        {
            MyWave wave = new MyWave();

            var nativeFileStream = new NativeFileStream(filepath, NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read);
            var soundStream      = new SoundStream(nativeFileStream);
            var buffer           = new AudioBuffer()
            {
                Stream = soundStream, AudioBytes = (int)soundStream.Length, Flags = SharpDX.XAudio2.BufferFlags.EndOfStream
            };

            wave.Buffer             = buffer;
            wave.DecodedPacketsInfo = soundStream.DecodedPacketsInfo;
            wave.WaveFormat         = soundStream.Format;

            this.sounds.Add(key, wave);
            return(buffer);
        }
Beispiel #8
0
        public Bitmap GetBitmap(string file)
        {
            string full;

            System.IO.FileInfo fi = null;
            if (BitmapFile.ContainsKey(file))
            {
                full = BitmapFile[file];
            }
            else
            {
                fi   = new System.IO.FileInfo(file);
                full = fi.FullName;
                BitmapFile.Add(file, full);
            }
            if (Bitmaps.ContainsKey(full))
            {
                return(Bitmaps[full]);
            }
            if (fi == null)
            {
                fi = new System.IO.FileInfo(full);
            }
            if (fi.Exists)
            {
                using (var fac = new ImagingFactory())
                    using (var fs = new NativeFileStream(full, NativeFileMode.Open, NativeFileAccess.Read))
                        using (var dec = new BitmapDecoder(fac, fs, DecodeOptions.CacheOnDemand))
                            using (var frame = dec.GetFrame(0))
                                using (var conv = new FormatConverter(fac))
                                {
                                    conv.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPBGRA);
                                    var bit = Bitmap.FromWicBitmap(target, conv);
                                    Bitmaps[full] = bit;
                                    return(bit);
                                }
            }
            else
            {
                Bitmaps.Add(full, null);
                return(null);
            }
        }
Beispiel #9
0
        public static Bitmap1 GetBitmap(D2D.DeviceContext context, string filePath)
        {
            ImagingFactory imagingFactory = new ImagingFactory();

            NativeFileStream fileStream = new NativeFileStream(
                Package.Current.InstalledLocation.Path + filePath,
                NativeFileMode.Open, NativeFileAccess.Read);

            BitmapDecoder bitmapDecoder = new BitmapDecoder(
                imagingFactory, fileStream, DecodeOptions.CacheOnDemand);

            BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

            FormatConverter converter = new FormatConverter(imagingFactory);

            converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

            return(SharpDX.Direct2D1.Bitmap1.FromWicBitmap(context, converter));
        }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Загрузка рисунка из файла
            /// </summary>
            /// <param name="file_name">Имя файла</param>
            /// <returns>Рисунок Direct2D</returns>
            //---------------------------------------------------------------------------------------------------------
            public static Direct2D.Bitmap LoadFromFile(String file_name)
            {
                if (mD2DImagingFactory == null)
                {
                    mD2DImagingFactory = new ImagingFactory();
                }

                NativeFileStream file_stream = new NativeFileStream(file_name, NativeFileMode.Open, NativeFileAccess.Read);

                BitmapDecoder     bitmap_decoder = new BitmapDecoder(mD2DImagingFactory, file_stream, DecodeOptions.CacheOnDemand);
                BitmapFrameDecode frame          = bitmap_decoder.GetFrame(0);

                FormatConverter converter = new FormatConverter(mD2DImagingFactory);

                converter.Initialize(frame, PixelFormat.Format32bppPRGBA);

                Direct2D.Bitmap bitmap = Direct2D.Bitmap.FromWicBitmap(D2DRenderTarget, converter);
                return(bitmap);
            }
        public static Bitmap1 CreateD2DBitmap(this DeviceContext deviceContext, string filePath)
        {
            var imagingFactory = new ImagingFactory();

            var fileStream = new NativeFileStream(
                filePath,
                NativeFileMode.Open,
                NativeFileAccess.Read);

            var bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand);
            var frame         = bitmapDecoder.GetFrame(0);

            var converter = new FormatConverter(imagingFactory);

            converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

            var newBitmap = Bitmap1.FromWicBitmap(deviceContext, converter);

            return(newBitmap);
        }
Beispiel #12
0
        Bitmap1 createD2DBitmap(string filePath, _d2d.DeviceContext deviceContext)
        {
            var imagingFactory = new _wic.ImagingFactory();

            var fileStream = new NativeFileStream(
                filePath,
                NativeFileMode.Open,
                NativeFileAccess.Read);

            var bitmapDecoder = new _wic.BitmapDecoder(imagingFactory, fileStream, _wic.DecodeOptions.CacheOnDemand);
            var frame         = bitmapDecoder.GetFrame(0);

            var converter = new _wic.FormatConverter(imagingFactory);

            converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

            var newBitmap = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(deviceContext, converter);

            return(newBitmap);
        }
Beispiel #13
0
        private void ReadSoundBytes(string fileName, Channel channel)
        {
            var fileStream = new NativeFileStream(fileName, NativeFileMode.Open, NativeFileAccess.Read);

            var          soundStream = new SoundStream(fileStream);
            var          dataStream  = soundStream.ToDataStream();
            int          k           = 1;
            List <short> test        = new List <short>();
            List <float> test2       = new List <float>();
            List <float> test3       = new List <float>();

            test.Add(0);
            test.Add(0);
            if (channel == Channel.Right)
            {
                chartR.Series[0].Points.Clear();
            }
            else
            {
                chartL.Series[0].Points.Clear();
            }

            while (dataStream.Length / sizeof(short) > k)
            {
                byte[] bytess = new byte[4];
                test[1] = dataStream.Read <short>();

                test2.Add(test[1]);
                var y = (100 * test[1]) / short.MaxValue;
                if (channel == Channel.Right)
                {
                    chartR.Series[0].Points.AddY(y);
                }
                else
                {
                    chartL.Series[0].Points.AddY(y);
                }

                k++;
            }
        }
Beispiel #14
0
        protected override Diagnostics.Logger ProcessFileAndGetLogResults(string inputFilePath, string outputFilePath, string dependencyFilePath, TkItem item)
        {
            var compilerFlags = Debug ? EffectCompilerFlags.Debug : EffectCompilerFlags.None;

            if (!string.IsNullOrEmpty(CompilerFlags))
            {
                compilerFlags |= (EffectCompilerFlags)Enum.Parse(typeof(EffectCompilerFlags), CompilerFlags);
            }

            var compilerResult = compiler.CompileFromFile(inputFilePath,
                                                          compilerFlags,
                                                          null,
                                                          null,
                                                          item.DynamicCompiling,
                                                          dependencyFilePath);

            if (!compilerResult.HasErrors && compilerResult.EffectData != null)
            {
                CreateDirectoryIfNotExists(outputFilePath);

                if (item.OutputCs)
                {
                    var codeWriter = new EffectDataCodeWriter
                    {
                        Namespace = item.OutputNamespace,
                        ClassName = item.OutputClassName,
                        FieldName = item.OutputFieldName,
                    };

                    using (var stream = new NativeFileStream(outputFilePath, NativeFileMode.Create, NativeFileAccess.Write, NativeFileShare.Write))
                        codeWriter.Write(compilerResult.EffectData, new StreamWriter(stream, Encoding.UTF8));
                }
                else
                {
                    compilerResult.EffectData.Save(outputFilePath);
                }
            }

            return(compilerResult.Logger);
        }
Beispiel #15
0
        public Stream Open(IncludeType type, string fileName, Stream parentStream)
        {
            var currentDirectory = CurrentDirectory.Peek();

            if (currentDirectory == null)
#if NETFX_CORE
            { currentDirectory = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; }
#else
            { currentDirectory = Environment.CurrentDirectory; }
#endif

            var filePath = fileName;

            if (!Path.IsPathRooted(filePath))
            {
                var directoryToSearch = new List <string> {
                    currentDirectory
                };
                directoryToSearch.AddRange(IncludeDirectories);
                foreach (var dirPath in directoryToSearch)
                {
                    var selectedFile = Path.Combine(dirPath, fileName);
                    if (NativeFile.Exists(selectedFile))
                    {
                        filePath = selectedFile;
                        break;
                    }
                }
            }

            if (filePath == null || !NativeFile.Exists(filePath))
            {
                throw new FileNotFoundException(String.Format("Unable to find file [{0}]", filePath ?? fileName));
            }

            NativeFileStream fs = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read);
            CurrentDirectory.Push(Path.GetDirectoryName(filePath));
            return(fs);
        }
Beispiel #16
0
        /// <summary>
        /// Loads a new Texture from a file on disk.
        /// </summary>
        /// <param name="device">DirectX device.</param>
        /// <param name="filename">Path to the texture file.</param>
        /// <returns></returns>
        public static async Task <Texture> LoadFromFile(SharpDX.Direct3D11.Device1 device, string filename)
        {
            Texture newTexture = new Texture();

            newTexture.texturePath = filename;
            NativeFileStream fileStream = new NativeFileStream(filename, NativeFileMode.Open, NativeFileAccess.Read);

            using (BinaryReader reader = new BinaryReader(fileStream))
            {
                int width  = reader.ReadInt32();
                int height = reader.ReadInt32();

                int    dataLength = reader.ReadInt32();
                byte[] data       = new byte[dataLength];

                data = reader.ReadBytes(dataLength);

                DataStream stream = new DataStream(dataLength, false, true);
                stream.Write(data, 0, dataLength);

                newTexture.texture = new Texture2D(device, new Texture2DDescription()
                {
                    ArraySize         = 1,
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Format            = Format.BC3_UNorm,
                    Height            = height,
                    MipLevels         = 1,
                    OptionFlags       = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Immutable,
                    Width             = width,
                }, new DataRectangle(stream.DataPointer, width * 4));

                newTexture.resourceView = new ShaderResourceView(device, newTexture.texture);
            }

            return(newTexture);
        }
Beispiel #17
0
        public static void Save(string fullPath, ShaderCollection shaderCollection)
        {
            NativeFileStream fs = new NativeFileStream(fullPath, NativeFileMode.Create, NativeFileAccess.Write);

            try
            {
                BinarySerializer bs = new BinarySerializer(fs, SerializerMode.Write)
                {
                    AllowIdentity = true
                };
                bs.Serialize(ref shaderCollection);
            }
            catch (SerializationException e)
            {
                LogEvent.Tool.Error(e.Message);
                throw;
            }
            finally
            {
                fs.Dispose();
            }
        }
    public AudioClip(string wavFilePath, float initialVolumne = 1, bool loopForever = false)
    {
        _loopForever    = loopForever;
        _wavFilePath    = wavFilePath;
        _initialVolumne = initialVolumne;
        var masteringsound   = new MasteringVoice(_xaudio);               //Yes, this is required.
        var nativefilestream = new NativeFileStream(wavFilePath,
                                                    NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read);

        _soundstream = new SoundStream(nativefilestream);
        _waveFormat  = _soundstream.Format;
        _buffer      = new AudioBuffer
        {
            Stream     = _soundstream.ToDataStream(),
            AudioBytes = (int)_soundstream.Length,
            Flags      = BufferFlags.EndOfStream
        };
        if (loopForever)
        {
            _buffer.LoopCount = 100;
        }
    }
Beispiel #19
0
        public static ShaderCollection Load(string fullPath)
        {
            NativeFileStream fs = new NativeFileStream(fullPath, NativeFileMode.Open, NativeFileAccess.Read);

            try
            {
                ShaderCollection sc = null;
                BinarySerializer bs = new BinarySerializer(fs, SerializerMode.Read)
                {
                    AllowIdentity = true
                };
                bs.Serialize(ref sc);
                return(sc);
            }
            catch (SerializationException e)
            {
                LogEvent.Tool.Error(e.Message);
                throw;
            }
            finally
            {
                fs.Dispose();
            }
        }
Beispiel #20
0
        /// <summary>
        /// Loads the specified image from a file.
        /// </summary>
        /// <param name="fileName">The filename.</param>
        /// <returns>An new image.</returns>
        /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
        public static Image Load(string fileName)
        {
            NativeFileStream stream = null;
            var memoryPtr           = IntPtr.Zero;
            int size;

            try
            {
                stream    = new NativeFileStream(fileName, NativeFileMode.Open, NativeFileAccess.Read);
                size      = (int)stream.Length;
                memoryPtr = Utilities.AllocateMemory(size);
                stream.Read(memoryPtr, 0, size);
            }
            catch (Exception)
            {
                if (memoryPtr != IntPtr.Zero)
                {
                    Utilities.FreeMemory(memoryPtr);
                }
                throw;
            }
            finally
            {
                try
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
                catch { }
            }

            // If everything was fine, load the image from memory
            return(Load(memoryPtr, size, false));
        }
Beispiel #21
0
        public void SetAudioHandler(string strFileName, int nVolume)
        {
            try
            {
                _xAudio2        = new XAudio2();
                _masteringVoice = new MasteringVoice(_xAudio2);
                _masteringVoice.SetVolume(nVolume / 100f, 0);

                _nativeFilestream = new NativeFileStream(strFileName, NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read);

                _soundStream = new SoundStream(_nativeFilestream);
                _waveFormat  = _soundStream.Format;
                _audioBuffer = new AudioBuffer
                {
                    Stream     = _soundStream.ToDataStream(),
                    AudioBytes = (int)_soundStream.Length,
                    Flags      = BufferFlags.EndOfStream
                };
            }
            catch (Exception ex)
            {
                DeadlyLog4Net._log.Error($"catch {MethodBase.GetCurrentMethod().Name}", ex);
            }
        }
Beispiel #22
0
        private static AudioBufferAndMetaData GetBuffer(string soundfile)
        {
            if (!AudioBuffers.ContainsKey(soundfile))
            {
                var nativefilestream = new NativeFileStream(
                    soundfile,
                    NativeFileMode.Open,
                    NativeFileAccess.Read,
                    NativeFileShare.Read);

                var soundstream = new SoundStream(nativefilestream);

                var buffer = new AudioBufferAndMetaData()
                {
                    Stream             = soundstream.ToDataStream(),
                    AudioBytes         = (int)soundstream.Length,
                    Flags              = BufferFlags.EndOfStream,
                    WaveFormat         = soundstream.Format,
                    DecodedPacketsInfo = soundstream.DecodedPacketsInfo
                };
                AudioBuffers[soundfile] = buffer;
            }
            return(AudioBuffers[soundfile]);
        }
Beispiel #23
0
 /// <summary>
 /// Loads a Cube texture from a stream.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="filePath">The file to load the texture from.</param>
 /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
 /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
 /// <exception cref="ArgumentException">If the texture is not of type Cube</exception>
 /// <returns>A texture</returns>
 public static new TextureCube Load(GraphicsDevice device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
 {
     using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read))
         return(Load(device, stream, flags | TextureFlags.ShaderResource, usage));
 }
Beispiel #24
0
        void Run(string[] args)
        {
            var assemblyUri  = new Uri(Assembly.GetEntryAssembly().CodeBase);
            var assemblyPath = Path.GetDirectoryName(assemblyUri.LocalPath);

            var newPath = Path.GetFullPath(Path.Combine(assemblyPath, @"..\Redist\D3D\" + (IntPtr.Size == 4 ? "x86" : "x64"))) + ";" + Environment.GetEnvironmentVariable("PATH");

            Environment.SetEnvironmentVariable("PATH", newPath);

            // Print the exe header
            PrintHeader();

            // Parse the command line
            if (!ParseCommandLine(args))
            {
                Environment.Exit(-1);
            }

            var options = this;

            // ----------------------------------------------------------------
            // Process macros
            // ----------------------------------------------------------------
            var macros = new List <EffectData.ShaderMacro>();

            foreach (var define in options.Defines)
            {
                var    nameValue = define.Split('=');
                string name      = nameValue[0];
                string value     = null;
                if (nameValue.Length > 1)
                {
                    value = nameValue[1];
                }
                macros.Add(new EffectData.ShaderMacro(name, value));
            }

            // ----------------------------------------------------------------
            // Setup compiler flags
            // ----------------------------------------------------------------
            var flags = EffectCompilerFlags.None;

            if (options.Debug)
            {
                flags |= EffectCompilerFlags.Debug;
            }

            switch (options.OptimizationLevel)
            {
            case 0:
                flags |= EffectCompilerFlags.OptimizationLevel0;
                break;

            case 1:
                flags |= EffectCompilerFlags.OptimizationLevel1;
                break;

            case 2:
                flags |= EffectCompilerFlags.OptimizationLevel2;
                break;

            case 3:
                flags |= EffectCompilerFlags.OptimizationLevel3;
                break;
            }

            if (options.PackRowMajor)
            {
                flags |= EffectCompilerFlags.PackMatrixRowMajor;
            }

            if (options.PackColumnMajor)
            {
                flags |= EffectCompilerFlags.PackMatrixColumnMajor;
            }

            if (options.AvoidFlowControl)
            {
                flags |= EffectCompilerFlags.AvoidFlowControl;
            }

            if (options.PreferFlowControl)
            {
                flags |= EffectCompilerFlags.PreferFlowControl;
            }

            if (options.EnableStrictness)
            {
                flags |= EffectCompilerFlags.EnableStrictness;
            }

            if (options.EnableBackwardsCompatibility)
            {
                flags |= EffectCompilerFlags.EnableBackwardsCompatibility;
            }

            if (options.IeeeStrictness)
            {
                flags |= EffectCompilerFlags.IeeeStrictness;
            }

            hasErrors = false;

            // ----------------------------------------------------------------
            // Process each fx files / tkfxo files
            // ----------------------------------------------------------------
            var fxFile   = options.FxFile;
            var filePath = Path.Combine(Environment.CurrentDirectory, fxFile);

            // Check that input file exists
            if (!File.Exists(filePath))
            {
                ErrorColor();
                Console.Error.WriteLine("File [{0}] does not exist", fxFile);
                ResetColor();
                Abort();
            }

            // ----------------------------------------------------------------
            // Pre check files
            // ----------------------------------------------------------------
            if (options.OutputClassFile == null && options.OutputFile == null)
            {
                options.OutputFile = Path.GetFileNameWithoutExtension(options.FxFile) + ".tkb";
            }

            // Check for output files
            bool outputFileExist = options.OutputClassFile != null && File.Exists(options.OutputClassFile);

            if (options.OutputFile != null && !File.Exists(options.OutputFile))
            {
                outputFileExist = false;
            }

            // New Compiler
            var compiler = new EffectCompiler();

            string outputDependencyDirPath  = Path.Combine(Environment.CurrentDirectory, OutputDependencyDirectory);
            string outputDependencyFilePath = Path.Combine(outputDependencyDirPath, compiler.GetDependencyFileNameFromSourcePath(options.FxFile));

            if (AllowDynamicCompiling)
            {
                CompileOnlyIfNewer = true;
            }

            if (CompileOnlyIfNewer)
            {
                if (!compiler.CheckForChanges(outputDependencyFilePath) && outputFileExist)
                {
                    Console.Error.WriteLine("Nothing to compile. Output file [{0}] is up-to-date", options.OutputFile);
                    Environment.Exit(0);
                }
            }

            var viewOnly = false;
            // Try to load this file as a precompiled file
            var effectData = EffectData.Load(fxFile);
            EffectCompilerResult compilerResult = null;

            if (effectData != null)
            {
                Console.WriteLine("Load Compiled File [{0}]", fxFile);
                viewOnly = true;
            }
            else
            {
                // Compile the fx file
                Console.WriteLine("Compile Effect File [{0}]", filePath);
                compilerResult = compiler.Compile(File.ReadAllText(filePath), filePath, flags, macros, options.IncludeDirs, AllowDynamicCompiling, CompileOnlyIfNewer ? outputDependencyFilePath : null);

                // If there is any warning, errors, turn Error color on
                if (compilerResult.Logger.Messages.Count > 0)
                {
                    ErrorColor();
                }

                // Show a message error for the current file
                if (compilerResult.HasErrors)
                {
                    Console.Error.WriteLine("Error when compiling file [{0}]:", fxFile);
                    hasErrors = true;
                }

                // Print all messages (warning and errors)
                foreach (var logMessage in compilerResult.Logger.Messages)
                {
                    Console.WriteLine(logMessage);
                }

                // If we have some messages, reset the color back
                if (compilerResult.Logger.Messages.Count > 0)
                {
                    ResetColor();
                }

                effectData = compilerResult.EffectData;
            }

            if (!NoDisassembly && effectData != null)
            {
                DumpBytecode(compiler, effectData);
            }

            if (hasErrors)
            {
                Abort();
            }

            if (!viewOnly)
            {
                Console.WriteLine();

                if (CompileOnlyIfNewer && compilerResult.DependencyFilePath != null)
                {
                    // Dependency file save to
                    Console.WriteLine("Save dependency list to [{0}]", outputDependencyFilePath);
                }

                if (OutputClassFile != null)
                {
                    var codeWriter = new EffectDataCodeWriter
                    {
                        Namespace = OutputNamespace,
                        ClassName = OutputClassname ?? Path.GetFileNameWithoutExtension(OutputClassFile),
                        FieldName = OutputFieldName,
                    };

                    Console.WriteLine("Save C# code output to [{0}]", OutputClassFile);
                    using (var stream = new NativeFileStream(OutputClassFile, NativeFileMode.Create, NativeFileAccess.Write, NativeFileShare.Write)) codeWriter.Write(effectData, new StreamWriter(stream, Encoding.UTF8));
                }

                if (options.OutputFile != null)
                {
                    Console.WriteLine("Save binary output to [{0}]", options.OutputFile);
                    // Save the result
                    effectData.Save(options.OutputFile);
                }
            }
        }
Beispiel #25
0
        public FileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
        {
            // This will perform validation on path
            _fileName = Path.GetFullPath(path);

            // make sure mode, access, and share are within range
            if (mode < FileMode.CreateNew || mode > FileMode.Append ||
                access < FileAccess.Read || access > FileAccess.ReadWrite ||
                share < FileShare.None || share > FileShare.ReadWrite)
            {
                throw new ArgumentOutOfRangeException();
            }

            // Get wantsRead and wantsWrite from access, note that they cannot both be false
            bool wantsRead  = (access & FileAccess.Read) == FileAccess.Read;
            bool wantsWrite = (access & FileAccess.Write) == FileAccess.Write;

            // You can't open for readonly access (wantsWrite == false) when
            // mode is CreateNew, Create, Truncate or Append (when it's not Open or OpenOrCreate)
            if (mode != FileMode.Open && mode != FileMode.OpenOrCreate && !wantsWrite)
            {
                throw new ArgumentException();
            }

            // We need to register the share information prior to the actual file open call (the NativeFileStream ctor)
            // so subsequent file operation on the same file will behave correctly
            _fileRecord = FileSystemManager.AddToOpenList(_fileName, (int)access, (int)share);

            try
            {
                uint attributes = NativeIO.GetAttributes(_fileName);
                bool exists     = (attributes != 0xFFFFFFFF);
                bool isReadOnly = (exists) ? (((FileAttributes)attributes) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly : false;

                // If the path specified is an existing directory, fail
                if (exists && ((((FileAttributes)attributes) & FileAttributes.Directory) == FileAttributes.Directory))
                {
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.UnauthorizedAccess);
                }

                // The seek limit is 0 (the beginning of the file) for all modes except Append
                _seekLimit = 0;

                switch (mode)
                {
                case FileMode.CreateNew:     // if the file exists, IOException is thrown
                    if (exists)
                    {
                        throw new IOException("", (int)IOException.IOExceptionErrorCode.PathAlreadyExists);
                    }
                    _nativeFileStream = new NativeFileStream(_fileName, bufferSize);
                    break;

                case FileMode.Create:     // if the file exists, it should be overwritten
                    _nativeFileStream = new NativeFileStream(_fileName, bufferSize);
                    if (exists)
                    {
                        _nativeFileStream.SetLength(0);
                    }
                    break;

                case FileMode.Open:     // if the file does not exist, IOException/FileNotFound is thrown
                    if (!exists)
                    {
                        throw new IOException("", (int)IOException.IOExceptionErrorCode.FileNotFound);
                    }
                    _nativeFileStream = new NativeFileStream(_fileName, bufferSize);
                    break;

                case FileMode.OpenOrCreate:     // if the file does not exist, it is created
                    _nativeFileStream = new NativeFileStream(_fileName, bufferSize);
                    break;

                case FileMode.Truncate:     // the file would be overwritten. if the file does not exist, IOException/FileNotFound is thrown
                    if (!exists)
                    {
                        throw new IOException("", (int)IOException.IOExceptionErrorCode.FileNotFound);
                    }
                    _nativeFileStream = new NativeFileStream(_fileName, bufferSize);
                    _nativeFileStream.SetLength(0);
                    break;

                case FileMode.Append:     // Opens the file if it exists and seeks to the end of the file. Append can only be used in conjunction with FileAccess.Write
                    // Attempting to seek to a position before the end of the file will throw an IOException and any attempt to read fails and throws an NotSupportedException
                    if (access != FileAccess.Write)
                    {
                        throw new ArgumentException();
                    }
                    _nativeFileStream = new NativeFileStream(_fileName, bufferSize);
                    _seekLimit        = _nativeFileStream.Seek(0, (uint)SeekOrigin.End);
                    break;

                    // We've already checked the mode value previously, so no need for default
                    //default:
                    //    throw new ArgumentOutOfRangeException();
                }

                // Now that we have a valid NativeFileStream, we add it to the FileRecord, so it could gets clean up
                // in case an eject or force format
                _fileRecord.NativeFileStream = _nativeFileStream;

                // Retrive the filesystem capabilities
                _nativeFileStream.GetStreamProperties(out _canRead, out _canWrite, out _canSeek);

                // If the file is readonly, regardless of the filesystem capability, we'll turn off write
                if (isReadOnly)
                {
                    _canWrite = false;
                }

                // Make sure the requests (wantsRead / wantsWrite) matches the filesystem capabilities (canRead / canWrite)
                if ((wantsRead && !_canRead) || (wantsWrite && !_canWrite))
                {
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.UnauthorizedAccess);
                }

                // finally, adjust the _canRead / _canWrite to match the requests
                if (!wantsWrite)
                {
                    _canWrite = false;
                }
                else if (!wantsRead)
                {
                    _canRead = false;
                }
            }
            catch
            {
                // something went wrong, clean up and re-throw the exception
                if (_nativeFileStream != null)
                {
                    _nativeFileStream.Close();
                }

                FileSystemManager.RemoveFromOpenList(_fileRecord);

                throw;
            }
        }
Beispiel #26
0
 public void CheckFileStreamException()
 {
     var test = new NativeFileStream("blabla", NativeFileMode.Open, NativeFileAccess.Read);
 }
Beispiel #27
0
 /// <summary>
 /// Saves this <see cref="ModelData"/> instance to the specified file.
 /// </summary>
 /// <param name="fileName">The output filename.</param>
 public void Save(string fileName)
 {
     using (var stream = new NativeFileStream(fileName, NativeFileMode.Create, NativeFileAccess.Write, NativeFileShare.Write))
         Save(stream);
 }
Beispiel #28
0
 /// <summary>
 /// Loads an <see cref="ModelData"/> from the specified file.
 /// </summary>
 /// <param name="fileName">The filename.</param>
 /// <returns>A <see cref="ModelData"/> </returns>
 public static ModelData Load(string fileName)
 {
     using (var stream = new NativeFileStream(fileName, NativeFileMode.Open, NativeFileAccess.Read))
         return(Load(stream));
 }
 public static FileDependencyList FromFile(string file)
 {
     using (var stream = new NativeFileStream(file, NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.ReadWrite)) return(FromStream(stream));
 }
Beispiel #30
0
        /// <summary>
        /// Loads a model from a file on disk.
        /// </summary>
        /// <param name="device">DirectX device.</param>
        /// <param name="filename">Path of the model.</param>
        /// <returns>Loaded model.</returns>
        public static Model Load(SharpDX.Direct3D11.Device1 device, string filename)
        {
            Model newModel = new Model();

            newModel.modelPath = filename;

            NativeFileStream fileStream = new NativeFileStream(filename, NativeFileMode.Open, NativeFileAccess.Read);

            using (BinaryReader reader = new BinaryReader(fileStream))
            {
                Vector3 bbMin;
                Vector3 bbMax;

                bbMin.X = reader.ReadSingle();
                bbMin.Y = reader.ReadSingle();
                bbMin.Z = reader.ReadSingle();

                bbMax.X = reader.ReadSingle();
                bbMax.Y = reader.ReadSingle();
                bbMax.Z = reader.ReadSingle();

                newModel.BBox = new BoundingBox(bbMin, bbMax);

                int numMeshes = reader.ReadInt32();

                for (int i = 0; i < numMeshes; i++)
                {
                    List <ModelVertex> vertices        = new List <ModelVertex>();
                    List <int>         indices         = new List <int>();
                    List <int>         invertedIndices = new List <int>();

                    int numVertices = reader.ReadInt32();

                    for (int j = 0; j < numVertices; j++)
                    {
                        float x = reader.ReadSingle();
                        float y = reader.ReadSingle();
                        float z = reader.ReadSingle();

                        float s = reader.ReadSingle();
                        float t = reader.ReadSingle();

                        vertices.Add(new ModelVertex(new Vector3(x, y, z), new Vector2(s, t)));
                    }

                    int numIndices = reader.ReadInt32();

                    for (int j = 0; j < numIndices; j++)
                    {
                        int index = reader.ReadInt32();
                        indices.Add(index);
                        invertedIndices.Add(index);

                        if ((j > 0) && ((j + 1) % 3 == 0))
                        {
                            int tempIndex = invertedIndices[j - 1];
                            invertedIndices[j - 1] = invertedIndices[j];
                            invertedIndices[j]     = tempIndex;
                        }
                    }

                    Buffer vertexBuffer        = Buffer.Create(device, BindFlags.VertexBuffer, vertices.ToArray());
                    Buffer indexBuffer         = Buffer.Create(device, BindFlags.IndexBuffer, indices.ToArray());
                    Buffer invertedIndexBuffer = Buffer.Create(device, BindFlags.IndexBuffer, invertedIndices.ToArray());
                    newModel.meshes.Add(new ModelMesh(vertexBuffer, indexBuffer, invertedIndexBuffer, numIndices));
                }
            }

            return(newModel);
        }
Beispiel #31
0
 /// <summary>
 /// Initializes a new wave bank from the file located at the provided file path.
 /// </summary>
 /// <param name="audioManager">The associated audio manager.</param>
 /// <param name="filePath">The path to the wave bank file.</param>
 /// <returns>The wave bank initialized from provided file.</returns>
 public static WaveBank FromFile(AudioManager audioManager, string filePath)
 {
     using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read))
         return new WaveBank(audioManager, stream);
 }
Beispiel #32
0
 /// <summary>
 /// Creates a new instance of the <see cref="SoundEffect"/> class from the specified file path.
 /// </summary>
 /// <param name="audioManager">The audio manager associated to the created instance.</param>
 /// <param name="filePath">The path to the file from which to create the effect.</param>
 /// <returns>The created effect.</returns>
 public static SoundEffect FromFile(AudioManager audioManager, string filePath)
 {
     using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read))
         return FromStream(audioManager, stream, Path.GetFileNameWithoutExtension(filePath));
 }