<commit_before>/* bzflag
 * Copyright (c) 1993-2012 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <stdlib.h>
#include <string>

#include "bzfsAPI.h"

class fairCTF : public bz_Plugin, public bz_CustomSlashCommandHandler
{
public:
  virtual const char* Name (){return "Fair CTF";}

  virtual void Init (const char* config);
  virtual void Cleanup(void );
  virtual void Event (bz_EventData *eventData);

  virtual bool SlashCommand (int playerID, bz_ApiString command, bz_ApiString message, bz_APIStringList *params);

  virtual void DropTeamFlag(int playerID);
  virtual void SetDropTime();
  virtual void UpdateState(bz_eTeamType teamLeaving);
  virtual bool isEven(bz_eTeamType teamLeaving);

  bool allowCTF;
  bool autoMode;

  float max_ratio;
  int max_gap_by_1;
  int max_gap;
  int drop_delay;

  double droptime;
};

BZ_PLUGIN(fairCTF)

void fairCTF::Init ( const char* config )
{
  // Initialize defaults
  allowCTF = true;
  autoMode = true;
  max_ratio = .25;
  max_gap_by_1 = 2;
  max_gap = 3;
  drop_delay = 5;

  // Parse out args

  std::string rawparams = config;

  std::string params[4];
  params[0] = "";
  params[1] = "";
  params[2] = "";
  params[3] = "";

  unsigned int n = 0;

  for(int i = 0; i < rawparams.length(); i++)
  {
    if (rawparams.at(i) == ':')
    {
      n++;

      if (n > 3)
      {
	break;
      }
    }
    else
    {
      params[n] += rawparams.at(i);
    }
  }

  if(params[0].length() > 0)
  {
    float tempratio = atof(params[0].c_str());
    if (tempratio > 0.0)
    {
      max_ratio = tempratio;
    }
  }

  if(params[1].length() > 0)
  {
    int tempmax1gap = atoi(params[1].c_str());
    if (tempmax1gap > 0)
    {
      max_gap_by_1 = tempmax1gap;
    }
  }

  if(params[2].length() > 0)
  {
    int tempmaxgap = atoi(params[2].c_str());
    if (tempmaxgap > 0)
    {
      max_gap = tempmaxgap;
    }
  }

  if(params[3].length() > 0)
  {
    int tempdelay = atoi(params[3].c_str());
    if (tempdelay > 0)
    {
      drop_delay = tempdelay;
    }
  }

  Register(bz_eFlagGrabbedEvent);
  Register(bz_ePlayerJoinEvent);
  Register(bz_ePlayerPartEvent);
  Register(bz_eTickEvent);

  bz_registerCustomSlashCommand ("ctf", this);

  bz_debugMessage(4,"fairCTF plugin loaded");

  UpdateState(eNoTeam);
}

void fairCTF::Cleanup()
{

  Flush();
  bz_removeCustomSlashCommand ("ctf");

  bz_debugMessage(4,"fairCTF plugin unloaded");
}

void fairCTF::Event(bz_EventData *eventData)
{
  if (eventData->eventType == bz_eFlagGrabbedEvent)
  {
    bz_FlagGrabbedEventData_V1* grabData = (bz_FlagGrabbedEventData_V1*)eventData;

    if (!allowCTF)
    {
      // Don't allow a team flag grab
      DropTeamFlag(grabData->playerID);
    }
  }
  else if (eventData->eventType == bz_ePlayerJoinEvent)
  {
    UpdateState(eNoTeam);
  }
  else if (eventData->eventType == bz_ePlayerPartEvent)
  {
    bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;
    // Need to compensate for that leaving player.
    UpdateState(partData->record->team);
  }
  else if (eventData->eventType == bz_eTickEvent)
  {

    if (droptime != 0.0 && bz_getCurrentTime() >= droptime)
    {
      // Time to drop any team flags.
      bz_APIIntList* pl = bz_getPlayerIndexList();

      for (unsigned int x = 0; x < pl->size(); x++)
      {
	DropTeamFlag(pl->get(x));
      }

      droptime = 0.0;
    }
  }
  else
  {
    // Huh?
    return;
  }
}

bool fairCTF::SlashCommand (int playerID, bz_ApiString command, bz_ApiString message, bz_APIStringList *params)
{
  std::string cs = "UNKNOWN";
  bz_BasePlayerRecord* pr = bz_getPlayerByIndex(playerID);
  if (pr != NULL)
  {
    cs = pr->callsign.c_str();
    bz_freePlayerRecord (pr);
  }

  if (!bz_hasPerm(playerID, "FAIRCTF"))
  {
    bz_sendTextMessage(BZ_SERVER, playerID, (cs + ", you do not have permission to use the /ctf command.").c_str());
  }
  else
  {
    if (message == "on")
    {
      if (!autoMode && allowCTF)
      {
	bz_sendTextMessage(BZ_SERVER, playerID, "CTF is already set to \"on\".");
      }
      else
      {
	autoMode = false;
	bz_sendTextMessage (BZ_SERVER, eAdministrators, ("CTF setting has been changed to \"on\" by " + cs + ".").c_str());
	if (!allowCTF)
	{
	  bz_sendTextMessage (BZ_SERVER, BZ_ALLUSERS, ("CTF has been enabled by " + cs + ".").c_str());
	  allowCTF = true;
	}
      }
    }
    else if (message == "off")
    {
      if (!autoMode && !allowCTF)
      {
	bz_sendTextMessage(BZ_SERVER, playerID, "CTF is already set to \"off\".");
      }
      else
      {
	autoMode = false;
	bz_sendTextMessage (BZ_SERVER, eAdministrators, ("CTF setting has been changed to \"off\" by " + cs + ".").c_str());
	if (allowCTF)
	{
	  bz_sendTextMessage (BZ_SERVER, BZ_ALLUSERS, ("CTF has been disabled by " + cs + ".").c_str());
	  allowCTF = false;
	  SetDropTime();
	}
      }
    }
    else if (message == "auto")
    {
      if (autoMode)
      {
	bz_sendTextMessage(BZ_SERVER, playerID, "CTF is already set to \"auto\".");
      }
      else
      {
	autoMode = true;
	bz_sendTextMessage (BZ_SERVER, eAdministrators, ("CTF setting has been changed to \"auto\" by " + cs + ".").c_str());
	UpdateState(eNoTeam);
      }
    }
    else
    {
      bz_sendTextMessage (BZ_SERVER, playerID, "Usage: /ctf on|off|auto");
    }
  }
  return true;
}

void fairCTF::DropTeamFlag(int playerID)
{
  bz_BasePlayerRecord* droppr = bz_getPlayerByIndex (playerID);

  if (droppr != NULL)
  {
    // Are they carrying a team flag?
    if (droppr->currentFlag == "Red team flag" ||
      droppr->currentFlag == "Green team flag" ||
      droppr->currentFlag == "Blue team flag" ||
      droppr->currentFlag == "Purple team flag")
    {
      bz_removePlayerFlag(playerID);
      bz_sendTextMessage (BZ_SERVER, playerID, "CTF play is currently disabled.");
    }

    bz_freePlayerRecord(droppr);
  }
}

void fairCTF::UpdateState(bz_eTeamType teamLeaving)
{
  if (autoMode)
  {
    bool fair = isEven(teamLeaving);

    if (fair && !allowCTF)
    {
      allowCTF = true;
      bz_sendTextMessage (BZ_SERVER, BZ_ALLUSERS, "Team sizes are sufficiently even. CTF play is now enabled.");
    }
    else if (!fair && allowCTF)
    {
      allowCTF = false;
      bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Team sizes are uneven. CTF play is now disabled.");

      SetDropTime();
    }
  }
}

void fairCTF::SetDropTime()
{
  if (drop_delay >= 0)
  {
    droptime = bz_getCurrentTime() + (double)drop_delay;
    if (drop_delay > 1)
    {
      bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, bz_format("Currently-held team flags will be dropped in %d seconds.", drop_delay));
    }
    else
    {
      bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Currently-held team flags will be dropped in 1 second.");
    }

  }
  else
  {
    bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Currently-held team flags will not be dropped.");
  }
}

bool fairCTF::isEven(bz_eTeamType teamLeaving)
{

  int teamsizes[4];

  teamsizes[0] = bz_getTeamCount (eRedTeam);
  teamsizes[1] = bz_getTeamCount (eGreenTeam);
  teamsizes[2] = bz_getTeamCount (eBlueTeam);
  teamsizes[3] = bz_getTeamCount (ePurpleTeam);

  int leavingTeamIndex = (int)teamLeaving;
  if (leavingTeamIndex >= 1 && leavingTeamIndex <= 4)
  {
    // Decrement the team count for the player that's leaving the game.
    teamsizes[leavingTeamIndex - 1]--;
  }

  //check fairness

  int smallestTeam = 10000; //impossibly high
  int largestTeam = 0;

  for (int x = 0; x < 4; x++)
  {
    if (teamsizes[x] > largestTeam)
    {
      largestTeam = teamsizes[x];
    }
    if (teamsizes[x] != 0 && teamsizes[x] < smallestTeam)
    {
      smallestTeam = teamsizes[x];
    }
  }

  //check differences and ratios

  if (smallestTeam == 10000 || largestTeam == smallestTeam) //equal, or server has no team tanks
  {
    return true;
  }
  if (smallestTeam <= max_gap_by_1) // user-defined cap on a difference of 1
  {
    return false;
  }
  if (largestTeam - smallestTeam == 1) //after UD limit
  {
    return true;
  }
  if ((static_cast<float> (largestTeam - smallestTeam)) / smallestTeam > max_ratio) //greater than specified gap
  {
    return false;
  }
  if (largestTeam - smallestTeam >= max_gap)
  {
    return false;
  }

  return true;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<commit_msg>Fix a few warnings.<commit_after>/* bzflag
 * Copyright (c) 1993-2012 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <stdlib.h>
#include <string>

#include "bzfsAPI.h"

class fairCTF : public bz_Plugin, public bz_CustomSlashCommandHandler
{
public:
  virtual const char* Name (){return "Fair CTF";}

  virtual void Init (const char* config);
  virtual void Cleanup(void );
  virtual void Event (bz_EventData *eventData);

  virtual bool SlashCommand (int playerID, bz_ApiString command, bz_ApiString message, bz_APIStringList *params);

  virtual void DropTeamFlag(int playerID);
  virtual void SetDropTime();
  virtual void UpdateState(bz_eTeamType teamLeaving);
  virtual bool isEven(bz_eTeamType teamLeaving);

  bool allowCTF;
  bool autoMode;

  float max_ratio;
  int max_gap_by_1;
  int max_gap;
  int drop_delay;

  double droptime;
};

BZ_PLUGIN(fairCTF)

void fairCTF::Init ( const char* config )
{
  // Initialize defaults
  allowCTF = true;
  autoMode = true;
  max_ratio = .25;
  max_gap_by_1 = 2;
  max_gap = 3;
  drop_delay = 5;

  // Parse out args

  std::string rawparams = config;

  std::string params[4];
  params[0] = "";
  params[1] = "";
  params[2] = "";
  params[3] = "";

  unsigned int n = 0;

  for(unsigned int i = 0; i < rawparams.length(); i++)
  {
    if (rawparams.at(i) == ':')
    {
      n++;

      if (n > 3)
      {
	break;
      }
    }
    else
    {
      params[n] += rawparams.at(i);
    }
  }

  if(params[0].length() > 0)
  {
    float tempratio = atof(params[0].c_str());
    if (tempratio > 0.0)
    {
      max_ratio = tempratio;
    }
  }

  if(params[1].length() > 0)
  {
    int tempmax1gap = atoi(params[1].c_str());
    if (tempmax1gap > 0)
    {
      max_gap_by_1 = tempmax1gap;
    }
  }

  if(params[2].length() > 0)
  {
    int tempmaxgap = atoi(params[2].c_str());
    if (tempmaxgap > 0)
    {
      max_gap = tempmaxgap;
    }
  }

  if(params[3].length() > 0)
  {
    int tempdelay = atoi(params[3].c_str());
    if (tempdelay > 0)
    {
      drop_delay = tempdelay;
    }
  }

  Register(bz_eFlagGrabbedEvent);
  Register(bz_ePlayerJoinEvent);
  Register(bz_ePlayerPartEvent);
  Register(bz_eTickEvent);

  bz_registerCustomSlashCommand ("ctf", this);

  bz_debugMessage(4,"fairCTF plugin loaded");

  UpdateState(eNoTeam);
}

void fairCTF::Cleanup()
{

  Flush();
  bz_removeCustomSlashCommand ("ctf");

  bz_debugMessage(4,"fairCTF plugin unloaded");
}

void fairCTF::Event(bz_EventData *eventData)
{
  if (eventData->eventType == bz_eFlagGrabbedEvent)
  {
    bz_FlagGrabbedEventData_V1* grabData = (bz_FlagGrabbedEventData_V1*)eventData;

    if (!allowCTF)
    {
      // Don't allow a team flag grab
      DropTeamFlag(grabData->playerID);
    }
  }
  else if (eventData->eventType == bz_ePlayerJoinEvent)
  {
    UpdateState(eNoTeam);
  }
  else if (eventData->eventType == bz_ePlayerPartEvent)
  {
    bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;
    // Need to compensate for that leaving player.
    UpdateState(partData->record->team);
  }
  else if (eventData->eventType == bz_eTickEvent)
  {

    if (droptime != 0.0 && bz_getCurrentTime() >= droptime)
    {
      // Time to drop any team flags.
      bz_APIIntList* pl = bz_getPlayerIndexList();

      for (unsigned int x = 0; x < pl->size(); x++)
      {
	DropTeamFlag(pl->get(x));
      }

      droptime = 0.0;
    }
  }
  else
  {
    // Huh?
    return;
  }
}

bool fairCTF::SlashCommand (int playerID, bz_ApiString /*command*/, bz_ApiString message, bz_APIStringList * /*params*/)
{
  std::string cs = "UNKNOWN";
  bz_BasePlayerRecord* pr = bz_getPlayerByIndex(playerID);
  if (pr != NULL)
  {
    cs = pr->callsign.c_str();
    bz_freePlayerRecord (pr);
  }

  if (!bz_hasPerm(playerID, "FAIRCTF"))
  {
    bz_sendTextMessage(BZ_SERVER, playerID, (cs + ", you do not have permission to use the /ctf command.").c_str());
  }
  else
  {
    if (message == "on")
    {
      if (!autoMode && allowCTF)
      {
	bz_sendTextMessage(BZ_SERVER, playerID, "CTF is already set to \"on\".");
      }
      else
      {
	autoMode = false;
	bz_sendTextMessage (BZ_SERVER, eAdministrators, ("CTF setting has been changed to \"on\" by " + cs + ".").c_str());
	if (!allowCTF)
	{
	  bz_sendTextMessage (BZ_SERVER, BZ_ALLUSERS, ("CTF has been enabled by " + cs + ".").c_str());
	  allowCTF = true;
	}
      }
    }
    else if (message == "off")
    {
      if (!autoMode && !allowCTF)
      {
	bz_sendTextMessage(BZ_SERVER, playerID, "CTF is already set to \"off\".");
      }
      else
      {
	autoMode = false;
	bz_sendTextMessage (BZ_SERVER, eAdministrators, ("CTF setting has been changed to \"off\" by " + cs + ".").c_str());
	if (allowCTF)
	{
	  bz_sendTextMessage (BZ_SERVER, BZ_ALLUSERS, ("CTF has been disabled by " + cs + ".").c_str());
	  allowCTF = false;
	  SetDropTime();
	}
      }
    }
    else if (message == "auto")
    {
      if (autoMode)
      {
	bz_sendTextMessage(BZ_SERVER, playerID, "CTF is already set to \"auto\".");
      }
      else
      {
	autoMode = true;
	bz_sendTextMessage (BZ_SERVER, eAdministrators, ("CTF setting has been changed to \"auto\" by " + cs + ".").c_str());
	UpdateState(eNoTeam);
      }
    }
    else
    {
      bz_sendTextMessage (BZ_SERVER, playerID, "Usage: /ctf on|off|auto");
    }
  }
  return true;
}

