<commit_before>#include "SIO/SIOWriter.h"

#include "EVENT/LCEvent.h"
#include "EVENT/LCRunHeader.h"
#include "EVENT/LCIO.h"
#include "EVENT/LCCollection.h"

#include "SIO/LCSIO.h"
#include "SIO/SIOEventHandler.h"
#include "SIO/SIOCollectionHandler.h"
//#include "SIO/SIOLCRelationHandler.h"
#include "SIO/SIORunHeaderHandler.h"

#include "LCIOSTLTypes.h"

#include "SIO_streamManager.h"
#include "SIO_recordManager.h"
#include "SIO_blockManager.h"
#include "SIO_stream.h"
#include "SIO_record.h"
#include "IMPL/LCIOExceptionHandler.h"

//#define DEBUG 1
#include "IMPL/LCTOOLS.h"
#include "IMPL/LCRelationImpl.h"

using namespace EVENT ;
using namespace IO ;
using namespace IMPL ;

namespace SIO {

  SIO_record * SIOWriter::_evtRecord ;
  SIO_record * SIOWriter::_hdrRecord ;
  SIO_record * SIOWriter::_runRecord ;

  SIOWriter::SIOWriter() : _hdrHandler(0), _runHandler(0) {

#ifdef DEBUG
    SIO_streamManager::setVerbosity( SIO_ALL ) ;
    SIO_recordManager::setVerbosity( SIO_ALL ) ;
    SIO_blockManager::setVerbosity( SIO_ALL ) ;
#else
    SIO_streamManager::setVerbosity( SIO_SILENT ) ;
    SIO_recordManager::setVerbosity( SIO_SILENT ) ;
    SIO_blockManager::setVerbosity(  SIO_SILENT ) ;
#endif
//     SIO_streamManager::setVerbosity( SIO_ERRORS ) ;
//     SIO_recordManager::setVerbosity( SIO_ERRORS ) ;
//     SIO_blockManager::setVerbosity(  SIO_ERRORS ) ;

    _runHandler = new SIORunHeaderHandler( LCSIO::RUNBLOCKNAME  ) ;
    _hdrHandler = new SIOEventHandler( LCSIO::HEADERBLOCKNAME ) ;

    //    evtP = new LCEvent* ;

    LCIOExceptionHandler::createInstance() ;

  }

  SIOWriter::~SIOWriter(){

    // delete and disconnect all existing handlers (SIO_blocks)
    //     typedef std::vector< SIOCollectionHandler* >::iterator CHI ;
    //     for( CHI ch = _connectedBlocks.begin() ; ch !=  _connectedBlocks.end() ; ch++){
    //       _evtRecord->disconnect( *ch );
    //       delete *ch ;
    //     }
    //     _runRecord->disconnect( _runHandler ) ;
    //     _hdrRecord->disconnect( _hdrHandler ) ;
    //     //delete evtP ;
    delete _hdrHandler ;
    delete _runHandler ;
    SIO_blockManager::clear();

  }

  void SIOWriter::open(const std::string & filename) throw(IOException, std::exception){

    std::string sioFilename ;
    getSIOFileName( filename, sioFilename ) ;

    // if the file exists we throw an exception

    FILE* f = fopen( sioFilename.c_str() , "r") ;
    if( f != 0 ){
      fclose(f) ;
      throw IOException( std::string( "[SIOWriter::open()] File already exists: "
    				      + sioFilename
				      + " \n              open it in append or new mode !\n"
				      )) ;
    }
    // open new file for writing
    return open( filename, EVENT::LCIO::WRITE_NEW ) ;
  }

  void SIOWriter::getSIOFileName(const std::string& filename,
				 std::string& sioFilename ) {

    if( filename.rfind(LCSIO::FILE_EXTENSION) == std::string::npos ||  // .slcio not found at all
	!(  filename.rfind(LCSIO::FILE_EXTENSION)
	    + strlen( LCSIO::FILE_EXTENSION ) == filename.length() ) ) {  // found, but not at end

      // find_last_of looks for characters and not substrings !!
//     if( filename.find_last_of(LCSIO::FILE_EXTENSION) != filename.length() - 1  ) {

      sioFilename = filename + LCSIO::FILE_EXTENSION ;
    }
    else
      sioFilename = filename ;
  }

  void SIOWriter::open(const std::string& filename, int writeMode) throw(IOException, std::exception) {

    // make sure filename has the proper extension (.slcio)
    std::string sioFilename ;
    getSIOFileName( filename, sioFilename ) ;

    // SIO has some rules about valid names for streams, records, etc ...
    //    const char* stream_name = LCSIO::getValidSIOName(sioFilename) ;
    std::string stream_name = LCSIO::getValidSIOName(sioFilename) ;
    _stream = SIO_streamManager::add(  stream_name.c_str() , 64 * SIO_KBYTE ) ;

    if( _stream == 0 )
      throw IOException( std::string( "[SIOWriter::open()] Bad or duplicate stream name: "
 				      + stream_name  )) ;
// 				      + std::string(stream_name)  )) ;
//     delete[] stream_name ;

    unsigned int  status = 0  ;
    switch( writeMode )
      {
      case EVENT::LCIO::WRITE_NEW :
	status  = _stream->open( sioFilename.c_str() , SIO_MODE_WRITE_NEW ) ;
	break ;
      case EVENT::LCIO::WRITE_APPEND :
	status  = _stream->open( sioFilename.c_str() , SIO_MODE_WRITE_APPEND ) ;
	break ;
      }

    if( !(status &1) )
      throw IOException( std::string( "[SIOWriter::open()] Couldn't open file: "
				      +  sioFilename ) ) ;

     // tell SIO the record names if not yet known
     if( (_runRecord = SIO_recordManager::get( LCSIO::RUNRECORDNAME )) == 0 )
     _runRecord = SIO_recordManager::add( LCSIO::RUNRECORDNAME ) ;

     if( (_hdrRecord = SIO_recordManager::get( LCSIO::HEADERRECORDNAME )) == 0 )
     _hdrRecord = SIO_recordManager::add( LCSIO::HEADERRECORDNAME ) ;

     if( (_evtRecord = SIO_recordManager::get( LCSIO::EVENTRECORDNAME )) ==0 )
     _evtRecord = SIO_recordManager::add( LCSIO::EVENTRECORDNAME ) ;

    _hdrRecord->setCompress( LCSIO::COMPRESSION ) ;
    _evtRecord->setCompress( LCSIO::COMPRESSION ) ;
    _runRecord->setCompress( LCSIO::COMPRESSION ) ;

  }

  void SIOWriter::writeRunHeader(const EVENT::LCRunHeader * hdr)  throw(IOException, std::exception) {

    // create a new handler for every new run

//     if( !_runHandler){
//       _runHandler = dynamic_cast<SIORunHeaderHandler*>
// 	( SIO_blockManager::get( LCSIO::RUNBLOCKNAME  ) ) ;

//       if( _runHandler == 0 )
// 	_runHandler = new SIORunHeaderHandler( LCSIO::RUNBLOCKNAME  ) ;

    _runRecord->disconnect(LCSIO::RUNBLOCKNAME ) ;
    _runRecord->connect( _runHandler );
//     }

    _runHandler->setRunHeader(  hdr ) ;

    if( _stream->getState()== SIO_STATE_OPEN ){

      // write LCRunHeader record
      unsigned int status =  _stream->write( LCSIO::RUNRECORDNAME    ) ;

      if( !(status & 1)  )
	throw IOException( std::string( "[SIOWriter::writeRunHeader] couldn't write run header to stream: "
					+  *_stream->getName() ) ) ;
    } else {

      throw IOException( std::string( "[SIOWriter::writeRunHeader] stream not opened: "
				      +  *_stream->getName() ) ) ;

    }
  }

  /** Creates Handlers needed for writing the event on this stream.
   * Needs to be called for every event.
   */
  void SIOWriter::setUpHandlers(const LCEvent * evt){

    // connect handlers to the record
    // create them if needed, i.e. they are not already in SIO_blockManager !

    //if( ! _hdrHandler ){
    // should this go ? - create your own handler ....
    //       _hdrHandler = dynamic_cast<SIOEventHandler*>
    // 	( SIO_blockManager::get( LCSIO::HEADERBLOCKNAME  ) ) ;
    //       if( ! _hdrHandler )
    // 	_hdrHandler = new SIOEventHandler( LCSIO::HEADERBLOCKNAME ) ;
    //      _hdrRecord->connect( _hdrHandler ) ;
    //}

    _hdrRecord->disconnect( LCSIO::HEADERBLOCKNAME ) ;
    _hdrRecord->connect( _hdrHandler ) ;

    //     // disconnect old handlers from last event first
    //     typedef std::vector< SIO_block* >::iterator CHI ;
    //     for( CHI ch = _connectedBlocks.begin() ; ch !=  _connectedBlocks.end() ; ch++){
    //       _evtRecord->disconnect( *ch );
    //     }
    //     _connectedBlocks.clear() ;

    // need to disconnect all blocks for multiple I/O streams
    _evtRecord->disconnectAll() ;

    const std::vector<std::string>* strVec = evt->getCollectionNames() ;

    for( std::vector<std::string>::const_iterator name = strVec->begin() ; name != strVec->end() ; name++){

      SIOCollectionHandler* ch = dynamic_cast<SIOCollectionHandler*>
	( SIO_blockManager::get( name->c_str() )  ) ;

      LCCollection* col = evt->getCollection( *name ) ;

      if(! col->isTransient() ){ // if a collection is transient we simply ignore it

	try{

	  if( ch == 0 ) {
	    ch =  new SIOCollectionHandler( *name, col->getTypeName())  ;
	  }
	  _evtRecord->connect( ch ) ;
// 	  _connectedBlocks.push_back( ch ) ;
	  ch->setCollection( col ) ;

	}
	catch(Exception& ex){   // unsuported type !
	  delete ch ;
	  ch =  0 ;
	}

      }

    }

//     //--- fg20040504 added relation handlers
//     const StringVec* relNames = evt->getRelationNames() ;

//     for( StringVec::const_iterator relName = relNames->begin() ; relName != relNames->end() ; relName++){

//       //      std::cout << " relation name:  " << *relName << std::endl ;

//       SIORelationHandler* rh = dynamic_cast<SIORelationHandler*>
// 	( SIO_blockManager::get( relName->c_str() )  ) ;

//       LCRelation* rel = evt->getRelation( *relName ) ;
//       //      LCRelationImpl* relImpl = dynamic_cast<LCRelationImpl*> ( rel ) ;
//       //      std::cout << " relation " << *relName << " casted  to LCRelationImpl  : " <<  relImpl << std::endl ;

//       if( rh == 0 ) {
// 	rh = new SIORelationHandler( *relName ) ;
//       }
//       _evtRecord->connect( rh ) ;
//       _connectedBlocks.push_back( rh ) ;
//       rh->setRelation( rel ) ;
//     }
//     //--- fg20040504 ------

  }

  void SIOWriter::writeEvent(const LCEvent* evt)  throw(IOException, std::exception) {

    //here we set up the collection handlers

    try{   setUpHandlers( evt) ;

    }catch(...){
      throw IOException(  "[SIOWriter::writeEvent] could not set up handlers " ) ;
    }

    if( _stream->getState()== SIO_STATE_OPEN ){

      // need to set the event in event header handler
      _hdrHandler->setEvent( evt ) ;

      unsigned int  status = 0  ;

      // write LCEventHeader record
      status =  _stream->write( LCSIO::HEADERRECORDNAME    ) ;

      if( ! (status & 1) )
	throw IOException(  std::string("[SIOWriter::writeEvent] couldn't write event header to stream: "
					+  *_stream->getName() )) ;

      // write the event record
      status =  _stream->write( LCSIO::EVENTRECORDNAME    ) ;

      if( ! (status & 1) )
	throw IOException(  std::string("[SIOWriter::writeEvent] couldn't write event header to stream: "
					+  *_stream->getName() )) ;
    }
    else

      throw IOException(  std::string("[SIOWriter::writeEvent] stream not opened : "
				      +  *_stream->getName()  )) ;

  }

  void SIOWriter::close() throw (IOException, std::exception) {

    const std::string* streamName  = _stream->getName() ;

    int status  =  SIO_streamManager::remove( _stream ) ;

    if(! (status &1) )
      throw IOException(  std::string("[SIOWriter::close] couldn't close stream  : "
				      + *streamName  )) ;

  }

  void SIOWriter::flush() throw (IOException, std::exception) {

    const std::string* streamName  = _stream->getName() ;

    int status =  _stream->flush() ;

    if(! (status &1) )
      throw IOException(  std::string("[SIOWriter::flush] couldn't flush stream  : "
				      + *streamName  )) ;

  }

} // namespace

<commit_msg>increased streamb buffer size to avoid frequent resizing<commit_after>#include "SIO/SIOWriter.h"

#include "EVENT/LCEvent.h"
#include "EVENT/LCRunHeader.h"
#include "EVENT/LCIO.h"
#include "EVENT/LCCollection.h"

