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

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

#include "editable.hxx"
#include "document.hxx"
#include "viewfunc.hxx"
#include "globstr.hrc"

//------------------------------------------------------------------

ScEditableTester::ScEditableTester() :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
}

void ScEditableTester::Reset()
{
    bIsEditable = bOnlyMatrix = TRUE;
}

ScEditableTester::ScEditableTester( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestBlock( pDoc, nTab, nStartCol, nStartRow, nEndCol, nEndRow );
}

ScEditableTester::ScEditableTester( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestSelectedBlock( pDoc, nStartCol, nStartRow, nEndCol, nEndRow, rMark );
}

ScEditableTester::ScEditableTester( ScDocument* pDoc, const ScRange& rRange ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestRange( pDoc, rRange );
}

ScEditableTester::ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestSelection( pDoc, rMark );
}

ScEditableTester::ScEditableTester( ScViewFunc* pView ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestView( pView );
}

//------------------------------------------------------------------

void ScEditableTester::TestBlock( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow )
{
    if ( bIsEditable || bOnlyMatrix )
    {
        BOOL bThisMatrix;
        if ( !pDoc->IsBlockEditable( nTab, nStartCol, nStartRow, nEndCol, nEndRow, &bThisMatrix ) )
        {
            bIsEditable = FALSE;
            if ( !bThisMatrix )
                bOnlyMatrix = FALSE;
        }
    }
}

void ScEditableTester::TestSelectedBlock( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark )
{
    SCTAB nTabCount = pDoc->GetTableCount();
    for (SCTAB nTab=0; nTab<nTabCount; nTab++)
        if (rMark.GetTableSelect(nTab))
            TestBlock( pDoc, nTab, nStartCol, nStartRow, nEndCol, nEndRow );
}

void ScEditableTester::TestRange( ScDocument* pDoc, const ScRange& rRange )
{
    SCCOL nStartCol = rRange.aStart.Col();
    SCROW nStartRow = rRange.aStart.Row();
    SCTAB nStartTab = rRange.aStart.Tab();
    SCCOL nEndCol = rRange.aEnd.Col();
    SCROW nEndRow = rRange.aEnd.Row();
    SCTAB nEndTab = rRange.aEnd.Tab();
    for (SCTAB nTab=nStartTab; nTab<=nEndTab; nTab++)
        TestBlock( pDoc, nTab, nStartCol, nStartRow, nEndCol, nEndRow );
}

void ScEditableTester::TestSelection( ScDocument* pDoc, const ScMarkData& rMark )
{
    if ( bIsEditable || bOnlyMatrix )
    {
        BOOL bThisMatrix;
        if ( !pDoc->IsSelectionEditable( rMark, &bThisMatrix ) )
        {
            bIsEditable = FALSE;
            if ( !bThisMatrix )
                bOnlyMatrix = FALSE;
        }
    }
}

void ScEditableTester::TestView( ScViewFunc* pView )
{
    if ( bIsEditable || bOnlyMatrix )
    {
        BOOL bThisMatrix;
        if ( !pView->SelectionEditable( &bThisMatrix ) )
        {
            bIsEditable = FALSE;
            if ( !bThisMatrix )
                bOnlyMatrix = FALSE;
        }
    }
}

//------------------------------------------------------------------

USHORT ScEditableTester::GetMessageId() const
{
    if (bIsEditable)
        return 0;
    else if (bOnlyMatrix)
        return STR_MATRIXFRAGMENTERR;
    else
        return STR_PROTECTIONERR;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.4.492); FILE MERGED 2008/03/31 17:15:29 rt 1.4.492.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: editable.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "editable.hxx"
#include "document.hxx"
#include "viewfunc.hxx"
#include "globstr.hrc"

//------------------------------------------------------------------

ScEditableTester::ScEditableTester() :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
}

void ScEditableTester::Reset()
{
    bIsEditable = bOnlyMatrix = TRUE;
}

ScEditableTester::ScEditableTester( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestBlock( pDoc, nTab, nStartCol, nStartRow, nEndCol, nEndRow );
}

ScEditableTester::ScEditableTester( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestSelectedBlock( pDoc, nStartCol, nStartRow, nEndCol, nEndRow, rMark );
}

ScEditableTester::ScEditableTester( ScDocument* pDoc, const ScRange& rRange ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestRange( pDoc, rRange );
}

ScEditableTester::ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestSelection( pDoc, rMark );
}

ScEditableTester::ScEditableTester( ScViewFunc* pView ) :
    bIsEditable( TRUE ),
    bOnlyMatrix( TRUE )
{
    TestView( pView );
}

//------------------------------------------------------------------

void ScEditableTester::TestBlock( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow )
{
    if ( bIsEditable || bOnlyMatrix )
    {
        BOOL bThisMatrix;
        if ( !pDoc->IsBlockEditable( nTab, nStartCol, nStartRow, nEndCol, nEndRow, &bThisMatrix ) )
        {
            bIsEditable = FALSE;
            if ( !bThisMatrix )
                bOnlyMatrix = FALSE;
        }
    }
}

void ScEditableTester::TestSelectedBlock( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark )
{
    SCTAB nTabCount = pDoc->GetTableCount();
    for (SCTAB nTab=0; nTab<nTabCount; nTab++)
        if (rMark.GetTableSelect(nTab))
            TestBlock( pDoc, nTab, nStartCol, nStartRow, nEndCol, nEndRow );
}

void ScEditableTester::TestRange( ScDocument* pDoc, const ScRange& rRange )
{
    SCCOL nStartCol = rRange.aStart.Col();
    SCROW nStartRow = rRange.aStart.Row();
    SCTAB nStartTab = rRange.aStart.Tab();
    SCCOL nEndCol = rRange.aEnd.Col();
    SCROW nEndRow = rRange.aEnd.Row();
    SCTAB nEndTab = rRange.aEnd.Tab();
    for (SCTAB nTab=nStartTab; nTab<=nEndTab; nTab++)
        TestBlock( pDoc, nTab, nStartCol, nStartRow, nEndCol, nEndRow );
}

void ScEditableTester::TestSelection( ScDocument* pDoc, const ScMarkData& rMark )
{
    if ( bIsEditable || bOnlyMatrix )
    {
        BOOL bThisMatrix;
        if ( !pDoc->IsSelectionEditable( rMark, &bThisMatrix ) )
        {
            bIsEditable = FALSE;
            if ( !bThisMatrix )
                bOnlyMatrix = FALSE;
        }
    }
}

void ScEditableTester::TestView( ScViewFunc* pView )
{
    if ( bIsEditable || bOnlyMatrix )
    {
        BOOL bThisMatrix;
        if ( !pView->SelectionEditable( &bThisMatrix ) )
        {
            bIsEditable = FALSE;
            if ( !bThisMatrix )
                bOnlyMatrix = FALSE;
        }
    }
}

//------------------------------------------------------------------

