<commit_before>/*************************************************************************
 *
 *  $RCSfile: all_tags.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-15 13:31:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include <ary/info/all_tags.hxx>

// NOT FULLY DEFINED SERVICES
#include <limits>
#include <ary/info/infodisp.hxx>
#include <adc_cl.hxx>

namespace ary
{
namespace info
{

//*****************************     StdTag      ***********************//

StdTag::StdTag( E_AtTagId i_eId )
    :   eId(i_eId),
        // aText,
        pNext(0)
{
}

bool
StdTag::Add_SpecialMeaningToken( const char *       i_sText,
                                 intt               i_nNr )
{
    // Does nothing

    // KORR
    //   Should be a logical exception:
    // csv_assert(false);
    return false;
}

UINT8
StdTag::NrOfSpecialMeaningTokens() const
{
    return 0;
}

AtTag *
StdTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    pNext = new StdTag(eId);
    return pNext;
}

void
StdTag::do_StoreAt( DocuDisplay &  o_rDisplay ) const
{
    o_rDisplay.Display_StdTag( *this );
}

DocuText *
StdTag::Text()
{
    return &aText;
}

//*****************************     BaseTag     ***********************//

BaseTag::BaseTag()
    :   // sBase
        // aText
        pNext(0)
{
}

bool
BaseTag::Add_SpecialMeaningToken( const char *      i_sText,
                                  intt              i_nNr )
{
    if ( i_nNr == 1 )
    {
        sBase.AssignText(i_sText,"::");
        return true;
    }
    return false;
}

const char *
BaseTag::Title() const
{
    return "Base Classes";
}

UINT8
BaseTag::NrOfSpecialMeaningTokens() const
{
    return 1;
}

AtTag *
BaseTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    pNext = new BaseTag;
    return pNext;
}

DocuText *
BaseTag::Text()
{
    return &aText;
}

//*****************************     ExceptionTag    ***********************//

ExceptionTag::ExceptionTag()
    :   // sException,
        // aText
        pNext(0)
{
}

bool
ExceptionTag::Add_SpecialMeaningToken( const char *     i_sText,
                                       intt             i_nNr )
{
    if ( i_nNr == 1 )
    {
        sException.AssignText(i_sText,"::");
        return true;
    }
    return false;
}

const char *
ExceptionTag::Title() const
{
    return "Thrown Exceptions";
}

UINT8
ExceptionTag::NrOfSpecialMeaningTokens() const
{
    return 1;
}

AtTag *
ExceptionTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    pNext = new ExceptionTag;
    return pNext;
}

DocuText *
ExceptionTag::Text()
{
    return &aText;
}

//*****************************     ImplementsTag   ***********************//

ImplementsTag::ImplementsTag()
    :   // sBase
        // aText
        pNext(0)
{
}

bool
ImplementsTag::Add_SpecialMeaningToken( const char *        i_sText,
                                        intt                i_nNr )
{
    if ( i_nNr == 1 )
    {
        sName.AssignText(i_sText,"::");
    }
    else
    {
        GetFollower()->Add_SpecialMeaningToken(i_sText,1);
    }
    return true;
}

const char *
ImplementsTag::Title() const
{
    return "Implements";
}

UINT8
ImplementsTag::NrOfSpecialMeaningTokens() const
{
    return std::numeric_limits<UINT8>::max();
}

AtTag *
ImplementsTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    pNext = new ImplementsTag;
    return pNext;
}

DocuText *
ImplementsTag::Text()
{
    return 0;
}

//*****************************     KeywordTag      ***********************//

KeywordTag::KeywordTag()
//  :   sKeys
{
}

bool
KeywordTag::Add_SpecialMeaningToken( const char *       i_sText,
                                     intt               i_nNr )
{
    sKeys.push_back(i_sText);
    return true;
}

const char *
KeywordTag::Title() const
{
    return "Keywords";
}

UINT8
KeywordTag::NrOfSpecialMeaningTokens() const
{
    return std::numeric_limits<UINT8>::max();
}

AtTag *
KeywordTag::GetFollower()
{
    return this;
}

DocuText *
KeywordTag::Text()
{
    return 0;
}

//*****************************     ParameterTag    ***********************//

ParameterTag::ParameterTag()
    :   // sName
        // aText
        pNext(0)
{
}

bool
ParameterTag::Add_SpecialMeaningToken( const char *     i_sText,
                                       intt             i_nNr )
{
    if ( i_nNr == 1 )
    {
        sName = i_sText;
        return true;
    }
    else if (i_nNr == 2)
    {
        uintt nLen = strlen(i_sText);
        if (*i_sText == '[' AND i_sText[nLen-1] == ']')
        {
            sValidRange = udmstri(i_sText+1, nLen-2);
            return true;
        }
    }
    return false;
}

UINT8
ParameterTag::NrOfSpecialMeaningTokens() const
{
    return 2;
}

AtTag *
ParameterTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    return  pNext = new ParameterTag;
}

DocuText *
ParameterTag::Text()
{
    return &aText;
}

void
ParameterTag::do_StoreAt( DocuDisplay &  o_rDisplay ) const
{
    o_rDisplay.Display_ParameterTag( *this );
}

//*****************************     SeeTag          ***********************//

SeeTag::SeeTag()
//  :   sReferences
{
}

bool
SeeTag::Add_SpecialMeaningToken( const char *       i_sText,
                                 intt               i_nNr )
{
    static QualifiedName aNull_;
    sReferences.push_back(aNull_);
    sReferences.back().AssignText(i_sText,"::");

    return true;
}

const char *
SeeTag::Title() const
{
    return "See Also";
}

UINT8
SeeTag::NrOfSpecialMeaningTokens() const
{
    return std::numeric_limits<UINT8>::max();
}

AtTag *
SeeTag::GetFollower()
{
    return this;
}

void
SeeTag::do_StoreAt( DocuDisplay &  o_rDisplay ) const
{
    o_rDisplay.Display_SeeTag( *this );
}

DocuText *
SeeTag::Text()
{
    return 0;
}

//*****************************     TemplateTag     ***********************//

TemplateTag::TemplateTag()
    :   // sName
        // aText
        pNext(0)
{
}

bool
TemplateTag::Add_SpecialMeaningToken( const char *      i_sText,
                                       intt             i_nNr )
{
    if ( i_nNr == 1 )
    {
        sName = i_sText;
        return true;
    }
    return false;
}

const char *
TemplateTag::Title() const
{
    return "Template Parameters";
}

UINT8
TemplateTag::NrOfSpecialMeaningTokens() const
{
    return 1;
}

AtTag *
TemplateTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    return  pNext = new TemplateTag;
}

void
TemplateTag::do_StoreAt( DocuDisplay &  o_rDisplay ) const
{
    o_rDisplay.Display_TemplateTag( *this );
}

DocuText *
TemplateTag::Text()
{
    return &aText;
}

//*****************************     LabelTag        ***********************//

LabelTag::LabelTag()
    :   sLabel()
{
}

bool
LabelTag::Add_SpecialMeaningToken( const char *     i_sText,
                                   intt             i_nNr )
{
    if ( i_nNr == 1 AND sLabel.length() == 0 )
    {
        sLabel = i_sText;
        return true;
    }
    // KORR_FUTURE
//  else    // Throw exception because of double label.
    return false;
}

const char *
LabelTag::Title() const
{
    return "Label";
}

UINT8
LabelTag::NrOfSpecialMeaningTokens() const
{
    return 1;
}

AtTag *
LabelTag::GetFollower()
{
    return this;
}

DocuText *
LabelTag::Text()
{
    return 0;
}

//*****************************     SinceTag        ***********************//

SinceTag::SinceTag()
    :   sVersion()
{
}

bool
SinceTag::Add_SpecialMeaningToken( const char *     i_sText,
                                   intt             )
{
    const char cCiphersend = '9' + 1;
    if ( sVersion.empty()
         AND NOT csv::in_range('0', *i_sText, cCiphersend)
         AND autodoc::CommandLine::Get_().DoesTransform_SinceTag() )
    {
        return true;
    }

    if (sVersion.empty())
    {
        sVersion = i_sText;
    }
    else
    {
        StreamLock sHelp(100);
        sVersion = sHelp() << sVersion << " " << i_sText << c_str;
    }

    return true;
}

const char *
SinceTag::Title() const
{
    return "Label";
}

UINT8
SinceTag::NrOfSpecialMeaningTokens() const
{
    return UINT8(-1);
}

AtTag *
SinceTag::GetFollower()
{
    return this;
}

void
SinceTag::do_StoreAt( DocuDisplay & o_rDisplay ) const
{
    o_rDisplay.Display_SinceTag( *this );
}

DocuText *
SinceTag::Text()
{
    return 0;
}

}   // namespace info
}   // namespace ary

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.18); FILE MERGED 2005/09/05 13:10:25 rt 1.3.18.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: all_tags.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:08:12 $
 *
 *  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
 *
 ************************************************************************/

#include <precomp.h>
#include <ary/info/all_tags.hxx>

// NOT FULLY DEFINED SERVICES
#include <limits>
#include <ary/info/infodisp.hxx>
#include <adc_cl.hxx>

namespace ary
{
namespace info
{

//*****************************     StdTag      ***********************//

StdTag::StdTag( E_AtTagId i_eId )
    :   eId(i_eId),
        // aText,
        pNext(0)
{
}

bool
StdTag::Add_SpecialMeaningToken( const char *       i_sText,
                                 intt               i_nNr )
{
    // Does nothing

    // KORR
    //   Should be a logical exception:
    // csv_assert(false);
    return false;
}

UINT8
StdTag::NrOfSpecialMeaningTokens() const
{
    return 0;
}

AtTag *
StdTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    pNext = new StdTag(eId);
    return pNext;
}

void
StdTag::do_StoreAt( DocuDisplay &  o_rDisplay ) const
{
    o_rDisplay.Display_StdTag( *this );
}

DocuText *
StdTag::Text()
{
    return &aText;
}

//*****************************     BaseTag     ***********************//

BaseTag::BaseTag()
    :   // sBase
        // aText
        pNext(0)
{
}

bool
BaseTag::Add_SpecialMeaningToken( const char *      i_sText,
                                  intt              i_nNr )
{
    if ( i_nNr == 1 )
    {
        sBase.AssignText(i_sText,"::");
        return true;
    }
    return false;
}

const char *
BaseTag::Title() const
{
    return "Base Classes";
}

UINT8
BaseTag::NrOfSpecialMeaningTokens() const
{
    return 1;
}

AtTag *
BaseTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    pNext = new BaseTag;
    return pNext;
}

