本文整理汇总了C#中Texture2D.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Texture2D.Dispose方法的具体用法?C# Texture2D.Dispose怎么用?C# Texture2D.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Texture2D
的用法示例。
在下文中一共展示了Texture2D.Dispose方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Make3D
private static Texture2D Make3D(Texture2D stereoTexture)
{
NvStereoImageHeader header = new NvStereoImageHeader(0x4433564e, 3840, 1080, 4, 0x00000002);
// stereoTexture contains a stereo image with the left eye image on the left half
// and the right eye image on the right half
// this staging texture will have an extra row to contain the stereo signature
Texture2DDescription stagingDesc = new Texture2DDescription()
{
ArraySize = 1,
Width = 2*size.Width,
Height = size.Height + 1,
BindFlags = BindFlags.None,
CpuAccessFlags = CpuAccessFlags.Write,
Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
OptionFlags = ResourceOptionFlags.None,
Usage = ResourceUsage.Staging,
MipLevels = 1,
SampleDescription = new SampleDescription(1, 0)
};
Texture2D staging = new Texture2D(device, stagingDesc);
// Identify the source texture region to copy (all of it)
ResourceRegion stereoSrcBox = new ResourceRegion
{Front = 0, Back = 1, Top = 0, Bottom = size.Height, Left = 0, Right = 2*size.Width};
// Copy it to the staging texture
device.CopySubresourceRegion(stereoTexture, 0, stereoSrcBox, staging, 0, 0, 0, 0);
// Open the staging texture for reading
DataRectangle box = staging.Map(0, MapMode.Write, SlimDX.Direct3D10.MapFlags.None);
// Go to the last row
//box.Data.Seek(stereoTexture.Description.Width*stereoTexture.Description.Height*4, System.IO.SeekOrigin.Begin);
box.Data.Seek(box.Pitch*1080, System.IO.SeekOrigin.Begin);
// Write the NVSTEREO header
box.Data.Write(data, 0, data.Length);
staging.Unmap(0);
// Create the final stereoized texture
Texture2DDescription finalDesc = new Texture2DDescription()
{
ArraySize = 1,
Width = 2 * size.Width,
Height = size.Height + 1,
BindFlags = BindFlags.ShaderResource,
CpuAccessFlags = CpuAccessFlags.Write,
Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
OptionFlags = ResourceOptionFlags.None,
Usage = ResourceUsage.Dynamic,
MipLevels = 1,
SampleDescription = new SampleDescription(1, 0)
};
// Copy the staging texture on a new texture to be used as a shader resource
Texture2D final = new Texture2D(device, finalDesc);
device.CopyResource(staging, final);
staging.Dispose();
return final;
}
示例2: PresentHook
//.........这里部分代码省略.........
// Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index
theTexture.Device.ImmediateContext.CopySubresourceRegion(theTexture, 0, new ResourceRegion()
{
Top = regionToCapture.Top,
Bottom = regionToCapture.Bottom,
Left = regionToCapture.Left,
Right = regionToCapture.Right,
Front = 0,
Back = 1 // Must be 1 or only black will be copied
}, textureDest, 0, 0, 0, 0);
// Note: it would be possible to capture multiple frames and process them in a background thread
// Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline
Guid requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread
ThreadPool.QueueUserWorkItem(delegate
{
//FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create);
//Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs);
DateTime startCopyToSystemMemory = DateTime.Now;
using (MemoryStream ms = new MemoryStream())
{
Texture2D.ToStream(textureDest.Device.ImmediateContext, textureDest, ImageFileFormat.Bmp, ms);
ms.Position = 0;
this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString());
DateTime startSendResponse = DateTime.Now;
SendResponse(ms, requestId);
this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString());
}
// Free the textureDest as we no longer need it.
textureDest.Dispose();
textureDest = null;
this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString());
});
// Prevent the request from being processed a second time
this.Request = null;
// Make sure we free up the resolved texture if it was created
if (textureResolved != null)
{
textureResolved.Dispose();
textureResolved = null;
}
}
this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString());
this.DebugMessage("PresentHook: Request End");
}
#endregion
#region TODO: Draw overlay (after screenshot so we don't capture overlay as well)
if (this.ShowOverlay)
{
// Note: Direct3D 11 doesn't have font support, so I believe the approach is to use
// a Direct3D 10.1 device with Direct2d, render to a texture, and then blend
// this into the Direct3D 11 backbuffer - hmm sounds like fun.
// http://forums.create.msdn.com/forums/t/38961.aspx
// http://www.gamedev.net/topic/547920-how-to-use-d2d-with-d3d11/
}
#endregion
}
catch (Exception e)
{
示例3: Main
//.........这里部分代码省略.........
// Load effect from file. It is a basic effect that renders a full screen quad through
// an ortho projectio=n matrix
effect = Effect.FromFile(device, "Texture.fx", "fx_4_0", ShaderFlags.Debug, EffectFlags.None);
EffectTechnique technique = effect.GetTechniqueByIndex(0);
EffectPass pass = technique.GetPassByIndex(0);
InputLayout layout = new InputLayout(device, pass.Description.Signature, new[]
{
new InputElement(
"POSITION", 0,
Format.
R32G32B32A32_Float,
0, 0),
new InputElement(
"TEXCOORD", 0,
Format.
R32G32_Float,
16, 0)
});
//effect.GetVariableByName("mWorld").AsMatrix().SetMatrix(
// Matrix.Translation(Layout.OrthographicTransform(Vector2.Zero, 99, size)));
//effect.GetVariableByName("mView").AsMatrix().SetMatrix(qCam.View);
//effect.GetVariableByName("mProjection").AsMatrix().SetMatrix(qCam.OrthoProjection);
//effect.GetVariableByName("tDiffuse").AsResource().SetResource(srv);
// Set RT and Viewports
device.OutputMerger.SetTargets(renderView);
device.Rasterizer.SetViewports(new Viewport(0, 0, size.Width, size.Height, 0.0f, 1.0f));
// Create solid rasterizer state
RasterizerStateDescription rDesc = new RasterizerStateDescription()
{
CullMode = CullMode.None,
IsDepthClipEnabled = true,
FillMode = FillMode.Solid,
IsAntialiasedLineEnabled = false,
IsFrontCounterclockwise = true,
//IsMultisampleEnabled = true,
};
RasterizerState rState = RasterizerState.FromDescription(device, rDesc);
device.Rasterizer.State = rState;
Texture2DDescription rtDesc = new Texture2DDescription
{
ArraySize = 1,
Width = size.Width,
Height = size.Height,
BindFlags = BindFlags.RenderTarget,
CpuAccessFlags = CpuAccessFlags.None,
Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
OptionFlags = ResourceOptionFlags.None,
Usage = ResourceUsage.Default,
MipLevels = 1,
SampleDescription = new SampleDescription(1, 0)
};
rtTex = new Texture2D(device, rtDesc);
rv = new RenderTargetView(device, rtTex);
stereoizedTexture = Make3D(sourceTexture);
//ResizeDevice(new Size(1920, 1080), true);
Console.WriteLine(form.ClientSize);
// Main Loop
MessagePump.Run(form, () =>
{
device.ClearRenderTargetView(renderView, Color.Cyan);
//device.InputAssembler.SetInputLayout(layout);
//device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
//device.OutputMerger.SetTargets(rv);
//device.InputAssembler.SetVertexBuffers(0,
// new VertexBufferBinding(vertices, 24, 0));
//device.InputAssembler.SetIndexBuffer(indices, Format.R16_UInt, 0);
//for (int i = 0; i < technique.Description.PassCount; ++i)
//{
// // Render the full screen quad
// pass.Apply();
// device.DrawIndexed(6, 0, 0);
//}
ResourceRegion stereoSrcBox = new ResourceRegion { Front = 0, Back = 1, Top = 0, Bottom = size.Height, Left = 0, Right = size.Width };
device.CopySubresourceRegion(stereoizedTexture, 0, stereoSrcBox, backBuffer, 0, 0, 0, 0);
//device.CopyResource(rv.Resource, backBuffer);
swapChain.Present(0, PresentFlags.None);
});
// Dispose resources
vertices.Dispose();
layout.Dispose();
effect.Dispose();
renderView.Dispose();
backBuffer.Dispose();
device.Dispose();
swapChain.Dispose();
rState.Dispose();
stereoizedTexture.Dispose();
sourceTexture.Dispose();
indices.Dispose();
srv.Dispose();
}
示例4: PresentHook
//.........这里部分代码省略.........
// Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index
theTexture.Device.CopySubresourceRegion(theTexture, 0, new ResourceRegion()
{
Top = regionToCapture.Top,
Bottom = regionToCapture.Bottom,
Left = regionToCapture.Left,
Right = regionToCapture.Right,
Front = 0,
Back = 1 // Must be 1 or only black will be copied
}, textureDest, 0, 0, 0, 0);
// Note: it would be possible to capture multiple frames and process them in a background thread
// Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline
Guid requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread
ThreadPool.QueueUserWorkItem(delegate
{
//FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create);
//Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs);
DateTime startCopyToSystemMemory = DateTime.Now;
using (MemoryStream ms = new MemoryStream())
{
Texture2D.ToStream(textureDest, ImageFileFormat.Bmp, ms);
ms.Position = 0;
this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString());
DateTime startSendResponse = DateTime.Now;
SendResponse(ms, requestId);
this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString());
}
// Free the textureDest as we no longer need it.
textureDest.Dispose();
textureDest = null;
this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString());
});
// Make sure we free up the resolved texture if it was created
if (textureResolved != null)
{
textureResolved.Dispose();
textureResolved = null;
}
}
this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString());
this.DebugMessage("PresentHook: Request End");
}
finally
{
// Prevent the request from being processed a second time
this.Request = null;
}
}
#endregion
#region Example: Draw overlay (after screenshot so we don't capture overlay as well)
if (this.ShowOverlay)
{
using (Texture2D texture = Texture2D.FromSwapChain<SlimDX.Direct3D10.Texture2D>(swapChain, 0))
{
if (_lastFrame != null)
{
FontDescription fd = new SlimDX.Direct3D10.FontDescription()
{
Height = 16,
FaceName = "Times New Roman",
IsItalic = false,
Width = 0,
MipLevels = 1,
CharacterSet = SlimDX.Direct3D10.FontCharacterSet.Default,
Precision = SlimDX.Direct3D10.FontPrecision.Default,
Quality = SlimDX.Direct3D10.FontQuality.Antialiased,
PitchAndFamily = FontPitchAndFamily.Default | FontPitchAndFamily.DontCare
};
using (Font font = new Font(texture.Device, fd))
{
DrawText(font, new Vector2(100, 100), String.Format("{0}", DateTime.Now), new Color4(System.Drawing.Color.Red.R, System.Drawing.Color.Red.G, System.Drawing.Color.Red.B, System.Drawing.Color.Red.A));
}
}
_lastFrame = DateTime.Now;
}
}
#endregion
}
catch (Exception e)
{
// If there is an error we do not want to crash the hooked application, so swallow the exception
this.DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.Message);
}
// As always we need to call the original method, note that EasyHook has already repatched the original method
// so calling it here will not cause an endless recursion to this function
return swapChain.Present(syncInterval, flags).Code;
}
}
示例5: CreateTexArray
public ShaderResourceView CreateTexArray(string arrayName, params string[] filenames)
{
if (_textures.ContainsKey(arrayName))
return _textures[arrayName];
//
// Load the texture elements individually from file. These textures
// won't be used by the GPU (0 bind flags), they are just used to
// load the image data from file. We use the STAGING usage so the
// CPU can read the resource.
//
int arraySize = filenames.Length;
var srcTex = new Texture2D[arraySize];
for(int i = 0; i < arraySize; ++i)
{
var loadInfo = new ImageLoadInformation
{
Usage = ResourceUsage.Staging,
BindFlags = BindFlags.None,
CpuAccessFlags = CpuAccessFlags.Read | CpuAccessFlags.Write,
OptionFlags = ResourceOptionFlags.None,
Format = Format.R8G8B8A8_UNorm,
FilterFlags = FilterFlags.None,
MipFilterFlags = FilterFlags.None
};
srcTex[i] = Texture2D.FromFile(_dxDevice, filenames[i], loadInfo);
}
//
// Create the texture array. Each element in the texture
// array has the same format/dimensions.
//
var texElementDesc = srcTex[0].Description;
var texArrayDesc = new Texture2DDescription
{
Width = texElementDesc.Width,
Height = texElementDesc.Height,
MipLevels = texElementDesc.MipLevels,
ArraySize = arraySize,
Format = Format.R8G8B8A8_UNorm,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.ShaderResource,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None
};
var texArray = new Texture2D(_dxDevice, texArrayDesc);
//
// Copy individual texture elements into texture array.
//
// for each texture element...
for (int i = 0; i < arraySize; ++i)
{
// for each mipmap level...
for (int j = 0; j < texElementDesc.MipLevels; ++j)
{
var mappedTex2D = srcTex[i].Map(j, MapMode.Read, MapFlags.None);
_dxDevice.UpdateSubresource(
new DataBox(mappedTex2D.Pitch, 0, mappedTex2D.Data), texArray,
Resource.CalculateSubresourceIndex(j, i, texElementDesc.MipLevels));
srcTex[i].Unmap(j);
}
}
//
// Create a resource view to the texture array.
//
var viewDesc = new ShaderResourceViewDescription();
viewDesc.Format = texArrayDesc.Format;
viewDesc.Dimension = ShaderResourceViewDimension.Texture2DArray;
viewDesc.MostDetailedMip = 0;
viewDesc.MipLevels = texArrayDesc.MipLevels;
viewDesc.FirstArraySlice = 0;
viewDesc.ArraySize = arraySize;
var texArrayRV = new ShaderResourceView(_dxDevice, texArray, viewDesc);
//
// Cleanup--we only need the resource view.
//
texArray.Dispose();
for(int i = 0; i < arraySize; ++i)
srcTex[i].Dispose();
_textures.Add(arrayName, texArrayRV);
return texArrayRV;
}
示例6: CreateRenderTargets
private void CreateRenderTargets(int width, int height)
{
var backBuffer = Resource.FromSwapChain<Texture2D>(SwapChain, 0);
RenderTargetView = new RenderTargetView(Device, backBuffer);
var depthDescription = new Texture2DDescription {
ArraySize = 1,
BindFlags = BindFlags.DepthStencil,
CpuAccessFlags = CpuAccessFlags.None,
Format = Format.D32_Float,
Height = backBuffer.Description.Height,
Width = backBuffer.Description.Width,
MipLevels = 1,
OptionFlags = ResourceOptionFlags.None,
SampleDescription = new SampleDescription(4, 4),
Usage = ResourceUsage.Default
};
var depthBuffer = new Texture2D(Device, depthDescription);
var depthStencilViewDescription = new DepthStencilViewDescription {
Format = depthDescription.Format,
Flags = DepthStencilViewFlags.None,
Dimension = depthDescription.SampleDescription.Count > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D,
MipSlice = 0
};
DepthStencilView = new DepthStencilView(Device, depthBuffer, depthStencilViewDescription);
Device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, width, height, 0f, 1f));
backBuffer.Dispose();
depthBuffer.Dispose();
}
示例7: PresentHook
//.........这里部分代码省略.........
// Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index
theTexture.Device.ImmediateContext.CopySubresourceRegion(theTexture, 0, new ResourceRegion()
{
Top = regionToCapture.Top,
Bottom = regionToCapture.Bottom,
Left = regionToCapture.Left,
Right = regionToCapture.Right,
Front = 0,
Back = 1 // Must be 1 or only black will be copied
}, textureDest, 0, 0, 0, 0);
// Note: it would be possible to capture multiple frames and process them in a background thread
// Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline
Guid requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread
ThreadPool.QueueUserWorkItem(delegate
{
//FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create);
//Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs);
DateTime startCopyToSystemMemory = DateTime.Now;
using (MemoryStream ms = new MemoryStream())
{
Texture2D.ToStream(textureDest.Device.ImmediateContext, textureDest, ImageFileFormat.Bmp, ms);
ms.Position = 0;
this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString());
DateTime startSendResponse = DateTime.Now;
SendResponse(ms, requestId);
this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString());
}
// Free the textureDest as we no longer need it.
textureDest.Dispose();
textureDest = null;
this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString());
});
// Prevent the request from being processed a second time
this.Request = null;
// Make sure we free up the resolved texture if it was created
if (textureResolved != null)
{
textureResolved.Dispose();
textureResolved = null;
}
}
this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString());
this.DebugMessage("PresentHook: Request End");
}
#endregion
#region overlay
if (idxhookUpdateimg != null)
{
imag = Image.FromStream(new MemoryStream(idxhookUpdateimg));
if (imag.Height == 1) { imag = null; }
idxhookUpdateimg = null;
this.DebugMessage("HOOKED");
this.DebugMessage("HWND: " + _swapChain.Description.OutputHandle.ToString());
if (imag != null)
{
using (MemoryStream stream = new MemoryStream())
{
示例8: Main
//.........这里部分代码省略.........
device.Factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);
Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
var renderView = new RenderTargetView(device, backBuffer);
var bytecode = ShaderBytecode.CompileFromFile("Render.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
var effect = new Effect(device, bytecode);
var technique = effect.GetTechniqueByIndex(0);
var pass = technique.GetPassByIndex(0);
String errors;
var computeByteCode = ShaderBytecode.CompileFromFile("compute.fx", "CS", "cs_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);
var compute = new ComputeShader(device, computeByteCode);
// shader variable handles
var conwayResourceH = effect.GetVariableByName("tex").AsResource();
var resolutionInvH = effect.GetVariableByName("resolutionInv").AsVector();
resolutionInvH.Set(new Vector2(1.0f / form.ClientSize.Width, 1.0f / form.ClientSize.Height));
EffectVectorVariable lightPosSSH = effect.GetVariableByName("lightPosSS").AsVector();
// create texture, fill it with random data
Texture2DDescription textureDesc = new Texture2DDescription()
{
Width = form.ClientSize.Width,
Height = form.ClientSize.Height,
MipLevels = 1,
ArraySize = 1,
CpuAccessFlags = CpuAccessFlags.None,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
OptionFlags = ResourceOptionFlags.None,
BindFlags = BindFlags.UnorderedAccess | BindFlags.ShaderResource,
Format = Format.R32_Float
};
var random = new Random();
var data = new float[form.ClientSize.Width * form.ClientSize.Height];
for (int i = 0; i < form.ClientSize.Width; ++i)
{
for (int j = 0; j < form.ClientSize.Height; ++j)
data[i * form.ClientSize.Height + j] = (float)random.Next(2);
}
DataStream ds = new DataStream(data, true, false);
DataRectangle dataRect = new DataRectangle(4 * form.ClientSize.Width, ds);
Texture2D conwayTex = new Texture2D(device, textureDesc, dataRect);
// Create SRV and UAV over the same texture
UnorderedAccessView conwayUAV = new UnorderedAccessView(device, conwayTex);
ShaderResourceView conwaySRV = new ShaderResourceView(device, conwayTex);
// On the more typical setup where you switch shaders,
// you will have to set the texture after every
conwayResourceH.SetResource(conwaySRV);
device.ImmediateContext.OutputMerger.SetTargets(renderView);
device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
Vector2 lightPosSS;
float angle = 0;
MessagePump.Run(form, () =>
{
// this does the light rotation
angle += 0.002f;
lightPosSS = new Vector2((float)Math.Sin(angle) * 0.5f + 0.5f, (float)Math.Cos(angle) * 0.5f + 0.5f);
lightPosSSH.Set(lightPosSS);
device.ImmediateContext.ComputeShader.Set(compute);
device.ImmediateContext.ComputeShader.SetUnorderedAccessView(conwayUAV, 0);
device.ImmediateContext.Dispatch(form.ClientSize.Width / 16 + 1, form.ClientSize.Height / 16 + 1, 1);
// After running the CS you have to unset UAV from the shader, so you can use it as SRV
device.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, 0);
device.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);
for (int i = 0; i < technique.Description.PassCount; ++i)
{
pass.Apply(device.ImmediateContext);
// No vertices are send as they are created in the vertex shader on the fly.
device.ImmediateContext.Draw(4, 0);
}
swapChain.Present(0, PresentFlags.None);
});
computeByteCode.Dispose();
conwayUAV.Dispose();
conwaySRV.Dispose();
conwayTex.Dispose();
ds.Dispose();
bytecode.Dispose();
effect.Dispose();
renderView.Dispose();
backBuffer.Dispose();
device.Dispose();
swapChain.Dispose();
}
示例9: SampleSprite
/// Construct from text
public SampleSprite(string text, uint argb, Font font, int positionX, int positionY)
{
int width = font.GetTextWidth(text, 0, text.Length);
int height = font.Metrics.Height;
// clamp to max size
width = Math.Min( width, 2048 );
var image = new Image(ImageMode.Rgba,
new ImageSize(width, height),
new ImageColor(0, 0, 0, 0) );
image.DrawText(text,
new ImageColor((int)((argb >> 16) & 0xff),
(int)((argb >> 8) & 0xff),
(int)((argb >> 0) & 0xff),
(int)((argb >> 24) & 0xff)),
font, new ImagePosition(0, 0));
var texture = new Texture2D(width, height, false, PixelFormat.Rgba);
texture.SetPixels(0, image.ToBuffer(), 0, 0, width, height);
image.Dispose();
SetTexture(texture);
texture.Dispose();
PositionX = positionX;
PositionY = positionY;
CenterX = texture.Width / 2;
CenterY = texture.Height / 2;
Degree = 0.0f;
ScaleX = 1.0f;
ScaleY = 1.0f;
SetLifeTimer();
}
示例10: ComputeBRDFIntegral
unsafe void ComputeBRDFIntegral( System.IO.FileInfo _TableFileName, uint _TableSize ) {
// ComputeShader CS = new ComputeShader( m_Device, new System.IO.FileInfo( "Shaders/ComputeBRDFIntegral.hlsl" ), "CS", new ShaderMacro[0] );
ComputeShader CS = new ComputeShader( m_Device, new System.IO.FileInfo( "Shaders/ComputeBRDFIntegral.hlsl" ), "CS", new ShaderMacro[] { new ShaderMacro( "IMPORTANCE_SAMPLING", "1" ) } );
Texture2D TexTable = new Texture2D( m_Device, _TableSize, _TableSize, 1, 1, PIXEL_FORMAT.RG32_FLOAT, false, true, null );
TexTable.SetCSUAV( 0 );
CS.Use();
CS.Dispatch( _TableSize >> 4, _TableSize >> 4, 1 );
CS.Dispose();
string DDSFileName = System.IO.Path.GetFileNameWithoutExtension( _TableFileName.FullName ) + ".dds";
// DirectXTexManaged.TextureCreator.CreateDDS( DDSFileName, TexTable );
throw new Exception( "Deprecated!" );
Texture2D TexTableStaging = new Texture2D( m_Device, _TableSize, _TableSize, 1, 1, PIXEL_FORMAT.RG32_FLOAT, true, false, null );
TexTableStaging.CopyFrom( TexTable );
TexTable.Dispose();
// Write tables
float2 Temp = new float2();
float F0_analytical;
float ambient_analytical;
float maxAbsoluteError_F0 = 0.0f;
float maxRelativeError_F0 = 0.0f;
float avgAbsoluteError_F0 = 0.0f;
float avgRelativeError_F0 = 0.0f;
float maxAbsoluteError_ambient = 0.0f;
float maxRelativeError_ambient = 0.0f;
float avgAbsoluteError_ambient = 0.0f;
float avgRelativeError_ambient = 0.0f;
float2[] Integral_SpecularReflectance = new float2[_TableSize];
PixelsBuffer Buff = TexTableStaging.Map( 0, 0 );
using ( System.IO.BinaryReader R = Buff.OpenStreamRead() )
using ( System.IO.FileStream S = _TableFileName.Create() )
using ( System.IO.BinaryWriter W = new System.IO.BinaryWriter( S ) )
for ( int Y=0; Y < _TableSize; Y++ ) {
float2 SumSpecularlyReflected = float2.Zero;
for ( int X=0; X < _TableSize; X++ ) {
Temp.x = R.ReadSingle();
Temp.y = R.ReadSingle();
W.Write( Temp.x );
W.Write( Temp.y );
SumSpecularlyReflected.x += Temp.x;
SumSpecularlyReflected.y += Temp.y;
// Check analytical solution
float NdotV = (float) X / (_TableSize-1);
float roughness = (float) Y / (_TableSize-1);
AnalyticalBRDFIntegral_Order3( NdotV, roughness, out F0_analytical, out ambient_analytical );
// AnalyticalBRDFIntegral_Order2( NdotV, roughness, out F0_analytical, out ambient_analytical );
float absoluteError_F0 = Math.Abs( F0_analytical - Temp.x );
float relativeError_F0 = F0_analytical > 1e-6f ? Temp.x / F0_analytical : 0.0f;
maxAbsoluteError_F0 = Math.Max( maxAbsoluteError_F0, absoluteError_F0 );
maxRelativeError_F0 = Math.Max( maxRelativeError_F0, relativeError_F0 );
avgAbsoluteError_F0 += absoluteError_F0;
avgRelativeError_F0 += relativeError_F0;
float absoluteError_ambient = Math.Abs( ambient_analytical - Temp.y );
float relativeError_ambient = ambient_analytical > 1e-6f ? Temp.x / ambient_analytical : 0.0f;
maxAbsoluteError_ambient = Math.Max( maxAbsoluteError_ambient, absoluteError_ambient );
maxRelativeError_ambient = Math.Max( maxRelativeError_ambient, relativeError_ambient );
avgAbsoluteError_ambient += absoluteError_ambient;
avgRelativeError_ambient += relativeError_ambient;
}
// Normalize and store "not specularly reflected" light
SumSpecularlyReflected = SumSpecularlyReflected / _TableSize;
float sum_dielectric = 1.0f - (0.04f * SumSpecularlyReflected.x + SumSpecularlyReflected.y);
float sum_metallic = 1.0f - (SumSpecularlyReflected.x + SumSpecularlyReflected.y);
Integral_SpecularReflectance[Y] = SumSpecularlyReflected;
}
TexTableStaging.UnMap( 0, 0 );
avgAbsoluteError_F0 /= _TableSize*_TableSize;
avgRelativeError_F0 /= _TableSize*_TableSize;
avgAbsoluteError_ambient /= _TableSize*_TableSize;
avgRelativeError_ambient /= _TableSize*_TableSize;
string TotalSpecularReflectionTableFileName = System.IO.Path.GetFileNameWithoutExtension( _TableFileName.FullName ) + ".table";
using ( System.IO.FileStream S = new System.IO.FileInfo( TotalSpecularReflectionTableFileName ).Create() )
using ( System.IO.BinaryWriter W = new System.IO.BinaryWriter( S ) )
for ( int i=0; i < _TableSize; i++ ) {
W.Write( Integral_SpecularReflectance[i].x );
W.Write( Integral_SpecularReflectance[i].y );
}
}