USHORT ScEditableTester::GetMessageId() const
{
    if (bIsEditable)
        return 0;
    else if (bOnlyMatrix)
        return STR_MATRIXFRAGMENTERR;
    else
        return STR_PROTECTIONERR;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: lbseldlg.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 09:37:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#undef SC_DLLIMPLEMENTATION

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#include <vcl/msgbox.hxx>

#include "lbseldlg.hxx"
#include "scresid.hxx"
#include "miscdlgs.hrc"

//==================================================================

ScSelEntryDlg::ScSelEntryDlg(      Window*  pParent,
                                   USHORT   nResId,
                             const String&  aTitle,
                             const String&  aLbTitle,
                                   List&    aEntryList ) :
    ModalDialog     ( pParent, ScResId( nResId ) ),
    //
    aFlLbTitle      ( this, ScResId( FL_ENTRYLIST ) ),
    aLb             ( this, ScResId( LB_ENTRYLIST ) ),
    aBtnOk          ( this, ScResId( BTN_OK ) ),
    aBtnCancel      ( this, ScResId( BTN_CANCEL ) ),
    aBtnHelp        ( this, ScResId( BTN_HELP ) )
{
    SetText( aTitle );
    aFlLbTitle.SetText( aLbTitle );
    aLb.Clear();
    aLb.SetDoubleClickHdl( LINK( this, ScSelEntryDlg, DblClkHdl ) );

    void*   pListEntry = aEntryList.First();
    while ( pListEntry )
    {
        aLb.InsertEntry( *((String*)pListEntry ) );
        pListEntry = aEntryList.Next();
    }

    if ( aLb.GetEntryCount() > 0 )
        aLb.SelectEntryPos( 0 );

    //-------------
    FreeResource();
}

//------------------------------------------------------------------------

String ScSelEntryDlg::GetSelectEntry() const
{
    return aLb.GetSelectEntry();
}

//------------------------------------------------------------------------

USHORT ScSelEntryDlg::GetSelectEntryPos() const
{
    return aLb.GetSelectEntryPos();
}

//------------------------------------------------------------------------

IMPL_LINK_INLINE_START( ScSelEntryDlg, DblClkHdl, void *, EMPTYARG )
{
    EndDialog( RET_OK );
    return 0;
}
IMPL_LINK_INLINE_END( ScSelEntryDlg, DblClkHdl, void *, EMPTYARG )

//------------------------------------------------------------------------

__EXPORT ScSelEntryDlg::~ScSelEntryDlg()
{
}

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

#undef SC_DLLIMPLEMENTATION

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#include <vcl/msgbox.hxx>

#include "lbseldlg.hxx"
#include "scresid.hxx"
#include "miscdlgs.hrc"

//==================================================================

ScSelEntryDlg::ScSelEntryDlg(      Window*  pParent,
                                   USHORT   nResId,
                             const String&  aTitle,
                             const String&  aLbTitle,
                                   List&    aEntryList ) :
    ModalDialog     ( pParent, ScResId( nResId ) ),
    //
    aFlLbTitle      ( this, ScResId( FL_ENTRYLIST ) ),
    aLb             ( this, ScResId( LB_ENTRYLIST ) ),
    aBtnOk          ( this, ScResId( BTN_OK ) ),
    aBtnCancel      ( this, ScResId( BTN_CANCEL ) ),
    aBtnHelp        ( this, ScResId( BTN_HELP ) )
{
    SetText( aTitle );
    aFlLbTitle.SetText( aLbTitle );
    aLb.Clear();
    aLb.SetDoubleClickHdl( LINK( this, ScSelEntryDlg, DblClkHdl ) );

    void*   pListEntry = aEntryList.First();
    while ( pListEntry )
    {
        aLb.InsertEntry( *((String*)pListEntry ) );
        pListEntry = aEntryList.Next();
    }

    if ( aLb.GetEntryCount() > 0 )
        aLb.SelectEntryPos( 0 );

    //-------------
    FreeResource();
}

//------------------------------------------------------------------------

String ScSelEntryDlg::GetSelectEntry() const
{
    return aLb.GetSelectEntry();
}

//------------------------------------------------------------------------

USHORT ScSelEntryDlg::GetSelectEntryPos() const
{
    return aLb.GetSelectEntryPos();
}

//------------------------------------------------------------------------

IMPL_LINK_INLINE_START( ScSelEntryDlg, DblClkHdl, void *, EMPTYARG )
{
    EndDialog( RET_OK );
    return 0;
}
IMPL_LINK_INLINE_END( ScSelEntryDlg, DblClkHdl, void *, EMPTYARG )

//------------------------------------------------------------------------

__EXPORT ScSelEntryDlg::~ScSelEntryDlg()
{
}

<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include <sstream> // stringstream

#include "niflib.h"
#include "obj/NiTriShape.h"
#include "obj/BSLightingShaderProperty.h"

using namespace Niflib;
using namespace std;

BOOST_AUTO_TEST_SUITE(write_test_suite)

BOOST_AUTO_TEST_CASE(write_incomplete_tree_test)
{
  stringstream ss;

  // create a simple nif tree with BSLightingShaderProperty
  NiTriShapeRef shape = new NiTriShape;
  BSLightingShaderPropertyRef prop = new BSLightingShaderProperty;
  shape->SetBSProperty(0, StaticCast<NiPropertyRef>(prop));
  BOOST_CHECK_NO_THROW(WriteNifTree(ss, shape));
  ss.seekg(0);
  NiObjectRef root;
  BOOST_CHECK_NO_THROW(root = ReadNifTree(ss));
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix name of test.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include <sstream> // stringstream

#include "niflib.h"
#include "obj/NiTriShape.h"
#include "obj/BSLightingShaderProperty.h"

using namespace Niflib;
using namespace std;

BOOST_AUTO_TEST_SUITE(bslightingshaderproperty_test_suite)

BOOST_AUTO_TEST_CASE(bslightingshaderproperty_test)
{
  stringstream ss;

  // create a simple nif tree with BSLightingShaderProperty
  NiTriShapeRef shape = new NiTriShape;
  BSLightingShaderPropertyRef prop = new BSLightingShaderProperty;
  shape->SetBSProperty(0, StaticCast<NiPropertyRef>(prop));
  BOOST_CHECK_NO_THROW(WriteNifTree(ss, shape));
  ss.seekg(0);
  NiObjectRef root;
  BOOST_CHECK_NO_THROW(root = ReadNifTree(ss));
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before><commit_msg>Fixed: member variable 'Baralho::gRenderer' is not initialized in the constructor.<commit_after><|endoftext|>


<commit_before>#include <avr/pgmspace.h>
#include <util/delay.h>
#include <stdlib.h>

#include "Adafruit_GFX.h"
#include "Adafruit_GP9002.h"
#include "glcdfont.c"

Adafruit_GP9002::Adafruit_GP9002(int8_t SCLK, int8_t MISO, int8_t MOSI,
				 int8_t CS, int8_t DC) {
  _sclk = SCLK;
  _miso = MISO;
  _mosi = MOSI;
  _cs = CS;
  _dc = DC;
  hwSPI = false;
  constructor(128, 64);
}

Adafruit_GP9002::Adafruit_GP9002(int8_t CS, int8_t DC) {
  _sclk = -1;
  _miso = -1;
  _mosi = -1;
  _cs = CS;
  _dc = DC;
  hwSPI = true;
  constructor(128, 64);
}

void Adafruit_GP9002::begin(void) {
  // set pin directions
  pinMode(_dc, OUTPUT);
  pinMode(_cs, OUTPUT);

  if (! hwSPI) {
    pinMode(_mosi, OUTPUT);
    pinMode(_miso, INPUT);
    pinMode(_sclk, OUTPUT);

    clkport     = portOutputRegister(digitalPinToPort(_sclk));
    clkpinmask  = digitalPinToBitMask(_sclk);
    mosiport    = portOutputRegister(digitalPinToPort(_mosi));
    mosipinmask = digitalPinToBitMask(_mosi);
    misopin = portInputRegister(digitalPinToPort(_miso));
    misopinmask = digitalPinToBitMask(_miso);
  } else {
    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV4);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
  }
  csport    = portOutputRegister(digitalPinToPort(_cs));
  cspinmask = digitalPinToBitMask(_cs);
  dcport    = portOutputRegister(digitalPinToPort(_dc));
  dcpinmask = digitalPinToBitMask(_dc);

  command(GP9002_DISPLAY);
  dataWrite(GP9002_DISPLAY_MONOCHROME);
  command(GP9002_LOWERADDR1);
  dataWrite(0x0);
  command(GP9002_HIGHERADDR1);
  dataWrite(0x0);
  command(GP9002_LOWERADDR2);
  dataWrite(0x0);
  command(GP9002_HIGHERADDR2);
  dataWrite(0x4);
  command(GP9002_OR);
  command(GP9002_CLEARSCREEN);
  command(GP9002_DISPLAY1ON);

  // hold the address so we can read and then write
  command(GP9002_ADDRHELD);
}

// updated high speed drawing!
void Adafruit_GP9002::drawFastVLine(uint16_t x, uint16_t orig_y, uint16_t h, uint16_t color) {
  if ((x >= width()) || (orig_y >= height())) return;
  //if ((orig_y+h) >= height())
  //  h = height() - orig_y -1;

  //drawLine(x, orig_y, x, orig_y+h, color); return;

  while (h) {
    if ((h >= 8) && ((orig_y) % 8 == 0))
      break;
    Serial.print("("); Serial.print(x, DEC); Serial.print(", "); Serial.print(orig_y); Serial.println(")");
    drawPixel(x, orig_y, color);
    orig_y++;
    h--;
  }

  if (h >= 8) {
    while (h >= 8) {
      // calculate addr
      uint16_t addr = 0;
      addr = x*8;
      uint16_t y = orig_y;
      y = 63 - y;
      addr += y/8;

      Serial.println(addr, HEX);
      command(GP9002_ADDRHELD);
      command(GP9002_ADDRL);
      dataWrite(addr & 0xFF);
      command(GP9002_ADDRH);
      dataWrite(addr >> 8);
      command(GP9002_DATAWRITE);
      // draw 8 pixels at once!
      if (color)
	dataWrite(0xFF);
      else
	dataWrite(0x00);
      h -= 8;
      orig_y += 8;
    }
  }
  while (h+1) {
    drawPixel(x, orig_y-1, color);
    orig_y++;
    h--;
  }

}

// the most basic function, set a single pixel
void Adafruit_GP9002::drawPixel(uint16_t x, uint16_t y, uint16_t color) {
  if ((x >= width()) || (y >= height()))
    return;

  uint8_t p;

  // calculate addr
  uint16_t addr = 0;
  addr = x*8;
  y = 63 - y;
  addr += y/8;

  command(GP9002_ADDRHELD);
  command(GP9002_ADDRL);
  dataWrite(addr & 0xFF);
  command(GP9002_ADDRH);
  dataWrite(addr >> 8);
  command(GP9002_DATAREAD);
  dataRead();
  p = dataRead();

  //Serial.println(p, HEX);

  if (color)
    p |= (1 << (7-(y % 8)));
  else
    p &= ~(1 << (7-(y % 8)));
  command(GP9002_DATAWRITE);
  dataWrite(p);
}

void Adafruit_GP9002::invert(boolean i) {
  // This is kinda clumsy but it does work
  // fill the opposite screen with all on pixels so we can invert!
  uint16_t addr = 0x400;

  command(GP9002_ADDRINCR);
  command(GP9002_ADDRL);
  dataWrite(addr & 0xFF);
  command(GP9002_ADDRH);
  dataWrite(addr >> 8);
  command(GP9002_DATAWRITE);

  if (i) {
    while (addr < 0x0800) {
      dataWrite(0xFF);
      addr++;
    }
    command(GP9002_XOR);
  } else {
    while (addr < 0x0800) {
      dataWrite(0x00);
      addr++;
    }
    command(GP9002_OR);
  }
  command(GP9002_ADDRHELD);

}

void Adafruit_GP9002::slowSPIwrite(uint8_t d) {
 for (uint8_t i=0; i<8; i++) {
   digitalWrite(_sclk, LOW);
   if (d & _BV(i)) {
     digitalWrite(_mosi, HIGH);
   } else {
     digitalWrite(_mosi, LOW);
   }
   digitalWrite(_sclk, HIGH);
 }
}

inline void Adafruit_GP9002::fastSPIwrite(uint8_t d) {
  if (hwSPI) {
    SPDR = d;
    while(!(SPSR & _BV(SPIF)));
    return;
  }
  for(uint8_t bit = 0x1; bit != 0x00; bit <<= 1) {
    *clkport &= ~clkpinmask;
    if(d & bit) *mosiport |=  mosipinmask;
    else        *mosiport &= ~mosipinmask;
    *clkport |=  clkpinmask;
  }
}

uint8_t Adafruit_GP9002::slowSPIread(void) {
 uint8_t reply = 0;
 for (uint8_t i=0; i<8; i++) {
   digitalWrite(_sclk, LOW);

   digitalWrite(_sclk, HIGH);
   if (digitalRead(_miso))
     reply |= _BV(i);
 }
 return reply;
}

inline uint8_t Adafruit_GP9002::fastSPIread(void) {
 uint8_t reply = 0;
 for (uint8_t i=0; i<8; i++) {
   *clkport &= ~clkpinmask;

   *clkport |=  clkpinmask;
   if ((*misopin) & misopinmask)
     reply |= _BV(i);
 }
 return reply;
}

void Adafruit_GP9002::command(uint8_t d) {
  *dcport |= dcpinmask;
  *csport &= ~cspinmask;
  fastSPIwrite(d);
  *csport |= cspinmask;
  delayMicroseconds(1); // should be 400ns actually
}

inline void Adafruit_GP9002::dataWrite(uint8_t d) {
  *dcport &= ~dcpinmask;
  *csport &= ~cspinmask;

  fastSPIwrite(d);

  *csport |= cspinmask;
  delayMicroseconds(1); // should be 600ns actually
}
inline uint8_t Adafruit_GP9002::dataRead() {
  uint8_t r;

  *dcport &= ~dcpinmask;
  *csport &= ~cspinmask;

  r = fastSPIread();

  *csport |= cspinmask;
  delayMicroseconds(1);

 return r;
}

void Adafruit_GP9002::setBrightness(uint8_t val) {

}

// clear everything
void Adafruit_GP9002::clearDisplay(void) {
  command(GP9002_CLEARSCREEN);

  delay(1);
}

void Adafruit_GP9002::displayOff(void) {
  command(GP9002_DISPLAYSOFF);
}
void Adafruit_GP9002::displayOn(void) {
   command(GP9002_DISPLAY1ON);
}

<commit_msg>optimized drawvline - hopefully good to go now :/<commit_after>#include <avr/pgmspace.h>
#include <util/delay.h>
#include <stdlib.h>

#include "Adafruit_GFX.h"
#include "Adafruit_GP9002.h"
#include "glcdfont.c"

Adafruit_GP9002::Adafruit_GP9002(int8_t SCLK, int8_t MISO, int8_t MOSI,
				 int8_t CS, int8_t DC) {
  _sclk = SCLK;
  _miso = MISO;
  _mosi = MOSI;
  _cs = CS;
  _dc = DC;
  hwSPI = false;
  constructor(128, 64);
}

Adafruit_GP9002::Adafruit_GP9002(int8_t CS, int8_t DC) {
  _sclk = -1;
  _miso = -1;
  _mosi = -1;
  _cs = CS;
  _dc = DC;
  hwSPI = true;
  constructor(128, 64);
}

void Adafruit_GP9002::begin(void) {
  // set pin directions
  pinMode(_dc, OUTPUT);
  pinMode(_cs, OUTPUT);

  if (! hwSPI) {
    pinMode(_mosi, OUTPUT);
    pinMode(_miso, INPUT);
    pinMode(_sclk, OUTPUT);

    clkport     = portOutputRegister(digitalPinToPort(_sclk));
    clkpinmask  = digitalPinToBitMask(_sclk);
    mosiport    = portOutputRegister(digitalPinToPort(_mosi));
    mosipinmask = digitalPinToBitMask(_mosi);
    misopin = portInputRegister(digitalPinToPort(_miso));
    misopinmask = digitalPinToBitMask(_miso);
  } else {
    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV4);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
  }
  csport    = portOutputRegister(digitalPinToPort(_cs));
  cspinmask = digitalPinToBitMask(_cs);
  dcport    = portOutputRegister(digitalPinToPort(_dc));
  dcpinmask = digitalPinToBitMask(_dc);

  command(GP9002_DISPLAY);
  dataWrite(GP9002_DISPLAY_MONOCHROME);
  command(GP9002_LOWERADDR1);
  dataWrite(0x0);
  command(GP9002_HIGHERADDR1);
  dataWrite(0x0);
  command(GP9002_LOWERADDR2);
  dataWrite(0x0);
  command(GP9002_HIGHERADDR2);
  dataWrite(0x4);
  command(GP9002_OR);
  command(GP9002_CLEARSCREEN);
  command(GP9002_DISPLAY1ON);

  // hold the address so we can read and then write
  command(GP9002_ADDRHELD);
}

// updated high speed drawing!
void Adafruit_GP9002::drawFastVLine(uint16_t x, uint16_t orig_y, uint16_t h, uint16_t color) {
  if ((x >= width()) || (orig_y >= height())) return;
  //if ((orig_y+h) >= height())
  //  h = height() - orig_y -1;

  //drawLine(x, orig_y, x, orig_y+h, color); return;

  while (h) {
    if ((h >= 8) && ((orig_y) % 8 == 0))
      break;
    drawPixel(x, orig_y, color);
    orig_y++;
    h--;
  }

  if (h >= 8) {
      // calculate addr
      uint16_t addr = 0;
      addr = x*8;
      uint16_t y = orig_y+h-8;
      y = 63 - y;
      addr += y/8;

      Serial.println(addr, HEX);
      command(GP9002_ADDRINCR);
      command(GP9002_ADDRL);
      dataWrite(addr & 0xFF);
      command(GP9002_ADDRH);
      dataWrite(addr >> 8);
      command(GP9002_DATAWRITE);

      while (h >= 8) {
	// draw 8 pixels at once!
	if (color)
	  dataWrite(0xFF);
	else
	  dataWrite(0x00);
	h -= 8;
	orig_y += 8;
      }
  }
  while (h+1) {
    drawPixel(x, orig_y-1, color);
    orig_y++;
    h--;
  }

}

// the most basic function, set a single pixel
void Adafruit_GP9002::drawPixel(uint16_t x, uint16_t y, uint16_t color) {
  if ((x >= width()) || (y >= height()))
    return;

  uint8_t p;

  // calculate addr
  uint16_t addr = 0;
  addr = x*8;
  y = 63 - y;
  addr += y/8;

  command(GP9002_ADDRHELD);
  command(GP9002_ADDRL);
  dataWrite(addr & 0xFF);
  command(GP9002_ADDRH);
  dataWrite(addr >> 8);
  command(GP9002_DATAREAD);
  dataRead();
  p = dataRead();

  //Serial.println(p, HEX);

  if (color)
    p |= (1 << (7-(y % 8)));
  else
    p &= ~(1 << (7-(y % 8)));
  command(GP9002_DATAWRITE);
  dataWrite(p);
}

void Adafruit_GP9002::invert(boolean i) {
  // This is kinda clumsy but it does work
  // fill the opposite screen with all on pixels so we can invert!
  uint16_t addr = 0x400;

  command(GP9002_ADDRINCR);
  command(GP9002_ADDRL);
  dataWrite(addr & 0xFF);
  command(GP9002_ADDRH);
  dataWrite(addr >> 8);
  command(GP9002_DATAWRITE);

  if (i) {
    while (addr < 0x0800) {
      dataWrite(0xFF);
      addr++;
    }
    command(GP9002_XOR);
  } else {
    while (addr < 0x0800) {
      dataWrite(0x00);
      addr++;
    }
    command(GP9002_OR);
  }
  command(GP9002_ADDRHELD);

}

void Adafruit_GP9002::slowSPIwrite(uint8_t d) {
 for (uint8_t i=0; i<8; i++) {
   digitalWrite(_sclk, LOW);
   if (d & _BV(i)) {
     digitalWrite(_mosi, HIGH);
   } else {
     digitalWrite(_mosi, LOW);
   }
   digitalWrite(_sclk, HIGH);
 }
}

inline void Adafruit_GP9002::fastSPIwrite(uint8_t d) {
  if (hwSPI) {
    SPDR = d;
    while(!(SPSR & _BV(SPIF)));
    return;
  }
  for(uint8_t bit = 0x1; bit != 0x00; bit <<= 1) {
    *clkport &= ~clkpinmask;
    if(d & bit) *mosiport |=  mosipinmask;
    else        *mosiport &= ~mosipinmask;
    *clkport |=  clkpinmask;
  }
}

uint8_t Adafruit_GP9002::slowSPIread(void) {
 uint8_t reply = 0;
 for (uint8_t i=0; i<8; i++) {
   digitalWrite(_sclk, LOW);

   digitalWrite(_sclk, HIGH);
   if (digitalRead(_miso))
     reply |= _BV(i);
 }
 return reply;
}

inline uint8_t Adafruit_GP9002::fastSPIread(void) {
 uint8_t reply = 0;
 for (uint8_t i=0; i<8; i++) {
   *clkport &= ~clkpinmask;

   *clkport |=  clkpinmask;
   if ((*misopin) & misopinmask)
     reply |= _BV(i);
 }
 return reply;
}

void Adafruit_GP9002::command(uint8_t d) {
  *dcport |= dcpinmask;
  *csport &= ~cspinmask;
  fastSPIwrite(d);
  *csport |= cspinmask;
  delayMicroseconds(1); // should be 400ns actually
}

inline void Adafruit_GP9002::dataWrite(uint8_t d) {
  *dcport &= ~dcpinmask;
  *csport &= ~cspinmask;

  fastSPIwrite(d);

  *csport |= cspinmask;
  delayMicroseconds(1); // should be 600ns actually
}
inline uint8_t Adafruit_GP9002::dataRead() {
  uint8_t r;

  *dcport &= ~dcpinmask;
  *csport &= ~cspinmask;

  r = fastSPIread();

  *csport |= cspinmask;
  delayMicroseconds(1);

 return r;
}

void Adafruit_GP9002::setBrightness(uint8_t val) {

}

// clear everything
void Adafruit_GP9002::clearDisplay(void) {
  command(GP9002_CLEARSCREEN);

  delay(1);
}

void Adafruit_GP9002::displayOff(void) {
  command(GP9002_DISPLAYSOFF);
}
void Adafruit_GP9002::displayOn(void) {
   command(GP9002_DISPLAY1ON);
}

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Alembic.h"

#include "AlembicWriteJob.h"
#include "ObjectList.h"

#include "SceneEnumProc.h"
#include "AlembicPolyMsh.h"
#include "AlembicXForm.h"
#include "AlembicCamera.h"
#include "AlembicPoints.h"
#include "AlembicCurves.h"
#include "CommonUtilities.h"

AlembicWriteJob::AlembicWriteJob(const std::string &in_FileName, const ObjectList &in_Selection, const std::vector<double> &in_Frames, Interface *i)
{
    mApplication = i;
	mMeshErrors = 0;
    mFileName = in_FileName;
    mSelection = in_Selection;

    for(int i=0; i < in_Frames.size(); i++)
    {
        mFrames.push_back(in_Frames[i]);
    }
}

AlembicWriteJob::~AlembicWriteJob()
{
}

void AlembicWriteJob::SetOption(const std::string & in_Name, const bool & in_Value)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    if(it == mOptions.end())
    {
        mOptions.insert(std::pair<std::string,bool>(in_Name,in_Value));
    }
    else
    {
        it->second = in_Value;
    }
}

