<commit_before>/*
 * Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi
 * All rights reserved.
 */
#include "terrain.h"

#include <vector>

#include "../common/log.h"

#include <png.h>

#include "../common/debugging.h"

namespace game { namespace strat
{
  Noise_Raii::Noise_Raii(int64_t seed, osn_context** ptr) noexcept
  {
    // Pointer to an empty pointer given, allocate it and point our parameter
    // to it.
    if(!(*ptr))
    {
      open_simplex_noise(seed, ptr);
      ptr_ = *ptr;
      allocated_ = true;
    }
    else allocated_ = false;

    // If the ptr was valid it doesn't need to be initialized so don't do it.

  }
  Noise_Raii::~Noise_Raii() noexcept
  {
    if(allocated_) open_simplex_noise_free(ptr_);
  }

  // This function could be run alone.
  void terrain_v1_radial_land(Grid_Map& map, Terrain_Params const& tp) noexcept
  {
    osn_context* osn = nullptr;
    auto noise_init = Noise_Raii{tp.seed, &osn};

    for(int i = 0; i < map.extents.y; ++i)
    {
      for(int j = 0; j < map.extents.x; ++j)
      {
        // Point from the continent origin to here.
        Vec<float> to_here = Vec<int>{j, i} - tp.origin;
        auto to_here_dir = normalize(to_here);

        // Tp size is more like diameter, but not necessarily any particular
        // value.
        auto radius = tp.size / 2.0f;

        // Given the direction and radius find the circle edge. This value
        // should be the same for every vector with equal direction, but not
        // necessarily length.
        auto circle_edge = tp.origin + to_here_dir * radius;

        // Angle from origin
        auto angle = std::atan2(to_here_dir.y, to_here_dir.x);
        // Get a small delta from the angle. We will use this to modify the
        auto delta = open_simplex_noise2(osn, to_here_dir.y,
                                         to_here_dir.x) * tp.radial.amplitude;

        auto modified_radius = radius + delta;

        // This tile is land.
        if(length(to_here) < modified_radius)
        {
          map.values[i * map.extents.x + j].type = Cell_Type::Land;
        }
        else
        {
          map.values[i * map.extents.x + j].type = Cell_Type::Water;
        }
      }
    }
  }

  void terrain_v1_map(Grid_Map& map, Terrain_Params const& ter_params) noexcept
  {
    switch(ter_params.algorithm)
    {
    case Landmass_Algorithm::Radial:
      terrain_v1_radial_land(map, ter_params);
      break;
    case Landmass_Algorithm::Other:
      ter_params.other.gen_fn(map, ter_params);
    }
  }

  void write_png_heightmap(Grid_Map const& map,
                           std::string const& filename) noexcept
  {
    // All this code is pretty much based completely on the libpng manual so
    // check that out.

    std::FILE* fp = std::fopen(filename.data(), "wb");
    if(!fp)
    {
      log_w("Failed to open file '%'", filename);
      return;
    }

    png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
                                                  NULL, NULL, NULL);
    if(!png_ptr)
    {
      log_w("Failed to initialize libpng to write file '%'", filename);
      return;
    }

    png_infop info_ptr = png_create_info_struct(png_ptr);
    if(!info_ptr)
    {
      png_destroy_write_struct(&png_ptr, NULL);
      log_w("Failed to initialize png info to write '%'", filename);
      return;
    }

    if(setjmp(png_jmpbuf(png_ptr)))
    {
      png_destroy_write_struct(&png_ptr, &info_ptr);
      fclose(fp);

      log_w("libpng error for '%'", filename);
      return;
    }

    png_init_io(png_ptr, fp);

    png_set_IHDR(png_ptr, info_ptr, map.extents.x, map.extents.y, 8,
                 PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
                 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

    std::vector<uint8_t*> ptrs;
    for(int i = 0; i < map.extents.y; ++i)
    {
      ptrs.push_back(new uint8_t[map.extents.x * 3]);
      for(int j = 0; j < map.extents.x; ++j)
      {
        uint8_t value = 0xff;
        if(map.values[i * map.extents.x + j].type == Cell_Type::Water)
        {
          value = 0;
        }
        ptrs.back()[j * 3] = value;
        ptrs.back()[j * 3 + 1] = value;
        ptrs.back()[j * 3 + 2] = value;
      }
    }

    png_set_rows(png_ptr, info_ptr, &ptrs[0]);
    png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);

    for(auto* ptr : ptrs) delete ptr;

    png_destroy_write_struct(&png_ptr, &info_ptr);
  }
} }
<commit_msg>Remove an unused variable in terrain.cpp<commit_after>/*
 * Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi
 * All rights reserved.
 */
#include "terrain.h"

#include <vector>

#include "../common/log.h"

#include <png.h>

#include "../common/debugging.h"

namespace game { namespace strat
{
  Noise_Raii::Noise_Raii(int64_t seed, osn_context** ptr) noexcept
  {
    // Pointer to an empty pointer given, allocate it and point our parameter
    // to it.
    if(!(*ptr))
    {
      open_simplex_noise(seed, ptr);
      ptr_ = *ptr;
      allocated_ = true;
    }
    else allocated_ = false;

    // If the ptr was valid it doesn't need to be initialized so don't do it.

  }
  Noise_Raii::~Noise_Raii() noexcept
  {
    if(allocated_) open_simplex_noise_free(ptr_);
  }

  // This function could be run alone.
  void terrain_v1_radial_land(Grid_Map& map, Terrain_Params const& tp) noexcept
  {
    osn_context* osn = nullptr;
    auto noise_init = Noise_Raii{tp.seed, &osn};

    for(int i = 0; i < map.extents.y; ++i)
    {
      for(int j = 0; j < map.extents.x; ++j)
      {
        // Point from the continent origin to here.
        Vec<float> to_here = Vec<int>{j, i} - tp.origin;
        auto to_here_dir = normalize(to_here);

        // Tp size is more like diameter, but not necessarily any particular
        // value.
        auto radius = tp.size / 2.0f;

        // Angle from origin
        auto angle = std::atan2(to_here_dir.y, to_here_dir.x);
        // Get a small delta from the angle. We will use this to modify the
        auto delta = open_simplex_noise2(osn, to_here_dir.y,
                                         to_here_dir.x) * tp.radial.amplitude;

        auto modified_radius = radius + delta;

        // This tile is land.
        if(length(to_here) < modified_radius)
        {
          map.values[i * map.extents.x + j].type = Cell_Type::Land;
        }
        else
        {
          map.values[i * map.extents.x + j].type = Cell_Type::Water;
        }
      }
    }
  }

  void terrain_v1_map(Grid_Map& map, Terrain_Params const& ter_params) noexcept
  {
    switch(ter_params.algorithm)
    {
    case Landmass_Algorithm::Radial:
      terrain_v1_radial_land(map, ter_params);
      break;
    case Landmass_Algorithm::Other:
      ter_params.other.gen_fn(map, ter_params);
    }
  }

  void write_png_heightmap(Grid_Map const& map,
                           std::string const& filename) noexcept
  {
    // All this code is pretty much based completely on the libpng manual so
    // check that out.

    std::FILE* fp = std::fopen(filename.data(), "wb");
    if(!fp)
    {
      log_w("Failed to open file '%'", filename);
      return;
    }

    png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
                                                  NULL, NULL, NULL);
    if(!png_ptr)
    {
      log_w("Failed to initialize libpng to write file '%'", filename);
      return;
    }

    png_infop info_ptr = png_create_info_struct(png_ptr);
    if(!info_ptr)
    {
      png_destroy_write_struct(&png_ptr, NULL);
      log_w("Failed to initialize png info to write '%'", filename);
      return;
    }

    if(setjmp(png_jmpbuf(png_ptr)))
    {
      png_destroy_write_struct(&png_ptr, &info_ptr);
      fclose(fp);

      log_w("libpng error for '%'", filename);
      return;
    }

    png_init_io(png_ptr, fp);

    png_set_IHDR(png_ptr, info_ptr, map.extents.x, map.extents.y, 8,
                 PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
                 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

    std::vector<uint8_t*> ptrs;
    for(int i = 0; i < map.extents.y; ++i)
    {
      ptrs.push_back(new uint8_t[map.extents.x * 3]);
      for(int j = 0; j < map.extents.x; ++j)
      {
        uint8_t value = 0xff;
        if(map.values[i * map.extents.x + j].type == Cell_Type::Water)
        {
          value = 0;
        }
        ptrs.back()[j * 3] = value;
        ptrs.back()[j * 3 + 1] = value;
        ptrs.back()[j * 3 + 2] = value;
      }
    }

    png_set_rows(png_ptr, info_ptr, &ptrs[0]);
    png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);

    for(auto* ptr : ptrs) delete ptr;

    png_destroy_write_struct(&png_ptr, &info_ptr);
  }
} }
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: convert.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 12:32:53 $
 *
 *  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_sw.hxx"

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif

#ifndef _MODOPT_HXX //autogen
#include <modcfg.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#include "swmodule.hxx"
#include "cmdid.h"
#include "convert.hxx"
#include "tablemgr.hxx"
#include "wrtsh.hxx"
#include "view.hxx"
#include "tblafmt.hxx"

