<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/modules.h>
#include <vistk/pipeline/process.h>
#include <vistk/pipeline/process_registry.h>

#include <tools/helpers/typed_value_desc.h>

#include <boost/algorithm/string/join.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>

#include <iostream>
#include <string>

#include <cstdlib>

namespace po = boost::program_options;

static po::options_description make_options();
static void usage(po::options_description const& options);

int main(int argc, char* argv[])
{
  vistk::load_known_modules();

  po::options_description const desc = make_options();

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help"))
  {
    usage(desc);
  }

  vistk::process_registry_t reg = vistk::process_registry::self();

  vistk::process_registry::types_t types;

  if (vm.count("type"))
  {
    types = vm["type"].as<vistk::process_registry::types_t>();
  }
  else
  {
    types = reg->types();
  }

  if (vm.count("list"))
  {
    BOOST_FOREACH (vistk::process_registry::type_t const& type, types)
    {
      std::cout << type << std::endl;
    }

    return 0;
  }

  vistk::config_t const conf = vistk::config::empty_config();

  BOOST_FOREACH (vistk::process_registry::type_t const& proc_type, types)
  {
    if (!vm.count("detail"))
    {
      std::cout << proc_type << ": " << reg->description(proc_type) << std::endl;

      continue;
    }

    std::cout << "Process type: " << proc_type << std::endl;
    std::cout << "  Description: " << reg->description(proc_type) << std::endl;

    vistk::process_t const proc = reg->create_process(proc_type, conf);

    std::cout << "  Configuration:" << std::endl;

    vistk::config::keys_t const keys = proc->available_config();

    BOOST_FOREACH (vistk::config::key_t const key, keys)
    {
      vistk::process::conf_info_t const info = proc->config_info(key);

      vistk::config::value_t const& def = info->def;
      vistk::config::description_t const& conf_desc = info->description;

      std::cout << "    Name       : " << key << std::endl;
      std::cout << "    Default    : " << def << std::endl;
      std::cout << "    Description: " << conf_desc << std::endl;
      std::cout << std::endl;
    }

    std::cout << "  Input ports:" << std::endl;

    vistk::process::ports_t const iports = proc->input_ports();

    BOOST_FOREACH (vistk::process::port_t const port, iports)
    {
      vistk::process::port_info_t const info = proc->input_port_info(port);

      vistk::process::port_type_t const& type = info->type;
      vistk::process::port_flags_t const& flags = info->flags;
      vistk::process::port_description_t const& port_desc = info->description;

      std::string const flags_str = boost::join(flags, ", ");

      std::cout << "    Name       : " << port << std::endl;
      std::cout << "    Type       : " << type << std::endl;
      std::cout << "    Flags      : " << flags_str << std::endl;
      std::cout << "    Description: " << port_desc << std::endl;
      std::cout << std::endl;
    }

    std::cout << "  Output ports:" << std::endl;

    vistk::process::ports_t const oports = proc->output_ports();

    BOOST_FOREACH (vistk::process::port_t const port, oports)
    {
      vistk::process::port_info_t const info = proc->output_port_info(port);

      vistk::process::port_type_t const& type = info->type;
      vistk::process::port_flags_t const& flags = info->flags;
      vistk::process::port_description_t const& port_desc = info->description;

      std::string const flags_str = boost::join(flags, ", ");

      std::cout << "    Name       : " << port << std::endl;
      std::cout << "    Type       : " << type << std::endl;
      std::cout << "    Flags      : " << flags_str << std::endl;
      std::cout << "    Description: " << port_desc << std::endl;
      std::cout << std::endl;
    }

    std::cout << std::endl;
    std::cout << std::endl;
  }

  return 0;
}

po::options_description
make_options()
{
  po::options_description desc;

  desc.add_options()
    ("help,h", "output help message and quit")
    ("type,t", po::value_desc<vistk::process_registry::types_t>()->metavar("TYPE"), "type to describe")
    ("list,l", "simply list types")
    ("detail,d", "output detailed information")
  ;

  return desc;
}

void
usage(po::options_description const& options)
{
  std::cerr << options << std::endl;

  exit(1);
}
<commit_msg>Output constraints for processes as well<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/modules.h>
#include <vistk/pipeline/process.h>
#include <vistk/pipeline/process_registry.h>

#include <tools/helpers/typed_value_desc.h>

#include <boost/algorithm/string/join.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>

#include <iostream>
#include <string>

#include <cstdlib>

namespace po = boost::program_options;

static po::options_description make_options();
static void usage(po::options_description const& options);

int main(int argc, char* argv[])
{
  vistk::load_known_modules();

  po::options_description const desc = make_options();

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help"))
  {
    usage(desc);
  }

  vistk::process_registry_t reg = vistk::process_registry::self();

  vistk::process_registry::types_t types;

  if (vm.count("type"))
  {
    types = vm["type"].as<vistk::process_registry::types_t>();
  }
  else
  {
    types = reg->types();
  }

  if (vm.count("list"))
  {
    BOOST_FOREACH (vistk::process_registry::type_t const& type, types)
    {
      std::cout << type << std::endl;
    }

    return 0;
  }

  vistk::config_t const conf = vistk::config::empty_config();

  BOOST_FOREACH (vistk::process_registry::type_t const& proc_type, types)
  {
    if (!vm.count("detail"))
    {
      std::cout << proc_type << ": " << reg->description(proc_type) << std::endl;

      continue;
    }

    std::cout << "Process type: " << proc_type << std::endl;
    std::cout << "  Description: " << reg->description(proc_type) << std::endl;

    vistk::process_t const proc = reg->create_process(proc_type, conf);

    vistk::process::constraints_t const constraints = proc->constraints();
    std::string const constraints_str = boost::join(constraints, ", ");

    std::cout << "  Constraints:" << constraints_str << std::endl;

    std::cout << "  Configuration:" << std::endl;

    vistk::config::keys_t const keys = proc->available_config();

    BOOST_FOREACH (vistk::config::key_t const key, keys)
    {
      vistk::process::conf_info_t const info = proc->config_info(key);

      vistk::config::value_t const& def = info->def;
      vistk::config::description_t const& conf_desc = info->description;

      std::cout << "    Name       : " << key << std::endl;
      std::cout << "    Default    : " << def << std::endl;
      std::cout << "    Description: " << conf_desc << std::endl;
      std::cout << std::endl;
    }

    std::cout << "  Input ports:" << std::endl;

    vistk::process::ports_t const iports = proc->input_ports();

    BOOST_FOREACH (vistk::process::port_t const port, iports)
    {
      vistk::process::port_info_t const info = proc->input_port_info(port);

      vistk::process::port_type_t const& type = info->type;
      vistk::process::port_flags_t const& flags = info->flags;
      vistk::process::port_description_t const& port_desc = info->description;

      std::string const flags_str = boost::join(flags, ", ");

      std::cout << "    Name       : " << port << std::endl;
      std::cout << "    Type       : " << type << std::endl;
      std::cout << "    Flags      : " << flags_str << std::endl;
      std::cout << "    Description: " << port_desc << std::endl;
      std::cout << std::endl;
    }

    std::cout << "  Output ports:" << std::endl;

    vistk::process::ports_t const oports = proc->output_ports();

    BOOST_FOREACH (vistk::process::port_t const port, oports)
    {
      vistk::process::port_info_t const info = proc->output_port_info(port);

      vistk::process::port_type_t const& type = info->type;
      vistk::process::port_flags_t const& flags = info->flags;
      vistk::process::port_description_t const& port_desc = info->description;

      std::string const flags_str = boost::join(flags, ", ");

      std::cout << "    Name       : " << port << std::endl;
      std::cout << "    Type       : " << type << std::endl;
      std::cout << "    Flags      : " << flags_str << std::endl;
      std::cout << "    Description: " << port_desc << std::endl;
      std::cout << std::endl;
    }

    std::cout << std::endl;
    std::cout << std::endl;
  }

  return 0;
}

po::options_description
make_options()
{
  po::options_description desc;

  desc.add_options()
    ("help,h", "output help message and quit")
    ("type,t", po::value_desc<vistk::process_registry::types_t>()->metavar("TYPE"), "type to describe")
    ("list,l", "simply list types")
    ("detail,d", "output detailed information")
  ;

  return desc;
}

void
usage(po::options_description const& options)
{
  std::cerr << options << std::endl;

  exit(1);
}
<|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-2014 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 "OgreD3D11VideoModeList.h"
#include "OgreException.h"
#include "OgreD3D11Driver.h"
#include "OgreD3D11VideoMode.h"

namespace Ogre
{
    //---------------------------------------------------------------------
    D3D11VideoModeList::D3D11VideoModeList( D3D11Driver* pDriver )
    {
        if( NULL == pDriver )
            OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "pDriver parameter is NULL", "D3D11VideoModeList::D3D11VideoModeList" );