DocuText *
BaseTag::Text()
{
    return &aText;
}

//*****************************     ExceptionTag    ***********************//

ExceptionTag::ExceptionTag()
    :   // sException,
        // aText
        pNext(0)
{
}

bool
ExceptionTag::Add_SpecialMeaningToken( const char *     i_sText,
                                       intt             i_nNr )
{
    if ( i_nNr == 1 )
    {
        sException.AssignText(i_sText,"::");
        return true;
    }
    return false;
}

const char *
ExceptionTag::Title() const
{
    return "Thrown Exceptions";
}

UINT8
ExceptionTag::NrOfSpecialMeaningTokens() const
{
    return 1;
}

AtTag *
ExceptionTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    pNext = new ExceptionTag;
    return pNext;
}

DocuText *
ExceptionTag::Text()
{
    return &aText;
}

//*****************************     ImplementsTag   ***********************//

ImplementsTag::ImplementsTag()
    :   // sBase
        // aText
        pNext(0)
{
}

bool
ImplementsTag::Add_SpecialMeaningToken( const char *        i_sText,
                                        intt                i_nNr )
{
    if ( i_nNr == 1 )
    {
        sName.AssignText(i_sText,"::");
    }
    else
    {
        GetFollower()->Add_SpecialMeaningToken(i_sText,1);
    }
    return true;
}

const char *
ImplementsTag::Title() const
{
    return "Implements";
}

UINT8
ImplementsTag::NrOfSpecialMeaningTokens() const
{
    return std::numeric_limits<UINT8>::max();
}

AtTag *
ImplementsTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    pNext = new ImplementsTag;
    return pNext;
}

DocuText *
ImplementsTag::Text()
{
    return 0;
}

//*****************************     KeywordTag      ***********************//

KeywordTag::KeywordTag()
//  :   sKeys
{
}

bool
KeywordTag::Add_SpecialMeaningToken( const char *       i_sText,
                                     intt               i_nNr )
{
    sKeys.push_back(i_sText);
    return true;
}

const char *
KeywordTag::Title() const
{
    return "Keywords";
}

UINT8
KeywordTag::NrOfSpecialMeaningTokens() const
{
    return std::numeric_limits<UINT8>::max();
}

AtTag *
KeywordTag::GetFollower()
{
    return this;
}

DocuText *
KeywordTag::Text()
{
    return 0;
}

//*****************************     ParameterTag    ***********************//

ParameterTag::ParameterTag()
    :   // sName
        // aText
        pNext(0)
{
}

bool
ParameterTag::Add_SpecialMeaningToken( const char *     i_sText,
                                       intt             i_nNr )
{
    if ( i_nNr == 1 )
    {
        sName = i_sText;
        return true;
    }
    else if (i_nNr == 2)
    {
        uintt nLen = strlen(i_sText);
        if (*i_sText == '[' AND i_sText[nLen-1] == ']')
        {
            sValidRange = udmstri(i_sText+1, nLen-2);
            return true;
        }
    }
    return false;
}

UINT8
ParameterTag::NrOfSpecialMeaningTokens() const
{
    return 2;
}

AtTag *
ParameterTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    return  pNext = new ParameterTag;
}

DocuText *
ParameterTag::Text()
{
    return &aText;
}

void
ParameterTag::do_StoreAt( DocuDisplay &  o_rDisplay ) const
{
    o_rDisplay.Display_ParameterTag( *this );
}

//*****************************     SeeTag          ***********************//

SeeTag::SeeTag()
//  :   sReferences
{
}

bool
SeeTag::Add_SpecialMeaningToken( const char *       i_sText,
                                 intt               i_nNr )
{
    static QualifiedName aNull_;
    sReferences.push_back(aNull_);
    sReferences.back().AssignText(i_sText,"::");

    return true;
}

const char *
SeeTag::Title() const
{
    return "See Also";
}

UINT8
SeeTag::NrOfSpecialMeaningTokens() const
{
    return std::numeric_limits<UINT8>::max();
}

AtTag *
SeeTag::GetFollower()
{
    return this;
}

void
SeeTag::do_StoreAt( DocuDisplay &  o_rDisplay ) const
{
    o_rDisplay.Display_SeeTag( *this );
}

DocuText *
SeeTag::Text()
{
    return 0;
}

//*****************************     TemplateTag     ***********************//

TemplateTag::TemplateTag()
    :   // sName
        // aText
        pNext(0)
{
}

bool
TemplateTag::Add_SpecialMeaningToken( const char *      i_sText,
                                       intt             i_nNr )
{
    if ( i_nNr == 1 )
    {
        sName = i_sText;
        return true;
    }
    return false;
}

const char *
TemplateTag::Title() const
{
    return "Template Parameters";
}

UINT8
TemplateTag::NrOfSpecialMeaningTokens() const
{
    return 1;
}

AtTag *
TemplateTag::GetFollower()
{
    if (pNext != 0)
        return pNext->GetFollower();
    return  pNext = new TemplateTag;
}

void
TemplateTag::do_StoreAt( DocuDisplay &  o_rDisplay ) const
{
    o_rDisplay.Display_TemplateTag( *this );
}

DocuText *
TemplateTag::Text()
{
    return &aText;
}

//*****************************     LabelTag        ***********************//

LabelTag::LabelTag()
    :   sLabel()
{
}

bool
LabelTag::Add_SpecialMeaningToken( const char *     i_sText,
                                   intt             i_nNr )
{
    if ( i_nNr == 1 AND sLabel.length() == 0 )
    {
        sLabel = i_sText;
        return true;
    }
    // KORR_FUTURE
//  else    // Throw exception because of double label.
    return false;
}

const char *
LabelTag::Title() const
{
    return "Label";
}

UINT8
LabelTag::NrOfSpecialMeaningTokens() const
{
    return 1;
}

AtTag *
LabelTag::GetFollower()
{
    return this;
}

DocuText *
LabelTag::Text()
{
    return 0;
}

//*****************************     SinceTag        ***********************//

SinceTag::SinceTag()
    :   sVersion()
{
}

bool
SinceTag::Add_SpecialMeaningToken( const char *     i_sText,
                                   intt             )
{
    const char cCiphersend = '9' + 1;
    if ( sVersion.empty()
         AND NOT csv::in_range('0', *i_sText, cCiphersend)
         AND autodoc::CommandLine::Get_().DoesTransform_SinceTag() )
    {
        return true;
    }

    if (sVersion.empty())
    {
        sVersion = i_sText;
    }
    else
    {
        StreamLock sHelp(100);
        sVersion = sHelp() << sVersion << " " << i_sText << c_str;
    }

    return true;
}

const char *
SinceTag::Title() const
{
    return "Label";
}

UINT8
SinceTag::NrOfSpecialMeaningTokens() const
{
    return UINT8(-1);
}

AtTag *
SinceTag::GetFollower()
{
    return this;
}

void
SinceTag::do_StoreAt( DocuDisplay & o_rDisplay ) const
{
    o_rDisplay.Display_SinceTag( *this );
}

DocuText *
SinceTag::Text()
{
    return 0;
}

}   // namespace info
}   // namespace ary

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: reposy.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:15:06 $
 *
 *  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
 *
 ************************************************************************/

//  VERSION:            Autodoc 2.2

#include <precomp.h>
#include <reposy.hxx>

// NOT FULLY DECLARED SERVICES
#include <ary/x_ary.hxx>
#include <ary/actions.hxx>
#include <idl/i_reposypart.hxx>

    // S P L I T //

#include <store/storage.hxx>
#include <store/strg_ifc.hxx>
#include <id_gener.hxx>
#include <cpp/c_gate.hxx>
#include <loc/l_gate.hxx>