bool AlembicWriteJob::HasOption(const std::string & in_Name)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    return it != mOptions.end();
}

bool AlembicWriteJob::GetOption(const std::string & in_Name)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    if(it != mOptions.end())
    {
        return it->second;
    }
    return false;
}

bool AlembicWriteJob::PreProcess()
{
    // check filenames
    if(mFileName.empty())
    {
        ESS_LOG_WARNING("[alembic] No filename specified.");
        return false;
    }

    // check objects
    if(mSelection.Count() == 0)
    {
        ESS_LOG_WARNING("[alembic] No objects specified.");
        return false;
    }

    // check frames
    if(mFrames.size() == 0)
    {
        ESS_LOG_WARNING("[alembic] No frames specified.");
        return false;
    }

    // init archive (use a locally scoped archive)
    std::string sceneFileName = "";
    sceneFileName.append( EC_MSTR_to_UTF8( mApplication->GetCurFilePath() ) );
    try
    {
        mArchive = CreateArchiveWithInfo(
			Alembic::AbcCoreHDF5::WriteArchive(),
			mFileName.c_str(),
			getExporterName( "3DS Max " EC_QUOTE( crate_Max_Version ) ).c_str(),
			getExporterFileName( sceneFileName ).c_str(),
			Abc::ErrorHandler::kThrowPolicy);
    }
    catch(Alembic::Util::Exception& e)
    {
        std::string exc(e.what());
		ESS_LOG_ERROR("[alembic] Error writing to file: "<<e.what());
        return false;
    }

    // get the frame rate
    mFrameRate = static_cast<float>(GetFrameRate());
    if(mFrameRate == 0.0f)
    {
        mFrameRate = 25.0f;
    }

    std::vector<AbcA::chrono_t> frames;
    for(LONG i=0;i<mFrames.size();i++)
    {
        frames.push_back(mFrames[i] / mFrameRate);
    }

    // create the sampling
    double timePerSample = 1.0 / mFrameRate;
    if(frames.size() > 1)
    {
		 if( ! HasAlembicWriterLicense() )
		 {
			 if(frames.size() > 75)
			 {
				frames.resize(75);
				ESS_LOG_WARNING("[ExocortexAlembic] Writer license not found: Maximum exportable samplecount is 75!");
			 }
		 }

	    double timePerCycle = frames[frames.size()-1] - frames[0];
        AbcA::TimeSamplingType samplingType((boost::uint32_t)frames.size(),timePerCycle);
        AbcA::TimeSampling sampling(samplingType,frames);
        mTs = mArchive.addTimeSampling(sampling);
    }
    else
    {
        AbcA::TimeSampling sampling(1.0,frames[0]);
        mTs = mArchive.addTimeSampling(sampling);
    }

    m_ArchiveBoxProp = AbcG::CreateOArchiveBounds(mArchive,mTs);

	const bool bParticleMesh = GetOption("exportParticlesAsMesh");
	const bool bFlattenHierarchy = GetOption("flattenHierarchy");
	const bool bTransformCache = GetOption("transformCache");

	if(bTransformCache){
		for( int i = 0; i < mSelection.objectEntries.size(); i ++ ) {
			ObjectEntry *object = &( mSelection.objectEntries[i] );

			if (GetOption("exportSelected") && !object->entry.node->Selected())
				continue;

			int type = object->entry.type;
			if (type == OBTYPE_MESH ||
				type == OBTYPE_CAMERA ||
				(type == OBTYPE_DUMMY && !bFlattenHierarchy)||
				type == OBTYPE_POINTS ||
				type == OBTYPE_CURVES)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicXForm(object->entry,this));
				AddObject(ptr);
			}
		}
	}else{
		for( int i = 0; i < mSelection.objectEntries.size(); i ++ ) {
			ObjectEntry *object = &( mSelection.objectEntries[i] );

			if (GetOption("exportSelected") && !object->entry.node->Selected())
				continue;

			int type = object->entry.type;
			if (type == OBTYPE_MESH || (bParticleMesh && type == OBTYPE_POINTS) )
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicPolyMesh(object->entry,this));
				AddObject(ptr);
			}
			else if (type == OBTYPE_CAMERA)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicCamera(object->entry,this));
				AddObject(ptr);
			}
			else if (type == OBTYPE_DUMMY && !bFlattenHierarchy)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicXForm(object->entry,this));
				AddObject(ptr);
			}
			else if (type == OBTYPE_POINTS && !bParticleMesh)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicPoints(object->entry,this));
				AddObject(ptr);
			}
			else if (type == OBTYPE_CURVES)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicCurves(object->entry,this));
				AddObject(ptr);
			}
		}
	}

    return true;
}

