OpenNI 1.5.7
Device.cpp file
<b>Source files:</b> Click the following link to view the source code file:
    - Device.cpp

This file contains the code for declaring, initalizing, and creating the basic OpenNI objects and nodes, and provides the basic access routiese. 

@section device_cpp_decls Main File Declarations 
@section device_cpp_decls Main File Declarations 

    The declarations at the head of this file define the main OpenNI objects and other environment variables.

    The following declarations define two of the main OpenNI objects required for building the OpenNI @ref prod_graph "production graph". The production graph is the main object in OpenNI.        
    @code
        Context g_Context;
        ScriptNode g_scriptNode;
    @endcode

    These two declarations are described separately in the following paragraphs.    

    the @ref xn::ScriptNode object loads an XML script from a file or string, and then runs the XML script to build a production graph.             

    The <i>@ref prod_graph "Production Graph"</i> is a network of software objects - called production nodes - that can identify blobs as hands or human users. In this sample program the production graph identifies blobs as human users, and tracks them as they move. 

    a @ref xn::Context object is a workspace in which the application builds an OpenNI production graph.    

    The following declarations define some environment variables. They are not OpenNI related.
    @code
        DeviceStringProperty g_PrimaryStream;
        ...
    @endcode

    The following declarations define more main OpenNI objects.
    @code
        Device g_Device;
        DepthGenerator g_Depth;
        ImageGenerator g_Image;
        IRGenerator g_IR;
        AudioGenerator g_Audio;
        Player g_Player;
    @endcode
    Each of these declarations is described separately in the following paragraphs. 

    A @ref xn::Device "Device" node represents a physical hardware device currently connected in the system and used for generating data. The Device node represents the hardware device by providing, for example, the device's name, serial number, and specific vendors. The Device node itself does not generate data.      

    a @ref xn::DepthGenerator node generates a depth map. Each map pixel value represents a distance from the sensor.               
    @code   
        DepthGenerator depthGen;
    @endcode

    A @ref xn::ImageGenerator "ImageGenerator" node generates color image maps of various formats, such as the RGB24 image format. Call its @ref xn::ImageGenerator::SetPixelFormat() "SetPixelFormat()" method to set the image format to be generated.        

    A @ref xn::IRGenerator "IRGenerator" node is a map generator that outputs infra-red maps. 
    The IR Generator node supports all MapGenerator functionality, as well as adding additional functionality.

    A @ref xn::AudioGenerator "AudioGenerator" node generates audio data. 

    A @ref xn::Player "Player" node plays a saved recording of an OpenNI data generation session.

    The following declarations define OpenNI use metadata classes to create @ref conc_meta_data "frame objects". The metadata classes provide @ref glos_frame_object "frame objects" to the corresponding generator nodes to support fast data access. for example, the @ref xn::DepthMetaData "DepthMetaData" object provides a frame object for a @ref xn::DepthGenerator "DepthGenerator" node, and so on.       
    @code
        DepthMetaData g_DepthMD;
        ImageMetaData g_ImageMD;
        IRMetaData g_irMD;
        AudioMetaData g_AudioMD;
    @endcode

    This program file makes extensive use of <code>g_pPrimary</code>. This is a pointer to a @ref xn::ProductionNode "ProductionNode" object to point to just one of the @ref xn::Generator "Generator nodes". This node is then termed the primary node in this sample program. <code>g_pPrimary</code> selectas which output map to display on the graphic display.  <code>g_pPrimary</code> is assigned its value in the <code>changePrimaryStream()</code> function.

    The ProductionNode class is a base class for all production nodes of the @ref prod_graph "Production Graph", including all @ref xn::Generator "Generator" nodes. Note that the <code>g_pPrimary pointer</code> is never itself used to make an object or node, but just to point to a node created somewhere else.          
    @code
        ProductionNode* g_pPrimary = NULL;
    @endcode