namespace ary
{

namespace
{
    static Dyn<RepositoryCenter> pTheOldInstance_(0);
}

namespace n22
{

using ::ary::Command;
using ::ary::X_Ary;

//*****************     Repository          ************//

namespace
{
    static Dyn<RepositoryCenter> pTheInstance_(0);
}

Repository &
Repository::Create_()
{
    if ( pTheInstance_ )
        throw X_Ary(X_Ary::x_MultipleRepository);

    pTheInstance_ = new RepositoryCenter;

    // KORR_FUTURE
    //   Create the Cpp repository:
    ::ary::Repository::Create_(0);

    return *pTheInstance_;
}

Repository &
Repository::The_()
{
    if ( NOT pTheInstance_ )
        throw X_Ary(X_Ary::x_MissingRepository);

    return *pTheInstance_;
}

void
Repository::Destroy_()
{
    pTheInstance_ = 0;

    // KORR_FUTURE
    //   Destroythe Cpp repository:
    ::ary::Repository::Destroy_();
}

//*****************     RepositoryCenter          ************//

RepositoryCenter::RepositoryCenter()
    :   sDisplayedName(),
        aLocation(),
#if 0       // Version 2.2
        pCppPartition(),
#endif // Version 2.2
        pIdlPartition()
{
}

RepositoryCenter::~RepositoryCenter()
{
}

void
RepositoryCenter::RunCommand_ProduceAllSecondaries()
{
    // KORR_FUTURE
}

void
RepositoryCenter::RunCommand_Statistic( ::ary::action::Statistic & io_rCommand )
{
    // KORR_FUTURE
}

void
RepositoryCenter::do_Perform( Command & io_rCommand )
{
    io_rCommand.Run(*this);
}

const String &
RepositoryCenter::inq_Name() const
{
    return sDisplayedName;
}

bool
RepositoryCenter::inq_HasIdl() const
{
    return bool(pIdlPartition);
}

bool
RepositoryCenter::inq_HasCpp() const
{
    return pTheOldInstance_->HasCpp();
}

const ::ary::idl::Gate &
RepositoryCenter::inq_Gate_Idl() const
{
    return const_cast< RepositoryCenter& >(*this).access_Gate_Idl();
}

const ::ary::cpp::DisplayGate &
RepositoryCenter::inq_Gate_Cpp() const
{
    return pTheOldInstance_->DisplayGate_Cpp();
}

::ary::idl::Gate &
RepositoryCenter::access_Gate_Idl()
{
    if (NOT pIdlPartition)
        pIdlPartition = new idl::RepositoryPartition(*this);

    return pIdlPartition->TheGate();
}

::ary::cpp::RwGate &
RepositoryCenter::access_Gate_Cpp()
{
    return pTheOldInstance_->RwGate_Cpp();
}

void
RepositoryCenter::do_Set_Name(const String & i_sName)
{
    sDisplayedName = i_sName;
    pTheOldInstance_->Set_Name(i_sName);
}

#if 0       // Version 2.2
/*
cpp::Gate &
RepositoryCenter::access_Gate_Cpp()
{
    csv_assert( pCppPartition );
    return pCppPartition->TheGate();
}
const cpp::Gate &
RepositoryCenter::inq_Gate_Cpp() const
{
    csv_assert( pCppPartition );
    return pCppPartition->TheGate();
}
*/
#endif    // Version 2.2

}   // namespace n22

/*  ClassType-Ids
    -------------

    cpp                 1000
    idl                 2000
    corba               3000
    java                4000
    information         5000
    logic location      6000
    phys location       7000
    sec. prod.          8000

    cpp
    ---
    Namespace           1000
    Class               1001
    Enum                1002
    Typedef             1003
    Function            1004
    Variable            1005
    EnumValue           1006
    NamespaceAlias      1007

    BuiltInType         1200
    CeType_Final        1201
    CeType_Extern       1202
    PtrType             1211
    RefType             1212
    ConstType           1221
    VolatileType        1222
    ArrayType           1230
    TemplateInstance    1235
    FunctionPtr         1240
    DataMemberPtr       1250
    OperationMemberPtr  1260

    TplParam_Type       1301
    TplParam_Value      1302

    OpSignature         1400

    Define              1601
    Macro               1602

    idl
    ---

    Module              2000
    Interface           2001
    Function            2002
    Service             2003
    Property            2004
    Enum                2005
    EnumValue           2006
    Typedef             2007
    Struct              2008
    StructElement       2009
    Exception           2010
    ConstantGroup       2011
    Constant            2012
    Singleton           2013
    Attribute           2014
    SglIfcService       2015
    SglIfcSingleton     2016

    BuiltInType         2200
    CeType              2201
    Sequence            2202
    ExplicitType        2203
    ExplicitNameRoom    2204
    TemplateParamType   2205

    java
    ----
    Package             4000
    Interface           4001
    Class               4002

    info
    ----
    CodeInformation
        (IDL)          11002
*/

                        //      S P L I T           //

struct RepositoryCenter::CheshireCat
{
    //  DATA
    String              sName;
    Dyn<store::Storage> pStorage;
    Dyn<Storage_Ifc>    pStorage_Ifc;
    Dyn<IdGenerator>    pIdGenerator;

    Dyn<cpp::Gate>      pGate_Cpp;
    Dyn<loc::Gate>      pGate_Locations;
    bool                bHasCppContent;

                        CheshireCat(
                            DYN IdGenerator &   let_drIds );
                        ~CheshireCat();
};

Repository &
Repository::Create_( DYN IdGenerator *   let_dpIds )
{
    csv_assert( NOT pTheOldInstance_ );

    DYN IdGenerator * dpIds =
            let_dpIds != 0
                ?   let_dpIds
                :   new Std_IdGenerator;
    pTheOldInstance_ = new RepositoryCenter( *dpIds );
    return *pTheOldInstance_;
}

Repository &
Repository::The_()
{
    csv_assert( pTheOldInstance_ );
    return *pTheOldInstance_;
}

void
Repository::Destroy_()
{
    pTheOldInstance_ = 0;
}

RepositoryCenter::RepositoryCenter( DYN IdGenerator &   let_drIds )
    :   pi( new CheshireCat(let_drIds) )
{
}

RepositoryCenter::~RepositoryCenter()
{
}

bool
RepositoryCenter::HasCpp() const
{
    return pi->bHasCppContent;
}

void
RepositoryCenter::Set_Name( const String & i_name )
{
     pi->sName = i_name;
}

const cpp::DisplayGate &
RepositoryCenter::inq_DisplayGate_Cpp() const
{
    return *pi->pGate_Cpp;
}

const udmstri &
RepositoryCenter::inq_Name() const
{
    return pi->sName;
}

cpp::RwGate &
RepositoryCenter::access_RwGate_Cpp()
{
    pi->bHasCppContent = true;
    return *pi->pGate_Cpp;
}

RepositoryCenter::
CheshireCat::CheshireCat( DYN IdGenerator &   let_drIds )
    :   sName(),
        pStorage(0),
        pStorage_Ifc(0),
        pIdGenerator( &let_drIds ),
        pGate_Cpp(0),
        pGate_Locations(0),
        bHasCppContent(false)
{
    pStorage                = new store::Storage;
    pStorage_Ifc            = new Storage_Ifc( *pStorage );
    pGate_Locations         = new loc::Gate(
                                        pStorage_Ifc->Ifc_Locations(),
                                        *pIdGenerator );
    pGate_Cpp               = new cpp::Gate(
                                        *pStorage_Ifc,
                                        *pIdGenerator,
                                        *pGate_Locations );
}

RepositoryCenter::
CheshireCat::~CheshireCat()
{
}

}   // namespace ary

<commit_msg>INTEGRATION: CWS warnings01 (1.6.4); FILE MERGED 2005/10/18 08:35:57 np 1.6.4.1: #i53898#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: reposy.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 11:55:51 $
 *
 *  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
 *
 ************************************************************************/

//  VERSION:            Autodoc 2.2

#include <precomp.h>
#include <reposy.hxx>

// NOT FULLY DECLARED SERVICES
#include <ary/x_ary.hxx>
#include <ary/actions.hxx>
#include <idl/i_reposypart.hxx>

    // S P L I T //

#include <store/storage.hxx>
#include <store/strg_ifc.hxx>
#include <id_gener.hxx>
#include <cpp/c_gate.hxx>
#include <loc/l_gate.hxx>

namespace ary
{

namespace
{
    static Dyn<RepositoryCenter> pTheOldInstance_(0);
}

namespace n22
{

using ::ary::Command;
using ::ary::X_Ary;

//*****************     Repository          ************//

namespace
{
    static Dyn<RepositoryCenter> pTheInstance_(0);
}

Repository &
Repository::Create_()
{
    if ( pTheInstance_ )
        throw X_Ary(X_Ary::x_MultipleRepository);

    pTheInstance_ = new RepositoryCenter;

    // KORR_FUTURE
    //   Create the Cpp repository:
    ::ary::Repository::Create_(0);

    return *pTheInstance_;
}

Repository &
Repository::The_()
{
    if ( NOT pTheInstance_ )
        throw X_Ary(X_Ary::x_MissingRepository);

    return *pTheInstance_;
}

void
Repository::Destroy_()
{
    pTheInstance_ = 0;

    // KORR_FUTURE
    //   Destroythe Cpp repository:
    ::ary::Repository::Destroy_();
}

//*****************     RepositoryCenter          ************//

RepositoryCenter::RepositoryCenter()
    :   sDisplayedName(),
        aLocation(),
#if 0       // Version 2.2
        pCppPartition(),
#endif // Version 2.2
        pIdlPartition()
{
}

RepositoryCenter::~RepositoryCenter()
{
}

void
RepositoryCenter::RunCommand_ProduceAllSecondaries()
{
    // KORR_FUTURE
}

void
RepositoryCenter::RunCommand_Statistic( ::ary::action::Statistic & )
{
    // KORR_FUTURE
}

void
RepositoryCenter::do_Perform( Command & io_rCommand )
{
    io_rCommand.Run(*this);
}

const String &
RepositoryCenter::inq_Name() const
{
    return sDisplayedName;
}

bool
RepositoryCenter::inq_HasIdl() const
{
    return bool(pIdlPartition);
}

bool
RepositoryCenter::inq_HasCpp() const
{
    return pTheOldInstance_->HasCpp();
}

const ::ary::idl::Gate &
RepositoryCenter::inq_Gate_Idl() const
{
    return const_cast< RepositoryCenter& >(*this).access_Gate_Idl();
}

const ::ary::cpp::DisplayGate &
RepositoryCenter::inq_Gate_Cpp() const
{
    return pTheOldInstance_->DisplayGate_Cpp();
}

::ary::idl::Gate &
RepositoryCenter::access_Gate_Idl()
{
    if (NOT pIdlPartition)
        pIdlPartition = new idl::RepositoryPartition(*this);

    return pIdlPartition->TheGate();
}

::ary::cpp::RwGate &
RepositoryCenter::access_Gate_Cpp()
{
    return pTheOldInstance_->RwGate_Cpp();
}

void
RepositoryCenter::do_Set_Name(const String & i_sName)
{
    sDisplayedName = i_sName;
    pTheOldInstance_->Set_Name(i_sName);
}

#if 0       // Version 2.2
/*
cpp::Gate &
RepositoryCenter::access_Gate_Cpp()
{
    csv_assert( pCppPartition );
    return pCppPartition->TheGate();
}
const cpp::Gate &
RepositoryCenter::inq_Gate_Cpp() const
{
    csv_assert( pCppPartition );
    return pCppPartition->TheGate();
}
*/
#endif    // Version 2.2

}   // namespace n22

/*  ClassType-Ids
    -------------

    cpp                 1000
    idl                 2000
    corba               3000
    java                4000
    information         5000
    logic location      6000
    phys location       7000
    sec. prod.          8000

    cpp
    ---
    Namespace           1000
    Class               1001
    Enum                1002
    Typedef             1003
    Function            1004
    Variable            1005
    EnumValue           1006
    NamespaceAlias      1007

    BuiltInType         1200
    CeType_Final        1201
    CeType_Extern       1202
    PtrType             1211
    RefType             1212
    ConstType           1221
    VolatileType        1222
    ArrayType           1230
    TemplateInstance    1235
    FunctionPtr         1240
    DataMemberPtr       1250
    OperationMemberPtr  1260

    TplParam_Type       1301
    TplParam_Value      1302

    OpSignature         1400

    Define              1601
    Macro               1602

    idl
    ---

    Module              2000
    Interface           2001
    Function            2002
    Service             2003
    Property            2004
    Enum                2005
    EnumValue           2006
    Typedef             2007
    Struct              2008
    StructElement       2009
    Exception           2010
    ConstantGroup       2011
    Constant            2012
    Singleton           2013
    Attribute           2014
    SglIfcService       2015
    SglIfcSingleton     2016

    BuiltInType         2200
    CeType              2201
    Sequence            2202
    ExplicitType        2203
    ExplicitNameRoom    2204
    TemplateParamType   2205

    java
    ----
    Package             4000
    Interface           4001
    Class               4002

    info
    ----
    CodeInformation
        (IDL)          11002
*/

