Source

where-is-makkah / WhereIsMakkah / ViewModel / MainViewModel.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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
using System;
using System.Device.Location;
using System.Windows.Media.Media3D;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Threading;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using WhereIsMakkah.Util;
using WhereIsMakkah.Lang;

namespace WhereIsMakkah.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        private Matrix3D _offsetFromNorthMatrix = Matrix3D.Identity;

        /// <summary>
        /// The <see cref="LocationDetermined" /> property's name.
        /// </summary>
        private bool _locationDetermined = false;

        /// <summary>
        /// Gets the LocationDetermined property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public bool LocationDetermined
        {
            set
            {
                if (_locationDetermined == value)
                {
                    return;
                }

                var oldValue = _locationDetermined;
                _locationDetermined = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(DirectionDeterminedPropertyName);
                RaisePropertyChanged(BusyPropertyName);
                RaisePropertyChanged(FeedbackPropertyName);
            }
        }

        /// <summary>
        /// The <see cref="MotionDetermined" /> property's name.
        /// </summary>
        private bool _motionDetermined = false;

        /// <summary>
        /// Gets the MotionDetermined property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public bool MotionDetermined
        {
            set
            {
                if (_motionDetermined == value)
                {
                    return;
                }

                var oldValue = _motionDetermined;
                _motionDetermined = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(DirectionDeterminedPropertyName);
                RaisePropertyChanged(BusyPropertyName);
            }
        }

        /// <summary>
        /// The <see cref="DirectionDetermined" /> property's name.
        /// </summary>
        public const string DirectionDeterminedPropertyName = "DirectionDetermined";

        /// <summary>
        /// Gets the DirectionDetermined property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public bool DirectionDetermined
        {
            get
            {
                return _locationServiceSetting && _locationDetermined && _motionDetermined;
            }
        }

        /// <summary>
        /// The <see cref="Busy" /> property's name.
        /// </summary>
        public const string BusyPropertyName = "Busy";

        /// <summary>
        /// Gets the Busy property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public bool Busy
        {
            get
            {
                return _locationServiceSetting ? !(_locationDetermined && _motionDetermined) : false;
            }
        }

        /// <summary>
        /// The <see cref="CurrentMatrix" /> property's name.
        /// </summary>
        public const string CurrentMatrixPropertyName = "CurrentMatrix";

        private Matrix3D _currentMatrix = Matrix3D.Identity;

        /// <summary>
        /// Gets the CurrentMatrix property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public Matrix3D CurrentMatrix
        {
            get
            {
                return _currentMatrix;
            }

            set
            {
                if (_currentMatrix == value)
                {
                    return;
                }

                var oldValue = _currentMatrix;
                _currentMatrix = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(CurrentMatrixPropertyName);
            }
        }


        /// <summary>
        /// The <see cref="Feedback" /> property's name.
        /// </summary>
        public const string FeedbackPropertyName = "Feedback";

        private string _feedback = "";

        /// <summary>
        /// Gets the Feedback property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public string Feedback
        {
            get
            {
                if (_locationServiceSetting)
                {
                    if (_locationDetermined)
                    {
                        var unit = _metricSetting ? AppResources.MetricUnitLabel : AppResources.ImperialUnitLabel;

                        return string.Format(AppResources.DistanceLabel, Distance.ToString("0"), unit);
                    }
                    else
                    {
                        return _feedback;
                    }
                }
                else
                {
                    return AppResources.FeedbackNoAccessLabel;
                }
            }

            set
            {
                if (_feedback == value)
                {
                    return;
                }

                var oldValue = _feedback;
                _feedback = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(FeedbackPropertyName);
            }
        }

        private bool _metricSetting = true;

        /// <summary>
        /// Gets the MetricSetting property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public bool MetricSetting
        {
            set
            {
                if (_metricSetting == value)
                {
                    return;
                }

                var oldValue = _metricSetting;
                _metricSetting = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(FeedbackPropertyName);
            }
        }

        /// <summary>
        /// The <see cref="Distance" /> property's name.
        /// </summary>
        public const string DistancePropertyName = "Distance";

        private double _distance = -1.0;

        /// <summary>
        /// Gets the Distance property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public double Distance
        {
            get
            {
                if (_metricSetting)
                {
                    return _distance;
                }
                else
                {
                    return _distance * 0.621371192;
                }
            }

            set
            {
                if (_distance == value)
                {
                    return;
                }

                var oldValue = _distance;
                _distance = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(FeedbackPropertyName);
            }
        }

        /// <summary>
        /// The <see cref="LocationServiceSetting" /> property's name.
        /// </summary>
        public const string LocationServiceSettingPropertyName = "LocationServiceSetting";

        private bool _locationServiceSetting = true;

        /// <summary>
        /// Gets the LocationServiceSetting property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public bool LocationServiceSetting
        {
            set
            {
                if (_locationServiceSetting == value)
                {
                    return;
                }

                var oldValue = _locationServiceSetting;
                _locationServiceSetting = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(DirectionDeterminedPropertyName);
                RaisePropertyChanged(BusyPropertyName);
                RaisePropertyChanged(FeedbackPropertyName);
            }
        }

        public RelayCommand SensorStartCommand
        {
            get;
            private set;
        }

        public RelayCommand SensorStopCommand
        {
            get;
            private set;
        }

        public RelayCommand SettingsCommand
        {
            get;
            private set;
        }

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                // Code runs "for real"
                _metricSetting = App.AppSettings.MetricSetting;
                _locationServiceSetting = App.AppSettings.LocationServiceSetting;
            }

            SensorStartCommand = new RelayCommand(() => StartSensor());
            SensorStopCommand = new RelayCommand(() => StopSensor());
            SettingsCommand = new RelayCommand(() => GoToSettingsPage());

            Messenger.Default.Register<SettingsChangedMessage>(this, (msg) => ReceiveMessage(msg));
        }

        private static readonly GeoCoordinate Makkah = new GeoCoordinate(21.4166666666666667, 39.8166666666666667);
        private GeoCoordinateWatcher _watcher;
        private Motion _motion;

        private void StartSensor()
        {
            StartLocationSensor();
            StartMotionSensor();
        }

        private void StopSensor()
        {
            StopLocationSensor();
            StopMotionSensor();
        }

        private void StartLocationSensor()
        {
            if (!_locationServiceSetting)
            {
                return;
            }

            if (_watcher == null)
            {
                _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                _watcher.MovementThreshold = 20;
                _watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(_watcher_StatusChanged);
            }

            Feedback = AppResources.FeedbackStartingLabel;

            _watcher.Start();
        }

        private void _watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    if (_watcher.Permission == GeoPositionPermission.Denied)
                    {
                        Feedback = AppResources.FeedbackNoAccessLabel;
                    }
                    else
                    {
                        Feedback = AppResources.FeedbackNoFunctionLabel;
                    }

                    StopLocationSensor();
                    break;

                case GeoPositionStatus.Initializing:
                    // moving on.
                    break;

                case GeoPositionStatus.NoData:
                    Feedback = AppResources.FeedbackNotAvailableLabel;

                    StopLocationSensor();
                    break;

                case GeoPositionStatus.Ready:
                    GeoCoordinate loc = _watcher.Position.Location;

                    Distance = GeoDistanceCalculator.DistanceInKilometers(loc.Latitude, loc.Longitude, Makkah.Latitude, Makkah.Longitude);

                    var destZ = 360.0 - GeoDistanceCalculator.InitialBearing(loc.Latitude, loc.Longitude, Makkah.Latitude, Makkah.Longitude); // counter-clockwise
                    _offsetFromNorthMatrix = RotateZTransform(destZ);
                    LocationDetermined = true;

                    StopLocationSensor();
                    break;
            }
        }

        private void StopLocationSensor()
        {
            if (_watcher == null)
            {
                return;
            }

            _watcher.Stop();
        }

        private void StartMotionSensor()
        {
            // Check to see whether the Motion API is supported on the device.
            if (!Motion.IsSupported)
            {
                Feedback = AppResources.FeedbackMotionNotSupportedLabel;
                return;
            }

            // If the Motion object is null, initialize it and add a CurrentValueChanged
            // event handler.
            if (_motion == null)
            {
                _motion = new Motion();
                _motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
                _motion.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<MotionReading>>(_motion_CurrentValueChanged);
            }

            // Try to start the Motion API.
            try
            {
                _motion.Start();
            }
            catch (Exception)
            {
                Feedback = AppResources.FeedbackMotionUnableToStartLabel;
            }
        }

        private void _motion_CurrentValueChanged(object sender, SensorReadingEventArgs<MotionReading> e)
        {
            // This event arrives on a background thread. Use BeginInvoke to call
            // CurrentValueChanged on the UI thread.
            DispatcherHelper.CheckBeginInvokeOnUI(() => CurrentValueChanged(e.SensorReading));
        }

        private void CurrentValueChanged(MotionReading e)
        {
            const double arrowWidth = 450.0;
            const double arrowHeight = 550.0;
            const double layoutWidth = 450.0;
            const double layoutHeight = 550.0;

            // Translate the image along the negative Z-axis such that it occupies 50% of the
            // vertical field of view.
            double fovY = Math.PI / 2.0;
            double translationZ = -arrowHeight * 0.75;

            // You can create a 3D effect by creating a number of simple 
            // tranformation Matrix3D matrixes and then multiply them together.
            Matrix3D centerImageAtOrigin = TranslationTransform(
                     -arrowWidth / 2.0,
                     -arrowHeight / 2.0, 0);
            Matrix3D invertYAxis = CreateScaleTransform(1.0, -1.0, 1.0);
            Matrix3D translateAwayFromCamera = TranslationTransform(0, 0, translationZ);
            Matrix3D perspective = PerspectiveTransformFovRH(fovY,
                    layoutWidth / layoutHeight,                         // aspect ratio
                    1.0,                                                // near plane
                    1000.0);                                            // far plane
            Matrix3D viewport = ViewportTransform(layoutWidth, layoutHeight);

            Matrix3D m = centerImageAtOrigin * invertYAxis;
            m = m * _offsetFromNorthMatrix;
            m = m * XnaMatrixToMatrix3D(e.Attitude.RotationMatrix);
            m = m * translateAwayFromCamera;
            m = m * perspective;
            m = m * viewport;

            CurrentMatrix = m;
            MotionDetermined = true;
        }

        private Matrix3D XnaMatrixToMatrix3D(Matrix matrix)
        {
            Matrix3D m = new Matrix3D();

            m.M11 = matrix.M11; m.M12 = matrix.M12; m.M13 = matrix.M13; m.M14 = matrix.M14;
            m.M21 = matrix.M21; m.M22 = matrix.M22; m.M23 = matrix.M23; m.M24 = matrix.M24;
            m.M31 = matrix.M31; m.M32 = matrix.M32; m.M33 = matrix.M33; m.M34 = matrix.M34;
            m.OffsetX = matrix.M41; m.OffsetY = matrix.M42; m.OffsetZ = matrix.M43; m.M44 = matrix.M44;

            return m;
        }

        private Matrix3D CreateScaleTransform(double sx, double sy, double sz)
        {
            Matrix3D m = new Matrix3D();

            m.M11 = sx; m.M12 = 0.0; m.M13 = 0.0; m.M14 = 0.0;
            m.M21 = 0.0; m.M22 = sy; m.M23 = 0.0; m.M24 = 0.0;
            m.M31 = 0.0; m.M32 = 0.0; m.M33 = sz; m.M34 = 0.0;
            m.OffsetX = 0.0; m.OffsetY = 0.0; m.OffsetZ = 0.0; m.M44 = 1.0;

            return m;
        }

        private Matrix3D TranslationTransform(double tx, double ty, double tz)
        {
            Matrix3D m = new Matrix3D();
            m.M11 = 1.0; m.M12 = 0.0; m.M13 = 0.0; m.M14 = 0.0;
            m.M21 = 0.0; m.M22 = 1.0; m.M23 = 0.0; m.M24 = 0.0;
            m.M31 = 0.0; m.M32 = 0.0; m.M33 = 1.0; m.M34 = 0.0;
            m.OffsetX = tx; m.OffsetY = ty; m.OffsetZ = tz; m.M44 = 1.0;
            return m;
        }

        private Matrix3D RotateZTransform(double degree)
        {
            double theta = degree * Math.PI / 180.0;
            double cos = Math.Cos(theta);
            double sin = Math.Sin(theta);

            Matrix3D m = new Matrix3D();
            m.M11 = cos; m.M12 = sin; m.M13 = 0.0; m.M14 = 0.0;
            m.M21 = -sin; m.M22 = cos; m.M23 = 0.0; m.M24 = 0.0;
            m.M31 = 0.0; m.M32 = 0.0; m.M33 = 1.0; m.M34 = 0.0;
            m.OffsetX = 0.0; m.OffsetY = 0.0; m.OffsetZ = 0.0; m.M44 = 1.0;
            return m;
        }

        private Matrix3D PerspectiveTransformFovRH(double fieldOfViewY, double aspectRatio, double zNearPlane, double zFarPlane)
        {
            double height = 1.0 / Math.Tan(fieldOfViewY / 2.0);
            double width = height / aspectRatio;
            double d = zNearPlane - zFarPlane;

            Matrix3D m = new Matrix3D();
            m.M11 = width; m.M12 = 0; m.M13 = 0; m.M14 = 0;
            m.M21 = 0; m.M22 = height; m.M23 = 0; m.M24 = 0;
            m.M31 = 0; m.M32 = 0; m.M33 = zFarPlane / d; m.M34 = -1;
            m.OffsetX = 0; m.OffsetY = 0; m.OffsetZ = zNearPlane * zFarPlane / d; m.M44 = 0;

            return m;
        }

        private Matrix3D ViewportTransform(double width, double height)
        {
            Matrix3D m = new Matrix3D();

            m.M11 = width / 2.0; m.M12 = 0.0; m.M13 = 0.0; m.M14 = 0.0;
            m.M21 = 0.0; m.M22 = -height / 2.0; m.M23 = 0.0; m.M24 = 0.0;
            m.M31 = 0.0; m.M32 = 0.0; m.M33 = 1.0; m.M34 = 0.0;
            m.OffsetX = width / 2.0; m.OffsetY = height / 2.0; m.OffsetZ = 0.0; m.M44 = 1.0;

            return m;
        }

        private void StopMotionSensor()
        {
            if (_motion == null)
            {
                return;
            }

            _motion.Stop();
        }

        private void GoToSettingsPage()
        {
            var msg = new GoToPageMessage() { PageName = "SettingsPage" };
            Messenger.Default.Send<GoToPageMessage>(msg);
        }

        private void ReceiveMessage(SettingsChangedMessage msg)
        {
            var key = msg.Key;
            if (key.Equals("Unit"))
            {
                MetricSetting = App.AppSettings.MetricSetting;
            }
            if (key.Equals("LocationService"))
            {
                LocationServiceSetting = App.AppSettings.LocationServiceSetting;
            }
        }

        ////public override void Cleanup()
        ////{
        ////    // Clean up if needed

        ////    base.Cleanup();
        ////}
    }
}