@section device_cpp_initConstants Function: initConstants() - Initializes the Primary Stream and the Resolutions

    In the following code block (shown in part), <code>g_PrimaryStream</code> is initialized with the enum IDs of all different types of production nodes, e.g., @ref xn::XN_NODE_TYPE_DEPTH means a DepthGenerator node.
    @code
        g_PrimaryStream.pValues[nIndex++] = "Any";
        g_PrimaryStream.pValues[nIndex++] = xnProductionNodeTypeToString(XN_NODE_TYPE_DEPTH);
        g_PrimaryStream.pValues[nIndex++] = xnProductionNodeTypeToString(XN_NODE_TYPE_IMAGE);
        g_PrimaryStream.pValues[nIndex++] = xnProductionNodeTypeToString(XN_NODE_TYPE_IR);
         ...
    @endcode

    In the following code block (shown in part), <code>g_Resolution</code> is initialized with all possible image map resolutions.
    @code
        g_Resolution.pValues[nIndex++] = XN_RES_QVGA;
        g_Resolution.pValueToName[XN_RES_QVGA] = Resolution(XN_RES_QVGA).GetName();
        g_Resolution.pValues[nIndex++] = XN_RES_VGA;
        g_Resolution.pValueToName[XN_RES_VGA] = Resolution(XN_RES_VGA).GetName();           
    @endcode

@section device_cpp_initConstants - onErrorStateChanged() - Callback invoked when  the Error State Changed

    This function tests whether the error state is now xn::XN_STATUS_OK, i.e., no error, or is an error. On error, the error message is accessed according to the value of @ref xn::XnStatus "errorState". The high word represents the error group of the  error. The low word is the sequential error number within the group. 