                        //      S P L I T           //

struct RepositoryCenter::CheshireCat
{
    //  DATA
    String              sName;
    Dyn<store::Storage> pStorage;
    Dyn<Storage_Ifc>    pStorage_Ifc;
    Dyn<IdGenerator>    pIdGenerator;

    Dyn<cpp::Gate>      pGate_Cpp;
    Dyn<loc::Gate>      pGate_Locations;
    bool                bHasCppContent;

                        CheshireCat(
                            DYN IdGenerator &   let_drIds );
                        ~CheshireCat();
};

Repository &
Repository::Create_( DYN IdGenerator *   let_dpIds )
{
    csv_assert( NOT pTheOldInstance_ );

    DYN IdGenerator * dpIds =
            let_dpIds != 0
                ?   let_dpIds
                :   new Std_IdGenerator;
    pTheOldInstance_ = new RepositoryCenter( *dpIds );
    return *pTheOldInstance_;
}

Repository &
Repository::The_()
{
    csv_assert( pTheOldInstance_ );
    return *pTheOldInstance_;
}

void
Repository::Destroy_()
{
    pTheOldInstance_ = 0;
}

RepositoryCenter::RepositoryCenter( DYN IdGenerator &   let_drIds )
    :   pi( new CheshireCat(let_drIds) )
{
}

RepositoryCenter::~RepositoryCenter()
{
}

bool
RepositoryCenter::HasCpp() const
{
    return pi->bHasCppContent;
}

void
RepositoryCenter::Set_Name( const String & i_name )
{
     pi->sName = i_name;
}

const cpp::DisplayGate &
RepositoryCenter::inq_DisplayGate_Cpp() const
{
    return *pi->pGate_Cpp;
}

const udmstri &
RepositoryCenter::inq_Name() const
{
    return pi->sName;
}

cpp::RwGate &
RepositoryCenter::access_RwGate_Cpp()
{
    pi->bHasCppContent = true;
    return *pi->pGate_Cpp;
}

RepositoryCenter::
CheshireCat::CheshireCat( DYN IdGenerator &   let_drIds )
    :   sName(),
        pStorage(0),
        pStorage_Ifc(0),
        pIdGenerator( &let_drIds ),
        pGate_Cpp(0),
        pGate_Locations(0),
        bHasCppContent(false)
{
    pStorage                = new store::Storage;
    pStorage_Ifc            = new Storage_Ifc( *pStorage );
    pGate_Locations         = new loc::Gate(
                                        pStorage_Ifc->Ifc_Locations(),
                                        *pIdGenerator );
    pGate_Cpp               = new cpp::Gate(
                                        *pStorage_Ifc,
                                        *pIdGenerator,
                                        *pGate_Locations );
}

RepositoryCenter::
CheshireCat::~CheshireCat()
{
}

}   // namespace ary

<|endoftext|>


<commit_before>#include "nodes/EANode/systems/ES/CMSA_ES.hpp"
#include "core/utils/HierRNG.hpp"
#include <math.h>
#include <unsupported/Eigen/MatrixFunctions>

CMSA_ES::CMSAMutation::CMSAMutation(
	unsigned int lambda
) : AdaptiveRealValueMutation() {
	this->lambda = lambda;
}

CMSA_ES::CMSAMutation::CMSAMutation(
	unsigned int lambda,
	double tau,
	double tauC
) : AdaptiveRealValueMutation() {
	this->lambda = lambda;
	this->tau = tau;
	this->tauC = tauC;
	this->tausCalculated = true;
}

void CMSA_ES::CMSAMutation::calculateTaus(Genome* initial) {
	unsigned int n = initial->genomeLength();
	this->tau = 1/sqrt(2 * n);
	this->tauC = 1 + n * (n + 1)/(2 * this->mu);
	this->tausCalculated = true;
}

void CMSA_ES::CMSAMutation::calculateProperGenomeLengths(
	Genome* initial
) {
	this->initialGenomeLength = initial->genomeLength();
	this->targetGenomeLength = initial->genomeLength() + 1;
}

Genome* CMSA_ES::CMSAMutation::addStdDevs(Genome* target) {
	std::vector<Gene*> newGenes = target->getGenomeCopy();
	newGenes.push_back(this->stdDevLocus->getGene(1));

	if (this->stdDevIndices.empty())
		stdDevIndices.push_back(target->genomeLength());

	return new Genome(newGenes, target->getSpeciesNode());
}

void CMSA_ES::CMSAMutation::otherSetupSteps(Genome* initial) {
	unsigned int n = initial->genomeLength();
	this->C = Eigen::MatrixXd::Identity(n, n);
}

void CMSA_ES::CMSAMutation::setMu(unsigned int mu) {
	this->mu = mu;
}

void CMSA_ES::CMSAMutation::calculateAverages(std::vector<Genome*> population) {
	unsigned int n = population[0]->genomeLength();
	double sigmaSum;
	std::vector<double> xSums(n, 0);

	for (unsigned int i = 0; i < population.size(); i++) {
		// Since the stdDevs haven't necessarily been set up yet, we
		// need to account for that
		sigmaSum += !this->stdDevIndices.empty() ?
			population[i]->getIndex<double>(this->stdDevIndices[0]) :
			1;

		std::vector<Gene*> genes = population[i]->getGenome();
		for (unsigned int k = 0; k < n; k++)
			xSums[k] += genes[k]->getIndex();
	}

	this->sigmaAvg = sigmaSum/this->mu;

	this->xAvg.clear();
	for (unsigned int i = 0; i < xSums.size(); i++)
		this->xAvg.push_back(xSums[i]/this->mu);

	if (!this->skCollection.empty()) {
		Eigen::MatrixXd SAvg = Eigen::MatrixXd::Zero(
			this->initialGenomeLength,
			this->initialGenomeLength
		);

		for (unsigned int i = 0; i < this->skCollection.size(); i++) {
			Eigen::VectorXd sk = this->skCollection[i];
			SAvg += sk * sk.transpose();
		}

		SAvg /= this->lambda;
		this->skCollection.clear();
		this->C = (1 - 1/this->tauC) * this->C + SAvg/this->tauC;
	}
}

Genome* CMSA_ES::CMSAMutation::mutateProper(Genome* target) {
	std::vector<Gene*> newGenes = target->getGenomeCopy();

	Gene* stdDevGene = newGenes[this->stdDevIndices[0]];
	double sigmaK = this->sigmaAvg
		* exp(HierRNG::gaussian(0, 1) * this->tau);
	newGenes[this->stdDevIndices[0]] = stdDevGene->copy(sigmaK);
	delete(stdDevGene);

	Eigen::VectorXd R(this->initialGenomeLength);
	for (unsigned int i = 0; i < this->initialGenomeLength; i++)
		R[i] = HierRNG::gaussian(0, 1);

	Eigen::VectorXd sk = this->C.sqrt() * R;
	Eigen::VectorXd zk = sigmaK * sk;

	for (unsigned int i = 0; i < this->initialGenomeLength; i++) {
		Gene* originalGene = newGenes[i];
		newGenes[i] = originalGene->copy(this->xAvg[i] + zk[i]);
		delete(originalGene);
	}

	this->skCollection.push_back(sk);
	return new Genome(newGenes, target->getSpeciesNode());
}
<commit_msg>[CMSA_ES Mutation]: Fixed "uninitialized value" issues<commit_after>#include "nodes/EANode/systems/ES/CMSA_ES.hpp"
#include "core/utils/HierRNG.hpp"
#include <math.h>
#include <unsupported/Eigen/MatrixFunctions>

CMSA_ES::CMSAMutation::CMSAMutation(
	unsigned int lambda
) : AdaptiveRealValueMutation() {
	this->lambda = lambda;
}

CMSA_ES::CMSAMutation::CMSAMutation(
	unsigned int lambda,
	double tau,
	double tauC
) : AdaptiveRealValueMutation() {
	this->lambda = lambda;
	this->tau = tau;
	this->tauC = tauC;
	this->tausCalculated = true;
}

void CMSA_ES::CMSAMutation::calculateTaus(Genome* initial) {
	unsigned int n = initial->genomeLength();
	this->tau = 1/sqrt(2 * n);
	this->tauC = 1 + n * (n + 1)/(2 * this->mu);
	this->tausCalculated = true;
}

void CMSA_ES::CMSAMutation::calculateProperGenomeLengths(
	Genome* initial
) {
	this->initialGenomeLength = initial->genomeLength();
	this->targetGenomeLength = initial->genomeLength() + 1;
}

Genome* CMSA_ES::CMSAMutation::addStdDevs(Genome* target) {
	std::vector<Gene*> newGenes = target->getGenomeCopy();
	newGenes.push_back(this->stdDevLocus->getGene(1));

	if (this->stdDevIndices.empty())
		this->stdDevIndices.push_back(target->genomeLength());

	return new Genome(newGenes, target->getSpeciesNode());
}

void CMSA_ES::CMSAMutation::otherSetupSteps(Genome* initial) {
	unsigned int n = initial->genomeLength();
	this->C = Eigen::MatrixXd::Identity(n, n);
}

void CMSA_ES::CMSAMutation::setMu(unsigned int mu) {
	this->mu = mu;
}

