<commit_before>// Copyright (c) 2010 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 "webkit/plugins/npapi/test/plugin_get_javascript_url_test.h"

#include "base/basictypes.h"

// url for "self".
#define SELF_URL "javascript:window.location+\"\""
// The identifier for the self url stream.
#define SELF_URL_STREAM_ID 1

// The identifier for the fetched url stream.
#define FETCHED_URL_STREAM_ID 2

// The maximum chunk size of stream data.
#define STREAM_CHUNK 197

const int kNPNEvaluateTimerID = 100;
const int kNPNEvaluateTimerElapse = 50;

namespace NPAPIClient {

ExecuteGetJavascriptUrlTest::ExecuteGetJavascriptUrlTest(
    NPP id, NPNetscapeFuncs *host_functions)
  : PluginTest(id, host_functions),
    test_started_(false),
#ifdef OS_WIN
    window_(NULL),
#endif
    npn_evaluate_context_(false) {
}

NPError ExecuteGetJavascriptUrlTest::SetWindow(NPWindow* pNPWindow) {
  if (pNPWindow->window == NULL)
    return NPERR_NO_ERROR;

  if (!test_started_) {
    std::string url = SELF_URL;
    HostFunctions()->geturlnotify(id(), url.c_str(), "_top",
                                  reinterpret_cast<void*>(SELF_URL_STREAM_ID));
    test_started_ = true;

#ifdef OS_WIN
    HWND window_handle = reinterpret_cast<HWND>(pNPWindow->window);
    if (!::GetProp(window_handle, L"Plugin_Instance")) {
      // TODO: this propery leaks.
      ::SetProp(window_handle, L"Plugin_Instance", this);
      // We attempt to retreive the NPObject for the plugin instance identified
      // by the NPObjectLifetimeTestInstance2 class as it may not have been
      // instantiated yet.
      SetTimer(window_handle, kNPNEvaluateTimerID, kNPNEvaluateTimerElapse,
               TimerProc);
    }
    window_ = window_handle;
#endif
  }

  return NPERR_NO_ERROR;
}

#ifdef OS_WIN
void CALLBACK ExecuteGetJavascriptUrlTest::TimerProc(
    HWND window, UINT message, UINT timer_id, unsigned long elapsed_time) {
  ExecuteGetJavascriptUrlTest* this_instance =
      reinterpret_cast<ExecuteGetJavascriptUrlTest*>
          (::GetProp(window, L"Plugin_Instance"));

  ::RemoveProp(window, L"Plugin_Instance");

  NPObject *window_obj = NULL;
  this_instance->HostFunctions()->getvalue(this_instance->id(),
                                           NPNVWindowNPObject,
                                           &window_obj);
  if (!window_obj) {
    this_instance->SetError("Failed to get NPObject for plugin instance2");
    this_instance->SignalTestCompleted();
    return;
  }

  std::string script = "javascript:window.location";
  NPString script_string;
  script_string.UTF8Characters = script.c_str();
  script_string.UTF8Length = static_cast<unsigned int>(script.length());
  NPVariant result_var;

  this_instance->npn_evaluate_context_ = true;
  NPError result = this_instance->HostFunctions()->evaluate(
      this_instance->id(), window_obj, &script_string, &result_var);
  this_instance->npn_evaluate_context_ = false;
}
#endif

NPError ExecuteGetJavascriptUrlTest::NewStream(NPMIMEType type,
                                               NPStream* stream,
                                               NPBool seekable,
                                               uint16* stype) {
  if (stream == NULL) {
    SetError("NewStream got null stream");
    return NPERR_INVALID_PARAM;
  }

  if (npn_evaluate_context_) {
    SetError("NewStream received in context of NPN_Evaluate");
    return NPERR_NO_ERROR;
  }

  COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),
                 cast_validity_check);
  unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);
  switch (stream_id) {
    case SELF_URL_STREAM_ID:
      break;
    default:
      SetError("Unexpected NewStream callback");
      break;
  }
  return NPERR_NO_ERROR;
}

int32 ExecuteGetJavascriptUrlTest::WriteReady(NPStream *stream) {
  if (npn_evaluate_context_) {
    SetError("WriteReady received in context of NPN_Evaluate");
    return NPERR_NO_ERROR;
  }
  return STREAM_CHUNK;
}

int32 ExecuteGetJavascriptUrlTest::Write(NPStream *stream, int32 offset,
                                         int32 len, void *buffer) {
  if (stream == NULL) {
    SetError("Write got null stream");
    return -1;
  }
  if (len < 0 || len > STREAM_CHUNK) {
    SetError("Write got bogus stream chunk size");
    return -1;
  }

  if (npn_evaluate_context_) {
    SetError("Write received in context of NPN_Evaluate");
    return len;
  }

  COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),
                 cast_validity_check);
  unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);
  switch (stream_id) {
    case SELF_URL_STREAM_ID:
      self_url_.append(static_cast<char*>(buffer), len);
      break;
    default:
      SetError("Unexpected write callback");
      break;
  }
  // Pretend that we took all the data.
  return len;
}

NPError ExecuteGetJavascriptUrlTest::DestroyStream(NPStream *stream,
                                                   NPError reason) {
  if (stream == NULL) {
    SetError("NewStream got null stream");
    return NPERR_INVALID_PARAM;
  }

#ifdef OS_WIN
  KillTimer(window_, kNPNEvaluateTimerID);
#endif

  if (npn_evaluate_context_) {
    SetError("DestroyStream received in context of NPN_Evaluate");
    return NPERR_NO_ERROR;
  }

  COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),
                 cast_validity_check);
  unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);
  switch (stream_id) {
    case SELF_URL_STREAM_ID:
      // don't care
      break;
    default:
      SetError("Unexpected NewStream callback");
      break;
  }
  return NPERR_NO_ERROR;
}

void ExecuteGetJavascriptUrlTest::URLNotify(const char* url, NPReason reason,
                                            void* data) {
  COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(data),
                 cast_validity_check);

  if (npn_evaluate_context_) {
    SetError("URLNotify received in context of NPN_Evaluate");
    return;
  }

  unsigned long stream_id = reinterpret_cast<unsigned long>(data);
  switch (stream_id) {
    case SELF_URL_STREAM_ID:
      if (strcmp(url, SELF_URL) != 0)
        SetError("URLNotify reported incorrect url for SELF_URL");
      if (self_url_.empty())
        SetError("Failed to obtain window location.");
      SignalTestCompleted();
      break;
    default:
      SetError("Unexpected NewStream callback");
      break;
  }
}

} // namespace NPAPIClient
<commit_msg>Add a non-null check for a pointer to NPAPIClient::ExecuteGetJavascriptUrlTest::TimerProc BUG=106522 TEST=trybot<commit_after>// Copyright (c) 2011 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 "webkit/plugins/npapi/test/plugin_get_javascript_url_test.h"

#include "base/basictypes.h"
#include "base/logging.h"

// url for "self".
#define SELF_URL "javascript:window.location+\"\""
// The identifier for the self url stream.
#define SELF_URL_STREAM_ID 1

// The identifier for the fetched url stream.
#define FETCHED_URL_STREAM_ID 2

// The maximum chunk size of stream data.
#define STREAM_CHUNK 197

const int kNPNEvaluateTimerID = 100;
const int kNPNEvaluateTimerElapse = 50;

namespace NPAPIClient {

ExecuteGetJavascriptUrlTest::ExecuteGetJavascriptUrlTest(
    NPP id, NPNetscapeFuncs *host_functions)
  : PluginTest(id, host_functions),
    test_started_(false),
#ifdef OS_WIN
    window_(NULL),
#endif
    npn_evaluate_context_(false) {
}

NPError ExecuteGetJavascriptUrlTest::SetWindow(NPWindow* pNPWindow) {
  if (pNPWindow->window == NULL)
    return NPERR_NO_ERROR;

  if (!test_started_) {
    std::string url = SELF_URL;
    HostFunctions()->geturlnotify(id(), url.c_str(), "_top",
                                  reinterpret_cast<void*>(SELF_URL_STREAM_ID));
    test_started_ = true;

#ifdef OS_WIN
    HWND window_handle = reinterpret_cast<HWND>(pNPWindow->window);
    if (!::GetProp(window_handle, L"Plugin_Instance")) {
      // TODO: this propery leaks.
      ::SetProp(window_handle, L"Plugin_Instance", this);
      // We attempt to retreive the NPObject for the plugin instance identified
      // by the NPObjectLifetimeTestInstance2 class as it may not have been
      // instantiated yet.
      SetTimer(window_handle, kNPNEvaluateTimerID, kNPNEvaluateTimerElapse,
               TimerProc);
    }
    window_ = window_handle;
#endif
  }

  return NPERR_NO_ERROR;
}

#ifdef OS_WIN
void CALLBACK ExecuteGetJavascriptUrlTest::TimerProc(
    HWND window, UINT message, UINT timer_id, unsigned long elapsed_time) {
  ExecuteGetJavascriptUrlTest* this_instance =
      reinterpret_cast<ExecuteGetJavascriptUrlTest*>
          (::GetProp(window, L"Plugin_Instance"));
  CHECK(this_instance);

  ::RemoveProp(window, L"Plugin_Instance");

  NPObject *window_obj = NULL;
  this_instance->HostFunctions()->getvalue(this_instance->id(),
                                           NPNVWindowNPObject,
                                           &window_obj);
  if (!window_obj) {
    this_instance->SetError("Failed to get NPObject for plugin instance2");
    this_instance->SignalTestCompleted();
    return;
  }

  std::string script = "javascript:window.location";
  NPString script_string;
  script_string.UTF8Characters = script.c_str();
  script_string.UTF8Length = static_cast<unsigned int>(script.length());
  NPVariant result_var;

  this_instance->npn_evaluate_context_ = true;
  NPError result = this_instance->HostFunctions()->evaluate(
      this_instance->id(), window_obj, &script_string, &result_var);
  this_instance->npn_evaluate_context_ = false;
}
#endif

NPError ExecuteGetJavascriptUrlTest::NewStream(NPMIMEType type,
                                               NPStream* stream,
                                               NPBool seekable,
                                               uint16* stype) {
  if (stream == NULL) {
    SetError("NewStream got null stream");
    return NPERR_INVALID_PARAM;
  }

  if (npn_evaluate_context_) {
    SetError("NewStream received in context of NPN_Evaluate");
    return NPERR_NO_ERROR;
  }

  COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),
                 cast_validity_check);
  unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);
  switch (stream_id) {
    case SELF_URL_STREAM_ID:
      break;
    default:
      SetError("Unexpected NewStream callback");
      break;
  }
  return NPERR_NO_ERROR;
}

int32 ExecuteGetJavascriptUrlTest::WriteReady(NPStream *stream) {
  if (npn_evaluate_context_) {
    SetError("WriteReady received in context of NPN_Evaluate");
    return NPERR_NO_ERROR;
  }
  return STREAM_CHUNK;
}

int32 ExecuteGetJavascriptUrlTest::Write(NPStream *stream, int32 offset,
                                         int32 len, void *buffer) {
  if (stream == NULL) {
    SetError("Write got null stream");
    return -1;
  }
  if (len < 0 || len > STREAM_CHUNK) {
    SetError("Write got bogus stream chunk size");
    return -1;
  }

  if (npn_evaluate_context_) {
    SetError("Write received in context of NPN_Evaluate");
    return len;
  }

  COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),
                 cast_validity_check);
  unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);
  switch (stream_id) {
    case SELF_URL_STREAM_ID:
      self_url_.append(static_cast<char*>(buffer), len);
      break;
    default:
      SetError("Unexpected write callback");
      break;
  }
  // Pretend that we took all the data.
  return len;
}

