<commit_before>#include <osgText/Text>
#include <osgText/Font>

#include <iostream>
#include <string>

#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/io_utils>

#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
#include <osgDB/ParameterOutput>

bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw);

osgDB::RegisterDotOsgWrapperProxy Text_Proxy
(
    new osgText::Text,
    "Text",
    "Object Drawable Text",
    Text_readLocalData,
    Text_writeLocalData
);

bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
    osgText::Text &text = static_cast<osgText::Text &>(obj);
    bool itAdvanced = false;

    if (fr.matchSequence("font %w"))
    {
        text.setFont(fr[1].getStr());
        fr += 2;
        itAdvanced = true;

    }

    if (fr[0].matchWord("fontResolution") || fr[0].matchWord("fontSize"))
    {
        unsigned int width;
        unsigned int height;
        if (fr[1].getUInt(width) && fr[2].getUInt(height))
        {
            text.setFontResolution(width,height);
            fr += 3;
            itAdvanced = true;
        }
    }

    if (fr[0].matchWord("characterSize"))
    {
        float height;
        float aspectRatio;
        if (fr[1].getFloat(height) && fr[2].getFloat(aspectRatio))
        {
            text.setCharacterSize(height,aspectRatio);
            fr += 3;
            itAdvanced = true;
        }
    }

    if (fr.matchSequence("characterSizeMode %w"))
    {
        std::string str = fr[1].getStr();
        if      (str=="OBJECT_COORDS") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS);
        else if (str=="SCREEN_COORDS") text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
        else if (str=="OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT);
    }

    // maximum dimentsions of text box.
    if (fr[0].matchWord("maximumWidth"))
    {
        float width;
        if (fr[1].getFloat(width))
        {
            text.setMaximumWidth(width);
            fr += 2;
            itAdvanced = true;
        }
    }

    if (fr[0].matchWord("maximumHeight"))
    {
        float height;
        if (fr[1].getFloat(height))
        {
            text.setMaximumHeight(height);
            fr += 2;
            itAdvanced = true;
        }
    }

    if (fr.matchSequence("alignment %w"))
    {
        std::string str = fr[1].getStr();
        if      (str=="LEFT_TOP") text.setAlignment(osgText::Text::LEFT_TOP);
        else if (str=="LEFT_CENTER") text.setAlignment(osgText::Text::LEFT_CENTER);
        else if (str=="LEFT_BOTTOM") text.setAlignment(osgText::Text::LEFT_BOTTOM);
        else if (str=="CENTER_TOP") text.setAlignment(osgText::Text::CENTER_TOP);
        else if (str=="CENTER_CENTER") text.setAlignment(osgText::Text::CENTER_CENTER);
        else if (str=="CENTER_BOTTOM") text.setAlignment(osgText::Text::CENTER_BOTTOM);
        else if (str=="RIGHT_TOP") text.setAlignment(osgText::Text::RIGHT_TOP);
        else if (str=="RIGHT_CENTER") text.setAlignment(osgText::Text::RIGHT_CENTER);
        else if (str=="RIGHT_BOTTOM") text.setAlignment(osgText::Text::RIGHT_BOTTOM);
        else if (str=="LEFT_BASE_LINE") text.setAlignment(osgText::Text::LEFT_BASE_LINE);
        else if (str=="CENTER_BASE_LINE") text.setAlignment(osgText::Text::CENTER_BASE_LINE);
        else if (str=="RIGHT_BASE_LINE") text.setAlignment(osgText::Text::RIGHT_BASE_LINE);
        else if (str=="BASE_LINE") text.setAlignment(osgText::Text::BASE_LINE);
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("axisAlignment %w"))
    {
        std::string str = fr[1].getStr();
        if      (str=="XY_PLANE") text.setAxisAlignment(osgText::Text::XY_PLANE);
        else if (str=="REVERSED_XY_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_XY_PLANE);
        else if (str=="XZ_PLANE") text.setAxisAlignment(osgText::Text::XZ_PLANE);
        else if (str=="REVERSED_XZ_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_XZ_PLANE);
        else if (str=="YZ_PLANE") text.setAxisAlignment(osgText::Text::YZ_PLANE);
        else if (str=="REVERSED_YZ_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_YZ_PLANE);
        else if (str=="SCREEN") text.setAxisAlignment(osgText::Text::SCREEN);
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("rotation"))
    {
        osg::Vec4 rotation;
        if (fr[1].getFloat(rotation.x()) && fr[2].getFloat(rotation.y()) && fr[3].getFloat(rotation.z()) && fr[4].getFloat(rotation.w()))
        {
            text.setRotation(rotation);
            fr += 4;
            itAdvanced = true;
        }
    }

    if (fr.matchSequence("autoRotateToScreen TRUE"))
    {
        text.setAutoRotateToScreen(true);
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("autoScaleToLimitScreenSizeToFontResolution TRUE"))
    {
        text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("layout %w") && fr[1].getStr())
    {
        std::string str = fr[1].getStr();
        if      (str=="LEFT_TO_RIGHT") text.setLayout(osgText::Text::LEFT_TO_RIGHT);
        else if (str=="RIGHT_TO_LEFT") text.setLayout(osgText::Text::RIGHT_TO_LEFT);
        else if (str=="VERTICAL") text.setLayout(osgText::Text::VERTICAL);
        fr += 2;
        itAdvanced = true;
    }

    // position
    if (fr[0].matchWord("position"))
    {
        osg::Vec3 p;
        if (fr[1].getFloat(p.x()) && fr[2].getFloat(p.y()) && fr[3].getFloat(p.z()))
        {
            text.setPosition(p);
            fr += 4;
            itAdvanced = true;
        }
    }

    // color
    if (fr[0].matchWord("color"))
    {
        osg::Vec4 c;
        if (fr[1].getFloat(c.x()) && fr[2].getFloat(c.y()) && fr[3].getFloat(c.z()) && fr[4].getFloat(c.w()))
        {
            text.setColor(c);
            fr += 4;
            itAdvanced = true;
        }
    }

    // draw mode
    if (fr[0].matchWord("drawMode"))
    {
        int i;
        if (fr[1].getInt(i)) {
            text.setDrawMode(i);
            fr += 2;
            itAdvanced = true;
        }
    }

    // text
    if (fr.matchSequence("text %s") && fr[1].getStr()) {
        text.setText(std::string(fr[1].getStr()));
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("text %i {"))
    {
        // pre 0.9.3 releases..
        int entry = fr[0].getNoNestedBrackets();

        int capacity;
        fr[1].getInt(capacity);

        osgText::String str;
        str.reserve(capacity);

        fr += 3;

        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int c;
            if (fr[0].getUInt(c))
            {
                ++fr;
                str.push_back(c);
            }
            else
            {
                ++fr;
            }
        }

        text.setText(str);

        itAdvanced = true;
        ++fr;
    }

    return itAdvanced;
}

bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
    const osgText::Text &text = static_cast<const osgText::Text &>(obj);

    if (text.getFont())
    {
        fw.indent() << "font " << text.getFont()->getFileName() << std::endl;
    }

    // font resolution
    fw.indent() << "fontResolution " << text.getFontWidth() << " " << text.getFontHeight() << std::endl;

    // charater size.
    fw.indent() << "characterSize " << text.getCharacterHeight() << " " << text.getCharacterAspectRatio() << std::endl;

    fw.indent() << "characterSizeMode ";
    switch(text.getCharacterSizeMode())
    {
      case osgText::Text::OBJECT_COORDS : fw<<"OBJECT_COORDS"<<std::endl; break;
      case osgText::Text::SCREEN_COORDS : fw<<"SCREEN_COORDS"<<std::endl; break;
      case osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT: fw<<"OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT"<<std::endl; break;
    }

    // maximum dimension of text box.
    if (text.getMaximumWidth()>0.0f)
    {
        fw.indent() << "maximumWidth " << text.getMaximumWidth() << std::endl;
    }

    if (text.getMaximumHeight()>0.0f)
    {
        fw.indent() << "maximumHeight " << text.getMaximumHeight() << std::endl;
    }

    // alignment
    fw.indent() << "alignment ";
    switch(text.getAlignment())
    {
      case osgText::Text::LEFT_TOP:        fw << "LEFT_TOP" << std::endl; break;
      case osgText::Text::LEFT_CENTER :    fw << "LEFT_CENTER" << std::endl; break;
      case osgText::Text::LEFT_BOTTOM :    fw << "LEFT_BOTTOM" << std::endl; break;

      case osgText::Text::CENTER_TOP:      fw << "CENTER_TOP" << std::endl; break;
      case osgText::Text::CENTER_CENTER:   fw << "CENTER_CENTER" << std::endl; break;
      case osgText::Text::CENTER_BOTTOM:   fw << "CENTER_BOTTOM" << std::endl; break;

      case osgText::Text::RIGHT_TOP:       fw << "RIGHT_TOP" << std::endl; break;
      case osgText::Text::RIGHT_CENTER:    fw << "RIGHT_CENTER" << std::endl; break;
      case osgText::Text::RIGHT_BOTTOM:    fw << "RIGHT_BOTTOM" << std::endl; break;

      case osgText::Text::LEFT_BASE_LINE:  fw << "LEFT_BASE_LINE" << std::endl; break;
      case osgText::Text::CENTER_BASE_LINE:fw << "CENTER_BASE_LINE" << std::endl; break;
      case osgText::Text::RIGHT_BASE_LINE: fw << "RIGHT_BASE_LINE" << std::endl; break;
    };

    if (!text.getRotation().zeroRotation())
    {
        fw.indent() << "rotation " << text.getRotation() << std::endl;
    }

    if (text.getAutoRotateToScreen())
    {
        fw.indent() << "autoRotateToScreen TRUE"<< std::endl;
    }

    // layout
    fw.indent() << "layout ";
    switch(text.getLayout())
    {
      case osgText::Text::LEFT_TO_RIGHT: fw << "LEFT_TO_RIGHT" << std::endl; break;
      case osgText::Text::RIGHT_TO_LEFT: fw << "RIGHT_TO_LEFT" << std::endl; break;
      case osgText::Text::VERTICAL: fw << "VERTICAL" << std::endl; break;
    };

    // position
    osg::Vec3 p = text.getPosition();
    fw.indent() << "position " << p.x() << " " << p.y() << " " << p.z() << std::endl;

    // color
    osg::Vec4 c = text.getColor();
    fw.indent() << "color " << c.x() << " " << c.y() << " " << c.z() << " " << c.w() << std::endl;

    // draw mode
    fw.indent() << "drawMode " << text.getDrawMode() << std::endl;

    // text
    const osgText::String& textstring = text.getText();
    bool isACString = true;
    osgText::String::const_iterator itr;
    for(itr=textstring.begin();
        itr!=textstring.end() && isACString;
        ++itr)
    {
        if (*itr==0 || *itr>256) isACString=false;
    }
    if (isACString)
    {
        std::string str;

        for(itr=textstring.begin();
            itr!=textstring.end();
            ++itr)
        {
            str += (char)(*itr);
        }

        //std::copy(textstring.begin(),textstring.end(),std::back_inserter(str));

        fw.indent() << "text " << fw.wrapString(str) << std::endl;
    }
    else
    {
        // do it the hardway...output each character as an int
        fw.indent() << "text "<<textstring.size()<<std::endl;;
        osgDB::writeArray(fw,textstring.begin(),textstring.end());
    }

    return true;
}
<commit_msg>Added .osg suppot for new alignment modes<commit_after>#include <osgText/Text>
#include <osgText/Font>