        mDriver = pDriver;
        enumerate();
    }
    //---------------------------------------------------------------------
    D3D11VideoModeList::~D3D11VideoModeList()
    {
        mDriver = NULL;
        mModeList.clear();
    }
    //---------------------------------------------------------------------
    BOOL D3D11VideoModeList::enumerate()
    {
        //      int pD3D = mDriver->getD3D();
        UINT adapter = mDriver->getAdapterNumber();
        HRESULT hr;
        IDXGIOutput *pOutput;
        for( int iOutput = 0; ; ++iOutput )
        {
            //AIZTODO: one output for a single monitor ,to be handled for mulimon
            hr = mDriver->getDeviceAdapter()->EnumOutputs( iOutput, &pOutput );
            if( DXGI_ERROR_NOT_FOUND == hr )
            {
                return false;
            }
            else if (FAILED(hr))
            {
                return false;   //Something bad happened.
            }
            else //Success!
            {
                DXGI_OUTPUT_DESC OutputDesc;
                pOutput->GetDesc(&OutputDesc);

                UINT NumModes = 0;
                hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
                    0,
                    &NumModes,
                    NULL );

                DXGI_MODE_DESC *pDesc = new DXGI_MODE_DESC[ NumModes ];
                ZeroMemory(pDesc, sizeof(DXGI_MODE_DESC) * NumModes);
                hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
                    0,
                    &NumModes,
                    pDesc );

                SAFE_RELEASE(pOutput);

                // display mode list can not be obtained when working over terminal session
                if(FAILED(hr))
                {
                    NumModes = 0;

                    if(hr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE)
                    {
                        pDesc[0].Width = 800;
                        pDesc[0].Height = 600;
                        pDesc[0].RefreshRate.Numerator = 60;
                        pDesc[0].RefreshRate.Denominator = 1;
                        pDesc[0].Format = DXGI_FORMAT_R8G8B8A8_UNORM;
                        pDesc[0].ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE;
                        pDesc[0].Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

                        NumModes = 1;
                    }
                }

                for( UINT m=0; m<NumModes; m++ )
                {
                    DXGI_MODE_DESC displayMode=pDesc[m];
                    // Filter out low-resolutions
                    if( displayMode.Width < 640 || displayMode.Height < 400 )
                        continue;

                    // Check to see if it is already in the list (to filter out refresh rates)
                    BOOL found = FALSE;
                    vector<D3D11VideoMode>::type::iterator it;
                    for( it = mModeList.begin(); it != mModeList.end(); it++ )
                    {
                        DXGI_OUTPUT_DESC oldOutput= it->getDisplayMode();
                        DXGI_MODE_DESC oldDisp = it->getModeDesc();
                        if(//oldOutput.Monitor==OutputDesc.Monitor &&
                            oldDisp.Width == displayMode.Width &&
                            oldDisp.Height == displayMode.Height// &&
                            //oldDisp.Format == displayMode.Format
                            )
                        {
                            // Check refresh rate and favour higher if poss
                            //if (oldDisp.RefreshRate < displayMode.RefreshRate)
                            //  it->increaseRefreshRate(displayMode.RefreshRate);
                            found = TRUE;
                            break;
                        }
                    }

                    if( !found )
                        mModeList.push_back( D3D11VideoMode( OutputDesc,displayMode ) );

                }
                delete [] pDesc;
            }
        }
        /*
        UINT iMode;
        for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_R5G6B5 ); iMode++ )
        {
        DXGI_OUTPUT_DESC displayMode;
        pD3D->EnumAdapterModes( adapter, D3DFMT_R5G6B5, iMode, &displayMode );

        // Filter out low-resolutions
        if( displayMode.Width < 640 || displayMode.Height < 400 )
        continue;

        // Check to see if it is already in the list (to filter out refresh rates)
        BOOL found = FALSE;
        vector<D3D11VideoMode>::type::iterator it;
        for( it = mModeList.begin(); it != mModeList.end(); it++ )
        {
        DXGI_OUTPUT_DESC oldDisp = it->getDisplayMode();
        if( oldDisp.Width == displayMode.Width &&
        oldDisp.Height == displayMode.Height &&
        oldDisp.Format == displayMode.Format )
        {
        // Check refresh rate and favour higher if poss
        if (oldDisp.RefreshRate < displayMode.RefreshRate)
        it->increaseRefreshRate(displayMode.RefreshRate);
        found = TRUE;
        break;
        }
        }

        if( !found )
        mModeList.push_back( D3D11VideoMode( displayMode ) );
        }

        for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_X8R8G8B8 ); iMode++ )
        {
        DXGI_OUTPUT_DESC displayMode;
        pD3D->EnumAdapterModes( adapter, D3DFMT_X8R8G8B8, iMode, &displayMode );

        // Filter out low-resolutions
        if( displayMode.Width < 640 || displayMode.Height < 400 )
        continue;

        // Check to see if it is already in the list (to filter out refresh rates)
        BOOL found = FALSE;
        vector<D3D11VideoMode>::type::iterator it;
        for( it = mModeList.begin(); it != mModeList.end(); it++ )
        {
        DXGI_OUTPUT_DESC oldDisp = it->getDisplayMode();
        if( oldDisp.Width == displayMode.Width &&
        oldDisp.Height == displayMode.Height &&
        oldDisp.Format == displayMode.Format )
        {
        // Check refresh rate and favour higher if poss
        if (oldDisp.RefreshRate < displayMode.RefreshRate)
        it->increaseRefreshRate(displayMode.RefreshRate);
        found = TRUE;
        break;
        }
        }

        if( !found )
        mModeList.push_back( D3D11VideoMode( displayMode ) );
        }
        */
        return TRUE;
    }
    //---------------------------------------------------------------------
    size_t D3D11VideoModeList::count()
    {
        return mModeList.size();
    }
    //---------------------------------------------------------------------
    D3D11VideoMode* D3D11VideoModeList::item( size_t index )
    {
        vector<D3D11VideoMode>::type::iterator p = mModeList.begin();

        return &p[index];
    }
    //---------------------------------------------------------------------
    D3D11VideoMode* D3D11VideoModeList::item( const String &name )
    {
        vector<D3D11VideoMode>::type::iterator it = mModeList.begin();
        if (it == mModeList.end())
            return NULL;

        for (;it != mModeList.end(); ++it)
        {
            if (it->getDescription() == name)
                return &(*it);
        }

        return NULL;
    }
    //---------------------------------------------------------------------
}
<commit_msg>Fixing VideoModeList to gracefully handle working over terminal sessions, for example when using Windows 8 simulator for app development.<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-2014 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 "OgreD3D11VideoModeList.h"
#include "OgreException.h"
#include "OgreD3D11Driver.h"
#include "OgreD3D11VideoMode.h"

namespace Ogre
{
    //---------------------------------------------------------------------
    D3D11VideoModeList::D3D11VideoModeList( D3D11Driver* pDriver )
    {
        if( NULL == pDriver )
            OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "pDriver parameter is NULL", "D3D11VideoModeList::D3D11VideoModeList" );