#include "table.hrc"
#include "convert.hrc"
#include "swabstdlg.hxx"

namespace swui
{
    SwAbstractDialogFactory * GetFactory();
}

//keep the state of the buttons on runtime
static int nSaveButtonState = -1; // 0: tab, 1: semicolon, 2: paragraph, 3: other, -1: not yet used
static sal_Bool bIsKeepColumn = sal_True;
static sal_Unicode uOther = ',';

void SwConvertTableDlg::GetValues(  sal_Unicode& rDelim,
                                    SwInsertTableOptions& rInsTblOpts,
                                    SwTableAutoFmt *& prTAFmt )
{
    if( aTabBtn.IsChecked() )
    {
        //0x0b mustn't be set when re-converting table into text
        bIsKeepColumn = !aKeepColumn.IsVisible() || aKeepColumn.IsChecked();
        rDelim = bIsKeepColumn ? 0x09 : 0x0b;
        nSaveButtonState = 0;
    }
    else if( aSemiBtn.IsChecked() )
    {
        rDelim = ';';
        nSaveButtonState = 1;
    }
    else if( aOtherBtn.IsChecked() && aOtherEd.GetText().Len() )
    {
        uOther = aOtherEd.GetText().GetChar( 0 );
        rDelim = uOther;
        nSaveButtonState = 3;
    }
    else
    {
        nSaveButtonState = 2;
        rDelim = cParaDelim;
        if(aOtherBtn.IsChecked())
        {
            nSaveButtonState = 3;
            uOther = 0;
        }
    }

    USHORT nInsMode = 0;
    if (aBorderCB.IsChecked())
        nInsMode |= tabopts::DEFAULT_BORDER;
    if (aHeaderCB.IsChecked())
        nInsMode |= tabopts::HEADLINE;
    if (aRepeatHeaderCB.IsEnabled() && aRepeatHeaderCB.IsChecked())
        rInsTblOpts.mnRowsToRepeat = USHORT( aRepeatHeaderNF.GetValue() );
    else
        rInsTblOpts.mnRowsToRepeat = 0;
    if (!aDontSplitCB.IsChecked())
        nInsMode |= tabopts::SPLIT_LAYOUT;

    if( pTAutoFmt )
        prTAFmt = new SwTableAutoFmt( *pTAutoFmt );

    rInsTblOpts.mnInsMode = nInsMode;
}

SwConvertTableDlg::SwConvertTableDlg( SwView& rView, bool bToTable )

    : SfxModalDialog( &rView.GetViewFrame()->GetWindow(), SW_RES(DLG_CONV_TEXT_TABLE)),
#ifdef MSC
#pragma warning (disable : 4355)
#endif
    aTabBtn         (this, SW_RES(CB_TAB)),
    aSemiBtn        (this, SW_RES(CB_SEMI)),
    aParaBtn        (this, SW_RES(CB_PARA)),
    aOtherBtn       (this, SW_RES(RB_OTHER)),
    aOtherEd        (this, SW_RES(ED_OTHER)),
    aKeepColumn     (this, SW_RES(CB_KEEPCOLUMN)),
    aDelimFL       (this, SW_RES(FL_DELIM)),

    aHeaderCB       (this, SW_RES(CB_HEADER)),
    aRepeatHeaderCB (this, SW_RES(CB_REPEAT_HEADER)),

    aRepeatHeaderFT         (this, SW_RES(FT_REPEAT_HEADER)),
    aRepeatHeaderBeforeFT   (this),
    aRepeatHeaderNF         (this, SW_RES(NF_REPEAT_HEADER)),
    aRepeatHeaderAfterFT    (this),
    aRepeatHeaderCombo      (this, SW_RES(WIN_REPEAT_HEADER), aRepeatHeaderNF, aRepeatHeaderBeforeFT, aRepeatHeaderAfterFT),

    aDontSplitCB    (this, SW_RES(CB_DONT_SPLIT)),
    aBorderCB       (this, SW_RES(CB_BORDER)),
    aOptionsFL      (this, SW_RES(FL_OPTIONS)),

    aOkBtn(this,SW_RES(BT_OK)),
    aCancelBtn(this,SW_RES(BT_CANCEL)),
    aHelpBtn(this, SW_RES(BT_HELP)),
    aAutoFmtBtn(this,SW_RES(BT_AUTOFORMAT)),
#ifdef MSC
#pragma warning (default : 4355)
#endif
    sConvertTextTable(SW_RES(STR_CONVERT_TEXT_TABLE)),
    pTAutoFmt( 0 ),
    pShell( &rView.GetWrtShell() )
{
    FreeResource();
    if(nSaveButtonState > -1)
    {
        switch (nSaveButtonState)
        {
            case 0:
                aTabBtn.Check();
                aKeepColumn.Check(bIsKeepColumn);
            break;
            case 1: aSemiBtn.Check();break;
            case 2: aParaBtn.Check();break;
            case 3:
                aOtherBtn.Check();
                if(uOther)
                    aOtherEd.SetText(uOther);
            break;
        }

    }
    if( bToTable )
    {
        SetText( sConvertTextTable );
        aAutoFmtBtn.SetClickHdl(LINK(this, SwConvertTableDlg, AutoFmtHdl));
        aAutoFmtBtn.Show();
        aKeepColumn.Show();
        aKeepColumn.Enable( aTabBtn.IsChecked() );
        aRepeatHeaderCombo.Arrange( aRepeatHeaderFT );
    }
    else
    {
        //Einfuege-Optionen verstecken
        aHeaderCB          .Show(FALSE);
        aRepeatHeaderCB    .Show(FALSE);
        aDontSplitCB       .Show(FALSE);
        aBorderCB          .Show(FALSE);
        aOptionsFL         .Show(FALSE);
        aRepeatHeaderCombo.Show(FALSE);

        //Groesse anpassen
        Size aSize(GetSizePixel());
        aSize.Height() = 8 + aHelpBtn.GetSizePixel().Height() + aHelpBtn.GetPosPixel().Y();
        SetOutputSizePixel(aSize);
    }
    aKeepColumn.SaveValue();

    Link aLk( LINK(this, SwConvertTableDlg, BtnHdl) );
    aTabBtn.SetClickHdl( aLk );
    aSemiBtn.SetClickHdl( aLk );
    aParaBtn.SetClickHdl( aLk );
    aOtherBtn.SetClickHdl(aLk );
    aOtherEd.Enable( aOtherBtn.IsChecked() );

    const SwModuleOptions* pModOpt = SW_MOD()->GetModuleConfig();

    BOOL bHTMLMode = 0 != (::GetHtmlMode(rView.GetDocShell())&HTMLMODE_ON);

    SwInsertTableOptions aInsOpts = pModOpt->GetInsTblFlags(bHTMLMode);
    USHORT nInsTblFlags = aInsOpts.mnInsMode;

    aHeaderCB.Check( 0 != (nInsTblFlags & tabopts::HEADLINE) );
    aRepeatHeaderCB.Check(aInsOpts.mnRowsToRepeat > 0);
    aDontSplitCB.Check( 0 == (nInsTblFlags & tabopts::SPLIT_LAYOUT));
    aBorderCB.Check( 0!= (nInsTblFlags & tabopts::DEFAULT_BORDER) );

    aHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, CheckBoxHdl));
    aRepeatHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, ReapeatHeaderCheckBoxHdl));
    ReapeatHeaderCheckBoxHdl();
    CheckBoxHdl();
}

SwConvertTableDlg:: ~SwConvertTableDlg()
{
    delete pTAutoFmt;
}

IMPL_LINK( SwConvertTableDlg, AutoFmtHdl, PushButton*, pButton )
{
    SwAbstractDialogFactory* pFact = swui::GetFactory();
    DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");

    AbstractSwAutoFormatDlg* pDlg = pFact->CreateSwAutoFormatDlg(pButton, pShell, DLG_AUTOFMT_TABLE, FALSE, pTAutoFmt);
    DBG_ASSERT(pDlg, "Dialogdiet fail!");
    if( RET_OK == pDlg->Execute())
        pDlg->FillAutoFmtOfIndex( pTAutoFmt );
    delete pDlg;
    return 0;
}

IMPL_LINK( SwConvertTableDlg, BtnHdl, Button*, pButton )
{
    if( pButton == &aTabBtn )
        aKeepColumn.SetState( aKeepColumn.GetSavedValue() );
    else
    {
        if( aKeepColumn.IsEnabled() )
            aKeepColumn.SaveValue();
        aKeepColumn.Check( TRUE );
    }
    aKeepColumn.Enable( aTabBtn.IsChecked() );
    aOtherEd.Enable( aOtherBtn.IsChecked() );
    return 0;
}

/*********************************************************************/
/*                                                                   */
/*********************************************************************/

IMPL_LINK(SwConvertTableDlg, CheckBoxHdl, CheckBox*, EMPTYARG)
{
    aRepeatHeaderCB.Enable(aHeaderCB.IsChecked());
    ReapeatHeaderCheckBoxHdl();

    return 0;
}

