<commit_before>#ifndef STAN_MATH_FWD_CORE_OPERATOR_DIVISION_HPP
#define STAN_MATH_FWD_CORE_OPERATOR_DIVISION_HPP

#include <stan/math/fwd/core/fvar.hpp>
#include <stan/math/prim/core/operator_division.hpp>
#include <complex>
#include <type_traits>

namespace stan {
namespace math {

/**
 * Return the result of dividing the first argument by the second.
 *
 * @tparam T type of fvar value and tangent
 * @param x1 first argument
 * @param x2 second argument
 * @return first argument divided by second argument
 */
template <typename T>
inline fvar<T> operator/(const fvar<T>& x1, const fvar<T>& x2) {
  return fvar<T>(x1.val_ / x2.val_,
                 (x1.d_ * x2.val_ - x1.val_ * x2.d_) / (x2.val_ * x2.val_));
}

/**
 * Return the result of dividing the first argument by the second.
 *
 * @tparam T type of fvar value and tangent
 * @param x1 first argument
 * @param x2 second argument
 * @return first argument divided by second argument
 */
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline fvar<T> operator/(const fvar<T>& x1, U x2) {
  return fvar<T>(x1.val_ / static_cast<double>(x2), x1.d_ / static_cast<double>(x2));
}

/**
 * Return the result of dividing the first argument by the second.
 *
 * @tparam T type of fvar value and tangent
 * @param x1 first argument
 * @param x2 second argument
 * @return first argument divided by second argument
 */
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline fvar<T> operator/(U x1, const fvar<T>& x2) {
  return fvar<T>(static_cast<double>(x1) / x2.val_, -static_cast<double>(x1) * x2.d_ / (x2.val_ * x2.val_));
}

template <typename T>
inline std::complex<fvar<T>> operator/(const std::complex<fvar<T>>& x1,
                                       const std::complex<fvar<T>>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(const std::complex<fvar<T>>& x1,
                                       const std::complex<U>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T>
inline std::complex<fvar<T>> operator/(const std::complex<fvar<T>>& x1,
                                       const fvar<T>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(const std::complex<fvar<T>>& x1, U x2) {
  return internal::complex_divide(x1, x2);
}

template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(const std::complex<U>& x1,
                                       const std::complex<fvar<T>>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(const std::complex<U>& x1,
                                       const fvar<T>& x2) {
  return internal::complex_divide(x1, x2);
}

template <typename T>
inline std::complex<fvar<T>> operator/(const fvar<T>& x1,
                                       const std::complex<fvar<T>>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T, typename U,
          typename = std::enable_if_t<std::is_arithmetic<U>::value>>
inline std::complex<fvar<T>> operator/(const fvar<T>& x1,
                                       const std::complex<U>& x2) {
  return internal::complex_divide(x1, x2);
}

template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(U x1, const std::complex<fvar<T>>& x2) {
  return internal::complex_divide(x1, x2);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_FWD_CORE_OPERATOR_DIVISION_HPP
#define STAN_MATH_FWD_CORE_OPERATOR_DIVISION_HPP

#include <stan/math/fwd/core/fvar.hpp>
#include <stan/math/prim/core/operator_division.hpp>
#include <complex>
#include <type_traits>

namespace stan {
namespace math {

/**
 * Return the result of dividing the first argument by the second.
 *
 * @tparam T type of fvar value and tangent
 * @param x1 first argument
 * @param x2 second argument
 * @return first argument divided by second argument
 */
template <typename T>
inline fvar<T> operator/(const fvar<T>& x1, const fvar<T>& x2) {
  return fvar<T>(x1.val_ / x2.val_,
                 (x1.d_ * x2.val_ - x1.val_ * x2.d_) / (x2.val_ * x2.val_));
}

/**
 * Return the result of dividing the first argument by the second.
 *
 * @tparam T type of fvar value and tangent
 * @param x1 first argument
 * @param x2 second argument
 * @return first argument divided by second argument
 */
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline fvar<T> operator/(const fvar<T>& x1, U x2) {
  return fvar<T>(x1.val_ / static_cast<double>(x2),
                 x1.d_ / static_cast<double>(x2));
}

/**
 * Return the result of dividing the first argument by the second.
 *
 * @tparam T type of fvar value and tangent
 * @param x1 first argument
 * @param x2 second argument
 * @return first argument divided by second argument
 */
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline fvar<T> operator/(U x1, const fvar<T>& x2) {
  return fvar<T>(static_cast<double>(x1) / x2.val_,
                 -static_cast<double>(x1) * x2.d_ / (x2.val_ * x2.val_));
}

template <typename T>
inline std::complex<fvar<T>> operator/(const std::complex<fvar<T>>& x1,
                                       const std::complex<fvar<T>>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(const std::complex<fvar<T>>& x1,
                                       const std::complex<U>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T>
inline std::complex<fvar<T>> operator/(const std::complex<fvar<T>>& x1,
                                       const fvar<T>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(const std::complex<fvar<T>>& x1, U x2) {
  return internal::complex_divide(x1, x2);
}

template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(const std::complex<U>& x1,
                                       const std::complex<fvar<T>>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(const std::complex<U>& x1,
                                       const fvar<T>& x2) {
  return internal::complex_divide(x1, x2);
}

template <typename T>
inline std::complex<fvar<T>> operator/(const fvar<T>& x1,
                                       const std::complex<fvar<T>>& x2) {
  return internal::complex_divide(x1, x2);
}
template <typename T, typename U,
          typename = std::enable_if_t<std::is_arithmetic<U>::value>>
inline std::complex<fvar<T>> operator/(const fvar<T>& x1,
                                       const std::complex<U>& x2) {
  return internal::complex_divide(x1, x2);
}

template <typename T, typename U, require_arithmetic_t<U>* = nullptr>
inline std::complex<fvar<T>> operator/(U x1, const std::complex<fvar<T>>& x2) {
  return internal::complex_divide(x1, x2);
}

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


<commit_before>#include "BOX.H"

#include "CONTROL.H"
#include "DRAW.H"
#include "LOT.H"
#include "SPECIFIC.H"

#include <stddef.h>

int number_boxes;
struct box_info* boxes;
unsigned short* overlap;
short* ground_zone[5][2];
unsigned short testclip;
unsigned short loops;

void DropBaddyPickups(struct ITEM_INFO* item)//259BC(<), 25BC8(<)
{
	short pickup_number;
	short room_number;
	struct ITEM_INFO* pickup;

	pickup_number = item->carried_item;

	if (pickup_number == -1)
	{
		return;
	}

	do
	{
		pickup = &items[pickup_number];
		pickup->pos.x_pos = (item->pos.x_pos & 0xFFFFFC00) | 0x200;
		pickup->pos.z_pos = (item->pos.z_pos & 0xFFFFFC00) | 0x200;
		room_number = item->room_number;

		pickup->pos.y_pos = GetHeight(GetFloor(pickup->pos.x_pos, item->pos.y_pos, pickup->pos.z_pos, &room_number), pickup->pos.x_pos, item->pos.y_pos, pickup->pos.z_pos);
		pickup->pos.y_pos -= GetBoundsAccurate(item)[3];

		//pickup->pos.y_pos -= bounds[3]; //old
#if 0
		ItemNewRoom(pickup_number, item->room_number);
#endif

	} while (pickup_number != -1);
}

int MoveCreature3DPos(struct PHD_3DPOS* srcpos, struct PHD_3DPOS* destpos, int velocity, short angdif, int angadd)
{
	S_Warn("[MoveCreature3DPos] - Unimplemented!\n");
	return 0;
}

void CreatureYRot(struct PHD_3DPOS* srcpos, short angle, short angadd)
{
	S_Warn("[CreatureYRot] - Unimplemented!\n");
}

short SameZone(struct creature_info* creature, struct ITEM_INFO* target_item)
{
	S_Warn("[SameZone] - Unimplemented!\n");
	return 0;
}

void FindAITargetObject(struct creature_info* creature, short obj_num)
{
	S_Warn("[FindAITargetObject] - Unimplemented!\n");
}

void GetAITarget(struct creature_info* creature)
{
	S_Warn("[GetAITarget] - Unimplemented!\n");
}

short AIGuard(struct creature_info* creature)
{
	S_Warn("[AIGuard] - Unimplemented!\n");
	return 0;
}

void AlertNearbyGuards(struct ITEM_INFO* item)//24D20(<), 24F2C(<)
{
	int slot = 4;
	struct creature_info* cinfo = baddie_slots;
	struct ITEM_INFO* target;
	long x = 0;
	long y = 0;
	long z = 0;
	long distance = 0;
	int i = 0;

	//loc_24D3C
	for (i = 0; i < slot; i++)
	{
		if (cinfo->item_num == -1)
		{
			continue;
		}

		target = &items[cinfo->item_num + i];

		//Rooms match, alert the guards!
		if (item->room_number == target->room_number)
		{
			//24DCC
			cinfo->alerted = 1;
			continue;
		}

		x = (target->pos.x_pos - item->pos.x_pos) / 64;
		y = (target->pos.y_pos - item->pos.y_pos) / 64;
		z = (target->pos.z_pos - item->pos.z_pos) / 64;

		distance = (x * x) + (y * y) + (z * z);

		//Though the item is not in the same room.
		//If the distance between them is < 0x1F40, alert the guards!
		if (distance < 0x1F40)
		{
			//24DCC
			cinfo->alerted = 1;
		}
	}

	return;
}

void AlertAllGuards(short item_number)
{
	S_Warn("[AlertAllGuards] - Unimplemented!\n");
}

void CreatureKill(struct ITEM_INFO* item, int kill_anim, int kill_state, short lara_anim)
{
	S_Warn("[CreatureKill] - Unimplemented!\n");
}

int CreatureVault(short item_number, short angle, int vault, int shift)
{
	S_Warn("[CreatureVault] - Unimplemented!\n");
	return 0;
}

short CreatureEffectT(struct ITEM_INFO* item, struct BITE_INFO* bite, short damage, short angle, short* generate)
{
	S_Warn("[CreatureEffectT] - Unimplemented!\n");
	return 0;
}

short CreatureEffect(struct ITEM_INFO* item, struct BITE_INFO* bite, short* generate)
{
	S_Warn("[CreatureEffect] - Unimplemented!\n");
	return 0;
}

void CreatureUnderwater(struct ITEM_INFO* item, long depth)
{
	S_Warn("[CreatureUnderwater] - Unimplemented!\n");
}

void CreatureFloat(short item_number)
{
	S_Warn("[CreatureFloat] - Unimplemented!\n");
}

void CreatureJoint(struct ITEM_INFO* item, short joint, short required)
{
	S_Warn("[CreatureJoint] - Unimplemented!\n");
}

void CreatureTilt(struct ITEM_INFO* item, short angle)//24418(<), 24624(<) (F)
{
	angle = (angle << 2) - item->pos.z_rot;

	if(angle < ANGLE(-3))
		angle = ANGLE(-3);
	else if (angle > ANGLE(3))
		angle = ANGLE(3);

	if (ABS(item->pos.z_rot) - ANGLE(15) > ANGLE(15))
	{
		angle >>= 1;
	}

	item->pos.z_rot += angle; // todo in orig code (mips) z_rot is lhu'd into v0 as unsigned, here i skipped that part, maybe it'll break
}

short CreatureTurn(struct ITEM_INFO* item, short maximum_turn)
{
	S_Warn("[CreatureTurn] - Unimplemented!\n");
	return 0;
}

int CreatureAnimation(short item_number, short angle, short tilt)
{
	S_Warn("[CreatureAnimation] - Unimplemented!\n");
	return 0;
}

void CreatureDie(short item_number, int explode)
{
	S_Warn("[CreatureDie] - Unimplemented!\n");
}

int BadFloor(long x, long y, long z, long box_height, long next_height, int room_number, struct lot_info* LOT)
{
	S_Warn("[BadFloor] - Unimplemented!\n");
	return 0;
}

int CreatureCreature(short item_number)
{
	S_Warn("[CreatureCreature] - Unimplemented!\n");
	return 0;
}

enum target_type CalculateTarget(struct PHD_VECTOR* target, struct ITEM_INFO* item, struct lot_info* LOT)
{
	S_Warn("[CalculateTarget] - Unimplemented!\n");
	return NO_TARGET;
}

void CreatureMood(struct ITEM_INFO* item, struct AI_info* info, int violent)
{
	S_Warn("[CreatureMood] - Unimplemented!\n");
}

void GetCreatureMood(struct ITEM_INFO* item, struct AI_info* info, int violent)
{
	S_Warn("[GetCreatureMood] - Unimplemented!\n");
}

int ValidBox(struct ITEM_INFO* item, short zone_number, short box_number)
{
	S_Warn("[ValidBox] - Unimplemented!\n");
	return 0;
}

int EscapeBox(struct ITEM_INFO* item, struct ITEM_INFO* enemy, short box_number)
{
	S_Warn("[EscapeBox] - Unimplemented!\n");
	return 0;
}

void TargetBox(struct lot_info* LOT, short box_number)
{
	S_Warn("[TargetBox] - Unimplemented!\n");
}

int UpdateLOT(struct lot_info* LOT, int expansion)
{
	S_Warn("[UpdateLOT] - Unimplemented!\n");
	return 0;
}

int SearchLOT(struct lot_info* LOT, int expansion)
{
	S_Warn("[SearchLOT] - Unimplemented!\n");
	return 0;
}

void CreatureAIInfo(struct ITEM_INFO* item, struct AI_info* info)
{
	S_Warn("[CreatureAIInfo] - Unimplemented!\n");
}

int CreatureActive(short item_number)
{
	S_Warn("[CreatureActive] - Unimplemented!\n");
	return 0;
}

void InitialiseCreature(short item_number)//21800, ?
{
	struct ITEM_INFO* item = &items[item_number];

	item->hit_status = 1;
	item->data = NULL;
	item->draw_room = (((item->pos.z_pos - room[item->room_number].z) / 1024) & 0xFF) | (((item->pos.x_pos - room[item->room_number].mesh->x) / 4) & 0xFF00);
	item->TOSSPAD = item->pos.y_rot & 0xE000;
	item->item_flags[2] = item->room_number | (item->pos.y_pos - room->minfloor);

	return;
}

int StalkBox(struct ITEM_INFO* item, struct ITEM_INFO* enemy, short box_number)
{
	S_Warn("[StalkBox] - Unimplemented!\n");
	return 0;
}

<commit_msg>Add CreatureActive();<commit_after>#include "BOX.H"

#include "CONTROL.H"
#include "DRAW.H"
#include "LOT.H"
#include "SPECIFIC.H"

#include <stddef.h>

int number_boxes;
struct box_info* boxes;
unsigned short* overlap;
short* ground_zone[5][2];
unsigned short testclip;
unsigned short loops;

void DropBaddyPickups(struct ITEM_INFO* item)//259BC(<), 25BC8(<)
{
	short pickup_number;
	short room_number;
	struct ITEM_INFO* pickup;

	pickup_number = item->carried_item;

	if (pickup_number == -1)
	{
		return;
	}

	do
	{
		pickup = &items[pickup_number];
		pickup->pos.x_pos = (item->pos.x_pos & 0xFFFFFC00) | 0x200;
		pickup->pos.z_pos = (item->pos.z_pos & 0xFFFFFC00) | 0x200;
		room_number = item->room_number;

		pickup->pos.y_pos = GetHeight(GetFloor(pickup->pos.x_pos, item->pos.y_pos, pickup->pos.z_pos, &room_number), pickup->pos.x_pos, item->pos.y_pos, pickup->pos.z_pos);
		pickup->pos.y_pos -= GetBoundsAccurate(item)[3];

		//pickup->pos.y_pos -= bounds[3]; //old
#if 0
		ItemNewRoom(pickup_number, item->room_number);
#endif

	} while (pickup_number != -1);
}

int MoveCreature3DPos(struct PHD_3DPOS* srcpos, struct PHD_3DPOS* destpos, int velocity, short angdif, int angadd)
{
	S_Warn("[MoveCreature3DPos] - Unimplemented!\n");
	return 0;
}

void CreatureYRot(struct PHD_3DPOS* srcpos, short angle, short angadd)
{
	S_Warn("[CreatureYRot] - Unimplemented!\n");
}

short SameZone(struct creature_info* creature, struct ITEM_INFO* target_item)
{
	S_Warn("[SameZone] - Unimplemented!\n");
	return 0;
}

void FindAITargetObject(struct creature_info* creature, short obj_num)
{
	S_Warn("[FindAITargetObject] - Unimplemented!\n");
}

void GetAITarget(struct creature_info* creature)
{
	S_Warn("[GetAITarget] - Unimplemented!\n");
}

short AIGuard(struct creature_info* creature)
{
	S_Warn("[AIGuard] - Unimplemented!\n");
	return 0;
}

void AlertNearbyGuards(struct ITEM_INFO* item)//24D20(<), 24F2C(<)
{
	int slot = 4;
	struct creature_info* cinfo = baddie_slots;
	struct ITEM_INFO* target;
	long x = 0;
	long y = 0;
	long z = 0;
	long distance = 0;
	int i = 0;

	//loc_24D3C
	for (i = 0; i < slot; i++)
	{
		if (cinfo->item_num == -1)
		{
			continue;
		}

		target = &items[cinfo->item_num + i];

		//Rooms match, alert the guards!
		if (item->room_number == target->room_number)
		{
			//24DCC
			cinfo->alerted = 1;
			continue;
		}

		x = (target->pos.x_pos - item->pos.x_pos) / 64;
		y = (target->pos.y_pos - item->pos.y_pos) / 64;
		z = (target->pos.z_pos - item->pos.z_pos) / 64;

		distance = (x * x) + (y * y) + (z * z);

		//Though the item is not in the same room.
		//If the distance between them is < 0x1F40, alert the guards!
		if (distance < 0x1F40)
		{
			//24DCC
			cinfo->alerted = 1;
		}
	}

	return;
}

void AlertAllGuards(short item_number)
{
	S_Warn("[AlertAllGuards] - Unimplemented!\n");
}

void CreatureKill(struct ITEM_INFO* item, int kill_anim, int kill_state, short lara_anim)
{
	S_Warn("[CreatureKill] - Unimplemented!\n");
}

int CreatureVault(short item_number, short angle, int vault, int shift)
{
	S_Warn("[CreatureVault] - Unimplemented!\n");
	return 0;
}

short CreatureEffectT(struct ITEM_INFO* item, struct BITE_INFO* bite, short damage, short angle, short* generate)
{
	S_Warn("[CreatureEffectT] - Unimplemented!\n");
	return 0;
}

short CreatureEffect(struct ITEM_INFO* item, struct BITE_INFO* bite, short* generate)
{
	S_Warn("[CreatureEffect] - Unimplemented!\n");
	return 0;
}

void CreatureUnderwater(struct ITEM_INFO* item, long depth)
{
	S_Warn("[CreatureUnderwater] - Unimplemented!\n");
}

void CreatureFloat(short item_number)
{
	S_Warn("[CreatureFloat] - Unimplemented!\n");
}

void CreatureJoint(struct ITEM_INFO* item, short joint, short required)
{
	S_Warn("[CreatureJoint] - Unimplemented!\n");
}

void CreatureTilt(struct ITEM_INFO* item, short angle)//24418(<), 24624(<) (F)
{
	angle = (angle << 2) - item->pos.z_rot;

	if(angle < ANGLE(-3))
		angle = ANGLE(-3);
	else if (angle > ANGLE(3))
		angle = ANGLE(3);

	if (ABS(item->pos.z_rot) - ANGLE(15) > ANGLE(15))
	{
		angle >>= 1;
	}

	item->pos.z_rot += angle; // todo in orig code (mips) z_rot is lhu'd into v0 as unsigned, here i skipped that part, maybe it'll break
}

short CreatureTurn(struct ITEM_INFO* item, short maximum_turn)
{
	S_Warn("[CreatureTurn] - Unimplemented!\n");
	return 0;
}

int CreatureAnimation(short item_number, short angle, short tilt)
{
	S_Warn("[CreatureAnimation] - Unimplemented!\n");
	return 0;
}

void CreatureDie(short item_number, int explode)
{
	S_Warn("[CreatureDie] - Unimplemented!\n");
}

int BadFloor(long x, long y, long z, long box_height, long next_height, int room_number, struct lot_info* LOT)
{
	S_Warn("[BadFloor] - Unimplemented!\n");
	return 0;
}

int CreatureCreature(short item_number)
{
	S_Warn("[CreatureCreature] - Unimplemented!\n");
	return 0;
}

enum target_type CalculateTarget(struct PHD_VECTOR* target, struct ITEM_INFO* item, struct lot_info* LOT)
{
	S_Warn("[CalculateTarget] - Unimplemented!\n");
	return NO_TARGET;
}

void CreatureMood(struct ITEM_INFO* item, struct AI_info* info, int violent)
{
	S_Warn("[CreatureMood] - Unimplemented!\n");
}

void GetCreatureMood(struct ITEM_INFO* item, struct AI_info* info, int violent)
{
	S_Warn("[GetCreatureMood] - Unimplemented!\n");
}

int ValidBox(struct ITEM_INFO* item, short zone_number, short box_number)
{
	S_Warn("[ValidBox] - Unimplemented!\n");
	return 0;
}

int EscapeBox(struct ITEM_INFO* item, struct ITEM_INFO* enemy, short box_number)
{
	S_Warn("[EscapeBox] - Unimplemented!\n");
	return 0;
}

void TargetBox(struct lot_info* LOT, short box_number)
{
	S_Warn("[TargetBox] - Unimplemented!\n");
}

int UpdateLOT(struct lot_info* LOT, int expansion)
{
	S_Warn("[UpdateLOT] - Unimplemented!\n");
	return 0;
}

int SearchLOT(struct lot_info* LOT, int expansion)
{
	S_Warn("[SearchLOT] - Unimplemented!\n");
	return 0;
}

void CreatureAIInfo(struct ITEM_INFO* item, struct AI_info* info)
{
	S_Warn("[CreatureAIInfo] - Unimplemented!\n");
}

int CreatureActive(short item_number)//218B0(<), ?
{
	struct ITEM_INFO* item = &items[item_number];

	if (item->flags & 0x8000)
	{
		if (item->status != 3)
		{
			return 1;
		}

		if (EnableBaddieAI(item_number, 0) != 0)
		{
			item->status = 2;
			return 1;
		}
	}

	return 0;
}

void InitialiseCreature(short item_number)//21800(<), ?
{
	struct ITEM_INFO* item = &items[item_number];

	item->hit_status = 1;
	item->data = NULL;
	item->draw_room = (((item->pos.z_pos - room[item->room_number].z) / 1024) & 0xFF) | (((item->pos.x_pos - room[item->room_number].mesh->x) / 4) & 0xFF00);
	item->TOSSPAD = item->pos.y_rot & 0xE000;
	item->item_flags[2] = item->room_number | (item->pos.y_pos - room->minfloor);

	return;
}

int StalkBox(struct ITEM_INFO* item, struct ITEM_INFO* enemy, short box_number)
{
	S_Warn("[StalkBox] - Unimplemented!\n");
	return 0;
}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/lib/assert.C $                                            */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2011,2018                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/** @file assert.C
 *  @brief Common handling functions for assert paths.
 */

#include <builtins.h>
#include <kernel/console.H>
#include <assert.h>
#include <sys/task.h>
#include <arch/ppc.H>
#include <kernel/misc.H>

#include <kernel/hbterminatetypes.H>
#include <kernel/terminate.H>
#include <sys/misc.h>
#include <kernel/kernel_reasoncodes.H>

/** Hook location for trace module to set up when loaded. */
namespace TRACE { void (*traceCallback)(void*, size_t) = NULL; };

extern "C" void __assert(AssertBehavior i_assertb, const char* i_file,
                         int i_line)
{
    if ((i_assertb == ASSERT_CRITICAL) && (KernelMisc::in_kernel_mode()))
    {
        i_assertb = ASSERT_KERNEL;
    }

    switch (i_assertb)
    {
        case ASSERT_TRACE_DONE: // Custom trace was provided.
            task_crash();
            break;

        case ASSERT_TRACE_NOTDONE: // Do a normal trace.
            if (NULL != TRACE::traceCallback)
            {
                (*TRACE::traceCallback)(linkRegister(), i_line);
            }
            else
            {
                printk("Assertion failed @%p at %s:%d.\n",
                       linkRegister(), i_file, i_line);
            }
            task_crash();
            break;

        case ASSERT_CRITICAL:  // Critical task, trace not available.
            printk("Assertion failed @%p on line %s:%d. (Crit_Assert)\n",
                   linkRegister(), i_file, i_line);

            // Need to call the external CritAssert system call
            cpu_crit_assert(reinterpret_cast<uint64_t>(linkRegister()));
            break;

        case ASSERT_KERNEL:  // Kernel assert called.
            printk("Assertion failed @%p on line %s:%d. (kassert)\n",
                   linkRegister(), i_file, i_line);

            /*@
             * @errortype
             * @moduleid     KERNEL::MOD_KERNEL_INVALID
             * @reasoncode   KERNEL::RC_ASSERT
             * @userdata1    Failing address
             * @userdata2    <unused>
             * @devdesc      Kernel has asserted
             * @custdesc     Boot firmware has crashed with an internal
             *               error.
             */
            // Call function to create SRC and update TI Data area
            termWriteSRC(TI_KERNEL_ASSERT, KERNEL::RC_ASSERT,
                         reinterpret_cast<uint64_t>(linkRegister()));

            // Call to force TI
            terminateExecuteTI();
            break;
    }

    // Loop forever if we make it here.  Should only happen in kernel code.
    while (true)
    {
        setThreadPriorityLow();
    }
}

<commit_msg>assert: Print the backtrace for critical and kernel assertions<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/lib/assert.C $                                            */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2011,2018                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/** @file assert.C
 *  @brief Common handling functions for assert paths.
 */

#include <builtins.h>
#include <kernel/console.H>
#include <assert.h>
#include <sys/task.h>
#include <arch/ppc.H>
#include <kernel/misc.H>

#include <kernel/hbterminatetypes.H>
#include <kernel/terminate.H>
#include <sys/misc.h>
#include <kernel/kernel_reasoncodes.H>
#include <kernel/taskmgr.H>

/** Hook location for trace module to set up when loaded. */
namespace TRACE { void (*traceCallback)(void*, size_t) = NULL; };

extern "C" void __assert(AssertBehavior i_assertb, const char* i_file,
                         int i_line)
{

    task_t* task = NULL;

    if (KernelMisc::in_kernel_mode())
    {
        task = TaskManager::getCurrentTask();

        if (i_assertb == ASSERT_CRITICAL)
        {
            i_assertb = ASSERT_KERNEL;
        }
    }

    switch (i_assertb)
    {
        case ASSERT_TRACE_DONE: // Custom trace was provided.
            task_crash();
            break;

        case ASSERT_TRACE_NOTDONE: // Do a normal trace.
            if (NULL != TRACE::traceCallback)
            {
                (*TRACE::traceCallback)(linkRegister(), i_line);
            }
            else
            {
                printk("Assertion failed @%p at %s:%d.\n",
                       linkRegister(), i_file, i_line);
            }
            task_crash();
            break;

        case ASSERT_CRITICAL:  // Critical task, trace not available.
            printk("Assertion failed @%p on line %s:%d. (Crit_Assert)\n",
                   linkRegister(), i_file, i_line);

            KernelMisc::printkBacktrace(task);

            // Need to call the external CritAssert system call
            cpu_crit_assert(reinterpret_cast<uint64_t>(linkRegister()));
            break;

        case ASSERT_KERNEL:  // Kernel assert called.
            printk("Assertion failed @%p on line %s:%d. (kassert)\n",
                   linkRegister(), i_file, i_line);

            KernelMisc::printkBacktrace(task);

            /*@
             * @errortype
             * @moduleid     KERNEL::MOD_KERNEL_INVALID
             * @reasoncode   KERNEL::RC_ASSERT
             * @userdata1    Failing address
             * @userdata2    <unused>
             * @devdesc      Kernel has asserted
             * @custdesc     Boot firmware has crashed with an internal
             *               error.
             */
            // Call function to create SRC and update TI Data area
            termWriteSRC(TI_KERNEL_ASSERT, KERNEL::RC_ASSERT,
                         reinterpret_cast<uint64_t>(linkRegister()));

            // Call to force TI
            terminateExecuteTI();
            break;
    }

    // Loop forever if we make it here.  Should only happen in kernel code.
    while (true)
    {
        setThreadPriorityLow();
    }
}

<|endoftext|>


<commit_before>// lock_ios.cpp - Per-stream synchronization.
// Copyright 2016 by David Krauss.
// This source is released under the MIT license, http://opensource.org/licenses/MIT

#include "lock_ios.h"

#include <cassert>
#include <stdexcept>
#include <system_error>

namespace s6_lock_ios {
namespace impl {

int ios_index() {
    static int value = std::ios_base::xalloc();
    return value;
}

void init( std::ios_base & s ) {
    void *& ptr = s.pword( ios_index() );
    if ( ptr ) return;

    s.register_callback( + []( std::ios_base::event e, std::ios_base & s, int ) {
        void *& ptr = s.pword( ios_index() );
        if ( e == std::ios_base::erase_event ) {
            // When the stream is terminated, destroy the mutex.
            delete static_cast< std::recursive_mutex * >( ptr );
            ptr = nullptr; // Do not double delete after copyfmt.

        } else if ( e == std::ios_base::copyfmt_event ) {
            ptr = nullptr; // Do not copy mutex access.
            // Note, copyfmt does not copy rdbuf or otherwise promote races.
        }
    }, 0 );

    ptr = new std::recursive_mutex; // Throw std::bad_alloc or std::system_error.
}

void manip::acquire( std::ios_base & s ) const {
    /*  Accessing pword here assumes that the implementation modifies nothing while
        retrieving a preexisting entry. */
    if ( void * ptr = s.pword( ios_index() ) ) {
        l = ios_lock( * static_cast< std::recursive_mutex * >( ptr ) );
    } else {
        // Imitate error handling of unique_lock::lock.
        throw std::system_error( std::make_error_code( std::errc::operation_not_permitted ), "shared stream is missing a mutex" );
    }
}
}
}
<commit_msg>Trim includes.<commit_after>// lock_ios.cpp - Per-stream synchronization.
// Copyright 2016 by David Krauss.
// This source is released under the MIT license, http://opensource.org/licenses/MIT

#include "lock_ios.h"

#include <system_error>

namespace s6_lock_ios {
namespace impl {

int ios_index() {
    static int value = std::ios_base::xalloc();
    return value;
}

void init( std::ios_base & s ) {
    void *& ptr = s.pword( ios_index() );
    if ( ptr ) return;

    s.register_callback( + []( std::ios_base::event e, std::ios_base & s, int ) {
        void *& ptr = s.pword( ios_index() );
        if ( e == std::ios_base::erase_event ) {
            // When the stream is terminated, destroy the mutex.
            delete static_cast< std::recursive_mutex * >( ptr );
            ptr = nullptr; // Do not double delete after copyfmt.

        } else if ( e == std::ios_base::copyfmt_event ) {
            ptr = nullptr; // Do not copy mutex access.
            // Note, copyfmt does not copy rdbuf or otherwise promote races.
        }
    }, 0 );

    ptr = new std::recursive_mutex; // Throw std::bad_alloc or std::system_error.
}

void manip::acquire( std::ios_base & s ) const {
    /*  Accessing pword here assumes that the implementation modifies nothing while
        retrieving a preexisting entry. */
    if ( void * ptr = s.pword( ios_index() ) ) {
        l = ios_lock( * static_cast< std::recursive_mutex * >( ptr ) );
    } else {
        // Imitate error handling of unique_lock::lock.
        throw std::system_error( std::make_error_code( std::errc::operation_not_permitted ), "shared stream is missing a mutex" );
    }
}
}
}
<|endoftext|>


<commit_before>#ifndef LUNAR_IR_HPP
#define LUNAR_IR_HPP

#include "lunar_common.hpp"
#include "lunar_string.hpp"

#include <vector>

/*
 * TYPE := TYPE0 | ( OWNERSHIP TYPE0 )
 * TYPE0 := SCALAR | VECTOR | STRING | LIST | STRUCT | DICT | SET | DATA | FUNC | RSTREAM | WSTREAM | IDENTIFIER
 *
 * OWNERSHIP := unique | shared | ref | global
 *
 * SCALAR := bool | u64 | s64 | u32 | s32 | u16 | s16 | u8 | s8 | double | float | binary | char | string | ATOM
 * ATOM := `IDENTIFIER
 *
 * VECTOR := ( vector TYPE SIZE)
 * SIZE := An integer greater than or equal to 0
 *
 * STRING := string
 *
 * LIST := ( list TYPE )
 *
 * STRUCT := ( struct IDENTIFIER ( TYPE IDENTIFIER )+ )
 *
 * DICT := ( dict TYPE TYPE )
 *
 * SET := ( set TYPE )
 *
 * DATA := ( data IDENTIFIER (TYPE IDENTIFIER)+ )
 *
 * FUNC := ( func (TYPE*) ( TYPE* ) )
 *
 * RSTREAM := (rstrm TYPE)
 * WSTREAM := (wstrm TYPE)
 */

namespace lunar {

enum OWNERSHIP {
    OWN_UNIQUE,
    OWN_SHARED,
    OWN_IMMOVABLE,
    OWN_REF,
    OWN_GLOBAL,
};

enum SCALAR {
    SC_BOOL,
    SC_U64,
    SC_S64,
    SC_U32,
    SC_S32,
    SC_U16,
    SC_S16,
    SC_U8,
    SC_S8,
    SC_DOUBLE,
    SC_FLOAT,
    SC_CHAR,
    SC_ATOM,
};

enum BASIC_TYPE {
    BT_SCALAR,
    BT_VECTOR,
    BT_STRING,
    BT_LIST,
    BT_STRUCT,
    BT_DICT,
    BT_SET,
    BT_DATA,
    BT_FUNCTYPE,
    BT_RSTREAM,
    BT_WSTREAM,
};

class lunar_ir_ast {
public:
    lunar_ir_ast() { }
    virtual ~lunar_ir_ast() { }
};

class lunar_ir_type {
public:
    lunar_ir_type(BASIC_TYPE type, OWNERSHIP owner_ship) : m_type(type), m_owner_ship(owner_ship) { }
    virtual ~lunar_ir_type() { }

protected:
    BASIC_TYPE m_type;
    OWNERSHIP  m_owner_ship;
};

class lunar_ir_scalar : public lunar_ir_type {
public:
    lunar_ir_scalar(OWNERSHIP owner_ship, SCALAR scalar)
        : lunar_ir_type(BT_SCALAR, owner_ship), m_scalar(scalar) { }

private:
    SCALAR m_scalar;
};

class lunar_ir_vector : public lunar_ir_type {
public:
    lunar_ir_vector(OWNERSHIP owner_ship, std::unique_ptr<lunar_ir_type> type, uint64_t size)
        : lunar_ir_type(BT_VECTOR, owner_ship),
          m_type(std::move(type)),
          m_size(size) { }

    virtual ~lunar_ir_vector() { }

private:
    std::unique_ptr<lunar_ir_type> m_type;
    uint64_t m_size;
};

class lunar_ir_list : public lunar_ir_type {
public:
    lunar_ir_list(OWNERSHIP owner_ship, std::unique_ptr<lunar_ir_type> type)
        : lunar_ir_type(BT_LIST, owner_ship),
          m_type(std::move(type)) { }

    virtual ~lunar_ir_list() { }

private:
    std::unique_ptr<lunar_ir_type> m_type;
};

class lunar_ir_struct : public lunar_ir_type {
public:
    lunar_ir_struct(OWNERSHIP owner_ship, const std::string &name)
        : lunar_ir_type(BT_STRUCT, owner_ship), m_name(name) { }

    virtual ~lunar_ir_struct() { }

    void add_member(std::unique_ptr<lunar_ir_type> type, const std::string &name)
    {
        m_member_types.push_back(std::move(type));
        m_member_names.push_back(name);
    }

private:
    std::vector<std::unique_ptr<lunar_ir_type>> m_member_types;
    std::vector<std::string> m_member_names;
    std::string m_name;
};

class lunar_ir_dict : public lunar_ir_type {
public:
    lunar_ir_dict(OWNERSHIP owner_ship, std::unique_ptr<lunar_ir_type> key, std::unique_ptr<lunar_ir_type> val)
        : lunar_ir_type(BT_DICT, owner_ship), m_key(std::move(key)), m_val(std::move(val)) { }

private:
    std::unique_ptr<lunar_ir_type> m_key;
    std::unique_ptr<lunar_ir_type> m_val;
};

class lunar_ir_set : public lunar_ir_type {
public:
    lunar_ir_set(OWNERSHIP owner_ship, std::unique_ptr<lunar_ir_type> val)
        : lunar_ir_type(BT_SET, owner_ship), m_val(std::move(val)) { }

private:
    std::unique_ptr<lunar_ir_type> m_val;
};

class lunar_ir_data : public lunar_ir_type {
public:
    lunar_ir_data(OWNERSHIP owner_ship, const std::string &name)
        : lunar_ir_type(BT_DATA, owner_ship), m_name(name) { }

    virtual ~lunar_ir_data() { }

    void add_member(std::unique_ptr<lunar_ir_type> type, const std::string &name)
    {
        m_member_types.push_back(std::move(type));
        m_member_names.push_back(name);
    }

private:
    std::vector<std::unique_ptr<lunar_ir_type>> m_member_types;
    std::vector<std::string> m_member_names;
    std::string m_name;
};

class lunar_ir_functype : public lunar_ir_type {
public:
    lunar_ir_functype(OWNERSHIP owner_ship) : lunar_ir_type(BT_FUNCTYPE, owner_ship) { }
    virtual ~lunar_ir_functype() { }

    void add_ret(std::unique_ptr<lunar_ir_type> ret)
    {
        m_ret.push_back(std::move(ret));
    }

    void add_arg(std::unique_ptr<lunar_ir_type> arg)
    {
        m_arg.push_back(std::move(arg));
    }

private:
    std::vector<std::unique_ptr<lunar_ir_type>> m_ret;
    std::vector<std::unique_ptr<lunar_ir_type>> m_arg;
};

class lunar_ir_rstream : public lunar_ir_type {
public:
    lunar_ir_rstream(std::unique_ptr<lunar_ir_type> type)
        : lunar_ir_type(BT_RSTREAM, OWN_UNIQUE), m_type(std::move(type)) { }

    virtual ~lunar_ir_rstream() { }

private:
    std::unique_ptr<lunar_ir_type> m_type;
};

class lunar_ir_wstream : public lunar_ir_type {
public:
    lunar_ir_wstream(std::unique_ptr<lunar_ir_type> type)
        : lunar_ir_type(BT_WSTREAM, OWN_SHARED), m_type(std::move(type)) { }

    virtual ~lunar_ir_wstream() { }

private:
    std::unique_ptr<lunar_ir_type> m_type;
};

class lunar_ir_string : public lunar_ir_type {
public:
    lunar_ir_string(OWNERSHIP owner_ship) : lunar_ir_type(BT_STRING, owner_ship) { }
    virtual ~lunar_ir_string() { }
};

}

#endif // LUNAR_IR_HPP<commit_msg>remove global from ownership<commit_after>#ifndef LUNAR_IR_HPP
#define LUNAR_IR_HPP

#include "lunar_common.hpp"
#include "lunar_string.hpp"

#include <vector>

/*
 * TYPE := TYPE0 | ( OWNERSHIP TYPE0 )
 * TYPE0 := SCALAR | VECTOR | STRING | LIST | STRUCT | DICT | SET | DATA | FUNC | RSTREAM | WSTREAM | IDENTIFIER
 *
 * OWNERSHIP := unique | shared | ref
 *
 * SCALAR := bool | u64 | s64 | u32 | s32 | u16 | s16 | u8 | s8 | double | float | binary | char | string | ATOM
 * ATOM := `IDENTIFIER
 *
 * VECTOR := ( vector TYPE SIZE)
 * SIZE := An integer greater than or equal to 0
 *
 * STRING := string
 *
 * LIST := ( list TYPE )
 *
 * STRUCT := ( struct IDENTIFIER ( TYPE IDENTIFIER )+ )
 *
 * DICT := ( dict TYPE TYPE )
 *
 * SET := ( set TYPE )
 *
 * DATA := ( data IDENTIFIER (TYPE IDENTIFIER)+ )
 *
 * FUNC := ( func (TYPE*) ( TYPE* ) )
 *
 * RSTREAM := (rstrm TYPE)
 * WSTREAM := (wstrm TYPE)
 */

namespace lunar {

enum OWNERSHIP {
    OWN_UNIQUE,
    OWN_SHARED,
    OWN_IMMOVABLE,
    OWN_REF,
};

enum SCALAR {
    SC_BOOL,
    SC_U64,
    SC_S64,
    SC_U32,
    SC_S32,
    SC_U16,
    SC_S16,
    SC_U8,
    SC_S8,
    SC_DOUBLE,
    SC_FLOAT,
    SC_CHAR,
    SC_ATOM,
};

enum BASIC_TYPE {
    BT_SCALAR,
    BT_VECTOR,
    BT_STRING,
    BT_LIST,
    BT_STRUCT,
    BT_DICT,
    BT_SET,
    BT_DATA,
    BT_FUNCTYPE,
    BT_RSTREAM,
    BT_WSTREAM,
};

class lunar_ir_ast {
public:
    lunar_ir_ast() { }
    virtual ~lunar_ir_ast() { }
};

class lunar_ir_type {
public:
    lunar_ir_type(BASIC_TYPE type, OWNERSHIP owner_ship) : m_type(type), m_owner_ship(owner_ship) { }
    virtual ~lunar_ir_type() { }

protected:
    BASIC_TYPE m_type;
    OWNERSHIP  m_owner_ship;
};

class lunar_ir_scalar : public lunar_ir_type {
public:
    lunar_ir_scalar(OWNERSHIP owner_ship, SCALAR scalar)
        : lunar_ir_type(BT_SCALAR, owner_ship), m_scalar(scalar) { }

private:
    SCALAR m_scalar;
};

class lunar_ir_vector : public lunar_ir_type {
public:
    lunar_ir_vector(OWNERSHIP owner_ship, std::unique_ptr<lunar_ir_type> type, uint64_t size)
        : lunar_ir_type(BT_VECTOR, owner_ship),
          m_type(std::move(type)),
          m_size(size) { }

    virtual ~lunar_ir_vector() { }

private:
    std::unique_ptr<lunar_ir_type> m_type;
    uint64_t m_size;
};

class lunar_ir_list : public lunar_ir_type {
public:
    lunar_ir_list(OWNERSHIP owner_ship, std::unique_ptr<lunar_ir_type> type)
        : lunar_ir_type(BT_LIST, owner_ship),
          m_type(std::move(type)) { }

    virtual ~lunar_ir_list() { }

private:
    std::unique_ptr<lunar_ir_type> m_type;
};

class lunar_ir_struct : public lunar_ir_type {
public:
    lunar_ir_struct(OWNERSHIP owner_ship, const std::string &name)
        : lunar_ir_type(BT_STRUCT, owner_ship), m_name(name) { }

    virtual ~lunar_ir_struct() { }

    void add_member(std::unique_ptr<lunar_ir_type> type, const std::string &name)
    {
        m_member_types.push_back(std::move(type));
        m_member_names.push_back(name);
    }

private:
    std::vector<std::unique_ptr<lunar_ir_type>> m_member_types;
    std::vector<std::string> m_member_names;
    std::string m_name;
};

class lunar_ir_dict : public lunar_ir_type {
public:
    lunar_ir_dict(OWNERSHIP owner_ship, std::unique_ptr<lunar_ir_type> key, std::unique_ptr<lunar_ir_type> val)
        : lunar_ir_type(BT_DICT, owner_ship), m_key(std::move(key)), m_val(std::move(val)) { }

private:
    std::unique_ptr<lunar_ir_type> m_key;
    std::unique_ptr<lunar_ir_type> m_val;
};

class lunar_ir_set : public lunar_ir_type {
public:
    lunar_ir_set(OWNERSHIP owner_ship, std::unique_ptr<lunar_ir_type> val)
        : lunar_ir_type(BT_SET, owner_ship), m_val(std::move(val)) { }

private:
    std::unique_ptr<lunar_ir_type> m_val;
};

class lunar_ir_data : public lunar_ir_type {
public:
    lunar_ir_data(OWNERSHIP owner_ship, const std::string &name)
        : lunar_ir_type(BT_DATA, owner_ship), m_name(name) { }

    virtual ~lunar_ir_data() { }

    void add_member(std::unique_ptr<lunar_ir_type> type, const std::string &name)
    {
        m_member_types.push_back(std::move(type));
        m_member_names.push_back(name);
    }

private:
    std::vector<std::unique_ptr<lunar_ir_type>> m_member_types;
    std::vector<std::string> m_member_names;
    std::string m_name;
};

class lunar_ir_functype : public lunar_ir_type {
public:
    lunar_ir_functype(OWNERSHIP owner_ship) : lunar_ir_type(BT_FUNCTYPE, owner_ship) { }
    virtual ~lunar_ir_functype() { }

    void add_ret(std::unique_ptr<lunar_ir_type> ret)
    {
        m_ret.push_back(std::move(ret));
    }

    void add_arg(std::unique_ptr<lunar_ir_type> arg)
    {
        m_arg.push_back(std::move(arg));
    }

private:
    std::vector<std::unique_ptr<lunar_ir_type>> m_ret;
    std::vector<std::unique_ptr<lunar_ir_type>> m_arg;
};

class lunar_ir_rstream : public lunar_ir_type {
public:
    lunar_ir_rstream(std::unique_ptr<lunar_ir_type> type)
        : lunar_ir_type(BT_RSTREAM, OWN_UNIQUE), m_type(std::move(type)) { }

    virtual ~lunar_ir_rstream() { }

private:
    std::unique_ptr<lunar_ir_type> m_type;
};

class lunar_ir_wstream : public lunar_ir_type {
public:
    lunar_ir_wstream(std::unique_ptr<lunar_ir_type> type)
        : lunar_ir_type(BT_WSTREAM, OWN_SHARED), m_type(std::move(type)) { }

    virtual ~lunar_ir_wstream() { }

private:
    std::unique_ptr<lunar_ir_type> m_type;
};

class lunar_ir_string : public lunar_ir_type {
public:
    lunar_ir_string(OWNERSHIP owner_ship) : lunar_ir_type(BT_STRING, owner_ship) { }
    virtual ~lunar_ir_string() { }
};

}

#endif // LUNAR_IR_HPP<|endoftext|>


<commit_before>/*
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 */

#include "mem/tport.hh"

bool
SimpleTimingPort::checkFunctional(PacketPtr pkt)
{
    DeferredPacketIterator i = transmitList.begin();
    DeferredPacketIterator end = transmitList.end();

    for (; i != end; ++i) {
        PacketPtr target = i->pkt;
        // If the target contains data, and it overlaps the
        // probed request, need to update data
        if (pkt->checkFunctional(target)) {
            return true;
        }
    }

    return false;
}

void
SimpleTimingPort::recvFunctional(PacketPtr pkt)
{
    if (!checkFunctional(pkt)) {
        // Just do an atomic access and throw away the returned latency
        recvAtomic(pkt);
    }
}

bool
SimpleTimingPort::recvTiming(PacketPtr pkt)
{
    // If the device is only a slave, it should only be sending
    // responses, which should never get nacked.  There used to be
    // code to hanldle nacks here, but I'm pretty sure it didn't work
    // correctly with the drain code, so that would need to be fixed
    // if we ever added it back.
    //assert(pkt->isRequest());

    if (pkt->memInhibitAsserted()) {
        // snooper will supply based on copy of packet
        // still target's responsibility to delete packet
        delete pkt;
        return true;
    }

    bool needsResponse = pkt->needsResponse();
    Tick latency = recvAtomic(pkt);
    // turn packet around to go back to requester if response expected
    if (needsResponse) {
        // recvAtomic() should already have turned packet into
        // atomic response
        assert(pkt->isResponse());
        schedSendTiming(pkt, curTick + latency);
    } else {
        delete pkt;
    }

    return true;
}

void
SimpleTimingPort::schedSendTiming(PacketPtr pkt, Tick when)
{
    assert(when > curTick);
    assert(when < curTick + Clock::Int::ms);

    // Nothing is on the list: add it and schedule an event
    if (transmitList.empty() || when < transmitList.front().tick) {
        transmitList.push_front(DeferredPacket(when, pkt));
        schedSendEvent(when);
        return;
    }

    // list is non-empty & this belongs at the end
    if (when >= transmitList.back().tick) {
        transmitList.push_back(DeferredPacket(when, pkt));
        return;
    }

    // this belongs in the middle somewhere
    DeferredPacketIterator i = transmitList.begin();
    i++; // already checked for insertion at front
    DeferredPacketIterator end = transmitList.end();

    for (; i != end; ++i) {
        if (when < i->tick) {
            transmitList.insert(i, DeferredPacket(when, pkt));
            return;
        }
    }
    assert(false); // should never get here
}

void
SimpleTimingPort::sendDeferredPacket()
{
    assert(deferredPacketReady());
    // take packet off list here; if recvTiming() on the other side
    // calls sendTiming() back on us (like SimpleTimingCpu does), then
    // we get confused by having a non-active packet on transmitList
    DeferredPacket dp = transmitList.front();
    transmitList.pop_front();
    bool success = sendTiming(dp.pkt);

    if (success) {
        if (!transmitList.empty() && !sendEvent->scheduled()) {
            Tick time = transmitList.front().tick;
            schedule(sendEvent, time <= curTick ? curTick+1 : time);
        }

        if (transmitList.empty() && drainEvent) {
            drainEvent->process();
            drainEvent = NULL;
        }
    } else {
        // Unsuccessful, need to put back on transmitList.  Callee
        // should not have messed with it (since it didn't accept that
        // packet), so we can just push it back on the front.
        assert(!sendEvent->scheduled());
        transmitList.push_front(dp);
    }

    waitingOnRetry = !success;

    if (waitingOnRetry) {
        DPRINTF(Bus, "Send failed, waiting on retry\n");
    }
}

void
SimpleTimingPort::recvRetry()
{
    DPRINTF(Bus, "Received retry\n");
    assert(waitingOnRetry);
    sendDeferredPacket();
}

void
SimpleTimingPort::processSendEvent()
{
    assert(!waitingOnRetry);
    sendDeferredPacket();
}

unsigned int
SimpleTimingPort::drain(Event *de)
{
    if (transmitList.size() == 0)
        return 0;
    drainEvent = de;
    return 1;
}
<commit_msg>Get rid of some commented out code.<commit_after>/*
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 */

#include "mem/tport.hh"

bool
SimpleTimingPort::checkFunctional(PacketPtr pkt)
{
    DeferredPacketIterator i = transmitList.begin();
    DeferredPacketIterator end = transmitList.end();

    for (; i != end; ++i) {
        PacketPtr target = i->pkt;
        // If the target contains data, and it overlaps the
        // probed request, need to update data
        if (pkt->checkFunctional(target)) {
            return true;
        }
    }

    return false;
}

void
SimpleTimingPort::recvFunctional(PacketPtr pkt)
{
    if (!checkFunctional(pkt)) {
        // Just do an atomic access and throw away the returned latency
        recvAtomic(pkt);
    }
}

bool
SimpleTimingPort::recvTiming(PacketPtr pkt)
{
    // If the device is only a slave, it should only be sending
    // responses, which should never get nacked.  There used to be
    // code to hanldle nacks here, but I'm pretty sure it didn't work
    // correctly with the drain code, so that would need to be fixed
    // if we ever added it back.

    if (pkt->memInhibitAsserted()) {
        // snooper will supply based on copy of packet
        // still target's responsibility to delete packet
        delete pkt;
        return true;
    }

    bool needsResponse = pkt->needsResponse();
    Tick latency = recvAtomic(pkt);
    // turn packet around to go back to requester if response expected
    if (needsResponse) {
        // recvAtomic() should already have turned packet into
        // atomic response
        assert(pkt->isResponse());
        schedSendTiming(pkt, curTick + latency);
    } else {
        delete pkt;
    }

    return true;
}

void
SimpleTimingPort::schedSendTiming(PacketPtr pkt, Tick when)
{
    assert(when > curTick);
    assert(when < curTick + Clock::Int::ms);

    // Nothing is on the list: add it and schedule an event
    if (transmitList.empty() || when < transmitList.front().tick) {
        transmitList.push_front(DeferredPacket(when, pkt));
        schedSendEvent(when);
        return;
    }

    // list is non-empty & this belongs at the end
    if (when >= transmitList.back().tick) {
        transmitList.push_back(DeferredPacket(when, pkt));
        return;
    }

    // this belongs in the middle somewhere
    DeferredPacketIterator i = transmitList.begin();
    i++; // already checked for insertion at front
    DeferredPacketIterator end = transmitList.end();

    for (; i != end; ++i) {
        if (when < i->tick) {
            transmitList.insert(i, DeferredPacket(when, pkt));
            return;
        }
    }
    assert(false); // should never get here
}

void
SimpleTimingPort::sendDeferredPacket()
{
    assert(deferredPacketReady());
    // take packet off list here; if recvTiming() on the other side
    // calls sendTiming() back on us (like SimpleTimingCpu does), then
    // we get confused by having a non-active packet on transmitList
    DeferredPacket dp = transmitList.front();
    transmitList.pop_front();
    bool success = sendTiming(dp.pkt);

    if (success) {
        if (!transmitList.empty() && !sendEvent->scheduled()) {
            Tick time = transmitList.front().tick;
            schedule(sendEvent, time <= curTick ? curTick+1 : time);
        }

        if (transmitList.empty() && drainEvent) {
            drainEvent->process();
            drainEvent = NULL;
        }
    } else {
        // Unsuccessful, need to put back on transmitList.  Callee
        // should not have messed with it (since it didn't accept that
        // packet), so we can just push it back on the front.
        assert(!sendEvent->scheduled());
        transmitList.push_front(dp);
    }

    waitingOnRetry = !success;

    if (waitingOnRetry) {
        DPRINTF(Bus, "Send failed, waiting on retry\n");
    }
}

void
SimpleTimingPort::recvRetry()
{
    DPRINTF(Bus, "Received retry\n");
    assert(waitingOnRetry);
    sendDeferredPacket();
}

void
SimpleTimingPort::processSendEvent()
{
    assert(!waitingOnRetry);
    sendDeferredPacket();
}

unsigned int
SimpleTimingPort::drain(Event *de)
{
    if (transmitList.size() == 0)
        return 0;
    drainEvent = de;
    return 1;
}
<|endoftext|>


<commit_before>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

#include "log.hh"
#include "model.hh"
#include "null.hh"
#include "conf.hh"
#include "helper.hh"
#include <cstring>

namespace {

  std::vector<void*> mods;

  void mods_atexit() {
    for(unsigned i=0;i<mods.size();i++) {
      dlclose(mods[i]);
    }
  }

  Model* lib_creator(Log& l, std::string params) {
    Model* m;
    std::string model_name,model_param,model_filename;
    std::string s(unescape_string(strdup(params.c_str())));

    split(s, model_name, model_param);
    split(model_name,model_name,model_filename,",");

    m = ModelFactory::create(l, model_name, model_param);

    if (!m) {
      void* handle=load_lib(model_name,model_filename);

      if (handle) {
	m = ModelFactory::create(l, model_name, model_param);
	if (mods.empty()) {
	  atexit(mods_atexit);
	}
	mods.push_back(handle);
      } else {
	m = new Null(l);
	if (m) {
	  m->status   = false;
	  m->errormsg = std::string("lib:Can't load model ") + params;
	}
      }
    }
    return m;
  }
  static ModelFactory::Register me("lib", lib_creator);
}
<commit_msg>Fix compiler error caused by dlclose()<commit_after>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

#include "log.hh"
#include "model.hh"
#include "null.hh"
#include "conf.hh"
#include "helper.hh"
#include <dlfcn.h>
#include <cstring>

namespace {

  std::vector<void*> mods;

  void mods_atexit() {
    for(unsigned i=0;i<mods.size();i++) {
      dlclose(mods[i]);
    }
  }

  Model* lib_creator(Log& l, std::string params) {
    Model* m;
    std::string model_name,model_param,model_filename;
    std::string s(unescape_string(strdup(params.c_str())));

    split(s, model_name, model_param);
    split(model_name,model_name,model_filename,",");

    m = ModelFactory::create(l, model_name, model_param);

    if (!m) {
      void* handle=load_lib(model_name,model_filename);

      if (handle) {
	m = ModelFactory::create(l, model_name, model_param);
	if (mods.empty()) {
	  atexit(mods_atexit);
	}
	mods.push_back(handle);
      } else {
	m = new Null(l);
	if (m) {
	  m->status   = false;
	  m->errormsg = std::string("lib:Can't load model ") + params;
	}
      }
    }
    return m;
  }
  static ModelFactory::Register me("lib", lib_creator);
}
<|endoftext|>


<commit_before>/**
 * Copyright 2014, Planet Labs, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "compositor.h"

/************************************************************************/
/*                              PLCInput()                              */
/************************************************************************/

PLCInput::PLCInput(int inputIndex)
{
    DS = NULL;
    cloudDS = NULL;
    this->inputIndex = inputIndex;
}

/************************************************************************/
/*                             ~PLCInput()                              */
/************************************************************************/

PLCInput::~PLCInput()
{
}

/************************************************************************/
/*                            ConsumeArgs()                             */
/*                                                                      */
/*      Parse arguments defining an input file and related              */
/*      information.                                                    */
/*                                                                      */
/*      Like:   [-i input_file [-c cloudmask] [-qm name value]*]*       */
/************************************************************************/
int PLCInput::ConsumeArgs(int argc, char **argv)
{
    if( !EQUAL(argv[0],"-i") || argc < 2)
        CPLError(CE_Fatal, CPLE_AppDefined,
                 "Did not get -i <filename> for input group.");

    filename = argv[1];

    int iArg = 2;

    while(iArg < argc)
    {
        if( iArg < argc-1 && EQUAL(argv[iArg],"-c") )
        {
            cloudMask = argv[iArg+1];
            iArg += 2;
        }
        else if( iArg < argc-2 && EQUAL(argv[iArg],"-qm") )
        {
            qualityMetrics[argv[iArg+1]] = CPLAtof(argv[iArg+2]);
            iArg += 3;
        }
        else
            break;
    }

    return iArg;
}

/************************************************************************/
/*                            ConsumeJson()                             */
/************************************************************************/

void PLCInput::ConsumeJson(WJElement json)

{
    WJElement value = NULL;
    for( value=json->child; value != NULL; value = value->next )
    {
        if( EQUAL(value->name, "filename") )
        {
            filename = WJEString(json, value->name, WJE_GET, "");
        }
        else if( EQUAL(value->name, "cloud_file") )
        {
            cloudMask = WJEString(json, value->name, WJE_GET, "");
        }
        else if( value->type == WJR_TYPE_STRING )
        {
            parameters[value->name] = WJEString(json, value->name, WJE_GET, "");
        }
        else
        {
            // need to capture other sorts of parameters too!
            qualityMetrics[value->name] =
                WJEDouble(json, value->name, WJE_GET, 0.0);
        }
    }
}

/************************************************************************/
/*                             Initialize()                             */
/*                                                                      */
/*      Ensure all arguments make sense, initialize quality methods,    */
/*      open file(s).                                                   */
/************************************************************************/

void PLCInput::Initialize(PLCContext *plContext)

{
    getDS();
    getCloudDS();
}

/************************************************************************/
/*                               getDS()                                */
/************************************************************************/

GDALDataset *PLCInput::getDS()

{
    if( DS == NULL )
    {
        DS = (GDALDataset *) GDALOpen(filename, GA_ReadOnly);
        if( DS == NULL )
            exit(1);
    }

    return DS;
}

/************************************************************************/
/*                             getCloudDS()                             */
/************************************************************************/

GDALDataset *PLCInput::getCloudDS()

{
    if( cloudDS == NULL && !EQUAL(cloudMask,""))
    {
        cloudDS = (GDALDataset *) GDALOpen(cloudMask, GA_ReadOnly);
        if( cloudDS == NULL )
            exit(1);
    }

    return cloudDS;
}

/************************************************************************/
/*                              getLine()                               */
/************************************************************************/

PLCLine *PLCInput::getLine(int line)

{
    getDS();

    int  i, width = DS->GetRasterXSize();
    PLCLine *lineObj = new PLCLine(width);

/* -------------------------------------------------------------------- */
/*      Load imagery.                                                   */
/* -------------------------------------------------------------------- */
    for( i=0; i < DS->GetRasterCount(); i++ )
    {
        CPLErr eErr;
        GDALRasterBand *band = DS->GetRasterBand(i+1);

        if( band->GetColorInterpretation() == GCI_AlphaBand )
            eErr = band->RasterIO(GF_Read, 0, line, width, 1,
                                  lineObj->getAlpha(), width, 1, GDT_Byte,
                                  0, 0);
        else
            eErr = band->RasterIO(GF_Read, 0, line, width, 1,
                                  lineObj->getBand(i), width, 1, GDT_Int16,
                                  0, 0);

        if( eErr != CE_None )
            exit(1);
    }

/* -------------------------------------------------------------------- */
/*      Load cloud mask                                                 */
/* -------------------------------------------------------------------- */
    if( !EQUAL(cloudMask,"") )
    {
        getCloudDS();

        CPLErr eErr;
        GDALRasterBand *band = cloudDS->GetRasterBand(1);

        eErr = band->RasterIO(GF_Read, 0, line, width, 1,
                              lineObj->getCloud(), width, 1, GDT_UInt16,
                              0, 0);

        if( eErr != CE_None )
            exit(1);
    }

    return lineObj;
}

/************************************************************************/
/*                               getQM()                                */
/************************************************************************/

double PLCInput::getQM(const char *key, double defaultValue)

{
    if(qualityMetrics.count(key) > 0)
        return qualityMetrics[key];
    else
        return defaultValue;
}

/************************************************************************/
/*                              getParm()                               */
/************************************************************************/

const char *PLCInput::getParm(const char *key, const char *defaultValue)

{
    if(parameters.count(key) > 0)
        return parameters[key].c_str();
    else
        return defaultValue;
}
<commit_msg>trigger rebuild<commit_after>/**
 * Copyright 2014, Planet Labs, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "compositor.h"

/************************************************************************/
/*                              PLCInput()                              */
/************************************************************************/

PLCInput::PLCInput(int inputIndex)
{
    DS = NULL;
    cloudDS = NULL;
    this->inputIndex = inputIndex;
}

/************************************************************************/
/*                             ~PLCInput()                              */
/************************************************************************/

PLCInput::~PLCInput()
{
}

/************************************************************************/
/*                            ConsumeArgs()                             */
/*                                                                      */
/*      Parse arguments defining an input file and related              */
/*      information.                                                    */
/*                                                                      */
/*      Like:   [-i input_file [-c cloudmask] [-qm name value]*]*       */
/************************************************************************/
int PLCInput::ConsumeArgs(int argc, char **argv)
{
    if( !EQUAL(argv[0],"-i") || argc < 2)
        CPLError(CE_Fatal, CPLE_AppDefined,
                 "Did not get -i <filename> for input group.");

    filename = argv[1];

    int iArg = 2;

    while(iArg < argc)
    {
        if( iArg < argc-1 && EQUAL(argv[iArg],"-c") )
        {
            cloudMask = argv[iArg+1];
            iArg += 2;
        }
        else if( iArg < argc-2 && EQUAL(argv[iArg],"-qm") )
        {
            qualityMetrics[argv[iArg+1]] = CPLAtof(argv[iArg+2]);
            iArg += 3;
        }
        else
            break;
    }

    return iArg;
}

/************************************************************************/
/*                            ConsumeJson()                             */
/************************************************************************/

void PLCInput::ConsumeJson(WJElement json)

{
    WJElement value = NULL;
    for( value=json->child; value != NULL; value = value->next )
    {
        if( EQUAL(value->name, "filename") )
        {
            filename = WJEString(json, value->name, WJE_GET, "");
        }
        else if( EQUAL(value->name, "cloud_file") )
        {
            cloudMask = WJEString(json, value->name, WJE_GET, "");
        }
        else if( value->type == WJR_TYPE_STRING )
        {
            parameters[value->name] = WJEString(json, value->name, WJE_GET, "");
        }
        else
        {
            // need to capture other sorts of parameters too!
            qualityMetrics[value->name] =
                WJEDouble(json, value->name, WJE_GET, 0.0);
        }
    }
}

/************************************************************************/
/*                             Initialize()                             */
/*                                                                      */
/*      Ensure all arguments make sense, initialize quality methods,    */
/*      open file(s).                                                   */
/************************************************************************/

void PLCInput::Initialize(PLCContext *plContext)

{
    getDS();
    getCloudDS();
}

/************************************************************************/
/*                               getDS()                                */
/************************************************************************/

GDALDataset *PLCInput::getDS()

{
    if( DS == NULL )
    {
        DS = (GDALDataset *) GDALOpen(filename, GA_ReadOnly);
        if( DS == NULL )
            exit(1);
    }

    return DS;
}

/************************************************************************/
/*                             getCloudDS()                             */
/************************************************************************/

GDALDataset *PLCInput::getCloudDS()

{
    if( cloudDS == NULL && !EQUAL(cloudMask,""))
    {
        cloudDS = (GDALDataset *) GDALOpen(cloudMask, GA_ReadOnly);
        if( cloudDS == NULL )
            exit(1);
    }

    return cloudDS;
}

/************************************************************************/
/*                              getLine()                               */
/************************************************************************/

PLCLine *PLCInput::getLine(int line)

{
    getDS();

    int  i, width = DS->GetRasterXSize();
    PLCLine *lineObj = new PLCLine(width);

/* -------------------------------------------------------------------- */
/*      Load imagery.                                                   */
/* -------------------------------------------------------------------- */
    for( i=0; i < DS->GetRasterCount(); i++ )
    {
        CPLErr eErr;
        GDALRasterBand *band = DS->GetRasterBand(i+1);

        if( band->GetColorInterpretation() == GCI_AlphaBand )
            eErr = band->RasterIO(GF_Read, 0, line, width, 1,
                                  lineObj->getAlpha(), width, 1, GDT_Byte,
                                  0, 0);
        else
            eErr = band->RasterIO(GF_Read, 0, line, width, 1,
                                  lineObj->getBand(i), width, 1, GDT_Int16,
                                  0, 0);

        if( eErr != CE_None )
            exit(1);
    }

/* -------------------------------------------------------------------- */
/*      Load cloud mask                                                 */
/* -------------------------------------------------------------------- */
    if( !EQUAL(cloudMask,"") )
    {
        getCloudDS();

        CPLErr eErr;
        GDALRasterBand *band = cloudDS->GetRasterBand(1);

        eErr = band->RasterIO(GF_Read, 0, line, width, 1,
                              lineObj->getCloud(), width, 1, GDT_UInt16,
                              0, 0);

        if( eErr != CE_None )
            exit(1);
    }

    return lineObj;
}

/************************************************************************/
/*                               getQM()                                */
/************************************************************************/

double PLCInput::getQM(const char *key, double defaultValue)

{
    if(qualityMetrics.count(key) > 0)
        return qualityMetrics[key];
    else
        return defaultValue;
}

/************************************************************************/
/*                              getParm()                               */
/************************************************************************/

const char *PLCInput::getParm(const char *key, const char *defaultValue)

{
    if(parameters.count(key) > 0)
        return parameters[key].c_str();
    else
        return defaultValue;
}
<|endoftext|>


<commit_before>///
/// @file   primesum.cpp
/// @brief  primesum C++ API
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesum-internal.hpp>
#include <primesum.hpp>
#include <primesieve.hpp>
#include <calculator.hpp>
#include <int128.hpp>
#include <pmath.hpp>

#include <algorithm>
#include <ctime>
#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <stdint.h>

#ifdef _OPENMP
  #include <omp.h>
#endif

#ifdef HAVE_MPI

#include <mpi.h>

namespace primesum {

int mpi_num_procs()
{
  int procs;
  MPI_Comm_size(MPI_COMM_WORLD, &procs);
  return procs;
}

int mpi_proc_id()
{
  int proc_id;
  MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);
  return proc_id;
}

int mpi_master_proc_id()
{
  return 0;
}

bool is_mpi_master_proc()
{
  return mpi_proc_id() == mpi_master_proc_id();
}

} // namespace

#endif

using namespace std;

namespace {

int threads_ = primesum::MAX_THREADS;

int status_precision_ = -1;

double alpha_ = -1;

}

namespace primesum {

maxint_t pi(maxint_t x, int threads)
{
  return pi_deleglise_rivat(x, threads);
}

maxint_t pi(maxint_t x)
{
  return pi(x, threads_);
}

/// Alias for the fastest prime summing function in primesum.
/// @param x  integer arithmetic expression e.g. "10^12".
/// @pre   x  <= get_max_x().
///
string pi(const string& x)
{
  return pi(x, threads_);
}

/// Alias for the fastest prime summing function in primesum.
/// @param x  integer arithmetic expression e.g. "10^12".
/// @pre   x  <= get_max_x().
///
string pi(const string& x, int threads)
{
  maxint_t pi_x = pi(to_maxint(x), threads);
  ostringstream oss;
  oss << pi_x;
  return oss.str();
}

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
maxint_t pi_deleglise_rivat(maxint_t x, int threads)
{
  return pi_deleglise_rivat_parallel1(x, threads);
}

/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x)
{
  return pi_legendre(x, threads_);
}

/// Parallel implementation of the Lagarias-Miller-Odlyzko
/// prime summing algorithm using OpenMP.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
maxint_t pi_lmo(maxint_t x, int threads)
{
  return pi_lmo_parallel1(x, threads);
}

/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x)
{
  return pi_primesieve(x, threads_);
}

/// Calculate the nth prime using a combination of the prime
/// counting function and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
///
int64_t nth_prime(int64_t n)
{
  return nth_prime(n, threads_);
}

/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a)
{
  return phi(x, a, threads_);
}

int64_t prime_sum_tiny(int64_t x)
{
  int64_t prime = 0;
  int64_t prime_sum = 0;
  primesieve::iterator iter(0, x);

  while ((prime = iter.next_prime()) <= x)
    prime_sum += prime;

  return prime_sum;
}

/// Returns the largest integer that can be used with
/// pi(string x). The return type is a string as max can be a 128-bit
/// integer which is not supported by all compilers.
///
string get_max_x(double alpha)
{
  ostringstream oss;

#ifdef HAVE_INT128_T
  // primesum is limited by:
  // z < 2^62, with z = x^(2/3) / alpha
  // x^(2/3) / alpha < 2^62
  // x < (2^62 * alpha)^(3/2)

  // safety buffer: use 61 instead of 62
  double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0);
  oss << (int128_t) max_x;
#else
  unused_param(alpha);
  oss << numeric_limits<int64_t>::max();
#endif

  return oss.str();
}

/// Get the wall time in seconds.
double get_wtime()
{
#ifdef _OPENMP
  return omp_get_wtime();
#else
  return static_cast<double>(std::clock()) / CLOCKS_PER_SEC;
#endif
}

int validate_threads(int threads)
{
#ifdef _OPENMP
  if (threads == MAX_THREADS)
    threads = omp_get_max_threads();
  return in_between(1, threads, omp_get_max_threads());
#else
  threads = 1;
  return threads;
#endif
}

int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)
{
  threads = validate_threads(threads);
  thread_threshold = max((int64_t) 1, thread_threshold);
  threads = (int) min((int64_t) threads, sieve_limit / thread_threshold);
  threads = max(1, threads);
  return threads;
}

void set_alpha(double alpha)
{
  alpha_ = alpha;
}

double get_alpha()
{
  return alpha_;
}

double get_alpha(maxint_t x, int64_t y)
{
  // y = x13 * alpha, thus alpha = y / x13
  double x13 = (double) iroot<3>(x);
  return (double) y / x13;
}

/// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor.
/// alpha = a log(x)^2 + b log(x) + c
/// a, b and c are constants that should be determined empirically.
/// @see ../doc/alpha-factor-tuning.pdf
///
double get_alpha_lmo(maxint_t x)
{
  double alpha = get_alpha();

  // use default alpha if no command-line alpha provided
  if (alpha < 1)
  {
    double a = 0.00156512;
    double b = -0.0261411;
    double c = 0.990948;
    double logx = log((double) x);

    alpha = a * pow(logx, 2) + b * logx + c;
  }

  return in_between(1, alpha, iroot<6>(x));
}

/// Calculate the Deleglise-Rivat alpha tuning factor.
/// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d
/// a, b, c and d are constants that should be determined empirically.
/// @see ../doc/alpha-tuning-factor.pdf
///
double get_alpha_deleglise_rivat(maxint_t x)
{
  double alpha = get_alpha();
  double x2 = (double) x;

  // use default alpha if no command-line alpha provided
  if (alpha < 1)
  {
    double a = 0.00109086;
    double b = -0.0156173;
    double c = -0.0754525;
    double d = 1.54658;
    double logx = log(x2);

    alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
  }

  return in_between(1, alpha, iroot<6>(x));
}

void set_num_threads(int threads)
{
  threads_ = validate_threads(threads);
}

int get_num_threads()
{
  return validate_threads(threads_);
}

void set_status_precision(int precision)
{
  status_precision_ = in_between(0, precision, 5);
}

int get_status_precision(maxint_t x)
{
  // use default precision when no command-line precision provided
  if (status_precision_ < 0)
  {
    if ((double) x >= 1e23)
      return 2;
    if ((double) x >= 1e21)
      return 1;
  }

  return (status_precision_ > 0) ? status_precision_ : 0;
}

maxint_t to_maxint(const string& expr)
{
  maxint_t n = calculator::eval<maxint_t>(expr);
  return n;
}

/// Get the primesum version number, in the form “i.j”.
string primesum_version()
{
  return PRIMESUM_VERSION;
}

} // namespace primesum
<commit_msg>Alpha factor tuning<commit_after>///
/// @file   primesum.cpp
/// @brief  primesum C++ API
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesum-internal.hpp>
#include <primesum.hpp>
#include <primesieve.hpp>
#include <calculator.hpp>
#include <int128.hpp>
#include <pmath.hpp>

#include <algorithm>
#include <ctime>
#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <stdint.h>

#ifdef _OPENMP
  #include <omp.h>
#endif

#ifdef HAVE_MPI

#include <mpi.h>

namespace primesum {

int mpi_num_procs()
{
  int procs;
  MPI_Comm_size(MPI_COMM_WORLD, &procs);
  return procs;
}

int mpi_proc_id()
{
  int proc_id;
  MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);
  return proc_id;
}

int mpi_master_proc_id()
{
  return 0;
}

bool is_mpi_master_proc()
{
  return mpi_proc_id() == mpi_master_proc_id();
}

} // namespace

#endif

using namespace std;

namespace {

int threads_ = primesum::MAX_THREADS;

int status_precision_ = -1;

double alpha_ = -1;

}

namespace primesum {

maxint_t pi(maxint_t x, int threads)
{
  return pi_deleglise_rivat(x, threads);
}

maxint_t pi(maxint_t x)
{
  return pi(x, threads_);
}

/// Alias for the fastest prime summing function in primesum.
/// @param x  integer arithmetic expression e.g. "10^12".
/// @pre   x  <= get_max_x().
///
string pi(const string& x)
{
  return pi(x, threads_);
}

/// Alias for the fastest prime summing function in primesum.
/// @param x  integer arithmetic expression e.g. "10^12".
/// @pre   x  <= get_max_x().
///
string pi(const string& x, int threads)
{
  maxint_t pi_x = pi(to_maxint(x), threads);
  ostringstream oss;
  oss << pi_x;
  return oss.str();
}

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
maxint_t pi_deleglise_rivat(maxint_t x, int threads)
{
  return pi_deleglise_rivat_parallel1(x, threads);
}

/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x)
{
  return pi_legendre(x, threads_);
}

/// Parallel implementation of the Lagarias-Miller-Odlyzko
/// prime summing algorithm using OpenMP.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
maxint_t pi_lmo(maxint_t x, int threads)
{
  return pi_lmo_parallel1(x, threads);
}

/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x)
{
  return pi_primesieve(x, threads_);
}

/// Calculate the nth prime using a combination of the prime
/// counting function and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
///
int64_t nth_prime(int64_t n)
{
  return nth_prime(n, threads_);
}

/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a)
{
  return phi(x, a, threads_);
}

int64_t prime_sum_tiny(int64_t x)
{
  int64_t prime = 0;
  int64_t prime_sum = 0;
  primesieve::iterator iter(0, x);

  while ((prime = iter.next_prime()) <= x)
    prime_sum += prime;

  return prime_sum;
}

/// Returns the largest integer that can be used with
/// pi(string x). The return type is a string as max can be a 128-bit
/// integer which is not supported by all compilers.
///
string get_max_x(double alpha)
{
  ostringstream oss;

#ifdef HAVE_INT128_T
  // primesum is limited by:
  // z < 2^62, with z = x^(2/3) / alpha
  // x^(2/3) / alpha < 2^62
  // x < (2^62 * alpha)^(3/2)

  // safety buffer: use 61 instead of 62
  double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0);
  oss << (int128_t) max_x;
#else
  unused_param(alpha);
  oss << numeric_limits<int64_t>::max();
#endif

  return oss.str();
}

/// Get the wall time in seconds.
double get_wtime()
{
#ifdef _OPENMP
  return omp_get_wtime();
#else
  return static_cast<double>(std::clock()) / CLOCKS_PER_SEC;
#endif
}

int validate_threads(int threads)
{
#ifdef _OPENMP
  if (threads == MAX_THREADS)
    threads = omp_get_max_threads();
  return in_between(1, threads, omp_get_max_threads());
#else
  threads = 1;
  return threads;
#endif
}

int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)
{
  threads = validate_threads(threads);
  thread_threshold = max((int64_t) 1, thread_threshold);
  threads = (int) min((int64_t) threads, sieve_limit / thread_threshold);
  threads = max(1, threads);
  return threads;
}

void set_alpha(double alpha)
{
  alpha_ = alpha;
}

double get_alpha()
{
  return alpha_;
}

double get_alpha(maxint_t x, int64_t y)
{
  // y = x13 * alpha, thus alpha = y / x13
  double x13 = (double) iroot<3>(x);
  return (double) y / x13;
}

/// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor.
/// alpha = a log(x)^2 + b log(x) + c
/// a, b and c are constants that should be determined empirically.
/// @see ../doc/alpha-factor-tuning.pdf
///
double get_alpha_lmo(maxint_t x)
{
  double alpha = get_alpha();

  // use default alpha if no command-line alpha provided
  if (alpha < 1)
  {
    double a = 0.00156512;
    double b = -0.0261411;
    double c = 0.990948;
    double logx = log((double) x);

    alpha = a * pow(logx, 2) + b * logx + c;
  }

  return in_between(1, alpha, iroot<6>(x));
}

/// Calculate the Deleglise-Rivat alpha tuning factor.
/// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d
/// a, b, c and d are constants that should be determined empirically.
/// @see ../doc/alpha-tuning-factor.pdf
///
double get_alpha_deleglise_rivat(maxint_t x)
{
  double alpha = get_alpha();
  double x2 = (double) x;

  // use default alpha if no command-line alpha provided
  if (alpha < 1)
  {
    double a = 0.00334278;
    double b = -0.126468;
    double c = 1.26094;
    double d = -1.10826;
    double logx = log(x2);

    alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
  }

  return in_between(1, alpha, iroot<6>(x));
}

void set_num_threads(int threads)
{
  threads_ = validate_threads(threads);
}

int get_num_threads()
{
  return validate_threads(threads_);
}

void set_status_precision(int precision)
{
  status_precision_ = in_between(0, precision, 5);
}

int get_status_precision(maxint_t x)
{
  // use default precision when no command-line precision provided
  if (status_precision_ < 0)
  {
    if ((double) x >= 1e23)
      return 2;
    if ((double) x >= 1e21)
      return 1;
  }

  return (status_precision_ > 0) ? status_precision_ : 0;
}

maxint_t to_maxint(const string& expr)
{
  maxint_t n = calculator::eval<maxint_t>(expr);
  return n;
}

/// Get the primesum version number, in the form “i.j”.
string primesum_version()
{
  return PRIMESUM_VERSION;
}

} // namespace primesum
<|endoftext|>