        mDriver = pDriver;
        enumerate();
    }
    //---------------------------------------------------------------------
    D3D11VideoModeList::~D3D11VideoModeList()
    {
        mDriver = NULL;
        mModeList.clear();
    }
    //---------------------------------------------------------------------
    BOOL D3D11VideoModeList::enumerate()
    {
        //      int pD3D = mDriver->getD3D();
        UINT adapter = mDriver->getAdapterNumber();
        HRESULT hr;
        IDXGIOutput *pOutput;
        for( int iOutput = 0; ; ++iOutput )
        {
            //AIZTODO: one output for a single monitor ,to be handled for mulimon
            hr = mDriver->getDeviceAdapter()->EnumOutputs( iOutput, &pOutput );
            if( DXGI_ERROR_NOT_FOUND == hr )
            {
                return false;
            }
            else if (FAILED(hr))
            {
                return false;   //Something bad happened.
            }
            else //Success!
            {
				DXGI_OUTPUT_DESC OutputDesc;
				pOutput->GetDesc(&OutputDesc);

				UINT NumModes = 0;
				hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
					0,
					&NumModes,
					NULL);

				// If working over a terminal session, for example using the Simulator for deployment/development, display modes cannot be obtained.
				if (hr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE)
				{
					DXGI_MODE_DESC fullScreenMode;
					fullScreenMode.Width = OutputDesc.DesktopCoordinates.right - OutputDesc.DesktopCoordinates.left;
					fullScreenMode.Height = OutputDesc.DesktopCoordinates.bottom - OutputDesc.DesktopCoordinates.top;
					fullScreenMode.RefreshRate.Numerator = 60;
					fullScreenMode.RefreshRate.Denominator = 1;
					fullScreenMode.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
					fullScreenMode.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE;
					fullScreenMode.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

					mModeList.push_back(D3D11VideoMode(OutputDesc, fullScreenMode));
				}
				else if (hr == S_OK)
				{
					if (NumModes > 0)
					{
						// Create an array to store Display Mode information
						DXGI_MODE_DESC *pDesc = new DXGI_MODE_DESC[NumModes];
						ZeroMemory(pDesc, sizeof(DXGI_MODE_DESC)* NumModes);

						// Populate our array with information
						hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
							0,
							&NumModes,
							pDesc);

						for (UINT m = 0; m < NumModes; m++)
						{
							DXGI_MODE_DESC displayMode = pDesc[m];
							// Filter out low-resolutions
							if (displayMode.Width < 640 || displayMode.Height < 400)
								continue;

							// Check to see if it is already in the list (to filter out refresh rates)
							BOOL found = FALSE;
							vector<D3D11VideoMode>::type::iterator it;
							for (it = mModeList.begin(); it != mModeList.end(); it++)
							{
								DXGI_OUTPUT_DESC oldOutput = it->getDisplayMode();
								DXGI_MODE_DESC oldDisp = it->getModeDesc();
								if (//oldOutput.Monitor==OutputDesc.Monitor &&
									oldDisp.Width == displayMode.Width &&
									oldDisp.Height == displayMode.Height// &&
									//oldDisp.Format == displayMode.Format
									)
								{
									// Check refresh rate and favour higher if poss
									//if (oldDisp.RefreshRate < displayMode.RefreshRate)
									//  it->increaseRefreshRate(displayMode.RefreshRate);
									found = TRUE;
									break;
								}
							}

							if (!found)
								mModeList.push_back(D3D11VideoMode(OutputDesc, displayMode));

						}
						delete[] pDesc;
					}
				}

				SAFE_RELEASE(pOutput);
            }
        }
        /*
        UINT iMode;
        for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_R5G6B5 ); iMode++ )
        {
        DXGI_OUTPUT_DESC displayMode;
        pD3D->EnumAdapterModes( adapter, D3DFMT_R5G6B5, iMode, &displayMode );

        // Filter out low-resolutions
        if( displayMode.Width < 640 || displayMode.Height < 400 )
        continue;

        // Check to see if it is already in the list (to filter out refresh rates)
        BOOL found = FALSE;
        vector<D3D11VideoMode>::type::iterator it;
        for( it = mModeList.begin(); it != mModeList.end(); it++ )
        {
        DXGI_OUTPUT_DESC oldDisp = it->getDisplayMode();
        if( oldDisp.Width == displayMode.Width &&
        oldDisp.Height == displayMode.Height &&
        oldDisp.Format == displayMode.Format )
        {
        // Check refresh rate and favour higher if poss
        if (oldDisp.RefreshRate < displayMode.RefreshRate)
        it->increaseRefreshRate(displayMode.RefreshRate);
        found = TRUE;
        break;
        }
        }

        if( !found )
        mModeList.push_back( D3D11VideoMode( displayMode ) );
        }

        for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_X8R8G8B8 ); iMode++ )
        {
        DXGI_OUTPUT_DESC displayMode;
        pD3D->EnumAdapterModes( adapter, D3DFMT_X8R8G8B8, iMode, &displayMode );

        // Filter out low-resolutions
        if( displayMode.Width < 640 || displayMode.Height < 400 )
        continue;

        // Check to see if it is already in the list (to filter out refresh rates)
        BOOL found = FALSE;
        vector<D3D11VideoMode>::type::iterator it;
        for( it = mModeList.begin(); it != mModeList.end(); it++ )
        {
        DXGI_OUTPUT_DESC oldDisp = it->getDisplayMode();
        if( oldDisp.Width == displayMode.Width &&
        oldDisp.Height == displayMode.Height &&
        oldDisp.Format == displayMode.Format )
        {
        // Check refresh rate and favour higher if poss
        if (oldDisp.RefreshRate < displayMode.RefreshRate)
        it->increaseRefreshRate(displayMode.RefreshRate);
        found = TRUE;
        break;
        }
        }

        if( !found )
        mModeList.push_back( D3D11VideoMode( displayMode ) );
        }
        */
        return TRUE;
    }
    //---------------------------------------------------------------------
    size_t D3D11VideoModeList::count()
    {
        return mModeList.size();
    }
    //---------------------------------------------------------------------
    D3D11VideoMode* D3D11VideoModeList::item( size_t index )
    {
        vector<D3D11VideoMode>::type::iterator p = mModeList.begin();

        return &p[index];
    }
    //---------------------------------------------------------------------
    D3D11VideoMode* D3D11VideoModeList::item( const String &name )
    {
        vector<D3D11VideoMode>::type::iterator it = mModeList.begin();
        if (it == mModeList.end())
            return NULL;

        for (;it != mModeList.end(); ++it)
        {
            if (it->getDescription() == name)
                return &(*it);
        }

        return NULL;
    }
    //---------------------------------------------------------------------
}
<|endoftext|>


<commit_before>/*
 *  caosVM_input.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on 28/07/2004.
 *  Copyright 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  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.
 *
 */

#include "World.h"
#include "Engine.h"
#include "PointerAgent.h"
#include "Backend.h"
#include "caosVM.h"
#include <iostream>
using std::cerr;

/**
 CLAC (command) message (integer)
 %status maybe

 Sets the type of message sent to the TARG agent when clicked.  If set to -1, no message
 will be sent.  Using this command will override and reset the value set with CLIK.
*/
void caosVM::c_CLAC() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(message)

	valid_agent(targ);

	targ->clac[0] = message;
	targ->clik = -1;
}

/**
 CLAC (integer)
 %status maybe
*/
void caosVM::v_CLAC() {
	valid_agent(targ);

	if (targ->clik != -1)
		result.setInt(targ->clac[0]);
	else
		result.setInt(-2);
}

/**
 CLIK (command) msg1 (integer) msg2 (integer) msg3 (integer)
 %status maybe

 Sets three different message types that will sent to the TARG agent when clicked, on a
 rotating basis.  Setting any of the three types to -1 will cause it to be ignored. Using
 this command will override and reset the value set by CLAC.
*/
void caosVM::c_CLIK() {
	VM_VERIFY_SIZE(3)
	VM_PARAM_INTEGER(msg3)
	VM_PARAM_INTEGER(msg2)
	VM_PARAM_INTEGER(msg1)

	valid_agent(targ);

	targ->clac[0] = msg1;
	targ->clac[1] = msg2;
	targ->clac[2] = msg3;
	targ->clik = 0;
}

/**
 CLIK (integer) data (integer)
 %status maybe
*/
void caosVM::v_CLIK() {
	VM_PARAM_INTEGER(data)

	valid_agent(targ);

	if (targ->clik == -1)
		result.setInt(-2);
	else switch (data) {
		case 0: result.setInt(targ->clik); break;
		case 1: result.setInt(targ->clac[0]); break;
		case 2: result.setInt(targ->clac[1]); break;
		case 3: result.setInt(targ->clac[2]); break;
	}
}

/**
 IMSK (command) flags (integer)
 %status stub

 Sets the input event flags for the target agent, which tell the engine which events the
 agent requires scripts to be fired for. For example, setting the "key up" flag means the
 target agent has the relevant script executed every time a key is released.

 Add the following values together to calculate the flags parameter: 1 for key down, 2 for key up, 4 for mouse move, 8 for mouse down, 16 for mouse up, 32 for mouse wheel movement and 64 for (translated) keypress.

 TODO: link to the script details (event numbers and parameters).
*/
void caosVM::c_IMSK() {
	VM_PARAM_INTEGER(flags)

	valid_agent(targ);
	targ->imsk_key_down = (flags & 1);
	targ->imsk_key_up = (flags & 2);
	targ->imsk_mouse_move = (flags & 4);
	targ->imsk_mouse_down = (flags & 8);
	targ->imsk_mouse_up = (flags & 16);
	targ->imsk_mouse_wheel = (flags & 32);
	targ->imsk_translated_char = (flags & 64);
	// TODO
}

/**
 IMSK (integer)
 %status stub

 Returns the input event flags for the target agent. See the IMSK command for details.
*/
void caosVM::v_IMSK() {
	valid_agent(targ);
	result.setInt(0); // TODO
}

/**
 KEYD (integer) keycode (integer)
 %status maybe

 Returns 1 if the specified key is held down, or 0 otherwise.
*/
void caosVM::v_KEYD() {
	VM_PARAM_INTEGER(keycode) // keycodes are crazy broken windows things

	if (engine.backend->keyDown(keycode))
		result.setInt(1);
	else
		result.setInt(0);
}

/**
 HOTS (agent)
 %status maybe

 Returns the agent that is currently underneath the Hand.
*/
void caosVM::v_HOTS() {
	Agent *a = world.agentAt(world.hand()->x, world.hand()->y); // TODO: use hotspot

	result.setAgent(a);
}

/**
 HOTP (integer)
 %status maybe

 Returns the PART of the agent (given by HOTS) that is currently underneath the Hand.

 Transparency of the parts themselves is ignored.
*/
void caosVM::v_HOTP() {
	CompoundPart *a = world.partAt(world.hand()->x, world.hand()->y, false);
	if (a)
		result.setInt(a->id);
	else
		result.setInt(-1);
}

/**
 PURE (command) value (integer)
 %status maybe

 Turns the normal pointing and clicking behavior of the Hand on (0) and off (1).

 If set to off, CLIK and CLAC will not work, and clicking events must be handled by IMSK.
*/
void caosVM::c_PURE() {
	VM_PARAM_INTEGER(value)

	world.hand()->handle_events = !value;
}

/**
 PURE (integer)
 %status maybe

 Returns whether the normal pointing and clicking behavior of the Hand is on or off.
*/
void caosVM::v_PURE() {
	// TODO: alex claims PURE is inverse behaviour for the command, is this true for this function too? (assuming it is for now)
	if (world.hand()->handle_events)
		result.setInt(0);
	else
		result.setInt(1);
}

/**
 MOPX (integer)
 %status maybe

 Returns the current X coordinate of the Hand in the world.
*/
void caosVM::v_MOPX() {
	result.setInt((int)world.hand()->x);
}

/**
 MOPY (integer)
 %status maybe

 Returns the current Y coordinate of the Hand in the world.
*/
void caosVM::v_MOPY() {
	result.setInt((int)world.hand()->y);
}

/**
 SCOL (integer) andmask (integer) eormask (integer) upspeeds (bytestring) downspeeds (bytestring)
 %status stub
*/
void caosVM::v_SCOL() {
	VM_PARAM_BYTESTR(downspeeds)
	VM_PARAM_BYTESTR(upspeeds)
	VM_PARAM_INTEGER(eormask)
	VM_PARAM_INTEGER(andmask)

	result.setInt(0); // TODO
}

