/************************************************************************************

PublicHeader:   OVR.h
Filename    :   OVR_DeviceMessages.h
Content     :   Definition of messages generated by devices
Created     :   February 5, 2013
Authors     :   Lee Cooper

Copyright   :   Copyright 2014 Oculus VR, Inc. All Rights reserved.

Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License"); 
you may not use the Oculus VR Rift SDK except in compliance with the License, 
which is provided at the time of installation or download, or which 
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-3.1 

Unless required by applicable law or agreed to in writing, the Oculus VR SDK 
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*************************************************************************************/

#ifndef OVR_DeviceMessages_h
#define OVR_DeviceMessages_h

#include "OVR_DeviceConstants.h"
#include "OVR_DeviceHandle.h"

#include "Kernel/OVR_Math.h"
#include "Kernel/OVR_Array.h"
#include "Kernel/OVR_Color.h"
#include "Kernel/OVR_String.h"

namespace OVR {

class DeviceBase;
class DeviceHandle;
class String;


#define OVR_MESSAGETYPE(devName, msgIndex)   ((Device_##devName << 8) | msgIndex)

// MessageType identifies the structure of the Message class; based on the message,
// casting can be used to obtain the exact value.
enum MessageType
{
    // Used for unassigned message types.
    Message_None            = 0,

    // Device Manager Messages
    Message_DeviceAdded             = OVR_MESSAGETYPE(Manager, 0),  // A new device is detected by manager.
    Message_DeviceRemoved           = OVR_MESSAGETYPE(Manager, 1),  // Existing device has been plugged/unplugged.
    // Sensor Messages
    Message_BodyFrame               = OVR_MESSAGETYPE(Sensor, 0),   // Emitted by sensor at regular intervals.
    Message_ExposureFrame	        = OVR_MESSAGETYPE(Sensor, 1),
    Message_PixelRead               = OVR_MESSAGETYPE(Sensor, 2),

    // Latency Tester Messages
    Message_LatencyTestSamples          = OVR_MESSAGETYPE(LatencyTester, 0),
    Message_LatencyTestColorDetected    = OVR_MESSAGETYPE(LatencyTester, 1),
    Message_LatencyTestStarted          = OVR_MESSAGETYPE(LatencyTester, 2),
    Message_LatencyTestButton           = OVR_MESSAGETYPE(LatencyTester, 3),
    
    Message_CameraFrame					= OVR_MESSAGETYPE(Camera, 0),
	Message_CameraAdded			        = OVR_MESSAGETYPE(Camera, 1),	
};

//-------------------------------------------------------------------------------------
// Base class for all messages.
class Message
{
public:
    Message(MessageType type = Message_None,
            DeviceBase* pdev = 0) : Type(type), pDevice(pdev)
    { }

    MessageType Type;    // What kind of message this is.
    DeviceBase* pDevice; // Device that emitted the message.
};


// Sensor BodyFrame notification.
// Sensor uses Right-Handed coordinate system to return results, with the following
// axis definitions:
//  - Y Up positive
//  - X Right Positive
//  - Z Back Positive
// Rotations a counter-clockwise (CCW) while looking in the negative direction
// of the axis. This means they are interpreted as follows:
//  - Roll is rotation around Z, counter-clockwise (tilting left) in XY plane.
//  - Yaw is rotation around Y, positive for turning left.
//  - Pitch is rotation around X, positive for pitching up.

//-------------------------------------------------------------------------------------
// ***** Sensor

class MessageBodyFrame : public Message
{
public:
    MessageBodyFrame(DeviceBase* dev)
        : Message(Message_BodyFrame, dev), Temperature(0.0f), TimeDelta(0.0f)
    {
    }

    Vector3f Acceleration;   // Acceleration in m/s^2.
    Vector3f RotationRate;   // Angular velocity in rad/s.
    Vector3f MagneticField;  // Magnetic field strength in Gauss.
    float    Temperature;    // Temperature reading on sensor surface, in degrees Celsius.
    float    TimeDelta;      // Time passed since last Body Frame, in seconds.