void fairCTF::DropTeamFlag(int playerID)
{
  bz_BasePlayerRecord* droppr = bz_getPlayerByIndex (playerID);

  if (droppr != NULL)
  {
    // Are they carrying a team flag?
    if (droppr->currentFlag == "Red team flag" ||
      droppr->currentFlag == "Green team flag" ||
      droppr->currentFlag == "Blue team flag" ||
      droppr->currentFlag == "Purple team flag")
    {
      bz_removePlayerFlag(playerID);
      bz_sendTextMessage (BZ_SERVER, playerID, "CTF play is currently disabled.");
    }

    bz_freePlayerRecord(droppr);
  }
}

void fairCTF::UpdateState(bz_eTeamType teamLeaving)
{
  if (autoMode)
  {
    bool fair = isEven(teamLeaving);

    if (fair && !allowCTF)
    {
      allowCTF = true;
      bz_sendTextMessage (BZ_SERVER, BZ_ALLUSERS, "Team sizes are sufficiently even. CTF play is now enabled.");
    }
    else if (!fair && allowCTF)
    {
      allowCTF = false;
      bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Team sizes are uneven. CTF play is now disabled.");

      SetDropTime();
    }
  }
}

void fairCTF::SetDropTime()
{
  if (drop_delay >= 0)
  {
    droptime = bz_getCurrentTime() + (double)drop_delay;
    if (drop_delay > 1)
    {
      bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, bz_format("Currently-held team flags will be dropped in %d seconds.", drop_delay));
    }
    else
    {
      bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Currently-held team flags will be dropped in 1 second.");
    }

  }
  else
  {
    bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "Currently-held team flags will not be dropped.");
  }
}