NPError ExecuteGetJavascriptUrlTest::DestroyStream(NPStream *stream,
                                                   NPError reason) {
  if (stream == NULL) {
    SetError("NewStream got null stream");
    return NPERR_INVALID_PARAM;
  }

#ifdef OS_WIN
  KillTimer(window_, kNPNEvaluateTimerID);
#endif

  if (npn_evaluate_context_) {
    SetError("DestroyStream received in context of NPN_Evaluate");
    return NPERR_NO_ERROR;
  }

  COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),
                 cast_validity_check);
  unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);
  switch (stream_id) {
    case SELF_URL_STREAM_ID:
      // don't care
      break;
    default:
      SetError("Unexpected NewStream callback");
      break;
  }
  return NPERR_NO_ERROR;
}

void ExecuteGetJavascriptUrlTest::URLNotify(const char* url, NPReason reason,
                                            void* data) {
  COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(data),
                 cast_validity_check);

  if (npn_evaluate_context_) {
    SetError("URLNotify received in context of NPN_Evaluate");
    return;
  }

  unsigned long stream_id = reinterpret_cast<unsigned long>(data);
  switch (stream_id) {
    case SELF_URL_STREAM_ID:
      if (strcmp(url, SELF_URL) != 0)
        SetError("URLNotify reported incorrect url for SELF_URL");
      if (self_url_.empty())
        SetError("Failed to obtain window location.");
      SignalTestCompleted();
      break;
    default:
      SetError("Unexpected NewStream callback");
      break;
  }
}

} // namespace NPAPIClient
<|endoftext|>


<commit_before>#include "Bombs.h"
#include <utils\Log.h>

Bombs::Bombs(GameContext* context) : _context(context) , _world(context->world) {
	float step = TWO_PI / 36.0f;
	for (int i = 0; i < 36; ++i) {
		_cells[i] = 0.9f + sin(step * static_cast<float>(i) * 12.0f) * 0.4f;
	}
	//_texture = ds::math::buildTexture(0, 440, 60, 60);
	_ring_texture = ds::math::buildTexture(40, 120, 6, 6);
	_scale_path.add(0.0f, v2(0.1f,0.1f));
	_scale_path.add(0.5f, v2(1.5f,1.5f));
	_scale_path.add(0.75f, v2(0.75f,0.75f));
	_scale_path.add(1.0f, v2(1.0f,1.0f));
}

Bombs::~Bombs() {
}

// ---------------------------------------
// create
// ---------------------------------------
void Bombs::create() {
	v2 pos;
	pos.x = ds::math::random(200.0f, 1400.0f);
	pos.y = ds::math::random(200.0f, 700.0f);
	ds::SID sid = _world->create(pos, "Bomb");
	BombData* data = (BombData*)_world->attach_data(sid, sizeof(BombData));
	float angle = ds::math::random(0.0f, TWO_PI);
	float v = ds::math::random(30.0f, 50.0f);
	v2 vel = ds::vector::getRadialVelocity(angle, v);
	_world->moveBy(sid, vel, true);
	_world->setRotation(sid, vel);
	_world->scaleByPath(sid, &_scale_path, _context->settings->bombFlashingTTL);
	data->state = BombData::BS_STARTING;
	_context->particles->start(BOMB_STARTUP, v3(pos));
}

void Bombs::handleEvents(const ds::ActionEventBuffer& buffer) {
	for (int i = 0; i < buffer.events.size(); ++i) {
		const ds::ActionEvent& event = buffer.events[i];
		if (_world->contains(event.sid)) {
			int type = _world->getType(event.sid);
			if (type == OT_BOMB) {
				if (event.type == ds::AT_SCALE_BY_PATH) {
					BombData* data = (BombData*)_world->get_data(event.sid);
					assert(data != 0);
					data->state = BombData::BS_ACTIVE;
				}
			}
		}
	}
}
// ---------------------------------------
// grab bomb
// ---------------------------------------
bool Bombs::grab(const v2& pos, float radius, ds::SID* id) {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		BombData* data = (BombData*)_world->get_data(_bomb_sids[i]);
		assert(data != 0);
		if (data->state == BombData::BS_ACTIVE) {
			v2 p = _world->getPosition(_bomb_sids[i]);
			if (ds::math::checkCircleIntersection(_context->world_pos, radius, p, 20.0f)) {
				data->state = BombData::BS_FOLLOWING;
				_world->stopAction(_bomb_sids[i], ds::AT_MOVE_BY);
				_world->setColor(_bomb_sids[i], ds::Color(0, 192, 32, 255));
				*id = _bomb_sids[i];
				return true;
			}
		}
	}
	return false;
}

// ---------------------------------------
// follow target
// ---------------------------------------
void Bombs::follow(ds::SID id, const v2& target) {
	if (_world->contains(id)) {
		v2 p = _world->getPosition(id);
		float angle = 0.0f;
		ds::math::followRelative(target,p, &angle, 60.0f, 0.02f);
		v2 diff = _context->world_pos - p;
		v2 n = normalize(diff);
		_world->setPosition(id, p);
		_world->setRotation(id,  ds::vector::calculateRotation(n));
	}
}

// ---------------------------------------
// burst
// ---------------------------------------
void Bombs::burst(ds::SID id, float direction) {
	if (_world->contains(id)) {
		BombData* data = (BombData*)_world->get_data(id);
		assert(data != 0);
		v2 p = _world->getPosition(id);
		v2 diff = _context->world_pos - p;
		v2 n = normalize(diff);
		float angle = ds::vector::calculateRotation(n);
		angle += PI;
		v2 vel = ds::vector::getRadialVelocity(angle, 100.0f);
		_world->moveBy(id,vel);
		data->state = BombData::BS_TICKING;
		data->timer = 0.0f;
		//_world->setColor(bomb.sid, ds::Color(128, 0, 0, 255));
		_world->flashColor(id, ds::Color(138, 39, 0), ds::Color(255, 165, 130), 0.3f, -1);
		_world->setRotation(id, vel);
	}
}

// ---------------------------------------
// clear
// ---------------------------------------
void Bombs::clear() {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		_world->remove(_bomb_sids[i]);
	}
}

// ---------------------------------------
// render
// ---------------------------------------
void Bombs::render() {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		BombData* data = (BombData*)_world->get_data(_bomb_sids[i]);
		assert(data != 0);
		if (data->state == BombData::BS_TICKING) {
			float norm = data->timer / _context->settings->bombFlashingTTL;
			v2 p = _world->getPosition(_bomb_sids[i]);
			drawRing(p ,norm);
		}
	}
}

// ---------------------------------------
// draw ring
// ---------------------------------------
void Bombs::drawRing(const v2& pos,float timer) {
	float step = TWO_PI / 36.0f;
	float angle = TWO_PI * timer * 0.2f;
	ds::Color clr(230, 88, 31, 255);
	clr.r = 0.9 + sin(timer * PI) * 0.1f;
	for (int i = 0; i < 36; ++i) {
		float x = pos.x + cos(angle) * BOMB_EXPLOSION_RADIUS * (1.0f + sin(timer * PI * 3.0f) * 0.1f);
		float y = pos.y + sin(angle) * BOMB_EXPLOSION_RADIUS * (1.0f + sin(timer * PI * 3.0f) * 0.1f);
		float d = _cells[i] + sin(timer * PI * 8.0f) * 0.4f;
		ds::sprites::draw(v2(x,y), _ring_texture, 0.0f, d, d, clr);
		angle += step;
	}
}

// ---------------------------------------
// activate
// ---------------------------------------
void Bombs::activate() {
	_spawn_timer = 0.0f;
	clear();
}

// ---------------------------------------
// scale gates
// ---------------------------------------
void Bombs::scaleBombs(EventBuffer* buffer, float dt) {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		BombData* data = (BombData*)_world->get_data(_bomb_sids[i]);
		assert(data != 0);
		if (data->state == BombData::BS_TICKING) {
			data->timer += dt;
			if (data->timer >= _context->settings->bombFlashingTTL) {
				v2 p = _world->getPosition(_bomb_sids[i]);
				_context->particles->start(BOMB_EXPLOSION, v3(p));
				_context->particles->start(BOMB_RING_EXPLOSION, v3(p));
				_context->particles->start(BOMB_DEBRIS, v3(p));
				buffer->add(GameEvent::GE_BOMB_EXPLODED, p);
				_world->remove(_bomb_sids[i]);
			}
		}
	}
}

// ---------------------------------------
// ticks
// ---------------------------------------
void Bombs::tick(EventBuffer* buffer, float dt) {
	// spawn
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	if (num < _context->settings->maxBombs) {
		_spawn_timer += dt;
		if (_spawn_timer > _context->settings->bombStartTTL) {
			_spawn_timer = 0.0f;
			create();
		}
	}
	scaleBombs(buffer, dt);
}

// ---------------------------------------
// check interception
// ---------------------------------------
void Bombs::checkInterception(EventBuffer* buffer, const v2& pos, float radius) {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		BombData* data = (BombData*)_world->get_data(_bomb_sids[i]);
		assert(data != 0);
		if (data->state == BombData::BS_ACTIVE) {
			v2 p = _world->getPosition(_bomb_sids[i]);
			if (ds::math::checkCircleIntersection(_context->world_pos, PLAYER_RADIUS, p, 20.0f)) {
				data->state = BombData::BS_TICKING;
				data->timer = 0.0f;
				_world->flashColor(_bomb_sids[i], ds::Color(138, 39, 0), ds::Color(255, 135, 88), 0.4f, -1);
				buffer->add(GameEvent::GE_BOMB_ACTIVATED, p);
			}
		}
	}
}

// ---------------------------------------
// kill all
// ---------------------------------------
void Bombs::killAll() {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		v2 p = _world->getPosition(_bomb_sids[i]);
		_context->particles->start(BOMB_EXPLOSION, p);
		_world->remove(_bomb_sids[i]);
	}
}<commit_msg>using particle group<commit_after>#include "Bombs.h"
#include <utils\Log.h>

Bombs::Bombs(GameContext* context) : _context(context) , _world(context->world) {
	float step = TWO_PI / 36.0f;
	for (int i = 0; i < 36; ++i) {
		_cells[i] = 0.9f + sin(step * static_cast<float>(i) * 12.0f) * 0.4f;
	}
	//_texture = ds::math::buildTexture(0, 440, 60, 60);
	_ring_texture = ds::math::buildTexture(40, 120, 6, 6);
	_scale_path.add(0.0f, v2(0.1f,0.1f));
	_scale_path.add(0.5f, v2(1.5f,1.5f));
	_scale_path.add(0.75f, v2(0.75f,0.75f));
	_scale_path.add(1.0f, v2(1.0f,1.0f));
}

Bombs::~Bombs() {
}