void AlembicWriteJob::AddObject(AlembicObjectPtr obj)
{
    mObjects.push_back(obj);
}

bool AlembicWriteJob::Process(double frame)
{
    bool result = false;

    for(size_t i=0;i<mFrames.size();i++)
    {
        // compare the frames
        if(abs(mFrames[i] - frame) > 0.001)
        {
            continue;
        }

        // run the export for all objects
        m_Archivebbox.makeEmpty();

        // run the export for all objects
        for(size_t j=0; j < mObjects.size(); j++)
        {
            bool status = mObjects[j]->Save(mFrames[i], i == (mFrames.size()-1) );
            if(status != true)
            {
                return status;
            }
            result = true;
        }

        // Set the archive bounds bounding box
        m_ArchiveBoxProp.set(m_Archivebbox);
    }

    return result;
}
<commit_msg>fixed #308<commit_after>#include "stdafx.h"
#include "Alembic.h"

#include "AlembicWriteJob.h"
#include "ObjectList.h"

#include "SceneEnumProc.h"
#include "AlembicPolyMsh.h"
#include "AlembicXForm.h"
#include "AlembicCamera.h"
#include "AlembicPoints.h"
#include "AlembicCurves.h"
#include "CommonUtilities.h"

AlembicWriteJob::AlembicWriteJob(const std::string &in_FileName, const ObjectList &in_Selection, const std::vector<double> &in_Frames, Interface *i)
{
    mApplication = i;
	mMeshErrors = 0;
    mFileName = in_FileName;
    mSelection = in_Selection;

    for(int i=0; i < in_Frames.size(); i++)
    {
        mFrames.push_back(in_Frames[i]);
    }
}

AlembicWriteJob::~AlembicWriteJob()
{
}

void AlembicWriteJob::SetOption(const std::string & in_Name, const bool & in_Value)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    if(it == mOptions.end())
    {
        mOptions.insert(std::pair<std::string,bool>(in_Name,in_Value));
    }
    else
    {
        it->second = in_Value;
    }
}

bool AlembicWriteJob::HasOption(const std::string & in_Name)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    return it != mOptions.end();
}

bool AlembicWriteJob::GetOption(const std::string & in_Name)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    if(it != mOptions.end())
    {
        return it->second;
    }
    return false;
}

bool AlembicWriteJob::PreProcess()
{
    // check filenames
    if(mFileName.empty())
    {
        ESS_LOG_WARNING("[alembic] No filename specified.");
        return false;
    }

    // check objects
    if(mSelection.Count() == 0)
    {
        ESS_LOG_WARNING("[alembic] No objects specified.");
        return false;
    }

    // check frames
    if(mFrames.size() == 0)
    {
        ESS_LOG_WARNING("[alembic] No frames specified.");
        return false;
    }

    // init archive (use a locally scoped archive)
    std::string sceneFileName = "";
    sceneFileName.append( EC_MSTR_to_UTF8( mApplication->GetCurFilePath() ) );
    try
    {
        mArchive = CreateArchiveWithInfo(
			Alembic::AbcCoreHDF5::WriteArchive( true ),
			mFileName.c_str(),
			getExporterName( "3DS Max " EC_QUOTE( crate_Max_Version ) ).c_str(),
			getExporterFileName( sceneFileName ).c_str(),
			Abc::ErrorHandler::kThrowPolicy);
    }
    catch(Alembic::Util::Exception& e)
    {
        std::string exc(e.what());
		ESS_LOG_ERROR("[alembic] Error writing to file: "<<e.what());
        return false;
    }

    // get the frame rate
    mFrameRate = static_cast<float>(GetFrameRate());
    if(mFrameRate == 0.0f)
    {
        mFrameRate = 25.0f;
    }

    std::vector<AbcA::chrono_t> frames;
    for(LONG i=0;i<mFrames.size();i++)
    {
        frames.push_back(mFrames[i] / mFrameRate);
    }

    // create the sampling
    double timePerSample = 1.0 / mFrameRate;
    if(frames.size() > 1)
    {
		 if( ! HasAlembicWriterLicense() )
		 {
			 if(frames.size() > 75)
			 {
				frames.resize(75);
				ESS_LOG_WARNING("[ExocortexAlembic] Writer license not found: Maximum exportable samplecount is 75!");
			 }
		 }

	    double timePerCycle = frames[frames.size()-1] - frames[0];
        AbcA::TimeSamplingType samplingType((boost::uint32_t)frames.size(),timePerCycle);
        AbcA::TimeSampling sampling(samplingType,frames);
        mTs = mArchive.addTimeSampling(sampling);
    }
    else
    {
        AbcA::TimeSampling sampling(1.0,frames[0]);
        mTs = mArchive.addTimeSampling(sampling);
    }

    m_ArchiveBoxProp = AbcG::CreateOArchiveBounds(mArchive,mTs);

	const bool bParticleMesh = GetOption("exportParticlesAsMesh");
	const bool bFlattenHierarchy = GetOption("flattenHierarchy");
	const bool bTransformCache = GetOption("transformCache");

	if(bTransformCache){
		for( int i = 0; i < mSelection.objectEntries.size(); i ++ ) {
			ObjectEntry *object = &( mSelection.objectEntries[i] );

			if (GetOption("exportSelected") && !object->entry.node->Selected())
				continue;

			int type = object->entry.type;
			if (type == OBTYPE_MESH ||
				type == OBTYPE_CAMERA ||
				(type == OBTYPE_DUMMY && !bFlattenHierarchy)||
				type == OBTYPE_POINTS ||
				type == OBTYPE_CURVES)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicXForm(object->entry,this));
				AddObject(ptr);
			}
		}
	}else{
		for( int i = 0; i < mSelection.objectEntries.size(); i ++ ) {
			ObjectEntry *object = &( mSelection.objectEntries[i] );

			if (GetOption("exportSelected") && !object->entry.node->Selected())
				continue;

			int type = object->entry.type;
			if (type == OBTYPE_MESH || (bParticleMesh && type == OBTYPE_POINTS) )
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicPolyMesh(object->entry,this));
				AddObject(ptr);
			}
			else if (type == OBTYPE_CAMERA)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicCamera(object->entry,this));
				AddObject(ptr);
			}
			else if (type == OBTYPE_DUMMY && !bFlattenHierarchy)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicXForm(object->entry,this));
				AddObject(ptr);
			}
			else if (type == OBTYPE_POINTS && !bParticleMesh)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicPoints(object->entry,this));
				AddObject(ptr);
			}
			else if (type == OBTYPE_CURVES)
			{
				AlembicObjectPtr ptr;
				ptr.reset(new AlembicCurves(object->entry,this));
				AddObject(ptr);
			}
		}
	}

    return true;
}

void AlembicWriteJob::AddObject(AlembicObjectPtr obj)
{
    mObjects.push_back(obj);
}

bool AlembicWriteJob::Process(double frame)
{
    bool result = false;

    for(size_t i=0;i<mFrames.size();i++)
    {
        // compare the frames
        if(abs(mFrames[i] - frame) > 0.001)
        {
            continue;
        }

        // run the export for all objects
        m_Archivebbox.makeEmpty();

        // run the export for all objects
        for(size_t j=0; j < mObjects.size(); j++)
        {
            bool status = mObjects[j]->Save(mFrames[i], i == (mFrames.size()-1) );
            if(status != true)
            {
                return status;
            }
            result = true;
        }

        // Set the archive bounds bounding box
        m_ArchiveBoxProp.set(m_Archivebbox);
    }

    return result;
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Alembic.h"

#include "AlembicWriteJob.h"
#include "ObjectList.h"

#include "SceneEnumProc.h"
#include "AlembicPolyMsh.h"
#include "AlembicXForm.h"
#include "AlembicCamera.h"
#include "AlembicPoints.h"
#include "AlembicCurves.h"
#include "CommonUtilities.h"
#include "CommonSubtreeMerge.h"

AlembicWriteJob::AlembicWriteJob(const std::string &in_FileName, std::map<std::string, bool>& objectsMap, const std::vector<double> &in_Frames, Interface *i)
{
    mApplication = i;
	mMeshErrors = 0;
    mFileName = in_FileName;
    mObjectsMap = objectsMap;

    for(int i=0; i < in_Frames.size(); i++)
    {
        mFrames.push_back(in_Frames[i]);
    }
}

AlembicWriteJob::~AlembicWriteJob()
{
}

void AlembicWriteJob::SetOption(const std::string & in_Name, const bool & in_Value)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    if(it == mOptions.end())
    {
        mOptions.insert(std::pair<std::string,bool>(in_Name,in_Value));
    }
    else
    {
        it->second = in_Value;
    }
}

bool AlembicWriteJob::HasOption(const std::string & in_Name)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    return it != mOptions.end();
}

bool AlembicWriteJob::GetOption(const std::string & in_Name)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    if(it != mOptions.end())
    {
        return it->second;
    }
    return false;
}

struct PreProcessStackElement
{
   SceneNodePtr eNode;
   Abc::OObject oParent;

   PreProcessStackElement(SceneNodePtr enode, Abc::OObject parent):eNode(enode), oParent(parent)
   {}
};