void CMSA_ES::CMSAMutation::calculateAverages(std::vector<Genome*> population) {
	unsigned int n = population[0]->genomeLength();
	double sigmaSum = 0;
	std::vector<double> xSums(n, 0);

	for (unsigned int i = 0; i < population.size(); i++) {
		// Since the stdDevs haven't necessarily been set up yet, we
		// need to account for that
		sigmaSum += !this->stdDevIndices.empty() ?
			population[i]->getIndex<double>(this->stdDevIndices[0]) :
			1;

		std::vector<Gene*> genes = population[i]->getGenome();
		for (unsigned int k = 0; k < n; k++)
			xSums[k] += genes[k]->getIndex();
	}

	this->sigmaAvg = sigmaSum/this->mu;

	this->xAvg.clear();
	for (unsigned int i = 0; i < xSums.size(); i++)
		this->xAvg.push_back(xSums[i]/this->mu);

	if (!this->skCollection.empty()) {
		Eigen::MatrixXd SAvg = Eigen::MatrixXd::Zero(
			this->initialGenomeLength,
			this->initialGenomeLength
		);

		for (unsigned int i = 0; i < this->skCollection.size(); i++) {
			Eigen::VectorXd sk = this->skCollection[i];
			SAvg += sk * sk.transpose();
		}

		SAvg /= this->lambda;
		this->skCollection.clear();
		this->C = (1 - 1/this->tauC) * this->C + SAvg/this->tauC;
	}
}

Genome* CMSA_ES::CMSAMutation::mutateProper(Genome* target) {
	std::vector<Gene*> newGenes = target->getGenomeCopy();

	Gene* stdDevGene = newGenes[this->stdDevIndices[0]];
	double sigmaK = this->sigmaAvg
		* exp(HierRNG::gaussian(0, 1) * this->tau);
	newGenes[this->stdDevIndices[0]] = stdDevGene->copy(sigmaK);
	delete(stdDevGene);

	Eigen::VectorXd R(this->initialGenomeLength);
	for (unsigned int i = 0; i < this->initialGenomeLength; i++)
		R[i] = HierRNG::gaussian(0, 1);

	Eigen::VectorXd sk = this->C.sqrt() * R;
	Eigen::VectorXd zk = sigmaK * sk;

	for (unsigned int i = 0; i < this->initialGenomeLength; i++) {
		Gene* originalGene = newGenes[i];
		newGenes[i] = originalGene->copy(this->xAvg[i] + zk[i]);
		delete(originalGene);
	}

	this->skCollection.push_back(sk);
	return new Genome(newGenes, target->getSpeciesNode());
}
<|endoftext|>


<commit_before>#pragma once

#include "openMVG/robust_estimation/rand_sampling.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp"
#include "openMVG/robust_estimation/robust_ransac_tools.hpp"
#include <limits>
#include <numeric>
#include <iostream>
#include <vector>
#include <iterator>

namespace openMVG {
namespace robust{

//*****************************************************
template<typename Kernel, typename Scorer>
double iterativeReweightedLeastSquares(const Kernel &kernel,
                                     const Scorer &scorer,
                                     typename Kernel::Model &best_model,
                                     std::vector<std::size_t> &inliers,
                                     double mtheta = std::sqrt(2),
                                     std::size_t numIter = 4)
{
  const std::size_t total_samples = kernel.NumSamples();
  const std::size_t min_samples = Kernel::MINIMUM_LSSAMPLES;
  double theta = scorer.getThreshold();
  // used in the iterations to update (reduce) the threshold value
  const double deltaTetha = (mtheta*theta - theta) / (numIter-1);

  std::vector<std::size_t> all_samples(total_samples);
  std::iota(all_samples.begin(), all_samples.end(), 0);

  // find inliers from best model with threshold theta
  inliers.clear();
  scorer.Score(kernel, best_model, all_samples, &inliers, theta);

  if(inliers.size() < min_samples)
  {
    inliers.clear();
    std::cerr << "[IRLS] returning cause inliers.size() < min_samples" << std::endl;
    return std::numeric_limits<double>::infinity();
  }

  // LS model from the above inliers
  std::vector<typename Kernel::Model> models;
  kernel.FitLS(inliers, &models);
  assert(models.size()==1);   // LS fitting must always return 1 model

  // change threshold for refinement
  theta *= mtheta;

  // iterative refinement
  for(std::size_t i = 0; i < numIter; ++i)
  {
    // find inliers on the best-so-far model
    // @todo maybe inliers instead of all samples to save some computation
    inliers.clear();
    scorer.Score(kernel, models[0], all_samples, &inliers, theta);

    if(inliers.size() < min_samples)
    {
      inliers.clear();
      std::cerr << "[IRLS] returning cause inliers.size() < min_samples" << std::endl;
      return std::numeric_limits<double>::infinity();
    }
//    std::cout << "[IRLS] #" << i
//            << " theta: " << theta
//            << " num inliers: " << inliers.size() << std::endl;

    // compute the weights for the inliers
    std::vector<double> weights;
    kernel.computeWeights(models[0], inliers, weights);

    // LS with weights on inliers
    models.clear();
    kernel.FitLS(inliers, &models, &weights);
    if(models.size() != 1)   // LS fitting must always return 1 model
    {
      std::cerr << "[IRLS] found "<< models.size() << " models, aborting..." << std::endl;
      return std::numeric_limits<double>::infinity();
    }

    // update the threshold
    theta -= deltaTetha;
  }

  assert(models.size()==1);
  best_model = models[0];
  inliers.clear();
  const double score = scorer.Score(kernel, best_model, all_samples, &inliers, theta);
  std::cout << "[IRLS] returning with num inliers: " << inliers.size()
          << " and score " << score << std::endl;
  return score;
}

template<typename Kernel, typename Scorer>
double localOptimization(const Kernel &kernel,
                       const Scorer &scorer,
                       typename Kernel::Model &bestModel,
                       std::vector<std::size_t> &bestInliers,
                       double mtheta = std::sqrt(2),
                       std::size_t numRep = 10,
                       std::size_t minSampleSize = 10)
{
  const std::size_t total_samples = kernel.NumSamples();
  const std::size_t min_samples = Kernel::MINIMUM_LSSAMPLES;
  assert((total_samples > min_samples) &&
          "[localOptimization] not enough data to estimate the model!");

  const double theta = scorer.getThreshold();

  std::vector<std::size_t> all_samples(total_samples);
  std::iota(all_samples.begin(), all_samples.end(), 0);

  std::size_t debugInit = 0;
  if(!bestInliers.empty())
  {
    debugInit = bestInliers.size();
    bestInliers.clear();
  }
  double bestScore = scorer.Score(kernel, bestModel, all_samples, &bestInliers, theta);
  if(debugInit != 0) assert(debugInit == bestInliers.size());

  // so far this is the best model
  std::size_t bestNumInliers = bestInliers.size();
  std::cout << "[localOptim] so far best num inliers: " << bestNumInliers << std::endl;
  std::cout << "[localOptim] so far best model:\n" << bestModel << std::endl;
  std::cout << "[localOptim] so far best score: " << bestScore << std::endl;

  // find inliers from best model with larger threshold t*m over all the samples
  std::vector<std::size_t> inliersBase;
  scorer.Score(kernel, bestModel, all_samples, &inliersBase, theta*mtheta);
  assert((inliersBase.size() > min_samples) &&
          "[localOptimization] not enough data in inliersBase to estimate the model!");

  // LS model from the above inliers
  std::vector<typename Kernel::Model> models;
  kernel.FitLS(inliersBase, &models);
  assert(models.size()==1);   // LS fitting must always return 1 model

  // find inliers with t again over all the samples
  inliersBase.clear();
  scorer.Score(kernel, models[0], all_samples, &inliersBase, theta);

  // sample of size sampleSize from the last best inliers
  const std::size_t sampleSize = std::min(minSampleSize, inliersBase.size()/2);
  if(sampleSize <= Kernel::MINIMUM_LSSAMPLES)
  {
    std::cout << "breaking cause sampleSize is " << sampleSize << std::endl;
    return bestScore;
  }

  // do numRep resampling + iterative LS
  for(std::size_t i = 0; i < numRep; ++i)
  {
    std::vector<std::size_t> sample;
    UniformSample(sampleSize, inliersBase, &sample);
    assert(sampleSize > Kernel::MINIMUM_LSSAMPLES);
    assert(sample.size() > Kernel::MINIMUM_LSSAMPLES);

    // LS estimation from the sample
    models.clear();
    kernel.FitLS(sample, &models);
    assert(models.size()==1);   // LS fitting must always return 1 model

    // IRLS
    std::vector<std::size_t> inliers;
    const double score = iterativeReweightedLeastSquares(kernel, scorer, models[0], inliers);

    // store new best model if it is the case
    if((inliers.size() > bestNumInliers) ||
       ((inliers.size() == bestNumInliers) && (score < bestScore)))
    {
      bestNumInliers = inliers.size();
      bestScore = score;
      bestModel = models[0];
      bestInliers.swap(inliers);
      std::cout << "[localOptim] new best num inliers: " << bestNumInliers << std::endl;
    }
  }
  return bestScore;
}

//@todo make visible parameters for the optimization step
template<typename Kernel, typename Scorer>
typename Kernel::Model LO_RANSAC(
  const Kernel &kernel,
  const Scorer &scorer,
  std::vector<std::size_t> *best_inliers = NULL,
  double *best_score = NULL,
  bool bVerbose = true,
  std::size_t max_iterations = 100,
  double outliers_probability = 1e-2)
{
  assert(outliers_probability < 1.0);
  assert(outliers_probability > 0.0);
  std::size_t iteration = 0;
  const std::size_t min_samples = Kernel::MINIMUM_SAMPLES;
  const std::size_t total_samples = kernel.NumSamples();

  const std::size_t really_max_iterations = 4096;

  std::size_t bestNumInliers = 0;
  double bestInlierRatio = 0.0;
  typename Kernel::Model bestModel;

  // Test if we have sufficient points for the kernel.
  if (total_samples < min_samples)
  {
    if (best_inliers) {
      best_inliers->clear();
    }
    return bestModel;
  }

  // In this robust estimator, the scorer always works on all the data points
  // at once. So precompute the list ahead of time [0,..,total_samples].
  std::vector<std::size_t> all_samples(total_samples);
  std::iota(all_samples.begin(), all_samples.end(), 0);

  std::vector<std::size_t> sample;
  for(iteration = 0; iteration < max_iterations; ++iteration)
  {
    UniformSample(min_samples, total_samples, &sample);

    std::vector<typename Kernel::Model> models;
    kernel.Fit(sample, &models);

    // Compute the inlier list for each fit.
    for(std::size_t i = 0; i < models.size(); ++i)
    {
      std::vector<std::size_t> inliers;
      double score = scorer.Score(kernel, models[i], all_samples, &inliers);
      std::cout << "sample=";
      std::sort(sample.begin(), sample.end());
      std::copy(sample.begin(), sample.end(),
                    std::ostream_iterator<std::size_t>(std::cout, ","));
      std::cout << "\nmodel " << i
              << " e: " << score << std::endl;

      if (bestNumInliers <= inliers.size())
      {
        bestModel = models[i];
        //** LOCAL OPTIMIZATION
        std::cout << "Before Optim: num inliers: " << inliers.size()
                << " score: " << score
                << " Kernel::MINIMUM_LSSAMPLES: " << Kernel::MINIMUM_LSSAMPLES
                << std::endl;

        std::cout << "Model:\n" << bestModel << std::endl;

        if(inliers.size() > Kernel::MINIMUM_LSSAMPLES)
        {
          score = localOptimization(kernel, scorer, bestModel, inliers);
        }
        std::cout << "After Optim: num inliers: " << inliers.size()
                << " score: " << score << std::endl;
        std::cout << "Model:\n" << bestModel << std::endl;

        bestNumInliers = inliers.size();
        bestInlierRatio = inliers.size() / double(total_samples);

        if (best_inliers)
        {
          best_inliers->swap(inliers);
        }

        if(bVerbose)
        {
          std::cout << " inliers=" << bestNumInliers << "/" << total_samples
                    << " (iter=" << iteration
                    << " ,i=" << i;
          std::cout << ",sample=";
          std::copy(sample.begin(), sample.end(),
                    std::ostream_iterator<std::size_t>(std::cout, ","));
          std::cout << ")";
        }
        if (bestInlierRatio)
        {
          max_iterations = IterationsRequired(min_samples,
                                              outliers_probability,
                                              bestInlierRatio);
          // safeguard to not get stuck in a big number of iterations
          max_iterations = std::min(max_iterations, really_max_iterations);
          if(bVerbose)
            std::cout << " New max_iteration: " << max_iterations << std::endl;
        }
      }
    }
  }
  if (best_score)
    *best_score = bestNumInliers;

  if(bestNumInliers)
    kernel.Unnormalize(&bestModel);

  return bestModel;
}

} // namespace robust
} // namespace openMVG<commit_msg>[robust] doc for loransac<commit_after>#pragma once