// ---------------------------------------
// create
// ---------------------------------------
void Bombs::create() {
	v2 pos;
	pos.x = ds::math::random(200.0f, 1400.0f);
	pos.y = ds::math::random(200.0f, 700.0f);
	ds::SID sid = _world->create(pos, "Bomb");
	BombData* data = (BombData*)_world->attach_data(sid, sizeof(BombData));
	float angle = ds::math::random(0.0f, TWO_PI);
	float v = ds::math::random(30.0f, 50.0f);
	v2 vel = ds::vector::getRadialVelocity(angle, v);
	_world->moveBy(sid, vel, true);
	_world->setRotation(sid, vel);
	_world->scaleByPath(sid, &_scale_path, _context->settings->bombFlashingTTL);
	data->state = BombData::BS_STARTING;
	_context->particles->start(BOMB_STARTUP, v3(pos));
}

void Bombs::handleEvents(const ds::ActionEventBuffer& buffer) {
	for (int i = 0; i < buffer.events.size(); ++i) {
		const ds::ActionEvent& event = buffer.events[i];
		if (_world->contains(event.sid)) {
			int type = _world->getType(event.sid);
			if (type == OT_BOMB) {
				if (event.type == ds::AT_SCALE_BY_PATH) {
					BombData* data = (BombData*)_world->get_data(event.sid);
					assert(data != 0);
					data->state = BombData::BS_ACTIVE;
				}
			}
		}
	}
}
// ---------------------------------------
// grab bomb
// ---------------------------------------
bool Bombs::grab(const v2& pos, float radius, ds::SID* id) {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		BombData* data = (BombData*)_world->get_data(_bomb_sids[i]);
		assert(data != 0);
		if (data->state == BombData::BS_ACTIVE) {
			v2 p = _world->getPosition(_bomb_sids[i]);
			if (ds::math::checkCircleIntersection(_context->world_pos, radius, p, 20.0f)) {
				data->state = BombData::BS_FOLLOWING;
				_world->stopAction(_bomb_sids[i], ds::AT_MOVE_BY);
				_world->setColor(_bomb_sids[i], ds::Color(0, 192, 32, 255));
				*id = _bomb_sids[i];
				return true;
			}
		}
	}
	return false;
}

// ---------------------------------------
// follow target
// ---------------------------------------
void Bombs::follow(ds::SID id, const v2& target) {
	if (_world->contains(id)) {
		v2 p = _world->getPosition(id);
		float angle = 0.0f;
		ds::math::followRelative(target,p, &angle, 60.0f, 0.02f);
		v2 diff = _context->world_pos - p;
		v2 n = normalize(diff);
		_world->setPosition(id, p);
		_world->setRotation(id,  ds::vector::calculateRotation(n));
	}
}

// ---------------------------------------
// burst
// ---------------------------------------
void Bombs::burst(ds::SID id, float direction) {
	if (_world->contains(id)) {
		BombData* data = (BombData*)_world->get_data(id);
		assert(data != 0);
		v2 p = _world->getPosition(id);
		v2 diff = _context->world_pos - p;
		v2 n = normalize(diff);
		float angle = ds::vector::calculateRotation(n);
		angle += PI;
		v2 vel = ds::vector::getRadialVelocity(angle, 100.0f);
		_world->moveBy(id,vel);
		data->state = BombData::BS_TICKING;
		data->timer = 0.0f;
		//_world->setColor(bomb.sid, ds::Color(128, 0, 0, 255));
		_world->flashColor(id, ds::Color(138, 39, 0), ds::Color(255, 165, 130), 0.3f, -1);
		_world->setRotation(id, vel);
	}
}

// ---------------------------------------
// clear
// ---------------------------------------
void Bombs::clear() {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		_world->remove(_bomb_sids[i]);
	}
}

// ---------------------------------------
// render
// ---------------------------------------
void Bombs::render() {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		BombData* data = (BombData*)_world->get_data(_bomb_sids[i]);
		assert(data != 0);
		if (data->state == BombData::BS_TICKING) {
			float norm = data->timer / _context->settings->bombFlashingTTL;
			v2 p = _world->getPosition(_bomb_sids[i]);
			drawRing(p ,norm);
		}
	}
}

// ---------------------------------------
// draw ring
// ---------------------------------------
void Bombs::drawRing(const v2& pos,float timer) {
	float step = TWO_PI / 36.0f;
	float angle = TWO_PI * timer * 0.2f;
	ds::Color clr(230, 88, 31, 255);
	clr.r = 0.9 + sin(timer * PI) * 0.1f;
	for (int i = 0; i < 36; ++i) {
		float x = pos.x + cos(angle) * BOMB_EXPLOSION_RADIUS * (1.0f + sin(timer * PI * 3.0f) * 0.1f);
		float y = pos.y + sin(angle) * BOMB_EXPLOSION_RADIUS * (1.0f + sin(timer * PI * 3.0f) * 0.1f);
		float d = _cells[i] + sin(timer * PI * 8.0f) * 0.4f;
		ds::sprites::draw(v2(x,y), _ring_texture, 0.0f, d, d, clr);
		angle += step;
	}
}

// ---------------------------------------
// activate
// ---------------------------------------
void Bombs::activate() {
	_spawn_timer = 0.0f;
	clear();
}

// ---------------------------------------
// scale gates
// ---------------------------------------
void Bombs::scaleBombs(EventBuffer* buffer, float dt) {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		BombData* data = (BombData*)_world->get_data(_bomb_sids[i]);
		assert(data != 0);
		if (data->state == BombData::BS_TICKING) {
			data->timer += dt;
			if (data->timer >= _context->settings->bombFlashingTTL) {
				v2 p = _world->getPosition(_bomb_sids[i]);
				_context->particles->startGroup(1, v3(p));
				buffer->add(GameEvent::GE_BOMB_EXPLODED, p);
				_world->remove(_bomb_sids[i]);
			}
		}
	}
}

// ---------------------------------------
// ticks
// ---------------------------------------
void Bombs::tick(EventBuffer* buffer, float dt) {
	// spawn
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	if (num < _context->settings->maxBombs) {
		_spawn_timer += dt;
		if (_spawn_timer > _context->settings->bombStartTTL) {
			_spawn_timer = 0.0f;
			create();
		}
	}
	scaleBombs(buffer, dt);
}

// ---------------------------------------
// check interception
// ---------------------------------------
void Bombs::checkInterception(EventBuffer* buffer, const v2& pos, float radius) {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		BombData* data = (BombData*)_world->get_data(_bomb_sids[i]);
		assert(data != 0);
		if (data->state == BombData::BS_ACTIVE) {
			v2 p = _world->getPosition(_bomb_sids[i]);
			if (ds::math::checkCircleIntersection(_context->world_pos, PLAYER_RADIUS, p, 20.0f)) {
				data->state = BombData::BS_TICKING;
				data->timer = 0.0f;
				_world->flashColor(_bomb_sids[i], ds::Color(138, 39, 0), ds::Color(255, 135, 88), 0.4f, -1);
				buffer->add(GameEvent::GE_BOMB_ACTIVATED, p);
			}
		}
	}
}

// ---------------------------------------
// kill all
// ---------------------------------------
void Bombs::killAll() {
	int num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);
	for (int i = 0; i < num; ++i) {
		v2 p = _world->getPosition(_bomb_sids[i]);
		_context->particles->start(BOMB_EXPLOSION, p);
		_world->remove(_bomb_sids[i]);
	}
}<|endoftext|>


<commit_before>///
/// anax
/// An open source C++ entity system.
///
/// Copyright (C) 2013-2014 Miguel Martin (miguel@miguel-martin.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.
///

#include <anax/World.hpp>

#include <algorithm>

#include <anax/Config.hpp>

#include <anax/detail/AnaxAssert.hpp>
#include <anax/util/ContainerUtils.hpp>

namespace anax
{
    void World::SystemDeleter::operator() (detail::BaseSystem* system) const
    {
        system->m_world = nullptr;
        system->m_entities.clear();
    }

    World::World() :
        World(DEFAULT_ENTITY_POOL_SIZE)
    {
    }

    World::World(std::size_t entityPoolSize) :
        m_entityIdPool(entityPoolSize),
        m_entityAttributes(entityPoolSize)
    {
    }

    void World::removeAllSystems()
    {
        m_systems.clear();
    }

    Entity World::createEntity()
    {
        checkForResize(1);

        m_entityCache.alive.emplace_back(*this, m_entityIdPool.create());
        return m_entityCache.alive.back();
    }

    std::vector<Entity> World::createEntities(std::size_t amount)
    {
        std::vector<Entity> temp;
        temp.reserve(amount);

        checkForResize(amount);

        for(decltype(amount) i = 0; i < amount; ++i)
        {
            Entity e{*this, m_entityIdPool.create()};
            m_entityCache.alive.push_back(e);
            temp.push_back(e);
        }

        return temp;
    }

    void World::killEntity(Entity& entity)
    {
        // deactivate the entity
        deactivateEntity(entity);

        // now kill the entity (add it to the killed cache)
        m_entityCache.killed.push_back(entity);
    }

    void World::killEntities(std::vector<Entity>& entities)
    {
        for(auto& i : entities)
        {
            killEntity(i);
        }
    }

    void World::activateEntity(Entity& entity)
    {
        ANAX_ASSERT(isValid(entity), "invalid entity tried to be activated");

        m_entityCache.activated.push_back(entity);
    }

    void World::deactivateEntity(Entity& entity)
    {
        ANAX_ASSERT(isValid(entity), "invalid entity tried to be deactivated");

        m_entityCache.deactivated.push_back(entity);
    }

    bool World::isActivated(const Entity& entity) const
    {
        ANAX_ASSERT(isValid(entity), "invalid entity passed to isActivated");

        return m_entityAttributes.attributes[entity.getId().index].activated;
    }

    bool World::isValid(const anax::Entity &entity) const
    {
        return m_entityIdPool.isValid(entity.getId());
    }

    void World::refresh()
    {
        // go through all the activated entities from last call to refresh
        for(auto& entity : m_entityCache.activated)
        {
            auto& attribute = m_entityAttributes.attributes[entity.getId().index];
            attribute.activated = true;

            // loop through all the systems within the world
            for(auto& i : m_systems)
            {
                auto systemIndex = i.first;

                // if the entity passes the filter the system has and is not already part of the system
                if(i.second->getFilter().doesPassFilter(m_entityAttributes.componentStorage.getComponentTypeList(entity)))
                {
                    if(attribute.systems.size() <= systemIndex || !attribute.systems[systemIndex])
                    {
                        i.second->add(entity); // add it to the system

                        util::EnsureCapacity(attribute.systems, systemIndex);
                        attribute.systems[systemIndex] = true;
                    }
                }
                // otherwise if the entity is within the system
                // and is not relevant to the system anymore...
                // note: the entity has already failed the filter
                else if(attribute.systems.size() > systemIndex && attribute.systems[systemIndex])
                {
                    // duplicate code (1)
                    i.second->remove(entity);
                    attribute.systems[systemIndex] = false;
                }
            }
        }

        // go through all the deactivated entities from last call to refresh
        for(auto& entity : m_entityCache.deactivated)
        {
            auto& attribute = m_entityAttributes.attributes[entity.getId().index];
            attribute.activated = false;

            // loop through all the systems within the world
            for(auto& i : m_systems)
            {
                auto systemIndex = i.first;
                if(attribute.systems.size() <= systemIndex) continue;

                if(attribute.systems[systemIndex])
                {
                    // duplicate code ...(1)
                    i.second->remove(entity);
                    attribute.systems[systemIndex] = false;
                }
            }
        }

        // go through all the killed entities from last call to refresh
        for(auto& entity : m_entityCache.killed)
        {
            // remove the entity from the alive array
            m_entityCache.alive.erase(std::remove(m_entityCache.alive.begin(), m_entityCache.alive.end(), entity), m_entityCache.alive.end());

            // destroy all the components it has
            m_entityAttributes.componentStorage.removeAllComponents(entity);

            // remove it from the id pool
            m_entityIdPool.remove(entity.getId());
        }

        // clear the temp cache
        m_entityCache.clearTemp();
    }