#include <iostream>
#include <string>

#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/io_utils>

#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
#include <osgDB/ParameterOutput>

bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw);

osgDB::RegisterDotOsgWrapperProxy Text_Proxy
(
    new osgText::Text,
    "Text",
    "Object Drawable Text",
    Text_readLocalData,
    Text_writeLocalData
);

bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
    osgText::Text &text = static_cast<osgText::Text &>(obj);
    bool itAdvanced = false;

    if (fr.matchSequence("font %w"))
    {
        text.setFont(fr[1].getStr());
        fr += 2;
        itAdvanced = true;

    }

    if (fr[0].matchWord("fontResolution") || fr[0].matchWord("fontSize"))
    {
        unsigned int width;
        unsigned int height;
        if (fr[1].getUInt(width) && fr[2].getUInt(height))
        {
            text.setFontResolution(width,height);
            fr += 3;
            itAdvanced = true;
        }
    }

    if (fr[0].matchWord("characterSize"))
    {
        float height;
        float aspectRatio;
        if (fr[1].getFloat(height) && fr[2].getFloat(aspectRatio))
        {
            text.setCharacterSize(height,aspectRatio);
            fr += 3;
            itAdvanced = true;
        }
    }

    if (fr.matchSequence("characterSizeMode %w"))
    {
        std::string str = fr[1].getStr();
        if      (str=="OBJECT_COORDS") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS);
        else if (str=="SCREEN_COORDS") text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
        else if (str=="OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT);
    }

    // maximum dimentsions of text box.
    if (fr[0].matchWord("maximumWidth"))
    {
        float width;
        if (fr[1].getFloat(width))
        {
            text.setMaximumWidth(width);
            fr += 2;
            itAdvanced = true;
        }
    }

    if (fr[0].matchWord("maximumHeight"))
    {
        float height;
        if (fr[1].getFloat(height))
        {
            text.setMaximumHeight(height);
            fr += 2;
            itAdvanced = true;
        }
    }

    if (fr.matchSequence("alignment %w"))
    {
        std::string str = fr[1].getStr();
        if      (str=="LEFT_TOP") text.setAlignment(osgText::Text::LEFT_TOP);
        else if (str=="LEFT_CENTER") text.setAlignment(osgText::Text::LEFT_CENTER);
        else if (str=="LEFT_BOTTOM") text.setAlignment(osgText::Text::LEFT_BOTTOM);
        else if (str=="CENTER_TOP") text.setAlignment(osgText::Text::CENTER_TOP);
        else if (str=="CENTER_CENTER") text.setAlignment(osgText::Text::CENTER_CENTER);
        else if (str=="CENTER_BOTTOM") text.setAlignment(osgText::Text::CENTER_BOTTOM);
        else if (str=="RIGHT_TOP") text.setAlignment(osgText::Text::RIGHT_TOP);
        else if (str=="RIGHT_CENTER") text.setAlignment(osgText::Text::RIGHT_CENTER);
        else if (str=="RIGHT_BOTTOM") text.setAlignment(osgText::Text::RIGHT_BOTTOM);
        else if (str=="LEFT_BASE_LINE") text.setAlignment(osgText::Text::LEFT_BASE_LINE);
        else if (str=="CENTER_BASE_LINE") text.setAlignment(osgText::Text::CENTER_BASE_LINE);
        else if (str=="RIGHT_BASE_LINE") text.setAlignment(osgText::Text::RIGHT_BASE_LINE);
        else if (str=="LEFT_BOTTOM_BASE_LINE") text.setAlignment(osgText::Text::LEFT_BOTTOM_BASE_LINE);
        else if (str=="CENTER_BOTTOM_BASE_LINE") text.setAlignment(osgText::Text::CENTER_BOTTOM_BASE_LINE);
        else if (str=="RIGHT_BOTTOM_BASE_LINE") text.setAlignment(osgText::Text::RIGHT_BOTTOM_BASE_LINE);
        else if (str=="BASE_LINE") text.setAlignment(osgText::Text::BASE_LINE);
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("axisAlignment %w"))
    {
        std::string str = fr[1].getStr();
        if      (str=="XY_PLANE") text.setAxisAlignment(osgText::Text::XY_PLANE);
        else if (str=="REVERSED_XY_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_XY_PLANE);
        else if (str=="XZ_PLANE") text.setAxisAlignment(osgText::Text::XZ_PLANE);
        else if (str=="REVERSED_XZ_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_XZ_PLANE);
        else if (str=="YZ_PLANE") text.setAxisAlignment(osgText::Text::YZ_PLANE);
        else if (str=="REVERSED_YZ_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_YZ_PLANE);
        else if (str=="SCREEN") text.setAxisAlignment(osgText::Text::SCREEN);
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("rotation"))
    {
        osg::Vec4 rotation;
        if (fr[1].getFloat(rotation.x()) && fr[2].getFloat(rotation.y()) && fr[3].getFloat(rotation.z()) && fr[4].getFloat(rotation.w()))
        {
            text.setRotation(rotation);
            fr += 4;
            itAdvanced = true;
        }
    }

    if (fr.matchSequence("autoRotateToScreen TRUE"))
    {
        text.setAutoRotateToScreen(true);
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("autoScaleToLimitScreenSizeToFontResolution TRUE"))
    {
        text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("layout %w") && fr[1].getStr())
    {
        std::string str = fr[1].getStr();
        if      (str=="LEFT_TO_RIGHT") text.setLayout(osgText::Text::LEFT_TO_RIGHT);
        else if (str=="RIGHT_TO_LEFT") text.setLayout(osgText::Text::RIGHT_TO_LEFT);
        else if (str=="VERTICAL") text.setLayout(osgText::Text::VERTICAL);
        fr += 2;
        itAdvanced = true;
    }

    // position
    if (fr[0].matchWord("position"))
    {
        osg::Vec3 p;
        if (fr[1].getFloat(p.x()) && fr[2].getFloat(p.y()) && fr[3].getFloat(p.z()))
        {
            text.setPosition(p);
            fr += 4;
            itAdvanced = true;
        }
    }

    // color
    if (fr[0].matchWord("color"))
    {
        osg::Vec4 c;
        if (fr[1].getFloat(c.x()) && fr[2].getFloat(c.y()) && fr[3].getFloat(c.z()) && fr[4].getFloat(c.w()))
        {
            text.setColor(c);
            fr += 4;
            itAdvanced = true;
        }
    }

    // draw mode
    if (fr[0].matchWord("drawMode"))
    {
        int i;
        if (fr[1].getInt(i)) {
            text.setDrawMode(i);
            fr += 2;
            itAdvanced = true;
        }
    }

    // text
    if (fr.matchSequence("text %s") && fr[1].getStr()) {
        text.setText(std::string(fr[1].getStr()));
        fr += 2;
        itAdvanced = true;
    }

    if (fr.matchSequence("text %i {"))
    {
        // pre 0.9.3 releases..
        int entry = fr[0].getNoNestedBrackets();

        int capacity;
        fr[1].getInt(capacity);

        osgText::String str;
        str.reserve(capacity);

        fr += 3;

        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int c;
            if (fr[0].getUInt(c))
            {
                ++fr;
                str.push_back(c);
            }
            else
            {
                ++fr;
            }
        }

        text.setText(str);

        itAdvanced = true;
        ++fr;
    }

    return itAdvanced;
}

bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
    const osgText::Text &text = static_cast<const osgText::Text &>(obj);

    if (text.getFont())
    {
        fw.indent() << "font " << text.getFont()->getFileName() << std::endl;
    }

    // font resolution
    fw.indent() << "fontResolution " << text.getFontWidth() << " " << text.getFontHeight() << std::endl;

    // charater size.
    fw.indent() << "characterSize " << text.getCharacterHeight() << " " << text.getCharacterAspectRatio() << std::endl;

    fw.indent() << "characterSizeMode ";
    switch(text.getCharacterSizeMode())
    {
      case osgText::Text::OBJECT_COORDS : fw<<"OBJECT_COORDS"<<std::endl; break;
      case osgText::Text::SCREEN_COORDS : fw<<"SCREEN_COORDS"<<std::endl; break;
      case osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT: fw<<"OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT"<<std::endl; break;
    }

    // maximum dimension of text box.
    if (text.getMaximumWidth()>0.0f)
    {
        fw.indent() << "maximumWidth " << text.getMaximumWidth() << std::endl;
    }

    if (text.getMaximumHeight()>0.0f)
    {
        fw.indent() << "maximumHeight " << text.getMaximumHeight() << std::endl;
    }

    // alignment
    fw.indent() << "alignment ";
    switch(text.getAlignment())
    {
      case osgText::Text::LEFT_TOP:        fw << "LEFT_TOP" << std::endl; break;
      case osgText::Text::LEFT_CENTER :    fw << "LEFT_CENTER" << std::endl; break;
      case osgText::Text::LEFT_BOTTOM :    fw << "LEFT_BOTTOM" << std::endl; break;

      case osgText::Text::CENTER_TOP:      fw << "CENTER_TOP" << std::endl; break;
      case osgText::Text::CENTER_CENTER:   fw << "CENTER_CENTER" << std::endl; break;
      case osgText::Text::CENTER_BOTTOM:   fw << "CENTER_BOTTOM" << std::endl; break;

      case osgText::Text::RIGHT_TOP:       fw << "RIGHT_TOP" << std::endl; break;
      case osgText::Text::RIGHT_CENTER:    fw << "RIGHT_CENTER" << std::endl; break;
      case osgText::Text::RIGHT_BOTTOM:    fw << "RIGHT_BOTTOM" << std::endl; break;

      case osgText::Text::LEFT_BASE_LINE:  fw << "LEFT_BASE_LINE" << std::endl; break;
      case osgText::Text::CENTER_BASE_LINE:fw << "CENTER_BASE_LINE" << std::endl; break;
      case osgText::Text::RIGHT_BASE_LINE: fw << "RIGHT_BASE_LINE" << std::endl; break;

      case osgText::Text::LEFT_BOTTOM_BASE_LINE:  fw << "LEFT_BOTTOM_BASE_LINE" << std::endl; break;
      case osgText::Text::CENTER_BOTTOM_BASE_LINE:fw << "CENTER_BOTTOM_BASE_LINE" << std::endl; break;
      case osgText::Text::RIGHT_BOTTOM_BASE_LINE: fw << "RIGHT_BOTTOM_BASE_LINE" << std::endl; break;
    };

    if (!text.getRotation().zeroRotation())
    {
        fw.indent() << "rotation " << text.getRotation() << std::endl;
    }

    if (text.getAutoRotateToScreen())
    {
        fw.indent() << "autoRotateToScreen TRUE"<< std::endl;
    }

    // layout
    fw.indent() << "layout ";
    switch(text.getLayout())
    {
      case osgText::Text::LEFT_TO_RIGHT: fw << "LEFT_TO_RIGHT" << std::endl; break;
      case osgText::Text::RIGHT_TO_LEFT: fw << "RIGHT_TO_LEFT" << std::endl; break;
      case osgText::Text::VERTICAL: fw << "VERTICAL" << std::endl; break;
    };

    // position
    osg::Vec3 p = text.getPosition();
    fw.indent() << "position " << p.x() << " " << p.y() << " " << p.z() << std::endl;

    // color
    osg::Vec4 c = text.getColor();
    fw.indent() << "color " << c.x() << " " << c.y() << " " << c.z() << " " << c.w() << std::endl;

    // draw mode
    fw.indent() << "drawMode " << text.getDrawMode() << std::endl;

    // text
    const osgText::String& textstring = text.getText();
    bool isACString = true;
    osgText::String::const_iterator itr;
    for(itr=textstring.begin();
        itr!=textstring.end() && isACString;
        ++itr)
    {
        if (*itr==0 || *itr>256) isACString=false;
    }
    if (isACString)
    {
        std::string str;

        for(itr=textstring.begin();
            itr!=textstring.end();
            ++itr)
        {
            str += (char)(*itr);
        }

        //std::copy(textstring.begin(),textstring.end(),std::back_inserter(str));

        fw.indent() << "text " << fw.wrapString(str) << std::endl;
    }
    else
    {
        // do it the hardway...output each character as an int
        fw.indent() << "text "<<textstring.size()<<std::endl;;
        osgDB::writeArray(fw,textstring.begin(),textstring.end());
    }

    return true;
}
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