bool AlembicWriteJob::PreProcess()
{
    // check filenames
    if(mFileName.empty())
    {
        ESS_LOG_WARNING("[alembic] No filename specified.");
        return false;
    }

    //// check objects
    //if(mSelection.Count() == 0)
    //{
    //    ESS_LOG_WARNING("[alembic] No objects specified.");
    //    return false;
    //}

    // check frames
    if(mFrames.size() == 0)
    {
        ESS_LOG_WARNING("[alembic] No frames specified.");
        return false;
    }

    const bool bUseOgawa = (bool)GetOption("useOgawa");

    // init archive (use a locally scoped archive)
    std::string sceneFileName = "";
    sceneFileName.append( EC_MSTR_to_UTF8( mApplication->GetCurFilePath() ) );
    try
    {
       if(bUseOgawa){
        mArchive = CreateArchiveWithInfo(
            Alembic::AbcCoreOgawa::WriteArchive(),
			mFileName.c_str(),
			getExporterName( "3DS Max " EC_QUOTE( crate_Max_Version ) ).c_str(),
			getExporterFileName( sceneFileName ).c_str(),
			Abc::ErrorHandler::kThrowPolicy);
       }
       else{
        mArchive = CreateArchiveWithInfo(
			Alembic::AbcCoreHDF5::WriteArchive( true ),
			mFileName.c_str(),
			getExporterName( "3DS Max " EC_QUOTE( crate_Max_Version ) ).c_str(),
			getExporterFileName( sceneFileName ).c_str(),
			Abc::ErrorHandler::kThrowPolicy);
       }

    }
    catch(Alembic::Util::Exception& e)
    {
        std::string exc(e.what());
		    ESS_LOG_ERROR("[alembic] Error writing to file: "<<e.what());
        return false;
    }

    // get the frame rate
    mFrameRate = static_cast<float>(GetFrameRate());
    if(mFrameRate == 0.0f)
    {
        mFrameRate = 25.0f;
    }

    std::vector<AbcA::chrono_t> frames;
    for(LONG i=0;i<mFrames.size();i++)
    {
        frames.push_back(mFrames[i] / mFrameRate);
    }

    // create the sampling
    double timePerSample = 1.0 / mFrameRate;
    if(frames.size() > 1)
    {
		 if( ! HasAlembicWriterLicense() )
		 {
       if( HasAlembicInvalidLicense() ) {
          ESS_LOG_ERROR("[alembic] No license available and EXOCORTEX_ALEMBIC_NO_DEMO defined, aborting." );
          return false;
       }
			 if(frames.size() > 75)
			 {
				frames.resize(75);
				ESS_LOG_WARNING("[ExocortexAlembic] Writer license not found: Maximum exportable samplecount is 75!");
			 }
		 }

	    double timePerCycle = frames[frames.size()-1] - frames[0];
        AbcA::TimeSamplingType samplingType((boost::uint32_t)frames.size(),timePerCycle);
        AbcA::TimeSampling sampling(samplingType,frames);
        mTs = mArchive.addTimeSampling(sampling);
    }
    else
    {
        AbcA::TimeSampling sampling(1.0,frames[0]);
        mTs = mArchive.addTimeSampling(sampling);
    }

    m_ArchiveBoxProp = AbcG::CreateOArchiveBounds(mArchive,mTs);

	const bool bParticleMesh = GetOption("exportParticlesAsMesh");
   bool bMergePolyMeshSubtree = GetOption("mergePolyMeshSubtree");

   bool bSelectParents = GetOption("includeParentNodes");/*|| !bFlattenHierarchy || bTransformCache*/
   const bool bSelectChildren = false;
   bool bTransformCache = GetOption("transformCache");
   const bool bFlattenHierarchy = GetOption("flattenHierarchy");

   if(bMergePolyMeshSubtree){
      bTransformCache = false;
      //bSelectParents = true;
   }

   bcsgSelection::types buildSelection = bcsgSelection::ALL;

   const bool bExportSelected = GetOption("exportSelected");
   const bool bObjectsParameterExists = GetOption("objectsParameterExists");
   if(bExportSelected){
      //copy max selection
      buildSelection = bcsgSelection::APP;
   }
   else if(bObjectsParameterExists){
      //select nothing when building, fill in later from parameter data
      buildSelection = bcsgSelection::NONE;
   }
   else{
      //select everything
   }

   int nNumNodes = 0;
   exoSceneRoot = buildCommonSceneGraph(nNumNodes, true, buildSelection);
   //WARNING ILM robot right crashes when printing
   //printSceneGraph(exoSceneRoot, false);

   if(bObjectsParameterExists){
      //Might be better to use refineSelection here, but call a function that sets up dccSelected flag first, then delete this function from codebase
      selectNodes(exoSceneRoot, mObjectsMap,  bSelectParents, bSelectChildren, !bTransformCache);

      bool bAllResolved = true;

      if(bObjectsParameterExists){
         for(SceneNode::SelectionT::iterator it = mObjectsMap.begin(); it != mObjectsMap.end(); it++){
            if(it->second == false){
               bAllResolved = false;
               ESS_LOG_WARNING("Could not resolve objects identifier: "<<it->first);
            }
         }
      }

      if(bAllResolved){
         removeUnselectedNodes(exoSceneRoot);
      }
   }
   else if(bExportSelected){
      refineSelection(exoSceneRoot, bSelectParents, bSelectChildren, !bTransformCache);
      removeUnselectedNodes(exoSceneRoot);
   }

   if(bMergePolyMeshSubtree){
      replacePolyMeshSubtree<SceneNodeMaxPtr, SceneNodeMax>(exoSceneRoot);
   }

   if(bFlattenHierarchy){
      nNumNodes = 0;
      flattenSceneGraph(exoSceneRoot, nNumNodes);
   }

   if(GetOption("renameConflictingNodes")){
      renameConflictingNodes(exoSceneRoot);
   }

   std::list<PreProcessStackElement> sceneStack;

   sceneStack.push_back(PreProcessStackElement(exoSceneRoot, mArchive.getTop()));

   try{

   while( !sceneStack.empty() )
   {

      PreProcessStackElement sElement = sceneStack.back();
      SceneNodePtr eNode = sElement.eNode;
      sceneStack.pop_back();

      Abc::OObject oParent = sElement.oParent;
      Abc::OObject oNewParent;

      AlembicObjectPtr pNewObject;

      if(eNode->type == SceneNode::SCENE_ROOT){
         //we do not want to export the Scene_Root (the alembic archive has one already)
      }
      else if(eNode->type == SceneNode::ITRANSFORM || eNode->type == SceneNode::ETRANSFORM){
         pNewObject.reset(new AlembicXForm(eNode, this, oParent));
      }
      else if(eNode->type == SceneNode::CAMERA){
         pNewObject.reset(new AlembicCamera(eNode, this, oParent));
      }
      else if(eNode->type == SceneNode::POLYMESH || eNode->type == SceneNode::POLYMESH_SUBTREE){
         pNewObject.reset(new AlembicPolyMesh(eNode, this, oParent));
      }
      //TODO: as far I recall we dont support SUBD. verify...
      //else if(eNode->type == SceneNode::SUBD){
      //   pNewObject.reset(new AlembicSubD(eNode, this, oParent));
      //}
      else if(eNode->type == SceneNode::CURVES){
         pNewObject.reset(new AlembicCurves(eNode, this, oParent));
      }
      else if(eNode->type == SceneNode::PARTICLES || eNode->type == SceneNode::PARTICLES_TP){
         if(bParticleMesh){
            pNewObject.reset(new AlembicPolyMesh(eNode, this, oParent));
         }
         else{
            pNewObject.reset(new AlembicPoints(eNode, this, oParent));
         }
      }
      //else{
      //   ESS_LOG_WARNING("Unknown type: not exporting "<<eNode->name);//Export as transform, and give warning?
      //}

      if(pNewObject){
         //add the AlembicObject to export list if it is not being skipped
         AddObject(pNewObject);
      }

      if(pNewObject){
         oNewParent = oParent.getChild(eNode->name);
      }
      else{ //this case should be unecessary
         //if we skip node A, we parent node A's children to the parent of A
         oNewParent = oParent;
      }

      if(oNewParent.valid()){
         for( std::list<SceneNodePtr>::iterator it = eNode->children.begin(); it != eNode->children.end(); it++){
            sceneStack.push_back(PreProcessStackElement(*it, oNewParent));
         }
      }
      else{
         ESS_LOG_ERROR("Do not have refernce to parent.");
         return false;
      }
   }

   }catch( std::exception& exp ){
      ESS_LOG_ERROR("An std::exception occured: "<<exp.what());
      return false;
   }catch(...){
      ESS_LOG_ERROR("Exception ecountered when exporting.");
   }

   if(mObjects.empty()){
      ESS_LOG_ERROR("No objects specified.");
      return false;
   }

   return true;
}

void AlembicWriteJob::AddObject(AlembicObjectPtr obj)
{
    mObjects.push_back(obj);
}

bool AlembicWriteJob::Process(double frame)
{
    bool result = false;

    for(size_t i=0;i<mFrames.size();i++)
    {
        // compare the frames
        if(abs(mFrames[i] - frame) > 0.001)
        {
            continue;
        }

        // run the export for all objects
        m_Archivebbox.makeEmpty();

        // run the export for all objects
        for(size_t j=0; j < mObjects.size(); j++)
        {
            bool status = mObjects[j]->Save(mFrames[i], i == (mFrames.size()-1) );
            if(status != true)
            {
                return status;
            }
            result = true;
        }

        // Set the archive bounds bounding box
        m_ArchiveBoxProp.set(m_Archivebbox);
    }

    return result;
}
<commit_msg>throw error if object parameter path does not resolve (Issue #471)<commit_after>#include "stdafx.h"
#include "Alembic.h"

#include "AlembicWriteJob.h"
#include "ObjectList.h"

#include "SceneEnumProc.h"
#include "AlembicPolyMsh.h"
#include "AlembicXForm.h"
#include "AlembicCamera.h"
#include "AlembicPoints.h"
#include "AlembicCurves.h"
#include "CommonUtilities.h"
#include "CommonSubtreeMerge.h"

AlembicWriteJob::AlembicWriteJob(const std::string &in_FileName, std::map<std::string, bool>& objectsMap, const std::vector<double> &in_Frames, Interface *i)
{
    mApplication = i;
	mMeshErrors = 0;
    mFileName = in_FileName;
    mObjectsMap = objectsMap;

    for(int i=0; i < in_Frames.size(); i++)
    {
        mFrames.push_back(in_Frames[i]);
    }
}

AlembicWriteJob::~AlembicWriteJob()
{
}

void AlembicWriteJob::SetOption(const std::string & in_Name, const bool & in_Value)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    if(it == mOptions.end())
    {
        mOptions.insert(std::pair<std::string,bool>(in_Name,in_Value));
    }
    else
    {
        it->second = in_Value;
    }
}

bool AlembicWriteJob::HasOption(const std::string & in_Name)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    return it != mOptions.end();
}

bool AlembicWriteJob::GetOption(const std::string & in_Name)
{
    std::map<std::string,bool>::iterator it = mOptions.find(in_Name);
    if(it != mOptions.end())
    {
        return it->second;
    }
    return false;
}

struct PreProcessStackElement
{
   SceneNodePtr eNode;
   Abc::OObject oParent;

   PreProcessStackElement(SceneNodePtr enode, Abc::OObject parent):eNode(enode), oParent(parent)
   {}
};