bool fairCTF::isEven(bz_eTeamType teamLeaving)
{

  int teamsizes[4];

  teamsizes[0] = bz_getTeamCount (eRedTeam);
  teamsizes[1] = bz_getTeamCount (eGreenTeam);
  teamsizes[2] = bz_getTeamCount (eBlueTeam);
  teamsizes[3] = bz_getTeamCount (ePurpleTeam);

  int leavingTeamIndex = (int)teamLeaving;
  if (leavingTeamIndex >= 1 && leavingTeamIndex <= 4)
  {
    // Decrement the team count for the player that's leaving the game.
    teamsizes[leavingTeamIndex - 1]--;
  }

  //check fairness

  int smallestTeam = 10000; //impossibly high
  int largestTeam = 0;

  for (int x = 0; x < 4; x++)
  {
    if (teamsizes[x] > largestTeam)
    {
      largestTeam = teamsizes[x];
    }
    if (teamsizes[x] != 0 && teamsizes[x] < smallestTeam)
    {
      smallestTeam = teamsizes[x];
    }
  }

  //check differences and ratios

  if (smallestTeam == 10000 || largestTeam == smallestTeam) //equal, or server has no team tanks
  {
    return true;
  }
  if (smallestTeam <= max_gap_by_1) // user-defined cap on a difference of 1
  {
    return false;
  }
  if (largestTeam - smallestTeam == 1) //after UD limit
  {
    return true;
  }
  if ((static_cast<float> (largestTeam - smallestTeam)) / smallestTeam > max_ratio) //greater than specified gap
  {
    return false;
  }
  if (largestTeam - smallestTeam >= max_gap)
  {
    return false;
  }

  return true;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<|endoftext|>


<commit_before>#include "System.h"
System::System()
{
	this->m_inputHandler = NULL;
	this->m_window = NULL;
}

System::~System()
{
}

int System::Shutdown()
{
	int result = 0;
	//Destroy the display window
	SDL_DestroyWindow(m_window);
	//Quit SDL subsystems
	SDL_Quit();
	this->m_graphicsHandler->Shutdown();
	delete this->m_graphicsHandler;
	delete this->m_camera;
	this->m_inputHandler->Shutdown();
	delete this->m_inputHandler;
	this->m_physicsHandler.ShutDown();
	return result;
}

int System::Initialize()
{
	int result = 1;
	this->m_fullscreen = false;
	this->m_running = true;
	this->m_window = NULL;
	//Get the instance if this application
	this->m_hinstance = GetModuleHandle(NULL);

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError());
	}
	else
	{
		printf("SDL succeeded in initializing the window!\n");
	}

	m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (m_window == NULL)
	{
		printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError());
	}
	else
	{
		printf("Window creation succeeded!\n");

		SDL_SysWMinfo wmInfo;
		SDL_VERSION(&wmInfo.version);
		SDL_GetWindowWMInfo(m_window, &wmInfo);
		m_hwnd = wmInfo.info.win.window;
	}

	this->m_graphicsHandler = new GraphicsHandler();
	if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT)))
	{
		printf("GraphicsHandler did not work. RIP!\n");
	}
	this->m_camera = new Camera();
	this->m_camera->Initialize();
	this->m_camera->SetRotationAroundPosOffset(0.0f, 1.0f, 1.0f);
	Camera* oldCam = this->m_graphicsHandler->SetCamera(this->m_camera);
	delete oldCam;
	oldCam = nullptr;
	//Initialize the PhysicsHandler
	this->m_physicsHandler.Initialize();

	//Initialize the InputHandler
	this->m_inputHandler = new InputHandler();
	this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT);

	return result;
}

//Do not place things here without talking to the system designers. Place any update method in the System::Update(float dt) method
int System::Run()
{
	int result = 0;
	LARGE_INTEGER frequency, currTime, prevTime, elapsedTime;
	QueryPerformanceFrequency(&frequency);
	//QueryPerformanceCounter(&prevTime);
	QueryPerformanceCounter(&currTime);
	while (this->m_running)
	{
		prevTime = currTime;
		QueryPerformanceCounter(&currTime);
		elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart;
		elapsedTime.QuadPart *= 1000000;
		elapsedTime.QuadPart /= frequency.QuadPart;
		this->m_physicsHandler.Update();
		//Prepare the InputHandler
		this->m_inputHandler->Update();
		//Handle events and update inputhandler through said events
		result = this->HandleEvents();
		SDL_PumpEvents();
		//Update game
		if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_ESCAPE))
		{
			this->m_running = false;
		}
		if (!this->Update((float)elapsedTime.QuadPart))
		{
			this->m_running = false;
		}
		if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_F))
		{
			this->FullscreenToggle();
		}
		//std::cout << int(totalTime) << "\n";
		//Render
		this->m_graphicsHandler->Render();

	}
	if (this->m_fullscreen)
		this->FullscreenToggle();

	return result;
}

int System::Update(float deltaTime)
{
	int result = 1;
	int translateCameraX = 0, translateCameraY = 0, translateCameraZ = 0;
	int rotateCameraY = 0;
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_W))
	{
		translateCameraZ++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S))
	{
		translateCameraZ--;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_SPACE))
	{
		translateCameraY++;
		if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_LSHIFT))
		{
			translateCameraY *= -1;
		}
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_D))
	{
		translateCameraX++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_A))
	{
		translateCameraX--;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_E))
	{
		rotateCameraY++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_Q))
	{
		rotateCameraY--;
	}
	if (translateCameraY || translateCameraX || translateCameraZ || rotateCameraY)
	{
		DirectX::XMFLOAT3 posTranslation = DirectX::XMFLOAT3(float(translateCameraX) * (deltaTime / 1000000.0f), float(translateCameraY) * (deltaTime / 1000000.0f), float(translateCameraZ) * (deltaTime / 1000000.0f));
		this->m_camera->ApplyLocalTranslation(posTranslation);
		//this->m_camera->AddToLookAt(posTranslation);
		float rotationAmount = DirectX::XM_PI / 6;
		rotationAmount *= deltaTime / 1000000.0f;
		DirectX::XMFLOAT4 newRotation = DirectX::XMFLOAT4(0.0f, rotateCameraY * DirectX::XMScalarSin(rotationAmount / 2.0f), 0.0f, DirectX::XMScalarCos(rotationAmount / 2.0f));
		this->m_camera->SetRotation(newRotation);
		this->m_camera->Update();
	}
	//
	return result;
}

int System::HandleEvents()
{
	SDL_Event m_event;
	while (SDL_PollEvent(&m_event))
	{
		switch (m_event.type)
		{
#pragma region
		case SDL_WINDOWEVENT:
		{
			switch (m_event.window.event)
			{
			case SDL_WINDOWEVENT_ENTER:
			{
				//OnMouseFocus();
				break;
			}
			case SDL_WINDOWEVENT_LEAVE:
			{
				//OnMouseBlur();
				break;
			}
			case SDL_WINDOWEVENT_FOCUS_GAINED:
			{
				//OnInputFocus();
				break;
			}
			case SDL_WINDOWEVENT_FOCUS_LOST:
			{
				//OnInputBlur();
				break;
			}
			case SDL_WINDOWEVENT_SHOWN:
			{
				break;
			}
			case SDL_WINDOWEVENT_HIDDEN:
			{
				break;
			}
			case SDL_WINDOWEVENT_EXPOSED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MOVED:
			{
				break;
			}
			case SDL_WINDOWEVENT_RESIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_SIZE_CHANGED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MINIMIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MAXIMIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_RESTORED:
			{
				break;
			}
			case SDL_WINDOWEVENT_CLOSE:
			{
				break;
			}
			}
			break;
		}
#pragma endregion window events
		case SDL_MOUSEMOTION:
		{
			break;
		}
		case SDL_QUIT:
		{
			//The big X in the corner
			this->m_running = false;
			break;
		}
#pragma region
		case SDL_KEYDOWN:
		{
			//OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);

			this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true);
			break;
		}
		case SDL_KEYUP:
		{
			//OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);
			this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false);
			break;
		}
		case SDL_MOUSEBUTTONDOWN:
		{
			this->m_inputHandler->SetMouseState(m_event.button.button, true);
			break;
		}
		case SDL_MOUSEBUTTONUP:
		{
			this->m_inputHandler->SetMouseState(m_event.button.button, false);
			break;
		}
#pragma endregion Key / Button events
		case SDL_MOUSEWHEEL:
		{
			this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y);
			break;
		}
		}
	}
	return 1;
}

int System::FullscreenToggle()
{
	int result = 0;
	this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
	SDL_SetWindowFullscreen(this->m_window, this->m_fullscreen ? 0 : SDL_WINDOW_FULLSCREEN);
	this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
	return result;
}
<commit_msg>FIX moved the update functions in System to Update()<commit_after>#include "System.h"
System::System()
{
	this->m_inputHandler = NULL;
	this->m_window = NULL;
}

System::~System()
{
}

int System::Shutdown()
{
	int result = 0;
	//Destroy the display window
	SDL_DestroyWindow(m_window);
	//Quit SDL subsystems
	SDL_Quit();
	this->m_graphicsHandler->Shutdown();
	delete this->m_graphicsHandler;
	delete this->m_camera;
	this->m_inputHandler->Shutdown();
	delete this->m_inputHandler;
	this->m_physicsHandler.ShutDown();
	return result;
}

int System::Initialize()
{
	int result = 1;
	this->m_fullscreen = false;
	this->m_running = true;
	this->m_window = NULL;
	//Get the instance if this application
	this->m_hinstance = GetModuleHandle(NULL);

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError());
	}
	else
	{
		printf("SDL succeeded in initializing the window!\n");
	}

	m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (m_window == NULL)
	{
		printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError());
	}
	else
	{
		printf("Window creation succeeded!\n");

		SDL_SysWMinfo wmInfo;
		SDL_VERSION(&wmInfo.version);
		SDL_GetWindowWMInfo(m_window, &wmInfo);
		m_hwnd = wmInfo.info.win.window;
	}

	this->m_graphicsHandler = new GraphicsHandler();
	if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT)))
	{
		printf("GraphicsHandler did not work. RIP!\n");
	}
	this->m_camera = new Camera();
	this->m_camera->Initialize();
	this->m_camera->SetRotationAroundPosOffset(0.0f, 1.0f, 1.0f);
	Camera* oldCam = this->m_graphicsHandler->SetCamera(this->m_camera);
	delete oldCam;
	oldCam = nullptr;
	//Initialize the PhysicsHandler
	this->m_physicsHandler.Initialize();

	//Initialize the InputHandler
	this->m_inputHandler = new InputHandler();
	this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT);

	return result;
}