IMPL_LINK(SwConvertTableDlg, ReapeatHeaderCheckBoxHdl, void*, EMPTYARG)
{
    sal_Bool bEnable = aHeaderCB.IsChecked() && aRepeatHeaderCB.IsChecked();
    aRepeatHeaderBeforeFT.Enable(bEnable);
    aRepeatHeaderAfterFT.Enable(bEnable);
    aRepeatHeaderNF.Enable(bEnable);

    return 0;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.15.242); FILE MERGED 2008/04/01 15:59:42 thb 1.15.242.3: #i85898# Stripping all external header guards 2008/04/01 12:55:52 thb 1.15.242.2: #i85898# Stripping all external header guards 2008/03/31 16:59:32 rt 1.15.242.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: convert.cxx,v $
 * $Revision: 1.16 $
 *
 * 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_sw.hxx"

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#include <vcl/msgbox.hxx>
#include <svtools/stritem.hxx>
#include <sfx2/viewfrm.hxx>
#include <modcfg.hxx>
#include <svx/htmlmode.hxx>
#include <viewopt.hxx>
#include "swmodule.hxx"
#include "cmdid.h"
#include "convert.hxx"
#include "tablemgr.hxx"
#include "wrtsh.hxx"
#include "view.hxx"
#include "tblafmt.hxx"

#include "table.hrc"
#include "convert.hrc"
#include "swabstdlg.hxx"

namespace swui
{
    SwAbstractDialogFactory * GetFactory();
}

//keep the state of the buttons on runtime
static int nSaveButtonState = -1; // 0: tab, 1: semicolon, 2: paragraph, 3: other, -1: not yet used
static sal_Bool bIsKeepColumn = sal_True;
static sal_Unicode uOther = ',';

void SwConvertTableDlg::GetValues(  sal_Unicode& rDelim,
                                    SwInsertTableOptions& rInsTblOpts,
                                    SwTableAutoFmt *& prTAFmt )
{
    if( aTabBtn.IsChecked() )
    {
        //0x0b mustn't be set when re-converting table into text
        bIsKeepColumn = !aKeepColumn.IsVisible() || aKeepColumn.IsChecked();
        rDelim = bIsKeepColumn ? 0x09 : 0x0b;
        nSaveButtonState = 0;
    }
    else if( aSemiBtn.IsChecked() )
    {
        rDelim = ';';
        nSaveButtonState = 1;
    }
    else if( aOtherBtn.IsChecked() && aOtherEd.GetText().Len() )
    {
        uOther = aOtherEd.GetText().GetChar( 0 );
        rDelim = uOther;
        nSaveButtonState = 3;
    }
    else
    {
        nSaveButtonState = 2;
        rDelim = cParaDelim;
        if(aOtherBtn.IsChecked())
        {
            nSaveButtonState = 3;
            uOther = 0;
        }
    }

    USHORT nInsMode = 0;
    if (aBorderCB.IsChecked())
        nInsMode |= tabopts::DEFAULT_BORDER;
    if (aHeaderCB.IsChecked())
        nInsMode |= tabopts::HEADLINE;
    if (aRepeatHeaderCB.IsEnabled() && aRepeatHeaderCB.IsChecked())
        rInsTblOpts.mnRowsToRepeat = USHORT( aRepeatHeaderNF.GetValue() );
    else
        rInsTblOpts.mnRowsToRepeat = 0;
    if (!aDontSplitCB.IsChecked())
        nInsMode |= tabopts::SPLIT_LAYOUT;

    if( pTAutoFmt )
        prTAFmt = new SwTableAutoFmt( *pTAutoFmt );

    rInsTblOpts.mnInsMode = nInsMode;
}

SwConvertTableDlg::SwConvertTableDlg( SwView& rView, bool bToTable )

    : SfxModalDialog( &rView.GetViewFrame()->GetWindow(), SW_RES(DLG_CONV_TEXT_TABLE)),
#ifdef MSC
#pragma warning (disable : 4355)
#endif
    aTabBtn         (this, SW_RES(CB_TAB)),
    aSemiBtn        (this, SW_RES(CB_SEMI)),
    aParaBtn        (this, SW_RES(CB_PARA)),
    aOtherBtn       (this, SW_RES(RB_OTHER)),
    aOtherEd        (this, SW_RES(ED_OTHER)),
    aKeepColumn     (this, SW_RES(CB_KEEPCOLUMN)),
    aDelimFL       (this, SW_RES(FL_DELIM)),

    aHeaderCB       (this, SW_RES(CB_HEADER)),
    aRepeatHeaderCB (this, SW_RES(CB_REPEAT_HEADER)),

    aRepeatHeaderFT         (this, SW_RES(FT_REPEAT_HEADER)),
    aRepeatHeaderBeforeFT   (this),
    aRepeatHeaderNF         (this, SW_RES(NF_REPEAT_HEADER)),
    aRepeatHeaderAfterFT    (this),
    aRepeatHeaderCombo      (this, SW_RES(WIN_REPEAT_HEADER), aRepeatHeaderNF, aRepeatHeaderBeforeFT, aRepeatHeaderAfterFT),

    aDontSplitCB    (this, SW_RES(CB_DONT_SPLIT)),
    aBorderCB       (this, SW_RES(CB_BORDER)),
    aOptionsFL      (this, SW_RES(FL_OPTIONS)),

    aOkBtn(this,SW_RES(BT_OK)),
    aCancelBtn(this,SW_RES(BT_CANCEL)),
    aHelpBtn(this, SW_RES(BT_HELP)),
    aAutoFmtBtn(this,SW_RES(BT_AUTOFORMAT)),
#ifdef MSC
#pragma warning (default : 4355)
#endif
    sConvertTextTable(SW_RES(STR_CONVERT_TEXT_TABLE)),
    pTAutoFmt( 0 ),
    pShell( &rView.GetWrtShell() )
{
    FreeResource();
    if(nSaveButtonState > -1)
    {
        switch (nSaveButtonState)
        {
            case 0:
                aTabBtn.Check();
                aKeepColumn.Check(bIsKeepColumn);
            break;
            case 1: aSemiBtn.Check();break;
            case 2: aParaBtn.Check();break;
            case 3:
                aOtherBtn.Check();
                if(uOther)
                    aOtherEd.SetText(uOther);
            break;
        }

    }
    if( bToTable )
    {
        SetText( sConvertTextTable );
        aAutoFmtBtn.SetClickHdl(LINK(this, SwConvertTableDlg, AutoFmtHdl));
        aAutoFmtBtn.Show();
        aKeepColumn.Show();
        aKeepColumn.Enable( aTabBtn.IsChecked() );
        aRepeatHeaderCombo.Arrange( aRepeatHeaderFT );
    }
    else
    {
        //Einfuege-Optionen verstecken
        aHeaderCB          .Show(FALSE);
        aRepeatHeaderCB    .Show(FALSE);
        aDontSplitCB       .Show(FALSE);
        aBorderCB          .Show(FALSE);
        aOptionsFL         .Show(FALSE);
        aRepeatHeaderCombo.Show(FALSE);

        //Groesse anpassen
        Size aSize(GetSizePixel());
        aSize.Height() = 8 + aHelpBtn.GetSizePixel().Height() + aHelpBtn.GetPosPixel().Y();
        SetOutputSizePixel(aSize);
    }
    aKeepColumn.SaveValue();

    Link aLk( LINK(this, SwConvertTableDlg, BtnHdl) );
    aTabBtn.SetClickHdl( aLk );
    aSemiBtn.SetClickHdl( aLk );
    aParaBtn.SetClickHdl( aLk );
    aOtherBtn.SetClickHdl(aLk );
    aOtherEd.Enable( aOtherBtn.IsChecked() );

    const SwModuleOptions* pModOpt = SW_MOD()->GetModuleConfig();

    BOOL bHTMLMode = 0 != (::GetHtmlMode(rView.GetDocShell())&HTMLMODE_ON);

    SwInsertTableOptions aInsOpts = pModOpt->GetInsTblFlags(bHTMLMode);
    USHORT nInsTblFlags = aInsOpts.mnInsMode;

    aHeaderCB.Check( 0 != (nInsTblFlags & tabopts::HEADLINE) );
    aRepeatHeaderCB.Check(aInsOpts.mnRowsToRepeat > 0);
    aDontSplitCB.Check( 0 == (nInsTblFlags & tabopts::SPLIT_LAYOUT));
    aBorderCB.Check( 0!= (nInsTblFlags & tabopts::DEFAULT_BORDER) );

    aHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, CheckBoxHdl));
    aRepeatHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, ReapeatHeaderCheckBoxHdl));
    ReapeatHeaderCheckBoxHdl();
    CheckBoxHdl();
}

SwConvertTableDlg:: ~SwConvertTableDlg()
{
    delete pTAutoFmt;
}

IMPL_LINK( SwConvertTableDlg, AutoFmtHdl, PushButton*, pButton )
{
    SwAbstractDialogFactory* pFact = swui::GetFactory();
    DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");

    AbstractSwAutoFormatDlg* pDlg = pFact->CreateSwAutoFormatDlg(pButton, pShell, DLG_AUTOFMT_TABLE, FALSE, pTAutoFmt);
    DBG_ASSERT(pDlg, "Dialogdiet fail!");
    if( RET_OK == pDlg->Execute())
        pDlg->FillAutoFmtOfIndex( pTAutoFmt );
    delete pDlg;
    return 0;
}