bool AlembicWriteJob::PreProcess()
{
    // check filenames
    if(mFileName.empty())
    {
        ESS_LOG_WARNING("[alembic] No filename specified.");
        return false;
    }

    //// check objects
    //if(mSelection.Count() == 0)
    //{
    //    ESS_LOG_WARNING("[alembic] No objects specified.");
    //    return false;
    //}

    // check frames
    if(mFrames.size() == 0)
    {
        ESS_LOG_WARNING("[alembic] No frames specified.");
        return false;
    }

    const bool bUseOgawa = (bool)GetOption("useOgawa");

    // init archive (use a locally scoped archive)
    std::string sceneFileName = "";
    sceneFileName.append( EC_MSTR_to_UTF8( mApplication->GetCurFilePath() ) );
    try
    {
       if(bUseOgawa){
        mArchive = CreateArchiveWithInfo(
            Alembic::AbcCoreOgawa::WriteArchive(),
			mFileName.c_str(),
			getExporterName( "3DS Max " EC_QUOTE( crate_Max_Version ) ).c_str(),
			getExporterFileName( sceneFileName ).c_str(),
			Abc::ErrorHandler::kThrowPolicy);
       }
       else{
        mArchive = CreateArchiveWithInfo(
			Alembic::AbcCoreHDF5::WriteArchive( true ),
			mFileName.c_str(),
			getExporterName( "3DS Max " EC_QUOTE( crate_Max_Version ) ).c_str(),
			getExporterFileName( sceneFileName ).c_str(),
			Abc::ErrorHandler::kThrowPolicy);
       }

    }
    catch(Alembic::Util::Exception& e)
    {
        std::string exc(e.what());
		    ESS_LOG_ERROR("[alembic] Error writing to file: "<<e.what());
        return false;
    }

    // get the frame rate
    mFrameRate = static_cast<float>(GetFrameRate());
    if(mFrameRate == 0.0f)
    {
        mFrameRate = 25.0f;
    }

    std::vector<AbcA::chrono_t> frames;
    for(LONG i=0;i<mFrames.size();i++)
    {
        frames.push_back(mFrames[i] / mFrameRate);
    }

    // create the sampling
    double timePerSample = 1.0 / mFrameRate;
    if(frames.size() > 1)
    {
		 if( ! HasAlembicWriterLicense() )
		 {
       if( HasAlembicInvalidLicense() ) {
          ESS_LOG_ERROR("[alembic] No license available and EXOCORTEX_ALEMBIC_NO_DEMO defined, aborting." );
          return false;
       }
			 if(frames.size() > 75)
			 {
				frames.resize(75);
				ESS_LOG_WARNING("[ExocortexAlembic] Writer license not found: Maximum exportable samplecount is 75!");
			 }
		 }

	    double timePerCycle = frames[frames.size()-1] - frames[0];
        AbcA::TimeSamplingType samplingType((boost::uint32_t)frames.size(),timePerCycle);
        AbcA::TimeSampling sampling(samplingType,frames);
        mTs = mArchive.addTimeSampling(sampling);
    }
    else
    {
        AbcA::TimeSampling sampling(1.0,frames[0]);
        mTs = mArchive.addTimeSampling(sampling);
    }

    m_ArchiveBoxProp = AbcG::CreateOArchiveBounds(mArchive,mTs);

	const bool bParticleMesh = GetOption("exportParticlesAsMesh");
   bool bMergePolyMeshSubtree = GetOption("mergePolyMeshSubtree");

   bool bSelectParents = GetOption("includeParentNodes");/*|| !bFlattenHierarchy || bTransformCache*/
   const bool bSelectChildren = false;
   bool bTransformCache = GetOption("transformCache");
   const bool bFlattenHierarchy = GetOption("flattenHierarchy");

   if(bMergePolyMeshSubtree){
      bTransformCache = false;
      //bSelectParents = true;
   }

   bcsgSelection::types buildSelection = bcsgSelection::ALL;

   const bool bExportSelected = GetOption("exportSelected");
   const bool bObjectsParameterExists = GetOption("objectsParameterExists");
   if(bExportSelected){
      //copy max selection
      buildSelection = bcsgSelection::APP;
   }
   else if(bObjectsParameterExists){
      //select nothing when building, fill in later from parameter data
      buildSelection = bcsgSelection::NONE;
   }
   else{
      //select everything
   }

   int nNumNodes = 0;
   exoSceneRoot = buildCommonSceneGraph(nNumNodes, true, buildSelection);
   //WARNING ILM robot right crashes when printing
   //printSceneGraph(exoSceneRoot, false);

   if(bObjectsParameterExists){
      //Might be better to use refineSelection here, but call a function that sets up dccSelected flag first, then delete this function from codebase
      selectNodes(exoSceneRoot, mObjectsMap,  bSelectParents, bSelectChildren, !bTransformCache);

      bool bAllResolved = true;

      if(bObjectsParameterExists){
         for(SceneNode::SelectionT::iterator it = mObjectsMap.begin(); it != mObjectsMap.end(); it++){
            if(it->second == false){
               bAllResolved = false;
               ESS_LOG_ERROR("Could not resolve objects identifier: "<<it->first);
            }
         }
      }

      if(bAllResolved){
         removeUnselectedNodes(exoSceneRoot);
      }
      else{
         return false;
      }
   }
   else if(bExportSelected){
      refineSelection(exoSceneRoot, bSelectParents, bSelectChildren, !bTransformCache);
      removeUnselectedNodes(exoSceneRoot);
   }

   if(bMergePolyMeshSubtree){
      replacePolyMeshSubtree<SceneNodeMaxPtr, SceneNodeMax>(exoSceneRoot);
   }

   if(bFlattenHierarchy){
      nNumNodes = 0;
      flattenSceneGraph(exoSceneRoot, nNumNodes);
   }

   if(GetOption("renameConflictingNodes")){
      renameConflictingNodes(exoSceneRoot);
   }

   std::list<PreProcessStackElement> sceneStack;

   sceneStack.push_back(PreProcessStackElement(exoSceneRoot, mArchive.getTop()));

   try{

   while( !sceneStack.empty() )
   {

      PreProcessStackElement sElement = sceneStack.back();
      SceneNodePtr eNode = sElement.eNode;
      sceneStack.pop_back();

      Abc::OObject oParent = sElement.oParent;
      Abc::OObject oNewParent;

      AlembicObjectPtr pNewObject;

      if(eNode->type == SceneNode::SCENE_ROOT){
         //we do not want to export the Scene_Root (the alembic archive has one already)
      }
      else if(eNode->type == SceneNode::ITRANSFORM || eNode->type == SceneNode::ETRANSFORM){
         pNewObject.reset(new AlembicXForm(eNode, this, oParent));
      }
      else if(eNode->type == SceneNode::CAMERA){
         pNewObject.reset(new AlembicCamera(eNode, this, oParent));
      }
      else if(eNode->type == SceneNode::POLYMESH || eNode->type == SceneNode::POLYMESH_SUBTREE){
         pNewObject.reset(new AlembicPolyMesh(eNode, this, oParent));
      }
      //TODO: as far I recall we dont support SUBD. verify...
      //else if(eNode->type == SceneNode::SUBD){
      //   pNewObject.reset(new AlembicSubD(eNode, this, oParent));
      //}
      else if(eNode->type == SceneNode::CURVES){
         pNewObject.reset(new AlembicCurves(eNode, this, oParent));
      }
      else if(eNode->type == SceneNode::PARTICLES || eNode->type == SceneNode::PARTICLES_TP){
         if(bParticleMesh){
            pNewObject.reset(new AlembicPolyMesh(eNode, this, oParent));
         }
         else{
            pNewObject.reset(new AlembicPoints(eNode, this, oParent));
         }
      }
      //else{
      //   ESS_LOG_WARNING("Unknown type: not exporting "<<eNode->name);//Export as transform, and give warning?
      //}

      if(pNewObject){
         //add the AlembicObject to export list if it is not being skipped
         AddObject(pNewObject);
      }

      if(pNewObject){
         oNewParent = oParent.getChild(eNode->name);
      }
      else{ //this case should be unecessary
         //if we skip node A, we parent node A's children to the parent of A
         oNewParent = oParent;
      }

      if(oNewParent.valid()){
         for( std::list<SceneNodePtr>::iterator it = eNode->children.begin(); it != eNode->children.end(); it++){
            sceneStack.push_back(PreProcessStackElement(*it, oNewParent));
         }
      }
      else{
         ESS_LOG_ERROR("Do not have refernce to parent.");
         return false;
      }
   }

   }catch( std::exception& exp ){
      ESS_LOG_ERROR("An std::exception occured: "<<exp.what());
      return false;
   }catch(...){
      ESS_LOG_ERROR("Exception ecountered when exporting.");
   }

   if(mObjects.empty()){
      ESS_LOG_ERROR("No objects specified.");
      return false;
   }

   return true;
}

void AlembicWriteJob::AddObject(AlembicObjectPtr obj)
{
    mObjects.push_back(obj);
}

bool AlembicWriteJob::Process(double frame)
{
    bool result = false;

    for(size_t i=0;i<mFrames.size();i++)
    {
        // compare the frames
        if(abs(mFrames[i] - frame) > 0.001)
        {
            continue;
        }

        // run the export for all objects
        m_Archivebbox.makeEmpty();

        // run the export for all objects
        for(size_t j=0; j < mObjects.size(); j++)
        {
            bool status = mObjects[j]->Save(mFrames[i], i == (mFrames.size()-1) );
            if(status != true)
            {
                return status;
            }
            result = true;
        }

        // Set the archive bounds bounding box
        m_ArchiveBoxProp.set(m_Archivebbox);
    }

    return result;
}
<|endoftext|>


<commit_before>#include "Manager.hpp"

#include "../../controllers/main/typedefs.hpp"
#include "../../controllers/main/events/PacketReceived.hpp"

using namespace tin::network::sniffer;

Manager::Manager(
    tin::network::sniffer::ManagerQueue& incomingQueue,
    tin::controllers::main::ControllerQueue& controllerQueue,
    std::string device,
    std::string expression
):
QueueThread(incomingQueue, ManagerVisitor(*this)),
sniffer(device, expression),
controllerQueue(controllerQueue)
{
    this->sniffer.run();

    this->sniffer.attachPacketReceivedHandler([this](const tin::utils::Packet::ptr& packet) {
        this->controllerQueue.push(
            tin::controllers::main::EventPtr(new tin::controllers::main::events::PacketReceived(packet))
        );
    });
}
<commit_msg>Do not autorun sniffer<commit_after>#include "Manager.hpp"

#include "../../controllers/main/typedefs.hpp"
#include "../../controllers/main/events/PacketReceived.hpp"

using namespace tin::network::sniffer;

Manager::Manager(
    tin::network::sniffer::ManagerQueue& incomingQueue,
    tin::controllers::main::ControllerQueue& controllerQueue,
    std::string device,
    std::string expression
):
QueueThread(incomingQueue, ManagerVisitor(*this)),
sniffer(device, expression),
controllerQueue(controllerQueue)
{
    this->sniffer.attachPacketReceivedHandler([this](const tin::utils::Packet::ptr& packet) {
        this->controllerQueue.push(
            tin::controllers::main::EventPtr(new tin::controllers::main::events::PacketReceived(packet))
        );
    });
}
<|endoftext|>


<commit_before>#include <assimp/cexport.h>
#include <boost/filesystem.hpp>
#include <Eigen/StdVector>
#include <dart/dynamics/dynamics.h>
#include <aikido/rviz/shape_conversions.hpp>
#include <aikido/rviz/ResourceServer.hpp>

using dart::dynamics::Shape;
using dart::dynamics::BoxShape;
using dart::dynamics::CylinderShape;
using dart::dynamics::EllipsoidShape;
using dart::dynamics::LineSegmentShape;
using dart::dynamics::MeshShape;
using dart::dynamics::PlaneShape;
using dart::dynamics::SoftMeshShape;
using visualization_msgs::Marker;

namespace aikido {
namespace rviz {

geometry_msgs::Point convertEigenToROSPoint(Eigen::Vector3d const &v)
{
  geometry_msgs::Point v_ros;
  v_ros.x = v[0];
  v_ros.y = v[1];
  v_ros.z = v[2];
  return v_ros;
}

geometry_msgs::Vector3 convertEigenToROSVector3(Eigen::Vector3d const &v)
{
  geometry_msgs::Vector3 v_ros;
  v_ros.x = v[0];
  v_ros.y = v[1];
  v_ros.z = v[2];
  return v_ros;
}

std_msgs::ColorRGBA convertEigenToROSColorRGBA(Eigen::Vector4d const &v)
{
  std_msgs::ColorRGBA v_ros;
  v_ros.r = v[0];
  v_ros.g = v[1];
  v_ros.b = v[2];
  v_ros.a = v[3];
  return v_ros;
}

geometry_msgs::Quaternion convertEigenToROSQuaternion(Eigen::Quaterniond const &v)
{
  geometry_msgs::Quaternion v_ros;
  v_ros.w = v.w();
  v_ros.x = v.x();
  v_ros.y = v.y();
  v_ros.z = v.z();
  return v_ros;
}

geometry_msgs::Pose convertEigenToROSPose(Eigen::Isometry3d const &v)
{
  Eigen::Quaterniond const quaternion(v.rotation());

  geometry_msgs::Pose v_ros;
  v_ros.orientation = convertEigenToROSQuaternion(quaternion);
  v_ros.position = convertEigenToROSPoint(v.translation());
  return v_ros;
}

bool convertAssimpMeshToROSTriangleList(
  aiMesh const &mesh, std::vector<geometry_msgs::Point> *triangle_list)
{
  triangle_list->reserve(triangle_list->size() + 3 * mesh.mNumFaces);

  for (unsigned int iface = 0; iface < mesh.mNumFaces; ++iface) {
    aiFace const &face = mesh.mFaces[iface];

    if (face.mNumIndices != 3) {
      return false;
    }

    for (unsigned int i = 0; i < 3; ++i) {
      unsigned int ivertex = face.mIndices[i];
      aiVector3D const &vertex = mesh.mVertices[ivertex];

      geometry_msgs::Point ros_vertex;
      ros_vertex.x = vertex.x;
      ros_vertex.y = vertex.y;
      ros_vertex.z = vertex.z;

      triangle_list->push_back(ros_vertex);
    }
  }
  return false;
}

bool convertShape(BoxShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->type = Marker::CUBE;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->scale = convertEigenToROSVector3(shape.getSize());
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());
  return true;
}

bool convertShape(CylinderShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->type = Marker::CYLINDER;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->scale.x = shape.getRadius();
  marker->scale.y = shape.getRadius();
  marker->scale.z = shape.getHeight();
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());
  return true;
}