#include <osg/ApplicationUsage>
#include <osg/Timer>
#include <osg/Notify>

#include <osgUtil/DisplayRequirementsVisitor>
#include <osgDB/FileUtils>

#include <osgProducer/OsgCameraGroup>

using namespace Producer;
using namespace osgProducer;

class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback
{
public:

    RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):
        _cameraGroup(cameraGroup),
        _sceneHandler(sceneHandler) {}

    virtual void operator()( const Producer::RenderSurface & rs)
    {

        osg::Timer timer;
        osg::Timer_t start_t = timer.tick();

        if (_cameraGroup->getRealizeCallback())
        {
            (*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);
        }
        else if (_sceneHandler) _sceneHandler->init();

        osg::Timer_t end_t = timer.tick();
        double time = timer.delta_m(start_t,end_t);
        osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl;

    }

    OsgCameraGroup* _cameraGroup;
    OsgSceneHandler* _sceneHandler;

};

std::string findCameraConfigFile(const std::string& configFile)
{
    std::string foundFile = osgDB::findDataFile(configFile);
    if (foundFile.empty()) return "";
    else return foundFile;
}

std::string extractCameraConfigFile(osg::ArgumentParser& arguments)
{
    // report the usage options.
    if (arguments.getApplicationUsage())
    {
        arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file");
    }

    std::string filename;
    if (arguments.read("-c",filename)) return findCameraConfigFile(filename);

    char *ptr;
    if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) )
    {
        osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl;
        return findCameraConfigFile(ptr);
    }

    return "";
}

OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup()
{
    _init();
    _applicationUsage = osg::ApplicationUsage::instance();
}

OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg):
    Producer::CameraGroup(cfg)
{
    _init();
    _applicationUsage = osg::ApplicationUsage::instance();
}

OsgCameraGroup::OsgCameraGroup(const std::string& configFile):
    Producer::CameraGroup(findCameraConfigFile(configFile))
{
    _init();
    _applicationUsage = osg::ApplicationUsage::instance();
}

OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments):
    Producer::CameraGroup(extractCameraConfigFile(arguments))
{
    _init();
    _applicationUsage = arguments.getApplicationUsage();
}

void OsgCameraGroup::_init()
{
    _thread_model = ThreadPerCamera;

    _scene_data = NULL;
    _global_stateset = NULL;
    _background_color.set( 0.2f, 0.2f, 0.4f, 1.0f );
    _LODScale = 1.0f;

    _fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE;
    _fusionDistanceValue = 1.0f;

    _initialized = false;

    if (!_frameStamp) _frameStamp = new osg::FrameStamp;

    // set up the maximum number of graphics contexts, before loading the scene graph
    // to ensure that texture objects and display buffers are configured to the correct size.
    osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() );

}

void OsgCameraGroup::setSceneData( osg::Node *scene )
{
    if (_scene_data==scene) return;

    if (_scene_decorator.valid() && _scene_data.valid())
    {
        _scene_decorator->removeChild(_scene_data.get());
    }

    _scene_data = scene;

    if (_scene_decorator.valid() && _scene_data.valid())
    {
        _scene_decorator->addChild(scene);
    }

    setUpSceneViewsWithData();
}

void OsgCameraGroup::setSceneDecorator( osg::Group* decorator)
{
    if (_scene_decorator==decorator) return;

    _scene_decorator = decorator;

    if (_scene_data.valid() && decorator)
    {
        decorator->addChild(_scene_data.get());
    }
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setUpSceneViewsWithData()
{
    for(SceneHandlerList::iterator  p = _shvec.begin(); p != _shvec.end(); p++ )
    {
        if (_scene_decorator.valid())
        {
            (*p)->setSceneData( _scene_decorator.get() );
        }
        else if (_scene_data.valid())
        {
            (*p)->setSceneData( _scene_data.get() );
        }
        else
        {
            (*p)->setSceneData( 0 );
        }

        (*p)->setFrameStamp( _frameStamp.get() );
        (*p)->setGlobalStateSet( _global_stateset.get() );
        (*p)->setBackgroundColor( _background_color );
        (*p)->setLODScale( _LODScale );
        (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
        (*p)->getState()->reset();
    }
}

void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )
{
    _frameStamp = fs;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset )
{
    _global_stateset = sset;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor )
{
    _background_color = backgroundColor;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setLODScale( float scale )
{
    // need to set a local variable?
    _LODScale = scale;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)
{
    // need to set a local variable?
    _fusionDistanceMode = mode;
    _fusionDistanceValue = value;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::advance()
{
    if( !_initialized ) return;
    CameraGroup::advance();
}

bool OsgCameraGroup::realize( ThreadingModel thread_model )
{
    if( _realized ) return _realized;
    _thread_model = thread_model;
    return realize();
}

// small visitor to check for the existance of particle systems,
// which currently arn't thread safe, so we would need to disable
// multithreading of cull and draw.
class SearchForParticleNodes : public osg::NodeVisitor
{
public:
    SearchForParticleNodes():
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _foundParticles(false)
    {
    }

    virtual void apply(osg::Node& node)
    {
        if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true;
        if (!_foundParticles) traverse(node);
    }

    bool _foundParticles;
};

bool OsgCameraGroup::realize()
{
    if( _initialized ) return _realized;

    if (!_ds) _ds = osg::DisplaySettings::instance();

    _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );

    _shvec.clear();

    osg::Node* node = getTopMostSceneData();
    if (node)
    {
        // traverse the scene graphs gathering the requirements of the OpenGL buffers.
        osgUtil::DisplayRequirementsVisitor drv;
        drv.setDisplaySettings(_ds.get());
        node->accept(drv);
    }

    unsigned int numMultiSamples = 0;

    #ifdef __sgi
    // switch on anti-aliasing by default, just in case we have an Onyx :-)
    numMultiSamples = 4;
    #endif

    // set up each render stage to clear the appropriate buffers.
    GLbitfield clear_mask=0;
    if (_ds->getRGB())              clear_mask |= GL_COLOR_BUFFER_BIT;
    if (_ds->getDepthBuffer())      clear_mask |= GL_DEPTH_BUFFER_BIT;
    if (_ds->getStencilBuffer())    clear_mask |= GL_STENCIL_BUFFER_BIT;

    for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
    {
        Producer::Camera *cam = _cfg->getCamera(i);

        // create the scene handler.
        osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());
        sh->setDefaults();
        sh->getState()->setContextID(i);

        _shvec.push_back( sh );
        cam->setSceneHandler( sh );

        // set up the clear mask.
        osgUtil::RenderStage *stage = sh->getRenderStage();
        if (stage) stage->setClearMask(clear_mask);

        // set the realize callback.
        Producer::RenderSurface* rs = cam->getRenderSurface();
        rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));

        // set up the visual chooser.
        if (_ds.valid() || numMultiSamples!=0)
        {

            Producer::VisualChooser* rs_vc = rs->getVisualChooser();
            if (!rs_vc)
            {
                rs_vc = new Producer::VisualChooser;
                rs_vc->setSimpleConfiguration();
                rs->setVisualChooser(rs_vc);
            }
            if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();
            if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());
            if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());

            rs_vc->setDepthSize(24);

            if (numMultiSamples)
            {
                #if defined( GLX_SAMPLES_SGIS )
                    rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS,  numMultiSamples);
                #endif
                #if defined( GLX_SAMPLES_BUFFER_SGIS )
                    rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS,  1);
                #endif
            }
        }
    }

    if( _global_stateset == NULL && _shvec.size() > 0 )
    {
        SceneHandlerList::iterator p = _shvec.begin();
        _global_stateset = (*p)->getGlobalStateSet();
    }

    setUpSceneViewsWithData();

    if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)
    {
        SearchForParticleNodes sfpn;
        getTopMostSceneData()->accept(sfpn);
        if (sfpn._foundParticles)
        {
            osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl;
            osg::notify(osg::INFO)<<"         to avoid threading problems in osgParticle."<<std::endl;
            _thread_model = Producer::CameraGroup::SingleThreaded;
        }
    }

    _initialized = CameraGroup::realize();

    return _initialized;
}

