protected override async void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback) { try { using (var memoryStream = new InMemoryRandomAccessStream()) { await RandomAccessStream.CopyAsync(stream.AsInputStream(), memoryStream); var decoder = await BitmapDecoder.CreateAsync(memoryStream); var frame = await decoder.GetFrameAsync(0); var transform = new BitmapTransform(); transform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor; transform.Rotation = BitmapRotation.None; var dataProvider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb); var data = dataProvider.DetachPixelData(); int width = (int)decoder.PixelWidth; int height = (int)decoder.PixelHeight; Mipmaps = new Mipmap[1]; Size = new Size2(width, height); Mipmaps[0] = new Mipmap(data, width, height, 1, 4); if (flip) { Mipmaps[0].FlipVertical(); } } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected virtual bool init(DisposableI parent, string fileName, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback) { try { if (usage == BufferUsages.Read && !isRenderTarget) { Debug.ThrowError("Texture2D", "Only RenderTargets may be readable"); } video = parent.FindParentOrSelfWithException <Video>(); if (isRenderTarget) { generateMipmaps = false; } if (fileName != null) { texture = new G.Texture2D("/Application/" + fileName, generateMipmaps); } else { texture = new G.Texture2D(width, height, generateMipmaps, Video.surfaceFormat(surfaceFormat), isRenderTarget ? G.PixelBufferOption.Renderable : G.PixelBufferOption.None); } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } if (!isRenderTarget) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } return(true); }
protected unsafe override bool init(IDisposableResource parent, Image image, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback) { initSuccess = base.init(parent, image, width, height, false, multiSampleType, surfaceFormat, renderTargetUsage, usage, true, loadedCallback); if (!initSuccess) { return(false); } try { if (usage == BufferUsages.Write) { Debug.ThrowError("RenderTarget", "Only Textures may be writable"); } uint frameBufferTEMP = 0; GL.GenFramebuffers(1, &frameBufferTEMP); frameBuffer = frameBufferTEMP; uint error; string errorName; if (Video.checkForError(out error, out errorName)) { Debug.ThrowError("RenderTarget", string.Format("{0} {1}: Failed to create renderTarget", error, errorName)); } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } return(true); }
protected override void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback) { try { using (var image = NSImage.FromStream(stream)) { var rep = image.Representations()[0]; int width = rep.PixelsWide; int height = rep.PixelsHigh; Mipmaps = new Mipmap[1]; Size = new Size2(width, height); var data = new byte[width * height * 4]; var emptyRect = RectangleF.Empty; using (CGContext imageContext = new CGBitmapContext(data, width, height, 8, width * 4, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast)) using (var cgImage = image.AsCGImage(ref emptyRect, null, null)) { imageContext.DrawImage(new RectangleF(0, 0, width, height), cgImage); Mipmaps[0] = new Mipmap(data, width, height, 1, 4); if (flip) { Mipmaps[0].FlipVertical(); } } } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
private void init(Stream stream, ShaderVersions shaderVersion, ShaderFloatingPointQuality vsQuality, ShaderFloatingPointQuality psQuality, Loader.LoadedCallbackMethod loadedCallback) { try { video = Parent.FindParentOrSelfWithException <Video>(); shaderVersion = (shaderVersion == ShaderVersions.Max) ? this.video.Caps.MaxShaderVersion : shaderVersion; var code = getShaders(stream); vertex = new VertexShader(this, code[0], shaderVersion, vsQuality); pixel = new PixelShader(this, code[1], shaderVersion, psQuality); program = GL.CreateProgram(); if (program == 0) { Debug.ThrowError("Shader", "Failed to create shader program"); } GL.AttachShader(program, vertex.Shader); GL.AttachShader(program, pixel.Shader); GL.LinkProgram(program); variables = new List <ShaderVariable>(); resources = new List <ShaderResource>(); Video.checkForError(); } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected override void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback) { try { using (var imageData = NSData.FromStream(stream)) using (var image = UIImage.LoadFromData(imageData)) { int width = (int)image.Size.Width; int height = (int)image.Size.Height; Mipmaps = new Mipmap[1]; Size = new Size2(width, height); var data = new byte[width * height * 4]; using (CGContext imageContext = new CGBitmapContext(data, width, height, 8, width * 4, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast)) { imageContext.DrawImage(new RectangleF(0, 0, width, height), image.CGImage); Mipmaps[0] = new Mipmap(data, width, height, 1, 4); if (flip) { Mipmaps[0].FlipVertical(); } } } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
private void init(string filename, Stream stream, ShaderVersions shaderVersion, ShaderFloatingPointQuality vsQuality, ShaderFloatingPointQuality psQuality, Loader.LoadedCallbackMethod loadedCallback) #endif { try { video = Parent.FindParentOrSelfWithException <Video>(); #if WIN32 shaderVersion = (shaderVersion == ShaderVersions.Max) ? video.Cap.MaxShaderVersion : shaderVersion; var code = getShaders(stream); vertex = new VertexShader(this, code[0], shaderVersion); pixel = new PixelShader(this, code[1], shaderVersion); #else await getReflections(filename); var code = getShaders(stream); vertex = new VertexShader(this, code[0]); pixel = new PixelShader(this, code[1]); #endif variables = new List <ShaderVariable>(); resources = new List <ShaderResource>(); } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected override void init(DisposableI parent, Stream stream, int instanceCount, bool looped, Loader.LoadedCallbackMethod loadedCallback) { base.init(parent, stream, instanceCount, looped, loadedCallback); try { audio = parent.FindParentOrSelfWithException <Audio>(); audio.UpdateCallback += Update; this.data = base.data; this.channels = base.channels; this.bitDepth = base.bitDepth; desc = AudioUnitUtils.AUCanonicalASBD(sampleRate, channels); desc.FormatFlags = (AudioFormatFlags)((int)AudioFormatFlags.IsSignedInteger | (int)AudioFormatFlags.IsPacked | (int)AudioFormatFlags.IsNonInterleaved); for (int i = 0; i != instanceCount; ++i) { inactiveInstances.AddLast(new SoundWAVInstance(this, looped)); } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
private void init(string fileName, Stream stream, ShaderVersions shaderVersion, Loader.LoadedCallbackMethod loadedCallback) { try { #if SILVERLIGHT video = Parent.FindParentOrSelfWithException <Video>(); getReflections(fileName); var code = getShaders(stream); vertex = new VertexShader(video.Device, code[0]); pixel = new PixelShader(video.Device, code[1]); #else effect = Parent.FindParentOrSelfWithException <RootDisposable>().Content.Load <Effect>(Streams.StripFileExt(fileName)); loadedFromContentManager = true; pass = effect.CurrentTechnique.Passes[0]; #endif variables = new List <ShaderVariable>(); resources = new List <ShaderResource>(); } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected override void init(DisposableI parent, System.IO.Stream stream, int instanceCount, bool looped, Loader.LoadedCallbackMethod loadedCallback) { base.init(parent, stream, instanceCount, looped, loadedCallback); try { audio = parent.FindParentOrSelfWithException <Audio>(); audio.updateCallback += Update; this.data = base.data; this.channels = base.channels; this.sampleRate = base.sampleRate; this.bitDepth = base.bitDepth; for (int i = 0; i != instanceCount; ++i) { inactiveInstances.AddLast(new SoundWAVInstance(this, looped)); } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected override void init(IDisposableResource parent, Stream stream, int instanceCount, bool looped, Loader.LoadedCallbackMethod loadedCallback) { base.init(parent, stream, instanceCount, looped, loadedCallback); try { audio = parent.FindParentOrSelfWithException <Audio>(); audio.UpdateCallback += Update; com = new SoundWAVCom(); var error = com.Init(audio.com, data, formatCode, channels, sampleRate, formatAvgBytesPerSec, formatBlockAlign, bitDepth, formatExtraSize); data = null; for (int i = 0; i != instanceCount; ++i) { inactiveInstances.AddLast(new SoundWAVInstance(this, looped)); } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected override bool init(DisposableI parent, string fileName, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback) { if (!base.init(parent, fileName, width, height, false, multiSampleType, surfaceFormat, renderTargetUsage, usage, true, loadedCallback)) { return(false); } try { if (usage == BufferUsages.Write) { Debug.ThrowError("RenderTarget", "Only Textures may be writable"); } frameBuffer = new G.FrameBuffer(); frameBuffer.SetColorTarget(texture, 0); } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } return(true); }
protected override bool init(DisposableI parent, string fileName, Image image, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback) { if (!base.init(parent, fileName, image, width, height, false, multiSampleType, surfaceFormat, renderTargetUsage, usage, true, loadedCallback)) { return(false); } try { if (usage == BufferUsages.Write) { Debug.ThrowError("RenderTarget", "Only Textures may be writable"); } if (fileName == null) { // TODO: handle multiSampleType types #if SILVERLIGHT var xUsage = X.RenderTargetUsage.PreserveContents; #else var xUsage = X.RenderTargetUsage.PlatformContents; #endif switch (renderTargetUsage) { case RenderTargetUsage.PlatformDefault: #if SILVERLIGHT xUsage = X.RenderTargetUsage.PreserveContents; #else xUsage = X.RenderTargetUsage.PlatformContents; #endif break; case RenderTargetUsage.PreserveContents: xUsage = X.RenderTargetUsage.PreserveContents; break; case RenderTargetUsage.DiscardContents: xUsage = X.RenderTargetUsage.DiscardContents; break; } X.DepthFormat format = X.DepthFormat.None; if (initDepthStencilFormat != DepthStencilFormats.None) { switch (initDepthStencilFormat) { case DepthStencilFormats.Defualt: format = X.DepthFormat.Depth24; break; case DepthStencilFormats.Depth24Stencil8: format = X.DepthFormat.Depth24Stencil8; break; case DepthStencilFormats.Depth16: format = X.DepthFormat.Depth16; break; case DepthStencilFormats.Depth24: format = X.DepthFormat.Depth24; break; default: Debug.ThrowError("RenderTarget", "Unsuported DepthStencilFormat type"); break; } } renderTarget = new X.RenderTarget2D(video.Device, width, height, false, Video.surfaceFormat(surfaceFormat), format, 0, xUsage); } else { Debug.ThrowError("RenderTarget", "(Load image data into RenderTarget Texture) -- Not implemented yet..."); } texture = renderTarget; } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } return(true); }
private void init(ShaderI shader, Texture2DI texture, Stream stream, string metricsFileName, Loader.LoadedCallbackMethod loadedCallback) { try { // load characters var metrics = new FontMetrics(); metrics.Load(stream); Characters = new Character[metrics.Characters.Length]; for (int i = 0; i != metrics.Characters.Length; ++i) { var character = metrics.Characters[i]; Characters[i] = new Character(character.Key, new Vector2(character.X, character.Y), new Vector2(character.Width, character.Height)); } // get shader variables this.texture = texture; this.shader = shader; shaderCamera = shader.Variable("Camera"); shaderPosition = shader.Variable("Position"); shaderSize = shader.Variable("Size"); shaderPositionUV = shader.Variable("PositionUV"); shaderSizeUV = shader.Variable("SizeUV"); texelOffset = shader.Variable("TexelOffset"); shaderColor = shader.Variable("Color"); shaderTexture = shader.Resource("DiffuseTexture"); // create buffers var layoutDesc = BufferLayoutDescAPI.New(BufferLayoutTypes.Position2); layout = BufferLayoutAPI.New(this, shader, layoutDesc); var Indices = new int[6] { 0, 1, 2, 0, 2, 3 }; var Vertices = new float[8] { 0, 0, 0, 1, 1, 1, 1, 0, }; indexBuffer = IndexBufferAPI.New(this, BufferUsages.Default, Indices); vertexBuffer = VertexBufferAPI.New(this, layoutDesc, BufferUsages.Default, VertexBufferTopologys.Triangle, Vertices); } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected unsafe override void init(DisposableI parent, Stream stream, int instanceCount, bool looped, Loader.LoadedCallbackMethod loadedCallback) { base.init(parent, stream, instanceCount, looped, loadedCallback); try { audio = parent.FindParentOrSelfWithException <Audio>(); audio.UpdateCallback += Update; // Gen buffer uint bufferTEMP = 0; AL.GenBuffers(1, &bufferTEMP); buffer = bufferTEMP; if (buffer == 0) { Debug.ThrowError("SoundWAV", "Failed to create buffer"); } // load wav data int format = 0; if (bitDepth == 16) { if (channels == 2) { format = AL.FORMAT_STEREO16; } else { format = AL.FORMAT_MONO16; } } else { if (channels == 2) { format = AL.FORMAT_STEREO8; } else { format = AL.FORMAT_MONO8; } } fixed(byte *dataPtr = data) { AL.BufferData(buffer, format, dataPtr, data.Length, sampleRate); } data = null; // create instances for (int i = 0; i != instanceCount; ++i) { inactiveInstances.AddLast(new SoundWAVInstance(this, looped)); } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected override void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback) { try { ImageType = ImageTypes.PVR; // Load Header var header = new PVRHeader(); var reader = new BinaryReader(stream); // Read header version 2 header.HeaderLength = reader.ReadUInt32(); header.Height = reader.ReadUInt32(); header.Width = reader.ReadUInt32(); header.NumMipmaps = reader.ReadUInt32(); header.Flags = reader.ReadUInt32(); header.DataLength = reader.ReadUInt32(); header.BPP = reader.ReadUInt32(); header.BitmaskRed = reader.ReadUInt32(); header.BitmaskGreen = reader.ReadUInt32(); header.BitmaskBlue = reader.ReadUInt32(); header.BitmaskAlpha = reader.ReadUInt32(); header.PVRTag = reader.ReadUInt32(); header.NumSurfs = reader.ReadUInt32(); // Read header version 3 /*header.Version = reader.ReadUInt32(); * header.Flags = reader.ReadUInt32(); * header.PixelFormat = reader.ReadUInt64(); * header.ColorSpace = reader.ReadUInt32(); * header.ChannelType = reader.ReadUInt32(); * header.Height = reader.ReadUInt32(); * header.Width = reader.ReadUInt32(); * header.Depth = reader.ReadUInt32(); * header.NumSurfaces = reader.ReadUInt32(); * header.NumFaces = reader.ReadUInt32(); * header.MIPMapCount = reader.ReadUInt32(); * header.MetaDataSize = reader.ReadUInt32(); * * while (stream.Position <= stream.Length) * { * if (stream.Position + sizeof(int) > stream.Length) Debug.ThrowError("ImagePVR", "No data ID"); * if (reader.ReadInt32() == Streams.MakeFourCC('P', 'V', 'R', (char)3)) break; * } * * var key = reader.ReadUInt32(); * var dSize = reader.ReadUInt32();*/ // Get Caps Compressed = true; // Get pixel format Size = new Size2((int)header.Width, (int)header.Height); int blockSize = 0, bpp = 0, blockWidth = 0, blockHeight = 0, blockDev = 1; //switch (header.PixelFormat)// version 3 switch (header.Flags & PVR_TEXTURE_FLAG_TYPE_MASK) { case FOURCC_2BPP_RGB: FormatGL = GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG; blockSize = 8 * 4; blockWidth = 8; blockHeight = 4; bpp = 2; blockDev = 2; ImageFormat = ImageFormats.PVR_RGB_2; SurfaceFormat = SurfaceFormats.PVR_RGB_2; break; case FOURCC_2BPP_RGBA: FormatGL = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; blockSize = 8 * 4; blockWidth = 8; blockHeight = 4; bpp = 2; blockDev = 2; ImageFormat = ImageFormats.PVR_RGBA_2; SurfaceFormat = SurfaceFormats.PVR_RGBA_2; break; case FOURCC_4BPP_RGB: FormatGL = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; blockSize = 4 * 4; blockWidth = 4; blockHeight = 4; bpp = 4; ImageFormat = ImageFormats.PVR_RGB_4; SurfaceFormat = SurfaceFormats.PVR_RGB_4; break; case FOURCC_4BPP_RGBA: FormatGL = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; blockSize = 4 * 4; blockWidth = 4; blockHeight = 4; bpp = 4; ImageFormat = ImageFormats.PVR_RGBA_4; SurfaceFormat = SurfaceFormats.PVR_RGBA_4; break; default: Debug.ThrowError("ImagePVR", "Unsuported PVR Format"); break; } // Create Mipmaps header.NumMipmaps++; //Mipmaps = new Mipmap[header.MIPMapCount == 0 ? 1 : header.MIPMapCount];// version 3 Mipmaps = new Mipmap[header.NumMipmaps == 0 ? 1 : header.NumMipmaps]; var size = Size; for (int i = 0; i < Mipmaps.Length; ++i) { int width = (size.Width / blockWidth), height = (size.Height / blockHeight); if (width < 2) { width = 2; } if (height < 2) { height = 2; } int dataSize = (width * height) * ((blockSize * bpp) / 8); var data = new byte[dataSize]; stream.Read(data, 0, dataSize); Mipmaps[i] = new Mipmap(data, size.Width, size.Height, blockDev, 4); size /= 2; } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected override void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback) { try { ImageType = ImageTypes.BMPC; ImageFormat = ImageFormats.BMPC; SurfaceFormat = SurfaceFormats.RGBAx8; using (var reader = new BinaryReader(stream)) { // File Type int type = reader.ReadInt32(); if (type != Streams.MakeFourCC('b', 'm', 'p', 'c')) { throw new Exception("Not a .bmpc file"); } // Version float version = reader.ReadSingle(); if (version != 1.0f) { throw new Exception("Unsuported .bmpc version"); } // Meta Data Size = new Size2(reader.ReadInt32(), reader.ReadInt32()); bool zipCompressed = reader.ReadBoolean(); // Data using (var decompressedDataStream = new MemoryStream()) { int dataLength = reader.ReadInt32(); int dataRead = 0; do { int read = 1024; if ((dataRead + read) > dataLength) { read -= (int)((dataRead + read) - dataLength); } var data = reader.ReadBytes(read); decompressedDataStream.Write(data, 0, data.Length); dataRead += read; } while (dataRead < dataLength); decompressedDataStream.Position = 0; #if NaCl || SILVERLIGHT using (var zip = new GZipInputStream(decompressedDataStream)) using (var dataStream = new MemoryStream()) { var buffer = new byte[4096]; int read = 0; do { read = zip.Read(buffer, 0, buffer.Length); dataStream.Write(buffer, 0, buffer.Length); } while (read > 0); Mipmaps = new Mipmap[1]; Mipmaps[0] = new Mipmap(dataStream.GetBuffer(), Size.Width, Size.Height, 1, 4); if (flip) { Mipmaps[0].FlipVertical(); } } #else using (var decompressedStream = new GZipStream(decompressedDataStream, CompressionMode.Decompress)) using (var dataStream = new MemoryStream()) { decompressedStream.CopyTo(dataStream); Mipmaps = new Mipmap[1]; Mipmaps[0] = new Mipmap(dataStream.ToArray(), Size.Width, Size.Height, 1, 4); if (flip) { Mipmaps[0].FlipVertical(); } } #endif } } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; Loader.AddLoadable(this); if (loadedCallback != null) { loadedCallback(this, true); } }
protected virtual bool init(IDisposableResource parent, Image image, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, bool lockable, Loader.LoadedCallbackMethod loadedCallback) { byte[][] mipmaps = null; int[] mipmapSizes = null, mipmapPitches = null; try { video = parent.FindParentOrSelfWithException <Video>(); if (isRenderTarget) { generateMipmaps = false; } // load image data if (image != null) { mipmaps = new byte[image.Mipmaps.Length][]; mipmapSizes = new int[image.Mipmaps.Length]; mipmapPitches = new int[image.Mipmaps.Length]; for (int i = 0; i != mipmaps.Length; ++i) { var imageMipmap = image.Mipmaps[i]; mipmaps[i] = image.Compressed ? imageMipmap.Data : imageMipmap.SwapRBColorChannels(); mipmapSizes[i] = imageMipmap.Data.Length; mipmapPitches[i] = imageMipmap.Pitch; } Size = image.Size; surfaceFormat = image.SurfaceFormat; PixelByteSize = image.CalculatePixelByteSize(); } else { if (width == 0 || height == 0) { Debug.ThrowError("Texture2D", "Width or Height cannot be 0"); } Size = new Size2(width, height); PixelByteSize = Image.CalculatePixelByteSize((surfaceFormat == SurfaceFormats.Defualt ? Video.DefaultSurfaceFormat() : surfaceFormat), width, height); } TexelOffset = (1 / Size.ToVector2()) * .5f; SizeF = Size.ToVector2(); // init texture REIGN_D3DUSAGE nativeUsage = isRenderTarget ? REIGN_D3DUSAGE.RENDERTARGET : REIGN_D3DUSAGE.NONE; REIGN_D3DPOOL nativePool = (mipmaps != null && !video.Caps.ExDevice) ? REIGN_D3DPOOL.MANAGED : REIGN_D3DPOOL.DEFAULT; if (usage == BufferUsages.Read) { if (!isRenderTarget) { Debug.ThrowError("Texture2D", "Only RenderTargets may be readable"); } // NOTE: Staging texture and states will be created in the RenderTarget } if (usage == BufferUsages.Write) { if (mipmaps != null) { if (video.Caps.ExDevice) { nativeUsage |= REIGN_D3DUSAGE.DYNAMIC; } } else { nativeUsage |= REIGN_D3DUSAGE.DYNAMIC; } } com = new Texture2DCom(); var error = com.Init(video.com, Size.Width, Size.Height, generateMipmaps, mipmaps, mipmapSizes, mipmapPitches, 0, nativePool, nativeUsage, video.surfaceFormat(surfaceFormat), isRenderTarget); switch (error) { case TextureError.Texture: Debug.ThrowError("Texture2D", "Failed to create Texture2D"); break; case TextureError.SystemTexture: Debug.ThrowError("Texture2D", "Failed to create System Texture2D"); break; } if (!video.Caps.ExDevice && nativePool != REIGN_D3DPOOL.MANAGED) { LostDevice_image = image; LostDevice_width = width; LostDevice_height = height; LostDevice_generateMipmaps = generateMipmaps; LostDevice_multiSampleType = multiSampleType; LostDevice_surfaceFormat = surfaceFormat; LostDevice_renderTargetUsage = renderTargetUsage; LostDevice_usage = usage; LostDevice_isRenderTarget = isRenderTarget; LostDevice_lockable = lockable; LostDevice_pool = nativePool; } if (nativePool == REIGN_D3DPOOL.DEFAULT && !video.Caps.ExDevice && !video.deviceReseting) { video.DeviceLost += deviceLost; video.DeviceReset += deviceReset; } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } if (!isRenderTarget) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } return(true); }
protected virtual bool init(DisposableI parent, string fileName, Image image, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback) { try { if (usage == BufferUsages.Read && !isRenderTarget) { Debug.ThrowError("Texture2D", "Only RenderTargets may be readable"); } video = parent.FindParentOrSelfWithException <Video>(); if (!isRenderTarget) { if (fileName != null || image != null) { #if SILVERLIGHT texture = new X.Texture2D(video.Device, image.Size.Width, image.Size.Height, image.Mipmaps.Length != 0, Video.surfaceFormat(surfaceFormat)); for (int i = 0; i != image.Mipmaps.Length; ++i) { var mipmap = image.Mipmaps[i]; texture.SetData <byte>(i, null, mipmap.Data, 0, mipmap.Data.Length); } #else texture = parent.FindParentOrSelfWithException <RootDisposable>().Content.Load <X.Texture2D>(Streams.StripFileExt(fileName)); loadedFromContentManager = true; #endif } else { texture = new X.Texture2D(video.Device, width, height, generateMipmaps, Video.surfaceFormat(surfaceFormat)); } Size = new Size2(texture.Width, texture.Height); PixelByteSize = Image.CalculatePixelByteSize(surfaceFormat, texture.Width, texture.Height); } else { Size = new Size2(width, height); PixelByteSize = Image.CalculatePixelByteSize(surfaceFormat, width, height); } TexelOffset = (1 / Size.ToVector2()) * .5f; SizeF = Size.ToVector2(); } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } if (!isRenderTarget) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } return(true); }
private void init(Stream stream, Loader.LoadedCallbackMethod loadedCallback) { try { var xml = new XmlSerializer(typeof(RMXModel), ""); var rmx = (RMXModel)xml.Deserialize(stream); rmx.Init(); // check file version if (rmx.Version != 1.0f) { Debug.ThrowError("SoftwareModel", "Unsuported file version, must be 1.0"); } // frames FrameStart = rmx.FrameStart; FrameEnd = rmx.FrameEnd; FPS = rmx.FPS; // materials Materials = new List <SoftwareMaterial>(); if (rmx.Materials.Materials != null) { foreach (var material in rmx.Materials.Materials) { Materials.Add(new SoftwareMaterial(material)); } } // meshes Meshes = new List <SoftwareMesh>(); if (rmx.Meshes.Meshes != null) { foreach (var mesh in rmx.Meshes.Meshes) { Meshes.Add(new SoftwareMesh(this, mesh)); } } // actions Actions = new List <SoftwareAction>(); if (rmx.Actions.Actions != null) { foreach (var action in rmx.Actions.Actions) { Actions.Add(new SoftwareAction(action)); } } // armatures Armatures = new List <SoftwareArmature>(); if (rmx.Armatures.Armatures != null) { foreach (var armature in rmx.Armatures.Armatures) { Armatures.Add(new SoftwareArmature(armature)); } } // objects Objects = new List <SoftwareObject>(); if (rmx.RMXObjects.Objects != null) { foreach (var o in rmx.RMXObjects.Objects) { if (o.Type == "MESH") { Objects.Add(new SoftwareObjectMesh(this, o)); } else if (o.Type == "ARMATURE") { Objects.Add(new SoftwareObjectArmature(this, o)); } } int i = 0; foreach (var o in Objects) { o.linkObjects(rmx.RMXObjects.Objects[i]); ++i; } } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
private void init(string filename, Stream stream, string contentDirectory, Dictionary <string, Type> materialTypes, List <MaterialFieldBinder> value1BinderTypes, List <MaterialFieldBinder> value2BinderTypes, List <MaterialFieldBinder> value3BinderTypes, List <MaterialFieldBinder> value4BinderTypes, List <MaterialFieldBinder> textureBinderTypes, Dictionary <string, string> fileExtOverrides, int classicInstanceCount, Loader.LoadedCallbackMethod loadedCallback) { try { var reader = new BinaryReader(stream); // meta data if (reader.ReadInt32() != Streams.MakeFourCC('R', 'M', 'F', 'T')) { Debug.ThrowError("Error", "Not a ReignModel file: " + filename); } float version = reader.ReadSingle(); if (version != 1.0f) { Debug.ThrowError("Error", "Unsuported model version: " + version.ToString()); } bool compressed = reader.ReadBoolean(); // frames FrameStart = reader.ReadSingle(); FrameEnd = reader.ReadSingle(); FrameCount = FrameEnd - FrameStart; FPS = reader.ReadSingle(); // materials int materialCount = reader.ReadInt32(); Materials = new MaterialI[materialCount]; Textures = new List <ITexture2D>(); for (int i = 0; i != materialCount; ++i) { string name = reader.ReadString(); // create material bool pass = false; foreach (var materialType in (Dictionary <string, Type>)materialTypes) { if (materialType.Key == name) { Materials[i] = (MaterialI)Activator.CreateInstance(materialType.Value); Materials[i].Name = name; pass = true; break; } } if (!pass) { Debug.ThrowError("Model", "Failed to find a valid material type for: " + name); } var material = Materials[i]; // values1 var values1 = new Dictionary <string, float>(); int valueCount = reader.ReadInt32(); for (int i2 = 0; i2 != valueCount; ++i2) { values1.Add(reader.ReadString(), reader.ReadSingle()); } bindTypes(material, values1, value1BinderTypes, contentDirectory, fileExtOverrides, handleFoundValueBinder); // values2 var values2 = new Dictionary <string, Vector2>(); valueCount = reader.ReadInt32(); for (int i2 = 0; i2 != valueCount; ++i2) { values2.Add(reader.ReadString(), reader.ReadVector2()); } bindTypes(material, values2, value2BinderTypes, contentDirectory, fileExtOverrides, handleFoundValueBinder); // values3 var values3 = new Dictionary <string, Vector3>(); valueCount = reader.ReadInt32(); for (int i2 = 0; i2 != valueCount; ++i2) { values3.Add(reader.ReadString(), reader.ReadVector3()); } bindTypes(material, values3, value3BinderTypes, contentDirectory, fileExtOverrides, handleFoundValueBinder); // values4 var values4 = new Dictionary <string, Vector4>(); valueCount = reader.ReadInt32(); for (int i2 = 0; i2 != valueCount; ++i2) { values4.Add(reader.ReadString(), reader.ReadVector4()); } bindTypes(material, values4, value4BinderTypes, contentDirectory, fileExtOverrides, handleFoundValueBinder); // textures var textures = new Dictionary <string, string>(); int textureCount = reader.ReadInt32(); for (int i2 = 0; i2 != textureCount; ++i2) { textures.Add(reader.ReadString(), reader.ReadString()); } bindTypes(material, textures, textureBinderTypes, contentDirectory, fileExtOverrides, handleFoundTextureBinder); } // meshes int meshCount = reader.ReadInt32(); Meshes = new Mesh[meshCount]; for (int i = 0; i != meshCount; ++i) { Meshes[i] = new Mesh(reader, this, classicInstanceCount); } // actions int actionCount = reader.ReadInt32(); Actions = new Action[actionCount]; for (int i = 0; i != actionCount; ++i) { Actions[i] = new Action(reader); } // armatures int armatureCount = reader.ReadInt32(); Armatures = new Armature[armatureCount]; for (int i = 0; i != armatureCount; ++i) { Armatures[i] = new Armature(reader); } // objects int objectCount = reader.ReadInt32(); Objects = new Object[objectCount]; for (int i = 0; i != objectCount; ++i) { string type = reader.ReadString(); if (type == "MESH") { Objects[i] = new ObjectMesh(reader, this); } else if (type == "ARMATURE") { Objects[i] = new ObjectArmature(reader, this); } else { Debug.ThrowError("Mesh", "Unsuported Object type: " + type); } } // link objects foreach (var o in Objects) { o.linkObjects(Objects); } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return; } if (Textures.Count == 0) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } else { new LoadWaiter(Textures.ToArray(), delegate(object sender, bool succeeded) { if (succeeded) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } else { FailedToLoad = true; Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } } }); } }
protected override void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback) { try { ImageType = ImageTypes.DDS; // Load Desc DDSURFACEDESC2 desc = new DDSURFACEDESC2(); var reader = new BinaryReader(stream); desc.MagicNumber = reader.ReadUInt32(); desc.dwSize = reader.ReadUInt32(); desc.dwFlags = reader.ReadUInt32(); desc.dwHeight = reader.ReadUInt32(); desc.dwWidth = reader.ReadUInt32(); desc.Union1 = new DDSURFACEDESC2.DUMMYUNIONNAMEN1(); desc.Union1.lPitch = reader.ReadInt32(); desc.Union5 = new DDSURFACEDESC2.DUMMYUNIONNAMEN5(); desc.Union5.dwBackBufferCount = reader.ReadUInt32(); desc.Union2 = new DDSURFACEDESC2.DUMMYUNIONNAMEN2(); desc.Union2.dwMipMapCount = reader.ReadUInt32(); desc.dwAlphaBitDepth = reader.ReadUInt32(); desc.dwReserved = reader.ReadUInt32(); desc.lpSurface = reader.ReadInt32(); desc.Union3 = new DDSURFACEDESC2.DUMMYUNIONNAMEN3(); desc.Union3.ddckCKDestOverlay = new DDCOLORKEY(); desc.Union3.ddckCKDestOverlay.dwColorSpaceLowValue = reader.ReadUInt32(); desc.Union3.ddckCKDestOverlay.dwColorSpaceHighValue = reader.ReadUInt32(); desc.ddckCKDestBlt = new DDCOLORKEY(); desc.ddckCKDestBlt.dwColorSpaceLowValue = reader.ReadUInt32(); desc.ddckCKDestBlt.dwColorSpaceHighValue = reader.ReadUInt32(); desc.ddckCKSrcOverlay = new DDCOLORKEY(); desc.ddckCKSrcOverlay.dwColorSpaceLowValue = reader.ReadUInt32(); desc.ddckCKSrcOverlay.dwColorSpaceHighValue = reader.ReadUInt32(); desc.ddckCKSrcBlt = new DDCOLORKEY(); desc.ddckCKSrcBlt.dwColorSpaceLowValue = reader.ReadUInt32(); desc.ddckCKSrcBlt.dwColorSpaceHighValue = reader.ReadUInt32(); desc.Union4 = new DDSURFACEDESC2.DUMMYUNIONNAMEN4(); desc.Union4.ddpfPixelFormat = new DDPIXELFORMAT(); desc.Union4.ddpfPixelFormat.dwSize = reader.ReadUInt32(); desc.Union4.ddpfPixelFormat.dwFlags = reader.ReadUInt32(); desc.Union4.ddpfPixelFormat.dwFourCC = reader.ReadUInt32(); { desc.Union4.ddpfPixelFormat.Union1 = new DDPIXELFORMAT.DUMMYUNIONNAMEN1(); desc.Union4.ddpfPixelFormat.Union1.dwRGBBitCount = reader.ReadUInt32(); desc.Union4.ddpfPixelFormat.Union2 = new DDPIXELFORMAT.DUMMYUNIONNAMEN2(); desc.Union4.ddpfPixelFormat.Union2.dwRBitMask = reader.ReadUInt32(); desc.Union4.ddpfPixelFormat.Union3 = new DDPIXELFORMAT.DUMMYUNIONNAMEN3(); desc.Union4.ddpfPixelFormat.Union3.MultiSampleCaps = new DDPIXELFORMAT.DUMMYUNIONNAMEN3.Caps(); desc.Union4.ddpfPixelFormat.Union3.MultiSampleCaps.wFlipMSTypes = reader.ReadInt16(); desc.Union4.ddpfPixelFormat.Union3.MultiSampleCaps.wBltMSTypes = reader.ReadInt16(); desc.Union4.ddpfPixelFormat.Union4 = new DDPIXELFORMAT.DUMMYUNIONNAMEN4(); desc.Union4.ddpfPixelFormat.Union4.dwBBitMask = reader.ReadUInt32(); desc.Union4.ddpfPixelFormat.Union5 = new DDPIXELFORMAT.DUMMYUNIONNAMEN5(); desc.Union4.ddpfPixelFormat.Union5.dwRGBAlphaBitMask = reader.ReadUInt32(); } desc.ddsCaps = new DDSCAPS2(); desc.ddsCaps.dwCaps = reader.ReadUInt32(); desc.ddsCaps.dwCaps2 = reader.ReadUInt32(); desc.ddsCaps.dwCaps3 = reader.ReadUInt32(); desc.ddsCaps.Union = new DDSCAPS2.DUMMYUNIONNAMEN(); desc.ddsCaps.Union.dwCaps4 = reader.ReadUInt32(); desc.dwTextureStage = reader.ReadUInt32(); // Check file ext if (desc.MagicNumber != 0x20534444u) { Debug.ThrowError("ImageDDS", "Not a DDS file"); } // Get file caps bool isCubemap = ((desc.ddsCaps.dwCaps & DDSCAPS_COMPLEX) != 0) && ((desc.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP) != 0); bool isVolumeTexture = ((desc.ddsCaps.dwCaps2 & DDSCAPS2_VOLUME) != 0); bool hasAlphaChannel = ((desc.Union4.ddpfPixelFormat.dwFlags & DDPF_ALPHAPIXELS) != 0); Compressed = ((desc.Union4.ddpfPixelFormat.dwFlags & DDPF_FOURCC) != 0); // Get pixel format Size = new Size2((int)desc.dwWidth, (int)desc.dwHeight); int blockSize = 0, blockDev = 1; if (Compressed) { FormatD3D = desc.Union4.ddpfPixelFormat.dwFourCC; switch (desc.Union4.ddpfPixelFormat.dwFourCC) { case FOURCC_DXT1: FormatGL = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; blockSize = 8; blockDev = 2; SurfaceFormat = SurfaceFormats.DXT1; ImageFormat = ImageFormats.DXT1; break; case FOURCC_DXT3: FormatGL = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; blockSize = 16; SurfaceFormat = SurfaceFormats.DXT3; ImageFormat = ImageFormats.DXT3; break; case FOURCC_DXT5: FormatGL = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; blockSize = 16; SurfaceFormat = SurfaceFormats.DXT5; ImageFormat = ImageFormats.DXT5; break; case FOURCC_ATC_RGB: FormatGL = ATC_RGB_AMD; blockSize = 8; blockDev = 2; SurfaceFormat = SurfaceFormats.ATC_RGB; ImageFormat = ImageFormats.ATC_RGB; break; case FOURCC_ATC_RGBA_EXPLICIT: FormatGL = ATC_RGBA_EXPLICIT_ALPHA_AMD; blockSize = 16; SurfaceFormat = SurfaceFormats.ATC_RGBA_Explicit; ImageFormat = ImageFormats.ATC_RGBA_Explicit; break; case FOURCC_ATC_RGBA_INTERPOLATED: FormatGL = ATC_RGBA_INTERPOLATED_ALPHA_AMD; blockSize = 16; SurfaceFormat = SurfaceFormats.ATC_RGBA_Interpolated; ImageFormat = ImageFormats.ATC_RGBA_Interpolated; break; default: Debug.ThrowError("ImageDDS", "Unsuported DDS Format"); break; } } else { Debug.ThrowError("ImageDDS", "Uncompressed textures not supported yet"); } if (isCubemap || isVolumeTexture) { Debug.ThrowError("ImageDDS", "Cubemap and VolumeTextures not supported yet"); } // Create Mipmaps Mipmaps = new Mipmap[desc.Union2.dwMipMapCount == 0 ? 1 : desc.Union2.dwMipMapCount]; var size = Size; for (int i = 0; i < Mipmaps.Length; ++i) { int dataSize = (((size.Width + 3) / 4) * ((size.Height + 3) / 4)) * blockSize; var data = new byte[dataSize]; stream.Read(data, 0, dataSize); if (flip && (FormatD3D == FOURCC_DXT1 || FormatD3D == FOURCC_DXT3 || FormatD3D == FOURCC_DXT5)) { data = flipCompressedData(data, size.Width, size.Height, blockSize); } Mipmaps[i] = new Mipmap(data, size.Width, size.Height, blockDev, 4); size /= 2; } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); if (loadedCallback != null) { loadedCallback(this, false); } return; } Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } }
protected virtual bool init(IDisposableResource parent, Image image, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback) { long[] mipmaps = null; int[] mipmapSizes = null, mipmapPitches = null; try { video = parent.FindParentOrSelfWithException <Video>(); if (isRenderTarget) { generateMipmaps = false; } // load image data if (image != null) { mipmaps = new long[image.Mipmaps.Length]; mipmapSizes = new int[image.Mipmaps.Length]; mipmapPitches = new int[image.Mipmaps.Length]; for (int i = 0; i != mipmaps.Length; ++i) { var imageMipmap = image.Mipmaps[i]; IntPtr mipmapPtr = Marshal.AllocHGlobal(imageMipmap.Data.Length); Marshal.Copy(imageMipmap.Data, 0, mipmapPtr, imageMipmap.Data.Length); mipmapSizes[i] = imageMipmap.Data.Length; mipmapPitches[i] = imageMipmap.Pitch; mipmaps[i] = mipmapPtr.ToInt64(); } Size = image.Size; surfaceFormat = image.SurfaceFormat; PixelByteSize = image.CalculatePixelByteSize(); } else { if (width == 0 || height == 0) { Debug.ThrowError("Texture2D", "Width or Height cannot be 0"); } Size = new Size2(width, height); PixelByteSize = Image.CalculatePixelByteSize((surfaceFormat == SurfaceFormats.Defualt ? Video.DefaultSurfaceFormat() : surfaceFormat), width, height); } SizeF = Size.ToVector2(); // init texture REIGN_D3D11_USAGE usageType = REIGN_D3D11_USAGE.DEFAULT; REIGN_D3D11_CPU_ACCESS_FLAG cpuAccessFlags = (REIGN_D3D11_CPU_ACCESS_FLAG)0; if (usage == BufferUsages.Read) { if (!isRenderTarget) { Debug.ThrowError("Texture2D", "Only RenderTargets may be readable"); } // NOTE: Staging texture and states will be created in the RenderTarget //usageType = REIGN_D3D11_USAGE.STAGING; //cpuAccessFlags = REIGN_D3D11_CPU_ACCESS_FLAG.READ; } if (usage == BufferUsages.Write) { usageType = REIGN_D3D11_USAGE.DYNAMIC; cpuAccessFlags = REIGN_D3D11_CPU_ACCESS_FLAG.WRITE; } com = new Texture2DCom(); var error = com.Init(video.com, Size.Width, Size.Height, generateMipmaps, mipmaps != null, mipmaps, mipmapSizes, mipmapPitches, 0, video.surfaceFormat(surfaceFormat), usageType, cpuAccessFlags, isRenderTarget); switch (error) { case TextureError.Texture: Debug.ThrowError("Texture2D", "Failed to create Texture2D"); break; case TextureError.ShaderResourceView: Debug.ThrowError("Texture2D", "Failed to create ShaderResourceView"); break; } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } finally { if (mipmaps != null) { for (int i = 0; i != mipmaps.Length; ++i) { if (mipmaps[i] != 0) { Marshal.FreeHGlobal(new IntPtr(mipmaps[i])); } } } } if (!isRenderTarget) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } return(true); }
protected unsafe virtual bool init(IDisposableResource parent, Image image, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback) { try { if (usage == BufferUsages.Read && !isRenderTarget) { Debug.ThrowError("Texture2D", "Only RenderTargets may be readable"); } video = parent.FindParentOrSelfWithException <Video>(); if (isRenderTarget) { generateMipmaps = false; } uint texturesTEMP = 0; GL.GenTextures(1, &texturesTEMP); Texture = texturesTEMP; if (Texture == 0) { Debug.ThrowError("Texture2D", "Failed to Generate Texture"); } GL.BindTexture(GL.TEXTURE_2D, Texture); if (!generateMipmaps) { GL.TexParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR); } else { GL.TexParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR_MIPMAP_LINEAR); } GL.TexParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.LINEAR); hasMipmaps = false; if (image != null) { var imageType = image.GetType(); #if NaCl if (imageType == typeof(ImageBMPC)) #else if (imageType == typeof(ImagePNG) || imageType == typeof(ImageJPG) || imageType == typeof(ImageBMP) || imageType == typeof(ImageBMPC)) #endif { uint pixelOrder, byteSizes; int format = Video.surfaceFormat(surfaceFormat, out pixelOrder, out byteSizes); var mipmap = image.Mipmaps[0]; fixed(byte *data = mipmap.Data) { GL.TexImage2D(GL.TEXTURE_2D, 0, format, mipmap.Size.Width, mipmap.Size.Height, 0, pixelOrder, byteSizes, data); if (generateMipmaps) { hasMipmaps = true; GL.GenerateMipmap(GL.TEXTURE_2D); } } } else if (imageType == typeof(ImageDDS) || imageType == typeof(ImagePVR)) { if (image.Mipmaps.Length != Image.Mipmap.CalculateMipmapLvls(image.Size.Width, image.Size.Height)) { Debug.ThrowError("Texture2D", "Compressed Textures require full mipmap chain"); } GL.TexParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR_MIPMAP_LINEAR); hasMipmaps = true; bool compressed = false; uint format = 0; string errorType = null; if (imageType == typeof(ImageDDS)) { var imageDDS = (ImageDDS)image; compressed = imageDDS.Compressed; format = imageDDS.FormatGL; errorType = "DDS"; } else if (imageType == typeof(ImagePVR)) { var imagePVR = (ImagePVR)image; compressed = imagePVR.Compressed; format = imagePVR.FormatGL; errorType = "PVR"; } if (compressed) { for (int i = 0; i < image.Mipmaps.Length; ++i) { var mipmap = image.Mipmaps[i]; fixed(byte *data = mipmap.Data) { // look up:: libtxc_dxtn.so for linux with mesa GL.CompressedTexImage2D(GL.TEXTURE_2D, i, format, mipmap.Size.Width, mipmap.Size.Height, 0, mipmap.Data.Length, data); } } } else { Debug.ThrowError("Texture2D", "Loading uncompresed " + errorType + " textures not supported"); } } Size = image.Size; PixelByteSize = image.CalculatePixelByteSize(); } else { //GL.TexImage2D(GL.TEXTURE_2D, 0, Video.surfaceFormat(surfaceFormat), width, height, 0, GL.RGBA, GL.UNSIGNED_BYTE, IntPtr.Zero.ToPointer()); uint pixelOrder, byteSizes; int format = Video.surfaceFormat(surfaceFormat, out pixelOrder, out byteSizes); GL.TexImage2D(GL.TEXTURE_2D, 0, format, width, height, 0, pixelOrder, byteSizes, IntPtr.Zero.ToPointer()); if (generateMipmaps) { hasMipmaps = true; GL.GenerateMipmap(GL.TEXTURE_2D); } Size = new Size2(width, height); PixelByteSize = Image.CalculatePixelByteSize((surfaceFormat == SurfaceFormats.Defualt ? Video.DefaultSurfaceFormat() : surfaceFormat), width, height); } SizeF = Size.ToVector2(); uint error; string errorName; if (Video.checkForError(out error, out errorName)) { Debug.ThrowError("Texture2D", string.Format("{0} {1}: Failed to load/create texture", error, errorName)); } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } if (!isRenderTarget) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } return(true); }