//Do not place things here without talking to the system designers. Place any update method in the System::Update(float dt) method
int System::Run()
{
	int result = 0;
	LARGE_INTEGER frequency, currTime, prevTime, elapsedTime;
	QueryPerformanceFrequency(&frequency);
	//QueryPerformanceCounter(&prevTime);
	QueryPerformanceCounter(&currTime);
	while (this->m_running)
	{
		prevTime = currTime;
		QueryPerformanceCounter(&currTime);
		elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart;
		elapsedTime.QuadPart *= 1000000;
		elapsedTime.QuadPart /= frequency.QuadPart;
		//Prepare the InputHandler
		this->m_inputHandler->Update();
		//Handle events and update inputhandler through said events
		result = this->HandleEvents();
		SDL_PumpEvents();
		//Update game
		if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_ESCAPE))
		{
			this->m_running = false;
		}
		if (!this->Update((float)elapsedTime.QuadPart))
		{
			this->m_running = false;
		}
		if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_F))
		{
			this->FullscreenToggle();
		}
		//std::cout << int(totalTime) << "\n";

	}
	if (this->m_fullscreen)
		this->FullscreenToggle();

	return result;
}

int System::Update(float deltaTime)
{
	int result = 1;

	int translateCameraX = 0, translateCameraY = 0, translateCameraZ = 0;
	int rotateCameraY = 0;
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_W))
	{
		translateCameraZ++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S))
	{
		translateCameraZ--;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_SPACE))
	{
		translateCameraY++;
		if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_LSHIFT))
		{
			translateCameraY *= -1;
		}
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_D))
	{
		translateCameraX++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_A))
	{
		translateCameraX--;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_E))
	{
		rotateCameraY++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_Q))
	{
		rotateCameraY--;
	}
	if (translateCameraY || translateCameraX || translateCameraZ || rotateCameraY)
	{
		DirectX::XMFLOAT3 posTranslation = DirectX::XMFLOAT3(float(translateCameraX) * (deltaTime / 1000000.0f), float(translateCameraY) * (deltaTime / 1000000.0f), float(translateCameraZ) * (deltaTime / 1000000.0f));
		this->m_camera->ApplyLocalTranslation(posTranslation);
		//this->m_camera->AddToLookAt(posTranslation);
		float rotationAmount = DirectX::XM_PI / 6;
		rotationAmount *= deltaTime / 1000000.0f;
		DirectX::XMFLOAT4 newRotation = DirectX::XMFLOAT4(0.0f, rotateCameraY * DirectX::XMScalarSin(rotationAmount / 2.0f), 0.0f, DirectX::XMScalarCos(rotationAmount / 2.0f));
		this->m_camera->SetRotation(newRotation);
		this->m_camera->Update();
	}

	this->m_physicsHandler.Update();

	//Render
	this->m_graphicsHandler->Render();
	return result;
}

int System::HandleEvents()
{
	SDL_Event m_event;
	while (SDL_PollEvent(&m_event))
	{
		switch (m_event.type)
		{
#pragma region
		case SDL_WINDOWEVENT:
		{
			switch (m_event.window.event)
			{
			case SDL_WINDOWEVENT_ENTER:
			{
				//OnMouseFocus();
				break;
			}
			case SDL_WINDOWEVENT_LEAVE:
			{
				//OnMouseBlur();
				break;
			}
			case SDL_WINDOWEVENT_FOCUS_GAINED:
			{
				//OnInputFocus();
				break;
			}
			case SDL_WINDOWEVENT_FOCUS_LOST:
			{
				//OnInputBlur();
				break;
			}
			case SDL_WINDOWEVENT_SHOWN:
			{
				break;
			}
			case SDL_WINDOWEVENT_HIDDEN:
			{
				break;
			}
			case SDL_WINDOWEVENT_EXPOSED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MOVED:
			{
				break;
			}
			case SDL_WINDOWEVENT_RESIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_SIZE_CHANGED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MINIMIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MAXIMIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_RESTORED:
			{
				break;
			}
			case SDL_WINDOWEVENT_CLOSE:
			{
				break;
			}
			}
			break;
		}
#pragma endregion window events
		case SDL_MOUSEMOTION:
		{
			break;
		}
		case SDL_QUIT:
		{
			//The big X in the corner
			this->m_running = false;
			break;
		}
#pragma region
		case SDL_KEYDOWN:
		{
			//OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);

			this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true);
			break;
		}
		case SDL_KEYUP:
		{
			//OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);
			this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false);
			break;
		}
		case SDL_MOUSEBUTTONDOWN:
		{
			this->m_inputHandler->SetMouseState(m_event.button.button, true);
			break;
		}
		case SDL_MOUSEBUTTONUP:
		{
			this->m_inputHandler->SetMouseState(m_event.button.button, false);
			break;
		}
#pragma endregion Key / Button events
		case SDL_MOUSEWHEEL:
		{
			this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y);
			break;
		}
		}
	}
	return 1;
}

int System::FullscreenToggle()
{
	int result = 0;
	this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
	SDL_SetWindowFullscreen(this->m_window, this->m_fullscreen ? 0 : SDL_WINDOW_FULLSCREEN);
	this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
	return result;
}
<|endoftext|>


<commit_before>// Copyright (C) 2017 Rob Caelers <rob.caelers@gmail.com>
//
// 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.

#define _GLIBCXX_USE_C99

#include <string.h>
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "esp_log.h"

#include "os/Resolver.hpp"
#include "os/NetworkErrors.hpp"

static const char tag[] = "NET";

using namespace os;

Resolver &
Resolver::instance()
{
  static Resolver instance;
  return instance;
}

Resolver::Resolver()
  : task("resolve_task", std::bind(&Resolver::resolve_task, this))
{
}

void
Resolver::resolve_async(std::string host, std::string port, resolved_slot_type slot)
{
  ESP_LOGD(tag, "Resolving %s:%s", host.c_str(), port.c_str());
  queue.emplace(std::move(host), std::move(port), std::move(slot));
}

void
Resolver::resolve_task()
{
  while (true)
    {
      nonstd::optional<ResolveJob> resolve_job(queue.pop());
      if (resolve_job)
        {
          int ret;
          std::error_code ec;
          struct addrinfo hints;
          struct addrinfo *addr_list = nullptr;

          memset(&hints, 0, sizeof(hints));
          hints.ai_family = AF_UNSPEC;

          ret = getaddrinfo(resolve_job->host.c_str(), resolve_job->port.c_str(), &hints, &addr_list);
          if (ret != 0)
            {
              ESP_LOGE(tag, "Failed to resolve %s, error %d", resolve_job->host.c_str(), ret);
              ec = NetworkErrc::NameResolutionFailed;
            }

          resolve_job->slot.call(ec, addr_list);
        }
    }
}
<commit_msg>Reduce memory usage of resolver.<commit_after>// Copyright (C) 2017 Rob Caelers <rob.caelers@gmail.com>
//
// 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.

#define _GLIBCXX_USE_C99

#include <string.h>
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "esp_log.h"

#include "os/Resolver.hpp"
#include "os/NetworkErrors.hpp"

static const char tag[] = "NET";

using namespace os;

Resolver &
Resolver::instance()
{
  static Resolver instance;
  return instance;
}

Resolver::Resolver()
  : task("resolve_task", std::bind(&Resolver::resolve_task, this), Task::CoreId::NoAffinity, 2048)
{
}

void
Resolver::resolve_async(std::string host, std::string port, resolved_slot_type slot)
{
  ESP_LOGD(tag, "Resolving %s:%s", host.c_str(), port.c_str());
  queue.emplace(std::move(host), std::move(port), std::move(slot));
}

void
Resolver::resolve_task()
{
  while (true)
    {
      nonstd::optional<ResolveJob> resolve_job(queue.pop());
      if (resolve_job)
        {
          int ret;
          std::error_code ec;
          struct addrinfo hints;
          struct addrinfo *addr_list = nullptr;

          memset(&hints, 0, sizeof(hints));
          hints.ai_family = AF_UNSPEC;

          ret = getaddrinfo(resolve_job->host.c_str(), resolve_job->port.c_str(), &hints, &addr_list);
          if (ret != 0)
            {
              ESP_LOGE(tag, "Failed to resolve %s, error %d", resolve_job->host.c_str(), ret);
              ec = NetworkErrc::NameResolutionFailed;
            }

          resolve_job->slot.call(ec, addr_list);
        }
    }
}
<|endoftext|>


<commit_before>#include "System.h"
System::System()
{
	this->m_inputHandler = NULL;
	this->m_window = NULL;
}

System::~System()
{
}

int System::Shutdown()
{
	int result = 0;
	//Destroy the display window
	SDL_DestroyWindow(m_window);
	//Quit SDL subsystems
	SDL_Quit();
	this->m_graphicsHandler->Shutdown();
	delete this->m_graphicsHandler;
	delete this->m_camera;
	this->m_inputHandler->Shutdown();
	delete this->m_inputHandler;
	return result;
}

int System::Initialize()
{
	int result = 1;
	this->m_fullscreen = false;
	this->m_running = true;
	this->m_window = NULL;
	//Get the instance if this application
	this->m_hinstance = GetModuleHandle(NULL);

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError());
	}
	else
	{
		printf("SDL succeeded in initializing the window!\n");
	}

	m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (m_window == NULL)
	{
		printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError());
	}
	else
	{
		printf("Window creation succeeded!\n");

		SDL_SysWMinfo wmInfo;
		SDL_VERSION(&wmInfo.version);
		SDL_GetWindowWMInfo(m_window, &wmInfo);
		m_hwnd = wmInfo.info.win.window;
	}

	this->m_graphicsHandler = new GraphicsHandler();
	if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT)))
	{
		printf("GraphicsHandler did not work. RIP!\n");
	}
	this->m_camera = new Camera();
	this->m_camera->Initialize();
	Camera* oldCam = this->m_graphicsHandler->SetCamera(this->m_camera);
	delete oldCam;
	oldCam = nullptr;
	//Initialize the InputHandler
	this->m_inputHandler = new InputHandler();
	this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT);
	return result;
}

