<commit_before>#include<bits/stdc++.h>
#include "sg-lexer.hpp"
#include "sg-parser.hpp"
#include "sg-ast.hpp"
#include "sg-linker.hpp"
#include "sg-graph.hpp"
#include "sg-bash-generator.hpp"
#include "sg-helpers.hpp"
#include "core-script.cpp" // contains the sg core as string literal
#include "argparse.hpp"
#define token std::pair<std::string, std::string> // token type, token content
#define Group_namespace std::unordered_map<std::string, Group*>

// The sg compiler
// Pascal Sommer, 2016

std::string version_number = "0.5";

void info_message(){
    std::cerr<<"StreamGraph compiler " << version_number << "\n";
    std::cerr<<"Copyright (C) 2016 Pascal Sommer\n";
}

void help_message(){
    std::cerr<<"Usage: sg infile [-o outfile]\n";
}

std::string get_base_name(std::string name){
    return name.substr(name.find_last_of("/") + 1);
}

std::string get_date(){
    time_t now = time(0);
    // convert `now` to string form
    std::string str_datetime = ctime(&now);
    return str_datetime;
}

void compilation_failed(){
    std::cerr<<"\nCompilation \033[0;31mfailed\033[0m at " << get_date() << "\n";
}

int main(int argc, char* argv[]){

    // parse options with argparse
    std::vector<option> argparse_options;

    // the input filename
    argparse_options.push_back({0, "", "", true});

    // the destination of the compiled bash script
    argparse_options.push_back({1, "o", "output-file", true});

    // display the help message
    argparse_options.push_back({99, "h", "help", false});

    auto parsed_options = argparse(argparse_options, argc, argv);

    // exit if argparse returned an error
    if(parsed_options.find(-1) != parsed_options.end()){
        help_message();
	std::cerr<<"\n";
	compilation_failed();
        return 1;
    }

    // display help message
    if(parsed_options.find(99) != parsed_options.end()){
	info_message();
	std::cerr<<"\n";
        help_message();
        return 0;
    }

    if (parsed_options.find(0)==parsed_options.end()){
	std::cerr<<"No input file given.\n";
	std::cerr<<"\n";
	help_message();
	std::cerr<<"\n";
	compilation_failed();
	return 1;
    }

    std::string program_path= parsed_options[0];
    std::string output_file;
    if (parsed_options.find(1)!=parsed_options.end()){
	// output path was given
	output_file = parsed_options[1];
    }else{
	if(program_path.substr(program_path.length() -3) == ".sg"){
	    output_file = program_path.substr(0, program_path.length() - 3);
	}else{
	    output_file = program_path;
	}
	output_file += ".sh";
    }

    std::string program_name = get_base_name(program_path);

    std::ifstream infile (program_path);
    if( ! infile.is_open()){
	print_error("Couldn't open file " + program_path + ".");
	compilation_failed();
	return 1;
    }

    Lexer l (program_path, infile);

    // lex the source code
    auto result = l.lex();

    if(result.back().first=="ERROR"){
	compilation_failed();
	return 1;
    }

    // parse the token stream
    Group* ast = parse(result);
    if (ast == 0){
	compilation_failed();
	return 1;
    }

    ast->name = program_name;

    // create an empty namespace to start the linker method
    Group_namespace gn;
    // link the DAG pointers in the AST
    bool link_ok = link(ast, gn);
    if ( ! link_ok){
	compilation_failed();
	return 1;
    }

    // create an empty group stack to start the graph checker
    std::stack<Group*> empty_group_stack;
    // check the graph for errors and remove unneccessary parts
    bool graph_ok = groups_check(ast, empty_group_stack);
    if ( ! graph_ok){
	compilation_failed();
	return 1;
    }

    // generate the bash script
    std::string bash_script = generate_bash_script(ast, sg_core, version_number);

    std::ofstream out_file_stream(output_file);
    if( ! out_file_stream.is_open() ){
	std::cerr << "Can't write to output file \"" << output_file << "\"\n";
	help_message();
	return 1;
    }
    out_file_stream<<bash_script<<"\n";
    out_file_stream.close();

    return 0;
}
<commit_msg>Whitespace<commit_after>#include<bits/stdc++.h>
#include "sg-lexer.hpp"
#include "sg-parser.hpp"
#include "sg-ast.hpp"
#include "sg-linker.hpp"
#include "sg-graph.hpp"
#include "sg-bash-generator.hpp"
#include "sg-helpers.hpp"
#include "core-script.cpp" // contains the sg core as string literal
#include "argparse.hpp"
#define token std::pair<std::string, std::string> // token type, token content
#define Group_namespace std::unordered_map<std::string, Group*>

// The sg compiler
// Pascal Sommer, 2016

std::string version_number = "0.5";

void info_message(){
    std::cerr<<"StreamGraph compiler " << version_number << "\n";
    std::cerr<<"Pascal Sommer, 2016\n";
}

void help_message(){
    std::cerr<<"Usage: sg infile [-o outfile]\n";
}

std::string get_base_name(std::string name){
    return name.substr(name.find_last_of("/") + 1);
}

std::string get_date(){
    time_t now = time(0);
    // convert `now` to string form
    std::string str_datetime = ctime(&now);
    return str_datetime;
}

void compilation_failed(){
    std::cerr<<"\nCompilation \033[0;31mfailed\033[0m at " << get_date() << "\n";
}

int main(int argc, char* argv[]){

    // parse options with argparse
    std::vector<option> argparse_options;

    // the input filename
    argparse_options.push_back({0, "", "", true});

    // the destination of the compiled bash script
    argparse_options.push_back({1, "o", "output-file", true});

    // display the help message
    argparse_options.push_back({99, "h", "help", false});

    auto parsed_options = argparse(argparse_options, argc, argv);

    // exit if argparse returned an error
    if(parsed_options.find(-1) != parsed_options.end()){
	std::cerr<<"\n";
        help_message();
	compilation_failed();
        return 1;
    }

    // display help message
    if(parsed_options.find(99) != parsed_options.end()){
	info_message();
	std::cerr<<"\n";
        help_message();
        return 0;
    }

    if (parsed_options.find(0)==parsed_options.end()){
	print_error("No input file given.");
	std::cerr<<"\n";
	help_message();
	compilation_failed();
	return 1;
    }

    std::string program_path= parsed_options[0];
    std::string output_file;
    if (parsed_options.find(1)!=parsed_options.end()){
	// output path was given
	output_file = parsed_options[1];
    }else{
	if(program_path.substr(program_path.length() -3) == ".sg"){
	    output_file = program_path.substr(0, program_path.length() - 3);
	}else{
	    output_file = program_path;
	}
	output_file += ".sh";
    }

    std::string program_name = get_base_name(program_path);

    std::ifstream infile (program_path);
    if( ! infile.is_open()){
	print_error("Couldn't open file " + program_path + ".");
	compilation_failed();
	return 1;
    }

    Lexer l (program_path, infile);

    // lex the source code
    auto result = l.lex();

    if(result.back().first=="ERROR"){
	compilation_failed();
	return 1;
    }

    // parse the token stream
    Group* ast = parse(result);
    if (ast == 0){
	compilation_failed();
	return 1;
    }

    ast->name = program_name;

    // create an empty namespace to start the linker method
    Group_namespace gn;
    // link the DAG pointers in the AST
    bool link_ok = link(ast, gn);
    if ( ! link_ok){
	compilation_failed();
	return 1;
    }

    // create an empty group stack to start the graph checker
    std::stack<Group*> empty_group_stack;
    // check the graph for errors and remove unneccessary parts
    bool graph_ok = groups_check(ast, empty_group_stack);
    if ( ! graph_ok){
	compilation_failed();
	return 1;
    }

    // generate the bash script
    std::string bash_script = generate_bash_script(ast, sg_core, version_number);

    std::ofstream out_file_stream(output_file);
    if( ! out_file_stream.is_open() ){
	std::cerr << "Can't write to output file \"" << output_file << "\"\n";
	help_message();
	return 1;
    }
    out_file_stream<<bash_script<<"\n";
    out_file_stream.close();

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AView.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 05:32:17 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_ADO_VIEW_HXX_
#include "ado/AView.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _CONNECTIVITY_ADO_ADOIMP_HXX_
#include "ado/adoimp.hxx"
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

// -------------------------------------------------------------------------
using namespace comphelper;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;

//  IMPLEMENT_SERVICE_INFO(OAdoView,"com.sun.star.sdbcx.AView","com.sun.star.sdbcx.View");
// -------------------------------------------------------------------------
OAdoView::OAdoView(sal_Bool _bCase,ADOView* _pView) : OView_ADO(_bCase,NULL)
,m_aView(_pView)
{
}
//--------------------------------------------------------------------------
Sequence< sal_Int8 > OAdoView::getUnoTunnelImplementationId()
{
    static ::cppu::OImplementationId * pId = 0;
    if (! pId)
    {
        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
        if (! pId)
        {
            static ::cppu::OImplementationId aId;
            pId = &aId;
        }
    }
    return pId->getImplementationId();
}

// com::sun::star::lang::XUnoTunnel
//------------------------------------------------------------------
sal_Int64 OAdoView::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)
{
    return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(),  rId.getConstArray(), 16 ) )
                ?
            (sal_Int64)this
                :
            OView_ADO::getSomething(rId);
}

// -------------------------------------------------------------------------
void OAdoView::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const
{
    if(m_aView.IsValid())
    {
        switch(nHandle)
        {
            case PROPERTY_ID_NAME:
                rValue <<= m_aView.get_Name();
                break;
            case PROPERTY_ID_CATALOGNAME:
                break;
            case PROPERTY_ID_SCHEMANAME:
                //  rValue <<= m_aView.get_Type();
                break;
            case PROPERTY_ID_COMMAND:
                {
                    OLEVariant aVar;
                    m_aView.get_Command(aVar);
                    if(!aVar.isNull() && !aVar.isEmpty())
                    {
                        ADOCommand* pCom = (ADOCommand*)aVar.getIDispatch();
                        OLEString aBSTR;
                        pCom->get_CommandText(&aBSTR);
                        rValue <<= (::rtl::OUString) aBSTR;
                    }
                }
                break;
        }
    }
    else
        OView_ADO::getFastPropertyValue(rValue,nHandle);
}
// -----------------------------------------------------------------------------
void SAL_CALL OAdoView::acquire() throw(::com::sun::star::uno::RuntimeException)
{
    OView_ADO::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OAdoView::release() throw(::com::sun::star::uno::RuntimeException)
{
    OView_ADO::release();
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS warnings01 (1.13.30); FILE MERGED 2005/11/07 14:43:10 fs 1.13.30.1: #i57457# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AView.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:16: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
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_ADO_VIEW_HXX_
#include "ado/AView.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _CONNECTIVITY_ADO_ADOIMP_HXX_
#include "ado/adoimp.hxx"
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

// -------------------------------------------------------------------------
using namespace comphelper;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;

//  IMPLEMENT_SERVICE_INFO(OAdoView,"com.sun.star.sdbcx.AView","com.sun.star.sdbcx.View");
// -------------------------------------------------------------------------
OAdoView::OAdoView(sal_Bool _bCase,ADOView* _pView) : OView_ADO(_bCase,NULL)
,m_aView(_pView)
{
}
//--------------------------------------------------------------------------
Sequence< sal_Int8 > OAdoView::getUnoTunnelImplementationId()
{
    static ::cppu::OImplementationId * pId = 0;
    if (! pId)
    {
        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
        if (! pId)
        {
            static ::cppu::OImplementationId aId;
            pId = &aId;
        }
    }
    return pId->getImplementationId();
}

// com::sun::star::lang::XUnoTunnel
//------------------------------------------------------------------
sal_Int64 OAdoView::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)
{
    return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(),  rId.getConstArray(), 16 ) )
                ? reinterpret_cast< sal_Int64 >( this )
                : OView_ADO::getSomething(rId);
}