/**
 SCRL (command) enable (integer)
 %status stub

 Turns on (1) or off (0) keyboard/mouse scrolling.
*/
void caosVM::c_SCRL() {
	VM_PARAM_INTEGER(enable)

	// TODO
}

/**
 MOUS (command) behaviour (integer)
 %status stub
*/
void caosVM::c_MOUS() {
	VM_PARAM_INTEGER(behaviour)

	// TODO
}

/* vim: set noet: */
<commit_msg>backport HOTS to c1 and c2 for convenience<commit_after>/*
 *  caosVM_input.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on 28/07/2004.
 *  Copyright 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  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.
 *
 */

#include "World.h"
#include "Engine.h"
#include "PointerAgent.h"
#include "Backend.h"
#include "caosVM.h"
#include <iostream>
using std::cerr;

/**
 CLAC (command) message (integer)
 %status maybe

 Sets the type of message sent to the TARG agent when clicked.  If set to -1, no message
 will be sent.  Using this command will override and reset the value set with CLIK.
*/
void caosVM::c_CLAC() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(message)

	valid_agent(targ);

	targ->clac[0] = message;
	targ->clik = -1;
}

/**
 CLAC (integer)
 %status maybe
*/
void caosVM::v_CLAC() {
	valid_agent(targ);

	if (targ->clik != -1)
		result.setInt(targ->clac[0]);
	else
		result.setInt(-2);
}

/**
 CLIK (command) msg1 (integer) msg2 (integer) msg3 (integer)
 %status maybe

 Sets three different message types that will sent to the TARG agent when clicked, on a
 rotating basis.  Setting any of the three types to -1 will cause it to be ignored. Using
 this command will override and reset the value set by CLAC.
*/
void caosVM::c_CLIK() {
	VM_VERIFY_SIZE(3)
	VM_PARAM_INTEGER(msg3)
	VM_PARAM_INTEGER(msg2)
	VM_PARAM_INTEGER(msg1)

	valid_agent(targ);

	targ->clac[0] = msg1;
	targ->clac[1] = msg2;
	targ->clac[2] = msg3;
	targ->clik = 0;
}

/**
 CLIK (integer) data (integer)
 %status maybe
*/
void caosVM::v_CLIK() {
	VM_PARAM_INTEGER(data)

	valid_agent(targ);

	if (targ->clik == -1)
		result.setInt(-2);
	else switch (data) {
		case 0: result.setInt(targ->clik); break;
		case 1: result.setInt(targ->clac[0]); break;
		case 2: result.setInt(targ->clac[1]); break;
		case 3: result.setInt(targ->clac[2]); break;
	}
}

/**
 IMSK (command) flags (integer)
 %status stub

 Sets the input event flags for the target agent, which tell the engine which events the
 agent requires scripts to be fired for. For example, setting the "key up" flag means the
 target agent has the relevant script executed every time a key is released.

 Add the following values together to calculate the flags parameter: 1 for key down, 2 for key up, 4 for mouse move, 8 for mouse down, 16 for mouse up, 32 for mouse wheel movement and 64 for (translated) keypress.

 TODO: link to the script details (event numbers and parameters).
*/
void caosVM::c_IMSK() {
	VM_PARAM_INTEGER(flags)

	valid_agent(targ);
	targ->imsk_key_down = (flags & 1);
	targ->imsk_key_up = (flags & 2);
	targ->imsk_mouse_move = (flags & 4);
	targ->imsk_mouse_down = (flags & 8);
	targ->imsk_mouse_up = (flags & 16);
	targ->imsk_mouse_wheel = (flags & 32);
	targ->imsk_translated_char = (flags & 64);
	// TODO
}

/**
 IMSK (integer)
 %status stub

 Returns the input event flags for the target agent. See the IMSK command for details.
*/
void caosVM::v_IMSK() {
	valid_agent(targ);
	result.setInt(0); // TODO
}

/**
 KEYD (integer) keycode (integer)
 %status maybe

 Returns 1 if the specified key is held down, or 0 otherwise.
*/
void caosVM::v_KEYD() {
	VM_PARAM_INTEGER(keycode) // keycodes are crazy broken windows things

	if (engine.backend->keyDown(keycode))
		result.setInt(1);
	else
		result.setInt(0);
}

/**
 HOTS (agent)
 %status maybe
 %pragma variants all

 Returns the agent that is currently underneath the Hand.
 NB: this command is not a real c1/c2 command, backported for convenience
*/
void caosVM::v_HOTS() {
	Agent *a = world.agentAt(world.hand()->x, world.hand()->y); // TODO: use hotspot

	result.setAgent(a);
}

/**
 HOTP (integer)
 %status maybe

 Returns the PART of the agent (given by HOTS) that is currently underneath the Hand.

 Transparency of the parts themselves is ignored.
*/
void caosVM::v_HOTP() {
	CompoundPart *a = world.partAt(world.hand()->x, world.hand()->y, false);
	if (a)
		result.setInt(a->id);
	else
		result.setInt(-1);
}

/**
 PURE (command) value (integer)
 %status maybe

 Turns the normal pointing and clicking behavior of the Hand on (0) and off (1).

 If set to off, CLIK and CLAC will not work, and clicking events must be handled by IMSK.
*/
void caosVM::c_PURE() {
	VM_PARAM_INTEGER(value)

	world.hand()->handle_events = !value;
}

/**
 PURE (integer)
 %status maybe

 Returns whether the normal pointing and clicking behavior of the Hand is on or off.
*/
void caosVM::v_PURE() {
	// TODO: alex claims PURE is inverse behaviour for the command, is this true for this function too? (assuming it is for now)
	if (world.hand()->handle_events)
		result.setInt(0);
	else
		result.setInt(1);
}

/**
 MOPX (integer)
 %status maybe

 Returns the current X coordinate of the Hand in the world.
*/
void caosVM::v_MOPX() {
	result.setInt((int)world.hand()->x);
}

/**
 MOPY (integer)
 %status maybe

 Returns the current Y coordinate of the Hand in the world.
*/
void caosVM::v_MOPY() {
	result.setInt((int)world.hand()->y);
}

/**
 SCOL (integer) andmask (integer) eormask (integer) upspeeds (bytestring) downspeeds (bytestring)
 %status stub
*/
void caosVM::v_SCOL() {
	VM_PARAM_BYTESTR(downspeeds)
	VM_PARAM_BYTESTR(upspeeds)
	VM_PARAM_INTEGER(eormask)
	VM_PARAM_INTEGER(andmask)

	result.setInt(0); // TODO
}

/**
 SCRL (command) enable (integer)
 %status stub

 Turns on (1) or off (0) keyboard/mouse scrolling.
*/
void caosVM::c_SCRL() {
	VM_PARAM_INTEGER(enable)

	// TODO
}

/**
 MOUS (command) behaviour (integer)
 %status stub
*/
void caosVM::c_MOUS() {
	VM_PARAM_INTEGER(behaviour)

	// TODO
}

/* vim: set noet: */
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013-2014 INRA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. 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.
 *
 * THIS SOFTWARE IS PROVIDED "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 HOLDER 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.
 */

#ifndef __VLE_KERNEL_COMMON_HPP__
#define __VLE_KERNEL_COMMON_HPP__

#include <memory>
#include <unordered_map>
#include <string>
#include <boost/any.hpp>
#include <vle/utils.hpp>

namespace vle {

/**
 * @brief @e vle::Common stores experimental conditions, simulation engine
 * parameters etc.
 */
typedef std::unordered_map <std::string, boost::any> Common;

template <typename T>
    T common_get(const Common& c, const std::string& name)
    {
        auto it = c.find(name);
        if (it == c.end())
            throw std::invalid_argument(
                stringf("Common: failed to find attribute %s", name.c_str()));

        return boost::any_cast <T>(it->second);
    }

template <typename T>
    const T* common_get_pointer(const Common& c, const std::string& name)
    {
        auto it = c.find(name);
        if (it == c.end())
            throw std::invalid_argument(
                stringf("Common: failed to find attribute %s", name.c_str()));

        return boost::any_cast <T>(&it->second);
    }

typedef std::shared_ptr <Common> CommonPtr;

}

#endif
<commit_msg>vle: append a get function for common<commit_after>/*
 * Copyright (C) 2013-2014 INRA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. 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.
 *
 * THIS SOFTWARE IS PROVIDED "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 HOLDER 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.
 */

#ifndef __VLE_KERNEL_COMMON_HPP__
#define __VLE_KERNEL_COMMON_HPP__

#include <memory>
#include <unordered_map>
#include <string>
#include <vle/utils.hpp>
#include <boost/any.hpp>
#include <boost/optional.hpp>

namespace vle {

/**
 * @brief @e vle::Common stores experimental conditions, simulation engine
 * parameters etc.
 */
typedef std::unordered_map <std::string, boost::any> Common;

template <typename T>
    T common_get(const Common& c, const std::string& name)
    {
        auto it = c.find(name);
        if (it == c.end())
            throw std::invalid_argument(
                stringf("Common: failed to find attribute %s", name.c_str()));

        return boost::any_cast <T>(it->second);
    }

template <typename T>
    const T* common_get_pointer(const Common& c, const std::string& name)
    {
        auto it = c.find(name);
        if (it == c.end())
            throw std::invalid_argument(
                stringf("Common: failed to find attribute %s", name.c_str()));

        return boost::any_cast <T>(&it->second);
    }

template <typename T>
boost::optional <T> get(const Common &c, const std::string &name)
{
    auto it = c.find(name);
    if (it == c.end())
        return boost::none;
    else
        return boost::any_cast <T>(it->second);
}

typedef std::shared_ptr <Common> CommonPtr;

}

