Imports System
Imports System.Windows
Imports System.Windows.Media
Imports Microsoft.Kinect
Imports Hologram.ImageManipulationExtensionMethods

''' <summary>
''' Interaction logic for MainWindow.xaml
''' </summary>
''' <remarks></remarks>
Class MainWindow
    Private _kinectSensor As KinectSensor

    Public Sub New()

        ' この呼び出しはデザイナーで必要です。
        InitializeComponent()

        ' InitializeComponent() 呼び出しの後で初期化を追加します。
        AddHandler Me.Unloaded, Sub()
                                    _kinectSensor.DepthStream.Disable()
                                    _kinectSensor.SkeletonStream.Disable()
                                End Sub

        AddHandler Me.Loaded, Sub()
                                  _kinectSensor = KinectSensor.KinectSensors(0)
                                  AddHandler _kinectSensor.SkeletonFrameReady, AddressOf SkeletonFrameReady
                                  AddHandler _kinectSensor.DepthFrameReady, AddressOf DepthFrameReady
                                  _kinectSensor.SkeletonStream.Enable()
                                  _kinectSensor.DepthStream.Enable()
                                  _kinectSensor.Start()
                              End Sub

    End Sub

    Sub DepthFrameReady(sender As Object, e As DepthImageFrameReadyEventArgs)
        Using imageData As DepthImageFrame = e.OpenDepthImageFrame()
            If (imageData Is Nothing OrElse imageData.PixelDataLength = 0) Then
                Exit Sub
            End If

            Me.image1.Source = imageData.ToBitmapSource()
        End Using
    End Sub

    Sub SkeletonFrameReady(sender As Object, e As SkeletonFrameReadyEventArgs)
        Dim x As Single = 0, y As Single = 0, z As Single = 0
        'get angle of skeleton
        Using frame As SkeletonFrame = e.OpenSkeletonFrame()
            If (frame Is Nothing OrElse frame.SkeletonArrayLength = 0) Then
                Exit Sub
            End If

            Dim skeletons(frame.SkeletonArrayLength - 1) As Skeleton
            frame.CopySkeletonDataTo(skeletons)
            For s As Integer = 0 To skeletons.Length - 1
                If (skeletons(s).TrackingState = SkeletonTrackingState.Tracked) Then
                    border.BorderBrush = New SolidColorBrush(Colors.Red)
                    Dim _skeleton As Skeleton = skeletons(s)
                    x = _skeleton.Position.X * 60
                    z = _skeleton.Position.Z * 120
                    y = _skeleton.Position.Y
                    Exit For
                Else
                    border.BorderBrush = New SolidColorBrush(Colors.Black)
                End If
            Next
        End Using
        If (Math.Abs(x) > 0) Then
            camera.Position = New System.Windows.Media.Media3D.Point3D(x, y, z)
            camera.LookDirection = New System.Windows.Media.Media3D.Vector3D(-x, -y, -z)
        End If
    End Sub

End Class