// -------------------------------------------------------------------------
void OAdoView::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const
{
    if(m_aView.IsValid())
    {
        switch(nHandle)
        {
            case PROPERTY_ID_NAME:
                rValue <<= m_aView.get_Name();
                break;
            case PROPERTY_ID_CATALOGNAME:
                break;
            case PROPERTY_ID_SCHEMANAME:
                //  rValue <<= m_aView.get_Type();
                break;
            case PROPERTY_ID_COMMAND:
                {
                    OLEVariant aVar;
                    m_aView.get_Command(aVar);
                    if(!aVar.isNull() && !aVar.isEmpty())
                    {
                        ADOCommand* pCom = (ADOCommand*)aVar.getIDispatch();
                        OLEString aBSTR;
                        pCom->get_CommandText(&aBSTR);
                        rValue <<= (::rtl::OUString) aBSTR;
                    }
                }
                break;
        }
    }
    else
        OView_ADO::getFastPropertyValue(rValue,nHandle);
}
// -----------------------------------------------------------------------------
void SAL_CALL OAdoView::acquire() throw(::com::sun::star::uno::RuntimeException)
{
    OView_ADO::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OAdoView::release() throw(::com::sun::star::uno::RuntimeException)
{
    OView_ADO::release();
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>#include "LoginState.h"

using namespace Ogre;

LoginState::LoginState()
{
    m_bQuit         = false;
    m_FrameEvent    = Ogre::FrameEvent();
}

void LoginState::enter()
{
    OgreFramework::getSingletonPtr()->m_pLog->logMessage("Entering LoginState...");
    CEGUI::WindowManager& winMgr(CEGUI::WindowManager::getSingleton());

    CEGUI::Window* base = winMgr.createWindow("DefaultWindow", "CEGUIApp/XsiliumLogin");

    CEGUI::Window* sheet = winMgr.loadLayoutFromFile("XsiliumLogin.layout");
    // attach this to the 'real' root
    base->addChild(sheet);

	CEGUI::Window *frame = sheet->getChild("CEGUIApp");
	frame->activate();

	sheet->getChild("CEGUIApp/edtUsername")->
	        subscribeEvent(CEGUI::Editbox::EventTextAccepted, CEGUI::Event::Subscriber(&LoginState::handleSubmit, this));

	sheet->getChild("CEGUIApp/btnConnexion")->subscribeEvent(CEGUI::PushButton::EventClicked,
			CEGUI::Event::Subscriber(&LoginState::PushConnexion, this));

    CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(sheet);

    m_pSceneMgr = OgreFramework::getSingletonPtr()->m_pRoot->createSceneManager(ST_GENERIC, "LoginSceneMgr");
    m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.7f, 0.7f, 0.7f));

    m_pCamera = m_pSceneMgr->createCamera("MenuCam");
    m_pCamera->setPosition(Vector3(0, 50, 100));
    m_pCamera->lookAt(Vector3(0, 0, 0));
    m_pCamera->setNearClipDistance(1);

    m_pCamera->setAspectRatio(Real(OgreFramework::getSingletonPtr()->m_pViewport->getActualWidth()) /
        Real(OgreFramework::getSingletonPtr()->m_pViewport->getActualHeight()));

    OgreFramework::getSingletonPtr()->m_pViewport->setCamera(m_pCamera);

    fldUsername = sheet->getChild("CEGUIApp/edtUsername");

    createScene();
}

void LoginState::createScene()
{
    ParticleSystem* ps;
    ps = m_pSceneMgr->createParticleSystem("Nimbus", "Xsilium/GreenyNimbus");
    		m_pSceneMgr->getRootSceneNode()->attachObject(ps);
}

void LoginState::exit()
{
    OgreFramework::getSingletonPtr()->m_pLog->logMessage("Leaving LoginState...");

    m_pSceneMgr->destroyCamera(m_pCamera);
    if(m_pSceneMgr)
        OgreFramework::getSingletonPtr()->m_pRoot->destroySceneManager(m_pSceneMgr);

    CEGUI::WindowManager::getSingleton().destroyAllWindows();

}

bool LoginState::keyPressed(const OIS::KeyEvent &keyEventRef)
{
    if(OgreFramework::getSingletonPtr()->m_pKeyboard->isKeyDown(OIS::KC_ESCAPE))
    {
        m_bQuit = true;
        return true;
    }
    CEGUI::System& gui_system(CEGUI::System::getSingleton());

     // do event injection
     CEGUI::GUIContext& ctx = CEGUI::System::getSingleton().getDefaultGUIContext();

     // key down
     ctx.injectKeyDown(static_cast<CEGUI::Key::Scan>(keyEventRef.key));

     // now character
     ctx.injectChar(keyEventRef.text);
    OgreFramework::getSingletonPtr()->keyPressed(keyEventRef);
    return true;
}

bool LoginState::keyReleased(const OIS::KeyEvent &keyEventRef)
{
    CEGUI::System::getSingleton().getDefaultGUIContext().
        injectKeyUp(static_cast<CEGUI::Key::Scan>(keyEventRef.key));
    OgreFramework::getSingletonPtr()->keyReleased(keyEventRef);
    return true;
}

bool LoginState::mouseMoved(const OIS::MouseEvent &evt)
{
	CEGUI::GUIContext& ctx = CEGUI::System::getSingleton().getDefaultGUIContext();

	   ctx.injectMouseMove(evt.state.X.rel, evt.state.Y.rel);
	   ctx.injectMouseWheelChange(evt.state.Z.rel / 120.0f);
    return true;
}

bool LoginState::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
    CEGUI::System::getSingleton().getDefaultGUIContext().
        injectMouseButtonDown(convertOISButtonToCegui(id));
    return true;
}

bool LoginState::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
    CEGUI::System::getSingleton().getDefaultGUIContext().
        injectMouseButtonUp(convertOISButtonToCegui(id));
    return true;
}

void LoginState::update(double timeSinceLastFrame)
{
    m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame;

    CEGUI::System& gui_system(CEGUI::System::getSingleton());

    gui_system.injectTimePulse(timeSinceLastFrame);
    gui_system.getDefaultGUIContext().injectTimePulse(timeSinceLastFrame);

    if(m_bQuit == true)
    {
        shutdown();
        return;
    }
}

bool LoginState::PushConnexion(const CEGUI::EventArgs &e)
		{
			OgreFramework::getSingletonPtr()->m_pLog->logMessage("Click PushConnexion!!!");
			changeAppState(findByName("GameState"));
			return true;
		}

bool LoginState::handleSubmit(const CEGUI::EventArgs&)
{
	CEGUI::String valueUsername =  fldUsername->getText();

	printf("test %s \n",valueUsername.c_str());

    return true;
}

CEGUI::MouseButton LoginState::convertOISButtonToCegui(int buttonID)
{
   using namespace OIS;

   switch (buttonID)
    {
   case OIS::MB_Left:
        return CEGUI::LeftButton;
   case OIS::MB_Right:
        return CEGUI::RightButton;
   case OIS::MB_Middle:
        return CEGUI::MiddleButton;
    default:
        return CEGUI::LeftButton;
    }

}

<commit_msg>Déplacement de l'affichage de printf valueUsername.c_str()); dans PushConnexion<commit_after>#include "LoginState.h"

using namespace Ogre;

LoginState::LoginState()
{
    m_bQuit         = false;
    m_FrameEvent    = Ogre::FrameEvent();
}

void LoginState::enter()
{
    OgreFramework::getSingletonPtr()->m_pLog->logMessage("Entering LoginState...");
    CEGUI::WindowManager& winMgr(CEGUI::WindowManager::getSingleton());

    CEGUI::Window* base = winMgr.createWindow("DefaultWindow", "CEGUIApp/XsiliumLogin");

    CEGUI::Window* sheet = winMgr.loadLayoutFromFile("XsiliumLogin.layout");
    // attach this to the 'real' root
    base->addChild(sheet);

	CEGUI::Window *frame = sheet->getChild("CEGUIApp");
	frame->activate();

	sheet->getChild("CEGUIApp/edtUsername")->
	        subscribeEvent(CEGUI::Editbox::EventTextAccepted, CEGUI::Event::Subscriber(&LoginState::handleSubmit, this));

	sheet->getChild("CEGUIApp/btnConnexion")->subscribeEvent(CEGUI::PushButton::EventClicked,
			CEGUI::Event::Subscriber(&LoginState::PushConnexion, this));

    CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(sheet);

    m_pSceneMgr = OgreFramework::getSingletonPtr()->m_pRoot->createSceneManager(ST_GENERIC, "LoginSceneMgr");
    m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.7f, 0.7f, 0.7f));

    m_pCamera = m_pSceneMgr->createCamera("MenuCam");
    m_pCamera->setPosition(Vector3(0, 50, 100));
    m_pCamera->lookAt(Vector3(0, 0, 0));
    m_pCamera->setNearClipDistance(1);

    m_pCamera->setAspectRatio(Real(OgreFramework::getSingletonPtr()->m_pViewport->getActualWidth()) /
        Real(OgreFramework::getSingletonPtr()->m_pViewport->getActualHeight()));

    OgreFramework::getSingletonPtr()->m_pViewport->setCamera(m_pCamera);

    fldUsername = sheet->getChild("CEGUIApp/edtUsername");

    createScene();
}

void LoginState::createScene()
{
    ParticleSystem* ps;
    ps = m_pSceneMgr->createParticleSystem("Nimbus", "Xsilium/GreenyNimbus");
    		m_pSceneMgr->getRootSceneNode()->attachObject(ps);
}

void LoginState::exit()
{
    OgreFramework::getSingletonPtr()->m_pLog->logMessage("Leaving LoginState...");

    m_pSceneMgr->destroyCamera(m_pCamera);
    if(m_pSceneMgr)
        OgreFramework::getSingletonPtr()->m_pRoot->destroySceneManager(m_pSceneMgr);

    CEGUI::WindowManager::getSingleton().destroyAllWindows();

}

bool LoginState::keyPressed(const OIS::KeyEvent &keyEventRef)
{
    if(OgreFramework::getSingletonPtr()->m_pKeyboard->isKeyDown(OIS::KC_ESCAPE))
    {
        m_bQuit = true;
        return true;
    }
    CEGUI::System& gui_system(CEGUI::System::getSingleton());

     // do event injection
     CEGUI::GUIContext& ctx = CEGUI::System::getSingleton().getDefaultGUIContext();

     // key down
     ctx.injectKeyDown(static_cast<CEGUI::Key::Scan>(keyEventRef.key));

     // now character
     ctx.injectChar(keyEventRef.text);
    OgreFramework::getSingletonPtr()->keyPressed(keyEventRef);
    return true;
}

bool LoginState::keyReleased(const OIS::KeyEvent &keyEventRef)
{
    CEGUI::System::getSingleton().getDefaultGUIContext().
        injectKeyUp(static_cast<CEGUI::Key::Scan>(keyEventRef.key));
    OgreFramework::getSingletonPtr()->keyReleased(keyEventRef);
    return true;
}

bool LoginState::mouseMoved(const OIS::MouseEvent &evt)
{
	CEGUI::GUIContext& ctx = CEGUI::System::getSingleton().getDefaultGUIContext();

	   ctx.injectMouseMove(evt.state.X.rel, evt.state.Y.rel);
	   ctx.injectMouseWheelChange(evt.state.Z.rel / 120.0f);
    return true;
}

bool LoginState::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
    CEGUI::System::getSingleton().getDefaultGUIContext().
        injectMouseButtonDown(convertOISButtonToCegui(id));
    return true;
}

bool LoginState::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
    CEGUI::System::getSingleton().getDefaultGUIContext().
        injectMouseButtonUp(convertOISButtonToCegui(id));
    return true;
}

void LoginState::update(double timeSinceLastFrame)
{
    m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame;

    CEGUI::System& gui_system(CEGUI::System::getSingleton());

    gui_system.injectTimePulse(timeSinceLastFrame);
    gui_system.getDefaultGUIContext().injectTimePulse(timeSinceLastFrame);

    if(m_bQuit == true)
    {
        shutdown();
        return;
    }
}

bool LoginState::PushConnexion(const CEGUI::EventArgs &e)
		{
			OgreFramework::getSingletonPtr()->m_pLog->logMessage("Click PushConnexion!!!");
			CEGUI::String valueUsername =  fldUsername->getText();

			printf("username: %s \n",valueUsername.c_str());
			changeAppState(findByName("GameState"));
			return true;
		}

bool LoginState::handleSubmit(const CEGUI::EventArgs&)
{
    return true;
}