#include "SIO/LCSIO.h"
#include "SIO/SIOEventHandler.h"
#include "SIO/SIOCollectionHandler.h"
//#include "SIO/SIOLCRelationHandler.h"
#include "SIO/SIORunHeaderHandler.h"

#include "LCIOSTLTypes.h"

#include "SIO_streamManager.h"
#include "SIO_recordManager.h"
#include "SIO_blockManager.h"
#include "SIO_stream.h"
#include "SIO_record.h"
#include "IMPL/LCIOExceptionHandler.h"

//#define DEBUG 1
#include "IMPL/LCTOOLS.h"
#include "IMPL/LCRelationImpl.h"

using namespace EVENT ;
using namespace IO ;
using namespace IMPL ;

namespace SIO {

  SIO_record * SIOWriter::_evtRecord ;
  SIO_record * SIOWriter::_hdrRecord ;
  SIO_record * SIOWriter::_runRecord ;

  SIOWriter::SIOWriter() : _hdrHandler(0), _runHandler(0) {

#ifdef DEBUG
    SIO_streamManager::setVerbosity( SIO_ALL ) ;
    SIO_recordManager::setVerbosity( SIO_ALL ) ;
    SIO_blockManager::setVerbosity( SIO_ALL ) ;
#else
    SIO_streamManager::setVerbosity( SIO_SILENT ) ;
    SIO_recordManager::setVerbosity( SIO_SILENT ) ;
    SIO_blockManager::setVerbosity(  SIO_SILENT ) ;
#endif
//     SIO_streamManager::setVerbosity( SIO_ERRORS ) ;
//     SIO_recordManager::setVerbosity( SIO_ERRORS ) ;
//     SIO_blockManager::setVerbosity(  SIO_ERRORS ) ;

    _runHandler = new SIORunHeaderHandler( LCSIO::RUNBLOCKNAME  ) ;
    _hdrHandler = new SIOEventHandler( LCSIO::HEADERBLOCKNAME ) ;

    //    evtP = new LCEvent* ;

    LCIOExceptionHandler::createInstance() ;

  }

  SIOWriter::~SIOWriter(){

    // delete and disconnect all existing handlers (SIO_blocks)
    //     typedef std::vector< SIOCollectionHandler* >::iterator CHI ;
    //     for( CHI ch = _connectedBlocks.begin() ; ch !=  _connectedBlocks.end() ; ch++){
    //       _evtRecord->disconnect( *ch );
    //       delete *ch ;
    //     }
    //     _runRecord->disconnect( _runHandler ) ;
    //     _hdrRecord->disconnect( _hdrHandler ) ;
    //     //delete evtP ;
    delete _hdrHandler ;
    delete _runHandler ;
    SIO_blockManager::clear();

  }

  void SIOWriter::open(const std::string & filename) throw(IOException, std::exception){

    std::string sioFilename ;
    getSIOFileName( filename, sioFilename ) ;

    // if the file exists we throw an exception

    FILE* f = fopen( sioFilename.c_str() , "r") ;
    if( f != 0 ){
      fclose(f) ;
      throw IOException( std::string( "[SIOWriter::open()] File already exists: "
    				      + sioFilename
				      + " \n              open it in append or new mode !\n"
				      )) ;
    }
    // open new file for writing
    return open( filename, EVENT::LCIO::WRITE_NEW ) ;
  }

  void SIOWriter::getSIOFileName(const std::string& filename,
				 std::string& sioFilename ) {

    if( filename.rfind(LCSIO::FILE_EXTENSION) == std::string::npos ||  // .slcio not found at all
	!(  filename.rfind(LCSIO::FILE_EXTENSION)
	    + strlen( LCSIO::FILE_EXTENSION ) == filename.length() ) ) {  // found, but not at end

      // find_last_of looks for characters and not substrings !!
//     if( filename.find_last_of(LCSIO::FILE_EXTENSION) != filename.length() - 1  ) {

      sioFilename = filename + LCSIO::FILE_EXTENSION ;
    }
    else
      sioFilename = filename ;
  }

  void SIOWriter::open(const std::string& filename, int writeMode) throw(IOException, std::exception) {

    // make sure filename has the proper extension (.slcio)
    std::string sioFilename ;
    getSIOFileName( filename, sioFilename ) ;

    // SIO has some rules about valid names for streams, records, etc ...
    //    const char* stream_name = LCSIO::getValidSIOName(sioFilename) ;
    std::string stream_name = LCSIO::getValidSIOName(sioFilename) ;
    _stream = SIO_streamManager::add(  stream_name.c_str() , 32*SIO_KBYTE*SIO_KBYTE ) ;

    if( _stream == 0 )
      throw IOException( std::string( "[SIOWriter::open()] Bad or duplicate stream name: "
 				      + stream_name  )) ;
// 				      + std::string(stream_name)  )) ;
//     delete[] stream_name ;

    unsigned int  status = 0  ;
    switch( writeMode )
      {
      case EVENT::LCIO::WRITE_NEW :
	status  = _stream->open( sioFilename.c_str() , SIO_MODE_WRITE_NEW ) ;
	break ;
      case EVENT::LCIO::WRITE_APPEND :
	status  = _stream->open( sioFilename.c_str() , SIO_MODE_WRITE_APPEND ) ;
	break ;
      }

    if( !(status &1) )
      throw IOException( std::string( "[SIOWriter::open()] Couldn't open file: "
				      +  sioFilename ) ) ;

     // tell SIO the record names if not yet known
     if( (_runRecord = SIO_recordManager::get( LCSIO::RUNRECORDNAME )) == 0 )
     _runRecord = SIO_recordManager::add( LCSIO::RUNRECORDNAME ) ;

     if( (_hdrRecord = SIO_recordManager::get( LCSIO::HEADERRECORDNAME )) == 0 )
     _hdrRecord = SIO_recordManager::add( LCSIO::HEADERRECORDNAME ) ;

     if( (_evtRecord = SIO_recordManager::get( LCSIO::EVENTRECORDNAME )) ==0 )
     _evtRecord = SIO_recordManager::add( LCSIO::EVENTRECORDNAME ) ;

    _hdrRecord->setCompress( LCSIO::COMPRESSION ) ;
    _evtRecord->setCompress( LCSIO::COMPRESSION ) ;
    _runRecord->setCompress( LCSIO::COMPRESSION ) ;

  }

  void SIOWriter::writeRunHeader(const EVENT::LCRunHeader * hdr)  throw(IOException, std::exception) {

    // create a new handler for every new run

//     if( !_runHandler){
//       _runHandler = dynamic_cast<SIORunHeaderHandler*>
// 	( SIO_blockManager::get( LCSIO::RUNBLOCKNAME  ) ) ;

//       if( _runHandler == 0 )
// 	_runHandler = new SIORunHeaderHandler( LCSIO::RUNBLOCKNAME  ) ;

    _runRecord->disconnect(LCSIO::RUNBLOCKNAME ) ;
    _runRecord->connect( _runHandler );
//     }

    _runHandler->setRunHeader(  hdr ) ;

    if( _stream->getState()== SIO_STATE_OPEN ){

      // write LCRunHeader record
      unsigned int status =  _stream->write( LCSIO::RUNRECORDNAME    ) ;

      if( !(status & 1)  )
	throw IOException( std::string( "[SIOWriter::writeRunHeader] couldn't write run header to stream: "
					+  *_stream->getName() ) ) ;
    } else {

      throw IOException( std::string( "[SIOWriter::writeRunHeader] stream not opened: "
				      +  *_stream->getName() ) ) ;

    }
  }

  /** Creates Handlers needed for writing the event on this stream.
   * Needs to be called for every event.
   */
  void SIOWriter::setUpHandlers(const LCEvent * evt){

    // connect handlers to the record
    // create them if needed, i.e. they are not already in SIO_blockManager !

    //if( ! _hdrHandler ){
    // should this go ? - create your own handler ....
    //       _hdrHandler = dynamic_cast<SIOEventHandler*>
    // 	( SIO_blockManager::get( LCSIO::HEADERBLOCKNAME  ) ) ;
    //       if( ! _hdrHandler )
    // 	_hdrHandler = new SIOEventHandler( LCSIO::HEADERBLOCKNAME ) ;
    //      _hdrRecord->connect( _hdrHandler ) ;
    //}

    _hdrRecord->disconnect( LCSIO::HEADERBLOCKNAME ) ;
    _hdrRecord->connect( _hdrHandler ) ;

    //     // disconnect old handlers from last event first
    //     typedef std::vector< SIO_block* >::iterator CHI ;
    //     for( CHI ch = _connectedBlocks.begin() ; ch !=  _connectedBlocks.end() ; ch++){
    //       _evtRecord->disconnect( *ch );
    //     }
    //     _connectedBlocks.clear() ;

    // need to disconnect all blocks for multiple I/O streams
    _evtRecord->disconnectAll() ;

    const std::vector<std::string>* strVec = evt->getCollectionNames() ;

    for( std::vector<std::string>::const_iterator name = strVec->begin() ; name != strVec->end() ; name++){

      SIOCollectionHandler* ch = dynamic_cast<SIOCollectionHandler*>
	( SIO_blockManager::get( name->c_str() )  ) ;

      LCCollection* col = evt->getCollection( *name ) ;

      if(! col->isTransient() ){ // if a collection is transient we simply ignore it

	try{

	  if( ch == 0 ) {
	    ch =  new SIOCollectionHandler( *name, col->getTypeName())  ;
	  }
	  _evtRecord->connect( ch ) ;
// 	  _connectedBlocks.push_back( ch ) ;
	  ch->setCollection( col ) ;

	}
	catch(Exception& ex){   // unsuported type !
	  delete ch ;
	  ch =  0 ;
	}

      }

    }

//     //--- fg20040504 added relation handlers
//     const StringVec* relNames = evt->getRelationNames() ;

//     for( StringVec::const_iterator relName = relNames->begin() ; relName != relNames->end() ; relName++){

//       //      std::cout << " relation name:  " << *relName << std::endl ;

//       SIORelationHandler* rh = dynamic_cast<SIORelationHandler*>
// 	( SIO_blockManager::get( relName->c_str() )  ) ;

//       LCRelation* rel = evt->getRelation( *relName ) ;
//       //      LCRelationImpl* relImpl = dynamic_cast<LCRelationImpl*> ( rel ) ;
//       //      std::cout << " relation " << *relName << " casted  to LCRelationImpl  : " <<  relImpl << std::endl ;

//       if( rh == 0 ) {
// 	rh = new SIORelationHandler( *relName ) ;
//       }
//       _evtRecord->connect( rh ) ;
//       _connectedBlocks.push_back( rh ) ;
//       rh->setRelation( rel ) ;
//     }
//     //--- fg20040504 ------

  }

  void SIOWriter::writeEvent(const LCEvent* evt)  throw(IOException, std::exception) {

    //here we set up the collection handlers

    try{   setUpHandlers( evt) ;

    }catch(...){
      throw IOException(  "[SIOWriter::writeEvent] could not set up handlers " ) ;
    }

    if( _stream->getState()== SIO_STATE_OPEN ){

      // need to set the event in event header handler
      _hdrHandler->setEvent( evt ) ;

      unsigned int  status = 0  ;

      // write LCEventHeader record
      status =  _stream->write( LCSIO::HEADERRECORDNAME    ) ;

      if( ! (status & 1) )
	throw IOException(  std::string("[SIOWriter::writeEvent] couldn't write event header to stream: "
					+  *_stream->getName() )) ;

      // write the event record
      status =  _stream->write( LCSIO::EVENTRECORDNAME    ) ;

      if( ! (status & 1) )
	throw IOException(  std::string("[SIOWriter::writeEvent] couldn't write event header to stream: "
					+  *_stream->getName() )) ;
    }
    else

      throw IOException(  std::string("[SIOWriter::writeEvent] stream not opened : "
				      +  *_stream->getName()  )) ;

  }

  void SIOWriter::close() throw (IOException, std::exception) {

    const std::string* streamName  = _stream->getName() ;

    int status  =  SIO_streamManager::remove( _stream ) ;

    if(! (status &1) )
      throw IOException(  std::string("[SIOWriter::close] couldn't close stream  : "
				      + *streamName  )) ;

  }

  void SIOWriter::flush() throw (IOException, std::exception) {

    const std::string* streamName  = _stream->getName() ;

    int status =  _stream->flush() ;

    if(! (status &1) )
      throw IOException(  std::string("[SIOWriter::flush] couldn't flush stream  : "
				      + *streamName  )) ;

  }

} // namespace

<|endoftext|>


<commit_before>#include <map>
#include <iostream>

#include "globals.hh"
#include "normalise.hh"
#include "shared.hh"
#include "eval.hh"
#include "parser.hh"
#include "help.txt.hh"

void printHelp()
{
    cout << string((char *) helpText, sizeof helpText);
}