bool convertShape(EllipsoidShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->type = Marker::SPHERE;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->scale = convertEigenToROSVector3(shape.getSize());
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());
  return true;
}

bool convertShape(LineSegmentShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  std::vector<Eigen::Vector3d> const &vertices = shape.getVertices();
  std::vector<Eigen::Vector2i, Eigen::aligned_allocator<Eigen::Vector2i> >
    const &connections = shape.getConnections();

  marker->type = Marker::LINE_STRIP;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());
  marker->scale.x = shape.getThickness();
  marker->points.reserve(2 * connections.size());

  for (Eigen::Vector2i const &connection : connections) {
    size_t const &i1 = connection[0];
    size_t const &i2 = connection[1];

    if (i1 >= connections.size() || i2 >= connections.size()) {
      return false;
    }

    Eigen::Vector3d const &p1 = vertices[i1];
    Eigen::Vector3d const &p2 = vertices[i2];
    marker->points.push_back(convertEigenToROSPoint(p1));
    marker->points.push_back(convertEigenToROSPoint(p2));
  }
  return true;
}

bool convertShape(MeshShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->scale = convertEigenToROSVector3(shape.getScale());

  aiScene const *scene = shape.getMesh();
  std::string const &meshUri = shape.getMeshUri();
  if (!meshUri.empty()) {
    marker->type = Marker::MESH_RESOURCE;
    marker->mesh_resource = meshUri;
    marker->mesh_use_embedded_materials = true;
    return true;
  }

  // Fall back on publishing the mesh as a TRIANGLE_LIST.
  if (scene) {
    marker->type = Marker::TRIANGLE_LIST;
    marker->color = convertEigenToROSColorRGBA(shape.getRGBA());

    for (unsigned int imesh = 0; imesh < scene->mNumMeshes; ++imesh) {
      if (!convertAssimpMeshToROSTriangleList(*scene->mMeshes[imesh],
                                              &marker->points)) {
        return false;
      }
    }
    return true;
  }

  return false; // Everything failed!
}

bool convertShape(PlaneShape const &shape, Marker *marker,
                  ResourceServer *resourceManager, double width)
{
  static Eigen::Matrix<double, 3, 6> const points = (
    Eigen::Matrix<double, 6, 3>() <<
      -0.5, -0.5, 0,
       0.5,  0.5, 0,
      -0.5,  0.5, 0,
      -0.5, -0.5, 0,
       0.5, -0.5, 0,
       0.5,  0.5, 0
  ).finished().transpose();

  marker->type = Marker::TRIANGLE_LIST;
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());

  Eigen::Vector3d const &normal = shape.getNormal();
  double const offset = shape.getOffset();

  // Constructing a frame on the plane at the point closest to the origin.
  Eigen::Quaterniond quat;
  quat.setFromTwoVectors(Eigen::Vector3d::UnitZ(), normal);

  Eigen::Affine3d frame(quat);
  frame.pretranslate(normal * offset);
  frame.scale(width);

  Eigen::MatrixXd const transformedPoints = frame * points;
  marker->points.resize(transformedPoints.cols());

  for (size_t i = 0; i < transformedPoints.cols(); ++i) {
    marker->points[i] = convertEigenToROSPoint(transformedPoints.col(i));
  }
  return true;
}

bool convertShape(SoftMeshShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->type = Marker::TRIANGLE_LIST;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());

  aiMesh const *mesh = shape.getAssimpMesh();
  if (mesh) {
    return convertAssimpMeshToROSTriangleList(*mesh, &marker->points);
  } else {
    return false;
  }
}

bool convertShape(Shape const &shape, Marker *marker, ResourceServer *rm)
{
  switch (shape.getShapeType()) {
  case Shape::BOX:
    return convertShape(dynamic_cast<BoxShape const &>(shape), marker, rm);

  case Shape::ELLIPSOID:
    return convertShape(dynamic_cast<EllipsoidShape const &>(shape), marker, rm);

  case Shape::CYLINDER:
    return convertShape(dynamic_cast<CylinderShape const &>(shape), marker, rm);

  case Shape::LINE_SEGMENT:
    return convertShape(dynamic_cast<LineSegmentShape const &>(shape), marker, rm);

  case Shape::MESH:
    return convertShape(dynamic_cast<MeshShape const &>(shape), marker, rm);

  case Shape::PLANE:
    return convertShape(dynamic_cast<PlaneShape const &>(shape), marker, rm);

  case Shape::SOFT_MESH:
    return convertShape(dynamic_cast<SoftMeshShape const &>(shape), marker, rm);

  default:
    return false;
  }
}

} // namespace rviz
} // namespace aikido
<commit_msg>[aikido_rviz] Fix radius vs. diameter of cylinders<commit_after>#include <assimp/cexport.h>
#include <boost/filesystem.hpp>
#include <Eigen/StdVector>
#include <dart/dynamics/dynamics.h>
#include <aikido/rviz/shape_conversions.hpp>
#include <aikido/rviz/ResourceServer.hpp>

using dart::dynamics::Shape;
using dart::dynamics::BoxShape;
using dart::dynamics::CylinderShape;
using dart::dynamics::EllipsoidShape;
using dart::dynamics::LineSegmentShape;
using dart::dynamics::MeshShape;
using dart::dynamics::PlaneShape;
using dart::dynamics::SoftMeshShape;
using visualization_msgs::Marker;

namespace aikido {
namespace rviz {

geometry_msgs::Point convertEigenToROSPoint(Eigen::Vector3d const &v)
{
  geometry_msgs::Point v_ros;
  v_ros.x = v[0];
  v_ros.y = v[1];
  v_ros.z = v[2];
  return v_ros;
}

geometry_msgs::Vector3 convertEigenToROSVector3(Eigen::Vector3d const &v)
{
  geometry_msgs::Vector3 v_ros;
  v_ros.x = v[0];
  v_ros.y = v[1];
  v_ros.z = v[2];
  return v_ros;
}

std_msgs::ColorRGBA convertEigenToROSColorRGBA(Eigen::Vector4d const &v)
{
  std_msgs::ColorRGBA v_ros;
  v_ros.r = v[0];
  v_ros.g = v[1];
  v_ros.b = v[2];
  v_ros.a = v[3];
  return v_ros;
}

geometry_msgs::Quaternion convertEigenToROSQuaternion(Eigen::Quaterniond const &v)
{
  geometry_msgs::Quaternion v_ros;
  v_ros.w = v.w();
  v_ros.x = v.x();
  v_ros.y = v.y();
  v_ros.z = v.z();
  return v_ros;
}

geometry_msgs::Pose convertEigenToROSPose(Eigen::Isometry3d const &v)
{
  Eigen::Quaterniond const quaternion(v.rotation());

  geometry_msgs::Pose v_ros;
  v_ros.orientation = convertEigenToROSQuaternion(quaternion);
  v_ros.position = convertEigenToROSPoint(v.translation());
  return v_ros;
}

bool convertAssimpMeshToROSTriangleList(
  aiMesh const &mesh, std::vector<geometry_msgs::Point> *triangle_list)
{
  triangle_list->reserve(triangle_list->size() + 3 * mesh.mNumFaces);

  for (unsigned int iface = 0; iface < mesh.mNumFaces; ++iface) {
    aiFace const &face = mesh.mFaces[iface];

    if (face.mNumIndices != 3) {
      return false;
    }

    for (unsigned int i = 0; i < 3; ++i) {
      unsigned int ivertex = face.mIndices[i];
      aiVector3D const &vertex = mesh.mVertices[ivertex];

      geometry_msgs::Point ros_vertex;
      ros_vertex.x = vertex.x;
      ros_vertex.y = vertex.y;
      ros_vertex.z = vertex.z;

      triangle_list->push_back(ros_vertex);
    }
  }
  return false;
}

bool convertShape(BoxShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->type = Marker::CUBE;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->scale = convertEigenToROSVector3(shape.getSize());
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());
  return true;
}

bool convertShape(CylinderShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->type = Marker::CYLINDER;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->scale.x = 2. * shape.getRadius();
  marker->scale.y = 2. * shape.getRadius();
  marker->scale.z = shape.getHeight();
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());
  return true;
}

bool convertShape(EllipsoidShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->type = Marker::SPHERE;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->scale = convertEigenToROSVector3(shape.getSize());
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());
  return true;
}

bool convertShape(LineSegmentShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  std::vector<Eigen::Vector3d> const &vertices = shape.getVertices();
  std::vector<Eigen::Vector2i, Eigen::aligned_allocator<Eigen::Vector2i> >
    const &connections = shape.getConnections();

  marker->type = Marker::LINE_STRIP;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());
  marker->scale.x = shape.getThickness();
  marker->points.reserve(2 * connections.size());

  for (Eigen::Vector2i const &connection : connections) {
    size_t const &i1 = connection[0];
    size_t const &i2 = connection[1];

    if (i1 >= connections.size() || i2 >= connections.size()) {
      return false;
    }

    Eigen::Vector3d const &p1 = vertices[i1];
    Eigen::Vector3d const &p2 = vertices[i2];
    marker->points.push_back(convertEigenToROSPoint(p1));
    marker->points.push_back(convertEigenToROSPoint(p2));
  }
  return true;
}

bool convertShape(MeshShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->scale = convertEigenToROSVector3(shape.getScale());

  aiScene const *scene = shape.getMesh();
  std::string const &meshUri = shape.getMeshUri();
  if (!meshUri.empty()) {
    marker->type = Marker::MESH_RESOURCE;
    marker->mesh_resource = meshUri;
    marker->mesh_use_embedded_materials = true;
    return true;
  }

  // Fall back on publishing the mesh as a TRIANGLE_LIST.
  if (scene) {
    marker->type = Marker::TRIANGLE_LIST;
    marker->color = convertEigenToROSColorRGBA(shape.getRGBA());

    for (unsigned int imesh = 0; imesh < scene->mNumMeshes; ++imesh) {
      if (!convertAssimpMeshToROSTriangleList(*scene->mMeshes[imesh],
                                              &marker->points)) {
        return false;
      }
    }
    return true;
  }

  return false; // Everything failed!
}

bool convertShape(PlaneShape const &shape, Marker *marker,
                  ResourceServer *resourceManager, double width)
{
  static Eigen::Matrix<double, 3, 6> const points = (
    Eigen::Matrix<double, 6, 3>() <<
      -0.5, -0.5, 0,
       0.5,  0.5, 0,
      -0.5,  0.5, 0,
      -0.5, -0.5, 0,
       0.5, -0.5, 0,
       0.5,  0.5, 0
  ).finished().transpose();

  marker->type = Marker::TRIANGLE_LIST;
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());

  Eigen::Vector3d const &normal = shape.getNormal();
  double const offset = shape.getOffset();

  // Constructing a frame on the plane at the point closest to the origin.
  Eigen::Quaterniond quat;
  quat.setFromTwoVectors(Eigen::Vector3d::UnitZ(), normal);

  Eigen::Affine3d frame(quat);
  frame.pretranslate(normal * offset);
  frame.scale(width);

  Eigen::MatrixXd const transformedPoints = frame * points;
  marker->points.resize(transformedPoints.cols());

  for (size_t i = 0; i < transformedPoints.cols(); ++i) {
    marker->points[i] = convertEigenToROSPoint(transformedPoints.col(i));
  }
  return true;
}