@section device_cpp_openCommon - openCommon() - Common Initialize Function

    This is a common initialize function called from a number of more specific functions that initialize the production graph.      
    @code
        void openCommon()
        {
            ...
        }           
    @endcode            

    This function uses @ref xn::Context::EnumerateExistingNodes to enumerate for all production nodes defined in the production graph, which returns in the <code>list</code> return parameter a @ref xn::NodeInfoList containing all the context's existing created nodes. Each node is represented by a @ref xn::NodeInfo "NodeInfo" object in the list. 

    The following for-loop iterates for all NodeInfo objects in the list. For each NodeInfo object found, this function calls @ref xn::NodeInfo::GetInstance() "GetInstance()" to return a reference to the actual production node instance represented by this NodeInfo object. The for-loop is shown below (in part): 
    @code
        for (NodeInfoList::Iterator it = list.Begin(); it != list.End(); ++it)
        {
            switch ((*it).GetDescription().Type)
            {
            case XN_NODE_TYPE_DEVICE:
                (*it).GetInstance(g_Device);
                break;
            case XN_NODE_TYPE_DEPTH:
                g_bIsDepthOn = true;
                (*it).GetInstance(g_Depth);
                break;
            ...
        }
    @endcode

    The above loop sets the generating state of all nodes to 'On', e.g., <code>g_bIsDepthOn = true</code>.

    The following statement registers an event handler, <code>onErrorStateChanged()</code>, for all OpenNI errors that might occur. 
    @code
        g_Context.RegisterToErrorStateChange(onErrorStateChanged, NULL, hDummy);
    @endcode

    The following statements initialize the constants (see @ref device_cpp_initConstants above) and calls the @ref device_cpp_readFrame "readFrame()" method to read the first data frame. The readFrame() method reads the data frame from each and every one of all the generators in the production graph. 
    @code
        initConstants();
        readFrame();
    @endcode


@section device_cpp_openDeviceFile - openDeviceFile() - Builds a Production Graph from an OpenNI Recording File

    This function sets up a replay of a session of OpenNI data generation exactly as it was recorded on an ONI file.

    The following call to the @ref xn::Context::Init() "Context::Init()" method builds the context's general software environment. This method initializes runtime variables and data structures, and examines all registered plug-ins to learn the purpose and specific capabilities of each. In particular, during initialization the context initialization examines all registered plug-ins to learn the purpose and specific capabilities of each.             
    @code
        XnStatus nRetVal = g_Context.Init();
    @endcode

    In the following, if <code>nRetVal</code> is an error value, the @ref xn::XN_IS_STATUS_OK "XN_IS_STATUS_OK()" macro halts program execution, returning nRetVal as the error value.  
    @code
        XN_IS_STATUS_OK(nRetVal);
    @endcode

    The following call to @ref xn::Context::OpenFileRecording() "OpenFileRecording()" recreates a production graph from a recorded ONI file and then replays the data generation exactly as it was recorded. The <code>csFile </code>parameter provides the name of the recorded file to be run. The <code>g_Player</code> parameter returns a @ref xn::ProductionNode object through which playback can be controlled, e.g., seeking and setting playback. 
    @code
        nRetVal = g_Context.OpenFileRecording(csFile, g_Player);
    @endcode

    The <code>openCommon()</code> method, called in the following statement, is descibed above in @ref device_cpp_openCommon.


@section device_cpp_openDeviceFromXml - openDeviceFromXml() - Builds a Production Graph from an OpenNI XML Script File

    The following call to the @ref xn::Context::InitFromXmlFile() "Context.InitFromXmlFile()" method builds the context's general software environment (see <code>g_Context.Init()</code> above) and then recreates a production graph from the specified OpenNI XML script file. This method is not for replaying a recording (compare with OpenFileRecording above).
    @code
        nRetVal = g_Context.InitFromXmlFile(csXmlFile, g_scriptNode, &errors);
    @endcode

    In the following statement, if <code>nRetVal</code> is an error value, the @ref xn::XN_IS_STATUS_OK "XN_IS_STATUS_OK()" macro halts program execution, returning nRetVal as the error value.    
    @code
        XN_IS_STATUS_OK(nRetVal);
    @endcode            


@section device_cpp_openDeviceFromXmlWithChoice - openDeviceFromXmlWithChoice() - Builds a Production Graph from an XML Script, Allowing User to Select a Device 

    This function does the same as the previous function, i.e., it builds the Production Graph from an OpenNI XML Script File, but it allows the user to intervene and select a device.

    the @ref xn::Context::EnumerateProductionTrees() method enumerates all available production nodes for a specific node type (e.g., the application wants to create a @ref xn::Device node) and returns a full list of matching production nodes.

    This function then gets the device IDs of all the devices it finds in the production graph using xn::Device::GetIdentificationCap() "GetIdentificationCap()".

    The function then interacts with the user using simple C functions to allow the user to select which device to use.


@section device_cpp_closeDevice - closeDevice() - Releases all the Production Nodes 

    This function releases all the production graph nodes.



@section device_cpp_readFrame readFrame() function - Reads a Data frame from each Generator

    This function reads a data frame from each of the generators in the production graph.

    If <code>g_pPrimary</code> has been set to point to any particular node (i.e., not NULL; <code>g_pPrimary</code> is initialized in the <code>changePrimaryStream()</code> function) then this function calls @ref xn::Context::WaitOneUpdateAll() "WaitOneUpdateAll()" to wait only for that particular node to generate new data, and then this function refreshes the data available in all the nodes.

    <code>g_pPrimary</code> can be pointing to NULL. This is a valid user selection, available from the GUI menu. <code>g_pPrimary</code> == NULL means that the user is not selcting any particular generator node. 

    Then the function checks if all the node pointers (e.g., <code>g-depth</code>) point to real nodes, and if so the function gets the node's @ref glos_frame_object "frame object", saving it in a metadata object. For example: the application saves a frame object from a  @ref xn::DepthGenerator "DepthGenerator" node as a ref xn::DepthMetaData object. 
    @code
        if (g_Depth.IsValid())
        {
            g_Depth.GetMetaData(g_DepthMD);
        }
    @endcode
    This frame object provides fast access to the saved generated data and its associated configuration.

@section device_cpp_changeRegistration changeRegistration() - Changes the View Point Registration

    <i>Viewpoint registration</i> is an OpenNI term for performing the mathematical conversion of one node's coordinate system to match the coordinate system of another node.

    In this sample program, this specific function can toggle the viewpoint registration of the DepthGenerator node to that of the ImageGenerator node and back again - i.e., reset it - depending on the input parameter. This particular conversion is a consequence of the particular type of the supplied hardware sensor. 

    The following test checks verifies that the DepthGenerator node is a valid node and that it supports the Alternative View Point capability.
    @code
        if (!g_Depth.IsValid() || !g_Depth.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT))
        {
            return;
        }               
    @endcode

    The following code block calls @ref xn::AlternativeViewPointCapability methods to toggle the viewpoint registration, as explained above.
    @code
        if (!nValue)
        {
            g_Depth.GetAlternativeViewPointCap().ResetViewPoint();
        }
        else if (g_Image.IsValid())
        {
            g_Depth.GetAlternativeViewPointCap().SetViewPoint(g_Image);
        }
    @endcode



