private bool Initialize(TextureManager manager, D3d.Format format, int width, int height, bool dynamic, bool mipmap) { D3d.Pool d3dPool = D3d.Pool.Managed; D3d.Usage d3dUsage = manager.GetUsageFlags(dynamic, mipmap, false); try { d3dTexture = new D3d.Texture(manager.Device.D3dDevice, width, height, manager.GetMipLevelCount(mipmap), d3dUsage, format, d3dPool); this.Initialize(manager, format, width, height, 1, d3dTexture); return(true); } catch (D3d.InvalidCallException e) { log.Warning("Unable to create texture: {0}", e.Message); } catch (D3d.OutOfVideoMemoryException e) { log.Warning("Unable to create texture: {0}", e.Message); } catch (OutOfMemoryException e) { log.Warning("Unable to create texture: {0}", e.Message); } return(false); }
public Texture TakeScreenshot() { DisplayMode dm = device.DisplayMode; Microsoft.DirectX.Direct3D.Texture shot = new Microsoft.DirectX.Direct3D.Texture(device, dm.Width, dm.Height, 1, 0, Format.A8R8G8B8, Pool.SystemMemory); device.GetFrontBufferData(0, shot.GetSurfaceLevel(0)); System.Drawing.Rectangle rect; if (fullscreen) { rect = new Rectangle(0, 0, width, height); } else { rect = new Rectangle(Kernel.Form.PointToScreen(new System.Drawing.Point(0, 0)), new Size(width, height)); } int[] pixels = (int[])shot.LockRectangle(typeof(int), 0, LockFlags.None, dm.Width * dm.Height); Texture res = new Texture(width, height); int i = 0; for (int y = rect.Top; y < rect.Bottom; y++) { for (int x = rect.Left; x < rect.Right; x++) { res[i++] = Color.FromColorCode(pixels[x + y * dm.Width]); } } shot.UnlockRectangle(0); return(res); }
private bool Initialize(TextureManager manager, D3d.Format format, int width, int height, bool dynamic, bool mipmap) { D3d.Pool d3dPool = D3d.Pool.Managed; D3d.Usage d3dUsage = manager.GetUsageFlags( dynamic,mipmap,false ); try { d3dTexture = new D3d.Texture( manager.Device.D3dDevice, width, height, manager.GetMipLevelCount(mipmap), d3dUsage, format, d3dPool ); this.Initialize(manager, format, width, height, 1, d3dTexture); return true; } catch (D3d.InvalidCallException e) { log.Warning("Unable to create texture: {0}", e.Message); } catch (D3d.OutOfVideoMemoryException e) { log.Warning("Unable to create texture: {0}", e.Message); } catch (OutOfMemoryException e) { log.Warning("Unable to create texture: {0}", e.Message); } return false; }
public int AddTexture(Texture texture) { int w, nw, h, nh, size, idx; // calculate new dimensions w = texture.Width; h = texture.Height; nw = 1; nh = 1; while (nw < w) { nw = nw << 1; } while (nh < h) { nh = nh << 1; } size = nw * nh; // create texture Microsoft.DirectX.Direct3D.Texture dxtex = new Microsoft.DirectX.Direct3D.Texture(device, nw, nh, 1, 0, Format.A8R8G8B8, Pool.Managed); //Microsoft.DirectX.Direct3D.Texture dxtex = new Microsoft.DirectX.Direct3D.Texture(device, nw, nh, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default); // add texture idx = textures.Add(new TexListElement(texture, dxtex)); // load texture LoadTexture(idx); return(idx); }
/// <summary> /// Creates a DirectX texture object. /// </summary> /// <param name="tex">Texture to contain in the object.</param> /// <param name="filename">Filename to the original texture file.</param> public Texture( D3D.Texture tex, string filename ) { _texture = tex; Initialize(); _name = filename; _file = filename; }
/// <summary> /// Creates a DirectX texture object. /// </summary> /// <param name="tex">Texture to contain in the object.</param> /// <param name="filename">Filename to the original texture file.</param> public Texture(D3D.Texture tex, string filename) { _texture = tex; Initialize(); _name = filename; _file = filename; }
public Explosion(Direct3D.Device NewDevice, DirectX.Vector3 NewPosition) { this.CurrDevice = NewDevice; this.ExplosionTexture = Direct3D.TextureLoader.FromFile(CurrDevice, GameConfig.Files.ExplosionPoint); this.LightTexture = Direct3D.TextureLoader.FromFile(CurrDevice, GameConfig.Files.ExplosionLight); this.ExplosionPosition = NewPosition; this.Rand = new Random(); this.UniversalGravity = .50f; this.ParticleCount = 100; this.NeedsDelete = false; this.Particles = new ArrayList(); for (int i = 0; i < this.ParticleCount; i++) { Particles.Add(new Particle(this.UniversalGravity, ExplosionPosition, new DirectX.Vector3((float)(Rand.NextDouble() * 0.75f - 0.375f), (float)(Rand.NextDouble() * 0.5f - 0.1f), 0.0f), DXUtil.Timer(DirectXTimer.GetApplicationTime))); } ExplosionFlash = new Flash(ExplosionPosition, DXUtil.Timer(DirectXTimer.GetApplicationTime)); this.LastUpdateTime = DXUtil.Timer(DirectXTimer.GetApplicationTime); }
/// <summary> /// Initializes a new instance of the <see cref="Pendulum"/> class. /// </summary> /// <param name="g">The graphic device to draw the pendulum to</param> /// <param name="gSize">Size of graphic display</param> /// <param name="texture">The texture to dispaly as the pendulum</param> /// <param name="sound">The sound to play as the pendulum swings</param> public Pendulum(Direct3D.Device g, Size gSize, Direct3D.Texture texture, SecondaryBuffer sound) { _sWidth = gSize.Width; _graphics = g; _sprite = new Direct3D.Sprite(_graphics); _texture = texture; _sound = sound; }
/// <summary> /// Loads the specified image into the texture. /// </summary> /// <param name="device">The DirectX device to load the texture into.</param> /// <param name="image">The image to load.</param> /// <param name="usage">The Direct3D Usage parameter for the image.</param> /// <param name="pool">The Direct3D Pool parameter for the image.</param> public void SetImage(D3D.Device device, Bitmap image, D3D.Usage usage, D3D.Pool pool) { if (_texture != null) { _texture.Dispose(); } _texture = new D3D.Texture(device, image, usage, pool); }
/// <summary> /// Safely disposes of the texture data. /// </summary> public void Dispose() { if (_texture != null) { _texture.Dispose(); _texture = null; } Initialize(); }
// -------------------------------------------------------------------- // Constructor // -------------------------------------------------------------------- public Sprite() { // no texture texture = null; // scaling default scaling = new DirectX.Vector2(1.0f, 1.0f); // no coloring color = Drawing.Color.White; }
private void LoadFromFile(string path) { try { _DXTexture = TextureLoader.FromFile(Graphics.GetInstance.Device, path); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Texture " + path + " not found!\n" + e); _DXTexture = Texture.EmptyTexture; } }
void IReflectorCreate.OnCreate(Control pc) { //throw new Exception( "The method or operation is not implemented." ); DoCreate(pc); sprite = new Direct3D.Sprite(state.graphics); texture = Direct3D.TextureLoader.FromFile( state.graphics, "c:/ftn3000/etc/images/misc/sky.jpg", 0, 0, 0, 0, Direct3D.Format.Unknown, Direct3D.Pool.Managed, Direct3D.Filter.Linear, Direct3D.Filter.Linear, 0); Run(); //paused = false; }
/// <summary> /// Load the inital textures /// </summary> public static void LoadTextures() { // Background texture images[256] = Microsoft.DirectX.Direct3D.TextureLoader.FromFile(device, globalSettings.path + "openSebJ.jpg"); images[0] = Microsoft.DirectX.Direct3D.TextureLoader.FromFile(device, globalSettings.path + "blank.jpg"); for (int i = 0; i < 255; i++) { //if (dsInterface.imageLocations[i] != null) if (globalSettings.osj.image_Locations[i] != null) { try { // This loop extracts the images from the memory stream where they were saved and loads them 1 by 1 through the // DirectX interface, in to memory. if (globalSettings.osj.image_Loaded[i] == true) { // Setup the blank byte array byte[] _bytes; // Use the application data directory defined as the temporary location to write the wave sample to // TODO: Setup the extension to match the image type - however it seems to work even without an extension? string imageName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\image" + i.ToString() + globalSettings.osj.imageDetails_Extension[i]; // Copy the memory stream to the temporary byte array _bytes = globalSettings.osj.image_MemoryStream[i].ToArray(); // Writes out the byte array to the predefined file location System.IO.File.WriteAllBytes(imageName, _bytes); // Load the file using the standard DirectX interface //dsInterface.loadSample(sampleName, i); images[i] = Microsoft.DirectX.Direct3D.TextureLoader.FromFile(device, imageName); // Delete the file saved out System.IO.File.Delete(imageName); } } catch (Exception e) { // If the load fails; then set the file name back to nothing //dsInterface.imageLocations[i] = null; globalSettings.osj.image_Locations[i] = null; globalSettings.osj.image_Loaded[i] = false; System.Windows.Forms.MessageBox.Show(e.ToString()); } } } background = images[256]; }
public override void release() { if (_Texture != null) { _Texture.Dispose(); _Texture = null; } if (_Sprite != null) { _Sprite.Dispose(); _Sprite = null; } }
/// <summary> /// Creates the texture from a file. /// </summary> /// <param name="renderer">The renderer.</param> /// <param name="filename">The name of the texture file to load.</param> public Texture(Renderer renderer, string filename) { if (renderer == null) throw new ArgumentNullException("renderer", "Unable to create texture without a valid renderer reference."); if (String.IsNullOrEmpty(filename)) throw new ArgumentNullException("filename", "Unable to create texture without valid filename."); // Add default extension if none is given if (Dynamic2DLighting.Properties.Settings.Default.DefaultTextureExtension.Length > 0 && StringHelper.GetExtension(filename).Length == 0) filename = filename + "." + Dynamic2DLighting.Properties.Settings.Default.DefaultTextureExtension; this.renderer = renderer; texFilename = filename; // Try to load the texture try { if (File.Exists(filename) == false) throw new FileNotFoundException(filename); ImageInformation imageInfo = TextureLoader.ImageInformationFromFile(filename); size = new Size(imageInfo.Width, imageInfo.Height); if (size.Width == 0 || size.Height == 0) throw new InvalidOperationException( "Image size=" + size + " is invalid, unable to create texture."); hasAlpha = imageInfo.Format == Format.Dxt5 || imageInfo.Format == Format.Dxt3 || imageInfo.Format.ToString().StartsWith("A"); d3dTexture = TextureLoader.FromFile(this.renderer.Device, filename); loaded = true; renderer.AddGraphicsObject(this); } catch (Exception ex) { loaded = false; Log.Write("Failed to load texture " + filename + ", will use empty texture! Error: " + ex.ToString()); } }
public GooAccess(Direct3D.Device NewGameDevice, GameEngine.ShaderLevel NewCardShaderLevel, DirectX.Matrix NewViewMatrix, DirectX.Matrix NewProjectionMatrix) { GameDevice = NewGameDevice; CardShaderLevel = NewCardShaderLevel; ViewMatrix = NewViewMatrix; ProjectionMatrix = NewProjectionMatrix; // Load Shader Effect From File GooEffect = Direct3D.Effect.FromFile(GameDevice, GameConfig.Files.GooFx, null, null, Direct3D.ShaderFlags.None, null); // Choose shader technique based on shader level. if (CardShaderLevel == GameEngine.ShaderLevel.Pixel_3_0) { GooEffect.Technique = "Goo_Parallax_3_0"; } else if (CardShaderLevel == GameEngine.ShaderLevel.Pixel_2_b) { GooEffect.Technique = "Goo_Parallax_2_b"; } else if (CardShaderLevel == GameEngine.ShaderLevel.Pixel_2_0) { GooEffect.Technique = "Goo_Parallax_2"; } else if (CardShaderLevel == GameEngine.ShaderLevel.Pixel_1_4) { GooEffect.Technique = "Goo_Bump_1_4"; } // Load Mesh From File GooMesh = Direct3D.Mesh.FromFile(GameConfig.Files.GooMesh, Direct3D.MeshFlags.Managed, GameDevice); // Load Textures From File ColorTexture = Direct3D.TextureLoader.FromFile(GameDevice, GameConfig.Files.GooColor); NormalTexture = Direct3D.TextureLoader.FromFile(GameDevice, GameConfig.Files.GooNormal); HeightTexture = Direct3D.TextureLoader.FromFile(GameDevice, GameConfig.Files.GooHeight); // Load Textures into Effect GooEffect.SetValue("ColorTexture", ColorTexture); GooEffect.SetValue("NormalsTexture", NormalTexture); GooEffect.SetValue("HeightTexture", HeightTexture); // Set Parallax and Bump Intensity GooEffect.SetValue("ParallaxAmount", .5f); GooEffect.SetValue("BumpAmount", 1.5f); }
public static void LoadMesh(Stream stream, D3D.Device dev, ref D3D.Mesh mesh, ref D3D.Material[] meshMaterials, ref D3D.Texture[] meshTextures) { D3D.ExtendedMaterial[] materialArray; mesh = D3D.Mesh.FromStream(stream, D3D.MeshFlags.Managed, dev, out materialArray); if ((materialArray != null) && (materialArray.Length > 0)) { meshMaterials = new D3D.Material[materialArray.Length]; meshTextures = new D3D.Texture[materialArray.Length]; for (int i = 0; i < materialArray.Length; i++) { meshMaterials[i] = materialArray[i].Material3D; if (!string.IsNullOrEmpty(materialArray[i].TextureFilename)) { meshTextures[i] = D3D.TextureLoader.FromFile(dev, materialArray[i].TextureFilename); } } } }
/// <summary> /// Creates a copy of a Texture object. /// </summary> /// <param name="tex">Texture object to copy.</param> public Texture(Texture tex) { if (tex != null) { _texture = tex.DXTexture; _name = tex._name; _file = tex._file; _mask = tex._mask; _render = tex._render; _shift = new Vector2(tex._shift.X, tex._shift.Y); _scale = new Vector2(tex._scale.X, tex._scale.Y); _operation = tex._operation; _operationText = tex._operationText; } else { _texture = null; Initialize(); } }
/// <summary> /// Creates a copy of a Texture object. /// </summary> /// <param name="tex">Texture object to copy.</param> public Texture( Texture tex ) { if ( tex != null ) { _texture = tex.DXTexture; _name = tex._name; _file = tex._file; _mask = tex._mask; _render = tex._render; _shift = new Vector2( tex._shift.X, tex._shift.Y ); _scale = new Vector2( tex._scale.X, tex._scale.Y ); _operation = tex._operation; _operationText = tex._operationText; } else { _texture = null; Initialize(); } }
public SplashButton(System.Windows.Forms.Form frm, D3D.Device device3D, Point location, Size dimension, string normalFileName, string mouseOverFileName, string mouseDownFileName, string disableFileName) { device3d = device3D; Location = location; size = dimension; int h = Location.Y + size.Height; int w = Location.X + size.Width; vertices = new D3D.CustomVertex.TransformedTextured[6]; vertices[0] = new D3D.CustomVertex.TransformedTextured(new Vector4(location.X, location.Y, 0f, 1f), 0, 0); vertices[1] = new D3D.CustomVertex.TransformedTextured(new Vector4(w, location.Y, 0f, 1f), 1, 0); vertices[2] = new D3D.CustomVertex.TransformedTextured(new Vector4(location.X, h, 0f, 1f), 0, 1); vertices[3] = new D3D.CustomVertex.TransformedTextured(new Vector4(location.X, h, 0f, 1f), 0, 1); vertices[4] = new D3D.CustomVertex.TransformedTextured(new Vector4(w, location.Y, 0f, 1f), 1, 0); vertices[5] = new D3D.CustomVertex.TransformedTextured(new Vector4(w, h, 0f, 1f), 1, 1); normalTexture = D3D.TextureLoader.FromFile(device3d, normalFileName); mouseOverTexture = D3D.TextureLoader.FromFile(device3d, mouseOverFileName); mouseDownTexture = D3D.TextureLoader.FromFile(device3d, mouseDownFileName); disableTexture = D3D.TextureLoader.FromFile(device3d, disableFileName); Enable = true; // // set mouse device // try { MouseDevice = new DI.Device(DI.SystemGuid.Mouse); MouseDevice.SetDataFormat(DI.DeviceDataFormat.Mouse); MouseDevice.Acquire(); } catch (DirectXException ex) { System.Windows.Forms.MessageBox.Show(ex.Message, ex.Source); } finally { frm.MouseMove += new System.Windows.Forms.MouseEventHandler(frm_MouseMove); } }
/// <summary> /// Called every time a sample is played - videos and images are checked to see if they have been loaded. /// If they have been loaded for the sample in question then thay are displayed in the view window. /// </summary> /// <param name="sample"></param> internal static void show(int sample) { // Check that the video window has been opened. Otherwise exceptions can be thrown as their is nothing // to render to. Surprise ;-) if (globalSettings.videoPortal == true && globalSettings.videoPortal_eRenderReady == true) { // Check for a loaded image - if one exists display it //if (dsInterface.imageLocations[sample] != null) if (globalSettings.osj.image_Locations[sample] != null) { eRender.background = eRender.images[sample]; eRender.renderBackground(eRender.background); } // Check for a loaded video - if one exists - display it if (globalSettings.osj.video_Locations[sample] != null) { // Need to check that the video file has been played, otherwise seting the position // back to 0 does nothing if (videoPlayed[sample] == false) { videoPlayed[sample] = true; int hr = dsMediaControl[sample].Run(); DsError.ThrowExceptionForHR(hr); } else { // Incase we have paused the video - this used to cause problems previously by opening // up additional windows but doesn't seem to be a problem now..? dsMediaControl[sample].Run(); } // If not disposed we can just reset the position, the clip never stops playing by the // looks of this - which is interesting in itself ;-) dsSeekControl[sample] = (DirectShowLib.IMediaPosition)dsGraph[sample]; dsSeekControl[sample].put_CurrentPosition(0); } } }
public void RenderTriangleStrip(int vertexPoolIdx, int first, int count, int textureIdx, int lightmapIdx) { if (!rendering) { return; } VertexBuffer vb = null; Microsoft.DirectX.Direct3D.Texture dxtex = null; Microsoft.DirectX.Direct3D.Texture dxlm = null; // get vertex buffer vb = ((VPListElement)vertexPools[vertexPoolIdx]).vb; // get texture & lightmap dxtex = ((TexListElement)textures[textureIdx]).dxtex; if (light) { dxlm = ((TexListElement)textures[lightmapIdx]).dxtex; } // set stream source (= VB), and FVF device.SetStreamSource(0, vb, 0); device.VertexFormat = VERTEX_FVF; // set textures if (!wire) { device.SetTexture(0, dxtex); if (light) { device.SetTexture(1, dxlm); } } // render device.DrawPrimitives(PrimitiveType.TriangleStrip, (int)first, (int)count - 2); }
private void setIconImage(string path, PictureBox pBx) { try { PresentParameters pp = new PresentParameters(); pp.Windowed = true; pp.SwapEffect = SwapEffect.Copy; Device device = new Device(0, DeviceType.Hardware, this.tgaIconPicBx, CreateFlags.HardwareVertexProcessing, pp); Microsoft.DirectX.Direct3D.Texture tx = TextureLoader.FromFile(device, path); Microsoft.DirectX.GraphicsStream gs = TextureLoader.SaveToStream(ImageFileFormat.Png, tx); Bitmap btmap = new Bitmap(gs); pBx.Image = btmap; gs.Dispose(); tx.Dispose(); device.Dispose(); } catch (Exception ex) { } }
public void Initialize(Device device) { material = new Material(); material.Ambient = ambient; material.Diffuse = diffuse; material.Emissive = emissive; specular = material.Specular; specularSharpness = material.SpecularSharpness; texture = null; if (texturePath.Length > 0) { try { texture = TextureLoader.FromFile(device, texturePath); } catch { System.Windows.Forms.MessageBox.Show("Texture could not be loaded"); } } }
private bool Initialize(TextureManager manager, D3d.Format format, int width, int height,bool mipmap,int multisample) { D3d.Pool d3dPool = D3d.Pool.Default; D3d.Usage d3dUsage = manager.GetUsageFlags( false,mipmap,true ); try { d3dTexture = new D3d.Texture( manager.Device.D3dDevice, width, height, manager.GetMipLevelCount(mipmap), d3dUsage, format, d3dPool ); // Create depth buffer. d3dDepthBuffer = manager.Device.D3dDevice.CreateDepthStencilSurface( width,height,manager.Device.Settings.depthBufferFormat,(D3d.MultiSampleType)multisample,0,true ); this.Initialize(manager, format, width, height, 1, d3dTexture); return true; } catch (D3d.InvalidCallException e) { log.Warning("Unable to create render texture: {0}", e.Message); } catch (D3d.OutOfVideoMemoryException e) { log.Warning("Unable to create render texture: {0}", e.Message); } catch (OutOfMemoryException e) { log.Warning("Unable to create render texture: {0}", e.Message); } return false; }
private bool Initialize(TextureManager manager, D3d.Format format, int width, int height, bool mipmap, int multisample) { D3d.Pool d3dPool = D3d.Pool.Default; D3d.Usage d3dUsage = manager.GetUsageFlags(false, mipmap, true); try { d3dTexture = new D3d.Texture(manager.Device.D3dDevice, width, height, manager.GetMipLevelCount(mipmap), d3dUsage, format, d3dPool); // Create depth buffer. d3dDepthBuffer = manager.Device.D3dDevice.CreateDepthStencilSurface(width, height, manager.Device.Settings.depthBufferFormat, (D3d.MultiSampleType)multisample, 0, true); this.Initialize(manager, format, width, height, 1, d3dTexture); return(true); } catch (D3d.InvalidCallException e) { log.Warning("Unable to create render texture: {0}", e.Message); } catch (D3d.OutOfVideoMemoryException e) { log.Warning("Unable to create render texture: {0}", e.Message); } catch (OutOfMemoryException e) { log.Warning("Unable to create render texture: {0}", e.Message); } return(false); }
/// <summary> /// /// </summary> private void LoadNormalTexture() { Debug.Assert(textureType == TextureType.OneD || textureType == TextureType.TwoD); using (AutoTimer auto = new AutoTimer(textureLoadMeter)) { // DDS load? if (name.EndsWith(".dds")) { Stream stream = TextureManager.Instance.FindResourceData(name); // use D3DX to load the image directly from the stream int numMips = numRequestedMipmaps + 1; // check if mip map volume textures are supported if (!(devCaps.TextureCaps.SupportsMipMap)) { // no mip map support for this kind of textures :( numMipmaps = 0; numMips = 1; } // Determine D3D pool to use D3D.Pool pool; if ((usage & TextureUsage.Dynamic) != 0) pool = D3D.Pool.Default; else pool = D3D.Pool.Managed; Debug.Assert(normTexture == null); Debug.Assert(texture == null); // Trace.TraceInformation("Loaded normal texture {0}", this.Name); normTexture = TextureLoader.FromStream(device, stream, 0, 0, numMips, D3D.Usage.None, D3D.Format.Unknown, pool, Filter.Triangle | Filter.Dither, Filter.Box, 0); // store a ref for the base texture interface texture = normTexture; // set the image data attributes SurfaceDescription desc = normTexture.GetLevelDescription(0); d3dPool = desc.Pool; // set src and dest attributes to the same, we can't know SetSrcAttributes(desc.Width, desc.Height, 1, D3DHelper.ConvertEnum(desc.Format)); SetFinalAttributes(desc.Width, desc.Height, 1, D3DHelper.ConvertEnum(desc.Format)); isLoaded = true; internalResourcesCreated = true; } else { // find & load resource data into stream Stream stream = TextureManager.Instance.FindResourceData(name); int pos = name.LastIndexOf('.'); string ext = name.Substring(pos + 1); Image img = Image.FromStream(stream, ext); LoadImage(img); stream.Dispose(); } } // using }
/// <summary> /// Loads the specified image into the texture. /// </summary> /// <param name="device">The DirectX device to load the texture into.</param> /// <param name="image">The image to load.</param> /// <param name="usage">The Direct3D Usage parameter for the image.</param> /// <param name="pool">The Direct3D Pool parameter for the image.</param> public void SetImage( D3D.Device device, Bitmap image, D3D.Usage usage, D3D.Pool pool ) { if ( _texture != null ) _texture.Dispose(); _texture = new D3D.Texture( device, image, usage, pool ); }
public void SetTexture(Texture newTexture) { texture = newTexture; }
public void OnDeviceReset(object sender, System.EventArgs e) { Direct3D.Device dev = (Direct3D.Device)sender; dev.RenderState.Lighting = false; // ZBufferring is on by default //dev.RenderState.ZBufferEnable = true; if(null != vertexBuffer) { vertexBuffer.Dispose(); } vertexBuffer = new Direct3D.VertexBuffer(m_aVertices[0].GetType(), m_aVertices.Length, dev, Direct3D.Usage.WriteOnly, Direct3D.CustomVertex.PositionColoredTextured.Format, Direct3D.Pool.Default); vertexBuffer.SetData(m_aVertices, 0, Direct3D.LockFlags.None); // In DirectX 9, Vertex and Pixel Shaders do not need to be recreated on a device reset dev.VertexShader = vertexShader; dev.PixelShader = pixelShader; dev.VertexFormat = Direct3D.CustomVertex.PositionColoredTextured.Format; dev.SetStreamSource(0, vertexBuffer, 0); if(null != indexBuffer) { indexBuffer.Dispose(); } indexBuffer = new Direct3D.IndexBuffer(m_aIndices[0].GetType(), m_aIndices.Length, dev, Direct3D.Usage.WriteOnly, Direct3D.Pool.Default); indexBuffer.SetData(m_aIndices, 0, Direct3D.LockFlags.None); dev.Indices = indexBuffer; System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); System.IO.Stream stream = assembly.GetManifestResourceStream("_6_ShaderAsm.photo.png"); // If you want to know the names of all of the embedded resources, // you can get an array of strings with the names. // string[] resourceNames = assembly.GetManifestResourceNames(); // If you want to load the texture from a file instead of an embedded resource, you can do this: // texture = Direct3D.TextureLoader.FromFile(dev, "photo.png"); if(null != texture) { texture.Dispose(); } texture = Direct3D.TextureLoader.FromStream(dev, stream); stream.Close(); dev.SetTexture(0, texture); }
/// <summary> /// Initialize the device objects /// </summary> /// <param name="dev">The grpahics device used to initialize</param> public void InitializeDeviceObjects(Device dev) { if (dev != null) { // Set up our events dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects); } // Keep a local copy of the device device = dev; textureState0 = device.TextureState[0]; textureState1 = device.TextureState[1]; samplerState0 = device.SamplerState[0]; renderState = device.RenderState; // Create a bitmap on which to measure the alphabet Bitmap bmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bmp); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.TextContrast = 0; // Establish the font and texture size textureScale = 1.0f; // Draw fonts into texture without scaling // Calculate the dimensions for the smallest power-of-two texture which // can hold all the printable characters textureWidth = textureHeight = 128; for (;;) { try { // Measure the alphabet PaintAlphabet(g, true); } catch (System.InvalidOperationException) { // Scale up the texture size and try again textureWidth *= 2; textureHeight *= 2; continue; } break; } // If requested texture is too big, use a smaller texture and smaller font, // and scale up when rendering. Direct3D.Caps d3dCaps = device.DeviceCaps; // If the needed texture is too large for the video card... if (textureWidth > d3dCaps.MaxTextureWidth) { // Scale the font size down to fit on the largest possible texture textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth; textureWidth = textureHeight = d3dCaps.MaxTextureWidth; for(;;) { // Create a new, smaller font ourFontHeight = (int) Math.Floor(ourFontHeight * textureScale); systemFont = new System.Drawing.Font(systemFont.Name, ourFontHeight, systemFont.Style); try { // Measure the alphabet PaintAlphabet(g, true); } catch (System.InvalidOperationException) { // If that still doesn't fit, scale down again and continue textureScale *= 0.9F; continue; } break; } } // Release the bitmap used for measuring and create one for drawing bmp.Dispose(); bmp = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); g = Graphics.FromImage(bmp); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.TextContrast = 0; // Draw the alphabet PaintAlphabet(g, false); // Create a new texture for the font from the bitmap we just created fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed); RestoreDeviceObjects(null, null); }
public virtual void Dispose() { if (d3dTexture != null) d3dTexture.Dispose(); d3dTexture = null; if (d3dSurface != null) d3dSurface.Dispose(); d3dSurface = null; loaded = false; }
/// <summary> /// Creates the texture as a render target. /// </summary> public Texture(Renderer renderer, int width, int height, bool alpha) { if (renderer == null) throw new ArgumentNullException("renderer", "Unable to create texture without a valid renderer reference."); this.renderer = renderer; try { d3dTexture = new Microsoft.DirectX.Direct3D.Texture(renderer.Device, width, height, 1, Usage.RenderTarget, alpha ? Format.A8R8G8B8 : Format.X8R8G8B8, Pool.Default); d3dSurface = d3dTexture.GetSurfaceLevel(0); this.size = new Size(width, height); this.hasAlpha = alpha; loaded = true; renderer.AddGraphicsObject(this); } catch (Exception ex) { loaded = false; Log.Write("Failed to create texture as render target, will use empty texture!" + " Error: " + ex.ToString()); } }
public int InitializeDevice(IntPtr dwUserID, ref VMR9AllocationInfo lpAllocInfo, ref int lpNumBuffers) { lock (this) { log.InfoFormat("DirectShowCodec[{0}]: {1}x{2} : {3} / {4} / {5} / {6} / 0x{7:x}", ID, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight, FourCCToStr(lpAllocInfo.Format), adapterInfo.CurrentDisplayMode.Format, lpAllocInfo.MinBuffers, (Pool)lpAllocInfo.Pool, lpAllocInfo.dwFlags); Axiom.Media.PixelFormat texFormat = D3DHelper.ConvertEnum(adapterInfo.CurrentDisplayMode.Format); Format format = (Format)lpAllocInfo.Format; // if format is YUV ? (note : 0x30303030 = " ") if (lpAllocInfo.Format > 0x30303030) { // NV12 textures appear not to play correctly; when using them with an // offscreen surface, they only show the first frame or so. Doing this // should cause it to renegotiate to RGB. // // New and improved: YV12 seems to have the same problem. if ( (lpAllocInfo.Format == StrToFourCC("NV12")) || (lpAllocInfo.Format == StrToFourCC("YV12")) ) { // XXXMLM - this may cause us to pop an external window log.WarnFormat("DirectShowCodec[{0}]: Rejecting {1} format", ID, FourCCToStr(lpAllocInfo.Format)); return D3DERR_INVALIDCALL; } // Check if the hardware support format conversion from this YUV format to the RGB desktop format if (!D3D.Manager.CheckDeviceFormatConversion(creationParameters.AdapterOrdinal, creationParameters.DeviceType, (Format)lpAllocInfo.Format, adapterInfo.CurrentDisplayMode.Format)) { // If not, refuse this format! // The VMR9 will propose other formats supported by the downstream filter output pin. log.WarnFormat("DirectShowCodec[{0}]: Cannot convert between formats", ID); return D3DERR_INVALIDCALL; } } try { IDirect3DDevice9* unmanagedDevice = device.UnmanagedComPointer; IntPtr hMonitor = D3D.Manager.GetAdapterMonitor(adapterInfo.Adapter); // Give our Direct3D device to the VMR9 filter try { IVMRSurfaceAllocatorNotify9 notify9 = vmrSurfaceAllocatorNotify; vmrSurfaceAllocatorNotify.SetD3DDevice((IntPtr)unmanagedDevice, hMonitor); } catch (InvalidCastException e) { // It turns out that if this function is called from the // decoder thread, the hr return value of the SetD3DDevice // call will be E_INVALIDCAST. However, if we've already // notified the allocator notify interface of the device, // the rest of this function will happen correctly. So // only throw the exception if we haven't notified the // device yet. if ((IntPtr)unmanagedDevice != notifiedDevice) { throw e; } } notifiedDevice = (IntPtr)unmanagedDevice; videoSize = new Size(lpAllocInfo.dwWidth, lpAllocInfo.dwHeight); videoRectangle = new Rectangle(Point.Empty, videoSize); // Always do power of two sized textures lpAllocInfo.dwWidth = Manager.NextPowerOfTwo(lpAllocInfo.dwWidth); lpAllocInfo.dwHeight = Manager.NextPowerOfTwo(lpAllocInfo.dwHeight); textureSize = new Size(lpAllocInfo.dwWidth, lpAllocInfo.dwHeight); // Just in case DeleteSurfaces(); // if format is YUV ? if (lpAllocInfo.Format > 0x30303030) { log.InfoFormat("DirectShowCodec[{0}]: Creating offscreen surface ({1}x{2})", ID, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight); // An offscreen surface must be created lpAllocInfo.dwFlags |= VMR9SurfaceAllocationFlags.OffscreenSurface; // Create it try { // ATI and nVidia both fail this call when created with YUV, so ask for // an RGB texture first if we can get away with it. if ((lpAllocInfo.dwFlags & VMR9SurfaceAllocationFlags.RGBDynamicSwitch) != 0) { videoSurface = device.CreateOffscreenPlainSurface(lpAllocInfo.dwWidth, lpAllocInfo.dwHeight, adapterInfo.CurrentDisplayMode.Format, (Pool)lpAllocInfo.Pool); } else { videoSurface = device.CreateOffscreenPlainSurface(lpAllocInfo.dwWidth, lpAllocInfo.dwHeight, (Format)lpAllocInfo.Format, (Pool)lpAllocInfo.Pool); } } catch { log.WarnFormat("Failed to create {0} surface", (Format)lpAllocInfo.Format); return D3DERR_INVALIDCALL; } // And get it unmanaged pointer unmanagedSurface = videoSurface.UnmanagedComPointer; axiomTexture = TextureManager.Instance.GetByName(textureName); if (axiomTexture != null) { log.InfoFormat("DirectShowCodec[{0}]: Removing old texture \"{1}\"", ID, textureName); axiomTexture.Unload(); axiomTexture.TextureType = TextureType.TwoD; axiomTexture.Width = lpAllocInfo.dwWidth; axiomTexture.Height = lpAllocInfo.dwHeight; axiomTexture.NumMipMaps = 0; axiomTexture.Format = texFormat; axiomTexture.Usage = TextureUsage.RenderTarget; axiomTexture.CreateInternalResources(); } else { axiomTexture = TextureManager.Instance.CreateManual( textureName, TextureType.TwoD, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight, 0, // no mip maps texFormat, // from the display TextureUsage.RenderTarget); } if (axiomTexture is D3DTexture) { D3DTexture d3t = (D3DTexture)axiomTexture; if (d3t.DXTexture is D3D.Texture) { privateTexture = (D3D.Texture)d3t.DXTexture; } else { throw new Exception("D3D texture could not get DX texture"); } } else { throw new Exception("D3D Texture failed to create"); } // Get the MipMap surface 0 for the copy (see PresentImage) privateSurface = privateTexture.GetSurfaceLevel(0); device.ColorFill(privateSurface, new Rectangle(0, 0, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight), Color.Black); // This code path need a surface copy needCopy = true; } else { log.InfoFormat("DirectShowCodec[{0}]: Creating texture surface ({1}x{2})", ID, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight); // in RGB pixel format //lpAllocInfo.dwFlags |= VMR9SurfaceAllocationFlags.TextureSurface; //Surface s = device.CreateRenderTarget(); axiomTexture = TextureManager.Instance.GetByName(textureName); if (axiomTexture != null) { log.InfoFormat("DirectShowCodec[{0}]: Removing old texture \"{1}\"", ID, textureName); axiomTexture.Unload(); axiomTexture.TextureType = TextureType.TwoD; axiomTexture.Width = lpAllocInfo.dwWidth; axiomTexture.Height = lpAllocInfo.dwHeight; axiomTexture.NumMipMaps = 0; axiomTexture.Format = texFormat; axiomTexture.Usage = TextureUsage.RenderTarget; axiomTexture.CreateInternalResources(); } else { axiomTexture = TextureManager.Instance.CreateManual( textureName, TextureType.TwoD, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight, 0, // no mip maps texFormat, // from the display TextureUsage.RenderTarget); } if (axiomTexture is D3DTexture) { D3DTexture d3t = (D3DTexture)axiomTexture; if (d3t.DXTexture is D3D.Texture) { privateTexture = (D3D.Texture)d3t.DXTexture; } } else { throw new Exception("D3D Texture failed to create"); } // And get the MipMap surface 0 for the VMR9 filter privateSurface = privateTexture.GetSurfaceLevel(0); unmanagedSurface = privateSurface.UnmanagedComPointer; device.ColorFill(privateSurface, new Rectangle(0, 0, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight), Color.Black); // This code path don't need a surface copy. // The client appllication use the same texture the VMR9 filter use. needCopy = false; } // This allocator only support 1 buffer. // Notify the VMR9 filter lpNumBuffers = 1; } catch (DirectXException e) { // A Direct3D error can occure : Notify it to the VMR9 filter LogUtil.ExceptionLog.ErrorFormat("Caught DirectX Exception: {0}", e.ToString()); return e.ErrorCode; } catch (Exception e) { // Or else, notify a more general error LogUtil.ExceptionLog.ErrorFormat("Caught Exception: {0}", e.ToString()); return E_FAIL; } // This allocation is a success return 0; } }
public void RenderTexture(int textureIdx, float left, float top, float width, float height, float depth) { if (!rendering) { return; } if (wire) { return; } Microsoft.DirectX.Direct3D.Texture dxtex = null; Microsoft.DirectX.Matrix mProj, mView, mWorld; bool zbuffer; // get texture dxtex = ((TexListElement)textures[textureIdx]).dxtex; // backup transformation matrices mProj = device.Transform.Projection; mView = device.Transform.View; mWorld = device.Transform.World; // Setup an orthographic perspective device.Transform.Projection = Microsoft.DirectX.Matrix.OrthoLH(1.0f, 1.0f, 0.0f, 1.0f); device.Transform.View = Microsoft.DirectX.Matrix.Identity; device.Transform.World = Microsoft.DirectX.Matrix.Scaling(width, height, 1.0f) * Microsoft.DirectX.Matrix.Translation(left, top, depth); // backup and set depthbuffer zbuffer = DepthBuffer; DepthBuffer = false; // Set render and texture stage states device.RenderState.AlphaBlendEnable = true; device.TextureState[0].ColorOperation = TextureOperation.SelectArg1; device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; device.TextureState[0].AlphaOperation = TextureOperation.SelectArg1; device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor; device.TextureState[1].ColorOperation = TextureOperation.Disable; // set texture device.SetTexture(0, dxtex); // set stream source (= VB), and FVF device.SetStreamSource(0, vb2d, 0); device.VertexFormat = CustomVertex.PositionTextured.Format; // Render texture device.DrawPrimitives(PrimitiveType.TriangleFan, 0, 2); // Restore states SetStates(); // restire DepthBuffer DepthBuffer = zbuffer; // Restore transformation matrices device.Transform.Projection = mProj; device.Transform.View = mView; device.Transform.World = mWorld; }
public static void LoadMesh(Stream stream, D3D.Device dev, ref D3D.Mesh mesh, ref D3D.Material[] meshMaterials, ref D3D.Texture[] meshTextures) { D3D.ExtendedMaterial[] materialArray; mesh = D3D.Mesh.FromStream(stream, D3D.MeshFlags.Managed, dev, out materialArray); if ((materialArray != null) && (materialArray.Length > 0)) { meshMaterials = new D3D.Material[materialArray.Length]; meshTextures = new D3D.Texture[materialArray.Length]; for (int i = 0; i < materialArray.Length; i++) { meshMaterials[i] = materialArray[i].Material3D; if (!string.IsNullOrEmpty(materialArray[i].TextureFilename)) meshTextures[i] = D3D.TextureLoader.FromFile(dev, materialArray[i].TextureFilename); } } }
// Delete surfaces... private void DeleteSurfaces() { lock (this) { if (privateTexture != null) { privateTexture.Dispose(); privateTexture = null; } if (privateSurface != null) { privateSurface.Dispose(); privateSurface = null; } if (videoSurface != null) { videoSurface.Dispose(); videoSurface = null; } axiomTexture = null; } }
public static void renderBackground(Texture texture) { // To store the converted video // no longer required - textures now saved out and sent to a memory stream. //convertedVideo[frameCounter++] = texture; // Prevent anything from being rendered until ready if (globalSettings.videoPortal_eRenderReady == false) { return; } // Origionaly split out but more stable as part of this method if (device == null || device.Disposed) { return; } device.BeginScene(); // Renders to a flat plane - i.e. the screen CustomVertex.TransformedTextured[] screenVert = new CustomVertex.TransformedTextured[4]; screenVert[0] = new CustomVertex.TransformedTextured(0, 0, 0, 1, 0, 0); screenVert[1] = new CustomVertex.TransformedTextured(clientForm.Width, 0, 0, 1, 1, 0); screenVert[2] = new CustomVertex.TransformedTextured(clientForm.Width, clientForm.Height, 0, 1, 1, 1); screenVert[3] = new CustomVertex.TransformedTextured(0, clientForm.Height, 0, 1, 0, 1); // To tile textures, use the wrap texture type - It's used by default... // device.SamplerState[1].AddressU = TextureAddress.Wrap; device.SamplerState[1].AddressV = TextureAddress.Wrap; // Then set the U&V co-ordinates to the number of times you want the texture replicated // i.e. if you change both the U&V co-ords to 2 then you will see the texture tiled 4 times, 2 across and 2 down // Turn off while drawing the background //device.RenderState.ZBufferEnable = false; // Test with vertex buffer // buffer.SetData(screenVert, 0, LockFlags.None); // -----------Stuffn with -------------------------------- //SamplerStateManager sam = new SamplerStateManager(); //sam = TextureAddress.Border; //device.SetSamplerState(0,SamplerStageStates.SrgbTexture, true); //TextureAddress tex = new TextureAddress(); //tex = TextureAddress.Border; // -----------Stuffn with -------------------------------- //// These would probably work if the textures were first copied to a newly created texture in this //// transactions scope //fUtil.addFrame(device.GetTexture(0)); //fUtil.addFrame(texture); //// This works to save the rendered frame to a BMP //Bitmap bmp = SaveToBitmap(device); //fUtil.addBmpFrame(bmp); // Attemptng to save the frame as a memory stream in the DDS format //SaveToDDSFile(device); //fUtil.addDDSFrame("TempDDSConv.dds"); //fUtil.addMSFrame(aMS); // Set the texture to render to the background device.SetTexture(0, texture); if (lastFrame != null) { // For Vertex Buffer //device.SetStreamSource(0, buffer, 0,0); device.SetTexture(1, lastFrame); // Sets the U&V co-ordinates for the '1' (i.e. second) texture stage to the same as the first! // I wish ths was better f*****g documented, seriosuly device.TextureState[1].TextureCoordinateIndex = 0; // For Vertex Buffer //device.SetStreamSource(1, buffer, 0,0); //-------------- more stuffn //device.SamplerState[0].AddressU = TextureAddress.Border; //device.SamplerState[0].AddressV = TextureAddress.Border; // wrap is the default mode device.SamplerState[1].AddressU = TextureAddress.Wrap; device.SamplerState[1].AddressV = TextureAddress.Wrap; //------------- //// Blend and mix - around 50% transperancy device.SetTextureStageState(0, TextureStageStates.ColorArgument1, (int)TextureArgument.TextureColor); device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); device.SetTextureStageState(1, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); device.SetTextureStageState(1, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.Add); // Lighter blend //device.SetTextureStageState(0, TextureStageStates.ColorArgument1, (int)TextureArgument.TextureColor); //device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); //device.SetTextureStageState(1, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); //device.SetTextureStageState(1, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); //device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.MultiplyAdd); // Subtract the darker colour from the lighter colour //device.SetTextureStageState(0, TextureStageStates.ColorArgument1, (int)TextureArgument.TextureColor); //device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); //device.SetTextureStageState(1, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); //device.SetTextureStageState(1, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); //device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.Subtract); // Add with a darker tinge //device.SetTextureStageState(0, TextureStageStates.ColorArgument1, (int)TextureArgument.TextureColor); //device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); //device.SetTextureStageState(1, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); //device.SetTextureStageState(1, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); //device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.AddSigned); // Add with highted highlights and darkened shadows //device.SetTextureStageState(0, TextureStageStates.ColorArgument1, (int)TextureArgument.TextureColor); //device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); //device.SetTextureStageState(1, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); //device.SetTextureStageState(1, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); //device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.AddSigned2X); // Add with a lighter mix //device.SetTextureStageState(0, TextureStageStates.ColorArgument1, (int)TextureArgument.TextureColor); //device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); //device.SetTextureStageState(1, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); //device.SetTextureStageState(1, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); //device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.AddSmooth); // Use colour to tint image mix //device.SetTextureStageState(0, TextureStageStates.ColorArgument1, (int)TextureArgument.TextureColor); //device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); //device.SetTextureStageState(1, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); //device.SetTextureStageState(1, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); //device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.Modulate); // Add image and inverse white parts of the image being added //device.SetTextureStageState(0, TextureStageStates.ColorArgument1, (int)TextureArgument.TextureColor); //device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); //device.SetTextureStageState(1, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); //device.SetTextureStageState(1, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); //device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.Lerp); // Black and white image add. //device.SetTextureStageState(0, TextureStageStates.ColorArgument1, (int)TextureArgument.TextureColor); //device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); //device.SetTextureStageState(1, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); //device.SetTextureStageState(1, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); //device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.DotProduct3); //if (secondLastFrame != null) //{ // device.TextureState[2].TextureCoordinateIndex = 0; // device.SetTextureStageState(1, TextureStageStates.ColorOperation, (int)TextureOperation.SelectArg1); // device.SetTexture(2, secondLastFrame); // device.SetTextureStageState(2, TextureStageStates.ColorArgument1, (int)TextureArgument.Current); // device.SetTextureStageState(2, TextureStageStates.ColorArgument2, (int)TextureArgument.TextureColor); // device.SetTextureStageState(2, TextureStageStates.ColorOperation, (int)TextureOperation.Add); //} } //secondLastFrame = lastFrame; lastFrame = texture; //device.VertexFormat = CustomVertex.TransformedTextured.Format; device.VertexFormat = vertexFormat; device.DrawUserPrimitives(PrimitiveType.TriangleFan, 2, screenVert); // Turn it back on // device.RenderState.ZBufferEnable = true; // Origionaly split out but more stable in the same method device.EndScene(); device.Present(); }
/// <summary> /// Creates a DirectX texture object. /// </summary> public Texture() { _texture = null; Initialize(); }
public static Texture Load(string strPic, int iRotate, int iMaxWidth, int iMaxHeight, bool bRGB, bool bZoom, bool bOversized, out int iWidth, out int iHeight) { iWidth = 0; iHeight = 0; if (strPic == null) { return(null); } if (strPic == string.Empty) { return(null); } Direct3D.Texture texture = null; Image theImage = null; try { try { theImage = ImageFast.FromFile(strPic); Log.Debug("Picture: Fast loaded texture {0}", strPic); } catch (Exception) { theImage = Image.FromFile(strPic); Log.Warn("Picture: Fallback loaded texture {0}", strPic); } if (theImage == null) { return(null); } if (iRotate > 0) { RotateFlipType fliptype; switch (iRotate) { case 1: fliptype = RotateFlipType.Rotate90FlipNone; theImage.RotateFlip(fliptype); break; case 2: fliptype = RotateFlipType.Rotate180FlipNone; theImage.RotateFlip(fliptype); break; case 3: fliptype = RotateFlipType.Rotate270FlipNone; theImage.RotateFlip(fliptype); break; default: fliptype = RotateFlipType.RotateNoneFlipNone; break; } } iWidth = theImage.Size.Width; iHeight = theImage.Size.Height; int iBitmapWidth = iWidth; int iBitmapHeight = iHeight; bool bResize = false; float fOutputFrameAR; if (bZoom) { bResize = true; iBitmapWidth = iMaxWidth; iBitmapHeight = iMaxHeight; while (iWidth < iMaxWidth || iHeight < iMaxHeight) { iWidth *= 2; iHeight *= 2; } int iOffsetX1 = GUIGraphicsContext.OverScanLeft; int iOffsetY1 = GUIGraphicsContext.OverScanTop; int iScreenWidth = GUIGraphicsContext.OverScanWidth; int iScreenHeight = GUIGraphicsContext.OverScanHeight; float fPixelRatio = GUIGraphicsContext.PixelRatio; float fSourceFrameAR = ((float)iWidth) / ((float)iHeight); fOutputFrameAR = fSourceFrameAR / fPixelRatio; } else { fOutputFrameAR = ((float)iWidth) / ((float)iHeight); } if (iWidth > iMaxWidth) { bResize = true; iWidth = iMaxWidth; iHeight = (int)(((float)iWidth) / fOutputFrameAR); } if (iHeight > (int)iMaxHeight) { bResize = true; iHeight = iMaxHeight; iWidth = (int)(fOutputFrameAR * ((float)iHeight)); } if (!bOversized) { iBitmapWidth = iWidth; iBitmapHeight = iHeight; } else { // Adjust width/height 2 pixcels for smoother zoom actions at the edges iBitmapWidth = iWidth + 2; iBitmapHeight = iHeight + 2; bResize = true; } if (bResize) { using (Bitmap result = new Bitmap(iBitmapWidth, iBitmapHeight)) { using (Graphics g = Graphics.FromImage(result)) { g.CompositingQuality = Thumbs.Compositing; g.InterpolationMode = Thumbs.Interpolation; g.SmoothingMode = Thumbs.Smoothing; if (bOversized) { // Set picture at center position int xpos = 1; // (iMaxWidth-iWidth)/2; int ypos = 1; // (iMaxHeight-iHeight)/2; g.DrawImage(theImage, new Rectangle(xpos, ypos, iWidth, iHeight)); } else { g.DrawImage(theImage, new Rectangle(0, 0, iWidth, iHeight)); } } texture = Picture.ConvertImageToTexture(result, out iWidth, out iHeight); } } else { texture = Picture.ConvertImageToTexture((Bitmap)theImage, out iWidth, out iHeight); } } catch (ThreadAbortException ext) { Log.Debug("Picture: exception loading {0} err:{1}", strPic, ext.Message); } catch (Exception ex) { Log.Warn("Picture: exception loading {0} err:{1}", strPic, ex.Message); } finally { if (theImage != null) { theImage.SafeDispose(); } } return(texture); }
///<summary> /// @copydoc HardwarePixelBuffer.BlitToMemory ///</summary> public override void BlitToMemory(BasicBox srcBox, PixelBox dst) { // Decide on pixel format of temp surface PixelFormat tmpFormat = format; if (D3DHelper.ConvertEnum(dst.Format) == D3D.Format.Unknown) tmpFormat = dst.Format; if (surface != null) { Debug.Assert(srcBox.Depth == 1 && dst.Depth == 1); // Create temp texture D3D.Texture tmp = new D3D.Texture(device, dst.Width, dst.Height, 1, // 1 mip level ie topmost, generate no mipmaps 0, D3DHelper.ConvertEnum(tmpFormat), Pool.Scratch); D3D.Surface subSurface = tmp.GetSurfaceLevel(0); // Copy texture to this temp surface Rectangle destRect, srcRect; srcRect = ToD3DRectangle(srcBox); destRect = ToD3DRectangleExtent(dst); SurfaceLoader.FromSurface(subSurface, destRect, surface, srcRect, Filter.None, 0); // Lock temp surface and copy it to memory int pitch; // Filled in by D3D GraphicsStream data = subSurface.LockRectangle(D3D.LockFlags.ReadOnly, out pitch); // Copy it PixelBox locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat); FromD3DLock(locked, pitch, data); PixelUtil.BulkPixelConversion(locked, dst); subSurface.UnlockRectangle(); // Release temporary surface and texture subSurface.Dispose(); tmp.Dispose(); } else { // Create temp texture D3D.VolumeTexture tmp = new D3D.VolumeTexture(device, dst.Width, dst.Height, dst.Depth, 0, D3D.Usage.None, D3DHelper.ConvertEnum(tmpFormat), Pool.Scratch); D3D.Volume subVolume = tmp.GetVolumeLevel(0); // Volume D3D.Box ddestBox = ToD3DBoxExtent(dst); D3D.Box dsrcBox = ToD3DBox(srcBox); VolumeLoader.FromVolume(subVolume, ddestBox, volume, dsrcBox, Filter.None, 0); // Lock temp surface and copy it to memory D3D.LockedBox lbox; // Filled in by D3D GraphicsStream data = subVolume.LockBox(LockFlags.ReadOnly, out lbox); // Copy it PixelBox locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat); FromD3DLock(locked, lbox, data); PixelUtil.BulkPixelConversion(locked, dst); subVolume.UnlockBox(); // Release temporary surface and texture subVolume.Dispose(); tmp.Dispose(); } }
/// <summary> /// /// </summary> //private void CreateDepthStencil() { // // Get the format of the depth stencil surface of our main render target. // D3D.Surface surface = device.DepthStencilSurface; // D3D.SurfaceDescription desc = surface.Description; // // Create a depth buffer for our render target, it must be of // // the same format as other targets !!! // depthBuffer = device.CreateDepthStencilSurface( // srcWidth, // srcHeight, // // TODO: Verify this goes through, this is ridiculous // (D3D.DepthFormat)desc.Format, // desc.MultiSampleType, // desc.MultiSampleQuality, // false); //} private void CreateNormalTexture() { // we must have those defined here Debug.Assert(srcWidth > 0 && srcHeight > 0); // determine which D3D9 pixel format we'll use D3D.Format d3dPixelFormat = ChooseD3DFormat(); // at this point, Ogre checks to see if this texture format works, // but we go on and figure out the rest of our info first. // set the appropriate usage based on the usage of this texture D3D.Usage d3dUsage = ((usage & TextureUsage.RenderTarget) == TextureUsage.RenderTarget) ? D3D.Usage.RenderTarget : D3D.Usage.None; // how many mips to use? int numMips = numRequestedMipmaps + 1; // Check dynamic textures if ((usage & TextureUsage.Dynamic) != 0) { if (CanUseDynamicTextures(d3dUsage, ResourceType.Textures, d3dPixelFormat)) { d3dUsage |= D3D.Usage.Dynamic; dynamicTextures = true; } else { dynamicTextures = false; } } // check if mip maps are supported on hardware mipmapsHardwareGenerated = false; if (devCaps.TextureCaps.SupportsMipMap) { if (((usage & TextureUsage.AutoMipMap) == TextureUsage.AutoMipMap) && numRequestedMipmaps > 0) { // use auto.gen. if available mipmapsHardwareGenerated = this.CanAutoGenMipMaps(d3dUsage, ResourceType.Textures, d3dPixelFormat); if (mipmapsHardwareGenerated) { d3dUsage |= D3D.Usage.AutoGenerateMipMap; numMips = 0; } } } else { // no mip map support for this kind of texture numMipmaps = 0; numMips = 1; } // check texture requirements D3D.TextureRequirements texRequire = new D3D.TextureRequirements(); texRequire.Width = srcWidth; texRequire.Height = srcHeight; texRequire.NumberMipLevels = numMips; texRequire.Format = d3dPixelFormat; // NOTE: Although texRequire is an out parameter, it actually does // use the data passed in with that object. TextureLoader.CheckTextureRequirements(device, d3dUsage, Pool.Default, out texRequire); numMips = texRequire.NumberMipLevels; d3dPixelFormat = texRequire.Format; Debug.Assert(normTexture == null); Debug.Assert(texture == null); log.InfoFormat("Created normal texture {0}", this.Name); // create the texture normTexture = new D3D.Texture( device, srcWidth, srcHeight, numMips, d3dUsage, d3dPixelFormat, d3dPool); // store base reference to the texture texture = normTexture; // set the final texture attributes D3D.SurfaceDescription desc = normTexture.GetLevelDescription(0); SetFinalAttributes(desc.Width, desc.Height, 1, D3DHelper.ConvertEnum(desc.Format)); if (mipmapsHardwareGenerated) texture.AutoGenerateFilterType = GetBestFilterMethod(); }
protected virtual void CreateBody() { if((m_strTexture.Trim().Length > 0 && m_d3dTexture == null) || (m_d3dTexture != null && m_d3dTexture.Disposed) ) { LoadTextureImage(m_strTexture); if(m_imgTexture != null) { m_d3dTexture = new Texture(m_d3dDevice, m_imgTexture, 0, Pool.Managed); m_d3dAlphaTexture = new Texture(m_d3dDevice, m_imgAlphaTexture, 0, Pool.Managed); } } float fltScale = ((this.MinDimension + this.MaxDimension)/2 * 0.15f); if(fltScale > 0.1f) fltScale = 0.1f; m_mshAxisCylinder = Mesh.Cylinder(Device,fltScale, fltScale, 20 * fltScale, 16, 16); m_mshAxisCone = Mesh.Cylinder(Device,0.0f, 3 * fltScale, 5 * fltScale, 16, 16); m_mshAxisLabel = Util_DX.CreateBillboard(Device,5 * fltScale, 5 * fltScale); m_matXAxis = new Material(); m_matXAxis.Diffuse = Color.Red; m_matYAxis = new Material(); m_matYAxis.Diffuse = Color.Green; m_matZAxis = new Material(); m_matZAxis.Diffuse = Color.Blue; LoadTextures(); }
public TexListElement(Texture tex, Microsoft.DirectX.Direct3D.Texture dxtex) { this.tex = tex; this.dxtex = dxtex; }
protected override void FreeInternalResourcesImpl() { if (texture != null) { texture.Dispose(); texture = null; } if (normTexture != null) { normTexture.Dispose(); normTexture = null; } if (cubeTexture != null) { cubeTexture.Dispose(); cubeTexture = null; } if (volumeTexture != null) { volumeTexture.Dispose(); volumeTexture = null; } foreach (IDisposable buf in managedObjects) buf.Dispose(); managedObjects.Clear(); }
private void LoadTexture() { texture = TextureLoader.FromFile(device, "F:\\TYCS\\GP\\images\\bg.jpg", 400, 400, 1, 0, Format.A8B8G8R8, Pool.Managed, Filter.Point, Filter.Point, Color.Transparent.ToArgb()); } //take any texture image as bg.
private void setIconImage(string path) { try { PresentParameters pp = new PresentParameters(); pp.Windowed = true; pp.SwapEffect = SwapEffect.Copy; Device device = new Device(0, DeviceType.Hardware, this.rgb_picBx, CreateFlags.HardwareVertexProcessing, pp); Microsoft.DirectX.Direct3D.Texture tx = TextureLoader.FromFile(device, path); Microsoft.DirectX.GraphicsStream gs = TextureLoader.SaveToStream(ImageFileFormat.Dib, tx); Bitmap RGB_bitmap = new Bitmap(gs); Bitmap alpha_bitmap = new Bitmap(gs); rgb_picBx.Image = RGB_bitmap; //alpha_bitmap.MakeTransparent(); gs.Seek(0, 0); System.Drawing.Imaging.BitmapData bmpData = alpha_bitmap.LockBits(new Rectangle(0, 0, alpha_bitmap.Width, alpha_bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, alpha_bitmap.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * alpha_bitmap.Height; int gsLen = (int)gs.Length; byte[] rgbaValues = new byte[bytes]; byte[] gsBytes = new byte[gsLen]; gs.Read(gsBytes, 0, gsLen); int gsLastI = gsLen - 1; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbaValues, 0, bytes); int i = 0; for (int y = 0; y < bmpData.Height; y++) { for (int x = 0; x < bmpData.Width; x++) { byte g = gsBytes[gsLastI - i++], b = gsBytes[gsLastI - i++], a = gsBytes[gsLastI - i++], r = gsBytes[gsLastI - i++]; Color pClr = Color.FromArgb(255, a, a, a); System.Runtime.InteropServices.Marshal.WriteInt32(bmpData.Scan0, (bmpData.Stride * y) + (4 * x), pClr.ToArgb()); } } alpha_bitmap.UnlockBits(bmpData); alpha_bitmap.RotateFlip(RotateFlipType.Rotate180FlipY); alpha_picBx.Image = alpha_bitmap; gs.Dispose(); tx.Dispose(); device.Dispose(); } catch (Exception ex) { } }
/// <summary> /// Initialize the device objects /// </summary> /// <param name="dev">The grpahics device used to initialize</param> public void InitializeDeviceObjects(Device dev) { if (dev != null) { // Set up our events dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects); } // Keep a local copy of the device device = dev; textureState0 = device.TextureState[0]; textureState1 = device.TextureState[1]; samplerState0 = device.SamplerState[0]; renderState = device.RenderState; // Create a bitmap on which to measure the alphabet Bitmap bmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bmp); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.TextContrast = 0; // Establish the font and texture size textureScale = 1.0f; // Draw fonts into texture without scaling // Calculate the dimensions for the smallest power-of-two texture which // can hold all the printable characters textureWidth = textureHeight = 128; for (;;) { try { // Measure the alphabet PaintAlphabet(g, true); } catch (System.InvalidOperationException) { // Scale up the texture size and try again textureWidth *= 2; textureHeight *= 2; continue; } break; } // If requested texture is too big, use a smaller texture and smaller font, // and scale up when rendering. Direct3D.Caps d3dCaps = device.DeviceCaps; // If the needed texture is too large for the video card... if (textureWidth > d3dCaps.MaxTextureWidth) { // Scale the font size down to fit on the largest possible texture textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth; textureWidth = textureHeight = d3dCaps.MaxTextureWidth; for (;;) { // Create a new, smaller font ourFontHeight = (int)Math.Floor(ourFontHeight * textureScale); systemFont = new System.Drawing.Font(systemFont.Name, ourFontHeight, systemFont.Style); try { // Measure the alphabet PaintAlphabet(g, true); } catch (System.InvalidOperationException) { // If that still doesn't fit, scale down again and continue textureScale *= 0.9F; continue; } break; } } // Release the bitmap used for measuring and create one for drawing bmp.Dispose(); bmp = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); g = Graphics.FromImage(bmp); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.TextContrast = 0; // Draw the alphabet PaintAlphabet(g, false); // Create a new texture for the font from the bitmap we just created fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed); RestoreDeviceObjects(null, null); }
public void Initialize(Device device) { material = new Material(); material.Ambient = ambient; material.Diffuse = diffuse; material.Emissive = emissive; specular = material.Specular; specularSharpness = material.SpecularSharpness; texture = null; if(texturePath.Length > 0) { try { texture = TextureLoader.FromFile(device,texturePath); } catch { System.Windows.Forms.MessageBox.Show("Texture could not be loaded"); } } }
/// <summary> /// Safely disposes of the texture data. /// </summary> public void Dispose() { if ( _texture != null ) { _texture.Dispose(); _texture = null; } Initialize(); }
/// <summary> /// Initialize the device objects /// </summary> /// <param name="dev">The grpahics device used to initialize</param> public void InitializeDeviceObjects(Device dev) { if (dev != null) { // Set up our events dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects); } // Keep a local copy of the device device = dev; textureState0 = device.TextureState[0]; textureState1 = device.TextureState[1]; samplerState0 = device.SamplerState[0]; renderState = device.RenderState; // Establish the font and texture size textureScale = 1.0f; // Draw fonts into texture without scaling // Large fonts need larger textures if (ourFontHeight > 60) { textureWidth = textureHeight = 2048; } else if (ourFontHeight > 30) { textureWidth = textureHeight = 1024; } else if (ourFontHeight > 15) { textureWidth = textureHeight = 512; } else { textureWidth = textureHeight = 256; } // If requested texture is too big, use a smaller texture and smaller font, // and scale up when rendering. Direct3D.Caps d3dCaps = device.DeviceCaps; if (textureWidth > d3dCaps.MaxTextureWidth) { textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth; textureWidth = textureHeight = d3dCaps.MaxTextureWidth; } Bitmap bmp = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bmp); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.TextContrast = 0; string str; float x = 0; float y = 0; Point p = new Point(0, 0); Size size = new Size(0, 0); // Calculate the spacing between characters based on line height size = g.MeasureString(" ", systemFont).ToSize(); x = spacingPerChar = (int)Math.Ceiling(size.Height * 0.3); for (char c = (char)32; c < (char)127; c++) { str = c.ToString(); // We need to do some things here to get the right sizes. The default implemententation of MeasureString // will return a resolution independant size. For our height, this is what we want. However, for our width, we // want a resolution dependant size. Size resSize = g.MeasureString(str, systemFont).ToSize(); size.Height = resSize.Height + 1; // Now the Resolution independent width if (c != ' ') // We need the special case here because a space has a 0 width in GenericTypoGraphic stringformats { resSize = g.MeasureString(str, systemFont, p, StringFormat.GenericTypographic).ToSize(); size.Width = resSize.Width; } else { size.Width = resSize.Width; } if ((x + size.Width + spacingPerChar) > textureWidth) { x = spacingPerChar; y += size.Height; } if (c != ' ') // We need the special case here because a space has a 0 width in GenericTypoGraphic stringformats { g.DrawString(str, systemFont, Brushes.White, new Point((int)x, (int)y), StringFormat.GenericTypographic); } else { g.DrawString(str, systemFont, Brushes.White, new Point((int)x, (int)y)); } textureCoords[c - 32, 0] = ((float)(x + 0 - spacingPerChar)) / textureWidth; textureCoords[c - 32, 1] = ((float)(y + 0 + 0)) / textureHeight; textureCoords[c - 32, 2] = ((float)(x + size.Width + spacingPerChar)) / textureWidth; textureCoords[c - 32, 3] = ((float)(y + size.Height + 0)) / textureHeight; x += size.Width + (2 * spacingPerChar); } // Create a new texture for the font from the bitmap we just created fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed); RestoreDeviceObjects(null, null); }