    void World::clear()
    {
        removeAllSystems(); // remove the systems

        // clear the attributes for all the entities
        m_entityAttributes.clear();

        // clear the entity cache
        m_entityCache.clear();

        // clear the id pool
        m_entityIdPool.clear();
    }

    std::size_t World::getEntityCount() const
    {
        return m_entityCache.alive.size();
    }

    const World::EntityArray& World::getEntities() const
    {
        return m_entityCache.alive;
    }

    void World::checkForResize(std::size_t amountOfEntitiesToBeAllocated)
    {
        auto newSize = getEntityCount() + amountOfEntitiesToBeAllocated;
        if(newSize > m_entityIdPool.getSize())
        {
            resize(newSize);
        }
    }

    void World::resize(std::size_t amount)
    {
        m_entityIdPool.resize(amount);
        m_entityAttributes.resize(amount);
    }

    void World::addSystem(detail::BaseSystem& system, detail::TypeId systemTypeId)
    {
        ANAX_ASSERT(!system.m_world, "System is already contained within a World");
        ANAX_ASSERT(m_systems.count(systemTypeId) == 0, "System of this type is already contained within the world");

        m_systems[systemTypeId].reset(&system);

        system.m_world = this;
        system.initialize();
    }

    void World::removeSystem(detail::TypeId systemTypeId)
    {
        ANAX_ASSERT(doesSystemExist(systemTypeId), "System does not exist in world");
        m_systems.erase(systemTypeId);
    }

    bool World::doesSystemExist(detail::TypeId systemTypeId) const
    {
        return m_systems.find(systemTypeId) != m_systems.end();
    }

    Entity World::getEntity(std::size_t index)
    {
        return Entity{*this, m_entityIdPool.get(index)};
    }
}
<commit_msg>Update World.cpp<commit_after>///
/// anax
/// An open source C++ entity system.
///
/// Copyright (C) 2013-2014 Miguel Martin (miguel@miguel-martin.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.
///

#include <anax/World.hpp>

#include <algorithm>

#include <anax/Config.hpp>

#include <anax/detail/AnaxAssert.hpp>
#include <anax/util/ContainerUtils.hpp>

namespace anax
{
    void World::SystemDeleter::operator() (detail::BaseSystem* system) const
    {
        system->m_world = nullptr;
        system->m_entities.clear();
    }

    World::World() :
        World(DEFAULT_ENTITY_POOL_SIZE)
    {
    }

    World::World(std::size_t entityPoolSize) :
        m_entityIdPool(entityPoolSize),
        m_entityAttributes(entityPoolSize)
    {
    }

    void World::removeAllSystems()
    {
        m_systems.clear();
    }

    Entity World::createEntity()
    {
        checkForResize(1);

        m_entityCache.alive.emplace_back(*this, m_entityIdPool.create());
        return m_entityCache.alive.back();
    }

    std::vector<Entity> World::createEntities(std::size_t amount)
    {
        std::vector<Entity> temp;
        temp.reserve(amount);

        checkForResize(amount);

        for(decltype(amount) i = 0; i < amount; ++i)
        {
            Entity e{*this, m_entityIdPool.create()};
            m_entityCache.alive.push_back(e);
            temp.push_back(e);
        }

        return temp;
    }

    void World::killEntity(Entity& entity)
    {
        // deactivate the entity
        deactivateEntity(entity);

        // now kill the entity (add it to the killed cache)
        m_entityCache.killed.push_back(entity);
    }

    void World::killEntities(std::vector<Entity>& entities)
    {
        for(auto& i : entities)
        {
            killEntity(i);
        }
    }

    void World::activateEntity(Entity& entity)
    {
        ANAX_ASSERT(isValid(entity), "invalid entity tried to be activated");

        m_entityCache.activated.push_back(entity);
    }

    void World::deactivateEntity(Entity& entity)
    {
        ANAX_ASSERT(isValid(entity), "invalid entity tried to be deactivated");

        m_entityCache.deactivated.push_back(entity);
    }

    bool World::isActivated(const Entity& entity) const
    {
        if( isValid(entity) )
            return m_entityAttributes.attributes[entity.getId().index].activated;
        else
            return false;
    }

    bool World::isValid(const anax::Entity &entity) const
    {
        return m_entityIdPool.isValid(entity.getId());
    }

    void World::refresh()
    {
        // go through all the activated entities from last call to refresh
        for(auto& entity : m_entityCache.activated)
        {
            auto& attribute = m_entityAttributes.attributes[entity.getId().index];
            attribute.activated = true;

            // loop through all the systems within the world
            for(auto& i : m_systems)
            {
                auto systemIndex = i.first;

                // if the entity passes the filter the system has and is not already part of the system
                if(i.second->getFilter().doesPassFilter(m_entityAttributes.componentStorage.getComponentTypeList(entity)))
                {
                    if(attribute.systems.size() <= systemIndex || !attribute.systems[systemIndex])
                    {
                        i.second->add(entity); // add it to the system

                        util::EnsureCapacity(attribute.systems, systemIndex);
                        attribute.systems[systemIndex] = true;
                    }
                }
                // otherwise if the entity is within the system
                // and is not relevant to the system anymore...
                // note: the entity has already failed the filter
                else if(attribute.systems.size() > systemIndex && attribute.systems[systemIndex])
                {
                    // duplicate code (1)
                    i.second->remove(entity);
                    attribute.systems[systemIndex] = false;
                }
            }
        }

        // go through all the deactivated entities from last call to refresh
        for(auto& entity : m_entityCache.deactivated)
        {
            auto& attribute = m_entityAttributes.attributes[entity.getId().index];
            attribute.activated = false;

            // loop through all the systems within the world
            for(auto& i : m_systems)
            {
                auto systemIndex = i.first;
                if(attribute.systems.size() <= systemIndex) continue;

                if(attribute.systems[systemIndex])
                {
                    // duplicate code ...(1)
                    i.second->remove(entity);
                    attribute.systems[systemIndex] = false;
                }
            }
        }

        // go through all the killed entities from last call to refresh
        for(auto& entity : m_entityCache.killed)
        {
            // remove the entity from the alive array
            m_entityCache.alive.erase(std::remove(m_entityCache.alive.begin(), m_entityCache.alive.end(), entity), m_entityCache.alive.end());

            // destroy all the components it has
            m_entityAttributes.componentStorage.removeAllComponents(entity);

            // remove it from the id pool
            m_entityIdPool.remove(entity.getId());
        }

        // clear the temp cache
        m_entityCache.clearTemp();
    }

    void World::clear()
    {
        removeAllSystems(); // remove the systems

        // clear the attributes for all the entities
        m_entityAttributes.clear();

        // clear the entity cache
        m_entityCache.clear();

        // clear the id pool
        m_entityIdPool.clear();
    }

    std::size_t World::getEntityCount() const
    {
        return m_entityCache.alive.size();
    }

    const World::EntityArray& World::getEntities() const
    {
        return m_entityCache.alive;
    }

    void World::checkForResize(std::size_t amountOfEntitiesToBeAllocated)
    {
        auto newSize = getEntityCount() + amountOfEntitiesToBeAllocated;
        if(newSize > m_entityIdPool.getSize())
        {
            resize(newSize);
        }
    }

    void World::resize(std::size_t amount)
    {
        m_entityIdPool.resize(amount);
        m_entityAttributes.resize(amount);
    }

    void World::addSystem(detail::BaseSystem& system, detail::TypeId systemTypeId)
    {
        ANAX_ASSERT(!system.m_world, "System is already contained within a World");
        ANAX_ASSERT(m_systems.count(systemTypeId) == 0, "System of this type is already contained within the world");

        m_systems[systemTypeId].reset(&system);

        system.m_world = this;
        system.initialize();
    }

    void World::removeSystem(detail::TypeId systemTypeId)
    {
        ANAX_ASSERT(doesSystemExist(systemTypeId), "System does not exist in world");
        m_systems.erase(systemTypeId);
    }

    bool World::doesSystemExist(detail::TypeId systemTypeId) const
    {
        return m_systems.find(systemTypeId) != m_systems.end();
    }

    Entity World::getEntity(std::size_t index)
    {
        return Entity{*this, m_entityIdPool.get(index)};
    }
}
<|endoftext|>


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

// cndefns.h -- shared #defines for CSE code and rcdef/cnrecs.def

// #included in cnrecs.def, cndtypes.def, .
// may be #included in cnglob.h cuz symbols defined here come out in dtypes.h, 1-94

// NOTE!! These #defines cannot contain expressions (rcdef limitation)

#ifndef _CNEDEFNS_H		// skip duplicate includes 1-94
#define _CNEDEFNS_H		// say included

//------------------------------------------------ OPTIONS --------------------------------------------------
#define AUTOSIZE	// identifies at least code being added for autosizing, 6-95.
					//  undefining probably won't completely undo.
					//  later edit out defined.

#undef BINRES	// define for code to output binary results files, 11-93.
				// Implemented for NREL, but generally useful (if documented for others!).

// #define SHINTERP	// define for subhour-interpolated weather data. Used in many files. 1-95
					// coded out #defined 4-1-10

#undef SOLAVNEND
			/* undef to use subhour-average interpolated solar or hour-average solar values at all uses.
			   Define to make use of subhour-end interpolated values for zones, average values for masses.
			   Code for defined incomplete: surface sgdist to zone total must be reworked to use
			   avg value for solar SGDIST'd to mass, end value for remainder going to zone, determined
			   m-h (eg in cgsolar.cpp) cuz SGDIST sgd_FSC/O are runtime-variable.
			   (Present code fails (ebal errs) when SGDISTS present, eg CKENV\S1HWN.)
			   Could code out undefined after works and Bruce/Phil confirm (memo NILES108.TXT).
			   Used in cnrecs.def, cuparse.cpp, cgwthr,cgsolar,cnloads.cpp. 1-18-95. */

//--- option(s) re supporting NREL Design Tool, 1993-94

/*--- history of removal of former seasons stuff which used different (possibly smaller) sgdist f's in "summer".
 * #undef SEASONS  91? 92?: define for vestigial do-nothing seasons and csType, smrBeg, smrEnd, and smrTemp commands.
 *		            files: cnrecs, cnguts, cncult,2,3 cuparse, cgsolar, cgwthr at least.
 *		   7-92:    Leaving SEASONS DEFINED, redid SGDISTS and cgsolar for shades open-closed not seasons,
 *			    making seasons do nothing but $isSummer.
 *		   1-93:    Undefined SEASONS; put temporary warnings in cncult.cpp re seasons commands.
 *		   2..3-94: All SEASONS code deleted. */

//--- following provide grep-able backtrack to deleted obsolete data and code 1-92 (some previously disabled)
#undef OLDNV	// cr/hst nat vent KEEP THE CODE -- Chip says record needed
#undef OLDFV	// cr/hst fan vent code
#undef OLDCF	// cr/hst ceiling fan code

// enhanced CSE zone models, 7-10
#undef CZM_COMPARE			// define to use methods identical to those in
							//   CZM.BAS (re result comparison) 10-10