@section device_cpp_changePrimaryStream changePrimaryStream() function - Change the Primary stream

    This function selects from which node the application will take generated data. It selects the new production node acording to the index into the <code>g_PrimaryStream</code> array. The @ref xnProductionNodeTypeFromString() function returns an enum specifting a particular node type, e.g., XN_NODE_TYPE_DEPTH specifies a DepthGenerator node.

    The user can invoke this functionality from the GUI user menu. The user can select a menu item to call this function.

    The following statement calls the  @ref xn::Context::CreateAnyProductionTree() method.


@section device_cpp_createStream createStream() - Creates a New Data Generatation Node

    This function creates a new stream by creating a new data generation node of a specified type calling the @ref xn::Context.CreateAnyProductionTree() method, as follows. 
    @code
        EnumerationErrors errors;
        XnStatus nRetVal = g_Context.CreateAnyProductionTree(type, NULL, generator, &errors);
    @endcode
    This method enumerates for production nodes of a specific node type, and creates the first production node found of that type.






@section device_cpp_toggleStream toggleStream() - Toggles between Starting and Stopping a Generator Node

    This function toggles between starting and stopping a generator node. The first two statements ensure that the specified generator is a valid node, and if not it calls createStream() (described above) to create a node of the required type.

    In the following statement, the @ref xn::Generator::IsValid() method checks that the reference points to a real node instance, or to to NULL, where in the  latter case the function calls createStream() to create the generator node. 
    @code
        if (!generator.IsValid())
        {
            createStream(generator, type);
        }
    @endcode

    In the following code block, the @ref xn::Generator::IsGenerating() "IsGenerating()" method returns whether the node is currently in Generating state. @ref xn::Generator::StartGenerating() "StartGenerating()" enters the node into Generating state, and @ref xn::Generator::StopGenerating() "StopGenerating()" makes the node leave Generating state (it enters Non-Generating state).         

    @code
        if (generator.IsGenerating())
        {
            generator.StopGenerating();
        }
        else
        {
            generator.StartGenerating();
            ...
        }                       
    @endcode

    After the application has called StartGenerating() it can call an 'Update Data()' method, e.g., @ref xn::Generator::WaitAndUpdateData(), to make a new frame available for getting. The application can then get the data (for example, using a metadata GetData() method, or some other mechanism depending on the type of node).                      

    This <code>toggleStream()</code> function is used by a number of other functions to start and stop each of the generators in this application - see below.

    Finally, this function then sets the boolean return parameter <code>bIsOn </code>from the <code>IsGenerating()</code> method. This parameter returns the updated 'Is Generating' state for all the 'Toggle Generating State' functions that follow below.


@section device_cpp_StartStopGen Starting and Stopping each of the Generators 

    The following group of functions start and stop each of the generators in this application. 
    @code
        void toggleDepthState(int nDummy)
        {
            toggleStream(g_Depth, XN_NODE_TYPE_DEPTH, &g_bIsDepthOn);
        }

        void toggleImageState(int nDummy)
        {
            toggleStream(g_Image, XN_NODE_TYPE_IMAGE, &g_bIsImageOn);
        }

        void toggleIRState(int nDummy)
        {
            toggleStream(g_IR, XN_NODE_TYPE_IR, &g_bIsIROn);
        }

        void toggleAudioState(int nDummy)
        {
            toggleStream(g_Audio, XN_NODE_TYPE_AUDIO, &g_bIsAudioOn);
        }       
    @endcode    


@section device_cpp_ToggleMirror Function: toggleMirror() - Toggles the Global Mirror

    This function can enable or disable the @ref xn::MirrorCapability "GlobalMirror" flag. For a detailed introduction to mirroring in OpenNI see @ref xn::MirrorCapability.

    The following statement gets the current value of the Global Mirror using the @ref xn::Context::GetGlobalMirror() "GetGlobalMirror()" method and then inverses it using the @ref xn::Context::GetGlobalMirror() "GetGlobalMirror()" method.
    @code
        XnStatus nRetVal = g_Context.SetGlobalMirror(!g_Context.GetGlobalMirror())
    @endcode

    Use the GUI menu access to toggle the GlobalMirrior.