#include "openMVG/robust_estimation/rand_sampling.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp"
#include "openMVG/robust_estimation/robust_ransac_tools.hpp"
#include <limits>
#include <numeric>
#include <iostream>
#include <vector>
#include <iterator>

namespace openMVG {
namespace robust{

/**
 * @brief It performs an iterative reweighted least square (IRLS) estimation of the problem
 * defined by \p Kernel. At each step it perform a LS estimation using weights
 * for each data element computed iteratively on some residual error.
 * This implementation follow the Algorithm 3 described in
 *
 * Karel Lebeda, Jiri Matas, Ondrej Chum:
 * Fixing the Locally Optimized RANSAC. BMVC 2012: 1-11
 *
 * @tparam Kernel The kernel used in the LORansac estimator which must provide a
 * minimum solver and a LS solver, the latter used here for the IRLS
 * @see openMVG/robust_estimation/robust_estimator_LORansacKernelAdaptor.hpp
 * @tparam Scorer The scorer used in the LORansac estimator @see ScorerEvaluator
 *
 * @param[in] kernel The kernel used in the LORansac estimator.
 * @param[in] scorer The scorer used in the LORansac estimator.
 * @param[out] best_model The best model found at the end of the iterations.
 * @param[out] inliers The inliers supporting the best model.
 * @param[in] mtheta A threshold multiplier used to vary the threshold of the scorer.
 * @param[in] numIter The max number of iterations to run.
 * @return the score of the best model as computed by the Scorer, infinity if the
 * process does not converge.
 */
template<typename Kernel, typename Scorer>
double iterativeReweightedLeastSquares(const Kernel &kernel,
                                     const Scorer &scorer,
                                     typename Kernel::Model &best_model,
                                     std::vector<std::size_t> &inliers,
                                     double mtheta = std::sqrt(2),
                                     std::size_t numIter = 4)
{
  const std::size_t total_samples = kernel.NumSamples();
  const std::size_t min_samples = Kernel::MINIMUM_LSSAMPLES;
  double theta = scorer.getThreshold();
  // used in the iterations to update (reduce) the threshold value
  const double deltaTetha = (mtheta*theta - theta) / (numIter-1);

  std::vector<std::size_t> all_samples(total_samples);
  std::iota(all_samples.begin(), all_samples.end(), 0);

  // find inliers from best model with threshold theta
  inliers.clear();
  scorer.Score(kernel, best_model, all_samples, &inliers, theta);

  if(inliers.size() < min_samples)
  {
    inliers.clear();
    std::cerr << "[IRLS] returning cause inliers.size() < min_samples" << std::endl;
    return std::numeric_limits<double>::infinity();
  }

  // LS model from the above inliers
  std::vector<typename Kernel::Model> models;
  kernel.FitLS(inliers, &models);
  assert(models.size()==1);   // LS fitting must always return 1 model

  // change threshold for refinement
  theta *= mtheta;

  // iterative refinement
  for(std::size_t i = 0; i < numIter; ++i)
  {
    // find inliers on the best-so-far model
    // @todo maybe inliers instead of all samples to save some computation
    inliers.clear();
    scorer.Score(kernel, models[0], all_samples, &inliers, theta);

    if(inliers.size() < min_samples)
    {
      inliers.clear();
      std::cerr << "[IRLS] returning cause inliers.size() < min_samples" << std::endl;
      return std::numeric_limits<double>::infinity();
    }
//    std::cout << "[IRLS] #" << i
//            << " theta: " << theta
//            << " num inliers: " << inliers.size() << std::endl;

    // compute the weights for the inliers
    std::vector<double> weights;
    kernel.computeWeights(models[0], inliers, weights);

    // LS with weights on inliers
    models.clear();
    kernel.FitLS(inliers, &models, &weights);
    if(models.size() != 1)   // LS fitting must always return 1 model
    {
      std::cerr << "[IRLS] found "<< models.size() << " models, aborting..." << std::endl;
      return std::numeric_limits<double>::infinity();
    }

    // update the threshold
    theta -= deltaTetha;
  }

  assert(models.size()==1);
  best_model = models[0];
  inliers.clear();
  const double score = scorer.Score(kernel, best_model, all_samples, &inliers, theta);
  std::cout << "[IRLS] returning with num inliers: " << inliers.size()
          << " and score " << score << std::endl;
  return score;
}

/**
 * @brief The local optimization step used by LORansac. It takes as input a model
 * and its inliers computed by a minimal solver and refine the solution by using
 * IRLS (@see iterativeReweightedLeastSquares()). It first estimates a new model
 * using LS and its associated inliers. Then it repeatedly (\p numRep) re-estimate
 * a new model by LS on a randomly drawn sample of those inliers and then refine
 * the model by IRLS. The best found model (in terms of number of supporting inliers
 * is then returned.
 *
 * This implementation follow the Algorithm 2 described in
 *
 * Karel Lebeda, Jiri Matas, Ondrej Chum:
 * Fixing the Locally Optimized RANSAC. BMVC 2012: 1-11
 *
 * @tparam Kernel The kernel used in the LORansac estimator which must provide a
 * minimum solver and a LS solver, the latter used here for the IRLS
 * @see openMVG/robust_estimation/robust_estimator_LORansacKernelAdaptor.hpp
 * @tparam Scorer The scorer used in the LORansac estimator @see ScorerEvaluator
 *
 * @param[in] kernel The kernel used in the LORansac estimator.
 * @param[in] scorer The scorer used in the LORansac estimator.
 * @param[in,out] best_model In input the model estimated by a minimum solver, as
 * output the best model found.
 * @param[out] bestInliers The inliers supporting the best model.
 * @param[in] mtheta A threshold multiplier used for IRLS.
 * @param[in] numRep The number of re-sampling/re-estimation of the model.
 * @param[in] minSampleSize Size of the inner sample used for re-estimation.
 * @return the best score of the best model as computed by Scorer.
 */
template<typename Kernel, typename Scorer>
double localOptimization(const Kernel &kernel,
                       const Scorer &scorer,
                       typename Kernel::Model &bestModel,
                       std::vector<std::size_t> &bestInliers,
                       double mtheta = std::sqrt(2),
                       std::size_t numRep = 10,
                       std::size_t minSampleSize = 10)
{
  const std::size_t total_samples = kernel.NumSamples();
  const std::size_t min_samples = Kernel::MINIMUM_LSSAMPLES;
  assert((total_samples > min_samples) &&
          "[localOptimization] not enough data to estimate the model!");

  const double theta = scorer.getThreshold();

  std::vector<std::size_t> all_samples(total_samples);
  std::iota(all_samples.begin(), all_samples.end(), 0);

  std::size_t debugInit = 0;
  if(!bestInliers.empty())
  {
    debugInit = bestInliers.size();
    bestInliers.clear();
  }
  double bestScore = scorer.Score(kernel, bestModel, all_samples, &bestInliers, theta);
  if(debugInit != 0) assert(debugInit == bestInliers.size());

  // so far this is the best model
  std::size_t bestNumInliers = bestInliers.size();
  std::cout << "[localOptim] so far best num inliers: " << bestNumInliers << std::endl;
  std::cout << "[localOptim] so far best model:\n" << bestModel << std::endl;
  std::cout << "[localOptim] so far best score: " << bestScore << std::endl;

  // find inliers from best model with larger threshold t*m over all the samples
  std::vector<std::size_t> inliersBase;
  scorer.Score(kernel, bestModel, all_samples, &inliersBase, theta*mtheta);
  assert((inliersBase.size() > min_samples) &&
          "[localOptimization] not enough data in inliersBase to estimate the model!");

  // LS model from the above inliers
  std::vector<typename Kernel::Model> models;
  kernel.FitLS(inliersBase, &models);
  assert(models.size()==1);   // LS fitting must always return 1 model

  // find inliers with t again over all the samples
  inliersBase.clear();
  scorer.Score(kernel, models[0], all_samples, &inliersBase, theta);

  // sample of size sampleSize from the last best inliers
  const std::size_t sampleSize = std::min(minSampleSize, inliersBase.size()/2);
  if(sampleSize <= Kernel::MINIMUM_LSSAMPLES)
  {
    std::cout << "breaking cause sampleSize is " << sampleSize << std::endl;
    return bestScore;
  }

  // do numRep resampling + iterative LS
  for(std::size_t i = 0; i < numRep; ++i)
  {
    std::vector<std::size_t> sample;
    UniformSample(sampleSize, inliersBase, &sample);
    assert(sampleSize > Kernel::MINIMUM_LSSAMPLES);
    assert(sample.size() > Kernel::MINIMUM_LSSAMPLES);

    // LS estimation from the sample
    models.clear();
    kernel.FitLS(sample, &models);
    assert(models.size()==1);   // LS fitting must always return 1 model

    // IRLS
    std::vector<std::size_t> inliers;
    const double score = iterativeReweightedLeastSquares(kernel, scorer, models[0], inliers);

    // store new best model if it is the case
    if((inliers.size() > bestNumInliers) ||
       ((inliers.size() == bestNumInliers) && (score < bestScore)))
    {
      bestNumInliers = inliers.size();
      bestScore = score;
      bestModel = models[0];
      bestInliers.swap(inliers);
      std::cout << "[localOptim] new best num inliers: " << bestNumInliers << std::endl;
    }
  }
  return bestScore;
}

//@todo make visible parameters for the optimization step
/**
 * @brief Implementation of the LORansac framework.
 *
 * This implementation follow the Algorithm 1 described in
 *
 * Karel Lebeda, Jiri Matas, Ondrej Chum:
 * Fixing the Locally Optimized RANSAC. BMVC 2012: 1-11
 *
 * @tparam Kernel The kernel used in the LORansac estimator which must provide a
 * minimum solver and a LS solver, the latter used here for the IRLS
 * @see openMVG/robust_estimation/robust_estimator_LORansacKernelAdaptor.hpp
 * @tparam Scorer The scorer used in the LORansac estimator @see ScorerEvaluator
 *
 * @param[in] kernel The kernel containing the problem to solve.
 * @param[in] scorer The scorer used to asses the model quality.
 * @param[out] best_inliers The indices of the samples supporting the best model.
 * @param[out] best_score The score of the best model, ie the number of inliers
 * supporting the best model.
 * @param[in] bVerbose Enable/Disable log messages
 * @param[in] max_iterations Maximum number of iterations for the ransac part.
 * @param[in] outliers_probability The wanted probability of picking outliers.
 * @return The best model found.
 */
template<typename Kernel, typename Scorer>
typename Kernel::Model LO_RANSAC(const Kernel &kernel,
                                const Scorer &scorer,
                                std::vector<std::size_t> *best_inliers = NULL,
                                double *best_score = NULL,
                                bool bVerbose = true,
                                std::size_t max_iterations = 100,
                                double outliers_probability = 1e-2)
{
  assert(outliers_probability < 1.0);
  assert(outliers_probability > 0.0);
  std::size_t iteration = 0;
  const std::size_t min_samples = Kernel::MINIMUM_SAMPLES;
  const std::size_t total_samples = kernel.NumSamples();

  const std::size_t really_max_iterations = 4096;

  std::size_t bestNumInliers = 0;
  double bestInlierRatio = 0.0;
  typename Kernel::Model bestModel;

  // Test if we have sufficient points for the kernel.
  if (total_samples < min_samples)
  {
    if (best_inliers) {
      best_inliers->clear();
    }
    return bestModel;
  }

  // In this robust estimator, the scorer always works on all the data points
  // at once. So precompute the list ahead of time [0,..,total_samples].
  std::vector<std::size_t> all_samples(total_samples);
  std::iota(all_samples.begin(), all_samples.end(), 0);

  std::vector<std::size_t> sample;
  for(iteration = 0; iteration < max_iterations; ++iteration)
  {
    UniformSample(min_samples, total_samples, &sample);

    std::vector<typename Kernel::Model> models;
    kernel.Fit(sample, &models);

    // Compute the inlier list for each fit.
    for(std::size_t i = 0; i < models.size(); ++i)
    {
      std::vector<std::size_t> inliers;
      double score = scorer.Score(kernel, models[i], all_samples, &inliers);
      std::cout << "sample=";
      std::sort(sample.begin(), sample.end());
      std::copy(sample.begin(), sample.end(),
                    std::ostream_iterator<std::size_t>(std::cout, ","));
      std::cout << "\nmodel " << i
              << " e: " << score << std::endl;

      if (bestNumInliers <= inliers.size())
      {
        bestModel = models[i];
        //** LOCAL OPTIMIZATION
        std::cout << "Before Optim: num inliers: " << inliers.size()
                << " score: " << score
                << " Kernel::MINIMUM_LSSAMPLES: " << Kernel::MINIMUM_LSSAMPLES
                << std::endl;

        std::cout << "Model:\n" << bestModel << std::endl;

        if(inliers.size() > Kernel::MINIMUM_LSSAMPLES)
        {
          score = localOptimization(kernel, scorer, bestModel, inliers);
        }
        std::cout << "After Optim: num inliers: " << inliers.size()
                << " score: " << score << std::endl;
        std::cout << "Model:\n" << bestModel << std::endl;

        bestNumInliers = inliers.size();
        bestInlierRatio = inliers.size() / double(total_samples);

        if (best_inliers)
        {
          best_inliers->swap(inliers);
        }

        if(bVerbose)
        {
          std::cout << " inliers=" << bestNumInliers << "/" << total_samples
                    << " (iter=" << iteration
                    << " ,i=" << i;
          std::cout << ",sample=";
          std::copy(sample.begin(), sample.end(),
                    std::ostream_iterator<std::size_t>(std::cout, ","));
          std::cout << ")";
        }
        if (bestInlierRatio)
        {
          max_iterations = IterationsRequired(min_samples,
                                              outliers_probability,
                                              bestInlierRatio);
          // safeguard to not get stuck in a big number of iterations
          max_iterations = std::min(max_iterations, really_max_iterations);
          if(bVerbose)
            std::cout << " New max_iteration: " << max_iterations << std::endl;
        }
      }
    }
  }
  if (best_score)
    *best_score = bestNumInliers;

  if(bestNumInliers)
    kernel.Unnormalize(&bestModel);

  return bestModel;
}

} // namespace robust
} // namespace openMVG<|endoftext|>