#undef AIRNET_COMPARE		// #define to use methods identical to those in
							//   AirNet.bas (re result comparison)
#undef CONV_ASHRAECOMPARE

#undef WTHR_T24DLL			// #define to support T24WTHR.DLL source for hourly compliance
							//   weather data

// implement zone exhaust fan, 8-10
#define ZONE_XFAN	// define to enable zone exhaust fan implementation, 8-10
					//   FAN object historically in ZNISUB.xfan but previously not simulated

#undef BUG_COLTYPECOPY	// define to include object trap code re memcpy bug
						//   associated with copying COL objects
						//   File coltypebug.cse crashes.
						//   Fixed (maybe) by overriding COL::CopyFrom().
						//   Further research needed: why both Copy() and CopyFrom()?
						//      (both use memcpy(), dangerous when object contains heap ptrs)
						//   2-24-2012

#undef RSYS_FIXEDOAT	// define to cause fixed RSYS supply air temp / humrat
						//   (development aid)

#define USE_STDLIB		// re conversion to non-MFC containers

#undef AUSZ_REPORTS		// define to enable hourly reports during autosizing
						//   Note: crude at best, use for testing only, 12-31-2012

//------------------------------------------------ DEFINES --------------------------------------------------
#define MAXSUBSTEPS 120		// max # of substeps per hour
							// limit may be less if specific items present
							//    if DHWSYS is present, limit is 60
							// increase with care, trouble has been seen for higher values
							//    e.g. 240 causes wfpak WDSUBHRFACTORS::wdsf_Setup() assert
							//    5-2021

#define HSMXSGDIST 8	// Max # of solar gain targets from one XSURF.
						// Need 1 per solar gain distribution. 4->5 1990, ->8 2-95.
#define XSMXTLRB 10		// Max # of layer boundary temps maintained in XSURF
						//   see XSURF.xs_tLrB[]

// terminal and mode definitions; used in cnrecs.def TU, ZNR,
//#define MAX_TUKS     3	// max capabilities per terminal: local heat, air heat, air cool.  No uses; define if needed.
#define MAX_ZONETUS    3	// max terminal units allowed to serve a zone: enforced during input
#define MAX_ZONEMODES 21	// max mdSeq[] modes pos with max TUs each with max capabilities:
							//   need 2 per TU capability (1 at set point, 1 floating above)
							//      + 2 per additional mode (e.g.nat vent) + 1 (low end floating)
							//   = 2 * MAX_TUKS * MAX_ZONETUS + 3

#define IVLDATADIM 4		// dimension of interval data arrays
							//    4 = Y, M, D, H
							// see IvlData() template function, cnglobl.h

#define RSYSMODES 3			// # of RSYS operating modes (not including rsmOFF)
							//   must be known in cnrecs.def
							//   must be consistent the rsmXXX enum

#define NDHWENDUSESPP 6		// # of DHW end uses (for use in cnrecs.def)
							//   must be same as C_DHWEUCH_COUNT
							//   see also cnglob.h const int NDHWENDUSES
#define NDHWENDUSESXPP 8	// # of extended DHW end uses
							//   must be same as C_DHWEUXCH_COUNT
#define NDHWSIZEDAYS 10		// # of DHW sizing design days for EcoSizer method

#define ASHP_COPREG 6		// select COP17/47 regression model
							//   1 = original (2012?)
							//   2 = revised 6-3-2013
							//   3 = COP/HSPF fit 6-4-2013
							//   4 = kwPerTon fit 6-4-2013
							//   5 = force COP17=1.8 at HSPF=6.8 6-4-2013
							//   6 = derive COP17 and COP35 so HSPF matches input

#define DETAILED_TIMING		// define to enable fine-grain timing

#undef COMFORT_MODEL		// define to include comfort model
							//   calculation of PPD and PMV

							// initial geometry implementation, 2-2017
							//   fixed size polygons as input convenience
							//   using ARRAY mechanism
							//   Note limit is due to ARRAY input only.
#define MAX_POLYGONVERTICES 12	// maximum number of input polygon vertices
#define DIM_POLYGONXYZ 37		// input arrays dimension
								//   = MAX_POLYLPVERTICIES*3 + 1

#define CRTERMAH			// define to enable support of TERMINAL / AIRHANDLER model
							//    in convective / radiant zones
#undef SUPPRESS_ENBAL_CHECKS	// define to suppress energy balance checks
								//   (development aid)

#endif	// ifndef _CNEDEFNS_H

// cndefns.h end
<commit_msg>Remove autosize definition.<commit_after>// Copyright (c) 1997-2019 The CSE Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.

// cndefns.h -- shared #defines for CSE code and rcdef/cnrecs.def

// #included in cnrecs.def, cndtypes.def, .
// may be #included in cnglob.h cuz symbols defined here come out in dtypes.h, 1-94

// NOTE!! These #defines cannot contain expressions (rcdef limitation)

#ifndef _CNEDEFNS_H		// skip duplicate includes 1-94
#define _CNEDEFNS_H		// say included

//------------------------------------------------ OPTIONS --------------------------------------------------
#undef BINRES	// define for code to output binary results files, 11-93.
				// Implemented for NREL, but generally useful (if documented for others!).

// #define SHINTERP	// define for subhour-interpolated weather data. Used in many files. 1-95
					// coded out #defined 4-1-10

#undef SOLAVNEND
			/* undef to use subhour-average interpolated solar or hour-average solar values at all uses.
			   Define to make use of subhour-end interpolated values for zones, average values for masses.
			   Code for defined incomplete: surface sgdist to zone total must be reworked to use
			   avg value for solar SGDIST'd to mass, end value for remainder going to zone, determined
			   m-h (eg in cgsolar.cpp) cuz SGDIST sgd_FSC/O are runtime-variable.
			   (Present code fails (ebal errs) when SGDISTS present, eg CKENV\S1HWN.)
			   Could code out undefined after works and Bruce/Phil confirm (memo NILES108.TXT).
			   Used in cnrecs.def, cuparse.cpp, cgwthr,cgsolar,cnloads.cpp. 1-18-95. */

//--- option(s) re supporting NREL Design Tool, 1993-94

/*--- history of removal of former seasons stuff which used different (possibly smaller) sgdist f's in "summer".
 * #undef SEASONS  91? 92?: define for vestigial do-nothing seasons and csType, smrBeg, smrEnd, and smrTemp commands.
 *		            files: cnrecs, cnguts, cncult,2,3 cuparse, cgsolar, cgwthr at least.
 *		   7-92:    Leaving SEASONS DEFINED, redid SGDISTS and cgsolar for shades open-closed not seasons,
 *			    making seasons do nothing but $isSummer.
 *		   1-93:    Undefined SEASONS; put temporary warnings in cncult.cpp re seasons commands.
 *		   2..3-94: All SEASONS code deleted. */

//--- following provide grep-able backtrack to deleted obsolete data and code 1-92 (some previously disabled)
#undef OLDNV	// cr/hst nat vent KEEP THE CODE -- Chip says record needed
#undef OLDFV	// cr/hst fan vent code
#undef OLDCF	// cr/hst ceiling fan code

// enhanced CSE zone models, 7-10
#undef CZM_COMPARE			// define to use methods identical to those in
							//   CZM.BAS (re result comparison) 10-10
#undef AIRNET_COMPARE		// #define to use methods identical to those in
							//   AirNet.bas (re result comparison)
#undef CONV_ASHRAECOMPARE

#undef WTHR_T24DLL			// #define to support T24WTHR.DLL source for hourly compliance
							//   weather data

// implement zone exhaust fan, 8-10
#define ZONE_XFAN	// define to enable zone exhaust fan implementation, 8-10
					//   FAN object historically in ZNISUB.xfan but previously not simulated

#undef BUG_COLTYPECOPY	// define to include object trap code re memcpy bug
						//   associated with copying COL objects
						//   File coltypebug.cse crashes.
						//   Fixed (maybe) by overriding COL::CopyFrom().
						//   Further research needed: why both Copy() and CopyFrom()?
						//      (both use memcpy(), dangerous when object contains heap ptrs)
						//   2-24-2012

#undef RSYS_FIXEDOAT	// define to cause fixed RSYS supply air temp / humrat
						//   (development aid)

#define USE_STDLIB		// re conversion to non-MFC containers

#undef AUSZ_REPORTS		// define to enable hourly reports during autosizing
						//   Note: crude at best, use for testing only, 12-31-2012

//------------------------------------------------ DEFINES --------------------------------------------------
#define MAXSUBSTEPS 120		// max # of substeps per hour
							// limit may be less if specific items present
							//    if DHWSYS is present, limit is 60
							// increase with care, trouble has been seen for higher values
							//    e.g. 240 causes wfpak WDSUBHRFACTORS::wdsf_Setup() assert
							//    5-2021

#define HSMXSGDIST 8	// Max # of solar gain targets from one XSURF.
						// Need 1 per solar gain distribution. 4->5 1990, ->8 2-95.
#define XSMXTLRB 10		// Max # of layer boundary temps maintained in XSURF
						//   see XSURF.xs_tLrB[]

// terminal and mode definitions; used in cnrecs.def TU, ZNR,
//#define MAX_TUKS     3	// max capabilities per terminal: local heat, air heat, air cool.  No uses; define if needed.
#define MAX_ZONETUS    3	// max terminal units allowed to serve a zone: enforced during input
#define MAX_ZONEMODES 21	// max mdSeq[] modes pos with max TUs each with max capabilities:
							//   need 2 per TU capability (1 at set point, 1 floating above)
							//      + 2 per additional mode (e.g.nat vent) + 1 (low end floating)
							//   = 2 * MAX_TUKS * MAX_ZONETUS + 3

#define IVLDATADIM 4		// dimension of interval data arrays
							//    4 = Y, M, D, H
							// see IvlData() template function, cnglobl.h

#define RSYSMODES 3			// # of RSYS operating modes (not including rsmOFF)
							//   must be known in cnrecs.def
							//   must be consistent the rsmXXX enum

#define NDHWENDUSESPP 6		// # of DHW end uses (for use in cnrecs.def)
							//   must be same as C_DHWEUCH_COUNT
							//   see also cnglob.h const int NDHWENDUSES
#define NDHWENDUSESXPP 8	// # of extended DHW end uses
							//   must be same as C_DHWEUXCH_COUNT
#define NDHWSIZEDAYS 10		// # of DHW sizing design days for EcoSizer method

#define ASHP_COPREG 6		// select COP17/47 regression model
							//   1 = original (2012?)
							//   2 = revised 6-3-2013
							//   3 = COP/HSPF fit 6-4-2013
							//   4 = kwPerTon fit 6-4-2013
							//   5 = force COP17=1.8 at HSPF=6.8 6-4-2013
							//   6 = derive COP17 and COP35 so HSPF matches input

#define DETAILED_TIMING		// define to enable fine-grain timing

#undef COMFORT_MODEL		// define to include comfort model
							//   calculation of PPD and PMV

							// initial geometry implementation, 2-2017
							//   fixed size polygons as input convenience
							//   using ARRAY mechanism
							//   Note limit is due to ARRAY input only.
#define MAX_POLYGONVERTICES 12	// maximum number of input polygon vertices
#define DIM_POLYGONXYZ 37		// input arrays dimension
								//   = MAX_POLYLPVERTICIES*3 + 1