osg::Node* OsgCameraGroup::getTopMostSceneData()
{
    if (_scene_decorator.valid())
        return _scene_decorator.get();
    else
        return _scene_data.get();
}

const osg::Node* OsgCameraGroup::getTopMostSceneData() const
{
    if (_scene_decorator.valid())
        return _scene_decorator.get();
    else
        return _scene_data.get();
}

void OsgCameraGroup::setView(const osg::Matrix& matrix)
{
    Producer::Matrix pm(matrix.ptr());
    CameraGroup::setView(pm);
}

const osg::Matrix OsgCameraGroup::getViewMatrix() const
{
    osg::Matrix matrix;
    if (_cfg && _cfg->getNumberOfCameras()>=1)
    {
        Producer::Camera *cam = _cfg->getCamera(0);
        matrix.set(cam->getViewMatrix());
    }
    return matrix;
}

void OsgCameraGroup::frame()
{
    osg::Node* node = getTopMostSceneData();
    if (node) node->getBound();

    CameraGroup::frame();
    _frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 );
}

<commit_msg>Added a setting of OsgCameraGroup::_applicateUsage to ApplicationUsage::instance() by default.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

#include <osg/ApplicationUsage>
#include <osg/Timer>
#include <osg/Notify>

#include <osgUtil/DisplayRequirementsVisitor>
#include <osgDB/FileUtils>

#include <osgProducer/OsgCameraGroup>

using namespace Producer;
using namespace osgProducer;

class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback
{
public:

    RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):
        _cameraGroup(cameraGroup),
        _sceneHandler(sceneHandler) {}

    virtual void operator()( const Producer::RenderSurface & rs)
    {

        osg::Timer timer;
        osg::Timer_t start_t = timer.tick();

        if (_cameraGroup->getRealizeCallback())
        {
            (*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);
        }
        else if (_sceneHandler) _sceneHandler->init();

        osg::Timer_t end_t = timer.tick();
        double time = timer.delta_m(start_t,end_t);
        osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl;

    }

    OsgCameraGroup* _cameraGroup;
    OsgSceneHandler* _sceneHandler;

};

std::string findCameraConfigFile(const std::string& configFile)
{
    std::string foundFile = osgDB::findDataFile(configFile);
    if (foundFile.empty()) return "";
    else return foundFile;
}

std::string extractCameraConfigFile(osg::ArgumentParser& arguments)
{
    // report the usage options.
    if (arguments.getApplicationUsage())
    {
        arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file");
    }

    std::string filename;
    if (arguments.read("-c",filename)) return findCameraConfigFile(filename);

    char *ptr;
    if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) )
    {
        osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl;
        return findCameraConfigFile(ptr);
    }

    return "";
}

OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup()
{
    _init();
}

OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg):
    Producer::CameraGroup(cfg)
{
    _init();
}

OsgCameraGroup::OsgCameraGroup(const std::string& configFile):
    Producer::CameraGroup(findCameraConfigFile(configFile))
{
    _init();
}

OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments):
    Producer::CameraGroup(extractCameraConfigFile(arguments))
{
    _init();
    _applicationUsage = arguments.getApplicationUsage();
}

void OsgCameraGroup::_init()
{
    _thread_model = ThreadPerCamera;

    _scene_data = NULL;
    _global_stateset = NULL;
    _background_color.set( 0.2f, 0.2f, 0.4f, 1.0f );
    _LODScale = 1.0f;

    _fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE;
    _fusionDistanceValue = 1.0f;

    _initialized = false;

    if (!_frameStamp) _frameStamp = new osg::FrameStamp;

    // set up the maximum number of graphics contexts, before loading the scene graph
    // to ensure that texture objects and display buffers are configured to the correct size.
    osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() );

    _applicationUsage = osg::ApplicationUsage::instance();
}

void OsgCameraGroup::setSceneData( osg::Node *scene )
{
    if (_scene_data==scene) return;

    if (_scene_decorator.valid() && _scene_data.valid())
    {
        _scene_decorator->removeChild(_scene_data.get());
    }

    _scene_data = scene;

    if (_scene_decorator.valid() && _scene_data.valid())
    {
        _scene_decorator->addChild(scene);
    }

    setUpSceneViewsWithData();
}

void OsgCameraGroup::setSceneDecorator( osg::Group* decorator)
{
    if (_scene_decorator==decorator) return;

    _scene_decorator = decorator;

    if (_scene_data.valid() && decorator)
    {
        decorator->addChild(_scene_data.get());
    }
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setUpSceneViewsWithData()
{
    for(SceneHandlerList::iterator  p = _shvec.begin(); p != _shvec.end(); p++ )
    {
        if (_scene_decorator.valid())
        {
            (*p)->setSceneData( _scene_decorator.get() );
        }
        else if (_scene_data.valid())
        {
            (*p)->setSceneData( _scene_data.get() );
        }
        else
        {
            (*p)->setSceneData( 0 );
        }

        (*p)->setFrameStamp( _frameStamp.get() );
        (*p)->setGlobalStateSet( _global_stateset.get() );
        (*p)->setBackgroundColor( _background_color );
        (*p)->setLODScale( _LODScale );
        (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
        (*p)->getState()->reset();
    }
}

void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )
{
    _frameStamp = fs;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset )
{
    _global_stateset = sset;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor )
{
    _background_color = backgroundColor;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setLODScale( float scale )
{
    // need to set a local variable?
    _LODScale = scale;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)
{
    // need to set a local variable?
    _fusionDistanceMode = mode;
    _fusionDistanceValue = value;
    setUpSceneViewsWithData();
}

void OsgCameraGroup::advance()
{
    if( !_initialized ) return;
    CameraGroup::advance();
}

bool OsgCameraGroup::realize( ThreadingModel thread_model )
{
    if( _realized ) return _realized;
    _thread_model = thread_model;
    return realize();
}

// small visitor to check for the existance of particle systems,
// which currently arn't thread safe, so we would need to disable
// multithreading of cull and draw.
class SearchForParticleNodes : public osg::NodeVisitor
{
public:
    SearchForParticleNodes():
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _foundParticles(false)
    {
    }

    virtual void apply(osg::Node& node)
    {
        if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true;
        if (!_foundParticles) traverse(node);
    }

    bool _foundParticles;
};

bool OsgCameraGroup::realize()
{
    if( _initialized ) return _realized;

    if (!_ds) _ds = osg::DisplaySettings::instance();

    _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );

    _shvec.clear();

    osg::Node* node = getTopMostSceneData();
    if (node)
    {
        // traverse the scene graphs gathering the requirements of the OpenGL buffers.
        osgUtil::DisplayRequirementsVisitor drv;
        drv.setDisplaySettings(_ds.get());
        node->accept(drv);
    }

    unsigned int numMultiSamples = 0;

    #ifdef __sgi
    // switch on anti-aliasing by default, just in case we have an Onyx :-)
    numMultiSamples = 4;
    #endif

    // set up each render stage to clear the appropriate buffers.
    GLbitfield clear_mask=0;
    if (_ds->getRGB())              clear_mask |= GL_COLOR_BUFFER_BIT;
    if (_ds->getDepthBuffer())      clear_mask |= GL_DEPTH_BUFFER_BIT;
    if (_ds->getStencilBuffer())    clear_mask |= GL_STENCIL_BUFFER_BIT;

    for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
    {
        Producer::Camera *cam = _cfg->getCamera(i);

        // create the scene handler.
        osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());
        sh->setDefaults();
        sh->getState()->setContextID(i);

        _shvec.push_back( sh );
        cam->setSceneHandler( sh );

        // set up the clear mask.
        osgUtil::RenderStage *stage = sh->getRenderStage();
        if (stage) stage->setClearMask(clear_mask);

        // set the realize callback.
        Producer::RenderSurface* rs = cam->getRenderSurface();
        rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));

        // set up the visual chooser.
        if (_ds.valid() || numMultiSamples!=0)
        {

            Producer::VisualChooser* rs_vc = rs->getVisualChooser();
            if (!rs_vc)
            {
                rs_vc = new Producer::VisualChooser;
                rs_vc->setSimpleConfiguration();
                rs->setVisualChooser(rs_vc);
            }
            if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();
            if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());
            if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());

            rs_vc->setDepthSize(24);

            if (numMultiSamples)
            {
                #if defined( GLX_SAMPLES_SGIS )
                    rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS,  numMultiSamples);
                #endif
                #if defined( GLX_SAMPLES_BUFFER_SGIS )
                    rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS,  1);
                #endif
            }
        }
    }

    if( _global_stateset == NULL && _shvec.size() > 0 )
    {
        SceneHandlerList::iterator p = _shvec.begin();
        _global_stateset = (*p)->getGlobalStateSet();
    }

    setUpSceneViewsWithData();

    if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)
    {
        SearchForParticleNodes sfpn;
        getTopMostSceneData()->accept(sfpn);
        if (sfpn._foundParticles)
        {
            osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl;
            osg::notify(osg::INFO)<<"         to avoid threading problems in osgParticle."<<std::endl;
            _thread_model = Producer::CameraGroup::SingleThreaded;
        }
    }

    _initialized = CameraGroup::realize();

    return _initialized;
}