CEGUI::MouseButton LoginState::convertOISButtonToCegui(int buttonID)
{
   using namespace OIS;

   switch (buttonID)
    {
   case OIS::MB_Left:
        return CEGUI::LeftButton;
   case OIS::MB_Right:
        return CEGUI::RightButton;
   case OIS::MB_Middle:
        return CEGUI::MiddleButton;
    default:
        return CEGUI::LeftButton;
    }

}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/util/utillidpnor.C $                                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2014,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#include <util/utillidmgr.H>
#include <util/utillidpnor.H>
#include <config.h>
#ifdef CONFIG_SECUREBOOT
#include <pnor/pnorif.H>
#include <errl/errlmanager.H>
#endif

#include <utility>
#include <map>
#include <trace/interface.H>
#include "utilbase.H"

namespace Util
{

const size_t lidIdStrLength = 9;

//  Map of PNOR section Ids to pairs of LidIds
//  Key - PNOR section
//  Value - LidAndContainerLid
//          The first Lid in the pair is the image content
//          The second Lid in the pair is the Container LID (Secure Header)
static const PnorLidsMap PnorToLidsMap =
{
    { PNOR::TESTRO,  LidAndContainerLid(TEST_LIDID, INVALID_LIDID)},
    { PNOR::OCC,     LidAndContainerLid(OCC_LIDID, OCC_CONTAINER_LIDID)},
    { PNOR::WOFDATA, LidAndContainerLid(WOF_LIDID, WOF_CONTAINER_LIDID)},
    { PNOR::HCODE,   LidAndContainerLid(NIMBUS_HCODE_LIDID, HCODE_CONTAINER_LIDID)},
    /* @TODO RTC:177927 - Figure out how to handle different Lids for the
                              same PNOR section based on chip.
    { PNOR::HCODE,   LidAndContainerLid(CUMULUS_HCODE_LIDID, HCODE_CONTAINER_LIDID)},
    */
    { PNOR::RINGOVD, LidAndContainerLid(HWREFIMG_RINGOVD_LIDID,INVALID_LIDID)},
};

LidAndContainerLid getPnorSecLidIds(const PNOR::SectionId i_sec)
{
    LidAndContainerLid l_lids;

    auto l_secIter = PnorToLidsMap.find(i_sec);
    if (l_secIter != PnorToLidsMap.end())
    {
        l_lids.lid = l_secIter->second.lid;
        l_lids.containerLid = l_secIter->second.containerLid;
    }

    return l_lids;
}

PNOR::SectionId getLidPnorSection(const LidId i_lid)
{
    PNOR::SectionId l_secId  = PNOR::INVALID_SECTION;

    // Search map by value
    // Note: Sacrificed constant look up with another map in the reverse
    //       direction to simplify maintenance with a single map
    auto l_secIter = std::find_if( PnorToLidsMap.begin(),
                                   PnorToLidsMap.end(),
                                   [i_lid](const PnorLidsPair & pair) -> bool
                                 {
                                     return pair.second.lid == i_lid;
                                 });
    // Check if we found a valid entry.
    if (l_secIter != PnorToLidsMap.end())
    {
        l_secId = l_secIter->first;
    }

    return l_secId;
}

} // end Util namespace

bool UtilLidMgr::getLidPnorSectionInfo(uint32_t i_lidId,
                                       PNOR::SectionInfo_t &o_lidPnorInfo)
{
    errlHndl_t l_err = NULL;
    bool l_lidInPnor = false;

    // Search if a lid id maps to pnor section
    auto l_secId = Util::getLidPnorSection(static_cast<Util::LidId>(i_lidId));

    do {
    // LidToPnor will return INVALID_SECITON if no mapping found
    if (l_secId == PNOR::INVALID_SECTION)
    {
        UTIL_FT("UtilLidMgr::getLidPnorSection lid 0x%X not in PNOR", i_lidId);
        o_lidPnorInfo.id = PNOR::INVALID_SECTION;
    }
    // A mapping was found
    else
    {
        l_err = PNOR::getSectionInfo(l_secId, o_lidPnorInfo);
        // Section is optional or lid is not in PNOR, so just delete error
        if (l_err)
        {
            o_lidPnorInfo.id = PNOR::INVALID_SECTION;
            delete l_err;
            l_err = NULL;
        }
        else
        {
            l_lidInPnor = true;
            UTIL_FT("UtilLidMgr::getLidPnorSection Lid 0x%X in PNOR", i_lidId);
#ifdef CONFIG_SECUREBOOT
#ifndef __HOSTBOOT_RUNTIME
            // The lid could be securely signed in PNOR
            if(o_lidPnorInfo.secure)
            {
                UTIL_FT("UtilLidMgr::getLidPnorSection verify Lid in PNOR");

                // Load the secure section
                l_err = loadSecureSection(l_secId);

                // If secure section fails to load log the error and assert
                if (l_err)
                {
                    errlCommit(l_err, UTIL_COMP_ID);
                    assert(false,"UtilLidMgr::getLidPnorSectionInfo: attempt to "
                                 "load Secure Section %d failed",
                                 l_secId);
                }

                // In Secureboot, rather than using the whole partition size,
                // only use the protected payload size that the Secure PnorRP
                // handles. This limits the memory footprint and prevents
                // downstream logic from going past the end of the image.
                // NOTE:  This assumes that any secure lid loaded from PNOR by
                // UtilLidMgr does not contain an unprotected section
                iv_lidPnorInfo.size = iv_lidPnorInfo.secureProtectedPayloadSize;
            }
#endif
#endif
            // @TODO CQ:SW400352 remove this check
            if ((l_secId == PNOR::OCC) && PNOR::isSectionEmpty(l_secId))
            {
                UTIL_FT("UtilLidMgr::getLidPnorSection PNOR section %s is empty get data from LID transfer",
                        PNOR::SectionIdToString(l_secId));
                l_lidInPnor = false;
                break;
            }
        }
    }
    } while(0);

    return l_lidInPnor;
}<commit_msg>Fix invalid pointer access in HBRT during PM Reset<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/util/utillidpnor.C $                                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2014,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#include <util/utillidmgr.H>
#include <util/utillidpnor.H>
#include <config.h>
#ifdef CONFIG_SECUREBOOT
#include <pnor/pnorif.H>
#include <errl/errlmanager.H>
#endif

#include <utility>
#include <map>
#include <trace/interface.H>
#include "utilbase.H"

namespace Util
{

const size_t lidIdStrLength = 9;

//  Map of PNOR section Ids to pairs of LidIds
//  Key - PNOR section
//  Value - LidAndContainerLid
//          The first Lid in the pair is the image content
//          The second Lid in the pair is the Container LID (Secure Header)
static const PnorLidsMap PnorToLidsMap =
{
    { PNOR::TESTRO,  LidAndContainerLid(TEST_LIDID, INVALID_LIDID)},
    { PNOR::OCC,     LidAndContainerLid(OCC_LIDID, OCC_CONTAINER_LIDID)},
    { PNOR::WOFDATA, LidAndContainerLid(WOF_LIDID, WOF_CONTAINER_LIDID)},
    { PNOR::HCODE,   LidAndContainerLid(NIMBUS_HCODE_LIDID, HCODE_CONTAINER_LIDID)},
    /* @TODO RTC:177927 - Figure out how to handle different Lids for the
                              same PNOR section based on chip.
    { PNOR::HCODE,   LidAndContainerLid(CUMULUS_HCODE_LIDID, HCODE_CONTAINER_LIDID)},
    */
    { PNOR::RINGOVD, LidAndContainerLid(HWREFIMG_RINGOVD_LIDID,INVALID_LIDID)},
};

LidAndContainerLid getPnorSecLidIds(const PNOR::SectionId i_sec)
{
    LidAndContainerLid l_lids;

    auto l_secIter = PnorToLidsMap.find(i_sec);
    if (l_secIter != PnorToLidsMap.end())
    {
        l_lids.lid = l_secIter->second.lid;
        l_lids.containerLid = l_secIter->second.containerLid;
    }

    return l_lids;
}

PNOR::SectionId getLidPnorSection(const LidId i_lid)
{
    PNOR::SectionId l_secId  = PNOR::INVALID_SECTION;

    // Search map by value
    // Note: Sacrificed constant look up with another map in the reverse
    //       direction to simplify maintenance with a single map
    auto l_secIter = std::find_if( PnorToLidsMap.begin(),
                                   PnorToLidsMap.end(),
                                   [i_lid](const PnorLidsPair & pair) -> bool
                                 {
                                     return pair.second.lid == i_lid;
                                 });
    // Check if we found a valid entry.
    if (l_secIter != PnorToLidsMap.end())
    {
        l_secId = l_secIter->first;
    }

    return l_secId;
}

} // end Util namespace

bool UtilLidMgr::getLidPnorSectionInfo(uint32_t i_lidId,
                                       PNOR::SectionInfo_t &o_lidPnorInfo)
{
    errlHndl_t l_err = NULL;
    bool l_lidInPnor = false;

    // Search if a lid id maps to pnor section
    auto l_secId = Util::getLidPnorSection(static_cast<Util::LidId>(i_lidId));

    do {
    // LidToPnor will return INVALID_SECITON if no mapping found
    if (l_secId == PNOR::INVALID_SECTION)
    {
        UTIL_FT("UtilLidMgr::getLidPnorSection lid 0x%X not in PNOR", i_lidId);
        o_lidPnorInfo.id = PNOR::INVALID_SECTION;
    }
    // A mapping was found
    else
    {
        l_err = PNOR::getSectionInfo(l_secId, o_lidPnorInfo);
        // Section is optional or lid is not in PNOR, so just delete error
        if (l_err)
        {
            o_lidPnorInfo.id = PNOR::INVALID_SECTION;
            delete l_err;
            l_err = NULL;
        }
        else
        {
            l_lidInPnor = true;
            UTIL_FT("UtilLidMgr::getLidPnorSection Lid 0x%X in PNOR", i_lidId);
#ifdef CONFIG_SECUREBOOT
#ifndef __HOSTBOOT_RUNTIME
            // The lid could be securely signed in PNOR
            if(o_lidPnorInfo.secure)
            {
                UTIL_FT("UtilLidMgr::getLidPnorSection verify Lid in PNOR");

                // Load the secure section
                l_err = loadSecureSection(l_secId);

                // If secure section fails to load log the error and assert
                if (l_err)
                {
                    errlCommit(l_err, UTIL_COMP_ID);
                    assert(false,"UtilLidMgr::getLidPnorSectionInfo: attempt to "
                                 "load Secure Section %d failed",
                                 l_secId);
                }

                // In Secureboot, rather than using the whole partition size,
                // only use the protected payload size that the Secure PnorRP
                // handles. This limits the memory footprint and prevents
                // downstream logic from going past the end of the image.
                // NOTE:  This assumes that any secure lid loaded from PNOR by
                // UtilLidMgr does not contain an unprotected section
                iv_lidPnorInfo.size = iv_lidPnorInfo.secureProtectedPayloadSize;
            }
#endif
#endif
            // @TODO CQ:SW400352 remove this check
            if ((l_secId == PNOR::OCC)
#ifndef __HOSTBOOT_RUNTIME
                && PNOR::isSectionEmpty(l_secId)
#else
                //use this check for HBRT due to secure lid load setting vaddr
                //to zero -- which causes isSectionEmpty to segfault
                && !o_lidPnorInfo.vaddr
#endif
               )
            {
                UTIL_FT("UtilLidMgr::getLidPnorSection PNOR section %s is empty get data from LID transfer",
                        PNOR::SectionIdToString(l_secId));
                l_lidInPnor = false;
                break;
            }
        }
    }
    } while(0);

    return l_lidInPnor;
}
<|endoftext|>


<commit_before>// Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <cmath>
#include <cstdlib>
#include <limits>
#include <utility>

#include "rclcpp/clock.hpp"
#include "rclcpp/time.hpp"

#include "builtin_interfaces/msg/duration.hpp"

#include "rcl/time.h"

#include "rclcpp/exceptions.hpp"

#include "rcutils/logging_macros.h"