<commit_before>#include <memory>
#include <random>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <cstdio> // only __FILE__ __LINE__ macros
#include <map>

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/rand.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/x509.h>

#include <cassert>

#include "utils.h"

using std::unique_ptr;
using std::string;
using std::cout;
using std::cerr;
using std::stringstream;
using std::ifstream;
using std::exception;
using std::runtime_error;
using std::map;

using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>;
using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>;
using EVP_KEY_ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
using BIO_FILE_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>;

string seed_random_number_gen()
{
    const int SEED_SZ = 128;
    int rc;

    //std::uniform_int_distribution<int> d(0, 9);
    //stringstream ss;

    //std::random_device rd1; // uses RDRND or /dev/urandom

    // for(int n = 0; n < SEED_SZ; ++n) {
    //     ss << d(rd1);
    // }

    char buf[SEED_SZ];
    int fd = open("/dev/random", O_RDONLY);
    if (fd == -1) {
        throw std::runtime_error("Err opening /dev/random" FILE_LINE);
    }
    int n = read(fd, buf, sizeof(buf)-1);
    if (n == -1) {
        throw std::runtime_error("Err reading /dev/random" FILE_LINE);
    }
    close(fd);
    cout << "Seeding SSL RNG from /dev/random...\n";
    RAND_add(buf, sizeof(buf), n);

    buf[n] = '\0';
    cout << "Generated random seed:\n";
    cout << buf << '\n';
    //string seed = ss.str();
    //cout << seed << '\n';

    // Seed the openssl RNG
    //cout << "Seeding SSL RNG from /dev/urandom...\n";
    //RAND_add(seed.c_str(), seed.length(), seed.length());

    rc = RAND_status();
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

    return string(buf);
}

void generate_key_pair(string& seed)
{
    int rc;

    RSA_ptr rsa(RSA_new(), ::RSA_free);
    BN_ptr bn(BN_new(), ::BN_free);

    BIO_FILE_ptr pem1(BIO_new_file("rsa-public-1.pem", "w"), ::BIO_free);

    BIO_FILE_ptr pem3(BIO_new_file("rsa-private-1.pem", "w"), ::BIO_free);

    rc = BN_set_word(bn.get(), RSA_F4);
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

    // Generate key
    rc = RSA_generate_key_ex(rsa.get(), 2048, bn.get(), NULL);
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

    // Convert RSA to PKEY
    EVP_KEY_ptr pkey(EVP_PKEY_new(), ::EVP_PKEY_free);
    rc = EVP_PKEY_set1_RSA(pkey.get(), rsa.get());
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

    //////////

    // Write public key in PKCS PEM
    rc = PEM_write_bio_RSAPublicKey(pem1.get(), rsa.get());
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

    // Write private key in PKCS PEM.
    rc = PEM_write_bio_PrivateKey(pem3.get(), pkey.get(), NULL, NULL, 0, NULL,
                                  NULL);
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

}

int open_socket()
{
    int fd;
    int retval;

    fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (fd == -1) {
        throw std::runtime_error("Could not open socket" FILE_LINE);
    }

    unlink(SOCK_NAME);
    sockaddr_un addr;
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, SOCK_NAME, sizeof(addr.sun_path)-1);
    retval = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    if (retval == -1) {
        perror(NULL);
        throw std::runtime_error("bind() " FILE_LINE);
    }

    retval = listen(fd, 5);
    if (retval == -1) {
        throw std::runtime_error("listen() " FILE_LINE);
    }
    return fd;
}