static Expr evalStdin(EvalState & state)
{
    startNest(nest, lvlTalkative, format("evaluating standard input"));
    string s, s2;
    while (getline(cin, s2)) s += s2 + "\n";
    Expr e = parseExprFromString(state, s, absPath("."));
    return evalExpr(state, e);
}

static void printNixExpr(EvalState & state, Expr e)
{
    ATMatcher m;
    ATermList es;

    /* !!! duplication w.r.t. parseDerivations in nix-env */

    if (atMatch(m, e) >> "Attrs" >> es) {
        Expr a = queryAttr(e, "type");
        if (a && evalString(state, a) == "derivation") {
            a = queryAttr(e, "drvPath");
            if (a) {
                cout << format("%1%\n") % evalPath(state, a);
                return;
            }
            throw Error("bad derivation");
        } else {
            ATermMap drvMap;
            queryAllAttrs(e, drvMap);
            for (ATermIterator i(drvMap.keys()); i; ++i)
                printNixExpr(state, evalExpr(state, drvMap.get(*i)));
            return;
        }
    }

    if (atMatch(m, e) >> "List" >> es) {
        for (ATermIterator i(es); i; ++i)
            printNixExpr(state, evalExpr(state, *i));
        return;
    }

    throw Error("expression does not evaluate to one or more derivations");
}

void run(Strings args)
{
    EvalState state;
    Strings files;
    bool readStdin = false;

    for (Strings::iterator it = args.begin();
         it != args.end(); )
    {
        string arg = *it++;

        if (arg == "-")
            readStdin = true;
        else if (arg[0] == '-')
            throw UsageError(format("unknown flag `%1%`") % arg);
        else
            files.push_back(arg);
    }

    openDB();

    if (readStdin) {
        Expr e = evalStdin(state);
        printNixExpr(state, e);
    }

    for (Strings::iterator it = files.begin();
         it != files.end(); it++)
    {
        Expr e = evalFile(state, absPath(*it));
        printNixExpr(state, e);
    }

    printEvalStats(state);
}

string programId = "nix-instantiate";
<commit_msg>* Mode `--parse-only' to parse the input (on stdin, `-'), and print   out the AST as an ATerm. * Mode `--eval-only' to parse and evaluate the input, and print the   resulting normal form as an ATerm.<commit_after>#include <map>
#include <iostream>

#include "globals.hh"
#include "normalise.hh"
#include "shared.hh"
#include "eval.hh"
#include "parser.hh"
#include "help.txt.hh"

void printHelp()
{
    cout << string((char *) helpText, sizeof helpText);
}

static Expr evalStdin(EvalState & state, bool parseOnly)
{
    startNest(nest, lvlTalkative, format("evaluating standard input"));
    string s, s2;
    while (getline(cin, s2)) s += s2 + "\n";
    Expr e = parseExprFromString(state, s, absPath("."));
    return parseOnly ? e : evalExpr(state, e);
}

static void printDrvPaths(EvalState & state, Expr e)
{
    ATMatcher m;
    ATermList es;

    /* !!! duplication w.r.t. parseDerivations in nix-env */

    if (atMatch(m, e) >> "Attrs" >> es) {
        Expr a = queryAttr(e, "type");
        if (a && evalString(state, a) == "derivation") {
            a = queryAttr(e, "drvPath");
            if (a) {
                cout << format("%1%\n") % evalPath(state, a);
                return;
            }
            throw Error("bad derivation");
        } else {
            ATermMap drvMap;
            queryAllAttrs(e, drvMap);
            for (ATermIterator i(drvMap.keys()); i; ++i)
                printDrvPaths(state, evalExpr(state, drvMap.get(*i)));
            return;
        }
    }

    if (atMatch(m, e) >> "List" >> es) {
        for (ATermIterator i(es); i; ++i)
            printDrvPaths(state, evalExpr(state, *i));
        return;
    }

    throw Error("expression does not evaluate to one or more derivations");
}

static void printResult(EvalState & state, Expr e, bool evalOnly)
{
    if (evalOnly)
        cout << format("%1%\n") % e;
    else
        printDrvPaths(state, e);
}

void run(Strings args)
{
    EvalState state;
    Strings files;
    bool readStdin = false;
    bool evalOnly = false;
    bool parseOnly = false;

    for (Strings::iterator it = args.begin();
         it != args.end(); )
    {
        string arg = *it++;

        if (arg == "-")
            readStdin = true;
        else if (arg == "--eval-only") {
            readOnlyMode = true;
            evalOnly = true;
        }
        else if (arg == "--parse-only") {
            readOnlyMode = true;
            parseOnly = evalOnly = true;
        }
        else if (arg[0] == '-')
            throw UsageError(format("unknown flag `%1%`") % arg);
        else
            files.push_back(arg);
    }

    openDB();

    if (readStdin) {
        Expr e = evalStdin(state, parseOnly);
        printResult(state, e, evalOnly);
    }

    for (Strings::iterator it = files.begin();
         it != files.end(); it++)
    {
        Expr e = evalFile(state, absPath(*it));
        /* !!! parseOnly ignored */
        printResult(state, e, evalOnly);
    }

    printEvalStats(state);
}

string programId = "nix-instantiate";
<|endoftext|>


<commit_before>/*
 *  Copyright 2007-2012 The OpenMx Project
 *
 *  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.
 */

#define R_NO_REMAP
#include <R.h>
#include <Rinternals.h>

#include <sys/stat.h>
#include <errno.h>

#include "omxDefines.h"
#include "omxState.h"
#include "omxNPSOLSpecific.h"
#include "omxImportFrontendState.h"
#include "matrix.h"

Matrix result_csolnpEqBStartFun;
Matrix result_csolnpEqB;
Matrix result_ineqLB;
Matrix result_ineqUB;
Matrix result_ineqVal;
//double EMPTY = -999999.0;

void setupIneqLess(struct Matrix *bl_ineqless, struct Matrix *bu_ineqless, int size)
    {
        int index = 0;
        for(int offset = 0; offset < size; offset++) {
            bl_ineqless->t[index] = NEG_INF;
            bu_ineqless->t[index] = -0.0;
            index++;
        }
    }

void setupIneqGreater(struct Matrix *lb, struct Matrix *ub, int size)
{
        int index = 0;
        for(int offset = 0; offset < size; offset++) {
            lb->t[index] = 0.0;
            ub->t[index] = INF;
            printf("%2f", lb->t[index]); putchar('\n');
            printf("%2f", ub->t[index]); putchar('\n');
            index++;
        }
}

void setupEqB(struct Matrix *eqPointer, int size)
    {
        int index = 0;
        for(int offset = 0; offset < size; offset++) {
            eqPointer->t[index] = 0.0;
            index++;
        }
    }

void omxProcessConstraintsCsolnp(struct Matrix *lb_ineq, struct Matrix *ub_ineq, struct Matrix *eqb)  {
    if (globalState->numConstraints == 0){
        return;
    }

    int i;
    int size;
	double EMPTY = -999999.0;
    Matrix lb_ineqless = fill(1, 1, EMPTY);
    Matrix ub_ineqless = fill(1, 1, EMPTY);
    Matrix lb_ineqmore = fill(1, 1, EMPTY);
    Matrix ub_ineqmore = fill(1, 1, EMPTY);
    Matrix eqbound = fill(1, 1, EMPTY);
    Matrix ineq_lb = fill(1, 1, EMPTY);
    Matrix ineq_ub = fill(1, 1, EMPTY);
    Matrix myeqb = fill(1, 1, EMPTY);

	for(int constraintIndex = 0; constraintIndex < globalState->numConstraints; constraintIndex++) {

		size = globalState->conList[constraintIndex].size;

            if (globalState->conList[constraintIndex].opCode == 0)
            {
                Matrix lb_ineqless = fill(size, 1, EMPTY);
                Matrix ub_ineqless = fill(size, 1, EMPTY);
                setupIneqLess(&lb_ineqless, &ub_ineqless, size);
            }

            if (globalState->conList[constraintIndex].opCode == 1)
            {
                eqbound = fill(size, 1, EMPTY);
                setupEqB(&eqbound, size);
            }

            if (globalState->conList[constraintIndex].opCode == 2)
            {
                lb_ineqmore = fill(size, 1, EMPTY);
                ub_ineqmore = fill(size, 1, EMPTY);
                setupIneqGreater(&lb_ineqmore, &ub_ineqmore, size);
            }

        printf("lb_ineqmore is: \n");
        print(lb_ineqmore); putchar('\n');
        printf("ub_ineqmore is: \n");
        print(ub_ineqmore); putchar('\n');

        if (M(lb_ineqless, 0, 0) != EMPTY)
        {
            printf("inside lb_ineqless \n");
            ineq_lb = copy(ineq_lb, lb_ineqless);
            ineq_ub = copy(ineq_ub, ub_ineqless);
        }
        else if (M(lb_ineqmore, 0, 0) != EMPTY)
        {
            printf("inside lb_ineqmore \n");
            ineq_lb = copy(ineq_lb, lb_ineqmore);
            ineq_ub = copy(ineq_ub, ub_ineqmore);
        }
        else if (M(eqbound, 0, 0) != EMPTY)
        {
            printf("inside lb_eqb \n");
            myeqb = copy(myeqb, eqbound);
        }
    }

    if (ineq_lb.cols > 1)
    {
        ineq_lb = subset(ineq_lb, 0, 1, ineq_lb.cols - 1);
        ineq_ub = subset(ineq_ub, 0, 1, ineq_ub.cols - 1);
    }

    if (myeqb.cols > 1)
    {
        myeqb = subset(myeqb, 0, 1, myeqb.cols - 1);
    }

    for (i = 0; i < ineq_lb.cols; i++)
    {
        lb_ineq->t[i] = M(ineq_lb, i, 0);
        ub_ineq->t[i] = M(ineq_ub, i, 0);
        printf("pointer check \n");
        printf("%2f", lb_ineq->t[i]); putchar('\n');
        printf("%2f", ub_ineq->t[i]); putchar('\n');
    }
    printf("%d", myeqb.cols); putchar('\n');

    for (i = 0; i < myeqb.cols; i++)
    {
        eqb->t[i] = M(myeqb, i, 0);
        printf("%2f", eqb->t[i]); putchar('\n');
    }

    lb_ineq->cols = ineq_lb.cols;
    ub_ineq->cols = ineq_ub.cols;
    eqb->cols = myeqb.cols;
    //printf("eqb is: \n");
    //print(eqb); putchar('\n');

}
<commit_msg>Csolnp: some prints removed<commit_after>/*
 *  Copyright 2007-2012 The OpenMx Project
 *
 *  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.
 */

#define R_NO_REMAP
#include <R.h>
#include <Rinternals.h>

#include <sys/stat.h>
#include <errno.h>

#include "omxDefines.h"
#include "omxState.h"
#include "omxNPSOLSpecific.h"
#include "omxImportFrontendState.h"
#include "matrix.h"

Matrix result_csolnpEqBStartFun;
Matrix result_csolnpEqB;
Matrix result_ineqLB;
Matrix result_ineqUB;
Matrix result_ineqVal;
//double EMPTY = -999999.0;

void setupIneqLess(struct Matrix *bl_ineqless, struct Matrix *bu_ineqless, int size)
    {
        int index = 0;
        for(int offset = 0; offset < size; offset++) {
            bl_ineqless->t[index] = NEG_INF;
            bu_ineqless->t[index] = -0.0;
            index++;
        }
    }

void setupIneqGreater(struct Matrix *lb, struct Matrix *ub, int size)
{
        int index = 0;
        for(int offset = 0; offset < size; offset++) {
            lb->t[index] = 0.0;
            ub->t[index] = INF;
            index++;
        }
}

void setupEqB(struct Matrix *eqPointer, int size)
    {
        int index = 0;
        for(int offset = 0; offset < size; offset++) {
            eqPointer->t[index] = 0.0;
            index++;
        }
    }