//Do not place things here without talking to the system designers. Place any update method in the System::Update(float dt) method
int System::Run()
{
	int result = 0;
	LARGE_INTEGER frequency, currTime, prevTime, elapsedTime;
	QueryPerformanceFrequency(&frequency);
	//QueryPerformanceCounter(&prevTime);
	QueryPerformanceCounter(&currTime);
	while (this->m_running)
	{
		prevTime = currTime;
		QueryPerformanceCounter(&currTime);
		elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart;
		elapsedTime.QuadPart *= 1000000;
		elapsedTime.QuadPart /= frequency.QuadPart;
		//Prepare the InputHandler
		this->m_inputHandler->Update();
		//Handle events and update inputhandler through said events
		result = this->HandleEvents();
		SDL_PumpEvents();
		//Update game
		if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_ESCAPE))
		{
			this->m_running = false;
		}
		if (!this->Update((float)elapsedTime.QuadPart))
		{
			this->m_running = false;
		}
		if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_F))
			this->FullscreenToggle();
		//Render
		this->m_graphicsHandler->Render();

	}
	if (this->m_fullscreen)
		this->FullscreenToggle();

	return result;
}

int System::Update(float deltaTime)
{
	int result = 1;
	int translateCameraX = 0, translateCameraY = 0;
	int rotateCameraY = 0;
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_W))
	{
		translateCameraY++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S))
	{
		translateCameraY--;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_D))
	{
		translateCameraX++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_A))
	{
		translateCameraX--;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_E))
	{
		rotateCameraY++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_Q))
	{
		rotateCameraY--;
	}
	if (translateCameraY || translateCameraX || rotateCameraY)
	{
		DirectX::XMFLOAT3 posTranslation = DirectX::XMFLOAT3(float(translateCameraX) * (deltaTime / 1000000.0f), float(translateCameraY) * (deltaTime / 1000000.0f), 0.0f);
		this->m_camera->AddToCameraPos(posTranslation);
		this->m_camera->AddToLookAt(posTranslation);
		float rotationAmount = DirectX::XM_PI / 8;
		rotationAmount *= deltaTime / 1000000.0f;
		DirectX::XMFLOAT4 newRotation = DirectX::XMFLOAT4(0.0f, rotateCameraY * DirectX::XMScalarSin(rotationAmount / 2.0f), 0.0f, DirectX::XMScalarCos(rotationAmount / 2.0f));
		this->m_camera->SetRotation(newRotation);
		this->m_camera->Update();
	}
	//
	return result;
}

int System::HandleEvents()
{
	SDL_Event m_event;
	while (SDL_PollEvent(&m_event))
	{
		switch (m_event.type)
		{
#pragma region
		case SDL_WINDOWEVENT:
		{
			switch (m_event.window.event)
			{
			case SDL_WINDOWEVENT_ENTER:
			{
				//OnMouseFocus();
				break;
			}
			case SDL_WINDOWEVENT_LEAVE:
			{
				//OnMouseBlur();
				break;
			}
			case SDL_WINDOWEVENT_FOCUS_GAINED:
			{
				//OnInputFocus();
				break;
			}
			case SDL_WINDOWEVENT_FOCUS_LOST:
			{
				//OnInputBlur();
				break;
			}
			case SDL_WINDOWEVENT_SHOWN:
			{
				break;
			}
			case SDL_WINDOWEVENT_HIDDEN:
			{
				break;
			}
			case SDL_WINDOWEVENT_EXPOSED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MOVED:
			{
				break;
			}
			case SDL_WINDOWEVENT_RESIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_SIZE_CHANGED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MINIMIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MAXIMIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_RESTORED:
			{
				break;
			}
			case SDL_WINDOWEVENT_CLOSE:
			{
				break;
			}
			}
			break;
		}
#pragma endregion window events
		case SDL_MOUSEMOTION:
		{
			break;
		}
		case SDL_QUIT:
		{
			//The big X in the corner
			this->m_running = false;
			break;
		}
#pragma region
		case SDL_KEYDOWN:
		{
			//OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);

			this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true);
			break;
		}
		case SDL_KEYUP:
		{
			//OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);
			this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false);
			break;
		}
		case SDL_MOUSEBUTTONDOWN:
		{
			break;
		}
		case SDL_MOUSEBUTTONUP:
		{
			break;
		}
#pragma endregion Key / Button events
		case SDL_MOUSEWHEEL:
		{
			this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y);
			break;
		}
		}
	}
	return 1;
}

int System::FullscreenToggle()
{
	int result = 0;
	this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
	SDL_SetWindowFullscreen(this->m_window, this->m_fullscreen ? 0 : SDL_WINDOW_FULLSCREEN);
	this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
	return result;
}
<commit_msg>UPDATE System fullscreen toggle<commit_after>#include "System.h"
System::System()
{
	this->m_inputHandler = NULL;
	this->m_window = NULL;
}

System::~System()
{
}

int System::Shutdown()
{
	int result = 0;
	//Destroy the display window
	SDL_DestroyWindow(m_window);
	//Quit SDL subsystems
	SDL_Quit();
	this->m_graphicsHandler->Shutdown();
	delete this->m_graphicsHandler;
	delete this->m_camera;
	this->m_inputHandler->Shutdown();
	delete this->m_inputHandler;
	return result;
}

int System::Initialize()
{
	int result = 1;
	this->m_fullscreen = false;
	this->m_running = true;
	this->m_window = NULL;
	//Get the instance if this application
	this->m_hinstance = GetModuleHandle(NULL);

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError());
	}
	else
	{
		printf("SDL succeeded in initializing the window!\n");
	}

	m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (m_window == NULL)
	{
		printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError());
	}
	else
	{
		printf("Window creation succeeded!\n");

		SDL_SysWMinfo wmInfo;
		SDL_VERSION(&wmInfo.version);
		SDL_GetWindowWMInfo(m_window, &wmInfo);
		m_hwnd = wmInfo.info.win.window;
	}

	this->m_graphicsHandler = new GraphicsHandler();
	if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT)))
	{
		printf("GraphicsHandler did not work. RIP!\n");
	}
	this->m_camera = new Camera();
	this->m_camera->Initialize();
	Camera* oldCam = this->m_graphicsHandler->SetCamera(this->m_camera);
	delete oldCam;
	oldCam = nullptr;
	//Initialize the InputHandler
	this->m_inputHandler = new InputHandler();
	this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT);
	return result;
}

//Do not place things here without talking to the system designers. Place any update method in the System::Update(float dt) method
int System::Run()
{
	int result = 0;
	LARGE_INTEGER frequency, currTime, prevTime, elapsedTime;
	QueryPerformanceFrequency(&frequency);
	//QueryPerformanceCounter(&prevTime);
	QueryPerformanceCounter(&currTime);
	while (this->m_running)
	{
		prevTime = currTime;
		QueryPerformanceCounter(&currTime);
		elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart;
		elapsedTime.QuadPart *= 1000000;
		elapsedTime.QuadPart /= frequency.QuadPart;
		//Prepare the InputHandler
		this->m_inputHandler->Update();
		//Handle events and update inputhandler through said events
		result = this->HandleEvents();
		SDL_PumpEvents();
		//Update game
		if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_ESCAPE))
		{
			this->m_running = false;
		}
		if (!this->Update((float)elapsedTime.QuadPart))
		{
			this->m_running = false;
		}
		if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_F))
		{
			this->FullscreenToggle();
		}
		//Render
		this->m_graphicsHandler->Render();

	}
	if (this->m_fullscreen)
		this->FullscreenToggle();

	return result;
}

int System::Update(float deltaTime)
{
	int result = 1;
	int translateCameraX = 0, translateCameraY = 0;
	int rotateCameraY = 0;
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_W))
	{
		translateCameraY++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S))
	{
		translateCameraY--;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_D))
	{
		translateCameraX++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_A))
	{
		translateCameraX--;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_E))
	{
		rotateCameraY++;
	}
	if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_Q))
	{
		rotateCameraY--;
	}
	if (translateCameraY || translateCameraX || rotateCameraY)
	{
		DirectX::XMFLOAT3 posTranslation = DirectX::XMFLOAT3(float(translateCameraX) * (deltaTime / 1000000.0f), float(translateCameraY) * (deltaTime / 1000000.0f), 0.0f);
		this->m_camera->AddToCameraPos(posTranslation);
		this->m_camera->AddToLookAt(posTranslation);
		float rotationAmount = DirectX::XM_PI / 8;
		rotationAmount *= deltaTime / 1000000.0f;
		DirectX::XMFLOAT4 newRotation = DirectX::XMFLOAT4(0.0f, rotateCameraY * DirectX::XMScalarSin(rotationAmount / 2.0f), 0.0f, DirectX::XMScalarCos(rotationAmount / 2.0f));
		this->m_camera->SetRotation(newRotation);
		this->m_camera->Update();
	}
	//
	return result;
}