#define CRTERMAH			// define to enable support of TERMINAL / AIRHANDLER model
							//    in convective / radiant zones
#undef SUPPRESS_ENBAL_CHECKS	// define to suppress energy balance checks
								//   (development aid)

#endif	// ifndef _CNEDEFNS_H

// cndefns.h end
<|endoftext|>


<commit_before>AliGenerator* AddMCGenPythia_He3(Float_t e_cms = 2760., Double_t ptHardMin = 0., Double_t ptHardMax = 1., Int_t tune = 2,Int_t cr=1,Float_t ptWeight=0)
{
  //Add Pythia generator: pt-hard bin or min bias

  gSystem->Load("liblhapdf");

  AliGenCocktail* gener = new AliGenCocktail();

  AliGenPythia *genP = NULL;
  genP = CreatePythia6Gen(e_cms, ptHardMin, ptHardMax, tune,cr,ptWeight);

  // deuterons and anti-deuterons
  AliGenLightNuclei* d = new AliGenLightNuclei();
  d->SetNucleusPdgCode(AliGenLightNuclei::kDeuteron);
  d->SetCoalescenceMomentum(0.100); // default
  d->SetSpinProbability(1);
  d->UsePerEventRates();

 // 3He and anti-3He nuclei
  AliGenLightNuclei* he3 = new AliGenLightNuclei();
  he3->SetNucleusPdgCode(AliGenLightNuclei::kHe3Nucleus);
  he3->SetCoalescenceMomentum(0.127);
  he3->SetSpinProbability(1);
  he3->UsePerEventRates();

  gener->AddGenerator(genP, "pythia8", 1);
  gener->AddGenerator(d,"deuteron",1);
  gener->AddGenerator(he3,"He3",1);

  return gener;
}

AliGenPythia* CreatePythia6Gen(Float_t e_cms, Int_t ptHardMin, Int_t ptHardMax, Int_t tune, Int_t cr,Float_t ptWeight) {

  if(tune==3)  gSystem->Load("libpythia6_4_28");
   if(tune<3)  gSystem->Load("libpythia6_4_25");
  gSystem->Load("libEGPythia6");
  gSystem->Load("libAliPythia6");

  AliGenPythia* genP = new AliGenPythia(1);

  //   vertex position and smearing
  genP->SetVertexSmear(kPerEvent);

  // structure function
  // use kCTEQ5l for Perugia tunes
  // except for tunes: Perugia * (325, MRSTLO*), Perugia 6 (326, CTEQ6L),
  // Perugia 11 M (355, MRST LO**), Perugia 11 C (356, CTEQ6L1)
  genP->SetStrucFunc(kCTEQ5L);

  //   charm, beauty, charm_unforced, beauty_unforced, jpsi, jpsi_chi, mb
  if(ptHardMin>0.) {

    genP->SetProcess(kPyJets);
    genP->SetPtHard((float)ptHardMin,(float)ptHardMax);
    if(ptWeight>0) genP->SetWeightPower(ptWeight);
  } else
    genP->SetProcess(kPyMb); // Minimum Bias

  //   Centre of mass energy
  genP->SetEnergyCMS(e_cms); // in GeV

  genP->UseNewMultipleInteractionsScenario(); // for all Pythia versions >= 6.3

  if(tune == 0){ // tune Perugia0
    genP->SetTune(320);
    if(cr==0) genP->SetTune(324);
  }
  if(tune == 1){ // tune Perugia2010
    genP->SetTune(327);
    if(cr==0) genP->SetTune(324);
  }
  if(tune == 2){ // tune Perugia2011 ('central' Perugia 2011)
    genP->SetTune(350);
    if(cr==0) genP->SetTune(354);
  }
  if(tune == 3){ // tune Perugia2012 ('central' Perugia 2012)
    genP->SetTune(370);
    if(cr==0) genP->SetTune(375);
  }

  genP->Print();

  return genP;
}
<commit_msg>AliFemto: modification for PYTHIA<commit_after>AliGenerator* AddMCGenPythia_He3(Float_t e_cms = 2760., Double_t ptHardMin = 0., Double_t ptHardMax = 1., Int_t tune = 2,Int_t cr=1,Float_t ptWeight=0)
{
  //Add Pythia generator: pt-hard bin or min bias

  AliGenCocktail* gener = new AliGenCocktail();

  AliGenPythia *genP = CreatePythia6Gen(e_cms, ptHardMin, ptHardMax, tune,cr,ptWeight);

  // deuterons and anti-deuterons
  AliGenLightNuclei* d = new AliGenLightNuclei();
  d->SetNucleusPdgCode(AliGenLightNuclei::kDeuteron);
  d->SetCoalescenceMomentum(0.100); // default
  d->SetSpinProbability(1);
  d->UsePerEventRates();

 // 3He and anti-3He nuclei
  AliGenLightNuclei* he3 = new AliGenLightNuclei();
  he3->SetNucleusPdgCode(AliGenLightNuclei::kHe3Nucleus);
  he3->SetCoalescenceMomentum(0.127);
  he3->SetSpinProbability(1);
  he3->UsePerEventRates();

  gener->AddGenerator(genP, "pythia8", 1);
  gener->AddGenerator(d,"deuteron",1);
  gener->AddGenerator(he3,"He3",1);

  return gener;
  //return genP;
}

AliGenerator* CreatePythia6Gen(Float_t e_cms, Int_t ptHardMin, Int_t ptHardMax, Int_t tune, Int_t cr,Float_t ptWeight) {

  if(tune==3)  gSystem->Load("libpythia6_4_28");
   if(tune<3)  gSystem->Load("libpythia6_4_25");
  gSystem->Load("libEGPythia6");
  gSystem->Load("libAliPythia6");

  AliGenPythia* genP = new AliGenPythia(1);

  //   vertex position and smearing
  genP->SetVertexSmear(kPerEvent);

  // structure function
  // use kCTEQ5l for Perugia tunes
  // except for tunes: Perugia * (325, MRSTLO*), Perugia 6 (326, CTEQ6L),
  // Perugia 11 M (355, MRST LO**), Perugia 11 C (356, CTEQ6L1)
  genP->SetStrucFunc(kCTEQ5L);

  //   charm, beauty, charm_unforced, beauty_unforced, jpsi, jpsi_chi, mb
  if(ptHardMin>0.) {

    genP->SetProcess(kPyJets);
    genP->SetPtHard((float)ptHardMin,(float)ptHardMax);
    if(ptWeight>0) genP->SetWeightPower(ptWeight);
  } else
    genP->SetProcess(kPyMb); // Minimum Bias

  //   Centre of mass energy
  genP->SetEnergyCMS(e_cms); // in GeV

  //genP->UseNewMultipleInteractionsScenario(); // for all Pythia versions >= 6.3

  if(tune == 0){ // tune Perugia0
    genP->SetTune(320);
    if(cr==0) genP->SetTune(324);
  }
  if(tune == 1){ // tune Perugia2010
    genP->SetTune(327);
    if(cr==0) genP->SetTune(324);
  }
  if(tune == 2){ // tune Perugia2011 ('central' Perugia 2011)
    genP->SetTune(350);
    if(cr==0) genP->SetTune(354);
  }
  if(tune == 3){ // tune Perugia2012 ('central' Perugia 2012)
    genP->SetTune(370);
    if(cr==0) genP->SetTune(375);
  }

  genP->Print();

  return genP;
}
<|endoftext|>


<commit_before>/*
   This file is part of the clazy static checker.

  Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
  Author: Sérgio Martins <sergio.martins@kdab.com>

  Copyright (C) 2015-2016 Sergio Martins <smartins@kde.org>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/

#include "Utils.h"
#include "Clazy.h"
#include "StringUtils.h"
#include "clazy_stl.h"
#include "checkbase.h"
#include "checkmanager.h"
#include "AccessSpecifierManager.h"

#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"

#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Rewrite/Frontend/FixItRewriter.h"
#include "clang/AST/ParentMap.h"
#include <llvm/Config/llvm-config.h>

#include <stdio.h>
#include <sstream>
#include <iostream>

using namespace clang;
using namespace std;

namespace {

class MyFixItOptions : public FixItOptions
{
public:
    MyFixItOptions(const MyFixItOptions &other) = delete;
    MyFixItOptions(bool inplace)
    {
        InPlace = inplace;
        FixWhatYouCan = true;
        FixOnlyWarnings = true;
        Silent = false;
    }

    std::string RewriteFilename(const std::string &filename, int &fd) override
    {
        fd = -1;
        return InPlace ? filename : filename + "_fixed.cpp";
    }

#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6
    // Clang >= 3.7 already has this member.
    // We define it for clang <= 3.6 so it builds.
    bool InPlace;
#endif
};

static void manuallyPopulateParentMap(ParentMap *map, Stmt *s)
{
    if (!s)
        return;

    for (Stmt *child : s->children()) {
        llvm::errs() << "Patching " << child->getStmtClassName() << "\n";
        map->setParent(child, s);
        manuallyPopulateParentMap(map, child);
    }
}

class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer>
{
    LazyASTConsumer(const LazyASTConsumer &) = delete;
public:
    LazyASTConsumer(CompilerInstance &ci, CheckManager *checkManager,
                    const RegisteredCheck::List &requestedChecks, bool inplaceFixits)
        : m_ci(ci)
        , m_sm(ci.getSourceManager())
        , m_rewriter(nullptr)
        , m_parentMap(nullptr)
        , m_checkManager(checkManager)
    {
        m_createdChecks = checkManager->createChecks(requestedChecks, ci);
        if (checkManager->fixitsEnabled())
            m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits));
    }

    ~LazyASTConsumer()
    {
        if (m_rewriter) {
            m_rewriter->WriteFixedFiles();
            delete m_rewriter;
        }

        delete m_parentMap;
    }

    void setParentMap(ParentMap *map)
    {
        assert(map && !m_parentMap);
        m_parentMap = map;
        for (auto &check : m_createdChecks)
            check->setParentMap(map);
    }

    bool VisitDecl(Decl *decl)
    {
        const bool isInSystemHeader = m_sm.isInSystemHeader(decl->getLocStart());

#if !defined(IS_OLD_CLANG)
        if (AccessSpecifierManager *a = m_checkManager->accessSpecifierManager())
            a->VisitDeclaration(decl);
#endif
        for (const auto &check : m_createdChecks) {
            if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
                check->VisitDeclaration(decl);
        }

        return true;
    }

    bool VisitStmt(Stmt *stm)
    {
        if (!m_parentMap) {
            if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred())
                return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST.

            setParentMap(new ParentMap(stm));
        }

        // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.
        if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) {
            m_parentMap->setParent(stm, lastStm);
            manuallyPopulateParentMap(m_parentMap, stm);
        }

        lastStm = stm;

        // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration
        // So add to parent map each time we go into a different hierarchy
        if (!m_parentMap->hasParent(stm))
            m_parentMap->addStmt(stm);

        const bool isInSystemHeader = m_sm.isInSystemHeader(stm->getLocStart());
        for (const auto &check : m_createdChecks) {
            if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
                check->VisitStatement(stm);
        }

        return true;
    }

    void HandleTranslationUnit(ASTContext &ctx) override
    {
        TraverseDecl(ctx.getTranslationUnitDecl());
    }

    Stmt *lastStm = nullptr;
    CompilerInstance &m_ci;
    const SourceManager &m_sm;
    FixItRewriter *m_rewriter;
    ParentMap *m_parentMap;
    CheckBase::List m_createdChecks;
    CheckManager *const m_checkManager;
};

}

static bool parseArgument(const string &arg, vector<string> &args)
{
    auto it = clazy_std::find(args, arg);
    if (it != args.end()) {
        args.erase(it, it + 1);
        return true;
    }

    return false;
}

static CheckLevel parseLevel(vector<std::string> &args)
{
    static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" };
    const int numLevels = levels.size();
    for (int i = 0; i < numLevels; ++i) {
        if (parseArgument(levels.at(i), args)) {
            return static_cast<CheckLevel>(i);
        }
    }

    return CheckLevelUndefined;
}

static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
    return c1.name < c2.name;
}

static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
    if (c1.level == c2.level)
        return checkLessThan(c1, c2);

    return c1.level < c2.level;
}

ClazyASTAction::ClazyASTAction()
    : PluginASTAction()
    , m_checkManager(CheckManager::instance())
{
}

std::unique_ptr<clang::ASTConsumer> ClazyASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)
{
    return llvm::make_unique<LazyASTConsumer>(ci, m_checkManager, m_checks, m_inplaceFixits);
}

bool ClazyASTAction::ParseArgs(const CompilerInstance &, const std::vector<std::string> &args_)
{
    std::vector<std::string> args = args_;

    if (parseArgument("help", args)) {
        PrintHelp(llvm::errs());
        return true;
    }

    if (parseArgument("no-inplace-fixits", args)) {
        // Unit-tests don't use inplace fixits
        m_inplaceFixits = false;
    }

    // This argument is for debugging purposes
    const bool printRequestedChecks = parseArgument("print-requested-checks", args);

    const CheckLevel requestedLevel = parseLevel(/*by-ref*/args);
    if (requestedLevel != CheckLevelUndefined) {
        m_checkManager->setRequestedLevel(requestedLevel);
    }

    if (parseArgument("enable-all-fixits", args)) {
        // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.
        m_checkManager->enableAllFixIts();
    }

    if (args.size() > 1) {
        // Too many arguments.
        llvm::errs() << "Too many arguments: ";
        for (const std::string &a : args)
            llvm::errs() << a << ' ';
        llvm::errs() << "\n";

        PrintHelp(llvm::errs());
        return false;
    } else if (args.size() == 1) {
        vector<string> userDisabledChecks;
        m_checks = m_checkManager->checksForCommaSeparatedString(args[0], /*by-ref=*/userDisabledChecks);
        if (m_checks.empty()) {
            llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n";
            PrintHelp(llvm::errs());
            return false;
        }
    }

    vector<string> userDisabledChecks;
    // Append checks specified from env variable
    RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(/*by-ref*/userDisabledChecks);
    copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks));

    if (m_checks.empty() && requestedLevel == CheckLevelUndefined) {
        // No check or level specified, lets use the default level
        m_checkManager->setRequestedLevel(DefaultCheckLevel);
    }

    // Add checks from requested level
    auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel();
    clazy_std::append(checksFromRequestedLevel, m_checks);
    clazy_std::sort_and_remove_dups(m_checks, checkLessThan);
    CheckManager::removeChecksFromList(m_checks, userDisabledChecks);

    if (printRequestedChecks) {
        llvm::errs() << "Requested checks: ";
        const unsigned int numChecks = m_checks.size();
        for (unsigned int i = 0; i < numChecks; ++i) {
            llvm::errs() << m_checks.at(i).name;
            const bool isLast = i == numChecks - 1;
            if (!isLast) {
                llvm::errs() << ", ";
            }
        }

        llvm::errs() << "\n";
    }

    return true;
}