void omxProcessConstraintsCsolnp(struct Matrix *lb_ineq, struct Matrix *ub_ineq, struct Matrix *eqb)  {
    if (globalState->numConstraints == 0){
        return;
    }

    int i;
    int size;
	double EMPTY = -999999.0;
    Matrix lb_ineqless = fill(1, 1, EMPTY);
    Matrix ub_ineqless = fill(1, 1, EMPTY);
    Matrix lb_ineqmore = fill(1, 1, EMPTY);
    Matrix ub_ineqmore = fill(1, 1, EMPTY);
    Matrix eqbound = fill(1, 1, EMPTY);
    Matrix ineq_lb = fill(1, 1, EMPTY);
    Matrix ineq_ub = fill(1, 1, EMPTY);
    Matrix myeqb = fill(1, 1, EMPTY);

	for(int constraintIndex = 0; constraintIndex < globalState->numConstraints; constraintIndex++) {

		size = globalState->conList[constraintIndex].size;

            if (globalState->conList[constraintIndex].opCode == 0)
            {
                Matrix lb_ineqless = fill(size, 1, EMPTY);
                Matrix ub_ineqless = fill(size, 1, EMPTY);
                setupIneqLess(&lb_ineqless, &ub_ineqless, size);
            }

            if (globalState->conList[constraintIndex].opCode == 1)
            {
                eqbound = fill(size, 1, EMPTY);
                setupEqB(&eqbound, size);
            }

            if (globalState->conList[constraintIndex].opCode == 2)
            {
                lb_ineqmore = fill(size, 1, EMPTY);
                ub_ineqmore = fill(size, 1, EMPTY);
                setupIneqGreater(&lb_ineqmore, &ub_ineqmore, size);
            }

        if (M(lb_ineqless, 0, 0) != EMPTY)
        {
            ineq_lb = copy(ineq_lb, lb_ineqless);
            ineq_ub = copy(ineq_ub, ub_ineqless);
        }
        else if (M(lb_ineqmore, 0, 0) != EMPTY)
        {
            ineq_lb = copy(ineq_lb, lb_ineqmore);
            ineq_ub = copy(ineq_ub, ub_ineqmore);
        }
        else if (M(eqbound, 0, 0) != EMPTY)
        {
            myeqb = copy(myeqb, eqbound);
        }
    }

    if (ineq_lb.cols > 1)
    {
        ineq_lb = subset(ineq_lb, 0, 1, ineq_lb.cols - 1);
        ineq_ub = subset(ineq_ub, 0, 1, ineq_ub.cols - 1);
    }

    if (myeqb.cols > 1)
    {
        myeqb = subset(myeqb, 0, 1, myeqb.cols - 1);
    }

    for (i = 0; i < ineq_lb.cols; i++)
    {
        lb_ineq->t[i] = M(ineq_lb, i, 0);
        ub_ineq->t[i] = M(ineq_ub, i, 0);
    }

    for (i = 0; i < myeqb.cols; i++)
    {
        eqb->t[i] = M(myeqb, i, 0);
    }

    lb_ineq->cols = ineq_lb.cols;
    ub_ineq->cols = ineq_ub.cols;
    eqb->cols = myeqb.cols;

}
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnord/util/binarymessagereader.h>
#include <cstable/CSTableReader.h>
#include <cstable/BooleanColumnReader.h>
#include <cstable/BitPackedIntColumnReader.h>
#include <cstable/UInt32ColumnReader.h>
#include <cstable/UInt64ColumnReader.h>
#include <cstable/LEB128ColumnReader.h>
#include <cstable/StringColumnReader.h>

namespace fnord {
namespace cstable {

CSTableReader::CSTableReader(
    const String& filename) :
    CSTableReader(
        new io::MmappedFile(File::openFile(filename, File::O_READ))) {}

CSTableReader::CSTableReader(const RefPtr<VFSFile> file) : file_(file) {
  util::BinaryMessageReader header(file_->data(), file_->size());
  auto magic = *header.readUInt32();
  if (magic != BinaryFormat::kMagicBytes) {
    RAISE(kIllegalStateError, "not a valid cstable");
  }

  auto version = *header.readUInt16();
  if (version != BinaryFormat::kVersion) {
    RAISEF(kIllegalStateError, "unsupported sstable version: $0", version);
  }

  //auto flags = *header.readUInt64();
  num_records_ = *header.readUInt64();
  num_columns_ = *header.readUInt32();

  for (int i = 0; i < num_columns_; ++i) {
    auto type = *header.readUInt32();
    auto name_len = *header.readUInt32();
    auto name_data = (char *) header.read(name_len);

    auto r_max = *header.readUInt32();
    auto d_max = *header.readUInt32();
    auto body_offset = *header.readUInt64();
    auto size = *header.readUInt64();

    ColumnInfo ci;
    ci.type = (ColumnType) type;
    ci.name = String(name_data, name_len);
    ci.body_offset = body_offset;
    ci.size = size;
    ci.r_max = r_max;
    ci.d_max = d_max;
    columns_.emplace(ci.name, ci);
  }
}

RefPtr<ColumnReader> CSTableReader::getColumnReader(const String& column_name) {
  auto col = columns_.find(column_name);
  if (col == columns_.end()) {
    RAISEF(kIndexError, "unknown column: $0", column_name);
  }

  const auto& c = col->second;
  void* cdata = ((char *) file_->data()) + col->second.body_offset;

  switch (c.type) {
    case ColumnType::BOOLEAN:
      return new BooleanColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::UINT32_BITPACKED:
      return new BitPackedIntColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::UINT32_PLAIN:
      return new UInt32ColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::UINT64_PLAIN:
      return new UInt64ColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::UINT64_LEB128:
      return new LEB128ColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::STRING_PLAIN:
      return new StringColumnReader(c.r_max, c.d_max, cdata, c.size);
  }

  RAISEF(kIllegalStateError, "invalid column type: $0", (uint32_t) c.type);
}

bool CSTableReader::hasColumn(const String& column_name) const {
  auto col = columns_.find(column_name);
  return col != columns_.end();
}

void CSTableReader::getColumn(
    const String& column_name,
    void** data,
    size_t* size) {
  auto col = columns_.find(column_name);
  if (col == columns_.end()) {
    RAISEF(kIndexError, "unknown column: $0", column_name);
  }

  *data = ((char *) file_->data()) + col->second.body_offset;
  *size = col->second.size;
}

size_t CSTableReader::numRecords() const {
  return num_records_;
}

} // namespace cstable
} // namespace fnord

<commit_msg>me stupid<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnord/util/binarymessagereader.h>
#include <cstable/CSTableReader.h>
#include <cstable/BooleanColumnReader.h>
#include <cstable/BitPackedIntColumnReader.h>
#include <cstable/UInt32ColumnReader.h>
#include <cstable/UInt64ColumnReader.h>
#include <cstable/LEB128ColumnReader.h>
#include <cstable/StringColumnReader.h>

namespace fnord {
namespace cstable {

CSTableReader::CSTableReader(
    const String& filename) :
    CSTableReader(
        new io::MmappedFile(File::openFile(filename, File::O_READ))) {}

CSTableReader::CSTableReader(const RefPtr<VFSFile> file) : file_(file) {
  util::BinaryMessageReader header(file_->data(), file_->size());
  auto magic = *header.readUInt32();
  if (magic != BinaryFormat::kMagicBytes) {
    RAISE(kIllegalStateError, "not a valid cstable");
  }

  auto version = *header.readUInt16();
  if (version != BinaryFormat::kVersion) {
    RAISEF(kIllegalStateError, "unsupported sstable version: $0", version);
  }

  auto flags = *header.readUInt64();
  num_records_ = *header.readUInt64();
  num_columns_ = *header.readUInt32();

  for (int i = 0; i < num_columns_; ++i) {
    auto type = *header.readUInt32();
    auto name_len = *header.readUInt32();
    auto name_data = (char *) header.read(name_len);

    auto r_max = *header.readUInt32();
    auto d_max = *header.readUInt32();
    auto body_offset = *header.readUInt64();
    auto size = *header.readUInt64();

    ColumnInfo ci;
    ci.type = (ColumnType) type;
    ci.name = String(name_data, name_len);
    ci.body_offset = body_offset;
    ci.size = size;
    ci.r_max = r_max;
    ci.d_max = d_max;
    columns_.emplace(ci.name, ci);
  }
}

RefPtr<ColumnReader> CSTableReader::getColumnReader(const String& column_name) {
  auto col = columns_.find(column_name);
  if (col == columns_.end()) {
    RAISEF(kIndexError, "unknown column: $0", column_name);
  }

  const auto& c = col->second;
  void* cdata = ((char *) file_->data()) + col->second.body_offset;

  switch (c.type) {
    case ColumnType::BOOLEAN:
      return new BooleanColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::UINT32_BITPACKED:
      return new BitPackedIntColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::UINT32_PLAIN:
      return new UInt32ColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::UINT64_PLAIN:
      return new UInt64ColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::UINT64_LEB128:
      return new LEB128ColumnReader(c.r_max, c.d_max, cdata, c.size);
    case ColumnType::STRING_PLAIN:
      return new StringColumnReader(c.r_max, c.d_max, cdata, c.size);
  }

  RAISEF(kIllegalStateError, "invalid column type: $0", (uint32_t) c.type);
}

bool CSTableReader::hasColumn(const String& column_name) const {
  auto col = columns_.find(column_name);
  return col != columns_.end();
}

void CSTableReader::getColumn(
    const String& column_name,
    void** data,
    size_t* size) {
  auto col = columns_.find(column_name);
  if (col == columns_.end()) {
    RAISEF(kIndexError, "unknown column: $0", column_name);
  }

  *data = ((char *) file_->data()) + col->second.body_offset;
  *size = col->second.size;
}

size_t CSTableReader::numRecords() const {
  return num_records_;
}

} // namespace cstable
} // namespace fnord

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * 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 "class_loader.h"
#include "class_linker.h"
#include "dex_file.h"
#include "logging.h"
#include "runtime.h"
#include "ScopedUtfChars.h"

#include "JniConstants.h" // Last to avoid problems with LOG redefinition.

namespace art {

namespace {

// A smart pointer that provides read-only access to a Java string's UTF chars.
// Unlike libcore's NullableScopedUtfChars, this will *not* throw NullPointerException if
// passed a null jstring. The correct idiom is:
//
//   NullableScopedUtfChars name(env, javaName);
//   if (env->ExceptionOccurred()) {
//       return NULL;
//   }
//   // ... use name.c_str()
//
// TODO: rewrite to get rid of this, or change ScopedUtfChars to offer this option.
class NullableScopedUtfChars {
public:
    NullableScopedUtfChars(JNIEnv* env, jstring s)
    : mEnv(env), mString(s)
    {
        mUtfChars = (s != NULL) ? env->GetStringUTFChars(s, NULL) : NULL;
    }

    ~NullableScopedUtfChars() {
        if (mUtfChars) {
            mEnv->ReleaseStringUTFChars(mString, mUtfChars);
        }
    }

    const char* c_str() const {
        return mUtfChars;
    }

    size_t size() const {
        return strlen(mUtfChars);
    }

    // Element access.
    const char& operator[](size_t n) const {
        return mUtfChars[n];
    }

private:
    JNIEnv* mEnv;
    jstring mString;
    const char* mUtfChars;

    // Disallow copy and assignment.
    NullableScopedUtfChars(const NullableScopedUtfChars&);
    void operator=(const NullableScopedUtfChars&);
};

static jint DexFile_openDexFile(JNIEnv* env, jclass, jstring javaSourceName, jstring javaOutputName) {
  ScopedUtfChars sourceName(env, javaSourceName);
  if (sourceName.c_str() == NULL) {
    return 0;
  }
  NullableScopedUtfChars outputName(env, javaOutputName);
  if (env->ExceptionOccurred()) {
    return 0;
  }
  const DexFile* dex_file = DexFile::Open(sourceName.c_str(), "");
  if (dex_file == NULL) {
    jniThrowExceptionFmt(env, "java/io/IOException", "unable to open DEX file: %s",
                         sourceName.c_str());
    return NULL;
  }
  return static_cast<jint>(reinterpret_cast<uintptr_t>(dex_file));
}

static const DexFile* toDexFile(JNIEnv* env, int dex_file_address) {
  const DexFile* dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(dex_file_address));
  if ((dex_file == NULL)) {
    jniThrowNullPointerException(env, "dex_file == null");
  }
  return dex_file;
}

void DexFile_closeDexFile(JNIEnv* env, jclass, jint cookie) {
  const DexFile* dex_file = toDexFile(env, cookie);
  if (dex_file == NULL) {
    return;
  }
  if (Runtime::Current()->GetClassLinker()->IsDexFileRegistered(*dex_file)) {
    return;
  }
  delete dex_file;
}

jclass DexFile_defineClass(JNIEnv* env, jclass, jstring javaName, jobject javaLoader, jint cookie) {
  const DexFile* dex_file = toDexFile(env, cookie);
  if (dex_file == NULL) {
    return NULL;
  }
  ScopedUtfChars class_name(env, javaName);
  if (class_name.c_str() == NULL) {
    return NULL;
  }
  const std::string descriptor = DotToDescriptor(class_name.c_str());
  const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
  if (dex_class_def == NULL) {
    jniThrowExceptionFmt(env, "java/lang/NoClassDefFoundError", "Class %s not found",
                         class_name.c_str());
    return NULL;
  }

  Object* class_loader_object = Decode<Object*>(env, javaLoader);
  ClassLoader* class_loader = down_cast<ClassLoader*>(class_loader_object);
  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
  class_linker->RegisterDexFile(*dex_file);
  Class* result = class_linker->DefineClass(descriptor, class_loader, *dex_file, *dex_class_def);
  return AddLocalReference<jclass>(env, result);
}

jobjectArray DexFile_getClassNameList(JNIEnv* env, jclass, jint cookie) {
  const DexFile* dex_file = toDexFile(env, cookie);
  if (dex_file == NULL) {
    return NULL;
  }
  UNIMPLEMENTED(ERROR);
  return NULL;
}

jboolean DexFile_isDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename) {
  // TODO: run dex2oat?
  UNIMPLEMENTED(WARNING);
  return JNI_FALSE;
}