namespace rclcpp
{

Duration::Duration(int32_t seconds, uint32_t nanoseconds)
{
  rcl_duration_.nanoseconds = RCL_S_TO_NS(static_cast<int64_t>(seconds));
  rcl_duration_.nanoseconds += nanoseconds;
}

Duration::Duration(int64_t nanoseconds)
{
  rcl_duration_.nanoseconds = nanoseconds;
}

Duration::Duration(std::chrono::nanoseconds nanoseconds)
{
  rcl_duration_.nanoseconds = nanoseconds.count();
}

Duration::Duration(const Duration & rhs)
{
  rcl_duration_.nanoseconds = rhs.rcl_duration_.nanoseconds;
}

Duration::Duration(
  const builtin_interfaces::msg::Duration & duration_msg)
{
  rcl_duration_.nanoseconds =
    static_cast<rcl_duration_value_t>(RCL_S_TO_NS(duration_msg.sec));
  rcl_duration_.nanoseconds += duration_msg.nanosec;
}

Duration::Duration(const rcl_duration_t & duration)
: rcl_duration_(duration)
{
  // noop
}

Duration::operator builtin_interfaces::msg::Duration() const
{
  builtin_interfaces::msg::Duration msg_duration;
  msg_duration.sec = static_cast<std::int32_t>(RCL_NS_TO_S(rcl_duration_.nanoseconds));
  msg_duration.nanosec =
    static_cast<std::uint32_t>(rcl_duration_.nanoseconds % (1000 * 1000 * 1000));
  return msg_duration;
}

Duration &
Duration::operator=(const Duration & rhs)
{
  rcl_duration_.nanoseconds = rhs.rcl_duration_.nanoseconds;
  return *this;
}

Duration &
Duration::operator=(const builtin_interfaces::msg::Duration & duration_msg)
{
  rcl_duration_.nanoseconds = RCL_S_TO_NS(static_cast<int64_t>(duration_msg.sec));
  rcl_duration_.nanoseconds += duration_msg.nanosec;
  return *this;
}

bool
Duration::operator==(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds == rhs.rcl_duration_.nanoseconds;
}

bool
Duration::operator<(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds < rhs.rcl_duration_.nanoseconds;
}

bool
Duration::operator<=(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds <= rhs.rcl_duration_.nanoseconds;
}

bool
Duration::operator>=(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds >= rhs.rcl_duration_.nanoseconds;
}

bool
Duration::operator>(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds > rhs.rcl_duration_.nanoseconds;
}

void
bounds_check_duration_sum(int64_t lhsns, int64_t rhsns, uint64_t max)
{
  auto abs_lhs = static_cast<uint64_t>(std::abs(lhsns));
  auto abs_rhs = static_cast<uint64_t>(std::abs(rhsns));

  if (lhsns > 0 && rhsns > 0) {
    if (abs_lhs + abs_rhs > max) {
      throw std::overflow_error("addition leads to int64_t overflow");
    }
  } else if (lhsns < 0 && rhsns < 0) {
    if (abs_lhs + abs_rhs > max) {
      throw std::underflow_error("addition leads to int64_t underflow");
    }
  }
}

Duration
Duration::operator+(const rclcpp::Duration & rhs) const
{
  bounds_check_duration_sum(
    this->rcl_duration_.nanoseconds,
    rhs.rcl_duration_.nanoseconds,
    std::numeric_limits<rcl_duration_value_t>::max());
  return Duration(
    rcl_duration_.nanoseconds + rhs.rcl_duration_.nanoseconds);
}

void
bounds_check_duration_difference(int64_t lhsns, int64_t rhsns, uint64_t max)
{
  auto abs_lhs = static_cast<uint64_t>(std::abs(lhsns));
  auto abs_rhs = static_cast<uint64_t>(std::abs(rhsns));

  if (lhsns > 0 && rhsns < 0) {
    if (abs_lhs + abs_rhs > max) {
      throw std::overflow_error("duration subtraction leads to int64_t overflow");
    }
  } else if (lhsns < 0 && rhsns > 0) {
    if (abs_lhs + abs_rhs > max) {
      throw std::underflow_error("duration subtraction leads to int64_t underflow");
    }
  }
}

Duration
Duration::operator-(const rclcpp::Duration & rhs) const
{
  bounds_check_duration_difference(
    this->rcl_duration_.nanoseconds,
    rhs.rcl_duration_.nanoseconds,
    std::numeric_limits<rcl_duration_value_t>::max());

  return Duration(
    rcl_duration_.nanoseconds - rhs.rcl_duration_.nanoseconds);
}

void
bounds_check_duration_scale(int64_t dns, double scale, uint64_t max)
{
  auto abs_dns = static_cast<uint64_t>(std::abs(dns));
  auto abs_scale = std::abs(scale);
  if (abs_scale > 1.0 &&
    abs_dns > static_cast<uint64_t>(static_cast<long double>(max) / static_cast<long double>(abs_scale)))
  {
    if ((dns > 0 && scale > 0) || (dns < 0 && scale < 0)) {
      throw std::overflow_error("duration scaling leads to int64_t overflow");
    } else {
      throw std::underflow_error("duration scaling leads to int64_t underflow");
    }
  }
}

Duration
Duration::operator*(double scale) const
{
  if (!std::isfinite(scale)) {
    throw std::runtime_error("abnormal scale in rclcpp::Duration");
  }
  bounds_check_duration_scale(
    this->rcl_duration_.nanoseconds,
    scale,
    std::numeric_limits<rcl_duration_value_t>::max());
  long double scale_ld = static_cast<long double>(scale);
  return Duration(static_cast<rcl_duration_value_t>(
             static_cast<long double>(rcl_duration_.nanoseconds) * scale_ld));
}

rcl_duration_value_t
Duration::nanoseconds() const
{
  return rcl_duration_.nanoseconds;
}

Duration
Duration::max()
{
  return Duration(std::numeric_limits<int32_t>::max(), 999999999);
}

double
Duration::seconds() const
{
  return std::chrono::duration<double>(std::chrono::nanoseconds(rcl_duration_.nanoseconds)).count();
}

rmw_time_t
Duration::to_rmw_time() const
{
  // reuse conversion logic from msg creation
  builtin_interfaces::msg::Duration msg = *this;
  rmw_time_t result;
  result.sec = static_cast<uint64_t>(msg.sec);
  result.nsec = static_cast<uint64_t>(msg.nanosec);
  return result;
}

Duration
Duration::from_seconds(double seconds)
{
  return Duration(static_cast<int64_t>(RCL_S_TO_NS(seconds)));
}

}  // namespace rclcpp
<commit_msg>Fix duration.cpp lint error (#930)<commit_after>// Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <cmath>
#include <cstdlib>
#include <limits>
#include <utility>

#include "rclcpp/clock.hpp"
#include "rclcpp/time.hpp"

#include "builtin_interfaces/msg/duration.hpp"

#include "rcl/time.h"

#include "rclcpp/exceptions.hpp"

#include "rcutils/logging_macros.h"

namespace rclcpp
{

Duration::Duration(int32_t seconds, uint32_t nanoseconds)
{
  rcl_duration_.nanoseconds = RCL_S_TO_NS(static_cast<int64_t>(seconds));
  rcl_duration_.nanoseconds += nanoseconds;
}

Duration::Duration(int64_t nanoseconds)
{
  rcl_duration_.nanoseconds = nanoseconds;
}

Duration::Duration(std::chrono::nanoseconds nanoseconds)
{
  rcl_duration_.nanoseconds = nanoseconds.count();
}

Duration::Duration(const Duration & rhs)
{
  rcl_duration_.nanoseconds = rhs.rcl_duration_.nanoseconds;
}

Duration::Duration(
  const builtin_interfaces::msg::Duration & duration_msg)
{
  rcl_duration_.nanoseconds =
    static_cast<rcl_duration_value_t>(RCL_S_TO_NS(duration_msg.sec));
  rcl_duration_.nanoseconds += duration_msg.nanosec;
}

Duration::Duration(const rcl_duration_t & duration)
: rcl_duration_(duration)
{
  // noop
}

Duration::operator builtin_interfaces::msg::Duration() const
{
  builtin_interfaces::msg::Duration msg_duration;
  msg_duration.sec = static_cast<std::int32_t>(RCL_NS_TO_S(rcl_duration_.nanoseconds));
  msg_duration.nanosec =
    static_cast<std::uint32_t>(rcl_duration_.nanoseconds % (1000 * 1000 * 1000));
  return msg_duration;
}

Duration &
Duration::operator=(const Duration & rhs)
{
  rcl_duration_.nanoseconds = rhs.rcl_duration_.nanoseconds;
  return *this;
}

Duration &
Duration::operator=(const builtin_interfaces::msg::Duration & duration_msg)
{
  rcl_duration_.nanoseconds = RCL_S_TO_NS(static_cast<int64_t>(duration_msg.sec));
  rcl_duration_.nanoseconds += duration_msg.nanosec;
  return *this;
}

bool
Duration::operator==(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds == rhs.rcl_duration_.nanoseconds;
}

bool
Duration::operator<(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds < rhs.rcl_duration_.nanoseconds;
}

bool
Duration::operator<=(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds <= rhs.rcl_duration_.nanoseconds;
}

bool
Duration::operator>=(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds >= rhs.rcl_duration_.nanoseconds;
}

bool
Duration::operator>(const rclcpp::Duration & rhs) const
{
  return rcl_duration_.nanoseconds > rhs.rcl_duration_.nanoseconds;
}

void
bounds_check_duration_sum(int64_t lhsns, int64_t rhsns, uint64_t max)
{
  auto abs_lhs = static_cast<uint64_t>(std::abs(lhsns));
  auto abs_rhs = static_cast<uint64_t>(std::abs(rhsns));

  if (lhsns > 0 && rhsns > 0) {
    if (abs_lhs + abs_rhs > max) {
      throw std::overflow_error("addition leads to int64_t overflow");
    }
  } else if (lhsns < 0 && rhsns < 0) {
    if (abs_lhs + abs_rhs > max) {
      throw std::underflow_error("addition leads to int64_t underflow");
    }
  }
}

Duration
Duration::operator+(const rclcpp::Duration & rhs) const
{
  bounds_check_duration_sum(
    this->rcl_duration_.nanoseconds,
    rhs.rcl_duration_.nanoseconds,
    std::numeric_limits<rcl_duration_value_t>::max());
  return Duration(
    rcl_duration_.nanoseconds + rhs.rcl_duration_.nanoseconds);
}

void
bounds_check_duration_difference(int64_t lhsns, int64_t rhsns, uint64_t max)
{
  auto abs_lhs = static_cast<uint64_t>(std::abs(lhsns));
  auto abs_rhs = static_cast<uint64_t>(std::abs(rhsns));

  if (lhsns > 0 && rhsns < 0) {
    if (abs_lhs + abs_rhs > max) {
      throw std::overflow_error("duration subtraction leads to int64_t overflow");
    }
  } else if (lhsns < 0 && rhsns > 0) {
    if (abs_lhs + abs_rhs > max) {
      throw std::underflow_error("duration subtraction leads to int64_t underflow");
    }
  }
}

Duration
Duration::operator-(const rclcpp::Duration & rhs) const
{
  bounds_check_duration_difference(
    this->rcl_duration_.nanoseconds,
    rhs.rcl_duration_.nanoseconds,
    std::numeric_limits<rcl_duration_value_t>::max());

  return Duration(
    rcl_duration_.nanoseconds - rhs.rcl_duration_.nanoseconds);
}

void
bounds_check_duration_scale(int64_t dns, double scale, uint64_t max)
{
  auto abs_dns = static_cast<uint64_t>(std::abs(dns));
  auto abs_scale = std::abs(scale);
  if (abs_scale > 1.0 && abs_dns >
    static_cast<uint64_t>(static_cast<long double>(max) / static_cast<long double>(abs_scale)))
  {
    if ((dns > 0 && scale > 0) || (dns < 0 && scale < 0)) {
      throw std::overflow_error("duration scaling leads to int64_t overflow");
    } else {
      throw std::underflow_error("duration scaling leads to int64_t underflow");
    }
  }
}

Duration
Duration::operator*(double scale) const
{
  if (!std::isfinite(scale)) {
    throw std::runtime_error("abnormal scale in rclcpp::Duration");
  }
  bounds_check_duration_scale(
    this->rcl_duration_.nanoseconds,
    scale,
    std::numeric_limits<rcl_duration_value_t>::max());
  long double scale_ld = static_cast<long double>(scale);
  return Duration(static_cast<rcl_duration_value_t>(
             static_cast<long double>(rcl_duration_.nanoseconds) * scale_ld));
}

rcl_duration_value_t
Duration::nanoseconds() const
{
  return rcl_duration_.nanoseconds;
}

Duration
Duration::max()
{
  return Duration(std::numeric_limits<int32_t>::max(), 999999999);
}

double
Duration::seconds() const
{
  return std::chrono::duration<double>(std::chrono::nanoseconds(rcl_duration_.nanoseconds)).count();
}

rmw_time_t
Duration::to_rmw_time() const
{
  // reuse conversion logic from msg creation
  builtin_interfaces::msg::Duration msg = *this;
  rmw_time_t result;
  result.sec = static_cast<uint64_t>(msg.sec);
  result.nsec = static_cast<uint64_t>(msg.nanosec);
  return result;
}

Duration
Duration::from_seconds(double seconds)
{
  return Duration(static_cast<int64_t>(RCL_S_TO_NS(seconds)));
}

}  // namespace rclcpp
<|endoftext|>


<commit_before>#include "compile.h"
#include <algorithm>
#include <cassert>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <iostream>

namespace {

class VarMap
{
public:
	VarMap(std::shared_ptr<VarMap> parent, const std::vector<std::string>& vars)
		: parent(parent), vars(vars) {}

	bool resolve(const std::string& var, int* depth, int* index) const {
		auto it = std::find(vars.begin(), vars.end(), var);
		if(it != vars.end()) {
			*depth = 0;
			*index = it - vars.begin();
			return true;
		}
		bool b = parent->resolve(var, depth, index);
		if(b)
			++*depth;
		return b;
	}

private:
	const std::shared_ptr<VarMap> parent;
	std::vector<std::string> vars;
};

struct Context
{
	const std::shared_ptr<VarMap> varmap;
	const std::shared_ptr<std::vector<gcc::OperationSequence>> codeblocks;

	int AddCodeBlock(const gcc::OperationSequence& ops) const {
		int id = codeblocks->size();
		codeblocks->push_back(ops);
		return id;
	}
};

std::vector<std::string> verify_lambda_param_node(ast::AST ast) {
	assert(ast->type == ast::LIST);

	std::vector<std::string> vars;
	for(int i=0; i<ast->list.size(); ++i) {
		assert(ast->list[i]->type == ast::SYMBOL);
		vars.push_back(ast->list[i]->symbol);
	}
	return vars;
}

gcc::OperationSequence rec(ast::AST ast, const Context& ctx)
{
	auto compile_op2 = [&](std::shared_ptr<gcc::Op> op) {
		assert(ast->type == ast::LIST);
		assert(ast->list.size() == 3);

		gcc::OperationSequence ops;
		gcc::Append(&ops, rec(ast->list[1], ctx));
		gcc::Append(&ops, rec(ast->list[2], ctx));
		gcc::Append(&ops, op);
		return ops;
	};
	auto compile_op2_rev = [&](std::shared_ptr<gcc::Op> op) {
		assert(ast->type == ast::LIST);
		assert(ast->list.size() == 3);

		gcc::OperationSequence ops;
		gcc::Append(&ops, rec(ast->list[2], ctx)); // note: reversed
		gcc::Append(&ops, rec(ast->list[1], ctx));
		gcc::Append(&ops, op);
		return ops;
	};
	auto compile_op1 = [&](std::shared_ptr<gcc::Op> op) {
		assert(ast->type == ast::LIST);
		assert(ast->list.size() == 2);

		gcc::OperationSequence ops;
		gcc::Append(&ops, rec(ast->list[1], ctx));
		gcc::Append(&ops, op);
		return ops;
	};

	switch(ast->type) {
		case ast::VALUE: {
			// constant
			gcc::OperationSequence ops;
			gcc::Append(&ops, std::make_shared<gcc::OpLDC>(ast->value));
			return ops;
		}
		case ast::SYMBOL: {
			// variable
			int depth, index;
			if(!ctx.varmap->resolve(ast->symbol, &depth, &index))
				assert(false);
			gcc::OperationSequence ops;
			gcc:Append(&ops, std::make_shared<gcc::OpLD>(depth, index));
			return ops;
		}
		case ast::LIST: {
			if(ast->list.empty()) {
				// use as nil
				gcc::OperationSequence ops;
				gcc::Append(&ops, std::make_shared<gcc::OpLDC>(0));
				return ops;
			} else if(ast->list.front()->type==ast::SYMBOL) {
				// special forms
				if(ast->list.front()->symbol == "+")
					return compile_op2(std::make_shared<gcc::OpADD>());
				if(ast->list.front()->symbol == "-")
					return compile_op2(std::make_shared<gcc::OpSUB>());
				if(ast->list.front()->symbol == "*")
					return compile_op2(std::make_shared<gcc::OpMUL>());
				if(ast->list.front()->symbol == "/")
					return compile_op2(std::make_shared<gcc::OpDIV>());
				if(ast->list.front()->symbol == "=")
					return compile_op2(std::make_shared<gcc::OpCEQ>());
				if(ast->list.front()->symbol == ">")
					return compile_op2(std::make_shared<gcc::OpCGT>());
				if(ast->list.front()->symbol == ">=")
					return compile_op2(std::make_shared<gcc::OpCGTE>());
				if(ast->list.front()->symbol == "<")
					return compile_op2_rev(std::make_shared<gcc::OpCGT>());
				if(ast->list.front()->symbol == "<=")
					return compile_op2_rev(std::make_shared<gcc::OpCGTE>());
				if(ast->list.front()->symbol == "int?")
					return compile_op1(std::make_shared<gcc::OpATOM>());
				if(ast->list.front()->symbol == "cons")
					return compile_op2(std::make_shared<gcc::OpCONS>());
				if(ast->list.front()->symbol == "car")
					return compile_op1(std::make_shared<gcc::OpCAR>());
				if(ast->list.front()->symbol == "cdr")
					return compile_op1(std::make_shared<gcc::OpCDR>());

				// (lambda (vars...) e)
				if(ast->list.front()->symbol == "lambda") {
					assert(ast->list.size() == 3);

					std::vector<std::string> vars = verify_lambda_param_node(ast->list[1]);
					std::shared_ptr<VarMap> neo_varmap = std::make_shared<VarMap>(ctx.varmap, vars);
					Context neo_ctx = {neo_varmap, ctx.codeblocks};

					gcc::OperationSequence body_ops = rec(ast->list[2], neo_ctx);
					gcc::Append(&body_ops, std::make_shared<gcc::OpRTN>());
					int id = ctx.AddCodeBlock(body_ops);

					gcc::OperationSequence ops;
					gcc::Append(&ops, std::make_shared<gcc::OpLDF>(id));
					return ops;
				}

				// (let ((x e) (x e)) e)

				// (if c t e)
				if(ast->list.front()->symbol == "if") {
					assert(ast->list.size() == 4);

					gcc::OperationSequence ops = rec(ast->list[1], ctx);
					gcc::OperationSequence t_ops = rec(ast->list[2], ctx);
					gcc::Append(&t_ops, std::make_shared<gcc::OpJOIN>());
					int tid = ctx.AddCodeBlock(t_ops);

					gcc::OperationSequence e_ops = rec(ast->list[3], ctx);
					gcc::Append(&e_ops, std::make_shared<gcc::OpJOIN>());
					int eid = ctx.AddCodeBlock(e_ops);

					gcc::Append(&ops, std::make_shared<gcc::OpSEL>(tid, eid));
					return ops;
				}
			}

			// general function applications
			gcc::OperationSequence ops;
			for(int i=1; i<ast->list.size(); ++i)
				gcc::Append(&ops, rec(ast->list[i], ctx));
			gcc::Append(&ops, rec(ast->list[0], ctx));
			gcc::Append(&ops, std::make_shared<gcc::OpAP>(ast->list.size() - 1));
			return ops;
		}
	}
	assert(false);
}

}  // namespace

PreLink compile_expression(ast::AST ast)
{
	std::shared_ptr<VarMap> nil_varmap;
	auto codeblocks = std::make_shared<std::vector<gcc::OperationSequence>>();
	Context ctx = {nil_varmap, codeblocks};
	auto mainblock = rec(ast, ctx);
	PreLink result = {mainblock, *codeblocks};
	return result;
}

PreLink compile_program(const std::vector<ast::AST> defines)
{
	std::map<std::string, std::pair<
		std::vector<std::string>,
		ast::AST
	>> funcs;

	for(auto ast: defines)
	{
		assert(ast->type == ast::LIST);
		assert(ast->list.size() == 3);
		assert(ast->list[0]->type == ast::SYMBOL);
		assert(ast->list[0]->symbol == "define");
		assert(ast->list[1]->type == ast::LIST);
		assert(ast->list[1]->list.size() >= 1);
		assert(ast->list[1]->list[0]->type == ast::SYMBOL);
		std::string name = ast->list[1]->list[0]->symbol;

		std::vector<std::string> params;
		for(size_t i=1; i<ast->list[1]->list.size(); ++i) {
			assert(ast->list[1]->list[i]->type == ast::SYMBOL);
			params.push_back(ast->list[1]->list[i]->symbol);
		}

		assert(funcs.count(name) == 0);
		funcs[name] = std::make_pair(params, ast->list[2]);
	}

	std::shared_ptr<VarMap> nil_varmap;

	std::vector<std::string> init_vars = {"arg1", "arg2"};
	std::shared_ptr<VarMap> init_varmap = std::make_shared<VarMap>(nil_varmap, init_vars);

	std::vector<std::string> global_vars;
	for(auto& kv: funcs)
		global_vars.push_back(kv.first);
	std::shared_ptr<VarMap> global_varmap = std::make_shared<VarMap>(init_varmap, global_vars);

	auto codeblocks = std::make_shared<std::vector<gcc::OperationSequence>>();

	std::vector<int> func_ids;
	int main_offset = -1, i=0;
	for(auto& kv: funcs)
	{
		Context ctx = {
			std::make_shared<VarMap>(global_varmap, kv.second.first),
			codeblocks
		};
		auto body_ops = rec(kv.second.second, ctx);
		gcc::Append(&body_ops, std::make_shared<gcc::OpRTN>());
		int id = ctx.AddCodeBlock(body_ops);
		if(kv.first == "main")
			main_offset = i;
		func_ids.push_back(id);
		++i;
	}
	assert(main_offset >= 0);
	// (define (__dummy_main__) (main))
	gcc::OperationSequence dummy_main_ops;
	gcc::Append(&dummy_main_ops, std::make_shared<gcc::OpLD>(0,main_offset));
	gcc::Append(&dummy_main_ops, std::make_shared<gcc::OpAP>(0));
	gcc::Append(&dummy_main_ops, std::make_shared<gcc::OpRTN>());
	Context tmp_ctx = {nil_varmap, codeblocks};
	int dummy_main_id = tmp_ctx.AddCodeBlock(dummy_main_ops);

	gcc::OperationSequence prolog_ops;

	gcc::Append(&prolog_ops, std::make_shared<gcc::OpDUM>(func_ids.size()));
	for(int id: func_ids)
		gcc::Append(&prolog_ops, std::make_shared<gcc::OpLDF>(id));
	gcc::Append(&prolog_ops, std::make_shared<gcc::OpLDF>(dummy_main_id));
	gcc::Append(&prolog_ops, std::make_shared<gcc::OpRAP>(func_ids.size()));
	gcc::Append(&prolog_ops, std::make_shared<gcc::OpRTN>());

	PreLink result = {prolog_ops, *codeblocks};
	return result;
}
<commit_msg>compiler: let<commit_after>#include "compile.h"
#include <algorithm>
#include <cassert>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <iostream>

namespace {

class VarMap
{
public:
	VarMap(std::shared_ptr<VarMap> parent, const std::vector<std::string>& vars)
		: parent(parent), vars(vars) {}

	bool resolve(const std::string& var, int* depth, int* index) const {
		auto it = std::find(vars.begin(), vars.end(), var);
		if(it != vars.end()) {
			*depth = 0;
			*index = it - vars.begin();
			return true;
		}
		bool b = parent->resolve(var, depth, index);
		if(b)
			++*depth;
		return b;
	}

private:
	const std::shared_ptr<VarMap> parent;
	std::vector<std::string> vars;
};

struct Context
{
	const std::shared_ptr<VarMap> varmap;
	const std::shared_ptr<std::vector<gcc::OperationSequence>> codeblocks;

	int AddCodeBlock(const gcc::OperationSequence& ops) const {
		int id = codeblocks->size();
		codeblocks->push_back(ops);
		return id;
	}
};

std::vector<std::string> verify_lambda_param_node(ast::AST ast) {
	assert(ast->type == ast::LIST);

	std::vector<std::string> vars;
	for(int i=0; i<ast->list.size(); ++i) {
		assert(ast->list[i]->type == ast::SYMBOL);
		vars.push_back(ast->list[i]->symbol);
	}
	return vars;
}

gcc::OperationSequence rec(ast::AST ast, const Context& ctx)
{
	auto compile_op2 = [&](std::shared_ptr<gcc::Op> op) {
		assert(ast->type == ast::LIST);
		assert(ast->list.size() == 3);

		gcc::OperationSequence ops;
		gcc::Append(&ops, rec(ast->list[1], ctx));
		gcc::Append(&ops, rec(ast->list[2], ctx));
		gcc::Append(&ops, op);
		return ops;
	};
	auto compile_op2_rev = [&](std::shared_ptr<gcc::Op> op) {
		assert(ast->type == ast::LIST);
		assert(ast->list.size() == 3);

		gcc::OperationSequence ops;
		gcc::Append(&ops, rec(ast->list[2], ctx)); // note: reversed
		gcc::Append(&ops, rec(ast->list[1], ctx));
		gcc::Append(&ops, op);
		return ops;
	};
	auto compile_op1 = [&](std::shared_ptr<gcc::Op> op) {
		assert(ast->type == ast::LIST);
		assert(ast->list.size() == 2);

		gcc::OperationSequence ops;
		gcc::Append(&ops, rec(ast->list[1], ctx));
		gcc::Append(&ops, op);
		return ops;
	};

	switch(ast->type) {
		case ast::VALUE: {
			// constant
			gcc::OperationSequence ops;
			gcc::Append(&ops, std::make_shared<gcc::OpLDC>(ast->value));
			return ops;
		}
		case ast::SYMBOL: {
			// variable
			int depth, index;
			if(!ctx.varmap->resolve(ast->symbol, &depth, &index))
				assert(false);
			gcc::OperationSequence ops;
			gcc:Append(&ops, std::make_shared<gcc::OpLD>(depth, index));
			return ops;
		}
		case ast::LIST: {
			if(ast->list.empty()) {
				// use as nil
				gcc::OperationSequence ops;
				gcc::Append(&ops, std::make_shared<gcc::OpLDC>(0));
				return ops;
			} else if(ast->list.front()->type==ast::SYMBOL) {
				// special forms
				if(ast->list.front()->symbol == "+")
					return compile_op2(std::make_shared<gcc::OpADD>());
				if(ast->list.front()->symbol == "-")
					return compile_op2(std::make_shared<gcc::OpSUB>());
				if(ast->list.front()->symbol == "*")
					return compile_op2(std::make_shared<gcc::OpMUL>());
				if(ast->list.front()->symbol == "/")
					return compile_op2(std::make_shared<gcc::OpDIV>());
				if(ast->list.front()->symbol == "=")
					return compile_op2(std::make_shared<gcc::OpCEQ>());
				if(ast->list.front()->symbol == ">")
					return compile_op2(std::make_shared<gcc::OpCGT>());
				if(ast->list.front()->symbol == ">=")
					return compile_op2(std::make_shared<gcc::OpCGTE>());
				if(ast->list.front()->symbol == "<")
					return compile_op2_rev(std::make_shared<gcc::OpCGT>());
				if(ast->list.front()->symbol == "<=")
					return compile_op2_rev(std::make_shared<gcc::OpCGTE>());
				if(ast->list.front()->symbol == "int?")
					return compile_op1(std::make_shared<gcc::OpATOM>());
				if(ast->list.front()->symbol == "cons")
					return compile_op2(std::make_shared<gcc::OpCONS>());
				if(ast->list.front()->symbol == "car")
					return compile_op1(std::make_shared<gcc::OpCAR>());
				if(ast->list.front()->symbol == "cdr")
					return compile_op1(std::make_shared<gcc::OpCDR>());

				// (lambda (vars...) e)
				if(ast->list.front()->symbol == "lambda") {
					assert(ast->list.size() == 3);

					std::vector<std::string> vars = verify_lambda_param_node(ast->list[1]);
					std::shared_ptr<VarMap> neo_varmap = std::make_shared<VarMap>(ctx.varmap, vars);
					Context neo_ctx = {neo_varmap, ctx.codeblocks};

					gcc::OperationSequence body_ops = rec(ast->list[2], neo_ctx);
					gcc::Append(&body_ops, std::make_shared<gcc::OpRTN>());
					int id = ctx.AddCodeBlock(body_ops);

					gcc::OperationSequence ops;
					gcc::Append(&ops, std::make_shared<gcc::OpLDF>(id));
					return ops;
				}

				// (let ((x e) (x e)) e)
				if(ast->list.front()->symbol == "let") {
					assert(ast->list.size() == 3);
					assert(ast->list[1]->type == ast::LIST);

					std::vector<std::string> vars;
					std::vector<ast::AST>    args;
					for(auto& kv: ast->list[1]->list) {
						assert(kv->type == ast::LIST);
						assert(kv->list.size() == 2);
						assert(kv->list[0]->type == ast::SYMBOL);
						vars.push_back(kv->list[0]->symbol);
						args.push_back(kv->list[1]);
					}

					std::shared_ptr<VarMap> neo_varmap = std::make_shared<VarMap>(ctx.varmap, vars);
					Context neo_ctx = {neo_varmap, ctx.codeblocks};

					gcc::OperationSequence body_ops = rec(ast->list[2], neo_ctx);
					gcc::Append(&body_ops, std::make_shared<gcc::OpRTN>());
					int id = ctx.AddCodeBlock(body_ops);

					gcc::OperationSequence ops;
					for(auto& arg: args)
						gcc::Append(&ops, rec(arg, ctx));
					gcc::Append(&ops, std::make_shared<gcc::OpLDF>(id));
					gcc::Append(&ops, std::make_shared<gcc::OpAP>(args.size()));
					return ops;
				}

				// (if c t e)
				if(ast->list.front()->symbol == "if") {
					assert(ast->list.size() == 4);

					gcc::OperationSequence ops = rec(ast->list[1], ctx);
					gcc::OperationSequence t_ops = rec(ast->list[2], ctx);
					gcc::Append(&t_ops, std::make_shared<gcc::OpJOIN>());
					int tid = ctx.AddCodeBlock(t_ops);

					gcc::OperationSequence e_ops = rec(ast->list[3], ctx);
					gcc::Append(&e_ops, std::make_shared<gcc::OpJOIN>());
					int eid = ctx.AddCodeBlock(e_ops);

					gcc::Append(&ops, std::make_shared<gcc::OpSEL>(tid, eid));
					return ops;
				}
			}

			// general function applications
			gcc::OperationSequence ops;
			for(int i=1; i<ast->list.size(); ++i)
				gcc::Append(&ops, rec(ast->list[i], ctx));
			gcc::Append(&ops, rec(ast->list[0], ctx));
			gcc::Append(&ops, std::make_shared<gcc::OpAP>(ast->list.size() - 1));
			return ops;
		}
	}
	assert(false);
}

}  // namespace

PreLink compile_expression(ast::AST ast)
{
	std::shared_ptr<VarMap> nil_varmap;
	auto codeblocks = std::make_shared<std::vector<gcc::OperationSequence>>();
	Context ctx = {nil_varmap, codeblocks};
	auto mainblock = rec(ast, ctx);
	PreLink result = {mainblock, *codeblocks};
	return result;
}

PreLink compile_program(const std::vector<ast::AST> defines)
{
	std::map<std::string, std::pair<
		std::vector<std::string>,
		ast::AST
	>> funcs;

	for(auto ast: defines)
	{
		assert(ast->type == ast::LIST);
		assert(ast->list.size() == 3);
		assert(ast->list[0]->type == ast::SYMBOL);
		assert(ast->list[0]->symbol == "define");
		assert(ast->list[1]->type == ast::LIST);
		assert(ast->list[1]->list.size() >= 1);
		assert(ast->list[1]->list[0]->type == ast::SYMBOL);
		std::string name = ast->list[1]->list[0]->symbol;

		std::vector<std::string> params;
		for(size_t i=1; i<ast->list[1]->list.size(); ++i) {
			assert(ast->list[1]->list[i]->type == ast::SYMBOL);
			params.push_back(ast->list[1]->list[i]->symbol);
		}

		assert(funcs.count(name) == 0);
		funcs[name] = std::make_pair(params, ast->list[2]);
	}

	std::shared_ptr<VarMap> nil_varmap;

	std::vector<std::string> init_vars = {"arg1", "arg2"};
	std::shared_ptr<VarMap> init_varmap = std::make_shared<VarMap>(nil_varmap, init_vars);

	std::vector<std::string> global_vars;
	for(auto& kv: funcs)
		global_vars.push_back(kv.first);
	std::shared_ptr<VarMap> global_varmap = std::make_shared<VarMap>(init_varmap, global_vars);

	auto codeblocks = std::make_shared<std::vector<gcc::OperationSequence>>();

	std::vector<int> func_ids;
	int main_offset = -1, i=0;
	for(auto& kv: funcs)
	{
		Context ctx = {
			std::make_shared<VarMap>(global_varmap, kv.second.first),
			codeblocks
		};
		auto body_ops = rec(kv.second.second, ctx);
		gcc::Append(&body_ops, std::make_shared<gcc::OpRTN>());
		int id = ctx.AddCodeBlock(body_ops);
		if(kv.first == "main")
			main_offset = i;
		func_ids.push_back(id);
		++i;
	}
	assert(main_offset >= 0);
	// (define (__dummy_main__) (main))
	gcc::OperationSequence dummy_main_ops;
	gcc::Append(&dummy_main_ops, std::make_shared<gcc::OpLD>(0,main_offset));
	gcc::Append(&dummy_main_ops, std::make_shared<gcc::OpAP>(0));
	gcc::Append(&dummy_main_ops, std::make_shared<gcc::OpRTN>());
	Context tmp_ctx = {nil_varmap, codeblocks};
	int dummy_main_id = tmp_ctx.AddCodeBlock(dummy_main_ops);

	gcc::OperationSequence prolog_ops;

	gcc::Append(&prolog_ops, std::make_shared<gcc::OpDUM>(func_ids.size()));
	for(int id: func_ids)
		gcc::Append(&prolog_ops, std::make_shared<gcc::OpLDF>(id));
	gcc::Append(&prolog_ops, std::make_shared<gcc::OpLDF>(dummy_main_id));
	gcc::Append(&prolog_ops, std::make_shared<gcc::OpRAP>(func_ids.size()));
	gcc::Append(&prolog_ops, std::make_shared<gcc::OpRTN>());

	PreLink result = {prolog_ops, *codeblocks};
	return result;
}
<|endoftext|>


<commit_before>{
//
// This script is a slightly modified version of hsum.C
// It produces an animated gif file. See comments below
// It can be run in batch mode too.
  gROOT->Reset();

  c1 = new TCanvas("c1","The HSUM example",200,10,600,400);
  c1->SetGrid();

  gBenchmark->Start("hsum");

// Create some histograms.
  total  = new TH1F("total","This is the total distribution",100,-4,4);
  main   = new TH1F("main","Main contributor",100,-4,4);
  s1     = new TH1F("s1","This is the first signal",100,-4,4);
  s2     = new TH1F("s2","This is the second signal",100,-4,4);
  total->Sumw2();   // this makes sure that the sum of squares of weights will be stored
  total->SetMarkerStyle(21);
  total->SetMarkerSize(0.7);
  main->SetFillColor(16);
  s1->SetFillColor(42);
  s2->SetFillColor(46);
  TSlider *slider = 0;
  gSystem->Unlink("hsumanim.gif"); // delete old file

// Fill histograms randomly
  gRandom->SetSeed();
  const Int_t kUPDATE = 500;
  Float_t xs1, xs2, xmain;
  Int_t gifcnt = 0;
  for ( Int_t i=0; i<10000; i++) {
     xmain = gRandom->Gaus(-1,1.5);
     xs1   = gRandom->Gaus(-0.5,0.5);
     xs2   = gRandom->Landau(1,0.15);
     main->Fill(xmain);
     s1->Fill(xs1,0.3);
     s2->Fill(xs2,0.2);
     total->Fill(xmain);
     total->Fill(xs1,0.3);
     total->Fill(xs2,0.2);
     if (i && (i%kUPDATE) == 0) {
        if (i == kUPDATE) {
           total->Draw("e1p");
           main->Draw("same");
           s1->Draw("same");
           s2->Draw("same");
           c1->Update();
           slider = new TSlider("slider","test",4.2,0,4.6,total->GetMaximum(),38);
           slider->SetFillColor(46);
        }
        if (slider) slider->SetRange(0,Float_t(i)/10000.);
        c1->Modified();
        c1->Update();
        c1->Print("hsumanim.gif+");
     }
  }
  slider->SetRange(0,1);
  total->Draw("sameaxis"); // to redraw axis hidden by the fill area
  c1->Modified();
  c1->Print("hsumanim.gif+");

  //You can view the animated file hsumanim.gif with Netscape/IE or mozilla

  gBenchmark->Show("hsum");
}
<commit_msg>Minor change in script to produce the animated gif only in batch mode.<commit_after>{
//
// This script is a slightly modified version of hsum.C.
// When run in batch mode, it produces an animated gif file.

  gROOT->Reset();

  c1 = new TCanvas("c1","The HSUM example",200,10,600,400);
  c1->SetGrid();

  gBenchmark->Start("hsum");

// Create some histograms.
  total  = new TH1F("total","This is the total distribution",100,-4,4);
  main   = new TH1F("main","Main contributor",100,-4,4);
  s1     = new TH1F("s1","This is the first signal",100,-4,4);
  s2     = new TH1F("s2","This is the second signal",100,-4,4);
  total->Sumw2();   // this makes sure that the sum of squares of weights will be stored
  total->SetMarkerStyle(21);
  total->SetMarkerSize(0.7);
  main->SetFillColor(16);
  s1->SetFillColor(42);
  s2->SetFillColor(46);
  TSlider *slider = 0;
  gSystem->Unlink("hsumanim.gif"); // delete old file

// Fill histograms randomly
  gRandom->SetSeed();
  const Int_t kUPDATE = 500;
  Float_t xs1, xs2, xmain;
  Int_t gifcnt = 0;
  for ( Int_t i=0; i<10000; i++) {
     xmain = gRandom->Gaus(-1,1.5);
     xs1   = gRandom->Gaus(-0.5,0.5);
     xs2   = gRandom->Landau(1,0.15);
     main->Fill(xmain);
     s1->Fill(xs1,0.3);
     s2->Fill(xs2,0.2);
     total->Fill(xmain);
     total->Fill(xs1,0.3);
     total->Fill(xs2,0.2);
     if (i && (i%kUPDATE) == 0) {
        if (i == kUPDATE) {
           total->Draw("e1p");
           main->Draw("same");
           s1->Draw("same");
           s2->Draw("same");
           c1->Update();
           slider = new TSlider("slider","test",4.2,0,4.6,total->GetMaximum(),38);
           slider->SetFillColor(46);
        }
        if (slider) slider->SetRange(0,Float_t(i)/10000.);
        c1->Modified();
        c1->Update();
        if (gROOT->IsBatch()) {
           c1->Print("hsumanim.gif+");
           printf("i = %d\n", i);
        }
     }
  }
  slider->SetRange(0,1);
  total->Draw("sameaxis"); // to redraw axis hidden by the fill area
  c1->Modified();
  if (gROOT->IsBatch()) c1->Print("hsumanim.gif+");

  //You can view the animated file hsumanim.gif with Netscape/IE or mozilla

  gBenchmark->Show("hsum");
}
<|endoftext|>


<commit_before>#include "Crc16.h"

const uint16_t Crc16::lut[] = {
    0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF,
    0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7,
    0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E,
    0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876,
    0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD,
    0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5,
    0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C,
    0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974,
    0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB,
    0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3,
    0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A,
    0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72,
    0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9,
    0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1,
    0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738,
    0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70,
    0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7,
    0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF,
    0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036,
    0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E,
    0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5,
    0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD,
    0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134,
    0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C,
    0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3,
    0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB,
    0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232,
    0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A,
    0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1,
    0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9,
    0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330,
    0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78,
};

uint16_t Crc16::compute(uint8_t *data, size_t len) {
    uint16_t crc = 0xFFFF; /* Seed value */

    for (size_t i = 0; i < len; ++i) {
        uint16_t lookup = lut[(crc ^ data[i]) & 0xFF];
        crc = (crc >> 8) ^ lookup;
    }

    return(~crc);
}

<commit_msg>Simplify implementation<commit_after>#include "Crc16.h"

const uint16_t Crc16::lut[] = {
    0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF,
    0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7,
    0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E,
    0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876,
    0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD,
    0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5,
    0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C,
    0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974,
    0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB,
    0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3,
    0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A,
    0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72,
    0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9,
    0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1,
    0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738,
    0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70,
    0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7,
    0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF,
    0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036,
    0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E,
    0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5,
    0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD,
    0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134,
    0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C,
    0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3,
    0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB,
    0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232,
    0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A,
    0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1,
    0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9,
    0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330,
    0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78,
};

uint16_t Crc16::compute(uint8_t *data, size_t len) {
    uint16_t crc = 0xFFFF; /* Seed value */

    for (size_t i = 0; i < len; ++i) {
        crc = (crc >> 8) ^ lut[(crc ^ data[i]) & 0xFF];
    }

    return(~crc);
}

<|endoftext|>


<commit_before>//
// Methods for plane generator
//
#include <math.h>
#include "CylSrc.hh"

void vlCylinderSource::SetResolution(int res)
{
  if ( res != this->Resolution )
    {
    this->Resolution = res;
    this->Resolution = (this->Resolution < 3 ? 3 :
        (this->Resolution > MAX_RESOLUTION ? MAX_RESOLUTION : this->Resolution));
    this->Modified();
    }
}
int vlCylinderSource::GetResolution()
{
  return this->Resolution;
}

void vlCylinderSource::SetHeight(float h)
{
  if ( h != this->Height )
    {
    this->Height = h;
    this->Height = (this->Height > 0.0 ? this->Height : 1.0);
    this->Modified();
    }
}
float vlCylinderSource::GetHeight()
{
  return this->Height;
}

void vlCylinderSource::SetRadius(float h)
{
  if ( h != this->Radius )
    {
    this->Radius = h;
    this->Radius = (this->Radius > 0.0 ? this->Radius : 0.5);
    this->Modified();
    }
}
float vlCylinderSource::GetRadius()
{
  return this->Radius;
}

void vlCylinderSource::SetCapping(int flag)
{
  if ( flag != this->Capping )
    {
    this->Capping = flag;
    this->Modified();
    }
}
int vlCylinderSource::GetCapping()
{
  return this->Capping;
}

void vlCylinderSource::Execute()
{
  float angle= 2.0*3.141592654/this->Resolution;
  int numVerts, numPolys, numPts;
  float xbot[3], tcbot[2], nbot[3];
  float xtop[3], tctop[2], ntop[3];
  int i, idx;
  int pts[MAX_RESOLUTION];
  vlFloatPoints *newPoints;
  vlFloatNormals *newNormals;
  vlFloatTCoords *newTCoords;
  vlCellArray *newPolys;
  vlPointData *newPtData;
//
// Set things up; allocate memory
//
  this->Initialize();

  if ( this->Capping )
    {
    numVerts = 4*this->Resolution;
    numPolys = this->Resolution + 2;
    }
  else
    {
    numVerts = 2*this->Resolution;
    numPolys = this->Resolution;
    }

  newPoints = new vlFloatPoints;
  newPoints->Initialize(numPts);

  newNormals = new vlFloatNormals;
  newNormals->Initialize(numPts);

  newTCoords = new vlFloatTCoords;
  newTCoords->Initialize(numPts,2);

  newPtData = new vlPointData;

  newPolys = new vlCellArray;
  newPolys->Initialize(newPolys->EstimateSize(numPolys,this->Resolution));
//
// Generate points and point data for sides
//
  for (i=0; i<this->Resolution; i++)
    {
    // x coordinate
    xbot[0] = xtop[0] = nbot[0] = ntop[0] = this->Radius * cos((double)i*angle);
    tcbot[0] = tctop[0] = fabs(2.0*i/this->Resolution - 1.0);

    // y coordinate
    xbot[1] = 0.5 * this->Height;
    xtop[1] = -0.5 * this->Height;
    nbot[1] = ntop[1] = 0.0;
    tcbot[1] = 0.0;
    tctop[1] = 1.0;

    // z coordinate
    xbot[2] = xtop[2] = nbot[2] = ntop[2] = -this->Radius * sin((double)i*angle);

    idx = 2*i;
    newPoints->InsertPoint(idx,xbot);
    newPoints->InsertPoint(idx+1,xtop);
    newTCoords->InsertTCoord(idx,tcbot);
    newTCoords->InsertTCoord(idx+1,tctop);
    newNormals->InsertNormal(idx,nbot);
    newNormals->InsertNormal(idx+1,ntop);
    }
//
// Generate polygons for sides
//
  for (i=0; i<this->Resolution; i++)
    {
    pts[0] = 2*i;
    pts[1] = pts[0] + 1;
    pts[2] = (pts[1] + 2) % this->Resolution;
    pts[3] = pts[3] - 1;
    newPolys->InsertNextCell(4,pts);
    }
//
// Generate points and point data for top/bottom polygons
//
  if ( this->Capping )
    {
    for (i=0; i<this->Resolution; i++)
      {
      // x coordinate
      xbot[0] = xtop[0] = this->Radius * cos((double)i*angle);
      nbot[0] = ntop[0] = 0.0;
      tcbot[0] = tctop[0] = xbot[0];

      // y coordinate
      xbot[1] = 0.5 * this->Height;
      xtop[1] = -0.5 * this->Height;
      nbot[1] = -1.0;
      ntop[1] =  1.0;

      // z coordinate
      xbot[2] = xtop[2] = -this->Radius * sin((double)i*angle);
      tcbot[1] = tctop[1] = xbot[2];

      idx = 2*this->Resolution;
      newPoints->InsertPoint(idx+i,xbot);
      newTCoords->InsertTCoord(idx+i,tcbot);
      newNormals->InsertNormal(idx+i,nbot);

      idx = 3*this->Resolution;
      newPoints->InsertPoint(idx+i,xtop);
      newTCoords->InsertTCoord(idx+i,tctop);
      newNormals->InsertNormal(idx+i,ntop);
      }
//
// Generate polygons for top/bottom polygons
//
    for (i=0; i<this->Resolution; i++)
      {
      pts[i] = 2*this->Resolution + i;
      }
    newPolys->InsertNextCell(this->Resolution,pts);
    for (i=0; i<this->Resolution; i++)
      {
      pts[i] = 3*this->Resolution + i;
      }
    newPolys->InsertNextCell(this->Resolution,pts);

    } // if capping
//
// Update ourselves
//
  this->SetPoints(newPoints);
  this->SetPointData(newPtData);
  newPtData->SetNormals(newNormals);
  newPtData->SetTCoords(newTCoords);

  newPolys->Squeeze(); // since we've estimated size; reclaim some space
  this->SetPolys(newPolys);
}
<commit_msg>ERR: Fixed indexing bug.<commit_after>//
// Methods for plane generator
//
#include <math.h>
#include "CylSrc.hh"

void vlCylinderSource::SetResolution(int res)
{
  if ( res != this->Resolution )
    {
    this->Resolution = res;
    this->Resolution = (this->Resolution < 3 ? 3 :
        (this->Resolution > MAX_RESOLUTION ? MAX_RESOLUTION : this->Resolution));
    this->Modified();
    }
}
int vlCylinderSource::GetResolution()
{
  return this->Resolution;
}

void vlCylinderSource::SetHeight(float h)
{
  if ( h != this->Height )
    {
    this->Height = h;
    this->Height = (this->Height > 0.0 ? this->Height : 1.0);
    this->Modified();
    }
}
float vlCylinderSource::GetHeight()
{
  return this->Height;
}

void vlCylinderSource::SetRadius(float h)
{
  if ( h != this->Radius )
    {
    this->Radius = h;
    this->Radius = (this->Radius > 0.0 ? this->Radius : 0.5);
    this->Modified();
    }
}
float vlCylinderSource::GetRadius()
{
  return this->Radius;
}

void vlCylinderSource::SetCapping(int flag)
{
  if ( flag != this->Capping )
    {
    this->Capping = flag;
    this->Modified();
    }
}
int vlCylinderSource::GetCapping()
{
  return this->Capping;
}

void vlCylinderSource::Execute()
{
  float angle= 2.0*3.141592654/this->Resolution;
  int numPolys, numPts;
  float xbot[3], tcbot[2], nbot[3];
  float xtop[3], tctop[2], ntop[3];
  int i, idx;
  int pts[MAX_RESOLUTION];
  vlFloatPoints *newPoints;
  vlFloatNormals *newNormals;
  vlFloatTCoords *newTCoords;
  vlCellArray *newPolys;
  vlPointData *newPtData;
//
// Set things up; allocate memory
//
  this->Initialize();

  if ( this->Capping )
    {
    numPts = 4*this->Resolution;
    numPolys = this->Resolution + 2;
    }
  else
    {
    numPts = 2*this->Resolution;
    numPolys = this->Resolution;
    }

  newPoints = new vlFloatPoints;
  newPoints->Initialize(numPts);

  newNormals = new vlFloatNormals;
  newNormals->Initialize(numPts);

  newTCoords = new vlFloatTCoords;
  newTCoords->Initialize(numPts,2);

  newPtData = new vlPointData;

  newPolys = new vlCellArray;
  newPolys->Initialize(newPolys->EstimateSize(numPolys,this->Resolution));
//
// Generate points and point data for sides
//
  for (i=0; i<this->Resolution; i++)
    {
    // x coordinate
    xbot[0] = xtop[0] = nbot[0] = ntop[0] = this->Radius * cos((double)i*angle);
    tcbot[0] = tctop[0] = fabs(2.0*i/this->Resolution - 1.0);

    // y coordinate
    xbot[1] = 0.5 * this->Height;
    xtop[1] = -0.5 * this->Height;
    nbot[1] = ntop[1] = 0.0;
    tcbot[1] = 0.0;
    tctop[1] = 1.0;

    // z coordinate
    xbot[2] = xtop[2] = nbot[2] = ntop[2] = -this->Radius * sin((double)i*angle);

    idx = 2*i;
    newPoints->InsertPoint(idx,xbot);
    newPoints->InsertPoint(idx+1,xtop);
    newTCoords->InsertTCoord(idx,tcbot);
    newTCoords->InsertTCoord(idx+1,tctop);
    newNormals->InsertNormal(idx,nbot);
    newNormals->InsertNormal(idx+1,ntop);
    }
//
// Generate polygons for sides
//
  for (i=0; i<this->Resolution; i++)
    {
    pts[0] = 2*i;
    pts[1] = pts[0] + 1;
    pts[2] = (pts[1] + 2) % (2*this->Resolution);
    pts[3] = pts[2] - 1;
    newPolys->InsertNextCell(4,pts);
    }
//
// Generate points and point data for top/bottom polygons
//
  if ( this->Capping )
    {
    for (i=0; i<this->Resolution; i++)
      {
      // x coordinate
      xbot[0] = xtop[0] = this->Radius * cos((double)i*angle);
      nbot[0] = ntop[0] = 0.0;
      tcbot[0] = tctop[0] = xbot[0];

      // y coordinate
      xbot[1] = 0.5 * this->Height;
      xtop[1] = -0.5 * this->Height;
      nbot[1] = -1.0;
      ntop[1] =  1.0;

      // z coordinate
      xbot[2] = xtop[2] = -this->Radius * sin((double)i*angle);
      tcbot[1] = tctop[1] = xbot[2];

      idx = 2*this->Resolution;
      newPoints->InsertPoint(idx+i,xbot);
      newTCoords->InsertTCoord(idx+i,tcbot);
      newNormals->InsertNormal(idx+i,nbot);

      idx = 3*this->Resolution;
      newPoints->InsertPoint(idx+i,xtop);
      newTCoords->InsertTCoord(idx+i,tctop);
      newNormals->InsertNormal(idx+i,ntop);
      }
//
// Generate polygons for top/bottom polygons
//
    for (i=0; i<this->Resolution; i++)
      {
      pts[i] = 2*this->Resolution + i;
      }
    newPolys->InsertNextCell(this->Resolution,pts);
    for (i=0; i<this->Resolution; i++)
      {
      pts[i] = 3*this->Resolution + i;
      }
    newPolys->InsertNextCell(this->Resolution,pts);

    } // if capping
//
// Update ourselves
//
  this->SetPoints(newPoints);
  this->SetPointData(newPtData);
  newPtData->SetNormals(newNormals);
  newPtData->SetTCoords(newTCoords);

  newPolys->Squeeze(); // since we've estimated size; reclaim some space
  this->SetPolys(newPolys);
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential.
#include "stdafx.h"
#include "DispatchQueueTest.h"
#include "DispatchQueue.h"

using namespace std;

class EventMaker:
  public CoreThread
{
public:
  EventMaker():
    CoreThread("EventMaker")
  {
    AcceptDispatchDelivery();
  }
};

class ThreadBase:
  public CoreThread
{
public:
  ThreadBase(){
    AcceptDispatchDelivery();
  }
};

template<int N>
class Thread:
  public ThreadBase
{};

TEST_F(DispatchQueueTest, SimpleEvents) {
  int count = 0;

  *this += [&count] () {
    ++count;
  };

  *this += [&count] () {
    count += 5 ;
  };

  int num = DispatchAllEvents();

  *this += [&count] () {
    count += 5 ;
  };

  EXPECT_EQ(2, num);
  EXPECT_EQ(6, count);
}

TEST_F(DispatchQueueTest, SingleThreadCommits){
  int count = 0;
  {
    Commision com = *this += [&count] () {
      count+=1;
    };

    DispatchAllEvents();

    *this += [&count] () {
      count+=2;
    };

    DispatchAllEvents();

    Commision com2 = *this += [&count] {
      count+=4;
    };

    DispatchAllEvents();

    EXPECT_EQ(0, count);

    com.Commit();

    DispatchAllEvents();

    EXPECT_EQ(3, count);
  }

  DispatchAllEvents();

  EXPECT_EQ(7, count);
}

#if _WIN32
TEST_F(DispatchQueueTest, DISABLED_MultiThreadCommits)
#else
TEST_F(DispatchQueueTest, MultiThreadCommits)
#endif
{
  AutoRequired<EventMaker> eventMaker;
  int count = 0;

  boost::mutex mut;
  boost::unique_lock<boost::mutex> lk(mut);
  boost::condition_variable cond;

  m_create->InitiateCoreThreads();

  *eventMaker += [&count, &cond, &mut] () {
    boost::unique_lock<boost::mutex> lk(mut);
    count += 1;
    cond.notify_all();
  };

  Commision com1 = *eventMaker += [&count, &cond, &mut] () {
    boost::unique_lock<boost::mutex> lk(mut);
    count += 2;
  };

  *eventMaker += [&count, &cond, &mut] () {
    boost::unique_lock<boost::mutex> lk(mut);
    count += 4;
    cond.notify_all();
  };

  EXPECT_FALSE( boost::cv_status::timeout == cond.wait_for(lk,boost::chrono::microseconds(500)) )
  << "Waited more than 500ms on condition variable";

  EXPECT_EQ(1, count);

  com1.Commit();

  EXPECT_FALSE( boost::cv_status::timeout == cond.wait_for(lk,boost::chrono::microseconds(500)) )
  << "Waited more than 500ms on condition variable";

  EXPECT_EQ(7, count);
}

TEST_F(DispatchQueueTest, PathologicalStartAndStop){
  AutoRequired<Thread<1>> t1;
  AutoRequired<Thread<2>> t2;
  AutoRequired<Thread<3>> t3;
  AutoRequired<Thread<4>> t4;
  m_create->InitiateCoreThreads();
  t1->Stop(true);
  EXPECT_TRUE(t1->WaitFor(boost::chrono::microseconds(200)));
  t2->Stop(true);
  EXPECT_TRUE(t2->WaitFor(boost::chrono::microseconds(200)));
  t3->Stop(true);
  EXPECT_TRUE(t3->WaitFor(boost::chrono::microseconds(200)));
  t4->Stop(true);
  EXPECT_TRUE(t4->WaitFor(boost::chrono::microseconds(200)));
}

<commit_msg>Lengthened wait time in DispathQueueTest.<commit_after>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential.
#include "stdafx.h"
#include "DispatchQueueTest.h"
#include "DispatchQueue.h"

using namespace std;

class EventMaker:
  public CoreThread
{
public:
  EventMaker():
    CoreThread("EventMaker")
  {
    AcceptDispatchDelivery();
  }
};

class ThreadBase:
  public CoreThread
{
public:
  ThreadBase(){
    AcceptDispatchDelivery();
  }
};

template<int N>
class Thread:
  public ThreadBase
{};

TEST_F(DispatchQueueTest, SimpleEvents) {
  int count = 0;

  *this += [&count] () {
    ++count;
  };

  *this += [&count] () {
    count += 5 ;
  };

  int num = DispatchAllEvents();

  *this += [&count] () {
    count += 5 ;
  };

  EXPECT_EQ(2, num);
  EXPECT_EQ(6, count);
}

TEST_F(DispatchQueueTest, SingleThreadCommits){
  int count = 0;
  {
    Commision com = *this += [&count] () {
      count+=1;
    };

    DispatchAllEvents();

    *this += [&count] () {
      count+=2;
    };

    DispatchAllEvents();

    Commision com2 = *this += [&count] {
      count+=4;
    };

    DispatchAllEvents();

    EXPECT_EQ(0, count);

    com.Commit();

    DispatchAllEvents();

    EXPECT_EQ(3, count);
  }

  DispatchAllEvents();

  EXPECT_EQ(7, count);
}

TEST_F(DispatchQueueTest, MultiThreadCommits) {
  AutoRequired<EventMaker> eventMaker;
  int count = 0;

  boost::mutex mut;
  boost::unique_lock<boost::mutex> lk(mut);
  boost::condition_variable cond;

  m_create->InitiateCoreThreads();

  *eventMaker += [&count, &cond, &mut] () {
    boost::unique_lock<boost::mutex> lk(mut);
    count += 1;
    cond.notify_all();
  };

  Commision com1 = *eventMaker += [&count, &cond, &mut] () {
    boost::unique_lock<boost::mutex> lk(mut);
    count += 2;
  };

  *eventMaker += [&count, &cond, &mut] () {
    boost::unique_lock<boost::mutex> lk(mut);
    count += 4;
    cond.notify_all();
  };

  ASSERT_EQ(boost::cv_status::no_timeout, cond.wait_for(lk,boost::chrono::seconds(2)))
  << "Waited more than 2 seconds on condition variable. Probably hanging.";

  EXPECT_EQ(1, count);

  com1.Commit();

  ASSERT_EQ(boost::cv_status::no_timeout, cond.wait_for(lk,boost::chrono::seconds(2)))
  << "Waited more than 2 seconds on condition variable. Probably hanging.";

  EXPECT_EQ(7, count);
}

TEST_F(DispatchQueueTest, PathologicalStartAndStop){
  AutoRequired<Thread<1>> t1;
  AutoRequired<Thread<2>> t2;
  AutoRequired<Thread<3>> t3;
  AutoRequired<Thread<4>> t4;
  m_create->InitiateCoreThreads();
  t1->Stop(true);
  EXPECT_TRUE(t1->WaitFor(boost::chrono::microseconds(200)));
  t2->Stop(true);
  EXPECT_TRUE(t2->WaitFor(boost::chrono::microseconds(200)));
  t3->Stop(true);
  EXPECT_TRUE(t3->WaitFor(boost::chrono::microseconds(200)));
  t4->Stop(true);
  EXPECT_TRUE(t4->WaitFor(boost::chrono::microseconds(200)));
}

<|endoftext|>