@section device_cpp_seekFrame  Function: seekFrame() - Seeks a Data Frame in a Recording 

    This function seeks a data frame from the primary stream (generator node) in an OpenNI recording. 

    The first thing this function does is to get the node name of the primary stream. if the primary stream is found to be NULL, this function then gets node name of any other valid node.

    The following statement calls the @ref xn::Player::SeekToFrame() "SeekToFrame()" method to moves the player to a specific frame of a specific played node so that playing will continue from that frame onwards.
    @code
        nRetVal = g_Player.SeekToFrame(strNodeName, nDiff, XN_PLAYER_SEEK_CUR);
    @endcode

    In the call above, the <code>nDiff</code> and <code>@ref xn::XN_PLAYER_SEEK_CUR</code> parameters specify that the seek operation moves <code>nDiff</code> frames from the current frame of the specified node. A positive value means to move forward, and a negative value means to move backwards. 

    In the following statement, the call to the @ref xn::Player::TellFrame() "TellFrame()" method gets the absolute current frame number of a specific node played by a player, i.e., the number of frames passed since the beginning of the recording.

    In the following statement, the call to the @ref xn::Player::GetNumFrames() "GetNumFrames()" method gets the number of frames of a specific node played by a player.


@section device_cpp_isgenon  Function: is 'Generator' On function\

    The following group of functions all return whether the production node is on. For example:
    @code
        bool isDepthOn()
        {
            return (g_bIsDepthOn);
        }           
    @endcode


@section device_cpp_setResolution Function: setResolution() - Sets the Resolution of the Output Map

    This function sets the resolution component of the generator node's current map output mode. This map output mode includes the frame resolution, i.e., its X and Y dimensions, which are the number of elements in each of the X- and Y- axes) and also the frame rate. This is the map output mode that the generator node will use to generate its next data frame.

    The resolution is provided y the <code>res</code> parameter to this function call, which is an enum value of type @ref xn::XnResolution "XnResolution", e.g., @ref xn::XN_RES_QVGA "XN_RES_QVGA". 

    The following code block calls the @ref xn::MapGenerator::GetMapOutputMode() "GetMapOutputMode()" method to get an @ref xn::XnMapOutputMode struct containing the generator node's current map output mode. The code then updates the mode's  resolution fields with new values, and then completes the operation by calling @ref xn::MapGenerator::SetMapOutputMode() "SetMapOutputMode()", passing the @ref xn::XnMapOutputMode struct as a parameter, to update the node's map output mode.
    @code
        XnMapOutputMode Mode;
        pGenerator->GetMapOutputMode(Mode);
        Mode.nXRes = Resolution((XnResolution)res).GetXResolution();
        Mode.nYRes = Resolution((XnResolution)res).GetYResolution();
        XnStatus nRetVal = pGenerator->SetMapOutputMode(Mode);
    @endcode

    See also the setFPS() function (the next function, below) for setting the frame rate.

    In the above, the 'Resolution' term is an OpenNI utility class for easy handling of resolution information. It creates a @ref xn::Resolution "Resolution" object from an enum value of type @ref xn::XnResolution "XnResolution", from which you can then get the X and Y dimensions if the frame.


@section device_cpp_setfps Function: setFPS() - Selects a Resolution for the Output Map

    This function sets the frame rate component of the generator node's current map output mode. 

    This function works in a similar way to the <code>setResolution()</code> function above. 

    The following code block calls the @ref xn::MapGenerator::GetMapOutputMode() "GetMapOutputMode()" method to get an @ref xn::XnMapOutputMode struct containing the generator node's current map output mode. The code then updates the mode's  frmae rate field, <code>nFPS</code>, with a new value, and then completes the operation by calling @ref xn::MapGenerator::SetMapOutputMode() "SetMapOutputMode()", passing the @ref xn::XnMapOutputMode struct as a parameter, to update the node's map output mode.
    @code
        XnMapOutputMode Mode;
        pGenerator->GetMapOutputMode(Mode);
        Mode.nFPS = fps;
        XnStatus nRetVal = pGenerator->SetMapOutputMode(Mode);
    @endcode    


