/* FILE IO METHODS */ /// <summary> /// Open a text file containing HLSL shader byte code. Search nearby directories if an absolute path /// to the file isn't provided. /// </summary> /// <param name="type"></param> /// <param name="fileName">The name of the shader file or absolute path to it (including the name).</param> /// <returns></returns> public Stream Open(IncludeType type, string fileName, Stream parentStream) { // Pull the working directory, or use the environment's if one isn't provided string currentDir = CurrentDirectory.Peek(); if (currentDir == null) { currentDir = Environment.CurrentDirectory; } // Examine the current working directory & subdirectories for the shader files to include string filePath = fileName; if (!Path.IsPathRooted(fileName)) { List<string> dirsToSearch = new List<string> { currentDir }; dirsToSearch.AddRange(IncludeDirectories); foreach (var dirPath in dirsToSearch) { string currentFile = Path.Combine(dirPath, fileName); if (NativeFile.Exists(currentFile)) { filePath = currentFile; break; } } } if (filePath == null || !NativeFile.Exists(filePath)) { throw new FileNotFoundException(String.Format("Unable to find the shader file [{0}]", filePath ?? fileName)); } // Open & read the found file NativeFileStream fileStream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read); CurrentDirectory.Push(Path.GetDirectoryName(filePath)); return fileStream; }
protected override Diagnostics.Logger ProcessFileAndGetLogResults(string inputFilePath, string outputFilePath, string dependencyFilePath, TkItem item) { var compilerResult = compiler.CompileFromFile(inputFilePath, Debug ? EffectCompilerFlags.Debug : EffectCompilerFlags.None, 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; }
/// <summary> /// Saves this instance to a file. /// </summary> /// <param name="fileName">The destination file.</param> /// <param name="fileType">Specify the output format.</param> /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks> public void Save(string fileName, ImageFileType fileType) { using (var imageStream = new SDXIO.NativeFileStream(fileName, SDXIO.NativeFileMode.Create, SDXIO.NativeFileAccess.Write)) { Save(imageStream, fileType); } }
public static D2D.Bitmap LoadBitmap(D2D.RenderTarget renderTarget, string imagePath) { FileInfo fi = new FileInfo(imagePath); if (!fi.Exists) { var ext = fi.Extension; string newExt = ""; if (ext == ".jpg") { newExt = ".png"; } else if (ext == ".png") { newExt = ".jpg"; } string newName = fi.FullName.Remove(fi.FullName.Length - 4, 4); imagePath = newName + newExt; } D2D.Bitmap bmp; if (Cached.ContainsKey(imagePath)) { bmp = Cached[imagePath]; if (bmp.IsDisposed) { Cached.TryRemove(imagePath, out _); } else { return(bmp); } } WIC.ImagingFactory imagingFactory = new WIC.ImagingFactory(); DXIO.NativeFileStream fileStream = new DXIO.NativeFileStream(imagePath, DXIO.NativeFileMode.Open, DXIO.NativeFileAccess.Read); WIC.BitmapDecoder bitmapDecoder = new WIC.BitmapDecoder(imagingFactory, fileStream, WIC.DecodeOptions.CacheOnDemand); WIC.BitmapFrameDecode frame = bitmapDecoder.GetFrame(0); WIC.FormatConverter converter = new WIC.FormatConverter(imagingFactory); converter.Initialize(frame, WIC.PixelFormat.Format32bppPRGBA); var bitmapProperties = new D2D.BitmapProperties(new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied)); //Size2 size = new Size2(frame.Size.Width, frame.Size.Height); bmp = D2D.Bitmap.FromWicBitmap(renderTarget, converter, bitmapProperties); if (!Cached.ContainsKey(imagePath)) { Cached.TryAdd(imagePath, bmp); //LogUtil.LogInfo("Created cache."); } return(bmp); }
/// <summary> /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file. /// </summary> /// <param name="path">The file to open for reading. </param> /// <returns>A byte array containing the contents of the file.</returns> public static byte[] ReadAllBytes(string path) { byte[] buffer; using (var stream = new NativeFileStream(path, NativeFileMode.Open, NativeFileAccess.Read)) { int offset = 0; long length = stream.Length; if (length > 0x7fffffffL) { throw new IOException("File too long"); } int count = (int)length; buffer = new byte[count]; while (count > 0) { int num4 = stream.Read(buffer, offset, count); if (num4 == 0) { throw new EndOfStreamException(); } offset += num4; count -= num4; } } return buffer; }
public static string ReadAllText(string path, Encoding encoding) { using (NativeFileStream nativeFileStream = new NativeFileStream(path, NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read)) { using (StreamReader streamReader = new StreamReader((Stream) nativeFileStream, encoding, true, 1024)) return streamReader.ReadToEnd(); } }
/// <summary> /// Opens a text file, reads all lines of the file, and then closes the file. /// </summary> /// <param name="path">The file to open for reading. </param> /// <returns>A string containing all lines of the file.</returns> public static string ReadAllText(string path, Encoding encoding) { using (var stream = new NativeFileStream(path, NativeFileMode.Open, NativeFileAccess.Read)) { using (StreamReader reader = new StreamReader(stream, encoding, true, 0x400)) { return reader.ReadToEnd(); } } }
private static void LoadBitmaps() { var fac = new SharpDX.WIC.ImagingFactory(); var target = GraphicsWindow.Instance.RenderTarget2D; var stream = new NativeFileStream(Application.StartupPath + "\\Images\\Ship 1.png", NativeFileMode.Open, NativeFileAccess.Read); var decoder = new BitmapDecoder(fac, stream, DecodeOptions.CacheOnDemand); var frame = decoder.GetFrame(0); var converter = new FormatConverter(fac); converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA); BitShip1 = Bitmap1.FromWicBitmap(GraphicsWindow.Instance.RenderTarget2D, converter); }
public static D2D.Bitmap LoadBitmap(this D2D.RenderTarget renderTarget, string imagePath) { lock (LockObj) { Sw.Start(); D2D.Bitmap bmp; if (Cached.ContainsKey(imagePath)) { Cached[imagePath].Time = DateTime.Now; bmp = Cached[imagePath].Bitmap; Sw.Stop(); LogUtil.LogInfo($"Cache: {Sw.ElapsedMilliseconds}ms."); } else { WIC.ImagingFactory imagingFactory = new WIC.ImagingFactory(); DXIO.NativeFileStream fileStream = new DXIO.NativeFileStream(imagePath, DXIO.NativeFileMode.Open, DXIO.NativeFileAccess.Read); WIC.BitmapDecoder bitmapDecoder = new WIC.BitmapDecoder(imagingFactory, fileStream, WIC.DecodeOptions.CacheOnDemand); WIC.BitmapFrameDecode frame = bitmapDecoder.GetFrame(0); WIC.FormatConverter converter = new WIC.FormatConverter(imagingFactory); converter.Initialize(frame, WIC.PixelFormat.Format32bppPRGBA); var bitmapProperties = new D2D.BitmapProperties(new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied)); //Size2 size = new Size2(frame.Size.Width, frame.Size.Height); bmp = D2D.Bitmap.FromWicBitmap(renderTarget, converter, bitmapProperties); Sw.Stop(); LogUtil.LogInfo($"Load: {Sw.ElapsedMilliseconds}ms."); } if (!Cached.ContainsKey(imagePath) && Sw.ElapsedMilliseconds > 50) { Cached.TryAdd(imagePath, new CacheInfo(DateTime.Now, bmp)); LogUtil.LogInfo("Created cache."); if (Cached.Count > 50) { Cached.TryRemove(Cached.OrderByDescending(c => c.Value.Time).First().Key, out _); LogUtil.LogInfo("Removed unused cache."); } } Sw.Reset(); return(bmp); } }
public static D2D.Bitmap LoadFromFile(D2D.RenderTarget renderTarget, string filePath) { WIC.ImagingFactory imagingFactory = new WIC.ImagingFactory(); DXIO.NativeFileStream fileStream = new DXIO.NativeFileStream(filePath, DXIO.NativeFileMode.Open, DXIO.NativeFileAccess.Read); WIC.BitmapDecoder bitmapDecoder = new WIC.BitmapDecoder(imagingFactory, fileStream, WIC.DecodeOptions.CacheOnDemand); WIC.BitmapFrameDecode frame = bitmapDecoder.GetFrame(0); WIC.FormatConverter converter = new WIC.FormatConverter(imagingFactory); converter.Initialize(frame, WIC.PixelFormat.Format32bppPRGBA); return(D2D.Bitmap.FromWicBitmap(RenderForm.RenderTarget, converter)); }
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; }
public unsafe int Read(IntPtr buffer, int offset, int count) { if (buffer == IntPtr.Zero) { throw new ArgumentNullException("buffer"); } int numberOfBytesRead; if (!NativeFile.ReadFile(this.handle, (IntPtr)((void *)((IntPtr)(void *)buffer + offset)), count, out numberOfBytesRead, IntPtr.Zero)) { throw new IOException("Unable to read from file", NativeFileStream.MarshalGetLastWin32Error()); } this.position += (long)numberOfBytesRead; return(numberOfBytesRead); }
/// <summary> /// Load the sound data from the sound-file. /// </summary> public override void Load() { var nativeFileStream = new NativeFileStream( File.Path, NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read); m_soundStream = new SoundStream(nativeFileStream); m_waveFormat = m_soundStream.Format; m_buffer = new AudioBuffer { Stream = m_soundStream.ToDataStream(), AudioBytes = (int)m_soundStream.Length, Flags = BufferFlags.EndOfStream }; OnLoaded(); }
public SoundEffect(string soundFxPath) { _xaudio = new XAudio2(); var masteringsound = new MasteringVoice(_xaudio); var nativefilestream = new NativeFileStream( soundFxPath, 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 }; }
public override void SetLength(long value) { long distanceToMoveHigh; if (!NativeFile.SetFilePointerEx(this.handle, value, out distanceToMoveHigh, SeekOrigin.Begin)) { throw new IOException("Unable to seek to this position", NativeFileStream.MarshalGetLastWin32Error()); } if (!NativeFile.SetEndOfFile(this.handle)) { throw new IOException("Unable to set the new length", NativeFileStream.MarshalGetLastWin32Error()); } if (this.position < value) { this.Seek(this.position, SeekOrigin.Begin); } else { this.Seek(0L, SeekOrigin.End); } }
public static byte[] ReadAllBytes(string path) { byte[] buffer; using (NativeFileStream nativeFileStream = new NativeFileStream(path, NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read)) { int offset = 0; long length = nativeFileStream.Length; if (length > (long) int.MaxValue) throw new IOException("File too long"); int count = (int) length; buffer = new byte[count]; while (count > 0) { int num = ((Stream) nativeFileStream).Read(buffer, offset, count); if (num == 0) throw new EndOfStreamException(); offset += num; count -= num; } } return buffer; }
public NativeFileStream(string fileName, NativeFileMode fileMode, NativeFileAccess access, NativeFileShare share = NativeFileShare.Read) { this.handle = NativeFile.Create(fileName, access, share, IntPtr.Zero, fileMode, NativeFileOptions.None, IntPtr.Zero); if (this.handle == new IntPtr(-1)) { int lastWin32Error = NativeFileStream.MarshalGetLastWin32Error(); if (lastWin32Error == 2) { throw new FileNotFoundException("Unable to find file", fileName); } Result resultFromWin32Error = Result.GetResultFromWin32Error(lastWin32Error); throw new IOException(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Unable to open file {0}", new object[1] { (object)fileName }), resultFromWin32Error.Code); } else { this.canRead = (NativeFileAccess)0 != (access & NativeFileAccess.Read); this.canWrite = (NativeFileAccess)0 != (access & NativeFileAccess.Write); this.canSeek = true; } }
/// <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) { SDXIO.NativeFileStream stream = null; IntPtr memoryPtr = IntPtr.Zero; int size; try { stream = new SDXIO.NativeFileStream(fileName, SDXIO.NativeFileMode.Open, SDXIO.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)); }
private void btnXAudio2_Click(object sender, RoutedEventArgs e) { XAudio2 xaudio; MasteringVoice masteringVoice; xaudio = new XAudio2(); masteringVoice = new MasteringVoice(xaudio); var nativefilestream = new NativeFileStream( @"Assets\Clk_1Sec1.wav", NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read); var soundstream = new SoundStream(nativefilestream); var waveFormat = soundstream.Format; var buffer = new AudioBuffer { Stream = soundstream.ToDataStream(), AudioBytes = (int)soundstream.Length, Flags = BufferFlags.EndOfStream, }; var sourceVoice = new SourceVoice(xaudio, waveFormat, true); // There is also support for shifting the frequency. sourceVoice.SetFrequencyRatio(1.0f); sourceVoice.SubmitSourceBuffer(buffer, soundstream.DecodedPacketsInfo); sourceVoice.Start(); }
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; }
/// <summary> /// Open a text file containing HLSL shader byte code. Search nearby directories if an absolute path /// to the file isn't provided. /// </summary> /// <param name="type"></param> /// <param name="fileName">The name of the shader file or absolute path to it (including the name).</param> /// <returns></returns> public Stream Open(IncludeType type, string fileName, Stream parentStream) { string shaderFile; if (!Path.IsPathRooted(fileName)) { string shaderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Shaders"); shaderFile = Path.Combine(shaderPath, Path.GetFileName(fileName)); } else { shaderFile = fileName; } if (!File.Exists(shaderFile)) { throw new FileNotFoundException("Could not find the shader file {0}", shaderFile); } // Open & read the found file NativeFileStream fileStream = new NativeFileStream(shaderFile, NativeFileMode.Open, NativeFileAccess.Read); return fileStream; }
public static ContentCompilerResult CompileFromFile(string fileName, ModelCompilerOptions compilerOptions) { using (var stream = new NativeFileStream(fileName, NativeFileMode.Open, NativeFileAccess.Read)) { return Compile(stream, fileName, compilerOptions); } }
/// <summary> /// Compiles an XML font file description to a file. Optionally output dependency file. /// </summary> /// <param name="sourceXmlFile">The source XML file.</param> /// <param name="outputFile">The output file.</param> /// <param name="dependencyFile">The dependency file.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns> public static ContentCompilerResult CompileAndSave(string sourceXmlFile, string outputFile, string dependencyFile = null) { var logger = new Logger(); var result = new ContentCompilerResult { Logger = logger }; try { var fontDescription = FontDescription.Load(sourceXmlFile); var defaultOutputFile = Path.GetFileNameWithoutExtension(sourceXmlFile); // Compiles to SpriteData outputFile = outputFile ?? defaultOutputFile; result.IsContentGenerated = true; if(dependencyFile != null) { if(!FileDependencyList.CheckForChanges(dependencyFile)) { result.IsContentGenerated = false; } } if(result.IsContentGenerated) { // Make sure that directory name doesn't collide with filename var directoryName = Path.GetDirectoryName(outputFile + ".tmp"); if(!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } using(var stream = new NativeFileStream(outputFile, NativeFileMode.Create, NativeFileAccess.Write)) { Compile(fontDescription, stream); if(dependencyFile != null) { var dependencies = new FileDependencyList(); dependencies.AddDefaultDependencies(); dependencies.AddDependencyPath(sourceXmlFile); dependencies.Save(dependencyFile); } } } } catch(FontException ex) { logger.Error(ex.Message); } catch (Exception ex) { logger.Error(ex.ToString()); } return result; }
/// <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; IntPtr 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); }
/// <summary> /// Saves this instance to a file. /// </summary> /// <param name="fileName">The destination file.</param> /// <param name="fileType">Specify the output format.</param> /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks> public void Save(string fileName, ImageFileType fileType) { using (var imageStream = new NativeFileStream(fileName, NativeFileMode.Create, NativeFileAccess.Write)) { Save(imageStream, fileType); } }
/// <summary> /// Loads an <see cref="EffectData"/> from the specified file. /// </summary> /// <param name="device">The graphics device</param> /// <param name="fileName">The filename.</param> /// <returns>An <see cref="EffectData"/> </returns> public static SpriteFont Load(GraphicsDevice device, string fileName) { var fileDirectory = Path.GetDirectoryName(fileName); using (var stream = new NativeFileStream(fileName, NativeFileMode.Open, NativeFileAccess.Read)) return Load(device, stream, bitmapName => Texture2D.Load(device, Path.Combine(fileDirectory, bitmapName))); }
/// <summary> /// Loads an existing image file into a SharpDX.Direct2D1.Bitmap1. /// </summary> /// <param name="filePath">Relative path to the content file.</param> /// <returns>Loaded bitmap.</returns> private SharpDX.Direct2D1.Bitmap1 LoadBitmapFromContentFile(string filePath) { SharpDX.Direct2D1.Bitmap1 newBitmap; // Neccessary for creating WIC objects. ImagingFactory imagingFactory = new ImagingFactory(); NativeFileStream fileStream = new NativeFileStream(Package.Current.InstalledLocation.Path + filePath, NativeFileMode.Open, NativeFileAccess.Read); // Used to read the image source file. BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand); // Get the first frame of the image. BitmapFrameDecode frame = bitmapDecoder.GetFrame(0); // Convert it to a compatible pixel format. FormatConverter converter = new FormatConverter(imagingFactory); converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA); // Create the new Bitmap1 directly from the FormatConverter. newBitmap = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(d2dContext, converter); Utilities.Dispose(ref bitmapDecoder); Utilities.Dispose(ref fileStream); Utilities.Dispose(ref imagingFactory); return newBitmap; }
public static void WriteSpriteFont(FontDescription options, string outputFilename, Glyph[] glyphs, float lineSpacing, Bitmap bitmap) { using (var stream = new NativeFileStream(outputFilename, NativeFileMode.Create, NativeFileAccess.Write)) { WriteSpriteFont(options, stream, glyphs, lineSpacing, bitmap); } }
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; hasErrors = false; // ---------------------------------------------------------------- // Pre check files // ---------------------------------------------------------------- if (options.OutputClassFile == null && options.OutputFile == null) { options.OutputFile = "output.tkfxo"; } // Check for output files bool outputFileExist = options.OutputClassFile != null && File.Exists(options.OutputClassFile); if (options.OutputFile != null && !File.Exists(options.OutputFile)) { outputFileExist = 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(); } // New Compiler var compiler = new EffectCompiler(); string outputDependencyDirPath = Path.Combine(Environment.CurrentDirectory, OutputDependencyDirectory); string outputDependencyFilePath = Path.Combine(outputDependencyDirPath, compiler.GetDependencyFileNameFromEffectPath(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); } } }
protected override bool ProcessItem(TkFxcItem item) { bool hasErrors = false; var inputFilePath = item.InputFilePath; var outputFilePath = item.OutputFilePath; var dependencyFilePath = Path.Combine(Path.Combine(ProjectDirectory.ItemSpec, IntermediateDirectory.ItemSpec), compiler.GetDependencyFileNameFromEffectPath(item.LinkName)); // Creates the dependency directory if it does no exist yet. var dependencyDirectoryPath = Path.GetDirectoryName(dependencyFilePath); if (!Directory.Exists(dependencyDirectoryPath)) { Directory.CreateDirectory(dependencyDirectoryPath); } Log.LogMessage(MessageImportance.High, "Check Toolkit FX file to compile {0} with dependency file {1}", inputFilePath, dependencyFilePath); if (compiler.CheckForChanges(dependencyFilePath) || !File.Exists(outputFilePath)) { Log.LogMessage(MessageImportance.High, "Start to compile {0}", inputFilePath); var compilerResult = compiler.CompileFromFile(inputFilePath, Debug ? EffectCompilerFlags.Debug : EffectCompilerFlags.None, null, null, item.DynamicCompiling, dependencyFilePath); if (compilerResult.HasErrors) { hasErrors = true; } else { Log.LogMessage(MessageImportance.High, "Compiled successfull {0} to {1}", inputFilePath, outputFilePath); } foreach (var message in compilerResult.Logger.Messages) { var text = message.ToString(); string line = null; var textReader = new StringReader(text); while ((line = textReader.ReadLine()) != null) { var match = parseMessage.Match(line); if (match.Success) { var filePath = match.Groups[1].Value; var lineNumber = int.Parse(match.Groups[2].Value); var colNumberText = match.Groups[3].Value; int colStartNumber; int colEndNumber; var colMatch = matchNumberRange.Match(colNumberText); if (colMatch.Success) { int.TryParse(colMatch.Groups[1].Value, out colStartNumber); int.TryParse(colMatch.Groups[2].Value, out colEndNumber); } else { int.TryParse(colNumberText, out colStartNumber); colEndNumber = colStartNumber; } var msgType = match.Groups[4].Value; var msgCode = match.Groups[5].Value; var msgText = match.Groups[6].Value; if (string.Compare(msgType, "error", StringComparison.InvariantCultureIgnoreCase) == 0) { Log.LogError(string.Empty, msgCode, string.Empty, filePath, lineNumber, colStartNumber, lineNumber, colEndNumber, msgText); } else if (string.Compare(msgType, "warning", StringComparison.InvariantCultureIgnoreCase) == 0) { Log.LogWarning(string.Empty, msgCode, string.Empty, filePath, lineNumber, colStartNumber, lineNumber, colEndNumber, msgText); } else if (string.Compare(msgType, "info", StringComparison.InvariantCultureIgnoreCase) == 0) { Log.LogWarning(string.Empty, msgCode, string.Empty, filePath, lineNumber, colStartNumber, lineNumber, colEndNumber, msgText); } else { Log.LogWarning(line); } } else { Log.LogWarning(line); } } } if (!compilerResult.HasErrors && compilerResult.EffectData != null) { try { var directoryName = Path.GetDirectoryName(outputFilePath); if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } 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); } } catch (Exception ex) { Log.LogError("Cannot write compiled file to {0} : {1}", inputFilePath, ex.Message); hasErrors = true; } } } return !hasErrors; }
/// <summary> /// Loads an <see cref="EffectData"/> from the specified file. /// </summary> /// <param name="fileName">The filename.</param> /// <returns>An <see cref="EffectData"/> </returns> public static EffectData Load(string fileName) { using (var stream = new NativeFileStream(fileName, NativeFileMode.Open, NativeFileAccess.Read)) return Load(stream); }
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<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 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; var archiveBytecode = new EffectData(); bool hasErrors = false; bool isFileUpToDate = CompileOnlyIfNewer; // ---------------------------------------------------------------- // Pre check files // ---------------------------------------------------------------- var outputTime = new DateTime(); var outputFileName = OutputClassFile ?? OutputFile; if (!ViewOnly && CompileOnlyIfNewer) { if (OutputClassFile != null) { if (File.Exists(OutputClassFile)) outputTime = File.GetLastWriteTime(OutputClassFile); } else if (OutputFile != null) { if (File.Exists(OutputFile)) outputTime = File.GetLastWriteTime(OutputFile); } else { ErrorColor(); Console.WriteLine("Missing /Fo OutputFile or /Fc OutputClassFile"); ResetColor(); Environment.Exit(-1); } // If the assembly is more recent than the ouput file, then regenerate it var assemblyTime = File.GetLastWriteTime(Assembly.GetExecutingAssembly().Location); if (assemblyTime > outputTime) { isFileUpToDate = false; } else { // Else check that all files are not more recent. foreach (var fxFile in options.FxFiles) { var filePath = Path.Combine(Environment.CurrentDirectory, fxFile); if (!File.Exists(filePath)) { isFileUpToDate = false; break; } if (File.GetLastWriteTime(filePath) > outputTime) { isFileUpToDate = false; break; } } } } if (!ViewOnly && isFileUpToDate) { Console.WriteLine("Nothing to compile, output file is up to date [{0}]", outputFileName); Environment.Exit(0); } // ---------------------------------------------------------------- // Process each fx files / tkfxo files // ---------------------------------------------------------------- foreach (var fxFile in options.FxFiles) { var filePath = Path.Combine(Environment.CurrentDirectory, fxFile); if (!File.Exists(filePath)) { ErrorColor(); Console.Error.WriteLine("File [{0}] does not exist", fxFile); ResetColor(); hasErrors = true; continue; } EffectData effectData = null; // Try to load this file as a precompiled file effectData = EffectData.Load(fxFile); if (effectData != null) { Console.WriteLine("Load Compiled File [{0}]", fxFile); } else { // Compile the fx file Console.WriteLine("Compile Effect File [{0}]", filePath); var effectBytecode = EffectCompiler.Compile(File.ReadAllText(filePath), filePath, flags, macros, options.IncludeDirs); // If there is any warning, errors, turn Error color on if (effectBytecode.Logger.Messages.Count > 0) { ErrorColor(); } // Show a message error for the current file if (effectBytecode.HasErrors) { Console.Error.WriteLine("Error when compiling file [{0}]:", fxFile); hasErrors = true; } // Print all messages (warning and errors) foreach (var logMessage in effectBytecode.Logger.Messages) { Console.WriteLine(logMessage); } // If we have some messages, reset the color back if (effectBytecode.Logger.Messages.Count > 0) { ResetColor(); } effectData = effectBytecode.EffectData; } // If there is no errors, merge the result to the final archive if (!hasErrors) { if (ProcessBytecode(effectData, archiveBytecode)) hasErrors = true; } } if (hasErrors) { ErrorColor(); Console.Error.WriteLine("Compilation has errors. Process aborted."); ResetColor(); Environment.Exit(-1); } else if (!ViewOnly) { Console.WriteLine(); 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(archiveBytecode, new StreamWriter(stream, Encoding.UTF8)); } else { Console.WriteLine("Save output to [{0}]", options.OutputFile); // Save the result archiveBytecode.Save(options.OutputFile); } } }
/// <summary> /// Loads a <see cref="SpriteFontData"/> from the specified stream. /// </summary> /// <param name="fileName">The filename.</param> /// <param name="bitmapDataLoader">A delegate to load bitmap data that are not stored in the buffer.</param> /// <returns>An <see cref="SpriteFontData"/>. Null if the stream is not a serialized <see cref="SpriteFontData"/>.</returns> public static SpriteFontData Load(string fileName, SpriteFontBitmapDataLoaderDelegate bitmapDataLoader = null) { using (var stream = new NativeFileStream(fileName, NativeFileMode.Open, NativeFileAccess.Read)) return Load(stream, bitmapDataLoader); }
internal static void CompareImage(Image from, Image to, string file = null) { // Check that description is identical to original image loaded from the disk. Assert.AreEqual(from.Description, to.Description, "Image description is different for image [{0}]", file); // Check that number of buffers are identical. Assert.AreEqual(from.PixelBuffer.Count, to.PixelBuffer.Count, "PixelBuffer size is different for image [{0}]", file); // Compare each pixel buffer for (int j = 0; j < from.PixelBuffer.Count; j++) { var srcPixelBuffer = from.PixelBuffer[j]; var dstPixelBuffer = to.PixelBuffer[j]; // Check only row and slice pitch Assert.AreEqual(srcPixelBuffer.RowStride, dstPixelBuffer.RowStride, "RowPitch is different for index [{0}], image [{1}]", j, file); Assert.AreEqual(srcPixelBuffer.BufferStride, dstPixelBuffer.BufferStride, "SlicePitch is different for index [{0}], image [{1}]", j, file); var isSameBuffer = Utilities.CompareMemory(srcPixelBuffer.DataPointer, dstPixelBuffer.DataPointer, srcPixelBuffer.BufferStride); if (!isSameBuffer) { var stream = new NativeFileStream("test_from.dds", NativeFileMode.Create, NativeFileAccess.Write, NativeFileShare.Write); stream.Write(srcPixelBuffer.DataPointer, 0, srcPixelBuffer.BufferStride); stream.Close(); stream = new NativeFileStream("test_to.dds", NativeFileMode.Create, NativeFileAccess.Write, NativeFileShare.Write); stream.Write(dstPixelBuffer.DataPointer, 0, dstPixelBuffer.BufferStride); stream.Close(); } Assert.True(isSameBuffer, "Content of PixelBuffer is different for index [{0}], image [{1}]", j, file); } }
/// <summary> /// Saves this <see cref="EffectData"/> 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); }
public static FontDescription Load(string fileName) { using (var stream = new NativeFileStream(fileName, NativeFileMode.Open, NativeFileAccess.Read)) return Load(stream); }
public void CheckFileStreamException() { var test = new NativeFileStream("blabla", NativeFileMode.Open, NativeFileAccess.Read); }
/// <summary> /// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a file stream. /// </summary> /// <param name="factory">The factory.</param> /// <param name="fileStream">The filename.</param> /// <param name="guidVendorRef">The GUID vendor ref.</param> /// <param name="metadataOptions">The metadata options.</param> /// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromFileHandle([In] unsigned int hFile,[In, Optional] const GUID* pguidVendor,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged> public BitmapDecoder(ImagingFactory factory, NativeFileStream fileStream, System.Guid guidVendorRef, SharpDX.WIC.DecodeOptions metadataOptions) { factory.CreateDecoderFromFileHandle(fileStream.Handle, guidVendorRef, metadataOptions, this); }