static JNINativeMethod gMethods[] = {
  NATIVE_METHOD(DexFile, closeDexFile, "(I)V"),
  NATIVE_METHOD(DexFile, defineClass, "(Ljava/lang/String;Ljava/lang/ClassLoader;I)Ljava/lang/Class;"),
  NATIVE_METHOD(DexFile, getClassNameList, "(I)[Ljava/lang/String;"),
  NATIVE_METHOD(DexFile, isDexOptNeeded, "(Ljava/lang/String;)Z"),
  NATIVE_METHOD(DexFile, openDexFile, "(Ljava/lang/String;Ljava/lang/String;I)I"),
};

}  // namespace

void register_dalvik_system_DexFile(JNIEnv* env) {
  jniRegisterNativeMethods(env, "dalvik/system/DexFile", gMethods, NELEM(gMethods));
}

}  // namespace art
<commit_msg>Fixed DexFile.defineClass to return null, not throw Exception<commit_after>/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * 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 "class_loader.h"
#include "class_linker.h"
#include "dex_file.h"
#include "logging.h"
#include "runtime.h"
#include "ScopedUtfChars.h"

#include "JniConstants.h" // Last to avoid problems with LOG redefinition.

namespace art {

namespace {

// A smart pointer that provides read-only access to a Java string's UTF chars.
// Unlike libcore's NullableScopedUtfChars, this will *not* throw NullPointerException if
// passed a null jstring. The correct idiom is:
//
//   NullableScopedUtfChars name(env, javaName);
//   if (env->ExceptionOccurred()) {
//       return NULL;
//   }
//   // ... use name.c_str()
//
// TODO: rewrite to get rid of this, or change ScopedUtfChars to offer this option.
class NullableScopedUtfChars {
public:
    NullableScopedUtfChars(JNIEnv* env, jstring s)
    : mEnv(env), mString(s)
    {
        mUtfChars = (s != NULL) ? env->GetStringUTFChars(s, NULL) : NULL;
    }

    ~NullableScopedUtfChars() {
        if (mUtfChars) {
            mEnv->ReleaseStringUTFChars(mString, mUtfChars);
        }
    }

    const char* c_str() const {
        return mUtfChars;
    }

    size_t size() const {
        return strlen(mUtfChars);
    }

    // Element access.
    const char& operator[](size_t n) const {
        return mUtfChars[n];
    }

private:
    JNIEnv* mEnv;
    jstring mString;
    const char* mUtfChars;

    // Disallow copy and assignment.
    NullableScopedUtfChars(const NullableScopedUtfChars&);
    void operator=(const NullableScopedUtfChars&);
};

static jint DexFile_openDexFile(JNIEnv* env, jclass, jstring javaSourceName, jstring javaOutputName) {
  ScopedUtfChars sourceName(env, javaSourceName);
  if (sourceName.c_str() == NULL) {
    return 0;
  }
  NullableScopedUtfChars outputName(env, javaOutputName);
  if (env->ExceptionOccurred()) {
    return 0;
  }
  const DexFile* dex_file = DexFile::Open(sourceName.c_str(), "");
  if (dex_file == NULL) {
    jniThrowExceptionFmt(env, "java/io/IOException", "unable to open DEX file: %s",
                         sourceName.c_str());
    return NULL;
  }
  return static_cast<jint>(reinterpret_cast<uintptr_t>(dex_file));
}

static const DexFile* toDexFile(JNIEnv* env, int dex_file_address) {
  const DexFile* dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(dex_file_address));
  if ((dex_file == NULL)) {
    jniThrowNullPointerException(env, "dex_file == null");
  }
  return dex_file;
}

void DexFile_closeDexFile(JNIEnv* env, jclass, jint cookie) {
  const DexFile* dex_file = toDexFile(env, cookie);
  if (dex_file == NULL) {
    return;
  }
  if (Runtime::Current()->GetClassLinker()->IsDexFileRegistered(*dex_file)) {
    return;
  }
  delete dex_file;
}

jclass DexFile_defineClass(JNIEnv* env, jclass, jstring javaName, jobject javaLoader, jint cookie) {
  const DexFile* dex_file = toDexFile(env, cookie);
  if (dex_file == NULL) {
    return NULL;
  }
  ScopedUtfChars class_name(env, javaName);
  if (class_name.c_str() == NULL) {
    return NULL;
  }
  const std::string descriptor = DotToDescriptor(class_name.c_str());
  const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
  if (dex_class_def == NULL) {
    return NULL;
  }

  Object* class_loader_object = Decode<Object*>(env, javaLoader);
  ClassLoader* class_loader = down_cast<ClassLoader*>(class_loader_object);
  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
  class_linker->RegisterDexFile(*dex_file);
  Class* result = class_linker->DefineClass(descriptor, class_loader, *dex_file, *dex_class_def);
  if (env->ExceptionCheck()) {
    env->ExceptionClear();
    return NULL;
  }
  return AddLocalReference<jclass>(env, result);
}

jobjectArray DexFile_getClassNameList(JNIEnv* env, jclass, jint cookie) {
  const DexFile* dex_file = toDexFile(env, cookie);
  if (dex_file == NULL) {
    return NULL;
  }
  UNIMPLEMENTED(ERROR);
  return NULL;
}

jboolean DexFile_isDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename) {
  // TODO: run dex2oat?
  UNIMPLEMENTED(WARNING);
  return JNI_FALSE;
}

static JNINativeMethod gMethods[] = {
  NATIVE_METHOD(DexFile, closeDexFile, "(I)V"),
  NATIVE_METHOD(DexFile, defineClass, "(Ljava/lang/String;Ljava/lang/ClassLoader;I)Ljava/lang/Class;"),
  NATIVE_METHOD(DexFile, getClassNameList, "(I)[Ljava/lang/String;"),
  NATIVE_METHOD(DexFile, isDexOptNeeded, "(Ljava/lang/String;)Z"),
  NATIVE_METHOD(DexFile, openDexFile, "(Ljava/lang/String;Ljava/lang/String;I)I"),
};

}  // namespace

void register_dalvik_system_DexFile(JNIEnv* env) {
  jniRegisterNativeMethods(env, "dalvik/system/DexFile", gMethods, NELEM(gMethods));
}

}  // namespace art
<|endoftext|>


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

#include <algorithm>

using namespace osg;
using namespace std;

DisplaySettings* DisplaySettings::instance()
{
    static ref_ptr<DisplaySettings> s_displaySettings = new DisplaySettings;
    return s_displaySettings.get();
}

DisplaySettings::DisplaySettings(const DisplaySettings& vs):Referenced()
{
    copy(vs);
}

DisplaySettings::~DisplaySettings()
{
}

 DisplaySettings& DisplaySettings::operator = (const DisplaySettings& vs)
{
    if (this==&vs) return *this;
    copy(vs);
    return *this;
}

void DisplaySettings::copy(const DisplaySettings& vs)
{
    _displayType = vs._displayType;
    _stereoMode = vs._stereoMode;
    _eyeSeparation = vs._eyeSeparation;
    _screenWidth = vs._screenWidth;
    _screenHeight = vs._screenHeight;
    _screenDistance = vs._screenDistance;

    _splitStereoHorizontalEyeMapping = vs._splitStereoHorizontalEyeMapping;
    _splitStereoHorizontalSeparation = vs._splitStereoHorizontalSeparation;

    _splitStereoVerticalEyeMapping = vs._splitStereoVerticalEyeMapping;
    _splitStereoVerticalSeparation = vs._splitStereoVerticalSeparation;

    _splitStereoAutoAdjustAspectRatio = vs._splitStereoAutoAdjustAspectRatio;

    _doubleBuffer = vs._doubleBuffer;
    _RGB = vs._RGB;
    _depthBuffer = vs._depthBuffer;
    _minimumNumberAlphaBits = vs._minimumNumberAlphaBits;
    _minimumNumberStencilBits = vs._minimumNumberStencilBits;

    _maxNumOfGraphicsContexts = vs._maxNumOfGraphicsContexts;
}

void DisplaySettings::merge(const DisplaySettings& vs)
{
    if (_stereo       || vs._stereo)        _stereo = true;

    // need to think what to do about merging the stereo mode.

    if (_doubleBuffer || vs._doubleBuffer)  _doubleBuffer = true;
    if (_RGB          || vs._RGB)           _RGB = true;
    if (_depthBuffer  || vs._depthBuffer)   _depthBuffer = true;

    if (vs._minimumNumberAlphaBits>_minimumNumberAlphaBits) _minimumNumberAlphaBits = vs._minimumNumberAlphaBits;
    if (vs._minimumNumberStencilBits>_minimumNumberStencilBits) _minimumNumberStencilBits = vs._minimumNumberStencilBits;
}

void DisplaySettings::setDefaults()
{
    _displayType = MONITOR;

    _stereo = false;
    _stereoMode = ANAGLYPHIC;
    _eyeSeparation = 0.05f;
    _screenWidth = 0.325f;
    _screenHeight = 0.26f;
    _screenDistance = 0.5f;

    _splitStereoHorizontalEyeMapping = LEFT_EYE_LEFT_VIEWPORT;
    _splitStereoHorizontalSeparation = 0;

    _splitStereoVerticalEyeMapping = LEFT_EYE_TOP_VIEWPORT;
    _splitStereoVerticalSeparation = 0;

    _splitStereoAutoAdjustAspectRatio = true;

    _doubleBuffer = true;
    _RGB = true;
    _depthBuffer = true;
    _minimumNumberAlphaBits = 0;
    _minimumNumberStencilBits = 0;

    _maxNumOfGraphicsContexts = 3;
}