#endif
<|endoftext|>


<commit_before>#include "player.h"

#include "game_system.h"
#include "bullet.h"
#include "utils.h"
#include "texture_manager.h"

#include <iostream>

namespace vot
{
    Player::Player(const sf::Texture &texture) :
        Character(texture),
        _cooldown(0.0f),
        _homing_cooldown(0.0f),
        _look_at_target(false),
        _auto_target(true),
        _target(nullptr),
        _powerup_hitbox(20.0f)
    {

    }

    void Player::init()
    {
        add_hardpoint_placement(new HardpointPlacement(0, 8, 225, 315));
        add_hardpoint_placement(new HardpointPlacement(-16, 4, 180, 300));
        add_hardpoint_placement(new HardpointPlacement(16, 4, 240, 0));
        add_hardpoint_placement(new HardpointPlacement(20, 10, 270, 45));
        add_hardpoint_placement(new HardpointPlacement(-20, 10, 75, 270));

        create_new_hardpoint(Powerup::BULLET);

        add_thruster_placement(28, 0, 0, 0.35f);
        add_thruster_placement(28, 0, 180, 0.35f);
        add_thruster_placement(-28, 0, 180, 0.35f);
        add_thruster_placement(-28, 0, 0, 0.35f);

        add_thruster_placement(-8, 14, 180, 0.5f);
        add_thruster_placement(8, 14, 180, 0.5f);
        add_thruster_placement(8, -8, 0, 0.35f);
        add_thruster_placement(-8, -8, 0, 0.35f);

        add_thruster_placement(-28, 3, 270, 0.35f);
        add_thruster_placement(28, 3, 90, 0.35f);
    }