IMPL_LINK( SwConvertTableDlg, BtnHdl, Button*, pButton )
{
    if( pButton == &aTabBtn )
        aKeepColumn.SetState( aKeepColumn.GetSavedValue() );
    else
    {
        if( aKeepColumn.IsEnabled() )
            aKeepColumn.SaveValue();
        aKeepColumn.Check( TRUE );
    }
    aKeepColumn.Enable( aTabBtn.IsChecked() );
    aOtherEd.Enable( aOtherBtn.IsChecked() );
    return 0;
}

/*********************************************************************/
/*                                                                   */
/*********************************************************************/

IMPL_LINK(SwConvertTableDlg, CheckBoxHdl, CheckBox*, EMPTYARG)
{
    aRepeatHeaderCB.Enable(aHeaderCB.IsChecked());
    ReapeatHeaderCheckBoxHdl();

    return 0;
}

IMPL_LINK(SwConvertTableDlg, ReapeatHeaderCheckBoxHdl, void*, EMPTYARG)
{
    sal_Bool bEnable = aHeaderCB.IsChecked() && aRepeatHeaderCB.IsChecked();
    aRepeatHeaderBeforeFT.Enable(bEnable);
    aRepeatHeaderAfterFT.Enable(bEnable);
    aRepeatHeaderNF.Enable(bEnable);

    return 0;
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Lefteris <lefteris@ethdev.com>
 * @date 2014
 * Solidity command line interface.
 */
#include "CommandLineInterface.h"

#include <string>
#include <iostream>
#include <fstream>

#include <boost/filesystem.hpp>

#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>

using namespace std;
namespace po = boost::program_options;

namespace dev
{
namespace solidity
{

// LTODO: Maybe some argument class pairing names with
// extensions and other attributes would be a better choice here?
static string const g_argAbiStr         = "abi";
static string const g_argAsmStr         = "asm";
static string const g_argAstStr         = "ast";
static string const g_argBinaryStr      = "binary";
static string const g_argOpcodesStr     = "opcodes";
static string const g_argNatspecDevStr  = "natspec-dev";
static string const g_argNatspecUserStr = "natspec-user";

static void version()
{
	cout << "solc, the solidity complier commandline interface " << dev::Version << endl
		 << "  by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
		 << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
	exit(0);
}

static inline bool argToStdout(po::variables_map const& _args, string const& _name)
{
	return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}

static bool needStdout(po::variables_map const& _args)
{
	return argToStdout(_args, g_argAbiStr) || argToStdout(_args, g_argNatspecUserStr) ||
		   argToStdout(_args, g_argNatspecDevStr) || argToStdout(_args, g_argAsmStr) ||
		   argToStdout(_args, g_argOpcodesStr) || argToStdout(_args, g_argBinaryStr);
}

static inline bool outputToFile(OutputType type)
{
	return type == OutputType::FILE || type == OutputType::BOTH;
}

static inline bool outputToStdout(OutputType type)
{
	return type == OutputType::STDOUT || type == OutputType::BOTH;
}

static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
	std::string token;
	_in >> token;
	if (token == "stdout")
		io_output = OutputType::STDOUT;
	else if (token == "file")
		io_output = OutputType::FILE;
	else if (token == "both")
		io_output = OutputType::BOTH;
	else
		throw boost::program_options::invalid_option_value(token);
	return _in;
}

void CommandLineInterface::handleBinary(string const& _contract)
{
	auto choice = m_args[g_argBinaryStr].as<OutputType>();
	if (outputToStdout(choice))
	{
		cout << "Binary: " << endl;
		cout << toHex(m_compiler.getBytecode(_contract)) << endl;
	}

	if (outputToFile(choice))
	{
		ofstream outFile(_contract + ".binary");
		outFile << toHex(m_compiler.getBytecode(_contract));
		outFile.close();
	}
}

void CommandLineInterface::handleOpcode(string const& _contract)
{
	auto choice = m_args[g_argOpcodesStr].as<OutputType>();
	if (outputToStdout(choice))
	{
		cout << "Opcodes: " << endl;
		cout << eth::disassemble(m_compiler.getBytecode(_contract));
		cout << endl;
	}

	if (outputToFile(choice))
	{
		ofstream outFile(_contract + ".opcode");
		outFile << eth::disassemble(m_compiler.getBytecode(_contract));
		outFile.close();
	}
}

void CommandLineInterface::handleBytecode(string const& _contract)
{
	if (m_args.count(g_argOpcodesStr))
		handleOpcode(_contract);
	if (m_args.count(g_argBinaryStr))
		handleBinary(_contract);
}

void CommandLineInterface::handleJson(DocumentationType _type,
									  string const& _contract)
{
	std::string argName;
	std::string suffix;
	std::string title;
	switch(_type)
	{
	case DocumentationType::ABI_INTERFACE:
		argName = g_argAbiStr;
		suffix = ".abi";
		title = "Contract ABI";
		break;
	case DocumentationType::NATSPEC_USER:
		argName = "g_argNatspecUserStr";
		suffix = ".docuser";
		title = "User Documentation";
		break;
	case DocumentationType::NATSPEC_DEV:
		argName = g_argNatspecDevStr;
		suffix = ".docdev";
		title = "Developer Documentation";
		break;
	default:
		// should never happen
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
	}

	if (m_args.count(argName))
	{
		auto choice = m_args[argName].as<OutputType>();
		if (outputToStdout(choice))
		{
			cout << title << endl;
			cout << m_compiler.getJsonDocumentation(_contract, _type);
		}

		if (outputToFile(choice))
		{
			ofstream outFile(_contract + suffix);
			outFile << m_compiler.getJsonDocumentation(_contract, _type);
			outFile.close();
		}
	}
}

bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n"				\
		"\tstdout: Print it to standard output\n"		\
		"\tfile: Print it to a file with same name\n"	\
		"\tboth: Print both to a file and the stdout\n"
	// Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "Show help message and exit")
		("version", "Show version and exit")
		("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
		("input-file", po::value<vector<string>>(), "input file")
		(g_argAstStr.c_str(), po::value<OutputType>(),
		 "Request to output the AST of the contract. " OUTPUT_TYPE_STR)
		(g_argAsmStr.c_str(), po::value<OutputType>(),
		 "Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
		(g_argOpcodesStr.c_str(), po::value<OutputType>(),
		 "Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
		(g_argBinaryStr.c_str(), po::value<OutputType>(),
		 "Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
		(g_argAbiStr.c_str(), po::value<OutputType>(),
		 "Request to output the contract's ABI interface. "  OUTPUT_TYPE_STR)
		(g_argNatspecUserStr.c_str(), po::value<OutputType>(),
		 "Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
		(g_argNatspecDevStr.c_str(), po::value<OutputType>(),
		 "Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR

	// All positional options should be interpreted as input files
	po::positional_options_description p;
	p.add("input-file", -1);

	// parse the compiler arguments
	try
	{
		po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
	}
	catch (po::error const& exception)
	{
		cout << exception.what() << endl;
		return false;
	}
	po::notify(m_args);

	if (m_args.count("help"))
	{
		cout << desc;
		return false;
	}

	if (m_args.count("version"))
	{
		version();
		return false;
	}

	return true;
}

bool CommandLineInterface::processInput()
{
	if (!m_args.count("input-file"))
	{
		string s;
		while (!cin.eof())
		{
			getline(cin, s);
			m_sourceCodes["<stdin>"].append(s);
		}
	}
	else
		for (string const& infile: m_args["input-file"].as<vector<string>>())
		{
			auto path = boost::filesystem::path(infile);
			if (!boost::filesystem::exists(path))
			{
				cout << "Skipping non existant input file \"" << infile << "\"" << endl;
				continue;
			}

			if (!boost::filesystem::is_regular_file(path))
			{
				cout << "\"" << infile << "\" is not a valid file. Skipping" << endl;
				continue;
			}

			m_sourceCodes[infile] = asString(dev::contents(infile));
		}

	try
	{
		for (auto const& sourceCode: m_sourceCodes)
			m_compiler.addSource(sourceCode.first, sourceCode.second);
		// TODO: Perhaps we should not compile unless requested
		m_compiler.compile(m_args["optimize"].as<bool>());
	}
	catch (ParserError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
		return false;
	}
	catch (DeclarationError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
		return false;
	}
	catch (TypeError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
		return false;
	}
	catch (CompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
		return false;
	}
	catch (InternalCompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", m_compiler);
		return false;
	}
	catch (Exception const& exception)
	{
		cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
		return false;
	}
	catch (...)
	{
		cerr << "Unknown exception during compilation." << endl;
		return false;
	}

	return true;
}

void CommandLineInterface::actOnInput()
{
	// do we need AST output?
	if (m_args.count(g_argAstStr))
	{
		auto choice = m_args[g_argAstStr].as<OutputType>();
		if (outputToStdout(choice))
		{
			cout << "Syntax trees:" << endl << endl;
			for (auto const& sourceCode: m_sourceCodes)
			{
				cout << endl << "======= " << sourceCode.first << " =======" << endl;
				ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
				printer.print(cout);
			}
		}

		if (outputToFile(choice))
		{
			for (auto const& sourceCode: m_sourceCodes)
			{
				boost::filesystem::path p(sourceCode.first);
				ofstream outFile(p.stem().string() + ".ast");
				ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
				printer.print(outFile);
				outFile.close();
			}
		}
	}

	vector<string> contracts = m_compiler.getContractNames();
	for (string const& contract: contracts)
	{
		if (needStdout(m_args))
			cout << endl << "======= " << contract << " =======" << endl;

		// do we need EVM assembly?
		if (m_args.count(g_argAsmStr))
		{
			auto choice = m_args[g_argAsmStr].as<OutputType>();
			if (outputToStdout(choice))
			{
				cout << "EVM assembly:" << endl;
				m_compiler.streamAssembly(cout, contract);
			}

			if (outputToFile(choice))
			{
				ofstream outFile(contract + ".evm");
				m_compiler.streamAssembly(outFile, contract);
				outFile.close();
			}
		}

		handleBytecode(contract);
		handleJson(DocumentationType::ABI_INTERFACE, contract);
		handleJson(DocumentationType::NATSPEC_DEV, contract);
		handleJson(DocumentationType::NATSPEC_USER, contract);
	} // end of contracts iteration
}

}
}
<commit_msg>Assertions that throw InternalCompilerErrors.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Lefteris <lefteris@ethdev.com>
 * @date 2014
 * Solidity command line interface.
 */
#include "CommandLineInterface.h"

#include <string>
#include <iostream>
#include <fstream>

#include <boost/filesystem.hpp>

#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>

using namespace std;
namespace po = boost::program_options;

namespace dev
{
namespace solidity
{

// LTODO: Maybe some argument class pairing names with
// extensions and other attributes would be a better choice here?
static string const g_argAbiStr         = "abi";
static string const g_argAsmStr         = "asm";
static string const g_argAstStr         = "ast";
static string const g_argBinaryStr      = "binary";
static string const g_argOpcodesStr     = "opcodes";
static string const g_argNatspecDevStr  = "natspec-dev";
static string const g_argNatspecUserStr = "natspec-user";

static void version()
{
	cout << "solc, the solidity complier commandline interface " << dev::Version << endl
		 << "  by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
		 << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
	exit(0);
}

static inline bool argToStdout(po::variables_map const& _args, string const& _name)
{
	return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}

static bool needStdout(po::variables_map const& _args)
{
	return argToStdout(_args, g_argAbiStr) || argToStdout(_args, g_argNatspecUserStr) ||
		   argToStdout(_args, g_argNatspecDevStr) || argToStdout(_args, g_argAsmStr) ||
		   argToStdout(_args, g_argOpcodesStr) || argToStdout(_args, g_argBinaryStr);
}

static inline bool outputToFile(OutputType type)
{
	return type == OutputType::FILE || type == OutputType::BOTH;
}

static inline bool outputToStdout(OutputType type)
{
	return type == OutputType::STDOUT || type == OutputType::BOTH;
}

static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
	std::string token;
	_in >> token;
	if (token == "stdout")
		io_output = OutputType::STDOUT;
	else if (token == "file")
		io_output = OutputType::FILE;
	else if (token == "both")
		io_output = OutputType::BOTH;
	else
		throw boost::program_options::invalid_option_value(token);
	return _in;
}

void CommandLineInterface::handleBinary(string const& _contract)
{
	auto choice = m_args[g_argBinaryStr].as<OutputType>();
	if (outputToStdout(choice))
	{
		cout << "Binary: " << endl;
		cout << toHex(m_compiler.getBytecode(_contract)) << endl;
	}

	if (outputToFile(choice))
	{
		ofstream outFile(_contract + ".binary");
		outFile << toHex(m_compiler.getBytecode(_contract));
		outFile.close();
	}
}

void CommandLineInterface::handleOpcode(string const& _contract)
{
	auto choice = m_args[g_argOpcodesStr].as<OutputType>();
	if (outputToStdout(choice))
	{
		cout << "Opcodes: " << endl;
		cout << eth::disassemble(m_compiler.getBytecode(_contract));
		cout << endl;
	}

	if (outputToFile(choice))
	{
		ofstream outFile(_contract + ".opcode");
		outFile << eth::disassemble(m_compiler.getBytecode(_contract));
		outFile.close();
	}
}

void CommandLineInterface::handleBytecode(string const& _contract)
{
	if (m_args.count(g_argOpcodesStr))
		handleOpcode(_contract);
	if (m_args.count(g_argBinaryStr))
		handleBinary(_contract);
}

void CommandLineInterface::handleJson(DocumentationType _type,
									  string const& _contract)
{
	std::string argName;
	std::string suffix;
	std::string title;
	switch(_type)
	{
	case DocumentationType::ABI_INTERFACE:
		argName = g_argAbiStr;
		suffix = ".abi";
		title = "Contract ABI";
		break;
	case DocumentationType::NATSPEC_USER:
		argName = "g_argNatspecUserStr";
		suffix = ".docuser";
		title = "User Documentation";
		break;
	case DocumentationType::NATSPEC_DEV:
		argName = g_argNatspecDevStr;
		suffix = ".docdev";
		title = "Developer Documentation";
		break;
	default:
		// should never happen
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
	}

	if (m_args.count(argName))
	{
		auto choice = m_args[argName].as<OutputType>();
		if (outputToStdout(choice))
		{
			cout << title << endl;
			cout << m_compiler.getJsonDocumentation(_contract, _type);
		}

		if (outputToFile(choice))
		{
			ofstream outFile(_contract + suffix);
			outFile << m_compiler.getJsonDocumentation(_contract, _type);
			outFile.close();
		}
	}
}

bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n"				\
		"\tstdout: Print it to standard output\n"		\
		"\tfile: Print it to a file with same name\n"	\
		"\tboth: Print both to a file and the stdout\n"
	// Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "Show help message and exit")
		("version", "Show version and exit")
		("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
		("input-file", po::value<vector<string>>(), "input file")
		(g_argAstStr.c_str(), po::value<OutputType>(),
		 "Request to output the AST of the contract. " OUTPUT_TYPE_STR)
		(g_argAsmStr.c_str(), po::value<OutputType>(),
		 "Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
		(g_argOpcodesStr.c_str(), po::value<OutputType>(),
		 "Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
		(g_argBinaryStr.c_str(), po::value<OutputType>(),
		 "Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
		(g_argAbiStr.c_str(), po::value<OutputType>(),
		 "Request to output the contract's ABI interface. "  OUTPUT_TYPE_STR)
		(g_argNatspecUserStr.c_str(), po::value<OutputType>(),
		 "Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
		(g_argNatspecDevStr.c_str(), po::value<OutputType>(),
		 "Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR

	// All positional options should be interpreted as input files
	po::positional_options_description p;
	p.add("input-file", -1);

	// parse the compiler arguments
	try
	{
		po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
	}
	catch (po::error const& exception)
	{
		cout << exception.what() << endl;
		return false;
	}
	po::notify(m_args);

	if (m_args.count("help"))
	{
		cout << desc;
		return false;
	}

	if (m_args.count("version"))
	{
		version();
		return false;
	}

	return true;
}

bool CommandLineInterface::processInput()
{
	if (!m_args.count("input-file"))
	{
		string s;
		while (!cin.eof())
		{
			getline(cin, s);
			m_sourceCodes["<stdin>"].append(s);
		}
	}
	else
		for (string const& infile: m_args["input-file"].as<vector<string>>())
		{
			auto path = boost::filesystem::path(infile);
			if (!boost::filesystem::exists(path))
			{
				cout << "Skipping non existant input file \"" << infile << "\"" << endl;
				continue;
			}

			if (!boost::filesystem::is_regular_file(path))
			{
				cout << "\"" << infile << "\" is not a valid file. Skipping" << endl;
				continue;
			}

			m_sourceCodes[infile] = asString(dev::contents(infile));
		}

	try
	{
		for (auto const& sourceCode: m_sourceCodes)
			m_compiler.addSource(sourceCode.first, sourceCode.second);
		// TODO: Perhaps we should not compile unless requested
		m_compiler.compile(m_args["optimize"].as<bool>());
	}
	catch (ParserError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
		return false;
	}
	catch (DeclarationError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
		return false;
	}
	catch (TypeError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
		return false;
	}
	catch (CompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
		return false;
	}
	catch (InternalCompilerError const& exception)
	{
		cerr << "Internal compiler error during compilation:" << endl
			 << boost::diagnostic_information(exception);
		return false;
	}
	catch (Exception const& exception)
	{
		cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
		return false;
	}
	catch (...)
	{
		cerr << "Unknown exception during compilation." << endl;
		return false;
	}

	return true;
}

void CommandLineInterface::actOnInput()
{
	// do we need AST output?
	if (m_args.count(g_argAstStr))
	{
		auto choice = m_args[g_argAstStr].as<OutputType>();
		if (outputToStdout(choice))
		{
			cout << "Syntax trees:" << endl << endl;
			for (auto const& sourceCode: m_sourceCodes)
			{
				cout << endl << "======= " << sourceCode.first << " =======" << endl;
				ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
				printer.print(cout);
			}
		}

		if (outputToFile(choice))
		{
			for (auto const& sourceCode: m_sourceCodes)
			{
				boost::filesystem::path p(sourceCode.first);
				ofstream outFile(p.stem().string() + ".ast");
				ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
				printer.print(outFile);
				outFile.close();
			}
		}
	}

	vector<string> contracts = m_compiler.getContractNames();
	for (string const& contract: contracts)
	{
		if (needStdout(m_args))
			cout << endl << "======= " << contract << " =======" << endl;

		// do we need EVM assembly?
		if (m_args.count(g_argAsmStr))
		{
			auto choice = m_args[g_argAsmStr].as<OutputType>();
			if (outputToStdout(choice))
			{
				cout << "EVM assembly:" << endl;
				m_compiler.streamAssembly(cout, contract);
			}

			if (outputToFile(choice))
			{
				ofstream outFile(contract + ".evm");
				m_compiler.streamAssembly(outFile, contract);
				outFile.close();
			}
		}

		handleBytecode(contract);
		handleJson(DocumentationType::ABI_INTERFACE, contract);
		handleJson(DocumentationType::NATSPEC_DEV, contract);
		handleJson(DocumentationType::NATSPEC_USER, contract);
	} // end of contracts iteration
}

}
}
<|endoftext|>


<commit_before>/*
  Copyright (C) 2008-2015 The Communi Project

  You may use this file under the terms of BSD license as follows:

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the copyright holder nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR
  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "zncmanager.h"
#include "ignoremanager.h"
#include <ircbuffermodel.h>
#include <ircconnection.h>
#include <irccommand.h>
#include <ircmessage.h>
#include <ircbuffer.h>

IRC_USE_NAMESPACE

ZncManager::ZncManager(QObject* parent) : QObject(parent)
{
    d.model = 0;
    d.timestamp = QDateTime::fromTime_t(0);
    setModel(qobject_cast<IrcBufferModel*>(parent));
}

ZncManager::~ZncManager()
{
}

IrcBufferModel* ZncManager::model() const
{
    return d.model;
}

void ZncManager::setModel(IrcBufferModel* model)
{
    if (d.model != model) {
        if (d.model && d.model->connection()) {
            IrcConnection* connection = d.model->connection();
            disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
            connection->removeMessageFilter(this);
            disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
        }
        d.model = model;
        if (d.model && d.model->connection()) {
            IrcNetwork* network = d.model->network();
            QStringList caps = network->requestedCapabilities();
            caps += "batch";
            caps += "server-time";
            caps += "echo-message";
            caps += "znc.in/batch";
            caps += "znc.in/playback";
            caps += "znc.in/server-time";
            caps += "znc.in/echo-message";
            caps += "znc.in/server-time-iso";
            network->setRequestedCapabilities(caps);

            IrcConnection* connection = d.model->connection();
            connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
            connection->installMessageFilter(this);
            connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
        }
        emit modelChanged(model);
    }
}

bool ZncManager::messageFilter(IrcMessage* message)
{
    if (message->connection()->isConnected())
        d.timestamp = qMax(d.timestamp, message->timeStamp());

    if (message->type() == IrcMessage::Batch) {
        IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message);
        if (batch->batch() == "znc.in/playback") {
            IrcBuffer* buffer = d.model->add(batch->parameters().value(2));
            foreach (IrcMessage* msg, batch->messages()) {
                msg->setFlags(msg->flags() | IrcMessage::Playback);
                if (msg->type() == IrcMessage::Private)
                    processMessage(static_cast<IrcPrivateMessage*>(msg));
            }
            buffer->receiveMessage(batch);
            return true;
        }
    }

    return IgnoreManager::instance()->messageFilter(message);
}

void ZncManager::processMessage(IrcPrivateMessage* message)
{
    if (message->nick() == "*buffextras") {
        const QString msg = message->content();
        const int idx = msg.indexOf(" ");
        const QString prefix = msg.left(idx);
        const QString content = msg.mid(idx + 1);

        message->setPrefix(prefix);
        if (content.startsWith("joined")) {
            message->setTag("intent", "JOIN");
            message->setParameters(QStringList() << message->target());
        } else if (content.startsWith("parted")) {
            message->setTag("intent", "PART");
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            message->setParameters(QStringList() << message->target() << reason);
        } else if (content.startsWith("quit")) {
            message->setTag("intent", "QUIT");
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            message->setParameters(QStringList() << reason);
        } else if (content.startsWith("is")) {
            message->setTag("intent", "NICK");
            const QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            message->setParameters(QStringList() << tokens.last());
        } else if (content.startsWith("set")) {
            message->setTag("intent", "MODE");
            QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            const QString user = tokens.takeLast();
            const QString mode = tokens.takeLast();
            message->setParameters(QStringList() << message->target() << mode << user);
        } else if (content.startsWith("changed")) {
            message->setTag("intent", "TOPIC");
            const QString topic = content.mid(content.indexOf(":") + 2);
            message->setParameters(QStringList() << message->target() << topic);
        } else if (content.startsWith("kicked")) {
            message->setTag("intent", "KICK");
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            message->setParameters(QStringList() << message->target() << tokens.value(1) << reason);
        }
    }
}

void ZncManager::requestPlayback()
{
    if (d.model->network()->isCapable("znc.in/playback")) {
        IrcConnection* connection = d.model->connection();
        IrcCommand* cmd = IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0));
        cmd->setParent(this);
        connection->sendCommand(cmd);
    }
}

void ZncManager::clearBuffer(IrcBuffer* buffer)
{
    if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*"))
        buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title())));
}
<commit_msg>ZncManager: don't filter out batch messages<commit_after>/*
  Copyright (C) 2008-2015 The Communi Project

  You may use this file under the terms of BSD license as follows:

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the copyright holder nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR
  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "zncmanager.h"
#include "ignoremanager.h"
#include <ircbuffermodel.h>
#include <ircconnection.h>
#include <irccommand.h>
#include <ircmessage.h>
#include <ircbuffer.h>

IRC_USE_NAMESPACE

ZncManager::ZncManager(QObject* parent) : QObject(parent)
{
    d.model = 0;
    d.timestamp = QDateTime::fromTime_t(0);
    setModel(qobject_cast<IrcBufferModel*>(parent));
}

ZncManager::~ZncManager()
{
}

IrcBufferModel* ZncManager::model() const
{
    return d.model;
}

void ZncManager::setModel(IrcBufferModel* model)
{
    if (d.model != model) {
        if (d.model && d.model->connection()) {
            IrcConnection* connection = d.model->connection();
            disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
            connection->removeMessageFilter(this);
            disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
        }
        d.model = model;
        if (d.model && d.model->connection()) {
            IrcNetwork* network = d.model->network();
            QStringList caps = network->requestedCapabilities();
            caps += "batch";
            caps += "server-time";
            caps += "echo-message";
            caps += "znc.in/batch";
            caps += "znc.in/playback";
            caps += "znc.in/server-time";
            caps += "znc.in/echo-message";
            caps += "znc.in/server-time-iso";
            network->setRequestedCapabilities(caps);

            IrcConnection* connection = d.model->connection();
            connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
            connection->installMessageFilter(this);
            connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
        }
        emit modelChanged(model);
    }
}

bool ZncManager::messageFilter(IrcMessage* message)
{
    if (message->connection()->isConnected())
        d.timestamp = qMax(d.timestamp, message->timeStamp());

    if (message->type() == IrcMessage::Batch) {
        IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message);
        if (batch->batch() == "znc.in/playback") {
            IrcBuffer* buffer = d.model->add(batch->parameters().value(2));
            foreach (IrcMessage* msg, batch->messages()) {
                msg->setFlags(msg->flags() | IrcMessage::Playback);
                if (msg->type() == IrcMessage::Private)
                    processMessage(static_cast<IrcPrivateMessage*>(msg));
            }
            buffer->receiveMessage(batch);
        }
    }

    return IgnoreManager::instance()->messageFilter(message);
}

void ZncManager::processMessage(IrcPrivateMessage* message)
{
    if (message->nick() == "*buffextras") {
        const QString msg = message->content();
        const int idx = msg.indexOf(" ");
        const QString prefix = msg.left(idx);
        const QString content = msg.mid(idx + 1);

        message->setPrefix(prefix);
        if (content.startsWith("joined")) {
            message->setTag("intent", "JOIN");
            message->setParameters(QStringList() << message->target());
        } else if (content.startsWith("parted")) {
            message->setTag("intent", "PART");
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            message->setParameters(QStringList() << message->target() << reason);
        } else if (content.startsWith("quit")) {
            message->setTag("intent", "QUIT");
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            message->setParameters(QStringList() << reason);
        } else if (content.startsWith("is")) {
            message->setTag("intent", "NICK");
            const QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            message->setParameters(QStringList() << tokens.last());
        } else if (content.startsWith("set")) {
            message->setTag("intent", "MODE");
            QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            const QString user = tokens.takeLast();
            const QString mode = tokens.takeLast();
            message->setParameters(QStringList() << message->target() << mode << user);
        } else if (content.startsWith("changed")) {
            message->setTag("intent", "TOPIC");
            const QString topic = content.mid(content.indexOf(":") + 2);
            message->setParameters(QStringList() << message->target() << topic);
        } else if (content.startsWith("kicked")) {
            message->setTag("intent", "KICK");
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            message->setParameters(QStringList() << message->target() << tokens.value(1) << reason);
        }
    }
}

void ZncManager::requestPlayback()
{
    if (d.model->network()->isCapable("znc.in/playback")) {
        IrcConnection* connection = d.model->connection();
        IrcCommand* cmd = IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0));
        cmd->setParent(this);
        connection->sendCommand(cmd);
    }
}

void ZncManager::clearBuffer(IrcBuffer* buffer)
{
    if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*"))
        buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title())));
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2016 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreUnifiedHighLevelGpuProgram.h"
#include "OgreException.h"
#include "OgreGpuProgramManager.h"

namespace Ogre
{
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgram::CmdDelegate UnifiedHighLevelGpuProgram::msCmdDelegate;
    static const String sLanguage = "unified";
    std::map<String,int> UnifiedHighLevelGpuProgram::mLanguagePriorities;

    int UnifiedHighLevelGpuProgram::getPriority(String shaderLanguage)
    {
        std::map<String,int>::iterator it = mLanguagePriorities.find(shaderLanguage);
        if (it == mLanguagePriorities.end())
            return -1;
        else
            return (*it).second;
    }

    void UnifiedHighLevelGpuProgram::setPrioriry(String shaderLanguage,int priority)
    {
        mLanguagePriorities[shaderLanguage] = priority;
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgram::UnifiedHighLevelGpuProgram(
        ResourceManager* creator, const String& name, ResourceHandle handle,
        const String& group, bool isManual, ManualResourceLoader* loader)
        :HighLevelGpuProgram(creator, name, handle, group, isManual, loader)
    {
        if (createParamDictionary("UnifiedHighLevelGpuProgram"))
        {
            setupBaseParamDictionary();

            ParamDictionary* dict = getParamDictionary();

            dict->addParameter(ParameterDef("delegate",
                "Additional delegate programs containing implementations.",
                PT_STRING),&msCmdDelegate);
        }

    }
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgram::~UnifiedHighLevelGpuProgram()
    {

    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::chooseDelegate() const
    {
        OGRE_LOCK_AUTO_MUTEX;

        mChosenDelegate.setNull();

        HighLevelGpuProgramPtr tmpDelegate;
        tmpDelegate.setNull();
        int tmpPriority = -10;

        for (StringVector::const_iterator i = mDelegateNames.begin(); i != mDelegateNames.end(); ++i)
        {
            HighLevelGpuProgramPtr deleg = HighLevelGpuProgramManager::getSingleton().getByName(*i, mGroup);

            //recheck with auto resource group
            if (deleg.isNull())
              deleg = HighLevelGpuProgramManager::getSingleton().getByName(*i);

            // Silently ignore missing links
            if(!deleg.isNull() && deleg->isSupported())
            {
                int priority = getPriority(deleg->getLanguage());
                //Find the delegate with the highest prioriry
                if (priority > tmpPriority)
                {
                    tmpDelegate = deleg;
                    tmpPriority = priority;
                }
            }

        }

        mChosenDelegate = tmpDelegate;
    }
    //-----------------------------------------------------------------------
    const HighLevelGpuProgramPtr& UnifiedHighLevelGpuProgram::_getDelegate() const
    {
        if (mChosenDelegate.isNull())
        {
            chooseDelegate();
        }
        return mChosenDelegate;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::addDelegateProgram(const String& name)
    {
            OGRE_LOCK_AUTO_MUTEX;

        mDelegateNames.push_back(name);

        // reset chosen delegate
        mChosenDelegate.setNull();

    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::clearDelegatePrograms()
    {
            OGRE_LOCK_AUTO_MUTEX;

        mDelegateNames.clear();
        mChosenDelegate.setNull();

    }
    //-----------------------------------------------------------------------------
    size_t UnifiedHighLevelGpuProgram::calculateSize(void) const
    {
        size_t memSize = 0;

        memSize += HighLevelGpuProgram::calculateSize();

        // Delegate Names
        for (StringVector::const_iterator i = mDelegateNames.begin(); i != mDelegateNames.end(); ++i)
            memSize += (*i).size() * sizeof(char);

        return memSize;
    }
    //-----------------------------------------------------------------------
    const String& UnifiedHighLevelGpuProgram::getLanguage(void) const
    {
        return sLanguage;
    }
    //-----------------------------------------------------------------------
    GpuProgramParametersSharedPtr UnifiedHighLevelGpuProgram::createParameters(void)
    {
        if (isSupported())
        {
            return _getDelegate()->createParameters();
        }
        else
        {
            // return a default set
            GpuProgramParametersSharedPtr params = GpuProgramManager::getSingleton().createParameters();
            // avoid any errors on parameter names that don't exist
            params->setIgnoreMissingParams(true);
            return params;
        }
    }
    //-----------------------------------------------------------------------
    GpuProgram* UnifiedHighLevelGpuProgram::_getBindingDelegate(void)
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->_getBindingDelegate();
        else
            return 0;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isSupported(void) const
    {
        // Supported if one of the delegates is
        return !(_getDelegate().isNull());
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isSkeletalAnimationIncluded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isSkeletalAnimationIncluded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isMorphAnimationIncluded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isMorphAnimationIncluded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isPoseAnimationIncluded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isPoseAnimationIncluded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    ushort UnifiedHighLevelGpuProgram::getNumberOfPosesIncluded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getNumberOfPosesIncluded();
        else
            return 0;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isVertexTextureFetchRequired(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isVertexTextureFetchRequired();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    GpuProgramParametersSharedPtr UnifiedHighLevelGpuProgram::getDefaultParameters(void)
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getDefaultParameters();
        else
            return GpuProgramParametersSharedPtr();
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::hasDefaultParameters(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->hasDefaultParameters();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::getPassSurfaceAndLightStates(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getPassSurfaceAndLightStates();
        else
            return HighLevelGpuProgram::getPassSurfaceAndLightStates();
    }
    //---------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::getPassFogStates(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getPassFogStates();
        else
            return HighLevelGpuProgram::getPassFogStates();
    }
    //---------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::getPassTransformStates(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getPassTransformStates();
        else
            return HighLevelGpuProgram::getPassTransformStates();

    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::hasCompileError(void) const
    {
        if (_getDelegate().isNull())
        {
            return false;
        }
        else
        {
            return _getDelegate()->hasCompileError();
        }
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::resetCompileError(void)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->resetCompileError();
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::load(bool backgroundThread)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->load(backgroundThread);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::reload(LoadingFlags flags)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->reload(flags);
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isReloadable(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isReloadable();
        else
            return true;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::unload(void)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->unload();
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isLoaded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isLoaded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isLoading() const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isLoading();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    Resource::LoadingState UnifiedHighLevelGpuProgram::getLoadingState() const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getLoadingState();
        else
            return Resource::LOADSTATE_UNLOADED;
    }
    //-----------------------------------------------------------------------
    size_t UnifiedHighLevelGpuProgram::getSize(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getSize();
        else
            return 0;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::touch(void)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->touch();
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isBackgroundLoaded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isBackgroundLoaded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::setBackgroundLoaded(bool bl)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->setBackgroundLoaded(bl);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::escalateLoading()
    {
        if (!_getDelegate().isNull())
            _getDelegate()->escalateLoading();
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::addListener(Resource::Listener* lis)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->addListener(lis);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::removeListener(Resource::Listener* lis)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->removeListener(lis);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::createLowLevelImpl(void)
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
            "This method should never get called!",
            "UnifiedHighLevelGpuProgram::createLowLevelImpl");
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::unloadHighLevelImpl(void)
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
            "This method should never get called!",
            "UnifiedHighLevelGpuProgram::unloadHighLevelImpl");
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::buildConstantDefinitions() const
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
            "This method should never get called!",
            "UnifiedHighLevelGpuProgram::buildConstantDefinitions");
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::loadFromSource(void)
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
            "This method should never get called!",
            "UnifiedHighLevelGpuProgram::loadFromSource");
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    String UnifiedHighLevelGpuProgram::CmdDelegate::doGet(const void* target) const
    {
        // Can't do this (not one delegate), shouldn't matter
        return BLANKSTRING;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::CmdDelegate::doSet(void* target, const String& val)
    {
        static_cast<UnifiedHighLevelGpuProgram*>(target)->addDelegateProgram(val);
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgramFactory::UnifiedHighLevelGpuProgramFactory()
    {
    }
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgramFactory::~UnifiedHighLevelGpuProgramFactory()
    {
    }
    //-----------------------------------------------------------------------
    const String& UnifiedHighLevelGpuProgramFactory::getLanguage(void) const
    {
        return sLanguage;
    }
    //-----------------------------------------------------------------------
    HighLevelGpuProgram* UnifiedHighLevelGpuProgramFactory::create(ResourceManager* creator,
        const String& name, ResourceHandle handle,
        const String& group, bool isManual, ManualResourceLoader* loader)
    {
        return OGRE_NEW UnifiedHighLevelGpuProgram(creator, name, handle, group, isManual, loader);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgramFactory::destroy(HighLevelGpuProgram* prog)
    {
        OGRE_DELETE prog;
    }
    //-----------------------------------------------------------------------

}

<commit_msg>Revert "Unified material did select the last program with the same priority which is wrong in the case of GL3+."<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2016 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreUnifiedHighLevelGpuProgram.h"
#include "OgreException.h"
#include "OgreGpuProgramManager.h"

namespace Ogre
{
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgram::CmdDelegate UnifiedHighLevelGpuProgram::msCmdDelegate;
    static const String sLanguage = "unified";
    std::map<String,int> UnifiedHighLevelGpuProgram::mLanguagePriorities;

    int UnifiedHighLevelGpuProgram::getPriority(String shaderLanguage)
    {
        std::map<String,int>::iterator it = mLanguagePriorities.find(shaderLanguage);
        if (it == mLanguagePriorities.end())
            return -1;
        else
            return (*it).second;
    }

    void UnifiedHighLevelGpuProgram::setPrioriry(String shaderLanguage,int priority)
    {
        mLanguagePriorities[shaderLanguage] = priority;
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgram::UnifiedHighLevelGpuProgram(
        ResourceManager* creator, const String& name, ResourceHandle handle,
        const String& group, bool isManual, ManualResourceLoader* loader)
        :HighLevelGpuProgram(creator, name, handle, group, isManual, loader)
    {
        if (createParamDictionary("UnifiedHighLevelGpuProgram"))
        {
            setupBaseParamDictionary();

            ParamDictionary* dict = getParamDictionary();

            dict->addParameter(ParameterDef("delegate",
                "Additional delegate programs containing implementations.",
                PT_STRING),&msCmdDelegate);
        }

    }
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgram::~UnifiedHighLevelGpuProgram()
    {

    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::chooseDelegate() const
    {
        OGRE_LOCK_AUTO_MUTEX;

        mChosenDelegate.setNull();

        HighLevelGpuProgramPtr tmpDelegate;
        tmpDelegate.setNull();
        int tmpPriority = -1;

        for (StringVector::const_iterator i = mDelegateNames.begin(); i != mDelegateNames.end(); ++i)
        {
            HighLevelGpuProgramPtr deleg = HighLevelGpuProgramManager::getSingleton().getByName(*i, mGroup);

            //recheck with auto resource group
            if (deleg.isNull())
              deleg = HighLevelGpuProgramManager::getSingleton().getByName(*i);

            // Silently ignore missing links
            if(!deleg.isNull() && deleg->isSupported())
            {
                int priority = getPriority(deleg->getLanguage());
                //Find the delegate with the highest prioriry
                if (priority >= tmpPriority)
                {
                    tmpDelegate = deleg;
                    tmpPriority = priority;
                }
            }

        }

        mChosenDelegate = tmpDelegate;
    }
    //-----------------------------------------------------------------------
    const HighLevelGpuProgramPtr& UnifiedHighLevelGpuProgram::_getDelegate() const
    {
        if (mChosenDelegate.isNull())
        {
            chooseDelegate();
        }
        return mChosenDelegate;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::addDelegateProgram(const String& name)
    {
            OGRE_LOCK_AUTO_MUTEX;

        mDelegateNames.push_back(name);

        // reset chosen delegate
        mChosenDelegate.setNull();

    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::clearDelegatePrograms()
    {
            OGRE_LOCK_AUTO_MUTEX;

        mDelegateNames.clear();
        mChosenDelegate.setNull();

    }
    //-----------------------------------------------------------------------------
    size_t UnifiedHighLevelGpuProgram::calculateSize(void) const
    {
        size_t memSize = 0;

        memSize += HighLevelGpuProgram::calculateSize();

        // Delegate Names
        for (StringVector::const_iterator i = mDelegateNames.begin(); i != mDelegateNames.end(); ++i)
            memSize += (*i).size() * sizeof(char);

        return memSize;
    }
    //-----------------------------------------------------------------------
    const String& UnifiedHighLevelGpuProgram::getLanguage(void) const
    {
        return sLanguage;
    }
    //-----------------------------------------------------------------------
    GpuProgramParametersSharedPtr UnifiedHighLevelGpuProgram::createParameters(void)
    {
        if (isSupported())
        {
            return _getDelegate()->createParameters();
        }
        else
        {
            // return a default set
            GpuProgramParametersSharedPtr params = GpuProgramManager::getSingleton().createParameters();
            // avoid any errors on parameter names that don't exist
            params->setIgnoreMissingParams(true);
            return params;
        }
    }
    //-----------------------------------------------------------------------
    GpuProgram* UnifiedHighLevelGpuProgram::_getBindingDelegate(void)
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->_getBindingDelegate();
        else
            return 0;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isSupported(void) const
    {
        // Supported if one of the delegates is
        return !(_getDelegate().isNull());
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isSkeletalAnimationIncluded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isSkeletalAnimationIncluded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isMorphAnimationIncluded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isMorphAnimationIncluded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isPoseAnimationIncluded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isPoseAnimationIncluded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    ushort UnifiedHighLevelGpuProgram::getNumberOfPosesIncluded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getNumberOfPosesIncluded();
        else
            return 0;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isVertexTextureFetchRequired(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isVertexTextureFetchRequired();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    GpuProgramParametersSharedPtr UnifiedHighLevelGpuProgram::getDefaultParameters(void)
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getDefaultParameters();
        else
            return GpuProgramParametersSharedPtr();
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::hasDefaultParameters(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->hasDefaultParameters();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::getPassSurfaceAndLightStates(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getPassSurfaceAndLightStates();
        else
            return HighLevelGpuProgram::getPassSurfaceAndLightStates();
    }
    //---------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::getPassFogStates(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getPassFogStates();
        else
            return HighLevelGpuProgram::getPassFogStates();
    }
    //---------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::getPassTransformStates(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getPassTransformStates();
        else
            return HighLevelGpuProgram::getPassTransformStates();

    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::hasCompileError(void) const
    {
        if (_getDelegate().isNull())
        {
            return false;
        }
        else
        {
            return _getDelegate()->hasCompileError();
        }
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::resetCompileError(void)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->resetCompileError();
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::load(bool backgroundThread)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->load(backgroundThread);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::reload(LoadingFlags flags)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->reload(flags);
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isReloadable(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isReloadable();
        else
            return true;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::unload(void)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->unload();
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isLoaded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isLoaded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isLoading() const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isLoading();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    Resource::LoadingState UnifiedHighLevelGpuProgram::getLoadingState() const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getLoadingState();
        else
            return Resource::LOADSTATE_UNLOADED;
    }
    //-----------------------------------------------------------------------
    size_t UnifiedHighLevelGpuProgram::getSize(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->getSize();
        else
            return 0;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::touch(void)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->touch();
    }
    //-----------------------------------------------------------------------
    bool UnifiedHighLevelGpuProgram::isBackgroundLoaded(void) const
    {
        if (!_getDelegate().isNull())
            return _getDelegate()->isBackgroundLoaded();
        else
            return false;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::setBackgroundLoaded(bool bl)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->setBackgroundLoaded(bl);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::escalateLoading()
    {
        if (!_getDelegate().isNull())
            _getDelegate()->escalateLoading();
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::addListener(Resource::Listener* lis)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->addListener(lis);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::removeListener(Resource::Listener* lis)
    {
        if (!_getDelegate().isNull())
            _getDelegate()->removeListener(lis);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::createLowLevelImpl(void)
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
            "This method should never get called!",
            "UnifiedHighLevelGpuProgram::createLowLevelImpl");
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::unloadHighLevelImpl(void)
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
            "This method should never get called!",
            "UnifiedHighLevelGpuProgram::unloadHighLevelImpl");
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::buildConstantDefinitions() const
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
            "This method should never get called!",
            "UnifiedHighLevelGpuProgram::buildConstantDefinitions");
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::loadFromSource(void)
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
            "This method should never get called!",
            "UnifiedHighLevelGpuProgram::loadFromSource");
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    String UnifiedHighLevelGpuProgram::CmdDelegate::doGet(const void* target) const
    {
        // Can't do this (not one delegate), shouldn't matter
        return BLANKSTRING;
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgram::CmdDelegate::doSet(void* target, const String& val)
    {
        static_cast<UnifiedHighLevelGpuProgram*>(target)->addDelegateProgram(val);
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgramFactory::UnifiedHighLevelGpuProgramFactory()
    {
    }
    //-----------------------------------------------------------------------
    UnifiedHighLevelGpuProgramFactory::~UnifiedHighLevelGpuProgramFactory()
    {
    }
    //-----------------------------------------------------------------------
    const String& UnifiedHighLevelGpuProgramFactory::getLanguage(void) const
    {
        return sLanguage;
    }
    //-----------------------------------------------------------------------
    HighLevelGpuProgram* UnifiedHighLevelGpuProgramFactory::create(ResourceManager* creator,
        const String& name, ResourceHandle handle,
        const String& group, bool isManual, ManualResourceLoader* loader)
    {
        return OGRE_NEW UnifiedHighLevelGpuProgram(creator, name, handle, group, isManual, loader);
    }
    //-----------------------------------------------------------------------
    void UnifiedHighLevelGpuProgramFactory::destroy(HighLevelGpuProgram* prog)
    {
        OGRE_DELETE prog;
    }
    //-----------------------------------------------------------------------

}

<|endoftext|>