static ApplicationUsageProxy DisplaySetting_e0(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_DISPLAY_TYPE <type>","MONITOR | POWERWALL | REALITY_CENTER | HEAD_MOUNTED_DISPLAY");
static ApplicationUsageProxy DisplaySetting_e1(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_STEREO_MODE <mode>","QUAD_BUFFER | ANAGLYPHIC | HORIZONTAL_SPLIT | VERTICAL_SPLIT | LEFT_EYE | RIGHT_EYE");
static ApplicationUsageProxy DisplaySetting_e2(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_STEREO <mode>","OFF | ON");
static ApplicationUsageProxy DisplaySetting_e3(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_EYE_SEPARATION <float>","physical distance between eyes");
static ApplicationUsageProxy DisplaySetting_e4(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SCREEN_DISTANCE <float>","physical distance between eyes and screen");
static ApplicationUsageProxy DisplaySetting_e5(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SCREEN_HEIGHT <float>","physical screen height");
static ApplicationUsageProxy DisplaySetting_e6(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_HORIZONTAL_EYE_MAPPING <mode>","LEFT_EYE_LEFT_VIEWPORT | LEFT_EYE_RIGHT_VIEWPORT");
static ApplicationUsageProxy DisplaySetting_e7(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_HORIZONTAL_SEPARATION <float>","number of pixels between viewports");
static ApplicationUsageProxy DisplaySetting_e8(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_VERTICAL_EYE_MAPPING <mode>","LEFT_EYE_TOP_VIEWPORT | LEFT_EYE_BOTTOM_VIEWPORT");
static ApplicationUsageProxy DisplaySetting_e9(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_AUTO_ADJUST_ASPECT_RATIO <mode>","OFF | ON  Default to ON to compenstate for the compression of the aspect ratio when viewing in split screen stereo.  Note, if you are setting fovx and fovy explicityly OFF should be used.");
static ApplicationUsageProxy DisplaySetting_e10(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_VERTICAL_SEPARATION <float>","number of pixels between viewports");
static ApplicationUsageProxy DisplaySetting_e11(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_MAX_NUMBER_OF_GRAPHICS_CONTEXTS <int>","maximum number of graphics contexts to be used with applications.");

void DisplaySettings::readEnvironmentalVariables()
{
    char *ptr;

    if ((ptr = getenv("OSG_DISPLAY_TYPE")) != 0)
    {
        if (strcmp(ptr,"MONITOR")==0)
        {
            _displayType = MONITOR;
        }
        else
        if (strcmp(ptr,"POWERWALL")==0)
        {
            _displayType = POWERWALL;
        }
        else
        if (strcmp(ptr,"REALITY_CENTER")==0)
        {
            _displayType = REALITY_CENTER;
        }
        else
        if (strcmp(ptr,"HEAD_MOUNTED_DISPLAY")==0)
        {
            _displayType = HEAD_MOUNTED_DISPLAY;
        }
    }

    if( (ptr = getenv("OSG_STEREO_MODE")) != 0)
    {
        if (strcmp(ptr,"QUAD_BUFFER")==0)
        {
            _stereoMode = QUAD_BUFFER;
        }
        else
        if (strcmp(ptr,"ANAGLYPHIC")==0)
        {
            _stereoMode = ANAGLYPHIC;
        }
        else
        if (strcmp(ptr,"HORIZONTAL_SPLIT")==0)
        {
            _stereoMode = HORIZONTAL_SPLIT;
        }
        else
        if (strcmp(ptr,"VERTICAL_SPLIT")==0)
        {
            _stereoMode = VERTICAL_SPLIT;
        }
        else
        if (strcmp(ptr,"LEFT_EYE")==0)
        {
            _stereoMode = LEFT_EYE;
        }
        else
        if (strcmp(ptr,"RIGHT_EYE")==0)
        {
            _stereoMode = RIGHT_EYE;
        }
    }

    if( (ptr = getenv("OSG_STEREO")) != 0)
    {
        if (strcmp(ptr,"OFF")==0)
        {
            _stereo = false;
        }
        else
        if (strcmp(ptr,"ON")==0)
        {
            _stereo = true;
        }
    }

    if( (ptr = getenv("OSG_EYE_SEPARATION")) != 0)
    {
        _eyeSeparation = atof(ptr);
    }

    if( (ptr = getenv("OSG_SCREEN_WIDTH")) != 0)
    {
        _screenWidth = atof(ptr);
    }

    if( (ptr = getenv("OSG_SCREEN_HEIGHT")) != 0)
    {
        _screenHeight = atof(ptr);
    }

    if( (ptr = getenv("OSG_SCREEN_DISTANCE")) != 0)
    {
        _screenDistance = atof(ptr);
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_HORIZONTAL_EYE_MAPPING")) != 0)
    {
        if (strcmp(ptr,"LEFT_EYE_LEFT_VIEWPORT")==0)
        {
            _splitStereoHorizontalEyeMapping = LEFT_EYE_LEFT_VIEWPORT;
        }
        else
        if (strcmp(ptr,"LEFT_EYE_RIGHT_VIEWPORT")==0)
        {
            _splitStereoHorizontalEyeMapping = LEFT_EYE_RIGHT_VIEWPORT;
        }
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_HORIZONTAL_SEPARATION")) != 0)
    {
        _splitStereoHorizontalSeparation = atoi(ptr);
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_VERTICAL_EYE_MAPPING")) != 0)
    {
        if (strcmp(ptr,"LEFT_EYE_TOP_VIEWPORT")==0)
        {
            _splitStereoVerticalEyeMapping = LEFT_EYE_TOP_VIEWPORT;
        }
        else
        if (strcmp(ptr,"LEFT_EYE_BOTTOM_VIEWPORT")==0)
        {
            _splitStereoVerticalEyeMapping = LEFT_EYE_BOTTOM_VIEWPORT;
        }
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_AUTO_ADJUST_ASPECT_RATIO")) != 0)
    {
        if (strcmp(ptr,"OFF")==0)
        {
            _stereo = false;
        }
        else
        if (strcmp(ptr,"ON")==0)
        {
            _stereo = true;
        }
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_VERTICAL_SEPARATION")) != 0)
    {
        _splitStereoVerticalSeparation = atoi(ptr);
    }

    if( (ptr = getenv("OSG_MAX_NUMBER_OF_GRAPHICS_CONTEXTS")) != 0)
    {
        _maxNumOfGraphicsContexts = atoi(ptr);
    }
}

void DisplaySettings::readCommandLine(ArgumentParser& arguments)
{

    // report the usage options.
    if (arguments.getApplicationUsage())
    {
        arguments.getApplicationUsage()->addCommandLineOption("--display <type>","MONITOR | POWERWALL | REALITY_CENTER | HEAD_MOUNTED_DISPLAY");
        arguments.getApplicationUsage()->addCommandLineOption("--stereo","Use default stereo mode which is ANAGLYPHIC if not overriden by environmental variable");
        arguments.getApplicationUsage()->addCommandLineOption("--stereo <mode>","ANAGLYPHIC | QUAD_BUFFER | HORIZONTAL_SPLIT | VERTICAL_SPLIT | LEFT_EYE | RIGHT_EYE | ON | OFF ");
        arguments.getApplicationUsage()->addCommandLineOption("--rgba","Request a RGBA color buffer visual");
        arguments.getApplicationUsage()->addCommandLineOption("--stencil","Request a stencil buffer visual");
    }

    std::string str;
    while(arguments.read("--display",str))
    {
        if (str=="MONITOR") _displayType = MONITOR;
        else if (str=="POWERWALL") _displayType = POWERWALL;
        else if (str=="REALITY_CENTER") _displayType = REALITY_CENTER;
        else if (str=="HEAD_MOUNTED_DISPLAY") _displayType = HEAD_MOUNTED_DISPLAY;
    }

    int pos;
    while ((pos=arguments.find("--stereo"))!=0)
    {
        if (arguments.match(pos+1,"ANAGLYPHIC"))            { arguments.remove(pos,2); _stereo = true;_stereoMode = ANAGLYPHIC; }
        else if (arguments.match(pos+1,"QUAD_BUFFER"))      { arguments.remove(pos,2); _stereo = true;_stereoMode = QUAD_BUFFER; }
        else if (arguments.match(pos+1,"HORIZONTAL_SPLIT")) { arguments.remove(pos,2); _stereo = true;_stereoMode = HORIZONTAL_SPLIT; }
        else if (arguments.match(pos+1,"VERTICAL_SPLIT"))   { arguments.remove(pos,2); _stereo = true;_stereoMode = VERTICAL_SPLIT; }
        else if (arguments.match(pos+1,"LEFT_EYE"))         { arguments.remove(pos,2); _stereo = true;_stereoMode = LEFT_EYE; }
        else if (arguments.match(pos+1,"RIGHT_EYE"))        { arguments.remove(pos,2); _stereo = true;_stereoMode = RIGHT_EYE; }
        else if (arguments.match(pos+1,"ON"))               { arguments.remove(pos,2); _stereo = true; }
        else if (arguments.match(pos+1,"OFF"))              { arguments.remove(pos,2); _stereo = false; }
        else                                                { arguments.remove(pos); _stereo = true; }
    }

    while (arguments.read("--rgba"))
    {
        _RGB = true;
        _minimumNumberAlphaBits = 1;
    }

    while (arguments.read("--stencil"))
    {
        _minimumNumberStencilBits = 1;
    }
}
<commit_msg>Fixed setting of OSG_SPLIT_STEREO_AUTO_ADJUST_ASPECT_RATIO value.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/
#include <osg/DisplaySettings>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/ref_ptr>

#include <algorithm>

using namespace osg;
using namespace std;

DisplaySettings* DisplaySettings::instance()
{
    static ref_ptr<DisplaySettings> s_displaySettings = new DisplaySettings;
    return s_displaySettings.get();
}

DisplaySettings::DisplaySettings(const DisplaySettings& vs):Referenced()
{
    copy(vs);
}

DisplaySettings::~DisplaySettings()
{
}

 DisplaySettings& DisplaySettings::operator = (const DisplaySettings& vs)
{
    if (this==&vs) return *this;
    copy(vs);
    return *this;
}

void DisplaySettings::copy(const DisplaySettings& vs)
{
    _displayType = vs._displayType;
    _stereoMode = vs._stereoMode;
    _eyeSeparation = vs._eyeSeparation;
    _screenWidth = vs._screenWidth;
    _screenHeight = vs._screenHeight;
    _screenDistance = vs._screenDistance;

    _splitStereoHorizontalEyeMapping = vs._splitStereoHorizontalEyeMapping;
    _splitStereoHorizontalSeparation = vs._splitStereoHorizontalSeparation;

    _splitStereoVerticalEyeMapping = vs._splitStereoVerticalEyeMapping;
    _splitStereoVerticalSeparation = vs._splitStereoVerticalSeparation;

    _splitStereoAutoAdjustAspectRatio = vs._splitStereoAutoAdjustAspectRatio;

    _doubleBuffer = vs._doubleBuffer;
    _RGB = vs._RGB;
    _depthBuffer = vs._depthBuffer;
    _minimumNumberAlphaBits = vs._minimumNumberAlphaBits;
    _minimumNumberStencilBits = vs._minimumNumberStencilBits;

    _maxNumOfGraphicsContexts = vs._maxNumOfGraphicsContexts;
}

void DisplaySettings::merge(const DisplaySettings& vs)
{
    if (_stereo       || vs._stereo)        _stereo = true;

    // need to think what to do about merging the stereo mode.

    if (_doubleBuffer || vs._doubleBuffer)  _doubleBuffer = true;
    if (_RGB          || vs._RGB)           _RGB = true;
    if (_depthBuffer  || vs._depthBuffer)   _depthBuffer = true;

    if (vs._minimumNumberAlphaBits>_minimumNumberAlphaBits) _minimumNumberAlphaBits = vs._minimumNumberAlphaBits;
    if (vs._minimumNumberStencilBits>_minimumNumberStencilBits) _minimumNumberStencilBits = vs._minimumNumberStencilBits;
}

void DisplaySettings::setDefaults()
{
    _displayType = MONITOR;

    _stereo = false;
    _stereoMode = ANAGLYPHIC;
    _eyeSeparation = 0.05f;
    _screenWidth = 0.325f;
    _screenHeight = 0.26f;
    _screenDistance = 0.5f;

    _splitStereoHorizontalEyeMapping = LEFT_EYE_LEFT_VIEWPORT;
    _splitStereoHorizontalSeparation = 0;

    _splitStereoVerticalEyeMapping = LEFT_EYE_TOP_VIEWPORT;
    _splitStereoVerticalSeparation = 0;

    _splitStereoAutoAdjustAspectRatio = true;

    _doubleBuffer = true;
    _RGB = true;
    _depthBuffer = true;
    _minimumNumberAlphaBits = 0;
    _minimumNumberStencilBits = 0;

    _maxNumOfGraphicsContexts = 3;
}

static ApplicationUsageProxy DisplaySetting_e0(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_DISPLAY_TYPE <type>","MONITOR | POWERWALL | REALITY_CENTER | HEAD_MOUNTED_DISPLAY");
static ApplicationUsageProxy DisplaySetting_e1(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_STEREO_MODE <mode>","QUAD_BUFFER | ANAGLYPHIC | HORIZONTAL_SPLIT | VERTICAL_SPLIT | LEFT_EYE | RIGHT_EYE");
static ApplicationUsageProxy DisplaySetting_e2(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_STEREO <mode>","OFF | ON");
static ApplicationUsageProxy DisplaySetting_e3(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_EYE_SEPARATION <float>","physical distance between eyes");
static ApplicationUsageProxy DisplaySetting_e4(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SCREEN_DISTANCE <float>","physical distance between eyes and screen");
static ApplicationUsageProxy DisplaySetting_e5(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SCREEN_HEIGHT <float>","physical screen height");
static ApplicationUsageProxy DisplaySetting_e6(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_HORIZONTAL_EYE_MAPPING <mode>","LEFT_EYE_LEFT_VIEWPORT | LEFT_EYE_RIGHT_VIEWPORT");
static ApplicationUsageProxy DisplaySetting_e7(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_HORIZONTAL_SEPARATION <float>","number of pixels between viewports");
static ApplicationUsageProxy DisplaySetting_e8(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_VERTICAL_EYE_MAPPING <mode>","LEFT_EYE_TOP_VIEWPORT | LEFT_EYE_BOTTOM_VIEWPORT");
static ApplicationUsageProxy DisplaySetting_e9(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_AUTO_ADJUST_ASPECT_RATIO <mode>","OFF | ON  Default to ON to compenstate for the compression of the aspect ratio when viewing in split screen stereo.  Note, if you are setting fovx and fovy explicityly OFF should be used.");
static ApplicationUsageProxy DisplaySetting_e10(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_SPLIT_STEREO_VERTICAL_SEPARATION <float>","number of pixels between viewports");
static ApplicationUsageProxy DisplaySetting_e11(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_MAX_NUMBER_OF_GRAPHICS_CONTEXTS <int>","maximum number of graphics contexts to be used with applications.");

void DisplaySettings::readEnvironmentalVariables()
{
    char *ptr;

    if ((ptr = getenv("OSG_DISPLAY_TYPE")) != 0)
    {
        if (strcmp(ptr,"MONITOR")==0)
        {
            _displayType = MONITOR;
        }
        else
        if (strcmp(ptr,"POWERWALL")==0)
        {
            _displayType = POWERWALL;
        }
        else
        if (strcmp(ptr,"REALITY_CENTER")==0)
        {
            _displayType = REALITY_CENTER;
        }
        else
        if (strcmp(ptr,"HEAD_MOUNTED_DISPLAY")==0)
        {
            _displayType = HEAD_MOUNTED_DISPLAY;
        }
    }

    if( (ptr = getenv("OSG_STEREO_MODE")) != 0)
    {
        if (strcmp(ptr,"QUAD_BUFFER")==0)
        {
            _stereoMode = QUAD_BUFFER;
        }
        else
        if (strcmp(ptr,"ANAGLYPHIC")==0)
        {
            _stereoMode = ANAGLYPHIC;
        }
        else
        if (strcmp(ptr,"HORIZONTAL_SPLIT")==0)
        {
            _stereoMode = HORIZONTAL_SPLIT;
        }
        else
        if (strcmp(ptr,"VERTICAL_SPLIT")==0)
        {
            _stereoMode = VERTICAL_SPLIT;
        }
        else
        if (strcmp(ptr,"LEFT_EYE")==0)
        {
            _stereoMode = LEFT_EYE;
        }
        else
        if (strcmp(ptr,"RIGHT_EYE")==0)
        {
            _stereoMode = RIGHT_EYE;
        }
    }

    if( (ptr = getenv("OSG_STEREO")) != 0)
    {
        if (strcmp(ptr,"OFF")==0)
        {
            _stereo = false;
        }
        else
        if (strcmp(ptr,"ON")==0)
        {
            _stereo = true;
        }
    }

    if( (ptr = getenv("OSG_EYE_SEPARATION")) != 0)
    {
        _eyeSeparation = atof(ptr);
    }

    if( (ptr = getenv("OSG_SCREEN_WIDTH")) != 0)
    {
        _screenWidth = atof(ptr);
    }

    if( (ptr = getenv("OSG_SCREEN_HEIGHT")) != 0)
    {
        _screenHeight = atof(ptr);
    }

    if( (ptr = getenv("OSG_SCREEN_DISTANCE")) != 0)
    {
        _screenDistance = atof(ptr);
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_HORIZONTAL_EYE_MAPPING")) != 0)
    {
        if (strcmp(ptr,"LEFT_EYE_LEFT_VIEWPORT")==0)
        {
            _splitStereoHorizontalEyeMapping = LEFT_EYE_LEFT_VIEWPORT;
        }
        else
        if (strcmp(ptr,"LEFT_EYE_RIGHT_VIEWPORT")==0)
        {
            _splitStereoHorizontalEyeMapping = LEFT_EYE_RIGHT_VIEWPORT;
        }
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_HORIZONTAL_SEPARATION")) != 0)
    {
        _splitStereoHorizontalSeparation = atoi(ptr);
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_VERTICAL_EYE_MAPPING")) != 0)
    {
        if (strcmp(ptr,"LEFT_EYE_TOP_VIEWPORT")==0)
        {
            _splitStereoVerticalEyeMapping = LEFT_EYE_TOP_VIEWPORT;
        }
        else
        if (strcmp(ptr,"LEFT_EYE_BOTTOM_VIEWPORT")==0)
        {
            _splitStereoVerticalEyeMapping = LEFT_EYE_BOTTOM_VIEWPORT;
        }
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_AUTO_ADJUST_ASPECT_RATIO")) != 0)
    {
        if (strcmp(ptr,"OFF")==0)
        {
            _splitStereoAutoAdjustAspectRatio = false;
        }
        else
        if (strcmp(ptr,"ON")==0)
        {
            _splitStereoAutoAdjustAspectRatio = true;
        }
    }

    if( (ptr = getenv("OSG_SPLIT_STEREO_VERTICAL_SEPARATION")) != 0)
    {
        _splitStereoVerticalSeparation = atoi(ptr);
    }

    if( (ptr = getenv("OSG_MAX_NUMBER_OF_GRAPHICS_CONTEXTS")) != 0)
    {
        _maxNumOfGraphicsContexts = atoi(ptr);
    }
}

void DisplaySettings::readCommandLine(ArgumentParser& arguments)
{

    // report the usage options.
    if (arguments.getApplicationUsage())
    {
        arguments.getApplicationUsage()->addCommandLineOption("--display <type>","MONITOR | POWERWALL | REALITY_CENTER | HEAD_MOUNTED_DISPLAY");
        arguments.getApplicationUsage()->addCommandLineOption("--stereo","Use default stereo mode which is ANAGLYPHIC if not overriden by environmental variable");
        arguments.getApplicationUsage()->addCommandLineOption("--stereo <mode>","ANAGLYPHIC | QUAD_BUFFER | HORIZONTAL_SPLIT | VERTICAL_SPLIT | LEFT_EYE | RIGHT_EYE | ON | OFF ");
        arguments.getApplicationUsage()->addCommandLineOption("--rgba","Request a RGBA color buffer visual");
        arguments.getApplicationUsage()->addCommandLineOption("--stencil","Request a stencil buffer visual");
    }

    std::string str;
    while(arguments.read("--display",str))
    {
        if (str=="MONITOR") _displayType = MONITOR;
        else if (str=="POWERWALL") _displayType = POWERWALL;
        else if (str=="REALITY_CENTER") _displayType = REALITY_CENTER;
        else if (str=="HEAD_MOUNTED_DISPLAY") _displayType = HEAD_MOUNTED_DISPLAY;
    }

    int pos;
    while ((pos=arguments.find("--stereo"))!=0)
    {
        if (arguments.match(pos+1,"ANAGLYPHIC"))            { arguments.remove(pos,2); _stereo = true;_stereoMode = ANAGLYPHIC; }
        else if (arguments.match(pos+1,"QUAD_BUFFER"))      { arguments.remove(pos,2); _stereo = true;_stereoMode = QUAD_BUFFER; }
        else if (arguments.match(pos+1,"HORIZONTAL_SPLIT")) { arguments.remove(pos,2); _stereo = true;_stereoMode = HORIZONTAL_SPLIT; }
        else if (arguments.match(pos+1,"VERTICAL_SPLIT"))   { arguments.remove(pos,2); _stereo = true;_stereoMode = VERTICAL_SPLIT; }
        else if (arguments.match(pos+1,"LEFT_EYE"))         { arguments.remove(pos,2); _stereo = true;_stereoMode = LEFT_EYE; }
        else if (arguments.match(pos+1,"RIGHT_EYE"))        { arguments.remove(pos,2); _stereo = true;_stereoMode = RIGHT_EYE; }
        else if (arguments.match(pos+1,"ON"))               { arguments.remove(pos,2); _stereo = true; }
        else if (arguments.match(pos+1,"OFF"))              { arguments.remove(pos,2); _stereo = false; }
        else                                                { arguments.remove(pos); _stereo = true; }
    }

    while (arguments.read("--rgba"))
    {
        _RGB = true;
        _minimumNumberAlphaBits = 1;
    }

    while (arguments.read("--stencil"))
    {
        _minimumNumberStencilBits = 1;
    }
}
<|endoftext|>


<commit_before>/*
 * This helper library glues delegate_glue and http_response_handler
 * together.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "HttpRequest.hxx"
#include "Handler.hxx"
#include "Glue.hxx"
#include "static_headers.hxx"
#include "http_response.hxx"
#include "strmap.hxx"
#include "istream/istream.hxx"
#include "istream/istream_file.hxx"
#include "gerrno.h"
#include "pool.hxx"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

struct delegate_get {
    struct pool *pool;
    const char *path;
    const char *content_type;
    struct http_response_handler_ref handler;
};

/*
 * delegate_handler
 *
 */

static void
delegate_get_callback(int fd, void *ctx)
{
    struct delegate_get *get = (struct delegate_get *)ctx;

    struct stat st;
    if (fstat(fd, &st) < 0) {
        GError *error = new_error_errno();
        g_prefix_error(&error, "Failed to stat %s: ", get->path);
        get->handler.InvokeAbort(error);
        return;
    }

    if (!S_ISREG(st.st_mode)) {
        close(fd);
        get->handler.InvokeMessage(*get->pool, HTTP_STATUS_NOT_FOUND,
                                   "Not a regular file");
        return;
    }

    /* XXX handle if-modified-since, ... */

    struct strmap *headers = strmap_new(get->pool);
    static_response_headers(get->pool, headers, fd, &st, get->content_type);

    struct istream *body = istream_file_fd_new(get->pool, get->path,
                                               fd, FdType::FD_FILE,
                                               st.st_size);
    get->handler.InvokeResponse(HTTP_STATUS_OK, headers, body);
}

static void
delegate_get_error(GError *error, void *ctx)
{
    struct delegate_get *get = (struct delegate_get *)ctx;

    get->handler.InvokeAbort(error);
}

static const struct delegate_handler delegate_get_handler = {
    .success = delegate_get_callback,
    .error = delegate_get_error,
};

/*
 * public
 *
 */

void
delegate_stock_request(StockMap *stock, struct pool *pool,
                       const char *helper,
                       const ChildOptions &options,
                       const char *path, const char *content_type,
                       const struct http_response_handler *handler, void *ctx,
                       struct async_operation_ref &async_ref)
{
    auto get = NewFromPool<struct delegate_get>(*pool);

    get->pool = pool;
    get->path = path;
    get->content_type = content_type;
    get->handler.Set(*handler, ctx);

    delegate_stock_open(stock, pool,
                        helper, options, path,
                        &delegate_get_handler, get,
                        async_ref);
}
<commit_msg>delegate/HttpRequest: rename struct with CamelCase<commit_after>/*
 * This helper library glues delegate_glue and http_response_handler
 * together.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "HttpRequest.hxx"
#include "Handler.hxx"
#include "Glue.hxx"
#include "static_headers.hxx"
#include "http_response.hxx"
#include "strmap.hxx"
#include "istream/istream.hxx"
#include "istream/istream_file.hxx"
#include "gerrno.h"
#include "pool.hxx"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

struct DelegateHttpRequest {
    struct pool *pool;
    const char *path;
    const char *content_type;
    struct http_response_handler_ref handler;
};

/*
 * delegate_handler
 *
 */

static void
delegate_get_callback(int fd, void *ctx)
{
    DelegateHttpRequest *get = (DelegateHttpRequest *)ctx;

    struct stat st;
    if (fstat(fd, &st) < 0) {
        GError *error = new_error_errno();
        g_prefix_error(&error, "Failed to stat %s: ", get->path);
        get->handler.InvokeAbort(error);
        return;
    }

    if (!S_ISREG(st.st_mode)) {
        close(fd);
        get->handler.InvokeMessage(*get->pool, HTTP_STATUS_NOT_FOUND,
                                   "Not a regular file");
        return;
    }

    /* XXX handle if-modified-since, ... */

    struct strmap *headers = strmap_new(get->pool);
    static_response_headers(get->pool, headers, fd, &st, get->content_type);

    struct istream *body = istream_file_fd_new(get->pool, get->path,
                                               fd, FdType::FD_FILE,
                                               st.st_size);
    get->handler.InvokeResponse(HTTP_STATUS_OK, headers, body);
}

static void
delegate_get_error(GError *error, void *ctx)
{
    DelegateHttpRequest *get = (DelegateHttpRequest *)ctx;

    get->handler.InvokeAbort(error);
}

static const struct delegate_handler delegate_get_handler = {
    .success = delegate_get_callback,
    .error = delegate_get_error,
};

/*
 * public
 *
 */

void
delegate_stock_request(StockMap *stock, struct pool *pool,
                       const char *helper,
                       const ChildOptions &options,
                       const char *path, const char *content_type,
                       const struct http_response_handler *handler, void *ctx,
                       struct async_operation_ref &async_ref)
{
    auto get = NewFromPool<DelegateHttpRequest>(*pool);

    get->pool = pool;
    get->path = path;
    get->content_type = content_type;
    get->handler.Set(*handler, ctx);

    delegate_stock_open(stock, pool,
                        helper, options, path,
                        &delegate_get_handler, get,
                        async_ref);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011-2017 Blender Foundation
 *
 * 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 "device/device_memory.h"
#include "device/device.h"

CCL_NAMESPACE_BEGIN

/* Device Memory */

device_memory::device_memory(Device *device, const char *name, MemoryType type)
    : data_type(device_type_traits<uchar>::data_type),
      data_elements(device_type_traits<uchar>::num_elements),
      data_size(0),
      device_size(0),
      data_width(0),
      data_height(0),
      data_depth(0),
      type(type),
      name(name),
      device(device),
      device_pointer(0),
      host_pointer(0),
      shared_pointer(0),
      shared_counter(0)
{
}

device_memory::~device_memory()
{
  assert(shared_pointer == 0);
  assert(shared_counter == 0);
}

void *device_memory::host_alloc(size_t size)
{
  if (!size) {
    return 0;
  }

  void *ptr = util_aligned_malloc(size, MIN_ALIGNMENT_CPU_DATA_TYPES);

  if (ptr) {
    util_guarded_mem_alloc(size);
  }
  else {
    throw std::bad_alloc();
  }

  return ptr;
}

void device_memory::host_free()
{
  if (host_pointer) {
    util_guarded_mem_free(memory_size());
    util_aligned_free((void *)host_pointer);
    host_pointer = 0;
  }
}

void device_memory::device_alloc()
{
  assert(!device_pointer && type != MEM_TEXTURE && type != MEM_GLOBAL);
  device->mem_alloc(*this);
}

void device_memory::device_free()
{
  if (device_pointer) {
    device->mem_free(*this);
  }
}

void device_memory::device_copy_to()
{
  if (host_pointer) {
    device->mem_copy_to(*this);
  }
}

void device_memory::device_copy_from(int y, int w, int h, int elem)
{
  assert(type != MEM_TEXTURE && type != MEM_READ_ONLY && type != MEM_GLOBAL);
  device->mem_copy_from(*this, y, w, h, elem);
}

void device_memory::device_zero()
{
  if (data_size) {
    device->mem_zero(*this);
  }
}

void device_memory::swap_device(Device *new_device,
                                size_t new_device_size,
                                device_ptr new_device_ptr)
{
  original_device = device;
  original_device_size = device_size;
  original_device_ptr = device_pointer;

  device = new_device;
  device_size = new_device_size;
  device_pointer = new_device_ptr;
}

void device_memory::restore_device()
{
  device = original_device;
  device_size = original_device_size;
  device_pointer = original_device_ptr;
}

bool device_memory::is_resident(Device *sub_device) const
{
  return device->is_resident(device_pointer, sub_device);
}

/* Device Sub Ptr */

device_sub_ptr::device_sub_ptr(device_memory &mem, int offset, int size) : device(mem.device)
{
  ptr = device->mem_alloc_sub_ptr(mem, offset, size);
}

device_sub_ptr::~device_sub_ptr()
{
  device->mem_free_sub_ptr(ptr);
}

/* Device Texture */

device_texture::device_texture(Device *device,
                               const char *name,
                               const uint slot,
                               ImageDataType image_data_type,
                               InterpolationType interpolation,
                               ExtensionType extension)
    : device_memory(device, name, MEM_TEXTURE), slot(slot)
{
  switch (image_data_type) {
    case IMAGE_DATA_TYPE_FLOAT4:
      data_type = TYPE_FLOAT;
      data_elements = 4;
      break;
    case IMAGE_DATA_TYPE_FLOAT:
      data_type = TYPE_FLOAT;
      data_elements = 1;
      break;
    case IMAGE_DATA_TYPE_BYTE4:
      data_type = TYPE_UCHAR;
      data_elements = 4;
      break;
    case IMAGE_DATA_TYPE_BYTE:
    case IMAGE_DATA_TYPE_NANOVDB_FLOAT:
    case IMAGE_DATA_TYPE_NANOVDB_FLOAT3:
      data_type = TYPE_UCHAR;
      data_elements = 1;
      break;
    case IMAGE_DATA_TYPE_HALF4:
      data_type = TYPE_HALF;
      data_elements = 4;
      break;
    case IMAGE_DATA_TYPE_HALF:
      data_type = TYPE_HALF;
      data_elements = 1;
      break;
    case IMAGE_DATA_TYPE_USHORT4:
      data_type = TYPE_UINT16;
      data_elements = 4;
      break;
    case IMAGE_DATA_TYPE_USHORT:
      data_type = TYPE_UINT16;
      data_elements = 1;
      break;
    case IMAGE_DATA_TYPE_OIIO:
      /* Assumes 64 bit pointers to be stored as uint. */
      static_assert(sizeof(void*) == sizeof(uint64_t));
      data_type = TYPE_UINT64;
      data_elements = 1;
      break;
    case IMAGE_DATA_NUM_TYPES:
      assert(0);
      return;
  }

  memset(&info, 0, sizeof(info));
  info.data_type = image_data_type;
  info.interpolation = interpolation;
  info.extension = extension;
}

device_texture::~device_texture()
{
  device_free();
  host_free();
}

/* Host memory allocation. */
void *device_texture::alloc(const size_t width, const size_t height, const size_t depth)
{
  const size_t new_size = size(width, height, depth);

  if (new_size != data_size) {
    device_free();
    host_free();
    host_pointer = host_alloc(data_elements * datatype_size(data_type) * new_size);
    assert(device_pointer == 0);
  }

  data_size = new_size;
  data_width = width;
  data_height = height;
  data_depth = depth;

  info.width = width;
  info.height = height;
  info.depth = depth;

  return host_pointer;
}

void device_texture::copy_to_device()
{
  device_copy_to();
}

CCL_NAMESPACE_END
<commit_msg>Make static_assert C++11 compliant<commit_after>/*
 * Copyright 2011-2017 Blender Foundation
 *
 * 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 "device/device_memory.h"
#include "device/device.h"

CCL_NAMESPACE_BEGIN

/* Device Memory */

device_memory::device_memory(Device *device, const char *name, MemoryType type)
    : data_type(device_type_traits<uchar>::data_type),
      data_elements(device_type_traits<uchar>::num_elements),
      data_size(0),
      device_size(0),
      data_width(0),
      data_height(0),
      data_depth(0),
      type(type),
      name(name),
      device(device),
      device_pointer(0),
      host_pointer(0),
      shared_pointer(0),
      shared_counter(0)
{
}

device_memory::~device_memory()
{
  assert(shared_pointer == 0);
  assert(shared_counter == 0);
}

void *device_memory::host_alloc(size_t size)
{
  if (!size) {
    return 0;
  }

  void *ptr = util_aligned_malloc(size, MIN_ALIGNMENT_CPU_DATA_TYPES);

  if (ptr) {
    util_guarded_mem_alloc(size);
  }
  else {
    throw std::bad_alloc();
  }

  return ptr;
}

void device_memory::host_free()
{
  if (host_pointer) {
    util_guarded_mem_free(memory_size());
    util_aligned_free((void *)host_pointer);
    host_pointer = 0;
  }
}

void device_memory::device_alloc()
{
  assert(!device_pointer && type != MEM_TEXTURE && type != MEM_GLOBAL);
  device->mem_alloc(*this);
}

void device_memory::device_free()
{
  if (device_pointer) {
    device->mem_free(*this);
  }
}

void device_memory::device_copy_to()
{
  if (host_pointer) {
    device->mem_copy_to(*this);
  }
}

void device_memory::device_copy_from(int y, int w, int h, int elem)
{
  assert(type != MEM_TEXTURE && type != MEM_READ_ONLY && type != MEM_GLOBAL);
  device->mem_copy_from(*this, y, w, h, elem);
}

void device_memory::device_zero()
{
  if (data_size) {
    device->mem_zero(*this);
  }
}

void device_memory::swap_device(Device *new_device,
                                size_t new_device_size,
                                device_ptr new_device_ptr)
{
  original_device = device;
  original_device_size = device_size;
  original_device_ptr = device_pointer;

  device = new_device;
  device_size = new_device_size;
  device_pointer = new_device_ptr;
}

void device_memory::restore_device()
{
  device = original_device;
  device_size = original_device_size;
  device_pointer = original_device_ptr;
}

bool device_memory::is_resident(Device *sub_device) const
{
  return device->is_resident(device_pointer, sub_device);
}

/* Device Sub Ptr */

device_sub_ptr::device_sub_ptr(device_memory &mem, int offset, int size) : device(mem.device)
{
  ptr = device->mem_alloc_sub_ptr(mem, offset, size);
}

device_sub_ptr::~device_sub_ptr()
{
  device->mem_free_sub_ptr(ptr);
}

/* Device Texture */

device_texture::device_texture(Device *device,
                               const char *name,
                               const uint slot,
                               ImageDataType image_data_type,
                               InterpolationType interpolation,
                               ExtensionType extension)
    : device_memory(device, name, MEM_TEXTURE), slot(slot)
{
  switch (image_data_type) {
    case IMAGE_DATA_TYPE_FLOAT4:
      data_type = TYPE_FLOAT;
      data_elements = 4;
      break;
    case IMAGE_DATA_TYPE_FLOAT:
      data_type = TYPE_FLOAT;
      data_elements = 1;
      break;
    case IMAGE_DATA_TYPE_BYTE4:
      data_type = TYPE_UCHAR;
      data_elements = 4;
      break;
    case IMAGE_DATA_TYPE_BYTE:
    case IMAGE_DATA_TYPE_NANOVDB_FLOAT:
    case IMAGE_DATA_TYPE_NANOVDB_FLOAT3:
      data_type = TYPE_UCHAR;
      data_elements = 1;
      break;
    case IMAGE_DATA_TYPE_HALF4:
      data_type = TYPE_HALF;
      data_elements = 4;
      break;
    case IMAGE_DATA_TYPE_HALF:
      data_type = TYPE_HALF;
      data_elements = 1;
      break;
    case IMAGE_DATA_TYPE_USHORT4:
      data_type = TYPE_UINT16;
      data_elements = 4;
      break;
    case IMAGE_DATA_TYPE_USHORT:
      data_type = TYPE_UINT16;
      data_elements = 1;
      break;
    case IMAGE_DATA_TYPE_OIIO:
      /* Assumes 64 bit pointers to be stored as uint. */
      static_assert(sizeof(void*) == sizeof(uint64_t), "");
      data_type = TYPE_UINT64;
      data_elements = 1;
      break;
    case IMAGE_DATA_NUM_TYPES:
      assert(0);
      return;
  }

  memset(&info, 0, sizeof(info));
  info.data_type = image_data_type;
  info.interpolation = interpolation;
  info.extension = extension;
}

device_texture::~device_texture()
{
  device_free();
  host_free();
}

/* Host memory allocation. */
void *device_texture::alloc(const size_t width, const size_t height, const size_t depth)
{
  const size_t new_size = size(width, height, depth);

  if (new_size != data_size) {
    device_free();
    host_free();
    host_pointer = host_alloc(data_elements * datatype_size(data_type) * new_size);
    assert(device_pointer == 0);
  }

  data_size = new_size;
  data_width = width;
  data_height = height;
  data_depth = depth;

  info.width = width;
  info.height = height;
  info.depth = depth;

  return host_pointer;
}

void device_texture::copy_to_device()
{
  device_copy_to();
}

CCL_NAMESPACE_END
<|endoftext|>


<commit_before><commit_msg>config.cc konvertiert die konfigurationsdatei nicht automatisch nach utf8. (fehlermeldung unter windows in unicode build, nicht getestet untr bsd/linux/usw)<commit_after><|endoftext|>


<commit_before>//
//  StoreLogger.cpp
//  ee_x
//
//  Created by Zinge on 5/19/17.
//
//

#include <stack>

#include "ee/store/StoreLogger.hpp"
#include "ee/core/Logger.hpp"
#include "ee/core/LogLevel.hpp"
#include "ee/core/internal/SpinLock.hpp"

namespace ee {
namespace store {
namespace detail {
class DefaultStoreLogger : public StoreLogger {
public:
    virtual void logDebug(const std::string& tag,
                          const std::string& message) override {
        core::Logger::log(core::LogLevel::Debug, tag, message);
    }

    virtual void logError(const std::string& tag,
                          const std::string& message) override {
        core::Logger::log(core::LogLevel::Error, tag, message);
    }
};
} // namespace detail

namespace {
core::SpinLock stackLock;
std::stack<StoreLogger*> stack;
detail::DefaultStoreLogger defaultLogger;

std::stack<StoreLogger*>& getLoggerStack() {
    return stack;
}
} // namespace

StoreLogger& StoreLogger::getInstance() {
    std::lock_guard<core::SpinLock> guard(stackLock);
    return *getLoggerStack().top();
}

StoreLogger::StoreLogger() {
    std::lock_guard<core::SpinLock> guard(stackLock);
    getLoggerStack().push(this);
}

StoreLogger::~StoreLogger() {
    std::lock_guard<core::SpinLock> guard(stackLock);
    getLoggerStack().pop();
}
} // namespace store
} // namespace ee
<commit_msg>- Optimize include.<commit_after>//
//  StoreLogger.cpp
//  ee_x
//
//  Created by Zinge on 5/19/17.
//
//

#include <stack>
#include <mutex>

#include "ee/store/StoreLogger.hpp"
#include "ee/core/Logger.hpp"
#include "ee/core/LogLevel.hpp"
#include "ee/core/internal/SpinLock.hpp"

namespace ee {
namespace store {
namespace detail {
class DefaultStoreLogger : public StoreLogger {
public:
    virtual void logDebug(const std::string& tag,
                          const std::string& message) override {
        core::Logger::log(core::LogLevel::Debug, tag, message);
    }

    virtual void logError(const std::string& tag,
                          const std::string& message) override {
        core::Logger::log(core::LogLevel::Error, tag, message);
    }
};
} // namespace detail

namespace {
core::SpinLock stackLock;
std::stack<StoreLogger*> stack;
detail::DefaultStoreLogger defaultLogger;

std::stack<StoreLogger*>& getLoggerStack() {
    return stack;
}
} // namespace

StoreLogger& StoreLogger::getInstance() {
    std::lock_guard<core::SpinLock> guard(stackLock);
    return *getLoggerStack().top();
}

StoreLogger::StoreLogger() {
    std::lock_guard<core::SpinLock> guard(stackLock);
    getLoggerStack().push(this);
}

StoreLogger::~StoreLogger() {
    std::lock_guard<core::SpinLock> guard(stackLock);
    getLoggerStack().pop();
}
} // namespace store
} // namespace ee
<|endoftext|>