void close_socket(int fd)
{
    close(fd);

    /* remove the FIFO */
    unlink(SOCK_NAME);
}

string read_socket(int fd)
{
    char buf[MAX_BUF];

    ssize_t num = read(fd, buf, MAX_BUF);
    if (num == -1) {
        throw std::runtime_error("read() " FILE_LINE);
    }
    printf("Received: %s\n", buf);

    return string(buf);
}

void write_socket(int fd)
{
    ifstream pubkey_file;
    pubkey_file.open("rsa-public-1.pem");

    string pubkey;
    string line;
    if (pubkey_file.is_open())
    {
        while (getline(pubkey_file, line))
        {
            cout << line << '\n';
            pubkey += line;
        }
        pubkey_file.close();
    }

    ssize_t num = write(fd, pubkey.c_str(), pubkey.length()+1);
    if (num == -1) {
        throw std::runtime_error("write() " FILE_LINE);
    }
}

int main(int argc, char* argv[])
{
    cout << "Starting token (pubkey) server...\n";

    int fd = -1;

    fd = open_socket();
    std::map<string, time_t> voters;

    try {
        for (;;) {
            string seed = seed_random_number_gen();
            generate_key_pair(seed);

            int cli_fd = accept(fd, NULL, NULL);
            if (cli_fd == -1) {
                throw std::runtime_error("accept() " FILE_LINE);
            }

            string voter = read_socket(cli_fd);
            cout << "Handing out token (pubkey) for voter " << voter << '\n';
            write_socket(cli_fd);
            voters.insert(std::make_pair(voter, time(nullptr)));
            close(cli_fd);
        }
    }
    catch (exception& ex) {
        cerr << ex.what() << '\n';
    }
    catch (...)
    {
        cerr << "Unknown error!\n";
    }

    close_socket(fd);

    return 0;
}
<commit_msg>Added give/deny token functionality<commit_after>#include <memory>
#include <random>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <cstdio> // only __FILE__ __LINE__ macros
#include <map>

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/rand.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/x509.h>

#include <cassert>

#include "utils.h"

using std::unique_ptr;
using std::string;
using std::cout;
using std::cerr;
using std::stringstream;
using std::ifstream;
using std::exception;
using std::runtime_error;
using std::map;

using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>;
using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>;
using EVP_KEY_ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
using BIO_FILE_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>;

enum class TokenStatus {
    GIVE_TOKEN = 1,
    DENY_TOKEN = 2
};

string seed_random_number_gen()
{
    const int SEED_SZ = 32;
    int rc;

    char buf[SEED_SZ];
    int fd = open("/dev/random", O_RDONLY);
    if (fd == -1) {
        throw std::runtime_error("Err opening /dev/random" FILE_LINE);
    }
    int n = read(fd, buf, sizeof(buf)-1);
    if (n == -1) {
        throw std::runtime_error("Err reading /dev/random" FILE_LINE);
    }
    close(fd);
    cout << "Seeding SSL RNG from /dev/random...\n";
    RAND_add(buf, sizeof(buf), n);

    buf[n] = '\0';
    cout << "Generated random seed:\n";
    cout << buf << '\n';

    rc = RAND_status();
    if (rc != 1)
        throw std::runtime_error("Open SSL (RAND_status()): " FILE_LINE);

    return string(buf);
}

void generate_key_pair(string& seed)
{
    int rc;

    RSA_ptr rsa(RSA_new(), ::RSA_free);
    BN_ptr bn(BN_new(), ::BN_free);

    BIO_FILE_ptr pem1(BIO_new_file("rsa-public-1.pem", "w"), ::BIO_free);

    BIO_FILE_ptr pem3(BIO_new_file("rsa-private-1.pem", "w"), ::BIO_free);

    rc = BN_set_word(bn.get(), RSA_F4);
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

    // Generate key
    rc = RSA_generate_key_ex(rsa.get(), 2048, bn.get(), NULL);
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

    // Convert RSA to PKEY
    EVP_KEY_ptr pkey(EVP_PKEY_new(), ::EVP_PKEY_free);
    rc = EVP_PKEY_set1_RSA(pkey.get(), rsa.get());
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

    // Write public key in PKCS PEM
    rc = PEM_write_bio_RSAPublicKey(pem1.get(), rsa.get());
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

    // Write private key in PKCS PEM.
    rc = PEM_write_bio_PrivateKey(pem3.get(), pkey.get(), NULL, NULL, 0, NULL,
                                  NULL);
    if (rc != 1)
        throw std::runtime_error("Open SSL: " FILE_LINE);

}

int open_socket()
{
    int fd;
    int retval;

    fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (fd == -1) {
        throw std::runtime_error("Could not open socket" FILE_LINE);
    }

    unlink(SOCK_NAME);
    sockaddr_un addr;
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, SOCK_NAME, sizeof(addr.sun_path)-1);
    retval = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    if (retval == -1) {
        perror(NULL);
        throw std::runtime_error("bind() " FILE_LINE);
    }

    retval = listen(fd, 5);
    if (retval == -1) {
        throw std::runtime_error("listen() " FILE_LINE);
    }
    return fd;
}

void close_socket(int fd)
{
    close(fd);

    /* remove the FIFO */
    unlink(SOCK_NAME);
}

string read_socket(int fd)
{
    char buf[MAX_BUF];

    ssize_t num = read(fd, buf, MAX_BUF);
    if (num == -1) {
        throw std::runtime_error("read() " FILE_LINE);
    }
    printf("Received: %s\n", buf);

    return string(buf);
}

void write_socket(int fd, TokenStatus status)
{

    string pubkey;
    if (status == TokenStatus::GIVE_TOKEN) {
        ifstream pubkey_file;
        pubkey_file.open("rsa-public-1.pem");

        string line;
        if (pubkey_file.is_open())
        {
            while (getline(pubkey_file, line))
            {
                cout << line << '\n';
                pubkey += line;
            }
            pubkey_file.close();
        }
    }
    else { // DENY_TOKEN
        pubkey = "WARNING: TOKEN DENIED, VOTER ALREADY RECEIVED TOKEN!";
    }

    ssize_t num = write(fd, pubkey.c_str(), pubkey.length()+1);
    if (num == -1) {
        throw std::runtime_error("write() " FILE_LINE);
    }
}

int main(int argc, char* argv[])
{
    cout << "Starting token (pubkey) server...\n";

    int fd = -1;

    fd = open_socket();
    std::map<string, time_t> voters;

    try {
        for (;;) {
            string seed = seed_random_number_gen();
            generate_key_pair(seed);

            int cli_fd = accept(fd, NULL, NULL);
            if (cli_fd == -1) {
                throw std::runtime_error("accept() " FILE_LINE);
            }

            string voter = read_socket(cli_fd);
            auto it = voters.find(voter);
            if (it == voters.end()) {
                cout << "Handing out token (pubkey) for voter " << voter << '\n';
                write_socket(cli_fd, TokenStatus::GIVE_TOKEN);
            }
            else {
                cout << "DENYING token (pubkey) for voter " << voter << '\n';
                write_socket(cli_fd, TokenStatus::DENY_TOKEN);
            }
            voters.insert(std::make_pair(voter, time(nullptr)));
            close(cli_fd);
        }
    }
    catch (exception& ex) {
        cerr << ex.what() << '\n';
    }
    catch (...)
    {
        cerr << "Unknown error!\n";
    }

    close_socket(fd);

    return 0;
}
<|endoftext|>


<commit_before>#include "SimpleWindow.hpp"
#include <QHBoxLayout>
#include <QApplication>
using namespace fast;

void SimpleWindow::addRenderer(Renderer::pointer renderer) {
    mView->addRenderer(renderer);
}

void SimpleWindow::setMaximumFramerate(unsigned char framerate) {
    mFramerate = framerate;
}

SimpleWindow::SimpleWindow() {
    mFramerate = 25;
    mView = View::New();

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(mView.getPtr().get());
    setLayout(mainLayout);
    setWindowTitle(tr("FAST"));
}

void SimpleWindow::runMainLoop() {

    show();
    QApplication::exec();
}

void SimpleWindow::keyPressEvent(QKeyEvent* event) {
    mView->keyPressEvent(event);
}

void SimpleWindow::mouseMoveEvent(QMouseEvent* event) {
    mView->mouseMoveEvent(event);
}

void SimpleWindow::mousePressEvent(QMouseEvent* event) {
    mView->mousePressEvent(event);
}

void SimpleWindow::mouseReleaseEvent(QMouseEvent* event) {
    mView->mouseReleaseEvent(event);
}

void SimpleWindow::setWindowSize(unsigned int w, unsigned int h) {
    this->resize(w,h);
}
<commit_msg>set default window size to 512 x 512<commit_after>#include "SimpleWindow.hpp"
#include <QHBoxLayout>
#include <QApplication>
using namespace fast;

void SimpleWindow::addRenderer(Renderer::pointer renderer) {
    mView->addRenderer(renderer);
}

void SimpleWindow::setMaximumFramerate(unsigned char framerate) {
    mFramerate = framerate;
}

SimpleWindow::SimpleWindow() {
    mFramerate = 25;
    mView = View::New();

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(mView.getPtr().get());
    setLayout(mainLayout);
    setWindowTitle(tr("FAST"));
    resize(512,512); // default window size
}

void SimpleWindow::runMainLoop() {

    show();
    QApplication::exec();
}

void SimpleWindow::keyPressEvent(QKeyEvent* event) {
    mView->keyPressEvent(event);
}

void SimpleWindow::mouseMoveEvent(QMouseEvent* event) {
    mView->mouseMoveEvent(event);
}

void SimpleWindow::mousePressEvent(QMouseEvent* event) {
    mView->mousePressEvent(event);
}

void SimpleWindow::mouseReleaseEvent(QMouseEvent* event) {
    mView->mouseReleaseEvent(event);
}

void SimpleWindow::setWindowSize(unsigned int w, unsigned int h) {
    this->resize(w,h);
}
<|endoftext|>