    // The absolute time from the host computers perspective that the message should be
    // interpreted as. This is based on incoming timestamp and processed by a filter
    // that syncs the clocks while attempting to keep the distance between messages
    // device clock matching.
    //
    // Integration should use TimeDelta, but prediction into the future should derive
    // the delta time from PredictToSeconds - AbsoluteTimeSeconds.
    //
    // This value will generally be <= the return from a call to ovr_GetTimeInSeconds(),
    // but could be greater by under 1 ms due to system time update interrupt delays.
    //
    double   AbsoluteTimeSeconds;
};

// Sent when we receive a device status changes (e.g.:
// Message_DeviceAdded, Message_DeviceRemoved).
class MessageDeviceStatus : public Message
{
public:
    MessageDeviceStatus(MessageType type, DeviceBase* dev, const DeviceHandle &hdev)
        : Message(type, dev), Handle(hdev) { }

    DeviceHandle Handle;
};

class MessageExposureFrame : public Message
{
public:
    MessageExposureFrame(DeviceBase* dev)
        : Message(Message_ExposureFrame, dev),
        CameraPattern(0), CameraFrameCount(0), CameraTimeSeconds(0) { }

    UByte   CameraPattern;
    UInt32  CameraFrameCount;
    double  CameraTimeSeconds;
};

class MessagePixelRead : public Message
{
public:
    MessagePixelRead(DeviceBase* dev)
        : Message(Message_PixelRead, dev),
        PixelReadValue(0), SensorTimeSeconds(0), FrameTimeSeconds(0) { }

    UByte   PixelReadValue;
    UInt32  RawSensorTime;
    UInt32  RawFrameTime;
    double  SensorTimeSeconds;
    double  FrameTimeSeconds;
};

//-------------------------------------------------------------------------------------
// ***** Latency Tester

// Sent when we receive Latency Tester samples.
class MessageLatencyTestSamples : public Message
{
public:
    MessageLatencyTestSamples(DeviceBase* dev)
        : Message(Message_LatencyTestSamples, dev)
    {
    }

    Array<Color>     Samples;
};

// Sent when a Latency Tester 'color detected' event occurs.
class MessageLatencyTestColorDetected : public Message
{
public:
    MessageLatencyTestColorDetected(DeviceBase* dev)
        : Message(Message_LatencyTestColorDetected, dev)
    {
    }

    UInt16      Elapsed;
    Color       DetectedValue;
    Color       TargetValue;
};

// Sent when a Latency Tester 'change color' event occurs.
class MessageLatencyTestStarted : public Message
{
public:
    MessageLatencyTestStarted(DeviceBase* dev)
        : Message(Message_LatencyTestStarted, dev)
    {
    }

    Color    TargetValue;
};

// Sent when a Latency Tester 'button' event occurs.
class MessageLatencyTestButton : public Message
{
public:
    MessageLatencyTestButton(DeviceBase* dev)
        : Message(Message_LatencyTestButton, dev)
    {
    }

};

//-------------------------------------------------------------------------------------
// ***** Camera

// Sent by camera, frame.
class MessageCameraFrame : public Message
{
public:
    MessageCameraFrame(DeviceBase* dev)
        : Message(Message_CameraFrame, dev), CameraHandle(NULL), pFrameData(NULL)
    {
        LostFrames = 0;
    }

    void SetInfo(UInt32 frameNumber, double timeSeconds, UInt32 width, UInt32 height, UInt32 format)
    {
        FrameNumber = frameNumber;
        ArrivalTimeSeconds = timeSeconds;
        Width = width;
        Height = height;
        Format = format;
    }

    void SetData(const UByte* pdata, UInt32 sizeInBytes)
    {
        pFrameData = pdata;
        FrameSizeInBytes = sizeInBytes;
    }

    UInt32   FrameNumber;			// an index of the frame
    double   ArrivalTimeSeconds;    // frame time in seconds, as recorded by the host computer
    const UByte* pFrameData;		// a ptr to frame data. 
    UInt32   FrameSizeInBytes;		// size of the data in the pFrameData.
    UInt32   Width, Height;			// width & height in pixels.
    UInt32   Format;				// format of pixel, see CameraDevice::PixelFormat enum
    UInt32   LostFrames;			// number of lost frames before this frame
	String	  DeviceIdentifier;		// identifies the device sensing the message
    UInt32* CameraHandle;			// Identifies the camera object associated with this frame
};

// Sent when a new camera is connected
class MessageCameraAdded : public Message
{
public:
    MessageCameraAdded(DeviceBase* dev)
        : Message(Message_CameraAdded, dev) { }

    MessageCameraAdded(UInt32* cam)
        : Message(Message_CameraAdded, NULL), CameraHandle(cam) { }

    UInt32* CameraHandle;			// Identifies the camera object associated with this frame
};

} // namespace OVR

#endif