    void Player::update(float dt)
    {
        auto gs = GameSystem::main();

        // Keyboard input {{{
        sf::Vector2f acc;
        float rot_acc = 0.0f;

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
        {
            acc.x -= strafe_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
        {
            acc.x += strafe_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
        {
            acc.y += backwards_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
        {
            acc.y -= forwards_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q))
        {
            rot_acc -= rot_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
        {
            rot_acc += rot_speed();
        }

        if (gs->is_key_pressed(sf::Keyboard::T))
        {
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
            {
                _auto_target = !_auto_target;
            }
            else
            {
                target(gs->next_target(_target));
            }
        }
        if (gs->is_key_pressed(sf::Keyboard::Z))
        {
            _look_at_target = !_look_at_target;
        }
        // }}}

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
        {
            auto points = hardpoints();
            for (auto i = 0u; i < points->size(); i++)
            {
                points->at(i)->fire();
            }
        }

        if (_look_at_target && _target != nullptr)
        {
            auto rot_spd = rot_speed();
            auto angles = Utils::calculate_angles(getPosition(), _target->getPosition(), rotation(), -90.0f);
            rot_spd *= dt;
            if (angles.delta_angle() < rot_spd && angles.delta_angle() > -rot_spd)
            {
                rotation(angles.to_angle());
                //rot_acc -= angles.delta_angle();
            }
            else
            {
                rot_acc += (angles.delta_angle() > 0) ? -rot_speed() : rot_speed();
                //rotateBy(angles.delta_angle() > 0 ? -rot_spd : rot_spd);
            }
        }

        acceleration(acc);
        rot_acceleration(rot_acc);

        _cooldown -= dt;
        _homing_cooldown -= dt;

        Character::update(dt);

        _powerup_hitbox.location(getPosition());
    }

    void Player::target(Enemy *value)
    {
        _target = value;

        auto points = hardpoints();
        for (auto i = 0u; i < points->size(); i++)
        {
            points->at(i)->target(value);
        }
    }
    Enemy *Player::target() const
    {
        return _target;
    }

    bool Player::looking_at_target() const
    {
        return _look_at_target;
    }
    bool Player::auto_target() const
    {
        return _auto_target;
    }

    Circle &Player::powerup_hitbox()
    {
        return _powerup_hitbox;
    }

    void Player::add_powerup(const Powerup &powerup)
    {
        create_new_hardpoint(powerup.type());
    }
    void Player::create_new_hardpoint(Powerup::Type type)
    {
        HardpointPlacement *empty_placement = nullptr;
        for (auto i = 0u; i < _hardpoint_placements.size(); i++)
        {
            auto placement = _hardpoint_placements[i].get();
            if (placement->hardpoint() == nullptr)
            {
                empty_placement = placement;
                break;
            }
        }

        if (empty_placement == nullptr)
        {
            return;
        }

        if (type == Powerup::BULLET)
        {
            auto pattern_bullet = GameSystem::main()->bullet_manager().find_src_pattern_bullet("player_bullet_small");
            auto pattern_turret = new PatternBulletHardpoint(*pattern_bullet, Group::PLAYER);
            auto bullet_turret_texture = TextureManager::texture("bullet_turret");
            pattern_turret->texture(bullet_turret_texture);
            pattern_turret->target(_target);

            empty_placement->hardpoint(pattern_turret);
            add_hardpoint(pattern_turret);
        }
        if (type == Powerup::BEAM)
        {
            auto beam_blueprint = GameSystem::main()->beam_manager().find_src_beam("beam1");
            auto beam_turret = new BeamHardpoint(*beam_blueprint, Group::PLAYER);

            auto beam_turret_texture = TextureManager::texture("beam_turret");
            beam_turret->texture(beam_turret_texture);
            beam_turret->target(_target);

            empty_placement->hardpoint(beam_turret);
            add_hardpoint(beam_turret);
        }
        if (type == Powerup::HOMING)
        {
            auto homing_blueprint = GameSystem::main()->bullet_manager().find_src_homing_bullet("homing_blue");
            auto homing_turret = new HomingBulletHardpoint(*homing_blueprint, Group::PLAYER);

            auto bullet_turret_texture = TextureManager::texture("bullet_turret");
            homing_turret->texture(bullet_turret_texture);
            homing_turret->target(_target);

            empty_placement->hardpoint(homing_turret);
            add_hardpoint(homing_turret);
        }
    }

    void Player::add_hardpoint_placement(HardpointPlacement *placement)
    {
        _hardpoint_placements.push_back(std::unique_ptr<HardpointPlacement>(placement));
    }
    void Player::add_thruster_placement(float x, float y, float rotation, float size)
    {
        auto thruster = new Thruster();
        thruster->setPosition(x, y);
        thruster->setRotation(rotation);
        thruster->thrust_size(size);
        add_thruster(thruster);
    }
}
<commit_msg>- Semi working look at target now.<commit_after>#include "player.h"

#include "game_system.h"
#include "bullet.h"
#include "utils.h"
#include "texture_manager.h"

#include <iostream>

namespace vot
{
    Player::Player(const sf::Texture &texture) :
        Character(texture),
        _cooldown(0.0f),
        _homing_cooldown(0.0f),
        _look_at_target(false),
        _auto_target(true),
        _target(nullptr),
        _powerup_hitbox(20.0f)
    {

    }

    void Player::init()
    {
        add_hardpoint_placement(new HardpointPlacement(0, 8, 225, 315));
        add_hardpoint_placement(new HardpointPlacement(-16, 4, 180, 300));
        add_hardpoint_placement(new HardpointPlacement(16, 4, 240, 0));
        add_hardpoint_placement(new HardpointPlacement(20, 10, 270, 45));
        add_hardpoint_placement(new HardpointPlacement(-20, 10, 75, 270));

        create_new_hardpoint(Powerup::BULLET);

        add_thruster_placement(28, 0, 0, 0.35f);
        add_thruster_placement(28, 0, 180, 0.35f);
        add_thruster_placement(-28, 0, 180, 0.35f);
        add_thruster_placement(-28, 0, 0, 0.35f);

        add_thruster_placement(-8, 14, 180, 0.5f);
        add_thruster_placement(8, 14, 180, 0.5f);
        add_thruster_placement(8, -8, 0, 0.35f);
        add_thruster_placement(-8, -8, 0, 0.35f);

        add_thruster_placement(-28, 3, 270, 0.35f);
        add_thruster_placement(28, 3, 90, 0.35f);
    }

    void Player::update(float dt)
    {
        auto gs = GameSystem::main();

        // Keyboard input {{{
        sf::Vector2f acc;
        float rot_acc = 0.0f;

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
        {
            acc.x -= strafe_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
        {
            acc.x += strafe_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
        {
            acc.y += backwards_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
        {
            acc.y -= forwards_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q))
        {
            rot_acc -= rot_speed();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
        {
            rot_acc += rot_speed();
        }

        if (gs->is_key_pressed(sf::Keyboard::T))
        {
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
            {
                _auto_target = !_auto_target;
            }
            else
            {
                target(gs->next_target(_target));
            }
        }
        if (gs->is_key_pressed(sf::Keyboard::Z))
        {
            _look_at_target = !_look_at_target;
        }
        // }}}

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
        {
            auto points = hardpoints();
            for (auto i = 0u; i < points->size(); i++)
            {
                points->at(i)->fire();
            }
        }

        if (_look_at_target && _target != nullptr)
        {
            auto time_to_stop = 0.0f;
            if (rot_acceleration() != 0.0f)
            {
                time_to_stop = rot_velocity() / rot_acceleration();
            }
            auto distance_to_stop = rot_velocity() * time_to_stop + 0.5f * rot_acceleration() * time_to_stop * time_to_stop;

            auto angles = Utils::calculate_angles(getPosition(), _target->getPosition(), rotation(), -90.0f);

            auto abs_delta = Utils::abs(angles.delta_angle());
            auto diff = abs_delta - Utils::abs(distance_to_stop);
            auto dir_speed = (angles.delta_angle() > 0) ? -rot_speed() : rot_speed();
            if (abs_delta > 0.1f && Utils::abs(rot_velocity()) < 0.1f)
            {
                if (diff > 0.1f)
                {
                    rot_acc -= dir_speed;
                }
                else if (diff < -0.1f)
                {
                    rot_acc += dir_speed;
                }
            }
            else if (diff < 0)
            {
                if (diff < -0.1f)
                {
                    rot_acc -= dir_speed;
                }
            }
            else if (diff > 0.1f)
            {
                rot_acc += dir_speed;
            }
            //rot_spd *= dt;
            /*
            if (angles.delta_angle() < rot_spd && angles.delta_angle() > -rot_spd)
            {
                //rotation(angles.to_angle());
                //rot_acc -= angles.delta_angle();
            }
            else
            {
                rot_acc += (angles.delta_angle() > 0) ? -rot_speed() : rot_speed();
                //rotateBy(angles.delta_angle() > 0 ? -rot_spd : rot_spd);
            }
            */
        }

        acceleration(acc);
        rot_acceleration(rot_acc);

        _cooldown -= dt;
        _homing_cooldown -= dt;

        Character::update(dt);

        _powerup_hitbox.location(getPosition());
    }

    void Player::target(Enemy *value)
    {
        _target = value;

        auto points = hardpoints();
        for (auto i = 0u; i < points->size(); i++)
        {
            points->at(i)->target(value);
        }
    }
    Enemy *Player::target() const
    {
        return _target;
    }

    bool Player::looking_at_target() const
    {
        return _look_at_target;
    }
    bool Player::auto_target() const
    {
        return _auto_target;
    }

    Circle &Player::powerup_hitbox()
    {
        return _powerup_hitbox;
    }

    void Player::add_powerup(const Powerup &powerup)
    {
        create_new_hardpoint(powerup.type());
    }
    void Player::create_new_hardpoint(Powerup::Type type)
    {
        HardpointPlacement *empty_placement = nullptr;
        for (auto i = 0u; i < _hardpoint_placements.size(); i++)
        {
            auto placement = _hardpoint_placements[i].get();
            if (placement->hardpoint() == nullptr)
            {
                empty_placement = placement;
                break;
            }
        }

        if (empty_placement == nullptr)
        {
            return;
        }

        if (type == Powerup::BULLET)
        {
            auto pattern_bullet = GameSystem::main()->bullet_manager().find_src_pattern_bullet("player_bullet_small");
            auto pattern_turret = new PatternBulletHardpoint(*pattern_bullet, Group::PLAYER);
            auto bullet_turret_texture = TextureManager::texture("bullet_turret");
            pattern_turret->texture(bullet_turret_texture);
            pattern_turret->target(_target);

            empty_placement->hardpoint(pattern_turret);
            add_hardpoint(pattern_turret);
        }
        if (type == Powerup::BEAM)
        {
            auto beam_blueprint = GameSystem::main()->beam_manager().find_src_beam("beam1");
            auto beam_turret = new BeamHardpoint(*beam_blueprint, Group::PLAYER);

            auto beam_turret_texture = TextureManager::texture("beam_turret");
            beam_turret->texture(beam_turret_texture);
            beam_turret->target(_target);

            empty_placement->hardpoint(beam_turret);
            add_hardpoint(beam_turret);
        }
        if (type == Powerup::HOMING)
        {
            auto homing_blueprint = GameSystem::main()->bullet_manager().find_src_homing_bullet("homing_blue");
            auto homing_turret = new HomingBulletHardpoint(*homing_blueprint, Group::PLAYER);

            auto bullet_turret_texture = TextureManager::texture("bullet_turret");
            homing_turret->texture(bullet_turret_texture);
            homing_turret->target(_target);

            empty_placement->hardpoint(homing_turret);
            add_hardpoint(homing_turret);
        }
    }

    void Player::add_hardpoint_placement(HardpointPlacement *placement)
    {
        _hardpoint_placements.push_back(std::unique_ptr<HardpointPlacement>(placement));
    }
    void Player::add_thruster_placement(float x, float y, float rotation, float size)
    {
        auto thruster = new Thruster();
        thruster->setPosition(x, y);
        thruster->setRotation(rotation);
        thruster->thrust_size(size);
        add_thruster(thruster);
    }
}
<|endoftext|>


<commit_before>//! @Yue Wang
//!
//! Exercise 10.13:
//! The library defines an algorithm named partition that takes a predicate
//! and partitions the container so that values for which the predicate is
//! true appear in the first part and those for which the predicate is false
//! appear in the second part. The algorithm returns an iterator just past
//! the last element for which the predicate returned true. Write a function
//! that takes a string and returns a bool indicating whether the string has
//! five characters or more. Use that function to partition words. Print the
//! elements that have five or more characters.
//!

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

bool predicate(const std::string &s)
{
    return s.size() >= 5;
}

int main()
{
    auto v = std::vector<std::string>{ "a", "as", "aasss", "aaaaassaa", "aaaaaabba", "aaa" };
    auto pivot = std::partition(v.begin(), v.end(), predicate);
    for (auto it = v.cbegin(); it != pivot; ++it)
        std::cout << *it << " ";
    std::cout << std::endl;

    return 0;
}
<commit_msg>Update ex10_13.cpp<commit_after>//! @Yue Wang
//!
//! Exercise 10.13:
//! The library defines an algorithm named partition that takes a predicate
//! and partitions the container so that values for which the predicate is
//! true appear in the first part and those for which the predicate is false
//! appear in the second part. The algorithm returns an iterator just past
//! the last element for which the predicate returned true. Write a function
//! that takes a string and returns a bool indicating whether the string has
//! five characters or more. Use that function to partition words. Print the
//! elements that have five or more characters.
//!

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

bool predicate(const std::string &s)
{
    return s.size() >= 5;
}

int main()
{
    auto v = std::vector<std::string>{ "a", "as", "aasss", "aaaaassaa", "aaaaaabba", "aaa" };
    auto pivot = std::partition(v.begin(), v.end(), predicate);

    for (auto it = v.cbegin(); it != pivot; ++it)
        std::cout << *it << " ";
    std::cout << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>#include "ex14_32.h"
#include "ex14_30_StrBlob.h"
#include <iostream>

StrBlobPtr&
StrBlobPtr_pointer::operator *()
{
    return *(this->pointer);
}

StrBlobPtr*
StrBlobPtr_pointer::operator ->()
{
    return & this->operator *();
}

int main()
{
    StrBlob sb{ "hello", "world" };
    StrBlobPtr iter = sb.begin();
    StrBlobPtr_pointer p(&iter);
    std::cout << p->deref() << std::endl;
}
<commit_msg>Update ex14_32.cpp<commit_after>#include "ex14_32.h"
#include "ex14_30_StrBlob.h"
#include <iostream>

StrBlobPtr&
StrBlobPtr_pointer::operator *() const
{
    return *pointer;
}

StrBlobPtr*
StrBlobPtr_pointer::operator ->() const
{
    return pointer;
}

int main()
{
    StrBlob sb{ "hello", "world" };
    StrBlobPtr iter = sb.begin();
    StrBlobPtr_pointer p(&iter);
    std::cout << p->deref() << std::endl;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <cassert>
#include <cmath>
#include <limits>
#include <sstream>
#include "ppapi/cpp/audio.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"

namespace {
const char* const kPlaySoundId = "playSound";
const char* const kStopSoundId = "stopSound";
const char* const kSetFrequencyId = "setFrequency";
static const char kMessageArgumentSeparator = ':';

const double kDefaultFrequency = 440.0;
const double kPi = 3.141592653589;
const double kTwoPi = 2.0 * kPi;
// The sample count we will request.
const uint32_t kSampleFrameCount = 4096u;
// Only supporting stereo audio for now.
const uint32_t kChannels = 2u;
}  // namespace

namespace sine_synth {
// The Instance class.  One of these exists for each instance of your NaCl
// module on the web page.  The browser will ask the Module object to create
// a new Instance for each occurrence of the <embed> tag that has these
// attributes:
//     type="application/x-nacl"
//     src="sine_synth.nmf"
class SineSynthInstance : public pp::Instance {
 public:
  explicit SineSynthInstance(PP_Instance instance)
      : pp::Instance(instance),
        frequency_(kDefaultFrequency),
        theta_(0),
        sample_frame_count_(kSampleFrameCount) {}
  virtual ~SineSynthInstance() {}

  // Called by the browser once the NaCl module is loaded and ready to
  // initialize.  Creates a Pepper audio context and initializes it. Returns
  // true on success.  Returning false causes the NaCl module to be deleted and
  // no other functions to be called.
  virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]);

  // Called by the browser to handle the postMessage() call in Javascript.
  // |var_message| is expected to be a string that contains the name of the
  // method to call.  Note that the setFrequency method takes a single
  // parameter, the frequency.  The frequency parameter is encoded as a string
  // and appended to the 'setFrequency' method name after a ':'.  Examples
  // of possible message strings are:
  //     playSound
  //     stopSound
  //     setFrequency:880
  // If |var_message| is not a recognized method name, this method does nothing.
  virtual void HandleMessage(const pp::Var& var_message);

  // Set the frequency of the sine wave to |frequency|.  Posts a message back
  // to the browser with the new frequency value.
  void SetFrequency(double frequency);

  // The frequency property accessor.
  double frequency() const { return frequency_; }

 private:
  static void SineWaveCallback(void* samples,
                               uint32_t buffer_size,
                               void* data) {
    SineSynthInstance* sine_synth_instance =
        reinterpret_cast<SineSynthInstance*>(data);
    const double frequency = sine_synth_instance->frequency();
    const double delta = kTwoPi * frequency / PP_AUDIOSAMPLERATE_44100;
    const int16_t max_int16 = std::numeric_limits<int16_t>::max();

    int16_t* buff = reinterpret_cast<int16_t*>(samples);

    // Make sure we can't write outside the buffer.
    assert(buffer_size >= (sizeof(*buff) * kChannels *
                           sine_synth_instance->sample_frame_count_));

    for (size_t sample_i = 0;
         sample_i < sine_synth_instance->sample_frame_count_;
         ++sample_i, sine_synth_instance->theta_ += delta) {
      // Keep theta_ from going beyond 2*Pi.
      if (sine_synth_instance->theta_ > kTwoPi) {
        sine_synth_instance->theta_ -= kTwoPi;
      }
      double sin_value(std::sin(sine_synth_instance->theta_));
      int16_t scaled_value = static_cast<int16_t>(sin_value * max_int16);
      for (size_t channel = 0; channel < kChannels; ++channel) {
        *buff++ = scaled_value;
      }
    }
  }

  pp::Audio audio_;
  double frequency_;

  // The last parameter sent to the sin function.  Used to prevent sine wave
  // skips on buffer boundaries.
  double theta_;

  // The count of sample frames per channel in an audio buffer.
  uint32_t sample_frame_count_;
};

bool SineSynthInstance::Init(uint32_t argc,
                             const char* argn[],
                             const char* argv[]) {
  // Ask the device for an appropriate sample count size.
  sample_frame_count_ =
      pp::AudioConfig::RecommendSampleFrameCount(PP_AUDIOSAMPLERATE_44100,
                                                 kSampleFrameCount);
  audio_ = pp::Audio(this,
                     pp::AudioConfig(this,
                                     PP_AUDIOSAMPLERATE_44100,
                                     sample_frame_count_),
                     SineWaveCallback,
                     this);
  return true;
}

void SineSynthInstance::HandleMessage(const pp::Var& var_message) {
  if (!var_message.is_string()) {
    return;
  }
  std::string message = var_message.AsString();
  if (message == kPlaySoundId) {
    audio_.StartPlayback();
  } else if (message == kStopSoundId) {
    audio_.StopPlayback();
  } else if (message.find(kSetFrequencyId) == 0) {
    // The argument to setFrequency is everything after the first ':'.
    size_t sep_pos = message.find_first_of(kMessageArgumentSeparator);
    if (sep_pos != std::string::npos) {
      std::string string_arg = message.substr(sep_pos + 1);
      // Got the argument value as a string: try to convert it to a number.
      std::istringstream stream(string_arg);
      double double_value;
      if (stream >> double_value) {
        SetFrequency(double_value);
        return;
      }
    }
  }
}

void SineSynthInstance::SetFrequency(double frequency) {
  frequency_ = frequency;
  PostMessage(pp::Var(frequency_));
}

// The Module class.  The browser calls the CreateInstance() method to create
// an instance of your NaCl module on the web page.  The browser creates a new
// instance for each <embed> tag with type="application/x-nacl".
class SineSynthModule : public pp::Module {
 public:
  SineSynthModule() : pp::Module() {}
  ~SineSynthModule() {}

  // Create and return a HelloWorldInstance object.
  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new SineSynthInstance(instance);
  }
};

}  // namespace sine_synth

// Factory function called by the browser when the module is first loaded.
// The browser keeps a singleton of this module.  It calls the
// CreateInstance() method on the object you return to make instances.  There
// is one instance per <embed> tag on the page.  This is the main binding
// point for your NaCl module with the browser.
namespace pp {
Module* CreateModule() {
  return new sine_synth::SineSynthModule();
}
}  // namespace pp
<commit_msg>Fix sine_synth example BUG=NONE TEST=this is the test / example. Review URL: https://chromiumcodereview.appspot.com/9421019<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <cassert>
#include <cmath>
#include <limits>
#include <sstream>
#include "ppapi/cpp/audio.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"

namespace {
const char* const kPlaySoundId = "playSound";
const char* const kStopSoundId = "stopSound";
const char* const kSetFrequencyId = "setFrequency";
static const char kMessageArgumentSeparator = ':';

const double kDefaultFrequency = 440.0;
const double kPi = 3.141592653589;
const double kTwoPi = 2.0 * kPi;
// The sample count we will request.
const uint32_t kSampleFrameCount = 4096u;
// Only supporting stereo audio for now.
const uint32_t kChannels = 2u;
}  // namespace

namespace sine_synth {
// The Instance class.  One of these exists for each instance of your NaCl
// module on the web page.  The browser will ask the Module object to create
// a new Instance for each occurrence of the <embed> tag that has these
// attributes:
//     type="application/x-nacl"
//     src="sine_synth.nmf"
class SineSynthInstance : public pp::Instance {
 public:
  explicit SineSynthInstance(PP_Instance instance)
      : pp::Instance(instance),
        frequency_(kDefaultFrequency),
        theta_(0),
        sample_frame_count_(kSampleFrameCount) {}
  virtual ~SineSynthInstance() {}

  // Called by the browser once the NaCl module is loaded and ready to
  // initialize.  Creates a Pepper audio context and initializes it. Returns
  // true on success.  Returning false causes the NaCl module to be deleted and
  // no other functions to be called.
  virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]);

  // Called by the browser to handle the postMessage() call in Javascript.
  // |var_message| is expected to be a string that contains the name of the
  // method to call.  Note that the setFrequency method takes a single
  // parameter, the frequency.  The frequency parameter is encoded as a string
  // and appended to the 'setFrequency' method name after a ':'.  Examples
  // of possible message strings are:
  //     playSound
  //     stopSound
  //     setFrequency:880
  // If |var_message| is not a recognized method name, this method does nothing.
  virtual void HandleMessage(const pp::Var& var_message);

  // Set the frequency of the sine wave to |frequency|.  Posts a message back
  // to the browser with the new frequency value.
  void SetFrequency(double frequency);

  // The frequency property accessor.
  double frequency() const { return frequency_; }

 private:
  static void SineWaveCallback(void* samples,
                               uint32_t buffer_size,
                               void* data) {
    SineSynthInstance* sine_synth_instance =
        reinterpret_cast<SineSynthInstance*>(data);
    const double frequency = sine_synth_instance->frequency();
    const double delta = kTwoPi * frequency / PP_AUDIOSAMPLERATE_44100;
    const int16_t max_int16 = std::numeric_limits<int16_t>::max();

    int16_t* buff = reinterpret_cast<int16_t*>(samples);

    // Make sure we can't write outside the buffer.
    assert(buffer_size >= (sizeof(*buff) * kChannels *
                           sine_synth_instance->sample_frame_count_));

    for (size_t sample_i = 0;
         sample_i < sine_synth_instance->sample_frame_count_;
         ++sample_i, sine_synth_instance->theta_ += delta) {
      // Keep theta_ from going beyond 2*Pi.
      if (sine_synth_instance->theta_ > kTwoPi) {
        sine_synth_instance->theta_ -= kTwoPi;
      }
      double sin_value(std::sin(sine_synth_instance->theta_));
      int16_t scaled_value = static_cast<int16_t>(sin_value * max_int16);
      for (size_t channel = 0; channel < kChannels; ++channel) {
        *buff++ = scaled_value;
      }
    }
  }

  pp::Audio audio_;
  double frequency_;

  // The last parameter sent to the sin function.  Used to prevent sine wave
  // skips on buffer boundaries.
  double theta_;

  // The count of sample frames per channel in an audio buffer.
  uint32_t sample_frame_count_;
};

bool SineSynthInstance::Init(uint32_t argc,
                             const char* argn[],
                             const char* argv[]) {
  // Ask the device for an appropriate sample count size.
  sample_frame_count_ =
      pp::AudioConfig::RecommendSampleFrameCount(this,
                                                 PP_AUDIOSAMPLERATE_44100,
                                                 kSampleFrameCount);
  audio_ = pp::Audio(this,
                     pp::AudioConfig(this,
                                     PP_AUDIOSAMPLERATE_44100,
                                     sample_frame_count_),
                     SineWaveCallback,
                     this);
  return true;
}

void SineSynthInstance::HandleMessage(const pp::Var& var_message) {
  if (!var_message.is_string()) {
    return;
  }
  std::string message = var_message.AsString();
  if (message == kPlaySoundId) {
    audio_.StartPlayback();
  } else if (message == kStopSoundId) {
    audio_.StopPlayback();
  } else if (message.find(kSetFrequencyId) == 0) {
    // The argument to setFrequency is everything after the first ':'.
    size_t sep_pos = message.find_first_of(kMessageArgumentSeparator);
    if (sep_pos != std::string::npos) {
      std::string string_arg = message.substr(sep_pos + 1);
      // Got the argument value as a string: try to convert it to a number.
      std::istringstream stream(string_arg);
      double double_value;
      if (stream >> double_value) {
        SetFrequency(double_value);
        return;
      }
    }
  }
}

void SineSynthInstance::SetFrequency(double frequency) {
  frequency_ = frequency;
  PostMessage(pp::Var(frequency_));
}

// The Module class.  The browser calls the CreateInstance() method to create
// an instance of your NaCl module on the web page.  The browser creates a new
// instance for each <embed> tag with type="application/x-nacl".
class SineSynthModule : public pp::Module {
 public:
  SineSynthModule() : pp::Module() {}
  ~SineSynthModule() {}

  // Create and return a HelloWorldInstance object.
  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new SineSynthInstance(instance);
  }
};

}  // namespace sine_synth

// Factory function called by the browser when the module is first loaded.
// The browser keeps a singleton of this module.  It calls the
// CreateInstance() method on the object you return to make instances.  There
// is one instance per <embed> tag on the page.  This is the main binding
// point for your NaCl module with the browser.
namespace pp {
Module* CreateModule() {
  return new sine_synth::SineSynthModule();
}
}  // namespace pp
<|endoftext|>


<commit_before>#include "NL_RenderingEngine.h"

#include "NL_IGameManager.h"
#include "NL_IInputProcessor.h"
#include "NL_ThreadLocal.h"
#include "NL_GlfwWindowManager.h"
#include "NL_EngineServices.h"
#include "NL_SharedData.h"

#include <iostream>

#include "lua.hpp"

namespace NLE
{
	namespace GRAPHICS
	{
		RenderingEngine::RenderingEngine(EngineServices& eServices) :
			_eServices(eServices)
		{
			_windowManager = new GlfwWindowManager(eServices.console);
		}

		RenderingEngine::~RenderingEngine()
		{
			delete _windowManager;
		}

		bool RenderingEngine::initialize(Size2D screenResolution, bool fullscreen, bool decorated, std::wstring title)
		{
			if (!_windowManager->initialize(screenResolution, fullscreen, decorated, title))
				return false;
			return true;
		}

		void RenderingEngine::update(SystemServices* sServices, double deltaT)
		{
			NLE::TLS::PerformanceTimer::reference timer = NLE::TLS::performanceTimer.local();
			timer.deltaT();

			_windowManager->pollEvents();

			DATA::SharedData& data = _eServices.data->getData();
			//data.sysExecutionTimes[RENDERING_ENGINE].set(timer.deltaT());
		}
	}
}<commit_msg>added performance recording to the default rendering engine<commit_after>#include "NL_RenderingEngine.h"

#include "NL_IGameManager.h"
#include "NL_IInputProcessor.h"
#include "NL_ThreadLocal.h"
#include "NL_GlfwWindowManager.h"
#include "NL_EngineServices.h"
#include "NL_SharedData.h"

#include <iostream>

#include "lua.hpp"

namespace NLE
{
	namespace GRAPHICS
	{
		RenderingEngine::RenderingEngine(EngineServices& eServices) :
			_eServices(eServices)
		{
			_windowManager = new GlfwWindowManager(eServices.console);
		}

		RenderingEngine::~RenderingEngine()
		{
			delete _windowManager;
		}

		bool RenderingEngine::initialize(Size2D screenResolution, bool fullscreen, bool decorated, std::wstring title)
		{
			if (!_windowManager->initialize(screenResolution, fullscreen, decorated, title))
				return false;
			return true;
		}

		void RenderingEngine::update(SystemServices* sServices, double deltaT)
		{
			NLE::TLS::PerformanceTimer::reference timer = NLE::TLS::performanceTimer.local();
			timer.deltaT();

			_windowManager->pollEvents();

			DATA::SharedData& data = _eServices.data->getData();
			data.sysExecutionTimes.set(RENDERING_ENGINE, timer.deltaT());
		}
	}
}<|endoftext|>


<commit_before>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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 <cppast/cpp_variable.hpp>
#include <cppast/cpp_namespace.hpp>
#include "GeneratorContext.h"
#include "MoveGlobalsPass.h"

namespace Urho3D
{

bool MoveGlobalsPass::Visit(MetaEntity* entity, cppast::visitor_info info)
{
    if (info.event == info.container_entity_exit)
        return true;

    if (entity->kind_ == cppast::cpp_entity_kind::namespace_t)
    {
        // Convert non-top-level namespaces to classes if they have any functions or variables.
        if (!entity->GetParent()->name_.empty())
        {
            const auto& ns = entity->Ast<cppast::cpp_namespace>();
            for (const auto& child : ns)
            {
                if (child.kind() == cppast::cpp_entity_kind::function_t ||
                    child.kind() == cppast::cpp_entity_kind::variable_t)
                {
                    entity->kind_ = cppast::cpp_entity_kind::class_t;
                    return true;
                }
            }
        }
    }
    else if (entity->kind_ == cppast::cpp_entity_kind::variable_t ||
        entity->kind_ == cppast::cpp_entity_kind::function_t)
    {
        auto& ns = *entity->GetParent();
        if (ns.kind_ != cppast::cpp_entity_kind::class_t)
        {
            std::string className = ns.name_;
            std::string classSymbol = ns.uniqueName_ + "::" + className;

            if (ns.uniqueName_ == className && entity->ast_ != nullptr)
            {
                className = GetFileName(*entity->ast_);
                classSymbol = ns.uniqueName_ + "::" + className;

                auto* toClass = generator->GetSymbol(classSymbol);
                if (toClass == nullptr)
                {
                    std::shared_ptr<MetaEntity> newClass(new MetaEntity());
                    toClass = newClass.get();
                    toClass->name_ = className;
                    toClass->sourceName_ = ns.sourceName_;
                    toClass->uniqueName_ = toClass->symbolName_ = classSymbol;
                    toClass->sourceSymbolName_ = ns.sourceSymbolName_;
                    toClass->kind_ = cppast::cpp_entity_kind::class_t;
                    ns.Add(toClass);
                    generator->symbols_[classSymbol] = toClass->shared_from_this();
                }

                toClass->Add(entity);
            }
        }
    }

    return true;
}

std::string MoveGlobalsPass::GetFileName(const cppast::cpp_entity& entity)
{
    const cppast::cpp_entity* e = &entity;
    while (e->kind() != cppast::cpp_entity_kind::file_t)
        e = &e->parent().value();

    auto fileName = e->name();
    auto index = fileName.rfind('/');
    if (index != std::string::npos)
        fileName = fileName.substr(index + 1);

    index = fileName.find('.');
    if (index != std::string::npos)
        fileName = fileName.substr(0, index);

    return fileName;
}

}
<commit_msg>CSharp: Turn file names to CamelCase when moving globals.<commit_after>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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 <cppast/cpp_variable.hpp>
#include <cppast/cpp_namespace.hpp>
#include "GeneratorContext.h"
#include "MoveGlobalsPass.h"

namespace Urho3D
{

bool MoveGlobalsPass::Visit(MetaEntity* entity, cppast::visitor_info info)
{
    if (info.event == info.container_entity_exit)
        return true;

    if (entity->kind_ == cppast::cpp_entity_kind::namespace_t)
    {
        // Convert non-top-level namespaces to classes if they have any functions or variables.
        if (!entity->GetParent()->name_.empty())
        {
            const auto& ns = entity->Ast<cppast::cpp_namespace>();
            for (const auto& child : ns)
            {
                if (child.kind() == cppast::cpp_entity_kind::function_t ||
                    child.kind() == cppast::cpp_entity_kind::variable_t)
                {
                    entity->kind_ = cppast::cpp_entity_kind::class_t;
                    return true;
                }
            }
        }
    }
    else if (entity->kind_ == cppast::cpp_entity_kind::variable_t ||
        entity->kind_ == cppast::cpp_entity_kind::function_t)
    {
        auto& ns = *entity->GetParent();
        if (ns.kind_ != cppast::cpp_entity_kind::class_t)
        {
            std::string className = ns.name_;
            std::string classSymbol = ns.uniqueName_ + "::" + className;

            if (ns.uniqueName_ == className && entity->ast_ != nullptr)
            {
                className = CamelCaseIdentifier(GetFileName(*entity->ast_));
                classSymbol = ns.uniqueName_ + "::" + className;

                auto* toClass = generator->GetSymbol(classSymbol);
                if (toClass == nullptr)
                {
                    std::shared_ptr<MetaEntity> newClass(new MetaEntity());
                    toClass = newClass.get();
                    toClass->name_ = className;
                    toClass->sourceName_ = ns.sourceName_;
                    toClass->uniqueName_ = toClass->symbolName_ = classSymbol;
                    toClass->sourceSymbolName_ = ns.sourceSymbolName_;
                    toClass->kind_ = cppast::cpp_entity_kind::class_t;
                    ns.Add(toClass);
                    generator->symbols_[classSymbol] = toClass->shared_from_this();
                }

                toClass->Add(entity);
            }
        }
    }

    return true;
}

std::string MoveGlobalsPass::GetFileName(const cppast::cpp_entity& entity)
{
    const cppast::cpp_entity* e = &entity;
    while (e->kind() != cppast::cpp_entity_kind::file_t)
        e = &e->parent().value();

    auto fileName = e->name();
    auto index = fileName.rfind('/');
    if (index != std::string::npos)
        fileName = fileName.substr(index + 1);

    index = fileName.find('.');
    if (index != std::string::npos)
        fileName = fileName.substr(0, index);

    return fileName;
}

}
<|endoftext|>