osg::Node* OsgCameraGroup::getTopMostSceneData()
{
    if (_scene_decorator.valid())
        return _scene_decorator.get();
    else
        return _scene_data.get();
}

const osg::Node* OsgCameraGroup::getTopMostSceneData() const
{
    if (_scene_decorator.valid())
        return _scene_decorator.get();
    else
        return _scene_data.get();
}

void OsgCameraGroup::setView(const osg::Matrix& matrix)
{
    Producer::Matrix pm(matrix.ptr());
    CameraGroup::setView(pm);
}

const osg::Matrix OsgCameraGroup::getViewMatrix() const
{
    osg::Matrix matrix;
    if (_cfg && _cfg->getNumberOfCameras()>=1)
    {
        Producer::Camera *cam = _cfg->getCamera(0);
        matrix.set(cam->getViewMatrix());
    }
    return matrix;
}

void OsgCameraGroup::frame()
{
    osg::Node* node = getTopMostSceneData();
    if (node) node->getBound();

    CameraGroup::frame();
    _frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 );
}

<|endoftext|>


<commit_before>
#include "ui_sc_editor.h"

#include <Scintilla.h>

namespace ImGui
{

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FillRect(ImVec2 pos, ImVec2 size, unsigned int color)
{
	ImGuiWindow* window = GetCurrentWindow();
	ImVec2 currentPos = window->Pos + pos;
    window->DrawList->AddRectFilled(currentPos, currentPos + size, color, 0.0);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

float GetTextWidth(const char* textStart, const char* textEnd)
{
	ImVec2 size = CalcTextSize(textStart, textEnd);
	return size.x;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ImVec2 GetRelativeMousePos()
{
    const ImGuiState* g = GImGui;
    ImGuiWindow* window = GetCurrentWindow();
    ImVec2 pos = g->IO.MousePos - window->Pos;
    ImVec2 zero = ImVec2(0.0f, 0.0f);
    return ImClamp(pos, zero, window->Size);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool IsFocusWindowKeyDown(int key, bool repeat)
{
	if (!GetWindowIsFocused())
		return false;

    //ImGuiState& g = GImGui;
    //ImGuiWindow* window = GetCurrentWindow();

    // Only send keyboard events to selected window

    //if (g.FocusedWindow != window)
     //   return false;

    return IsKeyPressed(key, repeat);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void GetWindowRect(ImGuiWindow* window, ImVec2* pos, ImVec2* size)
{
    *pos = window->Pos;
    *size = window->Size;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void SetWindowRect(ImGuiWindow* window, const ImVec2 pos, const ImVec2 size)
{
    window->PosFloat = pos;
    window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
    window->Size = size;
    window->SizeFull = size;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool IsActiveWindow(ImGuiWindow* window)
{
    const ImGuiState* g = GImGui;
    return g->FocusedWindow == window;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ImScEditor* ScInputText(const char* label, float xSize, float ySize, void (*callback)(void*), void* userData)
{
    ImGuiWindow* window = GetCurrentWindow();
    const ImGuiID id = window->GetID(label);

    (void)callback;
    (void)userData;

    ImGui::BeginChild("Log");

	ImGuiStorage* storage = GetStateStorage();
	ScEditor* editor = (ScEditor*)storage->GetVoidPtr(id);

	if (!editor)
	{
		(void)xSize;
		(void)ySize;
		editor = ScEditor_create((int)xSize, (int)ySize);
		storage->SetVoidPtr(id, (void*)editor);
	}

	ImScEditor* editorInterface = ScEditor_getInterface(editor);

	//float textSize = ImGui::GetTextLineHeightWithSpacing() - 1;
	// TODO: Remove hardcoded value, ask scintilla
	float textSize = 26;

	ScEditor_resize(editor, 0, 0, (int)window->Size.x - 20, (int)window->Size.y);

	int lineCount = (int)editorInterface->SendCommand(SCI_GETLINECOUNT, 0, 0);

	editorInterface->HandleInput();

	ImGuiListClipper clipper(lineCount, textSize);

	//ImVec2 pos = window->DC.CursorPos;

    ScEditor_setDrawList(GetWindowDrawList());
    ScEditor_setFont(GetWindowFont());
	ScEditor_setPos(0.0f, 0.0f);

	//int currentPos = (int)editorInterface->SendCommand(SCN_GETTOPLINE, 0, 0);

	//float scrollPos = ImGui::GetScrollPosY();

	//int iPos = (int)(((int)ImGui::GetScrollPosY()) / (int)(textSize));

	//if (currentPos != iPos)
	//{
	editorInterface->ScrollTo(clipper.DisplayStart);
	//}

	//printf("current pos in scintilla %d - pos sent %d\n", newPos, iPos);

	clipper.End();

    ImGui::EndChild();

	return editorInterface;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}

<commit_msg>Removed usage of GetWindowIsFocused (deprecated)<commit_after>
#include "ui_sc_editor.h"

#include <Scintilla.h>

namespace ImGui
{

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FillRect(ImVec2 pos, ImVec2 size, unsigned int color)
{
	ImGuiWindow* window = GetCurrentWindow();
	ImVec2 currentPos = window->Pos + pos;
    window->DrawList->AddRectFilled(currentPos, currentPos + size, color, 0.0);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

float GetTextWidth(const char* textStart, const char* textEnd)
{
	ImVec2 size = CalcTextSize(textStart, textEnd);
	return size.x;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ImVec2 GetRelativeMousePos()
{
    const ImGuiState* g = GImGui;
    ImGuiWindow* window = GetCurrentWindow();
    ImVec2 pos = g->IO.MousePos - window->Pos;
    ImVec2 zero = ImVec2(0.0f, 0.0f);
    return ImClamp(pos, zero, window->Size);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool IsFocusWindowKeyDown(int key, bool repeat)
{
	if (!IsWindowFocused())
		return false;

	//if (!GetWindowIsFocused())
	//	return false;

    //ImGuiState& g = GImGui;
    //ImGuiWindow* window = GetCurrentWindow();

    // Only send keyboard events to selected window

    //if (g.FocusedWindow != window)
     //   return false;

    return IsKeyPressed(key, repeat);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void GetWindowRect(ImGuiWindow* window, ImVec2* pos, ImVec2* size)
{
    *pos = window->Pos;
    *size = window->Size;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void SetWindowRect(ImGuiWindow* window, const ImVec2 pos, const ImVec2 size)
{
    window->PosFloat = pos;
    window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
    window->Size = size;
    window->SizeFull = size;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool IsActiveWindow(ImGuiWindow* window)
{
    const ImGuiState* g = GImGui;
    return g->FocusedWindow == window;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ImScEditor* ScInputText(const char* label, float xSize, float ySize, void (*callback)(void*), void* userData)
{
    ImGuiWindow* window = GetCurrentWindow();
    const ImGuiID id = window->GetID(label);

    (void)callback;
    (void)userData;

    //ImGui::BeginChild("Log");

	ImGuiStorage* storage = GetStateStorage();
	ScEditor* editor = (ScEditor*)storage->GetVoidPtr(id);

	if (!editor)
	{
		(void)xSize;
		(void)ySize;
		editor = ScEditor_create((int)xSize, (int)ySize);
		storage->SetVoidPtr(id, (void*)editor);
	}

	ImScEditor* editorInterface = ScEditor_getInterface(editor);

	//float textSize = ImGui::GetTextLineHeightWithSpacing() - 1;
	// TODO: Remove hardcoded value, ask scintilla
	float textSize = 26;

	ScEditor_resize(editor, 0, 0, (int)window->Size.x - 20, (int)window->Size.y);

	int lineCount = (int)editorInterface->SendCommand(SCI_GETLINECOUNT, 0, 0);

	editorInterface->HandleInput();

	ImGuiListClipper clipper(lineCount, textSize);

	//ImVec2 pos = window->DC.CursorPos;

    ScEditor_setDrawList(GetWindowDrawList());
    ScEditor_setFont(GetWindowFont());
	ScEditor_setPos(0.0f, 14.0f);

	//int currentPos = (int)editorInterface->SendCommand(SCN_GETTOPLINE, 0, 0);

	//float scrollPos = ImGui::GetScrollPosY();

	//int iPos = (int)(((int)ImGui::GetScrollPosY()) / (int)(textSize));

	//if (currentPos != iPos)
	//{
	editorInterface->ScrollTo(clipper.DisplayStart);
	//}

	//printf("current pos in scintilla %d - pos sent %d\n", newPos, iPos);

	clipper.End();

    //ImGui::EndChild();

	return editorInterface;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}

<|endoftext|>


<commit_before>/**
 * projectM -- Milkdrop-esque visualisation SDK
 * Copyright (C)2003-2007 projectM Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * See 'LICENSE.txt' included within this release
 *
 */
/**
 * $Id$
 *
 * Beat detection class. Takes decompressed sound buffers and returns
 * various characteristics
 *
 * $Log$
 *
 */

#ifndef _BEAT_DETECT_H
#define _BEAT_DETECT_H

#include "PCM.hpp"

class BeatDetect
{
	public:
		/** Vars */
		float beat_buffer[32][80],
		beat_instant[32],
		beat_history[32];
		float beat_val[32],
		beat_att[32],
		beat_variance[32];
		int beat_buffer_pos;
		float vol_buffer[80],
		vol_instant,
		vol_history;

		float treb ;
		float mid ;
		float bass ;
		float vol_old ;
		float beat_sensitivity;
		float treb_att ;
		float mid_att ;
		float bass_att ;
		float vol;

		PCM *pcm;

		/** Methods */
		DLLEXPORT BeatDetect(PCM *pcm);
		DLLEXPORT ~BeatDetect();
		void initBeatDetect();
		void reset();
		void detectFromSamples();
		void getBeatVals ( float *vdataL, float *vdataR );

};

#endif /** !_BEAT_DETECT_H */
<commit_msg>removed DLLEXPORT from beatdetect (was it necessary?)<commit_after>/**
 * projectM -- Milkdrop-esque visualisation SDK
 * Copyright (C)2003-2007 projectM Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * See 'LICENSE.txt' included within this release
 *
 */
/**
 * $Id$
 *
 * Beat detection class. Takes decompressed sound buffers and returns
 * various characteristics
 *
 * $Log$
 *
 */

#ifndef _BEAT_DETECT_H
#define _BEAT_DETECT_H

#include "PCM.hpp"

class BeatDetect
{
	public:
		/** Vars */
		float beat_buffer[32][80],
		beat_instant[32],
		beat_history[32];
		float beat_val[32],
		beat_att[32],
		beat_variance[32];
		int beat_buffer_pos;
		float vol_buffer[80],
		vol_instant,
		vol_history;

		float treb ;
		float mid ;
		float bass ;
		float vol_old ;
		float beat_sensitivity;
		float treb_att ;
		float mid_att ;
		float bass_att ;
		float vol;

		PCM *pcm;

		/** Methods */
		BeatDetect(PCM *pcm);
		~BeatDetect();
		void initBeatDetect();
		void reset();
		void detectFromSamples();
		void getBeatVals ( float *vdataL, float *vdataR );

};

#endif /** !_BEAT_DETECT_H */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: exprnode.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 17:41:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#define _NTSDK      // wg. HUGE_VAL MH
#define HUGE_VAL    HUGE
#include <math.h>

#include <rtl/math.hxx>
#include "sbcomp.hxx"
#include "expr.hxx"

//////////////////////////////////////////////////////////////////////////

SbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, SbiToken t, SbiExprNode* r )
{
    BaseInit( p );

    pLeft     = l;
    pRight    = r;
    eTok      = t;
    nVal      = 0;
    eType     = SbxVARIANT;     // Nodes sind immer Variant
    eNodeType = SbxNODE;
    bComposite= TRUE;
}

SbiExprNode::SbiExprNode( SbiParser* p, double n, SbxDataType t )
{
    BaseInit( p );

    eType     = t;
    eNodeType = SbxNUMVAL;
    nVal      = n;
}

SbiExprNode::SbiExprNode( SbiParser* p, const String& rVal )
{
    BaseInit( p );

    eType     = SbxSTRING;
    eNodeType = SbxSTRVAL;
    aStrVal   = rVal;
}

SbiExprNode::SbiExprNode( SbiParser* p, const SbiSymDef& r, SbxDataType t, SbiExprList* l )
{
    BaseInit( p );

    eType     = ( t == SbxVARIANT ) ? r.GetType() : t;
    eNodeType = SbxVARVAL;
    aVar.pDef = (SbiSymDef*) &r;
    aVar.pPar = l;
    aVar.pNext= NULL;

    // Funktionsergebnisse sind nie starr
    bComposite= BOOL( aVar.pDef->GetProcDef() != NULL );
}

// #120061 TypeOf
SbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, USHORT nId )
{
    BaseInit( p );

    pLeft      = l;
    eType      = SbxBOOL;
    eNodeType  = SbxTYPEOF;
    nTypeStrId = nId;
}

// AB: 17.12.95, Hilfsfunktion fuer Ctor fuer einheitliche Initialisierung
void SbiExprNode::BaseInit( SbiParser* p )
{
    pGen = &p->aGen;
    eTok = NIL;
    pLeft       = NULL;
    pRight      = NULL;
    pWithParent = NULL;
    bComposite  = FALSE;
    bError      = FALSE;
}

SbiExprNode::~SbiExprNode()
{
    delete pLeft;
    delete pRight;
    if( IsVariable() )
    {
        delete aVar.pPar;
        delete aVar.pNext;
    }
}

SbiSymDef* SbiExprNode::GetVar()
{
    if( eNodeType == SbxVARVAL )
        return aVar.pDef;
    else
        return NULL;
}

SbiSymDef* SbiExprNode::GetRealVar()
{
    SbiExprNode* p = GetRealNode();
    if( p )
        return p->GetVar();
    else
        return NULL;
}

// AB: 18.12.95
SbiExprNode* SbiExprNode::GetRealNode()
{
    if( eNodeType == SbxVARVAL )
    {
        SbiExprNode* p = this;
        while( p->aVar.pNext )
            p = p->aVar.pNext;
        return p;
    }
    else
        return NULL;
}

// Diese Methode setzt den Typ um, falls er in den Integer-Bereich hineinpasst

BOOL SbiExprNode::IsIntConst()
{
    if( eNodeType == SbxNUMVAL )
    {
        if( eType >= SbxINTEGER && eType <= SbxDOUBLE )
        {
            double n;
            if( nVal >= SbxMININT && nVal <= SbxMAXINT && modf( nVal, &n ) == 0 )
            {
                nVal = (double) (short) nVal;
                eType = SbxINTEGER;
                return TRUE;
            }
        }
    }
    return FALSE;
}

BOOL SbiExprNode::IsNumber()
{
    return BOOL( eNodeType == SbxNUMVAL );
}

BOOL SbiExprNode::IsString()
{
    return BOOL( eNodeType == SbxSTRVAL );
}

BOOL SbiExprNode::IsVariable()
{
    return BOOL( eNodeType == SbxVARVAL );
}

BOOL SbiExprNode::IsLvalue()
{
    return IsVariable();
}

// Ermitteln der Tiefe eines Baumes

short SbiExprNode::GetDepth()
{
    if( IsOperand() ) return 0;
    else
    {
        short d1 = pLeft->GetDepth();
        short d2 = pRight->GetDepth();
        return( (d1 < d2 ) ? d2 : d1 ) + 1;
    }
}

// Abgleich eines Baumes:
// 1. Constant Folding
// 2. Typabgleich
// 3. Umwandlung der Operanden in Strings
// 4. Hochziehen der Composite- und Error-Bits

void SbiExprNode::Optimize()
{
    FoldConstants();
    CollectBits();
}

// Hochziehen der Composite- und Fehlerbits

void SbiExprNode::CollectBits()
{
    if( pLeft )
    {
        pLeft->CollectBits();
        bError |= pLeft->bError;
        bComposite |= pLeft->bComposite;
    }
    if( pRight )
    {
        pRight->CollectBits();
        bError |= pRight->bError;
        bComposite |= pRight->bComposite;
    }
}

// Kann ein Zweig umgeformt werden, wird TRUE zurueckgeliefert. In diesem
// Fall ist das Ergebnis im linken Zweig.

void SbiExprNode::FoldConstants()
{
    if( IsOperand() ) return;
    pLeft->FoldConstants();
    if( pRight )
    {
        pRight->FoldConstants();
        if( pLeft->IsConstant() && pRight->IsConstant()
            && pLeft->eNodeType == pRight->eNodeType )
        {
            CollectBits();
            if( eTok == CAT )
                // CAT verbindet auch zwei Zahlen miteinander!
                eType = SbxSTRING;
            if( pLeft->eType == SbxSTRING )
                // Kein Type Mismatch!
                eType = SbxSTRING;
            if( eType == SbxSTRING )
            {
                String rl( pLeft->GetString() );
                String rr( pRight->GetString() );
                delete pLeft; pLeft = NULL;
                delete pRight; pRight = NULL;
                bComposite = FALSE;
                if( eTok == PLUS || eTok == CAT )
                {
                    eTok = CAT;
                    // Verkettung:
                    aStrVal = rl;
                    aStrVal += rr;
                    eType = SbxSTRING;
                    eNodeType = SbxSTRVAL;
                }
                else
                {
                    eType = SbxDOUBLE;
                    eNodeType = SbxNUMVAL;
                    StringCompare eRes = rr.CompareTo( rl );
                    switch( eTok )
                    {
                        case EQ:
                            nVal = ( eRes == COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE;
                            break;
                        case NE:
                            nVal = ( eRes != COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE;
                            break;
                        case LT:
                            nVal = ( eRes == COMPARE_LESS ) ? SbxTRUE : SbxFALSE;
                            break;
                        case GT:
                            nVal = ( eRes == COMPARE_GREATER ) ? SbxTRUE : SbxFALSE;
                            break;
                        case LE:
                            nVal = ( eRes != COMPARE_GREATER ) ? SbxTRUE : SbxFALSE;
                            break;
                        case GE:
                            nVal = ( eRes != COMPARE_LESS ) ? SbxTRUE : SbxFALSE;
                            break;
                        default:
                            pGen->GetParser()->Error( SbERR_CONVERSION );
                            bError = TRUE;
                    }
                }
            }
            else
            {
                double nl = pLeft->nVal;
                double nr = pRight->nVal;
                long ll = 0, lr = 0;
                long llMod = 0, lrMod = 0;
                if( ( eTok >= AND && eTok <= IMP )
                   || eTok == IDIV || eTok == MOD )
                {
                    // Integer-Operationen
                    BOOL err = FALSE;
                    if( nl > SbxMAXLNG ) err = TRUE, nl = SbxMAXLNG;
                    else
                    if( nl < SbxMINLNG ) err = TRUE, nl = SbxMINLNG;
                    if( nr > SbxMAXLNG ) err = TRUE, nr = SbxMAXLNG;
                    else
                    if( nr < SbxMINLNG ) err = TRUE, nr = SbxMINLNG;
                    ll = (long) nl; lr = (long) nr;
                    llMod = (long) (nl < 0 ? nl - 0.5 : nl + 0.5);
                    lrMod = (long) (nr < 0 ? nr - 0.5 : nr + 0.5);
                    if( err )
                    {
                        pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );
                        bError = TRUE;
                    }
                }
                BOOL bBothInt = BOOL( pLeft->eType < SbxSINGLE
                                   && pRight->eType < SbxSINGLE );
                delete pLeft; pLeft = NULL;
                delete pRight; pRight = NULL;
                nVal = 0;
                eType = SbxDOUBLE;
                eNodeType = SbxNUMVAL;
                bComposite = FALSE;
                BOOL bCheckType = FALSE;
                switch( eTok )
                {
                    case EXPON:
                        nVal = pow( nl, nr ); break;
                    case MUL:
                        bCheckType = TRUE;
                        nVal = nl * nr; break;
                    case DIV:
                        if( !nr )
                        {
                            pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;
                            bError = TRUE;
                        } else nVal = nl / nr;
                        break;
                    case PLUS:
                        bCheckType = TRUE;
                        nVal = nl + nr; break;
                    case MINUS:
                        bCheckType = TRUE;
                        nVal = nl - nr; break;
                    case EQ:
                        nVal = ( nl == nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case NE:
                        nVal = ( nl != nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case LT:
                        nVal = ( nl <  nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case GT:
                        nVal = ( nl >  nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case LE:
                        nVal = ( nl <= nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case GE:
                        nVal = ( nl >= nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case IDIV:
                        if( !lr )
                        {
                            pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;
                            bError = TRUE;
                        } else nVal = ll / lr;
                        eType = SbxLONG; break;
                    case MOD:
                        if( !lr )
                        {
                            pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;
                            bError = TRUE;
                        } else nVal = llMod % lrMod;
                        eType = SbxLONG; break;
                    case AND:
                        nVal = (double) ( ll & lr ); eType = SbxLONG; break;
                    case OR:
                        nVal = (double) ( ll | lr ); eType = SbxLONG; break;
                    case XOR:
                        nVal = (double) ( ll ^ lr ); eType = SbxLONG; break;
                    case EQV:
                        nVal = (double) ( ~ll ^ lr ); eType = SbxLONG; break;
                    case IMP:
                        nVal = (double) ( ~ll | lr ); eType = SbxLONG; break;
                    default: break;
                }

                if( !::rtl::math::isFinite( nVal ) )
                    pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );

                // Den Datentyp wiederherstellen, um Rundungsfehler
                // zu killen
                if( bCheckType && bBothInt
                 && nVal >= SbxMINLNG && nVal <= SbxMAXLNG )
                {
                    // NK-Stellen weg
                    long n = (long) nVal;
                    nVal = n;
                    eType = ( n >= SbxMININT && n <= SbxMAXINT )
                          ? SbxINTEGER : SbxLONG;
                }
            }
        }
    }
    else if( pLeft->IsNumber() )
    {
        nVal = pLeft->nVal;
        delete pLeft;
        pLeft = NULL;
        eType = SbxDOUBLE;
        eNodeType = SbxNUMVAL;
        bComposite = FALSE;
        switch( eTok )
        {
            case NEG:
                nVal = -nVal; break;
            case NOT: {
                // Integer-Operation!
                BOOL err = FALSE;
                if( nVal > SbxMAXLNG ) err = TRUE, nVal = SbxMAXLNG;
                else
                if( nVal < SbxMINLNG ) err = TRUE, nVal = SbxMINLNG;
                if( err )
                {
                    pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );
                    bError = TRUE;
                }
                nVal = (double) ~((long) nVal);
                eType = SbxLONG;
                } break;
            default: break;
        }
    }
    if( eNodeType == SbxNUMVAL )
    {
        // Evtl auf INTEGER falten (wg. besserem Opcode)?
        if( eType == SbxSINGLE || eType == SbxDOUBLE )
        {
            double x;
            if( nVal >= SbxMINLNG && nVal <= SbxMAXLNG
            && !modf( nVal, &x ) )
                eType = SbxLONG;
        }
        if( eType == SbxLONG && nVal >= SbxMININT && nVal <= SbxMAXINT )
            eType = SbxINTEGER;
    }
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.14.24); FILE MERGED 2006/09/01 17:17:02 kaib 1.14.24.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: exprnode.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 10:02:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basic.hxx"

#define _NTSDK      // wg. HUGE_VAL MH
#define HUGE_VAL    HUGE
#include <math.h>

#include <rtl/math.hxx>
#include "sbcomp.hxx"
#include "expr.hxx"

//////////////////////////////////////////////////////////////////////////

SbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, SbiToken t, SbiExprNode* r )
{
    BaseInit( p );

    pLeft     = l;
    pRight    = r;
    eTok      = t;
    nVal      = 0;
    eType     = SbxVARIANT;     // Nodes sind immer Variant
    eNodeType = SbxNODE;
    bComposite= TRUE;
}

SbiExprNode::SbiExprNode( SbiParser* p, double n, SbxDataType t )
{
    BaseInit( p );

    eType     = t;
    eNodeType = SbxNUMVAL;
    nVal      = n;
}

SbiExprNode::SbiExprNode( SbiParser* p, const String& rVal )
{
    BaseInit( p );

    eType     = SbxSTRING;
    eNodeType = SbxSTRVAL;
    aStrVal   = rVal;
}

SbiExprNode::SbiExprNode( SbiParser* p, const SbiSymDef& r, SbxDataType t, SbiExprList* l )
{
    BaseInit( p );

    eType     = ( t == SbxVARIANT ) ? r.GetType() : t;
    eNodeType = SbxVARVAL;
    aVar.pDef = (SbiSymDef*) &r;
    aVar.pPar = l;
    aVar.pNext= NULL;

    // Funktionsergebnisse sind nie starr
    bComposite= BOOL( aVar.pDef->GetProcDef() != NULL );
}

// #120061 TypeOf
SbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, USHORT nId )
{
    BaseInit( p );

    pLeft      = l;
    eType      = SbxBOOL;
    eNodeType  = SbxTYPEOF;
    nTypeStrId = nId;
}

// AB: 17.12.95, Hilfsfunktion fuer Ctor fuer einheitliche Initialisierung
void SbiExprNode::BaseInit( SbiParser* p )
{
    pGen = &p->aGen;
    eTok = NIL;
    pLeft       = NULL;
    pRight      = NULL;
    pWithParent = NULL;
    bComposite  = FALSE;
    bError      = FALSE;
}

SbiExprNode::~SbiExprNode()
{
    delete pLeft;
    delete pRight;
    if( IsVariable() )
    {
        delete aVar.pPar;
        delete aVar.pNext;
    }
}

SbiSymDef* SbiExprNode::GetVar()
{
    if( eNodeType == SbxVARVAL )
        return aVar.pDef;
    else
        return NULL;
}

SbiSymDef* SbiExprNode::GetRealVar()
{
    SbiExprNode* p = GetRealNode();
    if( p )
        return p->GetVar();
    else
        return NULL;
}

// AB: 18.12.95
SbiExprNode* SbiExprNode::GetRealNode()
{
    if( eNodeType == SbxVARVAL )
    {
        SbiExprNode* p = this;
        while( p->aVar.pNext )
            p = p->aVar.pNext;
        return p;
    }
    else
        return NULL;
}

// Diese Methode setzt den Typ um, falls er in den Integer-Bereich hineinpasst

BOOL SbiExprNode::IsIntConst()
{
    if( eNodeType == SbxNUMVAL )
    {
        if( eType >= SbxINTEGER && eType <= SbxDOUBLE )
        {
            double n;
            if( nVal >= SbxMININT && nVal <= SbxMAXINT && modf( nVal, &n ) == 0 )
            {
                nVal = (double) (short) nVal;
                eType = SbxINTEGER;
                return TRUE;
            }
        }
    }
    return FALSE;
}

BOOL SbiExprNode::IsNumber()
{
    return BOOL( eNodeType == SbxNUMVAL );
}

BOOL SbiExprNode::IsString()
{
    return BOOL( eNodeType == SbxSTRVAL );
}

BOOL SbiExprNode::IsVariable()
{
    return BOOL( eNodeType == SbxVARVAL );
}

BOOL SbiExprNode::IsLvalue()
{
    return IsVariable();
}

// Ermitteln der Tiefe eines Baumes

short SbiExprNode::GetDepth()
{
    if( IsOperand() ) return 0;
    else
    {
        short d1 = pLeft->GetDepth();
        short d2 = pRight->GetDepth();
        return( (d1 < d2 ) ? d2 : d1 ) + 1;
    }
}

// Abgleich eines Baumes:
// 1. Constant Folding
// 2. Typabgleich
// 3. Umwandlung der Operanden in Strings
// 4. Hochziehen der Composite- und Error-Bits

void SbiExprNode::Optimize()
{
    FoldConstants();
    CollectBits();
}

// Hochziehen der Composite- und Fehlerbits

void SbiExprNode::CollectBits()
{
    if( pLeft )
    {
        pLeft->CollectBits();
        bError |= pLeft->bError;
        bComposite |= pLeft->bComposite;
    }
    if( pRight )
    {
        pRight->CollectBits();
        bError |= pRight->bError;
        bComposite |= pRight->bComposite;
    }
}

// Kann ein Zweig umgeformt werden, wird TRUE zurueckgeliefert. In diesem
// Fall ist das Ergebnis im linken Zweig.

void SbiExprNode::FoldConstants()
{
    if( IsOperand() ) return;
    pLeft->FoldConstants();
    if( pRight )
    {
        pRight->FoldConstants();
        if( pLeft->IsConstant() && pRight->IsConstant()
            && pLeft->eNodeType == pRight->eNodeType )
        {
            CollectBits();
            if( eTok == CAT )
                // CAT verbindet auch zwei Zahlen miteinander!
                eType = SbxSTRING;
            if( pLeft->eType == SbxSTRING )
                // Kein Type Mismatch!
                eType = SbxSTRING;
            if( eType == SbxSTRING )
            {
                String rl( pLeft->GetString() );
                String rr( pRight->GetString() );
                delete pLeft; pLeft = NULL;
                delete pRight; pRight = NULL;
                bComposite = FALSE;
                if( eTok == PLUS || eTok == CAT )
                {
                    eTok = CAT;
                    // Verkettung:
                    aStrVal = rl;
                    aStrVal += rr;
                    eType = SbxSTRING;
                    eNodeType = SbxSTRVAL;
                }
                else
                {
                    eType = SbxDOUBLE;
                    eNodeType = SbxNUMVAL;
                    StringCompare eRes = rr.CompareTo( rl );
                    switch( eTok )
                    {
                        case EQ:
                            nVal = ( eRes == COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE;
                            break;
                        case NE:
                            nVal = ( eRes != COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE;
                            break;
                        case LT:
                            nVal = ( eRes == COMPARE_LESS ) ? SbxTRUE : SbxFALSE;
                            break;
                        case GT:
                            nVal = ( eRes == COMPARE_GREATER ) ? SbxTRUE : SbxFALSE;
                            break;
                        case LE:
                            nVal = ( eRes != COMPARE_GREATER ) ? SbxTRUE : SbxFALSE;
                            break;
                        case GE:
                            nVal = ( eRes != COMPARE_LESS ) ? SbxTRUE : SbxFALSE;
                            break;
                        default:
                            pGen->GetParser()->Error( SbERR_CONVERSION );
                            bError = TRUE;
                    }
                }
            }
            else
            {
                double nl = pLeft->nVal;
                double nr = pRight->nVal;
                long ll = 0, lr = 0;
                long llMod = 0, lrMod = 0;
                if( ( eTok >= AND && eTok <= IMP )
                   || eTok == IDIV || eTok == MOD )
                {
                    // Integer-Operationen
                    BOOL err = FALSE;
                    if( nl > SbxMAXLNG ) err = TRUE, nl = SbxMAXLNG;
                    else
                    if( nl < SbxMINLNG ) err = TRUE, nl = SbxMINLNG;
                    if( nr > SbxMAXLNG ) err = TRUE, nr = SbxMAXLNG;
                    else
                    if( nr < SbxMINLNG ) err = TRUE, nr = SbxMINLNG;
                    ll = (long) nl; lr = (long) nr;
                    llMod = (long) (nl < 0 ? nl - 0.5 : nl + 0.5);
                    lrMod = (long) (nr < 0 ? nr - 0.5 : nr + 0.5);
                    if( err )
                    {
                        pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );
                        bError = TRUE;
                    }
                }
                BOOL bBothInt = BOOL( pLeft->eType < SbxSINGLE
                                   && pRight->eType < SbxSINGLE );
                delete pLeft; pLeft = NULL;
                delete pRight; pRight = NULL;
                nVal = 0;
                eType = SbxDOUBLE;
                eNodeType = SbxNUMVAL;
                bComposite = FALSE;
                BOOL bCheckType = FALSE;
                switch( eTok )
                {
                    case EXPON:
                        nVal = pow( nl, nr ); break;
                    case MUL:
                        bCheckType = TRUE;
                        nVal = nl * nr; break;
                    case DIV:
                        if( !nr )
                        {
                            pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;
                            bError = TRUE;
                        } else nVal = nl / nr;
                        break;
                    case PLUS:
                        bCheckType = TRUE;
                        nVal = nl + nr; break;
                    case MINUS:
                        bCheckType = TRUE;
                        nVal = nl - nr; break;
                    case EQ:
                        nVal = ( nl == nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case NE:
                        nVal = ( nl != nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case LT:
                        nVal = ( nl <  nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case GT:
                        nVal = ( nl >  nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case LE:
                        nVal = ( nl <= nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case GE:
                        nVal = ( nl >= nr ) ? SbxTRUE : SbxFALSE;
                        eType = SbxINTEGER; break;
                    case IDIV:
                        if( !lr )
                        {
                            pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;
                            bError = TRUE;
                        } else nVal = ll / lr;
                        eType = SbxLONG; break;
                    case MOD:
                        if( !lr )
                        {
                            pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;
                            bError = TRUE;
                        } else nVal = llMod % lrMod;
                        eType = SbxLONG; break;
                    case AND:
                        nVal = (double) ( ll & lr ); eType = SbxLONG; break;
                    case OR:
                        nVal = (double) ( ll | lr ); eType = SbxLONG; break;
                    case XOR:
                        nVal = (double) ( ll ^ lr ); eType = SbxLONG; break;
                    case EQV:
                        nVal = (double) ( ~ll ^ lr ); eType = SbxLONG; break;
                    case IMP:
                        nVal = (double) ( ~ll | lr ); eType = SbxLONG; break;
                    default: break;
                }

                if( !::rtl::math::isFinite( nVal ) )
                    pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );

                // Den Datentyp wiederherstellen, um Rundungsfehler
                // zu killen
                if( bCheckType && bBothInt
                 && nVal >= SbxMINLNG && nVal <= SbxMAXLNG )
                {
                    // NK-Stellen weg
                    long n = (long) nVal;
                    nVal = n;
                    eType = ( n >= SbxMININT && n <= SbxMAXINT )
                          ? SbxINTEGER : SbxLONG;
                }
            }
        }
    }
    else if( pLeft->IsNumber() )
    {
        nVal = pLeft->nVal;
        delete pLeft;
        pLeft = NULL;
        eType = SbxDOUBLE;
        eNodeType = SbxNUMVAL;
        bComposite = FALSE;
        switch( eTok )
        {
            case NEG:
                nVal = -nVal; break;
            case NOT: {
                // Integer-Operation!
                BOOL err = FALSE;
                if( nVal > SbxMAXLNG ) err = TRUE, nVal = SbxMAXLNG;
                else
                if( nVal < SbxMINLNG ) err = TRUE, nVal = SbxMINLNG;
                if( err )
                {
                    pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );
                    bError = TRUE;
                }
                nVal = (double) ~((long) nVal);
                eType = SbxLONG;
                } break;
            default: break;
        }
    }
    if( eNodeType == SbxNUMVAL )
    {
        // Evtl auf INTEGER falten (wg. besserem Opcode)?
        if( eType == SbxSINGLE || eType == SbxDOUBLE )
        {
            double x;
            if( nVal >= SbxMINLNG && nVal <= SbxMAXLNG
            && !modf( nVal, &x ) )
                eType = SbxLONG;
        }
        if( eType == SbxLONG && nVal >= SbxMININT && nVal <= SbxMAXINT )
            eType = SbxINTEGER;
    }
}

<|endoftext|>


<commit_before>/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * Copyright Projet JRL-Japan, 2009
 *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * File:      CoMFreezer.cpp
 * Project:   SOT
 * Author:    Pierre Gergondet
 *
 * Version control
 * ===============
 *
 *  $Id$
 *
 * Description
 * ============
 *
 *
 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

#include <sot-core/com-freezer.h>
#include <sot-core/debug.h>
#include <dynamic-graph/factory.h>

using namespace dynamicgraph;
using namespace sot;

DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CoMFreezer, "CoMFreezer");

CoMFreezer::CoMFreezer(const std::string & name)
  : Entity(name)
  , m_lastCoM(3)
  , m_previousPGInProcess(false)
  , m_lastStopTime(-1)

  , CoMRefSIN(NULL, "CoMFreezer("+name+")::input(vector)::CoMRef")
  , PGInProcessSIN(NULL, "CoMFreezer("+name+")::input(bool)::PGInProcess")
  , freezedCoMSOUT(boost::bind(&CoMFreezer::computeFreezedCoM, this, _1, _2),
      CoMRefSIN << PGInProcessSIN,
      "CoMFreezer("+name+")::output(vector)::freezedCoM")
{
  sotDEBUGIN(5);

  signalRegistration( CoMRefSIN << PGInProcessSIN << freezedCoMSOUT );

  sotDEBUGOUT(5);
}

CoMFreezer::~CoMFreezer(void)
{
  sotDEBUGIN(5);
  sotDEBUGOUT(5);
  return;
}

ml::Vector & CoMFreezer::computeFreezedCoM(ml::Vector & freezedCoM, const int & time)
{
  sotDEBUGIN(15);

  unsigned PGInProcess = PGInProcessSIN(time);
  if(PGInProcess) /* CoM unfreezed */
  {
    m_lastCoM = CoMRefSIN(time);
    m_previousPGInProcess = PGInProcess;
  }
  else
  {
    if(m_previousPGInProcess) /* pg.inprocess switch from 1 to 0 */
    {
      m_lastStopTime = time;
      m_lastCoM = CoMRefSIN(time);
      m_previousPGInProcess = PGInProcess;
    }
    else if(time < m_lastStopTime + 200) /* keep updating for 1s */
    {
      m_lastCoM = CoMRefSIN(time);
    }
  }

  freezedCoM = m_lastCoM;

  sotDEBUGOUT(15);

  if(m_lastStopTime < 0)
  {
    m_lastCoM = CoMRefSIN(time);
    m_lastStopTime = time;
    freezedCoM = m_lastCoM;
    return freezedCoM;
  }

  return m_lastCoM;
}

void CoMFreezer::display(std::ostream & os) const
{
  os << "CoMFreezer " << getName() << "." << std::endl;
}
<commit_msg>Remove warnings (during conversion unsigned -> bool)<commit_after>/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * Copyright Projet JRL-Japan, 2009
 *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * File:      CoMFreezer.cpp
 * Project:   SOT
 * Author:    Pierre Gergondet
 *
 * Version control
 * ===============
 *
 *  $Id$
 *
 * Description
 * ============
 *
 *
 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

#include <sot-core/com-freezer.h>
#include <sot-core/debug.h>
#include <dynamic-graph/factory.h>

using namespace dynamicgraph;
using namespace sot;

DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CoMFreezer, "CoMFreezer");

CoMFreezer::CoMFreezer(const std::string & name)
  : Entity(name)
  , m_lastCoM(3)
  , m_previousPGInProcess(false)
  , m_lastStopTime(-1)

  , CoMRefSIN(NULL, "CoMFreezer("+name+")::input(vector)::CoMRef")
  , PGInProcessSIN(NULL, "CoMFreezer("+name+")::input(bool)::PGInProcess")
  , freezedCoMSOUT(boost::bind(&CoMFreezer::computeFreezedCoM, this, _1, _2),
      CoMRefSIN << PGInProcessSIN,
      "CoMFreezer("+name+")::output(vector)::freezedCoM")
{
  sotDEBUGIN(5);

  signalRegistration( CoMRefSIN << PGInProcessSIN << freezedCoMSOUT );

  sotDEBUGOUT(5);
}

CoMFreezer::~CoMFreezer(void)
{
  sotDEBUGIN(5);
  sotDEBUGOUT(5);
  return;
}

ml::Vector & CoMFreezer::computeFreezedCoM(ml::Vector & freezedCoM, const int & time)
{
  sotDEBUGIN(15);

  unsigned PGInProcess = PGInProcessSIN(time);
  if(PGInProcess) /* CoM unfreezed */
  {
    m_lastCoM = CoMRefSIN(time);
    m_previousPGInProcess = (PGInProcess == 0);
  }
  else
  {
    if(m_previousPGInProcess) /* pg.inprocess switch from 1 to 0 */
    {
      m_lastStopTime = time;
      m_lastCoM = CoMRefSIN(time);
      m_previousPGInProcess = (PGInProcess == 0);
    }
    else if(time < m_lastStopTime + 200) /* keep updating for 1s */
    {
      m_lastCoM = CoMRefSIN(time);
    }
  }

  freezedCoM = m_lastCoM;

  sotDEBUGOUT(15);

  if(m_lastStopTime < 0)
  {
    m_lastCoM = CoMRefSIN(time);
    m_lastStopTime = time;
    freezedCoM = m_lastCoM;
    return freezedCoM;
  }

  return m_lastCoM;
}

void CoMFreezer::display(std::ostream & os) const
{
  os << "CoMFreezer " << getName() << "." << std::endl;
}
<|endoftext|>