bool convertShape(SoftMeshShape const &shape, Marker *marker,
                  ResourceServer *resourceManager)
{
  marker->type = Marker::TRIANGLE_LIST;
  marker->pose = convertEigenToROSPose(shape.getLocalTransform());
  marker->color = convertEigenToROSColorRGBA(shape.getRGBA());

  aiMesh const *mesh = shape.getAssimpMesh();
  if (mesh) {
    return convertAssimpMeshToROSTriangleList(*mesh, &marker->points);
  } else {
    return false;
  }
}

bool convertShape(Shape const &shape, Marker *marker, ResourceServer *rm)
{
  switch (shape.getShapeType()) {
  case Shape::BOX:
    return convertShape(dynamic_cast<BoxShape const &>(shape), marker, rm);

  case Shape::ELLIPSOID:
    return convertShape(dynamic_cast<EllipsoidShape const &>(shape), marker, rm);

  case Shape::CYLINDER:
    return convertShape(dynamic_cast<CylinderShape const &>(shape), marker, rm);

  case Shape::LINE_SEGMENT:
    return convertShape(dynamic_cast<LineSegmentShape const &>(shape), marker, rm);

  case Shape::MESH:
    return convertShape(dynamic_cast<MeshShape const &>(shape), marker, rm);

  case Shape::PLANE:
    return convertShape(dynamic_cast<PlaneShape const &>(shape), marker, rm);

  case Shape::SOFT_MESH:
    return convertShape(dynamic_cast<SoftMeshShape const &>(shape), marker, rm);

  default:
    return false;
  }
}

} // namespace rviz
} // namespace aikido
<|endoftext|>


<commit_before>#ifndef AI_NETWORKING_H
#define AI_NETWORKING_H

#include <iostream>
#include <time.h>
#include <set>
#include <cfloat>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <bitset>
#include <assert.h>

#ifdef _WIN32
    #include <sys/types.h>
    #include <Winsock2.h>
    #include <Ws2tcpip.h>
#else
    #include <sys/socket.h>
    #include <sys/ioctl.h>
    #include <arpa/inet.h>
    #include <unistd.h>
    #include <time.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <netdb.h>
    #include <netinet/in.h>
    #include <string.h>
    #include <sys/types.h>
#endif

#include "hlt.hpp"

namespace detail {
static std::vector< std::vector<unsigned char> > productions;
static int width, height;
#ifdef _WIN32
static SOCKET connection = INVALID_SOCKET;
#else
static int connection;
#endif

static std::string serializeMoveSet(const std::set<hlt::Move> &moves) {
    std::ostringstream oss;
    for(auto a = moves.begin(); a != moves.end(); ++a) oss << a->loc.x << " " << a->loc.y << " " << (int)a->dir << " ";
    return oss.str();
}

static void deserializeMapSize(const std::string & inputString) {
    std::stringstream iss(inputString);
    iss >> width >> height;
}

static void deserializeProductions(const std::string & inputString) {
    std::stringstream iss(inputString);
    productions.resize(height);
    short temp;
    for(auto a = productions.begin(); a != productions.end(); a++) {
        a->resize(width);
        for(auto b = a->begin(); b != a->end(); b++) {
            iss >> temp;
            *b = temp;
        }
    }
}

static hlt::GameMap deserializeMap(const std::string & inputString) {
    std::stringstream iss(inputString);

    hlt::GameMap map(width, height);

    //Set productions
    for(int a = 0; a < map.height; a++) {
        for(int b = 0; b < map.width; b++) {
            map.contents[a][b].production = productions[a][b];
        }
    }

    //Run-length encode of owners
    unsigned short y = 0, x = 0;
    unsigned short counter = 0, owner = 0;
    while(y != map.height) {
        for(iss >> counter >> owner; counter; counter--) {
            map.contents[y][x].owner = owner;
            x++;
            if(x == map.width) {
                x = 0;
                y++;
            }
        }
    }

    for (int a = 0; a < map.contents.size(); a++) {
        for (int b = 0; b < map.contents[a].size(); b++) {
            short strengthShort;
            iss >> strengthShort;
            map.contents[a][b].strength = strengthShort;
        }
    }

    return map;
}
static void sendString(std::string & sendString) {
    sendString.push_back('\n');
#ifdef _WIN32

#else
    write(connection, sendString.c_str(), sendString.size());
#endif
    sendString.pop_back(); //Remove newline.
}

static std::string getString() {
    std::string newString;
    char buffer = 0;
    while(buffer != '\n') {
#ifdef _WIN32

#else
        assert(read(connection, &buffer, 1) >= 0);
#endif
        newString.push_back(buffer);
    }
    return newString;
}
}

static void getInit(unsigned char& playerTag, hlt::GameMap& m) {
    int port;
    std::cout << "Enter the port on which to connect: ";
    std::cin >> port;
#ifdef _WIN32

#else
    //Connect to port
    detail::connection = socket(AF_INET, SOCK_STREAM, 0);
    assert(detail::connection >= 0);
    struct hostent *server;
    server = gethostbyname("127.0.0.1");
    assert(server != NULL);
    struct sockaddr_in serverAddr;
    bzero((char *) &serverAddr, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&serverAddr.sin_addr.s_addr, server->h_length);
    serverAddr.sin_port = htons(port);
    assert(connect(detail::connection, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) >= 0);
#endif
    playerTag = (unsigned char)std::stoi(detail::getString());
    detail::deserializeMapSize(detail::getString());
    detail::deserializeProductions(detail::getString());
    m = detail::deserializeMap(detail::getString());
}

static void sendInit(std::string name) {
    detail::sendString(name);
}

static void getFrame(hlt::GameMap& m) {
    m = detail::deserializeMap(detail::getString());
}
static void sendFrame(const std::set<hlt::Move> &moves) {
    std::string serializedMoves = detail::serializeMoveSet(moves);
    detail::sendString(serializedMoves);
}

#endif
<commit_msg>Added windows sockets [tested]<commit_after>#ifndef AI_NETWORKING_H
#define AI_NETWORKING_H

#include <iostream>
#include <time.h>
#include <set>
#include <cfloat>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <bitset>
#include <assert.h>

#ifdef _WIN32
    #include <sys/types.h>
    #include <Winsock2.h>
    #include <Ws2tcpip.h>
#else
    #include <sys/socket.h>
    #include <sys/ioctl.h>
    #include <arpa/inet.h>
    #include <unistd.h>
    #include <time.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <netdb.h>
    #include <netinet/in.h>
    #include <string.h>
    #include <sys/types.h>
#endif

#include "hlt.hpp"

namespace detail {
static std::vector< std::vector<unsigned char> > productions;
static int width, height;
#ifdef _WIN32
static SOCKET connection = INVALID_SOCKET;
#else
static int connection;
#endif

static std::string serializeMoveSet(const std::set<hlt::Move> &moves) {
    std::ostringstream oss;
    for(auto a = moves.begin(); a != moves.end(); ++a) oss << a->loc.x << " " << a->loc.y << " " << (int)a->dir << " ";
    return oss.str();
}

static void deserializeMapSize(const std::string & inputString) {
    std::stringstream iss(inputString);
    iss >> width >> height;
}

static void deserializeProductions(const std::string & inputString) {
    std::stringstream iss(inputString);
    productions.resize(height);
    short temp;
    for(auto a = productions.begin(); a != productions.end(); a++) {
        a->resize(width);
        for(auto b = a->begin(); b != a->end(); b++) {
            iss >> temp;
            *b = temp;
        }
    }
}

static hlt::GameMap deserializeMap(const std::string & inputString) {
    std::stringstream iss(inputString);

    hlt::GameMap map(width, height);

    //Set productions
    for(int a = 0; a < map.height; a++) {
        for(int b = 0; b < map.width; b++) {
            map.contents[a][b].production = productions[a][b];
        }
    }

    //Run-length encode of owners
    unsigned short y = 0, x = 0;
    unsigned short counter = 0, owner = 0;
    while(y != map.height) {
        for(iss >> counter >> owner; counter; counter--) {
            map.contents[y][x].owner = owner;
            x++;
            if(x == map.width) {
                x = 0;
                y++;
            }
        }
    }

    for (int a = 0; a < map.contents.size(); a++) {
        for (int b = 0; b < map.contents[a].size(); b++) {
            short strengthShort;
            iss >> strengthShort;
            map.contents[a][b].strength = strengthShort;
        }
    }

    return map;
}
static void sendString(std::string & sendString) {
    sendString.push_back('\n');
#ifdef _WIN32
	int result = send(connection, sendString.c_str(), sendString.size(), 0);
	assert(result != SOCKET_ERROR);
#else
    int result = write(connection, sendString.c_str(), sendString.size());
	assert(result >= 1); //Should be at least 1, as at least a newline should get written.
#endif
    sendString.pop_back(); //Remove newline.
}

static std::string getString() {
    std::string newString;
    char buffer = 0;
    while(buffer != '\n') {
#ifdef _WIN32
		int result = recv(connection, &buffer, 1, 0);
		assert(result != SOCKET_ERROR);
#else
		int result = read(connection, &buffer, 1);
        assert(result >= 0);
#endif
        newString.push_back(buffer);
    }
    return newString;
}
}

static void getInit(unsigned char& playerTag, hlt::GameMap& m) {
    int port;
    std::cout << "Enter the port on which to connect: ";
    std::cin >> port;
#ifdef _WIN32
	WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	assert(iResult == 0); //Confirms that Winsock started up correctly.
	struct addrinfo hints, * result;
    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
	iResult = getaddrinfo("127.0.0.1", std::to_string(port).c_str(), &hints, &result);
	assert(iResult == 0); //Confirms that getaddrinfo did not fail.
	detail::connection = socket(result->ai_family, result->ai_socktype, result->ai_protocol); //Creates socket.
	assert(detail::connection != INVALID_SOCKET); //Confirms connection is a valid socket.
	iResult = connect(detail::connection, result->ai_addr, int(result->ai_addrlen));
	assert(iResult != SOCKET_ERROR); //Confirms that there was a successful connection.
	freeaddrinfo(result);
#else
    //Connect to port
    connection = socket(AF_INET, SOCK_STREAM, 0);
    assert(detail::connection >= 0);
    struct hostent *server;
    server = gethostbyname("127.0.0.1");
    assert(server != NULL);
    struct sockaddr_in serverAddr;
    bzero((char *) &serverAddr, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&serverAddr.sin_addr.s_addr, server->h_length);
    serverAddr.sin_port = htons(port);
    assert(connect(detail::connection, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) >= 0);
#endif
	std::cout << "Connected to intermediary on port #" << port << std::endl;
    playerTag = (unsigned char)std::stoi(detail::getString());
    detail::deserializeMapSize(detail::getString());
    detail::deserializeProductions(detail::getString());
    m = detail::deserializeMap(detail::getString());
}

static void sendInit(std::string name) {
    detail::sendString(name);
}

static void getFrame(hlt::GameMap& m) {
    m = detail::deserializeMap(detail::getString());
}
static void sendFrame(const std::set<hlt::Move> &moves) {
    std::string serializedMoves = detail::serializeMoveSet(moves);
    detail::sendString(serializedMoves);
}

#endif
<|endoftext|>