@section device_cpp_grp_setResolutionFps 'setResolution/Fps()' - Group of Functions for Setting Resolutions and Frame Rates

    The next functions defined in this file are a group of functions for setting  resolutions and frame rates for all generators in this sample application. All use the methods just defined above, @ref device_cpp_setResolution "setResolution()" and @ref device_cpp_setfps "setFPS()". The code below shows  some examples. 
    @code
        void setDepthResolution(int res)
        {
            setResolution(getDepthGenerator(), res);
        }
        ...
        ...
        void setImageFPS(int fps)
        {
            setFPS(getImageGenerator(), fps);
        }
    @endcode

    The 'get' functions used in the above are defined later in this file.

    All these 'set resolution/fps' functions are invoked by the user clicking the GUI menu items to make these settings. 


@section device_cpp_setStreamCropping Function: setStreamCropping() - Crops the Map Area of the Generator Output

    This function crops the map area of the generator output.

    <b>Usage: </b> For user area selections where the user can use the mouse to select just a part of the full map area for applying OpenNI or other graphic operations.

    <b>Parameters: </b> 

    <code>pGenerator</code> - generator node for which to set the cropping area.

    <code>pCropping</code> -  @ref xn::XnCropping struct containing the cropping details.

    The following statement checks that the generator node exists.
    @code
        if (pGenerator == NULL)
        {
            displayMessage("Stream does not exist!");
            return;
        }           
    @endcode

    The code first checks that the capability exists using the @ref xn::Generator::IsCapabilitySupported "IsCapabilitySupported()" method.

    The code then gets the crop capability using the @ref xn::MapGenerator::GetCroppingCap()  "GetCroppingCap()" method, and through it calls  the @ref xn::CroppingCapability::SetCropping() method.


@section device_cpp_setPlaybackSpeed Function: setPlaybackSpeed() - Sets the  playback speed 

    <b>Group:</b>  Recording and Playback 
    {If I want to use this format I will have to go back and make it consistent - ie at least for this sample NiViewer.}

    <b>Parameter:</b>  ratioDiff - Ratio of recording rate 

    This function sets the playback speed of an OpenNI recording as a ratio of the rate that the recording was made at. This OpenNI recording is a recording of all the actual map data that was generated during the time that recording was enabled. This is not the  same as a production graph stired in an OpenNI XML script file: a script file stores only the structure of the production graph but not the data that the production graph has or will generate.
    @code

        XnDouble dNewSpeed = g_Player.GetPlaybackSpeed() * pow(2.0, (XnDouble)ratioDiff);
        XnStatus nRetVal = g_Player.SetPlaybackSpeed(dNewSpeed);
    @endcode


@section device_cpp_getPlaybackSpeed Function: getPlaybackSpeed() - Gets the  playback speed            

    <b>Group:</b>  Recording and Playback 

    This function calls the @ref xn::Player::GetPlaybackSpeed() to get current playback speed. If the player is not valid it returns the "identity' ratio, 1. 


@section device_cpp_grp_getobject Function: setFPS() - Group of Functions for Setting Resolutions and Frame Rates

    Next is a group of functions for getting pointers to certain OpenNI objects: to production nodes, generators, and metadata objects. The code below shows some examples. 
    These  functions achieve a way of simply indicating as a boolean flag whether the nodes are actual <i>created</i> nodes, i.e., whether they have been initialized and made operational in the @ref prod_graph "production graph", or   they are still in the 'pre-creation'  state, i.e., they have been constructed as C++ objects but have not yet undergone creation.
    @code
        Device* getDevice()
        {
            return g_Device.IsValid() ? &g_Device : NULL;
        }
        DepthGenerator* getDepthGenerator()
        {
            return g_Depth.IsValid() ? &g_Depth : NULL;
        }
        ...
        ...
        const AudioMetaData* getAudioMetaData()
        {
            return g_Audio.IsValid() ? &g_AudioMD : NULL;
        }
    @endcode