int System::HandleEvents()
{
	SDL_Event m_event;
	while (SDL_PollEvent(&m_event))
	{
		switch (m_event.type)
		{
#pragma region
		case SDL_WINDOWEVENT:
		{
			switch (m_event.window.event)
			{
			case SDL_WINDOWEVENT_ENTER:
			{
				//OnMouseFocus();
				break;
			}
			case SDL_WINDOWEVENT_LEAVE:
			{
				//OnMouseBlur();
				break;
			}
			case SDL_WINDOWEVENT_FOCUS_GAINED:
			{
				//OnInputFocus();
				break;
			}
			case SDL_WINDOWEVENT_FOCUS_LOST:
			{
				//OnInputBlur();
				break;
			}
			case SDL_WINDOWEVENT_SHOWN:
			{
				break;
			}
			case SDL_WINDOWEVENT_HIDDEN:
			{
				break;
			}
			case SDL_WINDOWEVENT_EXPOSED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MOVED:
			{
				break;
			}
			case SDL_WINDOWEVENT_RESIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_SIZE_CHANGED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MINIMIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_MAXIMIZED:
			{
				break;
			}
			case SDL_WINDOWEVENT_RESTORED:
			{
				break;
			}
			case SDL_WINDOWEVENT_CLOSE:
			{
				break;
			}
			}
			break;
		}
#pragma endregion window events
		case SDL_MOUSEMOTION:
		{
			break;
		}
		case SDL_QUIT:
		{
			//The big X in the corner
			this->m_running = false;
			break;
		}
#pragma region
		case SDL_KEYDOWN:
		{
			//OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);

			this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true);
			break;
		}
		case SDL_KEYUP:
		{
			//OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);
			this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false);
			break;
		}
		case SDL_MOUSEBUTTONDOWN:
		{
			break;
		}
		case SDL_MOUSEBUTTONUP:
		{
			break;
		}
#pragma endregion Key / Button events
		case SDL_MOUSEWHEEL:
		{
			this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y);
			break;
		}
		}
	}
	return 1;
}

int System::FullscreenToggle()
{
	int result = 0;
	this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
	SDL_SetWindowFullscreen(this->m_window, this->m_fullscreen ? 0 : SDL_WINDOW_FULLSCREEN);
	this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
	return result;
}
<|endoftext|>


<commit_before>// Copyright 2008-2009, Google Inc.
// All rights reserved.
//
// 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 Google Inc. 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
// OWNER 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.

// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code.  Currently this tests:
//  Flash
//  Real
//  QuickTime
//  Windows Media Player
//    -this includes both WMP plugins.  npdsplay.dll is the older one that
//     comes with XP.  np-mswmp.dll can be downloaded from Microsoft and
//     needs SP2 or Vista.

#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>

#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <string>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/registry.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/default_plugin/plugin_impl.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kShortWaitTimeout = 10 * 1000;
const int kLongWaitTimeout  = 30 * 1000;

class PluginTest : public UITest {
 protected:
  virtual void SetUp() {
    const testing::TestInfo* const test_info =
        testing::UnitTest::GetInstance()->current_test_info();
    if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
      // The installer adds our process names to the registry key below.  Since
      // the installer might not have run on this machine, add it manually.
      RegKey regkey;
      if (regkey.Open(HKEY_LOCAL_MACHINE,
                      L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
                      KEY_WRITE)) {
        regkey.CreateKey(L"CHROME.EXE", KEY_READ);
      }
    } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
      // When testing the old WMP plugin, we need to force Chrome to not load
      // the new plugin.
      launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
    } else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
      launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,
                                              L"security_tests.dll");
    }

    UITest::SetUp();
  }

  void TestPlugin(const std::wstring& test_case,
                  int timeout,
                  bool mock_http) {
    GURL url = GetTestUrl(test_case, mock_http);
    NavigateToURL(url);
    WaitForFinish(timeout, mock_http);
  }

  // Generate the URL for testing a particular test.
  // HTML for the tests is all located in test_directory\plugin\<testcase>
  // Set |mock_http| to true to use mock HTTP server.
  GURL GetTestUrl(const std::wstring &test_case, bool mock_http) {
    if (mock_http)
      return URLRequestMockHTTPJob::GetMockUrl(L"plugin/" + test_case);

    FilePath path;
    PathService::Get(chrome::DIR_TEST_DATA, &path);
    path = path.AppendASCII("plugin");
    path = path.Append(FilePath::FromWStringHack(test_case));
    return net::FilePathToFileURL(path);
  }

  // Waits for the test case to finish.
  void WaitForFinish(const int wait_time, bool mock_http) {
    const int kSleepTime = 500;      // 2 times per second
    const int kMaxIntervals = wait_time / kSleepTime;

    GURL url = GetTestUrl(L"done", mock_http);
    scoped_refptr<TabProxy> tab(GetActiveTab());

    std::string done_str;
    for (int i = 0; i < kMaxIntervals; ++i) {
      Sleep(kSleepTime);

      // The webpage being tested has javascript which sets a cookie
      // which signals completion of the test.
      std::string cookieName = kTestCompleteCookie;
      tab->GetCookieByName(url, cookieName, &done_str);
      if (!done_str.empty())
        break;
    }

    EXPECT_EQ(kTestCompleteSuccess, done_str);
  }
};

TEST_F(PluginTest, Quicktime) {
  TestPlugin(L"quicktime.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, DISABLED_MediaPlayerNew) {
  TestPlugin(L"wmp_new.html", kShortWaitTimeout, false);
}

// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
  TestPlugin(L"wmp_old.html", kLongWaitTimeout, false);
}

TEST_F(PluginTest, Real) {
  TestPlugin(L"real.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, Flash) {
  TestPlugin(L"flash.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, FlashOctetStream) {
  TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, FlashSecurity) {
  TestPlugin(L"flash.html", kShortWaitTimeout, false);
}

// http://crbug.com/16114
TEST_F(PluginTest, FlashLayoutWhilePainting) {
  TestPlugin(L"flash-layout-while-painting.html", kShortWaitTimeout, true);
}

// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
  TestPlugin(L"Java.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, Silverlight) {
  TestPlugin(L"silverlight.html", kShortWaitTimeout, false);
}
<commit_msg>Try renabling the WMP plugin tests again.  The new one works on my Windows 7 box, the old one I can't run since I don't have an XP box. BUG=4809<commit_after>// Copyright 2008-2009, Google Inc.
// All rights reserved.
//
// 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 Google Inc. 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
// OWNER 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.

// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code.  Currently this tests:
//  Flash
//  Real
//  QuickTime
//  Windows Media Player
//    -this includes both WMP plugins.  npdsplay.dll is the older one that
//     comes with XP.  np-mswmp.dll can be downloaded from Microsoft and
//     needs SP2 or Vista.

#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>

#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <string>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/registry.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/default_plugin/plugin_impl.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kShortWaitTimeout = 10 * 1000;
const int kLongWaitTimeout  = 30 * 1000;

class PluginTest : public UITest {
 protected:
  virtual void SetUp() {
    const testing::TestInfo* const test_info =
        testing::UnitTest::GetInstance()->current_test_info();
    if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
      // The installer adds our process names to the registry key below.  Since
      // the installer might not have run on this machine, add it manually.
      RegKey regkey;
      if (regkey.Open(HKEY_LOCAL_MACHINE,
                      L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
                      KEY_WRITE)) {
        regkey.CreateKey(L"CHROME.EXE", KEY_READ);
      }
    } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
      // When testing the old WMP plugin, we need to force Chrome to not load
      // the new plugin.
      launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
    } else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
      launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,
                                              L"security_tests.dll");
    }

    UITest::SetUp();
  }

  void TestPlugin(const std::wstring& test_case,
                  int timeout,
                  bool mock_http) {
    GURL url = GetTestUrl(test_case, mock_http);
    NavigateToURL(url);
    WaitForFinish(timeout, mock_http);
  }

  // Generate the URL for testing a particular test.
  // HTML for the tests is all located in test_directory\plugin\<testcase>
  // Set |mock_http| to true to use mock HTTP server.
  GURL GetTestUrl(const std::wstring &test_case, bool mock_http) {
    if (mock_http)
      return URLRequestMockHTTPJob::GetMockUrl(L"plugin/" + test_case);

    FilePath path;
    PathService::Get(chrome::DIR_TEST_DATA, &path);
    path = path.AppendASCII("plugin");
    path = path.Append(FilePath::FromWStringHack(test_case));
    return net::FilePathToFileURL(path);
  }

  // Waits for the test case to finish.
  void WaitForFinish(const int wait_time, bool mock_http) {
    const int kSleepTime = 500;      // 2 times per second
    const int kMaxIntervals = wait_time / kSleepTime;

    GURL url = GetTestUrl(L"done", mock_http);
    scoped_refptr<TabProxy> tab(GetActiveTab());

    std::string done_str;
    for (int i = 0; i < kMaxIntervals; ++i) {
      Sleep(kSleepTime);

      // The webpage being tested has javascript which sets a cookie
      // which signals completion of the test.
      std::string cookieName = kTestCompleteCookie;
      tab->GetCookieByName(url, cookieName, &done_str);
      if (!done_str.empty())
        break;
    }

    EXPECT_EQ(kTestCompleteSuccess, done_str);
  }
};

