-
Notifications
You must be signed in to change notification settings - Fork 0
/
XnaControl.cs
105 lines (88 loc) · 3.19 KB
/
XnaControl.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
public partial class XnaControl : UserControl
{
private GraphicsDeviceService graphicsService;
private XnaImageSource imageSource;
/// <summary>
/// Gets the GraphicsDevice behind the control.
/// </summary>
public GraphicsDevice GraphicsDevice
{
get { return graphicsService.GraphicsDevice; }
}
/// <summary>
/// Invoked when the XnaControl needs to be redrawn.
/// </summary>
public Action<GraphicsDevice> DrawFunction;
public XnaControl()
{
InitializeComponent();
// hook up an event to fire when the control has finished loading
Loaded += new RoutedEventHandler(XnaControl_Loaded);
}
~XnaControl()
{
imageSource.Dispose();
// release on finalizer to clean up the graphics device
if (graphicsService != null)
graphicsService.Release();
}
void XnaControl_Loaded(object sender, RoutedEventArgs e)
{
// if we're not in design mode, initialize the graphics device
if (DesignerProperties.GetIsInDesignMode(this) == false)
{
InitializeGraphicsDevice();
}
}
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
// if we're not in design mode, recreate the
// image source for the new size
if (DesignerProperties.GetIsInDesignMode(this) == false &&
graphicsService != null)
{
// recreate the image source
imageSource.Dispose();
imageSource = new XnaImageSource(
GraphicsDevice, (int)ActualWidth, (int)ActualHeight);
rootImage.Source = imageSource.WriteableBitmap;
}
base.OnRenderSizeChanged(sizeInfo);
}
private void InitializeGraphicsDevice()
{
if (graphicsService == null)
{
// add a reference to the graphics device
graphicsService = GraphicsDeviceService.AddRef(
(PresentationSource.FromVisual(this) as HwndSource).Handle);
// create the image source
imageSource = new XnaImageSource(
GraphicsDevice, (int)ActualWidth, (int)ActualHeight);
rootImage.Source = imageSource.WriteableBitmap;
// hook the rendering event
CompositionTarget.Rendering += CompositionTarget_Rendering;
}
}
/// <summary>
/// Draws the control and allows subclasses to override
/// the default behavior of delegating the rendering.
/// </summary>
protected virtual void Render()
{
// invoke the draw delegate so someone will draw something pretty
if (DrawFunction != null)
DrawFunction(GraphicsDevice);
}
void CompositionTarget_Rendering(object sender, EventArgs e)
{
// set the image source render target
GraphicsDevice.SetRenderTarget(imageSource.RenderTarget);
// allow the control to draw
Render();
// unset the render target
GraphicsDevice.SetRenderTarget(null);
// commit the changes to the image source
imageSource.Commit();
}
}