-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
402 lines (330 loc) · 14.4 KB
/
MainWindow.xaml.cs
File metadata and controls
402 lines (330 loc) · 14.4 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Research.Kinect.Nui;
// Some of this code is taken from the MS Research SDK Example project
// ShapeGame. This is included in the Kinect SDK download.
// It also uses NAudio - an open source C# Audio Player which can be found at http://naudio.codeplex.com
// The piano samples are taken from http://audio.ibeat.org/?ccm=/media/files/DaDeMo/469
// Since the timer resolution defaults to about 10ms precisely, we need to
// increase the resolution to get framerates above between 50fps with any
// consistency.
using System.Runtime.InteropServices;
using Vector = Microsoft.Research.Kinect.Nui.Vector;
public class Win32
{
[DllImport("Winmm.dll")]
public static extern int timeBeginPeriod(UInt32 uPeriod);
}
namespace KinectWpfSynth
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region variables
const int TimerResolution = 2; // ms
const double MinFramerate = 15;
SpeechRecogniser recognizer = null;
private IKinectSynth kinectSynth = new PianoSynth();
//private IKinectSynth kinectSynth = new SanfordSynth();
private IKeyboard keyboard = new CircleKeyboard();
//private IKeyboard keyboard = new RectangleKeyboard();
private List<Color> rainbow = new List<Color> { Colors.DarkRed, Colors.Red, Colors.Orange, Colors.Yellow, Colors.Green, Colors.Blue, Colors.BlueViolet, Colors.Indigo };
private DateTime keyLastPressed = DateTime.Now;
public Dictionary<int, Player> players = new Dictionary<int, Player>();
// Player(s) placement in scene (z collapsed):
Rect playerBounds;
Rect screenRect;
double targetFramerate = 50;
int frameCount = 0;
bool runningGameThread = false;
bool nuiInitialized = false;
int playersAlive = 0;
Runtime nui = new Runtime();
DateTime lastFrameDrawn = DateTime.MinValue;
DateTime predNextFrame = DateTime.MinValue;
double actualFrameTime = 0;
#endregion
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, EventArgs e)
{
playfield.ClipToBounds = true;
UpdatePlayfieldSize();
if ((nui != null) && InitializeNui())
{
nui.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_ColorFrameReady);
nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(nui_SkeletonFrameReady);
InitialiseSpeechRecognition();
}
StartThread();
}
private void StartThread()
{
Win32.timeBeginPeriod(TimerResolution);
var gameThread = new Thread(GameThread);
gameThread.SetApartmentState(ApartmentState.STA);
gameThread.Start();
}
private void InitialiseSpeechRecognition()
{
try
{
recognizer = new SpeechRecogniser();
}
catch
{
recognizer = null;
}
if ((recognizer == null) || !recognizer.IsValid())
{
BannerText.NewBanner("No speech recognition", screenRect, false, Color.FromArgb(90, 255, 255, 255));
recognizer = null;
}
else
{
recognizer.SaidSomething += recognizer_SaidSomething;
banner.Content = "Piano";
}
}
void nui_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
//TODO Pick this apart a bit
SkeletonFrame skeletonFrame = e.SkeletonFrame;
int iSkeletonSlot = 0;
foreach (SkeletonData data in skeletonFrame.Skeletons)
{
if (SkeletonTrackingState.Tracked == data.TrackingState)
{
Player player;
if (players.ContainsKey(iSkeletonSlot))
{
player = players[iSkeletonSlot];
}
else
{
player = new Player(iSkeletonSlot);
player.setBounds(playerBounds);
players.Add(iSkeletonSlot, player);
}
player.lastUpdated = DateTime.Now;
// Update player's bone and joint positions
if (data.Joints.Count > 0)
{
player.isAlive = true;
// Head, hands, feet (hit testing happens in order here)
// We are only interested in Hands, but left everything else in for now in case
//player.UpdateJointPosition(data.Joints, JointID.Head);
player.UpdateJointPosition(data.Joints, JointID.HandLeft);
player.UpdateJointPosition(data.Joints, JointID.HandRight);
//player.UpdateJointPosition(data.Joints, JointID.FootLeft);
//player.UpdateJointPosition(data.Joints, JointID.FootRight);
// Hands and arms
//player.UpdateBonePosition(data.Joints, JointID.HandRight, JointID.WristRight);
//player.UpdateBonePosition(data.Joints, JointID.WristRight, JointID.ElbowRight);
//player.UpdateBonePosition(data.Joints, JointID.ElbowRight, JointID.ShoulderRight);
//player.UpdateBonePosition(data.Joints, JointID.HandLeft, JointID.WristLeft);
//player.UpdateBonePosition(data.Joints, JointID.WristLeft, JointID.ElbowLeft);
//player.UpdateBonePosition(data.Joints, JointID.ElbowLeft, JointID.ShoulderLeft);
//// Head and Shoulders
//player.UpdateBonePosition(data.Joints, JointID.ShoulderCenter, JointID.Head);
//player.UpdateBonePosition(data.Joints, JointID.ShoulderLeft, JointID.ShoulderCenter);
//player.UpdateBonePosition(data.Joints, JointID.ShoulderCenter, JointID.ShoulderRight);
//// Legs
//player.UpdateBonePosition(data.Joints, JointID.HipLeft, JointID.KneeLeft);
//player.UpdateBonePosition(data.Joints, JointID.KneeLeft, JointID.AnkleLeft);
//player.UpdateBonePosition(data.Joints, JointID.AnkleLeft, JointID.FootLeft);
//player.UpdateBonePosition(data.Joints, JointID.HipRight, JointID.KneeRight);
//player.UpdateBonePosition(data.Joints, JointID.KneeRight, JointID.AnkleRight);
//player.UpdateBonePosition(data.Joints, JointID.AnkleRight, JointID.FootRight);
//player.UpdateBonePosition(data.Joints, JointID.HipLeft, JointID.HipCenter);
//player.UpdateBonePosition(data.Joints, JointID.HipCenter, JointID.HipRight);
//// Spine
//player.UpdateBonePosition(data.Joints, JointID.HipCenter, JointID.ShoulderCenter);
PlayMusic();
}
}
iSkeletonSlot++;
}
}
void CheckPlayers()
{
foreach (var player in players.Where(player => !player.Value.isAlive))
{
// Player left scene since we aren't tracking it anymore, so remove from dictionary
players.Remove(player.Value.getId());
break;
}
// Count alive players
int alive = 0;
foreach (var player in players)
{
if (player.Value.isAlive)
alive++;
}
playersAlive = alive;
}
void nui_ColorFrameReady(object sender, ImageFrameReadyEventArgs e)
{
// 32-bit per pixel, RGBA image
PlanarImage Image = e.ImageFrame.Image;
video.Source = BitmapSource.Create(
Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
}
private bool InitializeNui()
{
UninitializeNui();
if (nui == null)
return false;
try
{
nui.Initialize(RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor);
}
catch (Exception _Exception)
{
Console.WriteLine(_Exception.ToString());
return false;
}
nui.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex);
nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
nui.SkeletonEngine.TransformSmooth = true;
nuiInitialized = true;
return true;
}
private void UninitializeNui()
{
if ((nui != null) && (nuiInitialized))
nui.Uninitialize();
nuiInitialized = false;
}
private void Playfield_SizeChanged(object sender, SizeChangedEventArgs e)
{
UpdatePlayfieldSize();
}
private void UpdatePlayfieldSize()
{
// Size of player wrt size of playfield, putting ourselves low on the screen.
screenRect.X = 0;
screenRect.Y = 0;
screenRect.Width = playfield.ActualWidth;
screenRect.Height = playfield.ActualHeight;
BannerText.UpdateBounds(screenRect);
playerBounds.X = 0;
playerBounds.Width = playfield.ActualWidth;
playerBounds.Y = playfield.ActualHeight * 0.2;
playerBounds.Height = playfield.ActualHeight;
foreach (var player in players)
player.Value.setBounds(playerBounds);
}
void recognizer_SaidSomething(object sender, SpeechRecogniser.SaidSomethingArgs e)
{
//CHeck to see if 2 seconds have passed since last note played
//If so, ok to make change. THis is to try and mitigate issue
//where playing notes cause recogniser to switch instrument
//but is not a satisfactory solution
//Looking to improve the grammar for selection
if(keyLastPressed.AddMilliseconds(2000) < DateTime.Now)
{
switch (e.Instruments)
{
case SpeechRecogniser.Instruments.Piano:
//kinectSynth = new PianoSynth();
break;
case SpeechRecogniser.Instruments.Organ:
//kinectSynth = new SanfordSynth();
break;
}
resetKeys();
}
banner.Content = e.Matched;
}
private void resetKeys()
{
foreach (var key in keyboard.Keys)
{
key.IsPlaying = false;
key.IsPressed = false;
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
runningGameThread = false;
Properties.Settings.Default.Save();
}
private void Window_Closed(object sender, EventArgs e)
{
if (recognizer != null)
recognizer.Stop();
UninitializeNui();
Environment.Exit(0);
}
private void GameThread()
{
runningGameThread = true;
predNextFrame = DateTime.Now;
actualFrameTime = 1000.0 / targetFramerate;
// Try to dispatch at as constant of a framerate as possible by sleeping just enough since
// the last time we dispatched.
while (runningGameThread)
{
// Calculate average framerate.
DateTime now = DateTime.Now;
if (lastFrameDrawn == DateTime.MinValue)
lastFrameDrawn = now;
double ms = now.Subtract(lastFrameDrawn).TotalMilliseconds;
actualFrameTime = actualFrameTime * 0.95 + 0.05 * ms;
lastFrameDrawn = now;
// Adjust target framerate down if we're not achieving that rate
frameCount++;
if (((frameCount % 100) == 0) && (1000.0 / actualFrameTime < targetFramerate * 0.92))
targetFramerate = Math.Max(MinFramerate, (targetFramerate + 1000.0 / actualFrameTime) / 2);
if (now > predNextFrame)
predNextFrame = now;
else
{
double msSleep = predNextFrame.Subtract(now).TotalMilliseconds;
if (msSleep >= TimerResolution)
Thread.Sleep((int)(msSleep + 0.5));
}
predNextFrame += TimeSpan.FromMilliseconds(1000.0 / targetFramerate);
Dispatcher.Invoke(DispatcherPriority.Send,
new Action<int>(HandleGameTimer), 0);
}
}
private void HandleGameTimer(int param)
{
// Draw new Wpf scene by adding all objects to canvas
playfield.Children.Clear();
if(keyboard.Keys.Count == 0) keyboard.InitKeyboard(rainbow);
keyboard.UpdateKeys(playfield);
foreach (var player in players)
player.Value.Draw(playfield.Children);
CheckPlayers();
}
private void PlayMusic()
{
foreach (var player in players)
{
keyboard.CheckKeyPress(player.Value.segments, kinectSynth);
}
}
}
}