TEST_F(PluginTest, Quicktime) {
  TestPlugin(L"quicktime.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, MediaPlayerNew) {
  TestPlugin(L"wmp_new.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, MediaPlayerOld) {
  TestPlugin(L"wmp_old.html", kLongWaitTimeout, false);
}

TEST_F(PluginTest, Real) {
  TestPlugin(L"real.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, Flash) {
  TestPlugin(L"flash.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, FlashOctetStream) {
  TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, FlashSecurity) {
  TestPlugin(L"flash.html", kShortWaitTimeout, false);
}

// http://crbug.com/16114
TEST_F(PluginTest, FlashLayoutWhilePainting) {
  TestPlugin(L"flash-layout-while-painting.html", kShortWaitTimeout, true);
}

// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
  TestPlugin(L"Java.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, Silverlight) {
  TestPlugin(L"silverlight.html", kShortWaitTimeout, false);
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "mvdQuicklookModel.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbStreamingShrinkImageFilter.h"

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdAlgorithm.h"

namespace mvd
{
/*
  TRANSLATOR mvd::QuicklookModel

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

const char* QuicklookModel::IMAGE_FILE_EXT = ".ql";

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
QuicklookModel
::QuicklookModel( QObject* parent ) :
  VectorImageModel( parent )
{
}

/*******************************************************************************/
QuicklookModel
::~QuicklookModel()
{
}

/*******************************************************************************/
void
QuicklookModel
::virtual_BuildModel( void* context )
{
  //
  // get the parent vector image model
  const VectorImageModel* viModel = GetImageModel< VectorImageModel >();
  assert( viModel!=NULL );

  const DatasetModel* datasetModel = viModel->GetDatasetModel();
  assert( datasetModel!=NULL );

  // Source image file information.
  QFileInfo imageFileInfo( viModel->GetFilename() );

  // Quicklook file information.
  QFileInfo quicklookFileInfo(
    datasetModel->GetDirectory().path(),
    imageFileInfo.completeBaseName()
    + QuicklookModel::IMAGE_FILE_EXT
    + "."
    + imageFileInfo.suffix()
  );

  // Quicklook filename.
  QString quicklookFilename( quicklookFileInfo.filePath() );

  // First time?
  if( !quicklookFileInfo.exists() )
    {
    // Instanciate a quicklook file writer.
    VectorImageFileWriterType::Pointer fileWriter(
      VectorImageFileWriterType::New()
    );

    // Write quicklook file on the disk.
    fileWriter->SetFileName( ToStdString( quicklookFilename ) + ".toto" );
    fileWriter->SetInput( viModel->ToImage() );
    fileWriter->Update();
    }

  // Source stored quicklook image-file.
  // TODO: Remove hard-coded 512x512 px size.
  SetFilename( quicklookFilename, 512, 512 );

  // Initialize RgbaImageModel.
  InitializeRgbaPipeline();
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<commit_msg>BUG: Removed forgotten hard-code string.<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "mvdQuicklookModel.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbStreamingShrinkImageFilter.h"

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdAlgorithm.h"

namespace mvd
{
/*
  TRANSLATOR mvd::QuicklookModel

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

const char* QuicklookModel::IMAGE_FILE_EXT = ".ql";

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
QuicklookModel
::QuicklookModel( QObject* parent ) :
  VectorImageModel( parent )
{
}

/*******************************************************************************/
QuicklookModel
::~QuicklookModel()
{
}

/*******************************************************************************/
void
QuicklookModel
::virtual_BuildModel( void* context )
{
  //
  // get the parent vector image model
  const VectorImageModel* viModel = GetImageModel< VectorImageModel >();
  assert( viModel!=NULL );

  const DatasetModel* datasetModel = viModel->GetDatasetModel();
  assert( datasetModel!=NULL );

  // Source image file information.
  QFileInfo imageFileInfo( viModel->GetFilename() );

  // Quicklook file information.
  QFileInfo quicklookFileInfo(
    datasetModel->GetDirectory().path(),
    imageFileInfo.completeBaseName()
    + QuicklookModel::IMAGE_FILE_EXT
    + "."
    + imageFileInfo.suffix()
  );

  // Quicklook filename.
  QString quicklookFilename( quicklookFileInfo.filePath() );

  // First time?
  if( !quicklookFileInfo.exists() )
    {
    // Instanciate a quicklook file writer.
    VectorImageFileWriterType::Pointer fileWriter(
      VectorImageFileWriterType::New()
    );

    // Write quicklook file on the disk.
    fileWriter->SetFileName( ToStdString( quicklookFilename ) );
    fileWriter->SetInput( viModel->ToImage() );
    fileWriter->Update();
    }

  // Source stored quicklook image-file.
  // TODO: Remove hard-coded 512x512 px size.
  SetFilename( quicklookFilename, 512, 512 );

  // Initialize RgbaImageModel.
  InitializeRgbaPipeline();
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<|endoftext|>


<commit_before>#include "hecl/ClientProcess.hpp"
#include "hecl/Database.hpp"
#include "athena/FileReader.hpp"
#include "BlenderConnection.hpp"

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#else
#include <sys/wait.h>
#endif

namespace hecl
{
static logvisor::Module Log("hecl::ClientProcess");

static int GetCPUCount()
{
#if _WIN32
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    return sysinfo.dwNumberOfProcessors;
#else
    return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}

void ClientProcess::BufferTransaction::run(BlenderToken& btok)
{
    athena::io::FileReader r(m_path.getAbsolutePath(), 32 * 1024, false);
    if (r.hasError())
    {
        Log.report(logvisor::Fatal, _S("unable to background-buffer '%s'"),
                   m_path.getAbsolutePath().c_str());
        return;
    }
    if (m_offset)
        r.seek(m_offset, athena::Begin);
    r.readBytesToBuf(m_targetBuf, m_maxLen);
    m_complete = true;
}

void ClientProcess::CookTransaction::run(BlenderToken& btok)
{
    m_returnResult = m_parent.syncCook(m_path, m_dataSpec, btok);
    m_complete = true;
}

ClientProcess::Worker::Worker(ClientProcess& proc)
: m_proc(proc)
{
    m_thr = std::thread(std::bind(&Worker::proc, this));
}

void ClientProcess::Worker::proc()
{
    while (m_proc.m_running)
    {
        std::unique_lock<std::mutex> lk(m_proc.m_mutex);
        if (m_proc.m_pendingQueue.size())
        {
            std::unique_ptr<Transaction> trans = std::move(m_proc.m_pendingQueue.front());
            m_proc.m_pendingQueue.pop_front();
            lk.unlock();
            trans->run(m_blendTok);
            lk.lock();
            m_proc.m_completedQueue.push_back(std::move(trans));
        }
        m_proc.m_cv.wait(lk);
    }
}

ClientProcess::ClientProcess(int verbosityLevel)
: m_verbosity(verbosityLevel)
{
    int cpuCount = GetCPUCount();
    m_workers.reserve(cpuCount);
    for (int i=0 ; i<cpuCount ; ++i)
        m_workers.emplace_back(*this);
}

const ClientProcess::BufferTransaction*
ClientProcess::addBufferTransaction(const ProjectPath& path, void* target,
                                    size_t maxLen, size_t offset)
{
    std::unique_lock<std::mutex> lk(m_mutex);
    BufferTransaction* ret = new BufferTransaction(*this, path, target, maxLen, offset);
    m_pendingQueue.emplace_back(ret);
    m_cv.notify_one();
    return ret;
}

const ClientProcess::CookTransaction*
ClientProcess::addCookTransaction(const hecl::ProjectPath& path, Database::IDataSpec* spec)
{
    std::unique_lock<std::mutex> lk(m_mutex);
    CookTransaction* ret = new CookTransaction(*this, path, spec);
    m_pendingQueue.emplace_back(ret);
    m_cv.notify_one();
    return ret;
}

bool ClientProcess::syncCook(const hecl::ProjectPath& path, Database::IDataSpec* spec, BlenderToken& btok)
{
    if (spec->canCook(path, btok))
    {
        const Database::DataSpecEntry* specEnt = spec->overrideDataSpec(path, spec->getDataSpecEntry(), btok);
        if (specEnt)
        {
            hecl::ProjectPath cooked = path.getCookedPath(*specEnt);
            spec->doCook(path, cooked, false, btok, [](const SystemChar*) {});
            return true;
        }
    }
    return false;
}

void ClientProcess::swapCompletedQueue(std::list<std::unique_ptr<Transaction>>& queue)
{
    std::unique_lock<std::mutex> lk(m_mutex);
    queue.swap(m_completedQueue);
}

void ClientProcess::shutdown()
{
    if (!m_running)
        return;
    m_running = false;
    m_cv.notify_all();
    for (Worker& worker : m_workers)
        if (worker.m_thr.joinable())
            worker.m_thr.join();
}

}
<commit_msg>Client process worker loop tweak<commit_after>#include "hecl/ClientProcess.hpp"
#include "hecl/Database.hpp"
#include "athena/FileReader.hpp"
#include "BlenderConnection.hpp"

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#else
#include <sys/wait.h>
#endif

namespace hecl
{
static logvisor::Module Log("hecl::ClientProcess");

static int GetCPUCount()
{
#if _WIN32
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    return sysinfo.dwNumberOfProcessors;
#else
    return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}

void ClientProcess::BufferTransaction::run(BlenderToken& btok)
{
    athena::io::FileReader r(m_path.getAbsolutePath(), 32 * 1024, false);
    if (r.hasError())
    {
        Log.report(logvisor::Fatal, _S("unable to background-buffer '%s'"),
                   m_path.getAbsolutePath().c_str());
        return;
    }
    if (m_offset)
        r.seek(m_offset, athena::Begin);
    r.readBytesToBuf(m_targetBuf, m_maxLen);
    m_complete = true;
}

void ClientProcess::CookTransaction::run(BlenderToken& btok)
{
    m_returnResult = m_parent.syncCook(m_path, m_dataSpec, btok);
    m_complete = true;
}

ClientProcess::Worker::Worker(ClientProcess& proc)
: m_proc(proc)
{
    m_thr = std::thread(std::bind(&Worker::proc, this));
}

void ClientProcess::Worker::proc()
{
    while (m_proc.m_running)
    {
        std::unique_lock<std::mutex> lk(m_proc.m_mutex);
        while (m_proc.m_pendingQueue.size())
        {
            std::unique_ptr<Transaction> trans = std::move(m_proc.m_pendingQueue.front());
            m_proc.m_pendingQueue.pop_front();
            lk.unlock();
            trans->run(m_blendTok);
            lk.lock();
            m_proc.m_completedQueue.push_back(std::move(trans));
        }
        m_proc.m_cv.wait(lk);
    }
}

ClientProcess::ClientProcess(int verbosityLevel)
: m_verbosity(verbosityLevel)
{
    int cpuCount = GetCPUCount();
    m_workers.reserve(cpuCount);
    for (int i=0 ; i<cpuCount ; ++i)
        m_workers.emplace_back(*this);
}

const ClientProcess::BufferTransaction*
ClientProcess::addBufferTransaction(const ProjectPath& path, void* target,
                                    size_t maxLen, size_t offset)
{
    std::unique_lock<std::mutex> lk(m_mutex);
    BufferTransaction* ret = new BufferTransaction(*this, path, target, maxLen, offset);
    m_pendingQueue.emplace_back(ret);
    m_cv.notify_one();
    return ret;
}

const ClientProcess::CookTransaction*
ClientProcess::addCookTransaction(const hecl::ProjectPath& path, Database::IDataSpec* spec)
{
    std::unique_lock<std::mutex> lk(m_mutex);
    CookTransaction* ret = new CookTransaction(*this, path, spec);
    m_pendingQueue.emplace_back(ret);
    m_cv.notify_one();
    return ret;
}

bool ClientProcess::syncCook(const hecl::ProjectPath& path, Database::IDataSpec* spec, BlenderToken& btok)
{
    if (spec->canCook(path, btok))
    {
        const Database::DataSpecEntry* specEnt = spec->overrideDataSpec(path, spec->getDataSpecEntry(), btok);
        if (specEnt)
        {
            hecl::ProjectPath cooked = path.getCookedPath(*specEnt);
            spec->doCook(path, cooked, false, btok, [](const SystemChar*) {});
            return true;
        }
    }
    return false;
}

void ClientProcess::swapCompletedQueue(std::list<std::unique_ptr<Transaction>>& queue)
{
    std::unique_lock<std::mutex> lk(m_mutex);
    queue.swap(m_completedQueue);
}

void ClientProcess::shutdown()
{
    if (!m_running)
        return;
    m_running = false;
    m_cv.notify_all();
    for (Worker& worker : m_workers)
        if (worker.m_thr.joinable())
            worker.m_thr.join();
}

}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_PROB_PARETO_CDF_HPP
#define STAN_MATH_PRIM_PROB_PARETO_CDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <cmath>

namespace stan {
namespace math {

template <typename T_y, typename T_scale, typename T_shape>
return_type_t<T_y, T_scale, T_shape> pareto_cdf(const T_y& y,
                                                const T_scale& y_min,
                                                const T_shape& alpha) {
  using T_partials_return = partials_return_t<T_y, T_scale, T_shape>;
  using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;
  using T_y_min_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;
  using T_alpha_ref = ref_type_if_t<!is_constant<T_shape>::value, T_shape>;
  using std::exp;
  using std::log;
  static const char* function = "pareto_cdf";
  check_consistent_sizes(function, "Random variable", y, "Scale parameter",
                         y_min, "Shape parameter", alpha);
  if (size_zero(y, y_min, alpha)) {
    return 1.0;
  }

  T_y_ref y_ref = y;
  T_y_min_ref y_min_ref = y_min;
  T_alpha_ref alpha_ref = alpha;

  check_nonnegative(function, "Random variable", y_ref);
  check_positive_finite(function, "Scale parameter", y_min_ref);
  check_positive_finite(function, "Shape parameter", alpha_ref);

  T_partials_return P(1.0);
  operands_and_partials<T_y_ref, T_y_min_ref, T_alpha_ref> ops_partials(
      y_ref, y_min_ref, alpha_ref);

  scalar_seq_view<T_y> y_vec(y_ref);
  scalar_seq_view<T_scale> y_min_vec(y_min_ref);
  scalar_seq_view<T_shape> alpha_vec(alpha_ref);
  size_t N = max_size(y, y_min, alpha);

  // Explicit return for extreme values
  // The gradients are technically ill-defined, but treated as zero
  for (size_t i = 0; i < stan::math::size(y); i++) {
    if (value_of(y_vec[i]) < value_of(y_min_vec[i])) {
      return ops_partials.build(0.0);
    }
  }

  for (size_t n = 0; n < N; n++) {
    // Explicit results for extreme values
    // The gradients are technically ill-defined, but treated as zero
    if (value_of(y_vec[n]) == INFTY) {
      continue;
    }

    const T_partials_return log_dbl
        = log(value_of(y_min_vec[n]) / value_of(y_vec[n]));
    const T_partials_return y_min_inv_dbl = 1.0 / value_of(y_min_vec[n]);
    const T_partials_return alpha_dbl = value_of(alpha_vec[n]);

    const T_partials_return Pn = 1.0 - exp(alpha_dbl * log_dbl);

    P *= Pn;

    if (!is_constant_all<T_y>::value) {
      ops_partials.edge1_.partials_[n]
          += alpha_dbl * y_min_inv_dbl * exp((alpha_dbl + 1) * log_dbl) / Pn;
    }
    if (!is_constant_all<T_scale>::value) {
      ops_partials.edge2_.partials_[n]
          += -alpha_dbl * y_min_inv_dbl * exp(alpha_dbl * log_dbl) / Pn;
    }
    if (!is_constant_all<T_shape>::value) {
      ops_partials.edge3_.partials_[n]
          += -exp(alpha_dbl * log_dbl) * log_dbl / Pn;
    }
  }

  if (!is_constant_all<T_y>::value) {
    for (size_t n = 0; n < stan::math::size(y); ++n) {
      ops_partials.edge1_.partials_[n] *= P;
    }
  }
  if (!is_constant_all<T_scale>::value) {
    for (size_t n = 0; n < stan::math::size(y_min); ++n) {
      ops_partials.edge2_.partials_[n] *= P;
    }
  }
  if (!is_constant_all<T_shape>::value) {
    for (size_t n = 0; n < stan::math::size(alpha); ++n) {
      ops_partials.edge3_.partials_[n] *= P;
    }
  }
  return ops_partials.build(P);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>bugfix cdf<commit_after>#ifndef STAN_MATH_PRIM_PROB_PARETO_CDF_HPP
#define STAN_MATH_PRIM_PROB_PARETO_CDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <cmath>

namespace stan {
namespace math {

template <typename T_y, typename T_scale, typename T_shape>
return_type_t<T_y, T_scale, T_shape> pareto_cdf(const T_y& y,
                                                const T_scale& y_min,
                                                const T_shape& alpha) {
  using T_partials_return = partials_return_t<T_y, T_scale, T_shape>;
  using T_y_ref = ref_type_t<T_y>;
  using T_y_min_ref = ref_type_t<T_scale>;
  using T_alpha_ref = ref_type_t<T_shape>;
  using std::exp;
  using std::log;
  static const char* function = "pareto_cdf";
  check_consistent_sizes(function, "Random variable", y, "Scale parameter",
                         y_min, "Shape parameter", alpha);
  if (size_zero(y, y_min, alpha)) {
    return 1.0;
  }

  T_y_ref y_ref = y;
  T_y_min_ref y_min_ref = y_min;
  T_alpha_ref alpha_ref = alpha;

  check_nonnegative(function, "Random variable", y_ref);
  check_positive_finite(function, "Scale parameter", y_min_ref);
  check_positive_finite(function, "Shape parameter", alpha_ref);

  T_partials_return P(1.0);
  operands_and_partials<T_y_ref, T_y_min_ref, T_alpha_ref> ops_partials(
      y_ref, y_min_ref, alpha_ref);

  scalar_seq_view<T_y_ref> y_vec(y_ref);
  scalar_seq_view<T_y_min_ref> y_min_vec(y_min_ref);
  scalar_seq_view<T_alpha_ref> alpha_vec(alpha_ref);
  size_t N = max_size(y, y_min, alpha);

  // Explicit return for extreme values
  // The gradients are technically ill-defined, but treated as zero
  for (size_t i = 0; i < stan::math::size(y); i++) {
    if (value_of(y_vec[i]) < value_of(y_min_vec[i])) {
      return ops_partials.build(0.0);
    }
  }

  for (size_t n = 0; n < N; n++) {
    // Explicit results for extreme values
    // The gradients are technically ill-defined, but treated as zero
    if (value_of(y_vec[n]) == INFTY) {
      continue;
    }

    const T_partials_return log_dbl
        = log(value_of(y_min_vec[n]) / value_of(y_vec[n]));
    const T_partials_return y_min_inv_dbl = 1.0 / value_of(y_min_vec[n]);
    const T_partials_return alpha_dbl = value_of(alpha_vec[n]);

    const T_partials_return Pn = 1.0 - exp(alpha_dbl * log_dbl);

    P *= Pn;

    if (!is_constant_all<T_y>::value) {
      ops_partials.edge1_.partials_[n]
          += alpha_dbl * y_min_inv_dbl * exp((alpha_dbl + 1) * log_dbl) / Pn;
    }
    if (!is_constant_all<T_scale>::value) {
      ops_partials.edge2_.partials_[n]
          += -alpha_dbl * y_min_inv_dbl * exp(alpha_dbl * log_dbl) / Pn;
    }
    if (!is_constant_all<T_shape>::value) {
      ops_partials.edge3_.partials_[n]
          += -exp(alpha_dbl * log_dbl) * log_dbl / Pn;
    }
  }

  if (!is_constant_all<T_y>::value) {
    for (size_t n = 0; n < stan::math::size(y); ++n) {
      ops_partials.edge1_.partials_[n] *= P;
    }
  }
  if (!is_constant_all<T_scale>::value) {
    for (size_t n = 0; n < stan::math::size(y_min); ++n) {
      ops_partials.edge2_.partials_[n] *= P;
    }
  }
  if (!is_constant_all<T_shape>::value) {
    for (size_t n = 0; n < stan::math::size(alpha); ++n) {
      ops_partials.edge3_.partials_[n] *= P;
    }
  }
  return ops_partials.build(P);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>