void ClazyASTAction::PrintHelp(llvm::raw_ostream &ros)
{
    RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel);
    clazy_std::sort(checks, checkLessThanByLevel);

    ros << "Available checks and FixIts:\n\n";

    int lastPrintedLevel = -1;
    const auto numChecks = checks.size();
    for (unsigned int i = 0; i < numChecks; ++i) {
        const RegisteredCheck &check = checks[i];
        if (lastPrintedLevel < check.level) {
            lastPrintedLevel = check.level;

            if (check.level > 0)
                ros << "\n";

            ros << "- Checks from level" << to_string(check.level) << ":\n";
        }

        auto padded = check.name;
        padded.insert(padded.end(), 39 - padded.size(), ' ');
        ros << "    - " << check.name;
        auto fixits = m_checkManager->availableFixIts(check.name);
        if (!fixits.empty()) {
            ros << "    (";
            bool isFirst = true;
            for (const auto& fixit : fixits) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    ros << ',';
                }

                ros << fixit.name;
            }
            ros << ')';
        }
        ros << "\n";
    }
    ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n";
    ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n";
    ros << "    export CLAZY_CHECKS=\"level0\"\n";
    ros << "    export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n";
    ros << "    export CLAZY_CHECKS=\"reserve-candidates\"\n\n";
    ros << "or pass as compiler arguments, for example:\n";
    ros << "    -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n";
    ros << "\n";
    ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n";
    ros << "    export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n";
    ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n";
}

static FrontendPluginRegistry::Add<ClazyASTAction>
X("clang-lazy", "clang lazy plugin");
<commit_msg>Allow to print help formated with markdown<commit_after>/*
   This file is part of the clazy static checker.

  Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
  Author: Sérgio Martins <sergio.martins@kdab.com>

  Copyright (C) 2015-2016 Sergio Martins <smartins@kde.org>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/

#include "Utils.h"
#include "Clazy.h"
#include "StringUtils.h"
#include "clazy_stl.h"
#include "checkbase.h"
#include "checkmanager.h"
#include "AccessSpecifierManager.h"

#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"

#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Rewrite/Frontend/FixItRewriter.h"
#include "clang/AST/ParentMap.h"
#include <llvm/Config/llvm-config.h>

#include <stdio.h>
#include <sstream>
#include <iostream>

using namespace clang;
using namespace std;

namespace {

class MyFixItOptions : public FixItOptions
{
public:
    MyFixItOptions(const MyFixItOptions &other) = delete;
    MyFixItOptions(bool inplace)
    {
        InPlace = inplace;
        FixWhatYouCan = true;
        FixOnlyWarnings = true;
        Silent = false;
    }

    std::string RewriteFilename(const std::string &filename, int &fd) override
    {
        fd = -1;
        return InPlace ? filename : filename + "_fixed.cpp";
    }

#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6
    // Clang >= 3.7 already has this member.
    // We define it for clang <= 3.6 so it builds.
    bool InPlace;
#endif
};

static void manuallyPopulateParentMap(ParentMap *map, Stmt *s)
{
    if (!s)
        return;

    for (Stmt *child : s->children()) {
        llvm::errs() << "Patching " << child->getStmtClassName() << "\n";
        map->setParent(child, s);
        manuallyPopulateParentMap(map, child);
    }
}

class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer>
{
    LazyASTConsumer(const LazyASTConsumer &) = delete;
public:
    LazyASTConsumer(CompilerInstance &ci, CheckManager *checkManager,
                    const RegisteredCheck::List &requestedChecks, bool inplaceFixits)
        : m_ci(ci)
        , m_sm(ci.getSourceManager())
        , m_rewriter(nullptr)
        , m_parentMap(nullptr)
        , m_checkManager(checkManager)
    {
        m_createdChecks = checkManager->createChecks(requestedChecks, ci);
        if (checkManager->fixitsEnabled())
            m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits));
    }

    ~LazyASTConsumer()
    {
        if (m_rewriter) {
            m_rewriter->WriteFixedFiles();
            delete m_rewriter;
        }

        delete m_parentMap;
    }

    void setParentMap(ParentMap *map)
    {
        assert(map && !m_parentMap);
        m_parentMap = map;
        for (auto &check : m_createdChecks)
            check->setParentMap(map);
    }

    bool VisitDecl(Decl *decl)
    {
        const bool isInSystemHeader = m_sm.isInSystemHeader(decl->getLocStart());

#if !defined(IS_OLD_CLANG)
        if (AccessSpecifierManager *a = m_checkManager->accessSpecifierManager())
            a->VisitDeclaration(decl);
#endif
        for (const auto &check : m_createdChecks) {
            if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
                check->VisitDeclaration(decl);
        }

        return true;
    }

    bool VisitStmt(Stmt *stm)
    {
        if (!m_parentMap) {
            if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred())
                return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST.

            setParentMap(new ParentMap(stm));
        }

        // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.
        if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) {
            m_parentMap->setParent(stm, lastStm);
            manuallyPopulateParentMap(m_parentMap, stm);
        }

        lastStm = stm;

        // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration
        // So add to parent map each time we go into a different hierarchy
        if (!m_parentMap->hasParent(stm))
            m_parentMap->addStmt(stm);

        const bool isInSystemHeader = m_sm.isInSystemHeader(stm->getLocStart());
        for (const auto &check : m_createdChecks) {
            if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
                check->VisitStatement(stm);
        }

        return true;
    }

    void HandleTranslationUnit(ASTContext &ctx) override
    {
        TraverseDecl(ctx.getTranslationUnitDecl());
    }

    Stmt *lastStm = nullptr;
    CompilerInstance &m_ci;
    const SourceManager &m_sm;
    FixItRewriter *m_rewriter;
    ParentMap *m_parentMap;
    CheckBase::List m_createdChecks;
    CheckManager *const m_checkManager;
};

}

static bool parseArgument(const string &arg, vector<string> &args)
{
    auto it = clazy_std::find(args, arg);
    if (it != args.end()) {
        args.erase(it, it + 1);
        return true;
    }

    return false;
}

static CheckLevel parseLevel(vector<std::string> &args)
{
    static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" };
    const int numLevels = levels.size();
    for (int i = 0; i < numLevels; ++i) {
        if (parseArgument(levels.at(i), args)) {
            return static_cast<CheckLevel>(i);
        }
    }

    return CheckLevelUndefined;
}

static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
    return c1.name < c2.name;
}

static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
    if (c1.level == c2.level)
        return checkLessThan(c1, c2);

    return c1.level < c2.level;
}

ClazyASTAction::ClazyASTAction()
    : PluginASTAction()
    , m_checkManager(CheckManager::instance())
{
}

std::unique_ptr<clang::ASTConsumer> ClazyASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)
{
    return llvm::make_unique<LazyASTConsumer>(ci, m_checkManager, m_checks, m_inplaceFixits);
}

bool ClazyASTAction::ParseArgs(const CompilerInstance &, const std::vector<std::string> &args_)
{
    std::vector<std::string> args = args_;

    if (parseArgument("help", args)) {
        PrintHelp(llvm::errs());
        return true;
    }

    if (parseArgument("no-inplace-fixits", args)) {
        // Unit-tests don't use inplace fixits
        m_inplaceFixits = false;
    }

    // This argument is for debugging purposes
    const bool printRequestedChecks = parseArgument("print-requested-checks", args);

    const CheckLevel requestedLevel = parseLevel(/*by-ref*/args);
    if (requestedLevel != CheckLevelUndefined) {
        m_checkManager->setRequestedLevel(requestedLevel);
    }

    if (parseArgument("enable-all-fixits", args)) {
        // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.
        m_checkManager->enableAllFixIts();
    }

    if (args.size() > 1) {
        // Too many arguments.
        llvm::errs() << "Too many arguments: ";
        for (const std::string &a : args)
            llvm::errs() << a << ' ';
        llvm::errs() << "\n";

        PrintHelp(llvm::errs());
        return false;
    } else if (args.size() == 1) {
        vector<string> userDisabledChecks;
        m_checks = m_checkManager->checksForCommaSeparatedString(args[0], /*by-ref=*/userDisabledChecks);
        if (m_checks.empty()) {
            llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n";
            PrintHelp(llvm::errs());
            return false;
        }
    }

    vector<string> userDisabledChecks;
    // Append checks specified from env variable
    RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(/*by-ref*/userDisabledChecks);
    copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks));

    if (m_checks.empty() && requestedLevel == CheckLevelUndefined) {
        // No check or level specified, lets use the default level
        m_checkManager->setRequestedLevel(DefaultCheckLevel);
    }

    // Add checks from requested level
    auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel();
    clazy_std::append(checksFromRequestedLevel, m_checks);
    clazy_std::sort_and_remove_dups(m_checks, checkLessThan);
    CheckManager::removeChecksFromList(m_checks, userDisabledChecks);

    if (printRequestedChecks) {
        llvm::errs() << "Requested checks: ";
        const unsigned int numChecks = m_checks.size();
        for (unsigned int i = 0; i < numChecks; ++i) {
            llvm::errs() << m_checks.at(i).name;
            const bool isLast = i == numChecks - 1;
            if (!isLast) {
                llvm::errs() << ", ";
            }
        }

        llvm::errs() << "\n";
    }

    return true;
}

void ClazyASTAction::PrintHelp(llvm::raw_ostream &ros)
{
    RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel);
    clazy_std::sort(checks, checkLessThanByLevel);

    ros << "Available checks and FixIts:\n\n";
    const bool useMarkdown = getenv("CLAZY_HELP_USE_MARKDOWN");

    int lastPrintedLevel = -1;
    const auto numChecks = checks.size();
    for (unsigned int i = 0; i < numChecks; ++i) {
        const RegisteredCheck &check = checks[i];
        const string levelStr = "level" + to_string(check.level);
        if (lastPrintedLevel < check.level) {
            lastPrintedLevel = check.level;

            if (check.level > 0)
                ros << "\n";

            ros << "- Checks from " << levelStr << ":\n";
        }

        const string relativeReadmePath = levelStr + "/README-" + check.name + ".md";

        auto padded = check.name;
        padded.insert(padded.end(), 39 - padded.size(), ' ');
        ros << "    - " << (useMarkdown ? "[" : "") << check.name << (useMarkdown ? "](" + relativeReadmePath + ")" : "");
        auto fixits = m_checkManager->availableFixIts(check.name);
        if (!fixits.empty()) {
            ros << "    (";
            bool isFirst = true;
            for (const auto& fixit : fixits) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    ros << ',';
                }

                ros << fixit.name;
            }
            ros << ')';
        }
        ros << "\n";
    }
    ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n";
    ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n";
    ros << "    export CLAZY_CHECKS=\"level0\"\n";
    ros << "    export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n";
    ros << "    export CLAZY_CHECKS=\"reserve-candidates\"\n\n";
    ros << "or pass as compiler arguments, for example:\n";
    ros << "    -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n";
    ros << "\n";
    ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n";
    ros << "    export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n";
    ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n";
}

static FrontendPluginRegistry::Add<ClazyASTAction>
X("clang-lazy", "clang lazy plugin");
<|endoftext|>


<commit_before>#include <catch.hpp>

#include <httplib/http/request.hpp>

#include <sstream>

TEST_CASE("request's output operator outputs", "[http_request_t]") {
    httplib::http_request_t request {
        "MyMETHOD",
        "/url/path?query&arg=value#frag",
        {13, 37},
        {
            {"Content-Length", {"10"}},
            {"Content-Type", {"application/json"}},
            {"Home", {"localhost"}},
            {"xxx", {"yyy", "zzz"}}
        }
    };

    std::ostringstream stream;
    stream << request;

    std::string expected =
        "MyMETHOD /url/path?query&arg=value#frag HTTP/13.37\r\n"
        "Home: localhost\r\n"
        "Content-Length: 10\r\n"
        "Content-Type: application/json\r\n"
        "xxx: yyy\r\n"
        "xxx: zzz\r\n"
        "\r\n";

    REQUIRE(stream.str() == expected);
}
<commit_msg>One more check.<commit_after>#include <catch.hpp>

#include <httplib/http/request.hpp>

#include <sstream>

TEST_CASE("request's output operator outputs", "[http_request_t]") {
    httplib::http_request_t request {
        "MyMETHOD",
        "/url/path?query&arg=value#frag",
        {13, 37},
        {
            {"Content-Length", {"10"}},
            {"Content-Type", {"application/json"}},
            {"Home", {"localhost"}},
            {"xxx", {"yyy", "zzz"}}
        }
    };

    std::ostringstream stream;
    stream << request;

    REQUIRE(static_cast<bool>(stream));

    std::string expected =
        "MyMETHOD /url/path?query&arg=value#frag HTTP/13.37\r\n"
        "Home: localhost\r\n"
        "Content-Length: 10\r\n"
        "Content-Type: application/json\r\n"
        "xxx: yyy\r\n"
        "xxx: zzz\r\n"
        "\r\n";

    REQUIRE(stream.str() == expected);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBenchmark.h"
#include "SkCanvas.h"
#include "SkFontHost.h"
#include "SkPaint.h"
#include "SkString.h"
#include "SkTemplates.h"

#include "gUniqueGlyphIDs.h"

class FontCacheBench : public SkBenchmark {
    enum { N = SkBENCHLOOP(50) };
public:
    FontCacheBench(void* param) : INHERITED(param) {
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return "fontcache";
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkPaint paint;
        this->setupPaint(&paint);
        paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);

        const uint16_t* array = gUniqueGlyphIDs;
        while (*array != 0xFFFF) {
            const uint16_t* end = array + 1;
            while (*end != 0xFFFF) {
                end += 1;
            }
            for (int i = 0; i < N; ++i) {
                size_t len = (end - array) * sizeof(uint16_t);
                paint.measureText(array, len);
            }
            array = end + 1;    // skip the sentinel
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

DEF_BENCH( return new FontCacheBench(p); )
<commit_msg>add cache efficiency test<commit_after>/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBenchmark.h"
#include "SkCanvas.h"
#include "SkFontHost.h"
#include "SkPaint.h"
#include "SkString.h"
#include "SkTemplates.h"

#include "gUniqueGlyphIDs.h"
#define gUniqueGlyphIDs_Sentinel    0xFFFF

static int count_glyphs(const uint16_t start[]) {
    const uint16_t* curr = start;
    while (*curr != gUniqueGlyphIDs_Sentinel) {
        curr += 1;
    }
    return curr - start;
}

class FontCacheBench : public SkBenchmark {
    enum {
        N = SkBENCHLOOP(50)
    };

public:
    FontCacheBench(void* param) : INHERITED(param) {}

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return "fontcache";
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkPaint paint;
        this->setupPaint(&paint);
        paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);

        const uint16_t* array = gUniqueGlyphIDs;
        while (*array != gUniqueGlyphIDs_Sentinel) {
            size_t count = count_glyphs(array);
            for (int i = 0; i < N; ++i) {
                paint.measureText(array, count * sizeof(uint16_t));
            }
            array += count + 1;    // skip the sentinel
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static uint32_t rotr(uint32_t value, unsigned bits) {
    return (value >> bits) | (value << (32 - bits));
}

typedef uint32_t (*HasherProc)(uint32_t);

static uint32_t hasher0(uint32_t value) {
    value = value ^ (value >> 16);
    return value ^ (value >> 8);
}

static uint32_t hasher2(uint32_t h) {
    h ^= h >> 16;
    h *= 0x85ebca6b;
    h ^= h >> 13;
    h *= 0xc2b2ae35;
    h ^= h >> 16;

    h ^= (h >> 8);
    return h;
}

static const struct {
    const char* fName;
    HasherProc  fHasher;
} gRec[] = {
    { "hasher0",  hasher0 },
    { "hasher2",  hasher2 },
};

#define kMaxHashBits   12
#define kMaxHashCount  (1 << kMaxHashBits)

static int count_collisions(const uint16_t array[], int count, HasherProc proc,
                            unsigned hashMask) {
    char table[kMaxHashCount];
    sk_bzero(table, sizeof(table));

    int collisions = 0;
    for (int i = 0; i < count; ++i) {
        int index = proc(array[i]) & hashMask;
        collisions += table[index];
        table[index] = 1;
    }
    return collisions;
}

static void dump_array(const uint16_t array[], int count) {
    for (int i = 0; i < count; ++i) {
        SkDebugf(" %d,", array[i]);
    }
    SkDebugf("\n");
}

class FontCacheEfficiency : public SkBenchmark {
public:
    FontCacheEfficiency(void* param) : INHERITED(param) {
        if (false) dump_array(NULL, 0);
        if (false) rotr(0, 0);
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return "fontefficiency";
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        static bool gDone;
        if (gDone) {
            return;
        }
        gDone = true;

        for (int hashBits = 6; hashBits <= 12; hashBits += 1) {
            int hashMask = ((1 << hashBits) - 1);
            for (int limit = 32; limit <= 1024; limit <<= 1) {
                for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) {
                    int collisions = 0;
                    int glyphs = 0;
                    const uint16_t* array = gUniqueGlyphIDs;
                    while (*array != gUniqueGlyphIDs_Sentinel) {
                        int count = SkMin32(count_glyphs(array), limit);
                        collisions += count_collisions(array, count, gRec[i].fHasher, hashMask);
                        glyphs += count;
                        array += count + 1;    // skip the sentinel
                    }
                    SkDebugf("hashBits [%d] limit [%d] collisions [%d / %d = %1.2g%%] using %s\n", hashBits, limit, collisions, glyphs,
                             collisions * 100.0 / glyphs, gRec[i].fName);
                }
            }
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

DEF_BENCH( return new FontCacheBench(p); )

// undefine this to run the efficiency test
//DEF_BENCH( return new FontCacheEfficiency(p); )
<|endoftext|>


<commit_before>#include "Course.h"
#include <string>
using namespace std;

Course::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){
	startTime = _startTime;
	endTime = _endTime;
	days = _days;
	courseName = _courseName;
	courseLoc = _courseLoc;
	courseId = _courseId;
}

int const Course::getEndTime(){
	return endTime;
}

int const Course::getStartTime(){
	return startTime;
}

string const Course::getDays(){
	return days;
}

string const Course::getName(){
	return courseName;
}

string const Course::getLoc(){
	return courseLoc;
}

int const Course::getId(){
	return courseId;
}

void Course::setRating(unsigned int _rating){

}

int const Course::getRating(){
	return 0;
}<commit_msg>Course.it11 - pass: rating<commit_after>#include "Course.h"
#include <string>
using namespace std;

Course::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){
	startTime = _startTime;
	endTime = _endTime;
	days = _days;
	courseName = _courseName;
	courseLoc = _courseLoc;
	courseId = _courseId;
}

int const Course::getEndTime(){
	return endTime;
}

int const Course::getStartTime(){
	return startTime;
}

string const Course::getDays(){
	return days;
}

string const Course::getName(){
	return courseName;
}

string const Course::getLoc(){
	return courseLoc;
}

int const Course::getId(){
	return courseId;
}

void Course::setRating(unsigned int _rating){
	rating = _rating;
}

int const Course::getRating(){
	return rating;
}<|endoftext|>