<commit_before>#include <cassert>

#include "SDL.h"

#include "ChooseAttributesPanel.h"
#include "ChooseGenderPanel.h"
#include "ChooseRacePanel.h"
#include "CursorAlignment.h"
#include "RichTextString.h"
#include "TextAlignment.h"
#include "TextSubPanel.h"
#include "../Assets/ExeStrings.h"
#include "../Assets/MiscAssets.h"
#include "../Assets/WorldMapMask.h"
#include "../Game/Game.h"
#include "../Game/Options.h"
#include "../Math/Rect.h"
#include "../Media/Color.h"
#include "../Media/FontManager.h"
#include "../Media/FontName.h"
#include "../Media/PaletteFile.h"
#include "../Media/PaletteName.h"
#include "../Media/TextureFile.h"
#include "../Media/TextureManager.h"
#include "../Media/TextureName.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Surface.h"
#include "../Utilities/String.h"

const int ChooseRacePanel::NO_ID = -1;

ChooseRacePanel::ChooseRacePanel(Game &game, const CharacterClass &charClass,
	const std::string &name, GenderName gender)
	: Panel(game), charClass(charClass), name(name), gender(gender)
{
	this->backToGenderButton = []()
	{
		auto function = [](Game &game, const CharacterClass &charClass,
			const std::string &name)
		{
			std::unique_ptr<Panel> namePanel(new ChooseGenderPanel(
				game, charClass, name));
			game.setPanel(std::move(namePanel));
		};
		return Button<Game&, const CharacterClass&, const std::string&>(function);
	}();

	this->acceptButton = []()
	{
		auto function = [](Game &game, const CharacterClass &charClass,
			const std::string &name, GenderName gender, int raceID)
		{
			std::unique_ptr<Panel> attributesPanel(new ChooseAttributesPanel(
				game, charClass, name, gender, raceID));
			game.setPanel(std::move(attributesPanel));
		};
		return Button<Game&, const CharacterClass&,
			const std::string&, GenderName, int>(function);
	}();

	// @todo: maybe allocate std::unique_ptr<std::function> for unravelling the map?
	// When done, set to null and push initial parchment sub-panel?

	// Push the initial text sub-panel.
	std::unique_ptr<Panel> textSubPanel = [&game, &charClass, &name]()
	{
		const Int2 center((Renderer::ORIGINAL_WIDTH / 2) - 1, 98);
		const Color color(48, 12, 12);

		const std::string text = [&game, &charClass, &name]()
		{
			std::string segment = game.getMiscAssets().getAExeStrings().get(
				ExeStringKey::ChooseRace);
			segment = String::replace(segment, '\r', '\n');

			// Replace first "%s" with player name.
			size_t index = segment.find("%s");
			segment.replace(index, 2, name);

			// Replace second "%s" with character class.
			index = segment.find("%s");
			segment.replace(index, 2, charClass.getName());

			return segment;
		}();

		const int lineSpacing = 1;

		const RichTextString richText(
			text,
			FontName::A,
			color,
			TextAlignment::Center,
			lineSpacing,
			game.getFontManager());

		Texture texture(Texture::generate(
			Texture::PatternType::Parchment, 240, 60, game.getTextureManager(),
			game.getRenderer()));

		const Int2 textureCenter(
			(Renderer::ORIGINAL_WIDTH / 2) - 1,
			(Renderer::ORIGINAL_HEIGHT / 2) - 1);

		// The sub-panel does nothing after it's removed.
		auto function = [](Game &game) {};

		return std::unique_ptr<Panel>(new TextSubPanel(
			game, center, richText, function, std::move(texture), textureCenter));
	}();

	game.pushSubPanel(std::move(textSubPanel));
}

ChooseRacePanel::~ChooseRacePanel()
{

}

int ChooseRacePanel::getProvinceMaskID(const Int2 &position) const
{
	const auto &worldMapMasks = this->getGame().getMiscAssets().getWorldMapMasks();
	const int maskCount = static_cast<int>(worldMapMasks.size());
	for (int maskID = 0; maskID < maskCount; maskID++)
	{
		// Ignore the center province and the "Exit" button.
		const int lastProvinceID = 8;
		const int exitButtonID = 9;
		if ((maskID == lastProvinceID) || (maskID == exitButtonID))
		{
			continue;
		}

		const WorldMapMask &mapMask = worldMapMasks.at(maskID);
		const Rect &maskRect = mapMask.getRect();

		if (maskRect.contains(position))
		{
			// See if the pixel is set in the bitmask.
			const bool success = mapMask.get(position.x, position.y);

			if (success)
			{
				// Return the mask's ID.
				return maskID;
			}
		}
	}

	// No province mask found at the given location.
	return ChooseRacePanel::NO_ID;
}

std::pair<SDL_Texture*, CursorAlignment> ChooseRacePanel::getCurrentCursor() const
{
	auto &textureManager = this->getGame().getTextureManager();
	const auto &texture = textureManager.getTexture(
		TextureFile::fromName(TextureName::SwordCursor),
		PaletteFile::fromName(PaletteName::Default));
	return std::make_pair(texture.get(), CursorAlignment::TopLeft);
}

void ChooseRacePanel::handleEvent(const SDL_Event &e)
{
	const auto &inputManager = this->getGame().getInputManager();
	bool escapePressed = inputManager.keyPressed(e, SDLK_ESCAPE);
	bool leftClick = inputManager.mouseButtonPressed(e, SDL_BUTTON_LEFT);
	bool rightClick = inputManager.mouseButtonPressed(e, SDL_BUTTON_RIGHT);

	// Interact with the map screen.
	if (escapePressed)
	{
		this->backToGenderButton.click(this->getGame(), this->charClass, this->name);
	}
	else if (leftClick)
	{
		const Int2 mousePosition = inputManager.getMousePosition();
		const Int2 originalPoint = this->getGame().getRenderer()
			.nativePointToOriginal(mousePosition);

		// Listen for clicks on the map, checking if the mouse is over a province mask.
		const int maskID = this->getProvinceMaskID(originalPoint);
		if (maskID != ChooseRacePanel::NO_ID)
		{
			// Choose the selected province.
			this->acceptButton.click(this->getGame(), this->charClass,
				this->name, this->gender, maskID);
		}
	}
}

void ChooseRacePanel::drawProvinceTooltip(int provinceID, Renderer &renderer)
{
	// Get the race name associated with the province.
	assert(provinceID != (ProvinceClickAreas.size() - 1));
	const std::string &raceName = this->getGame().getMiscAssets().getAExeStrings().getList(
		ExeStringKey::RaceNamesPlural).at(provinceID);

	const Texture tooltip(Panel::createTooltip(
		"Land of the " + raceName, FontName::D, this->getGame().getFontManager(), renderer));

	const auto &inputManager = this->getGame().getInputManager();
	const Int2 mousePosition = inputManager.getMousePosition();
	const Int2 originalPosition = renderer.nativePointToOriginal(mousePosition);
	const int mouseX = originalPosition.x;
	const int mouseY = originalPosition.y;
	const int x = ((mouseX + 8 + tooltip.getWidth()) < Renderer::ORIGINAL_WIDTH) ?
		(mouseX + 8) : (mouseX - tooltip.getWidth());
	const int y = ((mouseY + tooltip.getHeight()) < Renderer::ORIGINAL_HEIGHT) ?
		mouseY : (mouseY - tooltip.getHeight());

	renderer.drawOriginal(tooltip.get(), x, y);
}

void ChooseRacePanel::render(Renderer &renderer)
{
	// Clear full screen.
	renderer.clear();

	// Set palette.
	auto &textureManager = this->getGame().getTextureManager();
	textureManager.setPalette(PaletteFile::fromName(PaletteName::Default));

	// Draw background map.
	const auto &raceSelectMap = textureManager.getTexture(
		TextureFile::fromName(TextureName::RaceSelect),
		PaletteFile::fromName(PaletteName::BuiltIn));
	renderer.drawOriginal(raceSelectMap.get());

	// Arena just covers up the "exit" text at the bottom right.
	const auto &exitCover = textureManager.getTexture(
		TextureFile::fromName(TextureName::NoExit),
		TextureFile::fromName(TextureName::RaceSelect));
	renderer.drawOriginal(exitCover.get(),
		Renderer::ORIGINAL_WIDTH - exitCover.getWidth(),
		Renderer::ORIGINAL_HEIGHT - exitCover.getHeight());

	const auto &inputManager = this->getGame().getInputManager();
	const Int2 mousePosition = inputManager.getMousePosition();

	// Draw hovered province tooltip.
	const Int2 originalPoint = this->getGame().getRenderer()
		.nativePointToOriginal(mousePosition);

	// Draw tooltip if the mouse is in a province.
	const int maskID = this->getProvinceMaskID(originalPoint);
	if (maskID != ChooseRacePanel::NO_ID)
	{
		this->drawProvinceTooltip(maskID, renderer);
	}
}
<commit_msg>Removed obsolete assertion.<commit_after>#include <cassert>

#include "SDL.h"

#include "ChooseAttributesPanel.h"
#include "ChooseGenderPanel.h"
#include "ChooseRacePanel.h"
#include "CursorAlignment.h"
#include "RichTextString.h"
#include "TextAlignment.h"
#include "TextSubPanel.h"
#include "../Assets/ExeStrings.h"
#include "../Assets/MiscAssets.h"
#include "../Assets/WorldMapMask.h"
#include "../Game/Game.h"
#include "../Game/Options.h"
#include "../Math/Rect.h"
#include "../Media/Color.h"
#include "../Media/FontManager.h"
#include "../Media/FontName.h"
#include "../Media/PaletteFile.h"
#include "../Media/PaletteName.h"
#include "../Media/TextureFile.h"
#include "../Media/TextureManager.h"
#include "../Media/TextureName.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Surface.h"
#include "../Utilities/String.h"

const int ChooseRacePanel::NO_ID = -1;

ChooseRacePanel::ChooseRacePanel(Game &game, const CharacterClass &charClass,
	const std::string &name, GenderName gender)
	: Panel(game), charClass(charClass), name(name), gender(gender)
{
	this->backToGenderButton = []()
	{
		auto function = [](Game &game, const CharacterClass &charClass,
			const std::string &name)
		{
			std::unique_ptr<Panel> namePanel(new ChooseGenderPanel(
				game, charClass, name));
			game.setPanel(std::move(namePanel));
		};
		return Button<Game&, const CharacterClass&, const std::string&>(function);
	}();

	this->acceptButton = []()
	{
		auto function = [](Game &game, const CharacterClass &charClass,
			const std::string &name, GenderName gender, int raceID)
		{
			std::unique_ptr<Panel> attributesPanel(new ChooseAttributesPanel(
				game, charClass, name, gender, raceID));
			game.setPanel(std::move(attributesPanel));
		};
		return Button<Game&, const CharacterClass&,
			const std::string&, GenderName, int>(function);
	}();

	// @todo: maybe allocate std::unique_ptr<std::function> for unravelling the map?
	// When done, set to null and push initial parchment sub-panel?

	// Push the initial text sub-panel.
	std::unique_ptr<Panel> textSubPanel = [&game, &charClass, &name]()
	{
		const Int2 center((Renderer::ORIGINAL_WIDTH / 2) - 1, 98);
		const Color color(48, 12, 12);

		const std::string text = [&game, &charClass, &name]()
		{
			std::string segment = game.getMiscAssets().getAExeStrings().get(
				ExeStringKey::ChooseRace);
			segment = String::replace(segment, '\r', '\n');

			// Replace first "%s" with player name.
			size_t index = segment.find("%s");
			segment.replace(index, 2, name);

			// Replace second "%s" with character class.
			index = segment.find("%s");
			segment.replace(index, 2, charClass.getName());

			return segment;
		}();

		const int lineSpacing = 1;

		const RichTextString richText(
			text,
			FontName::A,
			color,
			TextAlignment::Center,
			lineSpacing,
			game.getFontManager());

		Texture texture(Texture::generate(
			Texture::PatternType::Parchment, 240, 60, game.getTextureManager(),
			game.getRenderer()));

		const Int2 textureCenter(
			(Renderer::ORIGINAL_WIDTH / 2) - 1,
			(Renderer::ORIGINAL_HEIGHT / 2) - 1);

		// The sub-panel does nothing after it's removed.
		auto function = [](Game &game) {};

		return std::unique_ptr<Panel>(new TextSubPanel(
			game, center, richText, function, std::move(texture), textureCenter));
	}();

	game.pushSubPanel(std::move(textSubPanel));
}

ChooseRacePanel::~ChooseRacePanel()
{

}

int ChooseRacePanel::getProvinceMaskID(const Int2 &position) const
{
	const auto &worldMapMasks = this->getGame().getMiscAssets().getWorldMapMasks();
	const int maskCount = static_cast<int>(worldMapMasks.size());
	for (int maskID = 0; maskID < maskCount; maskID++)
	{
		// Ignore the center province and the "Exit" button.
		const int lastProvinceID = 8;
		const int exitButtonID = 9;
		if ((maskID == lastProvinceID) || (maskID == exitButtonID))
		{
			continue;
		}

		const WorldMapMask &mapMask = worldMapMasks.at(maskID);
		const Rect &maskRect = mapMask.getRect();

		if (maskRect.contains(position))
		{
			// See if the pixel is set in the bitmask.
			const bool success = mapMask.get(position.x, position.y);

			if (success)
			{
				// Return the mask's ID.
				return maskID;
			}
		}
	}

	// No province mask found at the given location.
	return ChooseRacePanel::NO_ID;
}

std::pair<SDL_Texture*, CursorAlignment> ChooseRacePanel::getCurrentCursor() const
{
	auto &textureManager = this->getGame().getTextureManager();
	const auto &texture = textureManager.getTexture(
		TextureFile::fromName(TextureName::SwordCursor),
		PaletteFile::fromName(PaletteName::Default));
	return std::make_pair(texture.get(), CursorAlignment::TopLeft);
}

void ChooseRacePanel::handleEvent(const SDL_Event &e)
{
	const auto &inputManager = this->getGame().getInputManager();
	bool escapePressed = inputManager.keyPressed(e, SDLK_ESCAPE);
	bool leftClick = inputManager.mouseButtonPressed(e, SDL_BUTTON_LEFT);
	bool rightClick = inputManager.mouseButtonPressed(e, SDL_BUTTON_RIGHT);

	// Interact with the map screen.
	if (escapePressed)
	{
		this->backToGenderButton.click(this->getGame(), this->charClass, this->name);
	}
	else if (leftClick)
	{
		const Int2 mousePosition = inputManager.getMousePosition();
		const Int2 originalPoint = this->getGame().getRenderer()
			.nativePointToOriginal(mousePosition);

		// Listen for clicks on the map, checking if the mouse is over a province mask.
		const int maskID = this->getProvinceMaskID(originalPoint);
		if (maskID != ChooseRacePanel::NO_ID)
		{
			// Choose the selected province.
			this->acceptButton.click(this->getGame(), this->charClass,
				this->name, this->gender, maskID);
		}
	}
}

void ChooseRacePanel::drawProvinceTooltip(int provinceID, Renderer &renderer)
{
	// Get the race name associated with the province.
	const std::string &raceName = this->getGame().getMiscAssets().getAExeStrings().getList(
		ExeStringKey::RaceNamesPlural).at(provinceID);

	const Texture tooltip(Panel::createTooltip(
		"Land of the " + raceName, FontName::D, this->getGame().getFontManager(), renderer));

	const auto &inputManager = this->getGame().getInputManager();
	const Int2 mousePosition = inputManager.getMousePosition();
	const Int2 originalPosition = renderer.nativePointToOriginal(mousePosition);
	const int mouseX = originalPosition.x;
	const int mouseY = originalPosition.y;
	const int x = ((mouseX + 8 + tooltip.getWidth()) < Renderer::ORIGINAL_WIDTH) ?
		(mouseX + 8) : (mouseX - tooltip.getWidth());
	const int y = ((mouseY + tooltip.getHeight()) < Renderer::ORIGINAL_HEIGHT) ?
		mouseY : (mouseY - tooltip.getHeight());

	renderer.drawOriginal(tooltip.get(), x, y);
}

void ChooseRacePanel::render(Renderer &renderer)
{
	// Clear full screen.
	renderer.clear();

	// Set palette.
	auto &textureManager = this->getGame().getTextureManager();
	textureManager.setPalette(PaletteFile::fromName(PaletteName::Default));

	// Draw background map.
	const auto &raceSelectMap = textureManager.getTexture(
		TextureFile::fromName(TextureName::RaceSelect),
		PaletteFile::fromName(PaletteName::BuiltIn));
	renderer.drawOriginal(raceSelectMap.get());

	// Arena just covers up the "exit" text at the bottom right.
	const auto &exitCover = textureManager.getTexture(
		TextureFile::fromName(TextureName::NoExit),
		TextureFile::fromName(TextureName::RaceSelect));
	renderer.drawOriginal(exitCover.get(),
		Renderer::ORIGINAL_WIDTH - exitCover.getWidth(),
		Renderer::ORIGINAL_HEIGHT - exitCover.getHeight());

	const auto &inputManager = this->getGame().getInputManager();
	const Int2 mousePosition = inputManager.getMousePosition();

	// Draw hovered province tooltip.
	const Int2 originalPoint = this->getGame().getRenderer()
		.nativePointToOriginal(mousePosition);

	// Draw tooltip if the mouse is in a province.
	const int maskID = this->getProvinceMaskID(originalPoint);
	if (maskID != ChooseRacePanel::NO_ID)
	{
		this->drawProvinceTooltip(maskID, renderer);
	}
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <climits>
#include <iostream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#define rep(i, n) for (size_t i = 0; i < (size_t)(n); i++)
#define rep2(i, s, n) for (size_t i = (s); i < (size_t)(n); i++)
#define rep3(i, s, n) for (ll i = (s); i >= (ll)(n); i--)

using namespace std;
using ll = long long;

vector<int> dx = {0, 1, 0, -1};
vector<int> dy = {1, 0, -1, 0};

template <typename T>
void show(T a) {
  for (auto i : a) {
    cout << i << " ";
  }
  cout << endl;
}
template <typename T>
void showmatrix(T a) {
  for (auto j : a) {
    for (auto i : j) {
      cout << i;
    }
    cout << endl;
  }
  cout << endl;
}
void check(int i = 0) { cout << "checkpoint:[" << i << "]" << endl; }

int main(int argc, char* argv[]) {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  ll n;
  cin >> n;

  ll res = 0;
  {
    int count = 9;
    ll m = n;
    m = m / 100;
    while (m > 0) {
      res += count;
      m = m / 100;
      count *= 10;
    }
  }

  auto isdoubled = [](string& s) -> bool {
    ll len = s.size() / 2;
    rep(i, len) {
      if (s[i] != s[i + len]) return false;
    }
    return true;
  };

  string num = to_string(n);
  if (num.size() % 2 == 0) {
    res = 0;
    string before = num.substr(0, num.size() / 2);
    string after = num.substr(num.size() / 2, num.size());
    res = stoll(before);
    if (after < before) {
      res--;
    }
  }

  /*
  2:9
  4:90
  6:900
  */
  // ll m = n;
  // ll res = 0;

  // m = n;
  // ll digitcount = 0;
  // while (m > 0) {
  //   digitcount++;
  //   m /= 10;
  // }

  // if (digitcount % 2 == 0) {
  //   string num = to_string(n);
  //   ll tmp = num[num.size() / 2 - 1] - '0';
  //   ll zerocount = 10;
  //   rep3(i, num.size() / 2 - 2, 0) {
  //     if (i == 0) {
  //       tmp += (num[i] - '0') * zerocount;
  //     } else {
  //       tmp += (num[i] - '0' + 1) * zerocount;
  //     }
  //     zerocount *= 10;
  //   }
  //   string before = num.substr(0, num.size() / 2);
  //   string after = num.substr(num.size() / 2, num.size());
  //   if (after < before) {
  //     res += tmp - 1;
  //   } else {
  //     res += tmp;
  //   }
  //   // cout << tmp << endl;
  // } else {
  //   int count = 9;
  //   m = n;
  //   m = m / 100;
  //   res = 0;
  //   while (m > 0) {
  //     res += count;
  //     m = m / 100;
  //     count *= 10;
  //   }
  // }
  cout << res << endl;
}
<commit_msg>delete comment<commit_after>#include <algorithm>
#include <climits>
#include <iostream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#define rep(i, n) for (size_t i = 0; i < (size_t)(n); i++)
#define rep2(i, s, n) for (size_t i = (s); i < (size_t)(n); i++)
#define rep3(i, s, n) for (ll i = (s); i >= (ll)(n); i--)

using namespace std;
using ll = long long;

vector<int> dx = {0, 1, 0, -1};
vector<int> dy = {1, 0, -1, 0};

template <typename T>
void show(T a) {
  for (auto i : a) {
    cout << i << " ";
  }
  cout << endl;
}
template <typename T>
void showmatrix(T a) {
  for (auto j : a) {
    for (auto i : j) {
      cout << i;
    }
    cout << endl;
  }
  cout << endl;
}
void check(int i = 0) { cout << "checkpoint:[" << i << "]" << endl; }

int main(int argc, char* argv[]) {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  ll n;
  cin >> n;

  ll res = 0;
  {
    int count = 9;
    ll m = n;
    m = m / 100;
    while (m > 0) {
      res += count;
      m = m / 100;
      count *= 10;
    }
  }

  string num = to_string(n);
  if (num.size() % 2 == 0) {
    res = 0;
    string before = num.substr(0, num.size() / 2);
    string after = num.substr(num.size() / 2, num.size());
    res = stoll(before);
    if (after < before) {
      res--;
    }
  }

  /*
  2:9
  4:90
  6:900
  */
  //
  cout << res << endl;
}
<|endoftext|>


<commit_before>#include "catalogue_description.hh"

#include <sstream>

double parse_double(const std::string & in)
{
    std::stringstream s{in};
    double d;
    s >> d;
    return d;
}

double parse_sign(const std::string & in)
{
    if ("-" == in)
        return -1;

    return +1;
}

const Star parse_line_into_star(const CatalogParsingDescription & description, const std::string & line)
{
    ln_equ_posn pos{};
    std::string name;
    double vmag{};

    double dec_sign{1};

    for (auto const & desc : description.descriptions)
    {
        std::string part{line.substr(desc.start - 1, desc.len)};

#define CF CatalogParsingDescription::Field
        switch (desc.field)
        {
            case CF::Name:
                name = part;
                break;
            case CF::RAh:
                pos.ra += 15.0 * parse_double(part);
                break;
            case CF::RAm:
                pos.ra += parse_double(part) / 4.;
                break;
            case CF::RAs:
                pos.ra += parse_double(part) / 240.;
                break;
            case CF::DE_:
                dec_sign = parse_sign(part);
                break;
            case CF::DEd:
                pos.dec += parse_double(part);
                break;
            case CF::DEm:
                pos.dec += parse_double(part) / 60.;
                break;
            case CF::DEs:
                pos.dec += parse_double(part) / 3600.;
                break;
            case CF::Vmag:
                vmag = parse_double(part);
                break;
        }
#undef CF
    }
    pos.dec *= dec_sign;
    return Star(name, pos, vmag);
}

/*
    Bright Star Catalogue

    5- 14  A10    ---     Name     Name, generally Bayer and/or Flamsteed name
    76- 77  I2     h       RAh      ?Hours RA, equinox J2000, epoch 2000.0 (1)
    78- 79  I2     min     RAm      ?Minutes RA, equinox J2000, epoch 2000.0 (1)
    80- 83  F4.1   s       RAs      ?Seconds RA, equinox J2000, epoch 2000.0 (1)
        84  A1     ---     DE-      ?Sign Dec, equinox J2000, epoch 2000.0 (1)
    85- 86  I2     deg     DEd      ?Degrees Dec, equinox J2000, epoch 2000.0 (1)
    87- 88  I2     arcmin  DEm      ?Minutes Dec, equinox J2000, epoch 2000.0 (1)
    89- 90  I2     arcsec  DEs      ?Seconds Dec, equinox J2000, epoch 2000.0 (1)
   103-107  F5.2   mag     Vmag     ?Visual magnitude
*/
CatalogParsingDescription descriptions =
{ {
        { 5, 10, CatalogParsingDescription::Field::Name },
        { 76, 2, CatalogParsingDescription::Field::RAh },
        { 78, 2, CatalogParsingDescription::Field::RAm },
        { 80, 4, CatalogParsingDescription::Field::RAs },
        { 84, 1, CatalogParsingDescription::Field::DE_ },
        { 85, 2, CatalogParsingDescription::Field::DEd },
        { 87, 2, CatalogParsingDescription::Field::DEm },
        { 89, 2, CatalogParsingDescription::Field::DEs },
        { 103, 5, CatalogParsingDescription::Field::Vmag },
} };
<commit_msg>don't die if you can't parse catalog line<commit_after>#include "catalogue_description.hh"

#include <sstream>

double parse_double(const std::string & in)
{
    std::stringstream s{in};
    double d;
    s >> d;
    return d;
}

double parse_sign(const std::string & in)
{
    if ("-" == in)
        return -1;

    return +1;
}

const Star parse_line_into_star(const CatalogParsingDescription & description, const std::string & line)
{
    ln_equ_posn pos{};
    std::string name;
    double vmag{};

    double dec_sign{1};

    for (auto const & desc : description.descriptions)
    {
        try
        {
            std::string part{line.substr(desc.start - 1, desc.len)};

#define CF CatalogParsingDescription::Field
            switch (desc.field)
            {
                case CF::Name:
                    name = part;
                    break;
                case CF::RAh:
                    pos.ra += 15.0 * parse_double(part);
                    break;
                case CF::RAm:
                    pos.ra += parse_double(part) / 4.;
                    break;
                case CF::RAs:
                    pos.ra += parse_double(part) / 240.;
                    break;
                case CF::DE_:
                    dec_sign = parse_sign(part);
                    break;
                case CF::DEd:
                    pos.dec += parse_double(part);
                    break;
                case CF::DEm:
                    pos.dec += parse_double(part) / 60.;
                    break;
                case CF::DEs:
                    pos.dec += parse_double(part) / 3600.;
                    break;
                case CF::Vmag:
                    vmag = parse_double(part);
                    break;
            }
#undef CF
        }
        catch (const std::out_of_range &)
        {
            throw std::runtime_error(""); // skipping the line
        }
    }
    pos.dec *= dec_sign;
    return Star(name, pos, vmag);
}

/*
    Bright Star Catalogue

    5- 14  A10    ---     Name     Name, generally Bayer and/or Flamsteed name
    76- 77  I2     h       RAh      ?Hours RA, equinox J2000, epoch 2000.0 (1)
    78- 79  I2     min     RAm      ?Minutes RA, equinox J2000, epoch 2000.0 (1)
    80- 83  F4.1   s       RAs      ?Seconds RA, equinox J2000, epoch 2000.0 (1)
        84  A1     ---     DE-      ?Sign Dec, equinox J2000, epoch 2000.0 (1)
    85- 86  I2     deg     DEd      ?Degrees Dec, equinox J2000, epoch 2000.0 (1)
    87- 88  I2     arcmin  DEm      ?Minutes Dec, equinox J2000, epoch 2000.0 (1)
    89- 90  I2     arcsec  DEs      ?Seconds Dec, equinox J2000, epoch 2000.0 (1)
   103-107  F5.2   mag     Vmag     ?Visual magnitude
*/
CatalogParsingDescription descriptions =
{ {
        { 5, 10, CatalogParsingDescription::Field::Name },
        { 76, 2, CatalogParsingDescription::Field::RAh },
        { 78, 2, CatalogParsingDescription::Field::RAm },
        { 80, 4, CatalogParsingDescription::Field::RAs },
        { 84, 1, CatalogParsingDescription::Field::DE_ },
        { 85, 2, CatalogParsingDescription::Field::DEd },
        { 87, 2, CatalogParsingDescription::Field::DEm },
        { 89, 2, CatalogParsingDescription::Field::DEs },
        { 103, 5, CatalogParsingDescription::Field::Vmag },
} };
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tbinsert.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: mba $ $Date: 2001-06-11 08:29:22 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// System - Includes -----------------------------------------------------

#include <string> // HACK: prevent conflict between STLPORT and Workshop headers

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------

#include <tools/shl.hxx>
#include <svtools/intitem.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/dispatch.hxx>

#include "tbinsert.hxx"
#include "tbinsert.hrc"
#include "global.hxx"
#include "scmod.hxx"
#include "scresid.hxx"
#include "sc.hrc"

// -----------------------------------------------------------------------

SFX_IMPL_TOOLBOX_CONTROL( ScTbxInsertCtrl, SfxUInt16Item);

//------------------------------------------------------------------
//
//  ToolBox - Controller
//
//------------------------------------------------------------------

ScTbxInsertCtrl::ScTbxInsertCtrl( USHORT nId, ToolBox& rTbx, SfxBindings& rBind ) :
        SfxToolBoxControl( nId, rTbx, rBind ),
        nLastSlotId(0)
{
}

__EXPORT ScTbxInsertCtrl::~ScTbxInsertCtrl()
{
}

void __EXPORT ScTbxInsertCtrl::StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pState )
{
    GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );

    if( eState == SFX_ITEM_AVAILABLE )
    {
        const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );
        if(pItem)
        {
            nLastSlotId = pItem->GetValue();
            USHORT nImageId = nLastSlotId ? nLastSlotId : GetId();
            Image aImage = GetBindings().GetImageManager()->GetImage( nImageId, SC_MOD() );
            GetToolBox().SetItemImage(GetId(), aImage);
        }
    }
}

SfxPopupWindow* __EXPORT ScTbxInsertCtrl::CreatePopupWindow()
{
    USHORT nWinResId, nTbxResId;
    USHORT nSlotId = GetId();
    if (nSlotId == SID_TBXCTL_INSERT)
    {
        nWinResId = RID_TBXCTL_INSERT;
        nTbxResId = RID_TOOLBOX_INSERT;
    }
    else if (nSlotId == SID_TBXCTL_INSCELLS)
    {
        nWinResId = RID_TBXCTL_INSCELLS;
        nTbxResId = RID_TOOLBOX_INSCELLS;
    }
    else /* SID_TBXCTL_INSOBJ */
    {
        nWinResId = RID_TBXCTL_INSOBJ;
        nTbxResId = RID_TOOLBOX_INSOBJ;
    }

    WindowAlign eNewAlign = ( GetToolBox().IsHorizontal() ) ? WINDOWALIGN_LEFT : WINDOWALIGN_TOP;
    ScTbxInsertPopup *pWin = new ScTbxInsertPopup( nSlotId, eNewAlign,
                                    ScResId(nWinResId), ScResId(nTbxResId), GetBindings() );
    pWin->StartPopupMode(&GetToolBox(), TRUE);
    pWin->StartSelection();
    pWin->Show();
    return pWin;
}

SfxPopupWindowType __EXPORT ScTbxInsertCtrl::GetPopupWindowType() const
{
    return nLastSlotId ? SFX_POPUPWINDOW_ONTIMEOUT : SFX_POPUPWINDOW_ONCLICK;
}

void __EXPORT ScTbxInsertCtrl::Select( BOOL bMod1 )
{
    if (nLastSlotId)
        GetBindings().GetDispatcher()->Execute(nLastSlotId);
}

//------------------------------------------------------------------
//
//  Popup - Window
//
//------------------------------------------------------------------

ScTbxInsertPopup::ScTbxInsertPopup( USHORT nId, WindowAlign eNewAlign,
                        const ResId& rRIdWin, const ResId& rRIdTbx,
                        SfxBindings& rBindings ) :
                SfxPopupWindow  ( nId, rRIdWin, rBindings),
                aTbx            ( this, GetBindings(), rRIdTbx ),
                aRIdWinTemp(rRIdWin),
                aRIdTbxTemp(rRIdTbx)
{
    aTbx.UseDefault();
    FreeResource();

    aTbx.GetToolBox().SetAlign( eNewAlign );
    if (eNewAlign == WINDOWALIGN_LEFT || eNewAlign == WINDOWALIGN_RIGHT)
        SetText( EMPTY_STRING );

    Size aSize = aTbx.CalcWindowSizePixel();
    aTbx.SetPosSizePixel( Point(), aSize );
    SetOutputSizePixel( aSize );
    aTbx.GetToolBox().SetSelectHdl( LINK(this, ScTbxInsertPopup, TbxSelectHdl));
    aTbxClickHdl = aTbx.GetToolBox().GetClickHdl();
    aTbx.GetToolBox().SetClickHdl(  LINK(this, ScTbxInsertPopup, TbxClickHdl));
}

ScTbxInsertPopup::~ScTbxInsertPopup()
{
}

SfxPopupWindow* __EXPORT ScTbxInsertPopup::Clone() const
{
    return new ScTbxInsertPopup( GetId(), aTbx.GetToolBox().GetAlign(),
                                    aRIdWinTemp, aRIdTbxTemp,
                                    (SfxBindings&) GetBindings() );
}

void ScTbxInsertPopup::StartSelection()
{
    aTbx.GetToolBox().StartSelection();
}

IMPL_LINK(ScTbxInsertPopup, TbxSelectHdl, ToolBox*, pBox)
{
    EndPopupMode();

    USHORT nLastSlotId = pBox->GetCurItemId();
    SfxUInt16Item aItem( GetId(), nLastSlotId );
    SfxDispatcher* pDisp = GetBindings().GetDispatcher();
    pDisp->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
    pDisp->Execute( nLastSlotId, SFX_CALLMODE_ASYNCHRON );
    return 0;
}

IMPL_LINK(ScTbxInsertPopup, TbxClickHdl, ToolBox*, pBox)
{
    USHORT nLastSlotId = pBox->GetCurItemId();
    SfxUInt16Item aItem( GetId(), nLastSlotId );
    GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
    if(aTbxClickHdl.IsSet())
        aTbxClickHdl.Call(pBox);
    return 0;
}

void __EXPORT ScTbxInsertPopup::PopupModeEnd()
{
    aTbx.GetToolBox().EndSelection();
    SfxPopupWindow::PopupModeEnd();
}

<commit_msg>#99643# use high contrast image if necessary<commit_after>/*************************************************************************
 *
 *  $RCSfile: tbinsert.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: nn $ $Date: 2002-05-29 18:10:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// System - Includes -----------------------------------------------------

#include <string> // HACK: prevent conflict between STLPORT and Workshop headers

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------

#include <tools/shl.hxx>
#include <svtools/intitem.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/dispatch.hxx>

#include "tbinsert.hxx"
#include "tbinsert.hrc"
#include "global.hxx"
#include "scmod.hxx"
#include "scresid.hxx"
#include "sc.hrc"

// -----------------------------------------------------------------------

SFX_IMPL_TOOLBOX_CONTROL( ScTbxInsertCtrl, SfxUInt16Item);

//------------------------------------------------------------------
//
//  ToolBox - Controller
//
//------------------------------------------------------------------

ScTbxInsertCtrl::ScTbxInsertCtrl( USHORT nId, ToolBox& rTbx, SfxBindings& rBind ) :
        SfxToolBoxControl( nId, rTbx, rBind ),
        nLastSlotId(0)
{
}

__EXPORT ScTbxInsertCtrl::~ScTbxInsertCtrl()
{
}

void __EXPORT ScTbxInsertCtrl::StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pState )
{
    GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );

    if( eState == SFX_ITEM_AVAILABLE )
    {
        const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );
        if(pItem)
        {
            nLastSlotId = pItem->GetValue();
            USHORT nImageId = nLastSlotId ? nLastSlotId : GetId();
            Image aImage = GetBindings().GetImageManager()->GetImage( nImageId,
                           GetToolBox().GetDisplayBackground().GetColor().IsDark(),
                           SC_MOD() );
            GetToolBox().SetItemImage(GetId(), aImage);
        }
    }
}

SfxPopupWindow* __EXPORT ScTbxInsertCtrl::CreatePopupWindow()
{
    USHORT nWinResId, nTbxResId;
    USHORT nSlotId = GetId();
    if (nSlotId == SID_TBXCTL_INSERT)
    {
        nWinResId = RID_TBXCTL_INSERT;
        nTbxResId = RID_TOOLBOX_INSERT;
    }
    else if (nSlotId == SID_TBXCTL_INSCELLS)
    {
        nWinResId = RID_TBXCTL_INSCELLS;
        nTbxResId = RID_TOOLBOX_INSCELLS;
    }
    else /* SID_TBXCTL_INSOBJ */
    {
        nWinResId = RID_TBXCTL_INSOBJ;
        nTbxResId = RID_TOOLBOX_INSOBJ;
    }

    WindowAlign eNewAlign = ( GetToolBox().IsHorizontal() ) ? WINDOWALIGN_LEFT : WINDOWALIGN_TOP;
    ScTbxInsertPopup *pWin = new ScTbxInsertPopup( nSlotId, eNewAlign,
                                    ScResId(nWinResId), ScResId(nTbxResId), GetBindings() );
    pWin->StartPopupMode(&GetToolBox(), TRUE);
    pWin->StartSelection();
    pWin->Show();
    return pWin;
}

SfxPopupWindowType __EXPORT ScTbxInsertCtrl::GetPopupWindowType() const
{
    return nLastSlotId ? SFX_POPUPWINDOW_ONTIMEOUT : SFX_POPUPWINDOW_ONCLICK;
}

void __EXPORT ScTbxInsertCtrl::Select( BOOL bMod1 )
{
    if (nLastSlotId)
        GetBindings().GetDispatcher()->Execute(nLastSlotId);
}

//------------------------------------------------------------------
//
//  Popup - Window
//
//------------------------------------------------------------------

ScTbxInsertPopup::ScTbxInsertPopup( USHORT nId, WindowAlign eNewAlign,
                        const ResId& rRIdWin, const ResId& rRIdTbx,
                        SfxBindings& rBindings ) :
                SfxPopupWindow  ( nId, rRIdWin, rBindings),
                aTbx            ( this, GetBindings(), rRIdTbx ),
                aRIdWinTemp(rRIdWin),
                aRIdTbxTemp(rRIdTbx)
{
    aTbx.UseDefault();
    FreeResource();

    aTbx.GetToolBox().SetAlign( eNewAlign );
    if (eNewAlign == WINDOWALIGN_LEFT || eNewAlign == WINDOWALIGN_RIGHT)
        SetText( EMPTY_STRING );

    Size aSize = aTbx.CalcWindowSizePixel();
    aTbx.SetPosSizePixel( Point(), aSize );
    SetOutputSizePixel( aSize );
    aTbx.GetToolBox().SetSelectHdl( LINK(this, ScTbxInsertPopup, TbxSelectHdl));
    aTbxClickHdl = aTbx.GetToolBox().GetClickHdl();
    aTbx.GetToolBox().SetClickHdl(  LINK(this, ScTbxInsertPopup, TbxClickHdl));
}

ScTbxInsertPopup::~ScTbxInsertPopup()
{
}

SfxPopupWindow* __EXPORT ScTbxInsertPopup::Clone() const
{
    return new ScTbxInsertPopup( GetId(), aTbx.GetToolBox().GetAlign(),
                                    aRIdWinTemp, aRIdTbxTemp,
                                    (SfxBindings&) GetBindings() );
}

void ScTbxInsertPopup::StartSelection()
{
    aTbx.GetToolBox().StartSelection();
}

IMPL_LINK(ScTbxInsertPopup, TbxSelectHdl, ToolBox*, pBox)
{
    EndPopupMode();

    USHORT nLastSlotId = pBox->GetCurItemId();
    SfxUInt16Item aItem( GetId(), nLastSlotId );
    SfxDispatcher* pDisp = GetBindings().GetDispatcher();
    pDisp->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
    pDisp->Execute( nLastSlotId, SFX_CALLMODE_ASYNCHRON );
    return 0;
}

IMPL_LINK(ScTbxInsertPopup, TbxClickHdl, ToolBox*, pBox)
{
    USHORT nLastSlotId = pBox->GetCurItemId();
    SfxUInt16Item aItem( GetId(), nLastSlotId );
    GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
    if(aTbxClickHdl.IsSet())
        aTbxClickHdl.Call(pBox);
    return 0;
}

void __EXPORT ScTbxInsertPopup::PopupModeEnd()
{
    aTbx.GetToolBox().EndSelection();
    SfxPopupWindow::PopupModeEnd();
}

<|endoftext|>


<commit_before>#include "stdafx.h"

#include <string>
#include <map>
#include <vector>
#include "../Application.h"
#include "../ModuleScripting.h"
#include "../ModuleInput.h"
#include "../ModuleWindow.h"
#include "../ComponentTransform.h"
#include "../GameObject.h"
#include "../Component.h"
#include "../ComponentScript.h"
#include "../ComponentRectTransform.h"
#include "../SDL/include/SDL_scancode.h"
#include "../Globals.h"
#include "../ComponentUiButton.h"
#include "../ComponentCanvas.h"

namespace MapSelectUI
{

	GameObject* map_mainportrait = nullptr;
	GameObject* map_name = nullptr;
	GameObject* player1r_vote = nullptr;
	GameObject* player2r_vote = nullptr;
	GameObject* player1b_vote = nullptr;
	GameObject* player2b_vote = nullptr;
	GameObject* right_arrow = nullptr;
	GameObject* left_arrow = nullptr;

	ComponentUiButton* c_map_mainportrait = nullptr;
	ComponentUiButton* c_map_name = nullptr;
	ComponentUiButton* c_player1r_vote = nullptr;
	ComponentUiButton* c_player2r_vote = nullptr;
	ComponentUiButton* c_player1b_vote = nullptr;
	ComponentUiButton* c_player2b_vote = nullptr;
	ComponentUiButton* c_right_arrow = nullptr;
	ComponentUiButton* c_left_arrow = nullptr;

	bool a_pressed = false;
	bool b_pressed = false;
	bool dpad_left_pressed = false;
	bool dpad_right_pressed = false;

	int current_map = 1;
	// 1 -   , 2 -   , 3 -   ,

	void MapSelectUI_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos)
	{
		public_gos->insert(std::pair<const char*, GameObject*>("MapPortrait", map_mainportrait));
		public_gos->insert(std::pair<const char*, GameObject*>("MapName", map_mainportrait));
		public_gos->insert(std::pair<const char*, GameObject*>("P1-Red Vote", player1r_vote));
		public_gos->insert(std::pair<const char*, GameObject*>("P2-Red Vote", player2r_vote));
		public_gos->insert(std::pair<const char*, GameObject*>("P1-Blue Vote", player1b_vote));
		public_gos->insert(std::pair<const char*, GameObject*>("P2-Blue Vote", player2b_vote));
		public_gos->insert(std::pair<const char*, GameObject*>("R-Arrow", right_arrow));
		public_gos->insert(std::pair<const char*, GameObject*>("L-Arrow", left_arrow));
	}

	void MapSelectUI_UpdatePublics(GameObject* game_object)
	{
		ComponentScript* test_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);

		map_mainportrait = test_script->public_gos.at("MapPortrait");
		map_name = test_script->public_gos.at("MapName");
		player1r_vote = test_script->public_gos.at("P1-Red Vote");
		player2r_vote = test_script->public_gos.at("P2-Red Vote");
		player1b_vote = test_script->public_gos.at("P1-Blue Vote");
		player2b_vote = test_script->public_gos.at("P2-Blue Vote");
		right_arrow = test_script->public_gos.at("R-Arrow");
		left_arrow = test_script->public_gos.at("L-Arrow");

		c_map_mainportrait = (ComponentUiButton*)map_mainportrait->GetComponent(C_UI_BUTTON);
		c_map_name = (ComponentUiButton*)map_name->GetComponent(C_UI_BUTTON);
		c_player1r_vote = (ComponentUiButton*)player1r_vote->GetComponent(C_UI_BUTTON);
		c_player2r_vote = (ComponentUiButton*)player2r_vote->GetComponent(C_UI_BUTTON);
		c_player1b_vote = (ComponentUiButton*)player1b_vote->GetComponent(C_UI_BUTTON);
		c_player2b_vote = (ComponentUiButton*)player2b_vote->GetComponent(C_UI_BUTTON);
		c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON);
		c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON);
	}

	void MapSelectUI_ActualizePublics(GameObject* game_object)
	{
		ComponentScript* this_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);

		this_script->public_gos.at("MapPortrait") = map_mainportrait;
		this_script->public_gos.at("MapName") = map_name;
		this_script->public_gos.at("P1-Red Vote") = player1r_vote;
		this_script->public_gos.at("P2-Red Vote") = player2r_vote;
		this_script->public_gos.at("P1-Blue Vote") = player1b_vote;
		this_script->public_gos.at("P2-Blue Vote") = player2b_vote;
		this_script->public_gos.at("R-Arrow") = right_arrow;
		this_script->public_gos.at("L-Arrow") = left_arrow;

		c_map_mainportrait = (ComponentUiButton*)map_mainportrait->GetComponent(C_UI_BUTTON);
		c_map_name = (ComponentUiButton*)map_name->GetComponent(C_UI_BUTTON);
		c_player1r_vote = (ComponentUiButton*)player1r_vote->GetComponent(C_UI_BUTTON);
		c_player2r_vote = (ComponentUiButton*)player2r_vote->GetComponent(C_UI_BUTTON);
		c_player1b_vote = (ComponentUiButton*)player1b_vote->GetComponent(C_UI_BUTTON);
		c_player2b_vote = (ComponentUiButton*)player2b_vote->GetComponent(C_UI_BUTTON);
		c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON);
		c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON);
	}

	void MapSelectUI_UpdatePublics(GameObject* game_object);

	void MapSelectUI_Start(GameObject* game_object)
	{
	}

	void MapSelectUI_Update(GameObject* game_object)
	{
		for (int playerID = 0; playerID < 4; playerID++)
		{
			if (a_pressed == false)
			{
				if (App->input->GetJoystickButton(playerID, JOY_BUTTON::A) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN)
				{

				}
			}

			if (b_pressed == false)
			{
				if (App->input->GetJoystickButton(playerID, JOY_BUTTON::B) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN)
				{

				}
			}

			if (dpad_left_pressed == false || dpad_right_pressed == false)
			{
				if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_LEFT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_DOWN)
				{
					if (current_map <= 1)
						current_map = 3;
					else
						current_map--;
					if(!dpad_left_pressed)
						c_map_mainportrait->OnPressId(current_map-2);
					dpad_left_pressed = true;
				}

				if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_RIGHT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_DOWN)
				{
					if (current_map >= 3)
						current_map = 1;
					else
						current_map++;
					if (!dpad_right_pressed)
						c_map_mainportrait->OnPressId(current_map-2);
					dpad_right_pressed = true;
				}
			}
		}
		dpad_left_pressed = false;
		dpad_right_pressed = false;
	}
}<commit_msg>Map Select UI Progress<commit_after>#include "stdafx.h"

#include <string>
#include <map>
#include <vector>
#include "../Application.h"
#include "../ModuleScripting.h"
#include "../ModuleInput.h"
#include "../ModuleWindow.h"
#include "../ComponentTransform.h"
#include "../GameObject.h"
#include "../Component.h"
#include "../ComponentScript.h"
#include "../ComponentRectTransform.h"
#include "../SDL/include/SDL_scancode.h"
#include "../Globals.h"
#include "../ComponentUiButton.h"
#include "../ComponentCanvas.h"

namespace MapSelectUI
{

	GameObject* map_mainportrait = nullptr;
	GameObject* map_name = nullptr;
	GameObject* players_vote[4];
	GameObject* right_arrow = nullptr;
	GameObject* left_arrow = nullptr;

	ComponentUiButton* c_map_mainportrait = nullptr;
	ComponentUiButton* c_map_name = nullptr;
	ComponentUiButton* c_players_vote[4];
	// 0 - P1 Red, 1 - P2 Red, 2 - P1 Blue, 2 - P2 Blue,
	ComponentUiButton* c_right_arrow = nullptr;
	ComponentUiButton* c_left_arrow = nullptr;

	bool players_ready[4] = { false };

	bool a_pressed = false;
	bool b_pressed = false;
	bool dpad_left_pressed = false;
	bool dpad_right_pressed = false;

	int current_map = 1;
	// 1 -   , 2 -   , 3 -   ,

	void MapSelectUI_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos)
	{
		public_gos->insert(std::pair<const char*, GameObject*>("MapPortrait", map_mainportrait));
		public_gos->insert(std::pair<const char*, GameObject*>("MapName", map_mainportrait));
		public_gos->insert(std::pair<const char*, GameObject*>("P1-Red Vote", players_vote[0]));
		public_gos->insert(std::pair<const char*, GameObject*>("P2-Red Vote", players_vote[1]));
		public_gos->insert(std::pair<const char*, GameObject*>("P1-Blue Vote", players_vote[2]));
		public_gos->insert(std::pair<const char*, GameObject*>("P2-Blue Vote", players_vote[3]));
		public_gos->insert(std::pair<const char*, GameObject*>("R-Arrow", right_arrow));
		public_gos->insert(std::pair<const char*, GameObject*>("L-Arrow", left_arrow));
	}

	void MapSelectUI_UpdatePublics(GameObject* game_object)
	{
		ComponentScript* test_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);

		map_mainportrait = test_script->public_gos.at("MapPortrait");
		map_name = test_script->public_gos.at("MapName");
		players_vote[0] = test_script->public_gos.at("P1-Red Vote");
		players_vote[1] = test_script->public_gos.at("P2-Red Vote");
		players_vote[2] = test_script->public_gos.at("P1-Blue Vote");
		players_vote[3] = test_script->public_gos.at("P2-Blue Vote");
		right_arrow = test_script->public_gos.at("R-Arrow");
		left_arrow = test_script->public_gos.at("L-Arrow");

		c_map_mainportrait = (ComponentUiButton*)map_mainportrait->GetComponent(C_UI_BUTTON);
		c_map_name = (ComponentUiButton*)map_name->GetComponent(C_UI_BUTTON);
		c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON);
		c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON);
		c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON);
		c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON);
		c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON);
		c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON);
	}

	void MapSelectUI_ActualizePublics(GameObject* game_object)
	{
		ComponentScript* this_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);

		this_script->public_gos.at("MapPortrait") = map_mainportrait;
		this_script->public_gos.at("MapName") = map_name;
		this_script->public_gos.at("P1-Red Vote") = players_vote[0];
		this_script->public_gos.at("P2-Red Vote") = players_vote[1];
		this_script->public_gos.at("P1-Blue Vote") = players_vote[2];
		this_script->public_gos.at("P2-Blue Vote") = players_vote[3];
		this_script->public_gos.at("R-Arrow") = right_arrow;
		this_script->public_gos.at("L-Arrow") = left_arrow;

		c_map_mainportrait = (ComponentUiButton*)map_mainportrait->GetComponent(C_UI_BUTTON);
		c_map_name = (ComponentUiButton*)map_name->GetComponent(C_UI_BUTTON);
		c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON);
		c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON);
		c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON);
		c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON);
		c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON);
		c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON);
	}

	void MapSelectUI_UpdatePublics(GameObject* game_object);

	void MapSelectUI_Start(GameObject* game_object)
	{
	}

	void MapSelectUI_Update(GameObject* game_object)
	{
		for (int playerID = 0; playerID < 4; playerID++)
		{
			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::A) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN)
			{
				c_players_vote[playerID]->OnPressId(current_map - 1);
				a_pressed = true;

				players_ready[playerID] = true;
			}

			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::B) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN)
			{
				c_players_vote[playerID]->OnPressId(current_map - 1);
				b_pressed = true;

				players_ready[playerID] = false;
			}

			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_LEFT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_DOWN)
			{
				if (current_map <= 1)
					current_map = 3;
				else
					current_map--;

				c_map_mainportrait->OnPressId(current_map - 2);

				dpad_left_pressed = true;
			}

			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_RIGHT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_DOWN)
			{
				if (current_map >= 3)
					current_map = 1;
				else
					current_map++;

				c_map_mainportrait->OnPressId(current_map - 2);

				if (dpad_right_pressed == false)
				{
					c_right_arrow->OnPressId(1);
					dpad_right_pressed = true;
				}
			}
		}

		if (dpad_left_pressed)
		{
			dpad_left_pressed = false;
			for (int playerID = 0; playerID < 4; playerID++)
			{
				if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_LEFT) == KEY_REPEAT || App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT)
				{
					dpad_left_pressed = true;
				}
			}
			if (!dpad_left_pressed)
			{
				c_right_arrow->OnPressId(1);
			}
		}

		if (dpad_right_pressed)
		{
			dpad_right_pressed = false;
			for (int playerID = 0; playerID < 4; playerID++)
			{
				if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_RIGHT) == KEY_REPEAT || App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT)
				{
					dpad_right_pressed = true;
				}
			}
			if (!dpad_right_pressed)
			{
				c_right_arrow->OnPressId(1);
			}
		}

		int total = 0;
		for (int j = 0; j < 4; j++)
		{
			if (players_ready[j])
				total++;

			if (total == 4)
			{
				// move to next scene
			}
		}
	}
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "../Lab6-CMyList/StringList.h"
#include "../Lab6-CMyList/ListIterators.h"

using namespace std;

struct EmptyStringList
{
	CStringList list;
};

BOOST_FIXTURE_TEST_SUITE(Stringlist, EmptyStringList)

	BOOST_AUTO_TEST_SUITE(when_created)
		BOOST_AUTO_TEST_CASE(is_empty)
		{
			BOOST_CHECK(list.IsEmpty());
		}
	BOOST_AUTO_TEST_SUITE_END()

	BOOST_AUTO_TEST_SUITE(after_push_back_a_string)

	BOOST_AUTO_TEST_CASE(increases_its_size_by_1)
	{
		auto oldSize = list.GetSize();
		list.PushBack("Hello World");
		BOOST_CHECK_EQUAL(list.GetSize(), oldSize + 1);
		list.PushBack("Hello World");
		BOOST_CHECK_EQUAL(list.GetSize(), oldSize + 2);
	}

	BOOST_AUTO_TEST_CASE(makes_it_accessible_via_GetBackElement_and_GetFrontElement_method)
	{
		list.PushBack("Hello World");
		BOOST_CHECK_EQUAL(list.GetBackElement(), "Hello World");
		BOOST_CHECK_EQUAL(list.GetFrontElement(), "Hello World");
		list.PushBack("bye");
		BOOST_CHECK_EQUAL(list.GetBackElement(), "bye");
		BOOST_CHECK_EQUAL(list.GetFrontElement(), "Hello World");
	}

	BOOST_AUTO_TEST_SUITE_END()

	BOOST_AUTO_TEST_SUITE(after_push_front_a_string)

	BOOST_AUTO_TEST_CASE(increases_its_size_by_1)
	{
		auto oldSize = list.GetSize();
		list.PushFront("Hello World");
		BOOST_CHECK_EQUAL(list.GetSize(), oldSize + 1);
		list.PushFront("Hello World");
		BOOST_CHECK_EQUAL(list.GetSize(), oldSize + 2);
	}

	BOOST_AUTO_TEST_CASE(makes_it_accessible_via_GetBackElement_and_GetFrontElement_method)
	{
		list.PushFront("Hello World");
		BOOST_CHECK_EQUAL(list.GetFrontElement(), "Hello World");
		BOOST_CHECK_EQUAL(list.GetBackElement(), "Hello World");
		list.PushFront("bye");
		BOOST_CHECK_EQUAL(list.GetFrontElement(), "bye");
		BOOST_CHECK_EQUAL(list.GetBackElement(), "Hello World");
	}

	BOOST_AUTO_TEST_CASE(makes_it_accessible_via_iterator_to_first_element)
	{
		list.PushBack("Hello World");
		auto it = list.begin();
		BOOST_CHECK_EQUAL(addressof(*it), addressof(list.GetBackElement()));
	}

	BOOST_AUTO_TEST_SUITE_END()

struct WasFilled : public EmptyStringList
{
	WasFilled()
	{
		list = { "first","second","third" };
	}
	std::vector<std::string> expectedString = { "first", "second", "third" };
};
BOOST_FIXTURE_TEST_SUITE(InitialisedList, WasFilled)
	BOOST_AUTO_TEST_CASE(can_go_through_the_list_using_the_operators_start_and_end)
		{
			size_t index = 0;
			for (auto it = list.begin(); it != list.end(); ++it)
			{
				BOOST_CHECK(*it == expectedString[index]);
				++index;
			}
		}
	BOOST_AUTO_TEST_CASE(can_go_through_the_list_using_reverse_iterators)
	{
		size_t index = list.GetSize() - 1;
		for (auto iter = list.rbegin(); iter != list.rend(); --iter)
		{
			BOOST_CHECK(*iter == expectedString[index]);
			--index;
		}
		}
	BOOST_AUTO_TEST_CASE(can_get_access_to_elements_from_range_based_for)
	{
		size_t index = 0;
		for (auto str : list)
		{
			BOOST_CHECK(str == expectedString[index]);
			++index;
		}
	}
	BOOST_AUTO_TEST_CASE(can_be_cleared)
	{
		BOOST_CHECK(!list.IsEmpty());
		list.Clear();
		BOOST_CHECK(list.IsEmpty());

	}
	BOOST_AUTO_TEST_CASE(can_be_cleared_where_the_list_is_empty)
	{
		CStringList emptyList;

		BOOST_CHECK(emptyList.IsEmpty());
		emptyList.Clear();
		BOOST_CHECK(emptyList.IsEmpty());
	}

	BOOST_AUTO_TEST_CASE(can_insert_element_at_iterator_pos)
	{
		auto it = ++list.begin();
		list.Insert(it, "zero");
		BOOST_CHECK_EQUAL(*++list.begin(), "zero");

		list.Insert(list.begin(), "brazers");
		BOOST_CHECK_EQUAL(*list.begin(), "brazers");

		list.Insert(list.end(), "brazers");

		vector<string> expectedStrings = { "brazers", "first", "zero", "second", "third", "brazers" };
		size_t i = 0;
		for (auto str : list)
		{
			BOOST_CHECK_EQUAL(str, expectedStrings[i]);
			i++;
		}
	}
	BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()<commit_msg>не работают тесты<commit_after>#include "stdafx.h"
#include "../Lab6-CMyList/StringList.h"
#include "../Lab6-CMyList/ListIterators.h"

using namespace std;

struct EmptyStringList
{
	CStringList list;
};

BOOST_FIXTURE_TEST_SUITE(Stringlist, EmptyStringList)

	BOOST_AUTO_TEST_SUITE(when_created)
		BOOST_AUTO_TEST_CASE(is_empty)
		{
			BOOST_CHECK(list.IsEmpty());
		}
	BOOST_AUTO_TEST_SUITE_END()

	BOOST_AUTO_TEST_SUITE(after_push_back_a_string)

	BOOST_AUTO_TEST_CASE(increases_its_size_by_1)
	{
		auto oldSize = list.GetSize();
		list.PushBack("Hello World");
		BOOST_CHECK_EQUAL(list.GetSize(), oldSize + 1);
		list.PushBack("Hello World");
		BOOST_CHECK_EQUAL(list.GetSize(), oldSize + 2);
	}

	BOOST_AUTO_TEST_CASE(makes_it_accessible_via_GetBackElement_and_GetFrontElement_method)
	{
		list.PushBack("Hello World");
		BOOST_CHECK_EQUAL(list.GetBackElement(), "Hello World");
		BOOST_CHECK_EQUAL(list.GetFrontElement(), "Hello World");
		list.PushBack("bye");
		BOOST_CHECK_EQUAL(list.GetBackElement(), "bye");
		BOOST_CHECK_EQUAL(list.GetFrontElement(), "Hello World");
	}

	BOOST_AUTO_TEST_SUITE_END()

	BOOST_AUTO_TEST_SUITE(after_push_front_a_string)

	BOOST_AUTO_TEST_CASE(increases_its_size_by_1)
	{
		auto oldSize = list.GetSize();
		list.PushFront("Hello World");
		BOOST_CHECK_EQUAL(list.GetSize(), oldSize + 1);
		list.PushFront("Hello World");
		BOOST_CHECK_EQUAL(list.GetSize(), oldSize + 2);
	}

	BOOST_AUTO_TEST_CASE(makes_it_accessible_via_GetBackElement_and_GetFrontElement_method)
	{
		list.PushFront("Hello World");
		BOOST_CHECK_EQUAL(list.GetFrontElement(), "Hello World");
		BOOST_CHECK_EQUAL(list.GetBackElement(), "Hello World");
		list.PushFront("bye");
		BOOST_CHECK_EQUAL(list.GetFrontElement(), "bye");
		BOOST_CHECK_EQUAL(list.GetBackElement(), "Hello World");
	}

	BOOST_AUTO_TEST_CASE(makes_it_accessible_via_iterator_to_first_element)
	{
		list.PushBack("Hello World");
		auto it = list.begin();
		BOOST_CHECK_EQUAL(addressof(*it), addressof(list.GetBackElement()));
	}

	BOOST_AUTO_TEST_SUITE_END()

struct WasFilled : public EmptyStringList
{
	WasFilled()
	{
		list = { "first","second","third" };
	}
	std::vector<std::string> expectedString = { "first", "second", "third" };
};/*
BOOST_FIXTURE_TEST_SUITE(InitialisedList, WasFilled)
	BOOST_AUTO_TEST_CASE(can_go_through_the_list_using_the_operators_start_and_end)
		{
			size_t index = 0;
			for (auto it = list.begin(); it != list.end(); ++it)
			{
				BOOST_CHECK(*it == expectedString[index]);
				++index;
			}
		}
	BOOST_AUTO_TEST_CASE(can_go_through_the_list_using_reverse_iterators)
	{
		size_t index = list.GetSize() - 1;
		for (auto iter = list.rbegin(); iter != list.rend(); --iter)
		{
			BOOST_CHECK(*iter == expectedString[index]);
			--index;
		}
		}
	BOOST_AUTO_TEST_CASE(can_get_access_to_elements_from_range_based_for)
	{
		size_t index = 0;
		for (auto str : list)
		{
			BOOST_CHECK(str == expectedString[index]);
			++index;
		}
	}
	BOOST_AUTO_TEST_CASE(can_be_cleared)
	{
		BOOST_CHECK(!list.IsEmpty());
		list.Clear();
		BOOST_CHECK(list.IsEmpty());

	}
	BOOST_AUTO_TEST_CASE(can_be_cleared_where_the_list_is_empty)
	{
		CStringList emptyList;

		BOOST_CHECK(emptyList.IsEmpty());
		emptyList.Clear();
		BOOST_CHECK(emptyList.IsEmpty());
	}

	BOOST_AUTO_TEST_CASE(can_insert_element_at_iterator_pos)
	{
		auto it = ++list.begin();
		list.Insert(it, "zero");
		BOOST_CHECK_EQUAL(*++list.begin(), "zero");

		list.Insert(list.begin(), "brazers");
		BOOST_CHECK_EQUAL(*list.begin(), "brazers");

		list.Insert(list.end(), "brazers");

		vector<string> expectedStrings = { "brazers", "first", "zero", "second", "third", "brazers" };
		size_t i = 0;
		for (auto str : list)
		{
			BOOST_CHECK_EQUAL(str, expectedStrings[i]);
			i++;
		}
	}
	BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()*/<|endoftext|>


<commit_before>#include <iostream>

#include "array.hpp"

using namespace std;

int main() {
    cout << "----------------------- 3D -----------------------\n";
    nd::array<double> array3d = {
            {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}},
            {{4, 5, 6}, {4, 5, 6}, {4, 5, 6}}
    };

    cout << "n dimensions: " << array3d.ndim() << "\n";
    cout << "n elements: " << array3d.size() << "\n";
    cout << array3d << "\n";

    // get array in an array
    cout << "sub array is:\n" << array3d[0] << "\n";

    // get array scalar object
    cout << "scalar value: " << array3d[0][1][2] << "\n";

    // get and set a scalar value with template type T.
    // this way is faster than at() and operator[]
    array3d.item({1, 1, 1}) = 999;

    // apply function to all elements
    array3d.unary_expr([](double val) { return val / 2; });

    cout << "array is now:\n" << array3d << "\n\n";

    cout << "----------------------- 1D -----------------------\n";

    nd::array<double> array1d = {1, 2, 3, 4, 5, 6.5};

    cout << array1d << "\n";

    // make array1d a 2x3 array
    array1d.reshape({2, 3});

    cout << "reshape array:" << "\n";
    cout << array1d << "\n";

    cout << "------------------- transpose --------------------\n";

    nd::array<int> someArray({2, 3}, 0);

    someArray.arrange(0, 2 * 3);

    cout << someArray.transpose() << "\n";

    return 0;
}
<commit_msg>updated main<commit_after>#include <iostream>

#include "array.hpp"

using namespace std;

int main() {
    cout << "----------------------- 3D -----------------------\n";
    nd::array<double> array3d = {
            {
                    {1, 2, 3},
                    {1, 2, 3},
                    {1, 2, 3}
            },

            {
                    {4, 5, 6},
                    {4, 5, 6},
                    {4, 5, 6}
            }
    };

    cout << "n dimensions: " << array3d.ndim() << "\n";
    cout << "n elements: " << array3d.size() << "\n";
    cout << array3d << "\n";

    // get array in an array
    cout << "sub array is:\n" << array3d[0] << "\n";

    // get array scalar object
    cout << "scalar value: " << array3d[0][1][2] << "\n";

    // get and set a scalar value with template type T.
    // this way is faster than at() and operator[]
    array3d.item({1, 1, 1}) = 999;

    // apply function to all elements
    array3d.unary_expr([](double val) { return val / 2; });

    cout << "array is now:\n" << array3d << "\n\n";

    cout << "----------------------- 1D -----------------------\n";

    nd::array<double> array1d = {1, 2, 3, 4, 5, 6.5};

    cout << array1d << "\n";

    // make array1d a 2x3 array
    array1d.reshape({2, 3});

    cout << "reshape array:" << "\n";
    cout << array1d << "\n";

    cout << "------------------- transpose --------------------\n";

    nd::array<int> someArray({2, 3}, 0);

    someArray.arrange(0, 2 * 3);

    cout << someArray.transpose() << "\n";

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <array>
#include <random>

#include <SFML/Graphics.hpp>

#include "vector2.h"
#include "triangle.h"
#include "delaunay.h"

int main(int argc, char * argv[])
{
	int numberPoints = 40;
	if (argc>1)
	{
		numberPoints = atoi(argv[1]);
	}

	std::default_random_engine eng(std::random_device{}());
	std::uniform_real_distribution<float> dist_w(0, 800);
	std::uniform_real_distribution<float> dist_h(0, 600);

	std::cout << "Generating " << numberPoints << " random points" << std::endl;

	std::vector<Vector2<float> > points;
	for(int i = 0; i < numberPoints; ++i) {
		points.push_back(Vector2<float>(dist_w(eng), dist_h(eng)));
	}

	Delaunay<float> triangulation;
	const std::vector<Triangle<float> > triangles = triangulation.triangulate(points);
	std::cout << triangles.size() << " triangles generated\n";
	const std::vector<Edge<float> > edges = triangulation.getEdges();

	std::cout << " ========= ";

	std::cout << "\nPoints : " << points.size() << std::endl;
	for(const auto &p : points)
		std::cout << p << std::endl;

	std::cout << "\nTriangles : " << triangles.size() << std::endl;
	for(const auto &t : triangles)
		std::cout << t << std::endl;

	std::cout << "\nEdges : " << edges.size() << std::endl;
	for(const auto &e : edges)
		std::cout << e << std::endl;

	// SFML window
	sf::RenderWindow window(sf::VideoMode(800, 600), "Delaunay triangulation");

	// Transform each points of each vector as a rectangle
	std::vector<sf::RectangleShape*> squares;

	for(const auto p : points) {
		sf::RectangleShape *c1 = new sf::RectangleShape(sf::Vector2f(4, 4));
		c1->setPosition(p.x, p.y);
		squares.push_back(c1);
	}

	// Make the lines
	std::vector<std::array<sf::Vertex, 2> > lines;
	for(const auto &e : edges) {
		lines.push_back({{
			sf::Vertex(sf::Vector2f(e.p1.x + 2, e.p1.y + 2)),
			sf::Vertex(sf::Vector2f(e.p2.x + 2, e.p2.y + 2))
		}});
	}

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}

		window.clear();

		// Draw the squares
		for(const auto &s : squares) {
			window.draw(*s);
		}

		// Draw the lines
		for(const auto &l : lines) {
			window.draw(l.data(), 2, sf::Lines);
		}

		window.display();
	}

	return 0;
}
<commit_msg>untemplate example, fix float conversion issues<commit_after>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <array>
#include <random>

#include <SFML/Graphics.hpp>

#include "vector2.h"
#include "triangle.h"
#include "delaunay.h"

int main(int argc, char * argv[])
{
	int numberPoints = 40;
	if (argc>1)
	{
		numberPoints = atoi(argv[1]);
	}

	std::default_random_engine eng(std::random_device{}());
	std::uniform_real_distribution<double> dist_w(0, 800);
	std::uniform_real_distribution<double> dist_h(0, 600);

	std::cout << "Generating " << numberPoints << " random points" << std::endl;

	std::vector<Vector2> points;
	for(int i = 0; i < numberPoints; ++i) {
		points.push_back(Vector2{dist_w(eng), dist_h(eng)});
	}

	Delaunay triangulation;
	const std::vector<Triangle> triangles = triangulation.triangulate(points);
	std::cout << triangles.size() << " triangles generated\n";
	const std::vector<Edge> edges = triangulation.getEdges();

	std::cout << " ========= ";

	std::cout << "\nPoints : " << points.size() << std::endl;
	for(const auto &p : points)
		std::cout << p << std::endl;

	std::cout << "\nTriangles : " << triangles.size() << std::endl;
	for(const auto &t : triangles)
		std::cout << t << std::endl;

	std::cout << "\nEdges : " << edges.size() << std::endl;
	for(const auto &e : edges)
		std::cout << e << std::endl;

	// SFML window
	sf::RenderWindow window(sf::VideoMode(800, 600), "Delaunay triangulation");

	// Transform each points of each vector as a rectangle
	std::vector<sf::RectangleShape*> squares;

	for(const auto p : points) {
		sf::RectangleShape *c1 = new sf::RectangleShape(sf::Vector2f(4, 4));
		c1->setPosition(static_cast<float>(p.x), static_cast<float>(p.y));
		squares.push_back(c1);
	}

	// Make the lines
	std::vector<std::array<sf::Vertex, 2> > lines;
	for(const auto &e : edges) {
		lines.push_back({{
			sf::Vertex(sf::Vector2f(
					static_cast<float>(e.p1.x + 2.),
					static_cast<float>(e.p1.y + 2.))),
			sf::Vertex(sf::Vector2f(
					static_cast<float>(e.p2.x + 2.),
					static_cast<float>(e.p2.y + 2.))),
		}});
	}

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}

		window.clear();

		// Draw the squares
		for(const auto &s : squares) {
			window.draw(*s);
		}

		// Draw the lines
		for(const auto &l : lines) {
			window.draw(l.data(), 2, sf::Lines);
		}

		window.display();
	}

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Strict compilation for airbourne board<commit_after><|endoftext|>


<commit_before>#include "buffer.hpp"
#include "validate.hpp"
#include "parser_rt.hpp"
#include <cstdio>

#ifndef TEST
# error "Please specify a test."
#endif

using namespace Jak;
int main()
{
#if TEST == 1
    TinyBasicParser p(Buf("10 PRINT 'Hello, World!'"));
    int refCode = 0;
#elif TEST == 2
    TinyBasicParser p(Buf("\
10 PRINT 'Hello, World!'\n\
20 GOTO 10"));
    int refCode = 0;
#elif TEST == 3
    TinyBasicParser p(Buf("\
10 PRINT 'Hello, World!'\n\
20 GOTO 10\n"));
    int refCode = 0;
#elif TEST == 4
    TinyBasicParser p(Buf("\
10 PIRNT 'Hello, World!'"));
    int refCode = 12;
#endif
    auto code = static_cast<int>(p.file().code());
    printf("%d\n", code);
    printf("\n%s\n", (code == refCode) ? "PASS" : "FAIL");
}
<commit_msg>also compare with ref line number<commit_after>#include "buffer.hpp"
#include "validate.hpp"
#include "parser_rt.hpp"
#include <cstdio>

#ifndef TEST
# error "Please specify a test."
#endif

using namespace Jak;
int main()
{
#if TEST == 1
    TinyBasicParser p(Buf("10 PRINT 'Hello, World!'"));
    int refCode = 0;
    int refLine = 1;
#elif TEST == 2
    TinyBasicParser p(Buf("\
10 PRINT 'Hello, World!'\n\
20 GOTO 10"));
    int refCode = 0;
    int refLine = 2;
#elif TEST == 3
    TinyBasicParser p(Buf("\
10 PRINT 'Hello, World!'\n\
20 GOTO 10\n"));
    int refCode = 0;
    int refLine = 3;
#elif TEST == 4
    TinyBasicParser p(Buf("\
10 PIRNT 'Hello, World!'"));
    int refCode = 12;
    int refLine = 1;
#endif
    auto rv = p.file();
    auto code = static_cast<int>(rv.code());
    auto line = rv.lineNo();
    printf("%d %d\n", code, line);
    printf("\n%s\n", (code == refCode && line == refLine) ? "PASS" : "FAIL");
}
<|endoftext|>


<commit_before><commit_msg>am f4515652: am cc94b55e: Hammerhead: Camera3: Set appropriate lens shading map mode<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.3.32); FILE MERGED 2005/09/05 17:27:14 rt 1.3.32.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>


<commit_before>// Created by: Peter KURNEV
// Copyright (c) 2010-2012 OPEN CASCADE SAS
// Copyright (c) 2007-2010 CEA/DEN, EDF R&D, OPEN CASCADE
// Copyright (c) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, CEDRAT,
//                         EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.

#include <BOPDS_PassKey.ixx>

#include <stdio.h>

#ifdef WNT
#pragma warning( disable : 4101)
#endif

//=======================================================================
//function : Dump
//purpose  :
//=======================================================================
  void BOPDS_PassKey::Dump(const Standard_Integer )const
{
}
<commit_msg>[mingw-warning-fix][unknown-pragma]<commit_after>// Created by: Peter KURNEV
// Copyright (c) 2010-2012 OPEN CASCADE SAS
// Copyright (c) 2007-2010 CEA/DEN, EDF R&D, OPEN CASCADE
// Copyright (c) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, CEDRAT,
//                         EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.

#include <BOPDS_PassKey.ixx>

#include <stdio.h>

#ifdef _MSC_VER
#pragma warning( disable : 4101)
#endif

//=======================================================================
//function : Dump
//purpose  :
//=======================================================================
  void BOPDS_PassKey::Dump(const Standard_Integer )const
{
}
<|endoftext|>


<commit_before>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2013-02-18 Martin Siggel <Martin.Siggel@dlr.de>
*
* 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 "CTiglTriangularizer.h"
#include "ITiglGeometricComponent.h"
#include "CCPACSWing.h"

#include <TopoDS.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Shell.hxx>
#include <TopoDS_Face.hxx>

#include <TopExp_Explorer.hxx>
#include <TopLoc_Location.hxx>
#include <Poly_Triangulation.hxx>
#include <BRep_Tool.hxx>
#include <BRepGProp_Face.hxx>

#include <gp_Pnt.hxx>
#include <gp_Pnt2d.hxx>

#include <TColgp_Array1OfPnt2d.hxx>
#include <climits>

namespace tigl{

CTiglTriangularizer::CTiglTriangularizer()
{
    useMultipleObjects(false);
}

CTiglTriangularizer::CTiglTriangularizer(TopoDS_Shape& shape, bool multipleObj) {
    useMultipleObjects(multipleObj);

    triangularizeShape(shape);
}

int CTiglTriangularizer::triangularizeShape(const TopoDS_Shape& shape){
    TopExp_Explorer shellExplorer;
    TopExp_Explorer faceExplorer;

    for (shellExplorer.Init(shape, TopAbs_SHELL); shellExplorer.More(); shellExplorer.Next()) {
        const TopoDS_Shell shell = TopoDS::Shell(shellExplorer.Current());

        for (faceExplorer.Init(shell, TopAbs_FACE); faceExplorer.More(); faceExplorer.Next()) {
            TopoDS_Face face = TopoDS::Face(faceExplorer.Current());
            unsigned long *vertexList = NULL;
            unsigned long nVertices, iPolyLower, iPolyUpper;
            triangularizeFace(face,vertexList, nVertices, iPolyLower, iPolyUpper);
            if(vertexList) delete[] vertexList;
        } // for faces
        if(_useMultipleObjects) createNewObject();
    } // for shells

    return 0;
}

CTiglTriangularizer::CTiglTriangularizer(ITiglGeometricComponent& comp, ComponentTraingMode mode) {
    useMultipleObjects(false);

    triangularizeComponent(comp, mode);
}

bool isValidCoord(double c){
    double tolerance = Precision::Confusion();
    if(c > -tolerance && c < 1+tolerance)
        return true;
    else
        return false;
}

int CTiglTriangularizer::triangularizeComponent(ITiglGeometricComponent& component, ComponentTraingMode mode){
    const TopoDS_Shape& shape = component.GetLoft();

    TopExp_Explorer shellExplorer;
    TopExp_Explorer faceExplorer;

    for (shellExplorer.Init(shape, TopAbs_SHELL); shellExplorer.More(); shellExplorer.Next()) {
        const TopoDS_Shell shell = TopoDS::Shell(shellExplorer.Current());

        for (faceExplorer.Init(shell, TopAbs_FACE); faceExplorer.More(); faceExplorer.Next()) {
            TopoDS_Face face = TopoDS::Face(faceExplorer.Current());
            unsigned long * vertexIndexList = NULL;
            unsigned long nVertices, iPolyLower, iPolyUpper;
            triangularizeFace(face, vertexIndexList, nVertices, iPolyLower, iPolyUpper);
            if(nVertices > 0 && vertexIndexList != NULL &&  mode ==  SEGMENT_INFO){
                // compute a central point on the face
                BRepGProp_Face prop(face);
                Standard_Real umin, umax, vmin, vmax;
                prop.Bounds(umin, umax, vmin, vmax);

                Standard_Real umean = 0.5*(umin+umax);
                Standard_Real vmean = 0.5*(vmin+vmax);

                gp_Pnt centralP; gp_Vec n;
                prop.Normal(umean,vmean,centralP,n);

                if(component.GetComponentType() & TIGL_COMPONENT_WING){

                    // check to which segment this face belongs
                    CCPACSWing& wing = dynamic_cast<CCPACSWing&>(component) ;
                    int iSegmentFound = 0;
                    for(int iSegment = 1 ; iSegment <= wing.GetSegmentCount(); ++iSegment){
                        CCPACSWingSegment& segment = (CCPACSWingSegment&) wing.GetSegment(iSegment);
                        double eta = 0., xsi = 0.;
                        segment.GetEtaXsi(centralP, false, eta, xsi);

                        if(isValidCoord(eta) && isValidCoord(xsi)){
                            iSegmentFound = iSegment;
                            break;
                        }
                    }

                    currentObject().setMetadataElements("uID segmentIndex eta xsi isOnTop");
                    if(iSegmentFound > 0){
                        // determine if this face is an upper segment face
                        CCPACSWingSegment& segment = (CCPACSWingSegment&) wing.GetSegment(iSegmentFound);

                        // GetIsOnTop is very slow, therefore we do it only once per face
                        bool isUpperFace = segment.GetIsOnTop(centralP);

                        for(unsigned int iPoly = iPolyLower; iPoly <= iPolyUpper; iPoly++){
                            currentObject().setPolyDataReal(iPoly, "is_upper", (double) isUpperFace);
                            currentObject().setPolyDataReal(iPoly, "segment_index", (double) iSegmentFound);

                            unsigned long npoints = currentObject().getNPointsOfPolygon(iPoly);

                            CTiglPoint baryCenter(0.,0.,0.);
                            for(unsigned long jPoint = 0; jPoint < npoints; ++jPoint){
                                unsigned long index = currentObject().getVertexIndexOfPolygon(jPoint, iPoly);
                                baryCenter += currentObject().getVertexPoint(index);
                            }
                            baryCenter = baryCenter*(double)(1./(double)npoints);

                            double eta = 0., xsi = 0.;
                            segment.GetEtaXsi(baryCenter.Get_gp_Pnt(), false, eta, xsi);
                            currentObject().setPolyDataReal(iPoly, "eta", eta);
                            currentObject().setPolyDataReal(iPoly, "xsi", xsi);

                            // create metadata string
                            std::stringstream stream;
                            stream << "\"" << segment.GetUID() << "\" " << iSegmentFound << " " << eta << " " << xsi << " " << isUpperFace;
                            currentObject().setPolyMetadata(iPoly, stream.str().c_str());
                        }
                    }
                    else {
                        for(unsigned int iPoly = iPolyLower; iPoly <= iPolyUpper; iPoly++){
                            currentObject().setPolyMetadata(iPoly,"\"\" 0 0.0 0.0 0");
                        }
                    } // iSegmentFound
                } // isWing
            } // advanced mode

            if(vertexIndexList) delete[] vertexIndexList;
        } // for faces
        if(_useMultipleObjects) createNewObject();
    } // for shells

    return 0;
}

int CTiglTriangularizer::triangularizeFace(const TopoDS_Face & face, unsigned long* &indexBuffer, unsigned long &nVertices, unsigned long &iPolyLower, unsigned long &iPolyUpper){
    TopLoc_Location location;
    const Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation(face, location);

    indexBuffer = NULL;
    if (triangulation.IsNull())
        return 0;

    gp_Trsf nodeTransformation = location;

    unsigned long ilower = 0;
    unsigned long iBufferSize = 0;

    if(triangulation->HasUVNodes()){
        // we use the uv nodes to compute normal vectors for each point

        BRepGProp_Face prop(face);
        currentObject().enableNormals(true);

        const TColgp_Array1OfPnt2d& uvnodes = triangulation->UVNodes(); // get (face-local) list of nodes
        ilower = uvnodes.Lower();

        iBufferSize = uvnodes.Upper()-uvnodes.Lower()+1;
        indexBuffer = new unsigned long [iBufferSize];
        unsigned long * pIndexBuf = indexBuffer;
        for(int inode = uvnodes.Lower(); inode <= uvnodes.Upper(); ++inode){
            const gp_Pnt2d& uv_pnt = uvnodes(inode);
            gp_Pnt p; gp_Vec n;
            prop.Normal(uv_pnt.X(),uv_pnt.Y(),p,n);

            *pIndexBuf++ = currentObject().addPointNormal(p.XYZ(), n.XYZ());
        }
    }
    else {
        // we cannot compute normals

        const TColgp_Array1OfPnt& nodes = triangulation->Nodes(); // get (face-local) list of nodes
        ilower = nodes.Lower();

        iBufferSize = nodes.Upper()-nodes.Lower()+1;
        indexBuffer = new unsigned long [iBufferSize];
        unsigned long * pIndexBuf = indexBuffer;
        for(int inode = nodes.Lower(); inode <= nodes.Upper(); inode++){
            const gp_Pnt& p = nodes(inode).Transformed(nodeTransformation);
            *pIndexBuf++ = currentObject().addPointNormal(p.XYZ(), CTiglPoint(1,0,0));
        }
    }

    const Poly_Array1OfTriangle& triangles = triangulation->Triangles();
    iPolyLower = ULONG_MAX;
    iPolyUpper = 0;
    for (int j = triangles.Lower(); j <= triangles.Upper(); j++) // iterate over triangles in the array
    {
        const Poly_Triangle& triangle = triangles(j);
        int occindex1, occindex2, occindex3;
        triangle.Get(occindex1, occindex2, occindex3); // get indices into index1..3
        unsigned long index1, index2, index3;
        index1 = indexBuffer[occindex1-ilower];
        index2 = indexBuffer[occindex2-ilower];
        index3 = indexBuffer[occindex3-ilower];

        unsigned int iPolyIndex = 0;

        if(face.Orientation() == TopAbs_FORWARD)
            iPolyIndex = currentObject().addTriangleByVertexIndex(index1, index2, index3);
        else
            iPolyIndex = currentObject().addTriangleByVertexIndex(index1, index3, index2);

        if(iPolyIndex > iPolyUpper) iPolyUpper = iPolyIndex;
        if(iPolyIndex < iPolyLower) iPolyLower = iPolyIndex;

    } // for triangles

    nVertices = iBufferSize;
    return 0;
}

void CTiglTriangularizer::useMultipleObjects(bool use){
    _useMultipleObjects = use;
}

} // namespace tigl
<commit_msg>Reduced tolerance in VTK export to improve segment detection<commit_after>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2013-02-18 Martin Siggel <Martin.Siggel@dlr.de>
*
* 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 "CTiglTriangularizer.h"
#include "ITiglGeometricComponent.h"
#include "CCPACSWing.h"

#include <TopoDS.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Shell.hxx>
#include <TopoDS_Face.hxx>

#include <TopExp_Explorer.hxx>
#include <TopLoc_Location.hxx>
#include <Poly_Triangulation.hxx>
#include <BRep_Tool.hxx>
#include <BRepGProp_Face.hxx>

#include <gp_Pnt.hxx>
#include <gp_Pnt2d.hxx>

#include <TColgp_Array1OfPnt2d.hxx>
#include <climits>

namespace tigl{

CTiglTriangularizer::CTiglTriangularizer()
{
    useMultipleObjects(false);
}

CTiglTriangularizer::CTiglTriangularizer(TopoDS_Shape& shape, bool multipleObj) {
    useMultipleObjects(multipleObj);

    triangularizeShape(shape);
}

int CTiglTriangularizer::triangularizeShape(const TopoDS_Shape& shape){
    TopExp_Explorer shellExplorer;
    TopExp_Explorer faceExplorer;

    for (shellExplorer.Init(shape, TopAbs_SHELL); shellExplorer.More(); shellExplorer.Next()) {
        const TopoDS_Shell shell = TopoDS::Shell(shellExplorer.Current());

        for (faceExplorer.Init(shell, TopAbs_FACE); faceExplorer.More(); faceExplorer.Next()) {
            TopoDS_Face face = TopoDS::Face(faceExplorer.Current());
            unsigned long *vertexList = NULL;
            unsigned long nVertices, iPolyLower, iPolyUpper;
            triangularizeFace(face,vertexList, nVertices, iPolyLower, iPolyUpper);
            if(vertexList) delete[] vertexList;
        } // for faces
        if(_useMultipleObjects) createNewObject();
    } // for shells

    return 0;
}

CTiglTriangularizer::CTiglTriangularizer(ITiglGeometricComponent& comp, ComponentTraingMode mode) {
    useMultipleObjects(false);

    triangularizeComponent(comp, mode);
}

bool isValidCoord(double c){
    double tolerance = 2.e-4;
    if(c > -tolerance && c < 1+tolerance)
        return true;
    else
        return false;
}

int CTiglTriangularizer::triangularizeComponent(ITiglGeometricComponent& component, ComponentTraingMode mode){
    const TopoDS_Shape& shape = component.GetLoft();

    TopExp_Explorer shellExplorer;
    TopExp_Explorer faceExplorer;

    for (shellExplorer.Init(shape, TopAbs_SHELL); shellExplorer.More(); shellExplorer.Next()) {
        const TopoDS_Shell shell = TopoDS::Shell(shellExplorer.Current());

        for (faceExplorer.Init(shell, TopAbs_FACE); faceExplorer.More(); faceExplorer.Next()) {
            TopoDS_Face face = TopoDS::Face(faceExplorer.Current());
            unsigned long * vertexIndexList = NULL;
            unsigned long nVertices, iPolyLower, iPolyUpper;
            triangularizeFace(face, vertexIndexList, nVertices, iPolyLower, iPolyUpper);
            if(nVertices > 0 && vertexIndexList != NULL &&  mode ==  SEGMENT_INFO){
                // compute a central point on the face
                BRepGProp_Face prop(face);
                Standard_Real umin, umax, vmin, vmax;
                prop.Bounds(umin, umax, vmin, vmax);

                Standard_Real umean = 0.5*(umin+umax);
                Standard_Real vmean = 0.5*(vmin+vmax);

                gp_Pnt centralP; gp_Vec n;
                prop.Normal(umean,vmean,centralP,n);

                if(component.GetComponentType() & TIGL_COMPONENT_WING){

                    // check to which segment this face belongs
                    CCPACSWing& wing = dynamic_cast<CCPACSWing&>(component) ;
                    int iSegmentFound = 0;
                    for(int iSegment = 1 ; iSegment <= wing.GetSegmentCount(); ++iSegment){
                        CCPACSWingSegment& segment = (CCPACSWingSegment&) wing.GetSegment(iSegment);
                        double eta = 0., xsi = 0.;
                        segment.GetEtaXsi(centralP, false, eta, xsi);

                        if(isValidCoord(eta) && isValidCoord(xsi)){
                            iSegmentFound = iSegment;
                            break;
                        }
                    }

                    currentObject().setMetadataElements("uID segmentIndex eta xsi isOnTop");
                    if(iSegmentFound > 0){
                        // determine if this face is an upper segment face
                        CCPACSWingSegment& segment = (CCPACSWingSegment&) wing.GetSegment(iSegmentFound);

                        // GetIsOnTop is very slow, therefore we do it only once per face
                        bool isUpperFace = segment.GetIsOnTop(centralP);

                        for(unsigned int iPoly = iPolyLower; iPoly <= iPolyUpper; iPoly++){
                            currentObject().setPolyDataReal(iPoly, "is_upper", (double) isUpperFace);
                            currentObject().setPolyDataReal(iPoly, "segment_index", (double) iSegmentFound);

                            unsigned long npoints = currentObject().getNPointsOfPolygon(iPoly);

                            CTiglPoint baryCenter(0.,0.,0.);
                            for(unsigned long jPoint = 0; jPoint < npoints; ++jPoint){
                                unsigned long index = currentObject().getVertexIndexOfPolygon(jPoint, iPoly);
                                baryCenter += currentObject().getVertexPoint(index);
                            }
                            baryCenter = baryCenter*(double)(1./(double)npoints);

                            double eta = 0., xsi = 0.;
                            segment.GetEtaXsi(baryCenter.Get_gp_Pnt(), false, eta, xsi);
                            currentObject().setPolyDataReal(iPoly, "eta", eta);
                            currentObject().setPolyDataReal(iPoly, "xsi", xsi);

                            // create metadata string
                            std::stringstream stream;
                            stream << "\"" << segment.GetUID() << "\" " << iSegmentFound << " " << eta << " " << xsi << " " << isUpperFace;
                            currentObject().setPolyMetadata(iPoly, stream.str().c_str());
                        }
                    }
                    else {
                        for(unsigned int iPoly = iPolyLower; iPoly <= iPolyUpper; iPoly++){
                            currentObject().setPolyMetadata(iPoly,"\"\" 0 0.0 0.0 0");
                        }
                    } // iSegmentFound
                } // isWing
            } // advanced mode

            if(vertexIndexList) delete[] vertexIndexList;
        } // for faces
        if(_useMultipleObjects) createNewObject();
    } // for shells

    return 0;
}

int CTiglTriangularizer::triangularizeFace(const TopoDS_Face & face, unsigned long* &indexBuffer, unsigned long &nVertices, unsigned long &iPolyLower, unsigned long &iPolyUpper){
    TopLoc_Location location;
    const Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation(face, location);

    indexBuffer = NULL;
    if (triangulation.IsNull())
        return 0;

    gp_Trsf nodeTransformation = location;

    unsigned long ilower = 0;
    unsigned long iBufferSize = 0;

    if(triangulation->HasUVNodes()){
        // we use the uv nodes to compute normal vectors for each point

        BRepGProp_Face prop(face);
        currentObject().enableNormals(true);

        const TColgp_Array1OfPnt2d& uvnodes = triangulation->UVNodes(); // get (face-local) list of nodes
        ilower = uvnodes.Lower();

        iBufferSize = uvnodes.Upper()-uvnodes.Lower()+1;
        indexBuffer = new unsigned long [iBufferSize];
        unsigned long * pIndexBuf = indexBuffer;
        for(int inode = uvnodes.Lower(); inode <= uvnodes.Upper(); ++inode){
            const gp_Pnt2d& uv_pnt = uvnodes(inode);
            gp_Pnt p; gp_Vec n;
            prop.Normal(uv_pnt.X(),uv_pnt.Y(),p,n);

            *pIndexBuf++ = currentObject().addPointNormal(p.XYZ(), n.XYZ());
        }
    }
    else {
        // we cannot compute normals

        const TColgp_Array1OfPnt& nodes = triangulation->Nodes(); // get (face-local) list of nodes
        ilower = nodes.Lower();

        iBufferSize = nodes.Upper()-nodes.Lower()+1;
        indexBuffer = new unsigned long [iBufferSize];
        unsigned long * pIndexBuf = indexBuffer;
        for(int inode = nodes.Lower(); inode <= nodes.Upper(); inode++){
            const gp_Pnt& p = nodes(inode).Transformed(nodeTransformation);
            *pIndexBuf++ = currentObject().addPointNormal(p.XYZ(), CTiglPoint(1,0,0));
        }
    }

    const Poly_Array1OfTriangle& triangles = triangulation->Triangles();
    iPolyLower = ULONG_MAX;
    iPolyUpper = 0;
    for (int j = triangles.Lower(); j <= triangles.Upper(); j++) // iterate over triangles in the array
    {
        const Poly_Triangle& triangle = triangles(j);
        int occindex1, occindex2, occindex3;
        triangle.Get(occindex1, occindex2, occindex3); // get indices into index1..3
        unsigned long index1, index2, index3;
        index1 = indexBuffer[occindex1-ilower];
        index2 = indexBuffer[occindex2-ilower];
        index3 = indexBuffer[occindex3-ilower];

        unsigned int iPolyIndex = 0;

        if(face.Orientation() == TopAbs_FORWARD)
            iPolyIndex = currentObject().addTriangleByVertexIndex(index1, index2, index3);
        else
            iPolyIndex = currentObject().addTriangleByVertexIndex(index1, index3, index2);

        if(iPolyIndex > iPolyUpper) iPolyUpper = iPolyIndex;
        if(iPolyIndex < iPolyLower) iPolyLower = iPolyIndex;

    } // for triangles

    nVertices = iBufferSize;
    return 0;
}

void CTiglTriangularizer::useMultipleObjects(bool use){
    _useMultipleObjects = use;
}

} // namespace tigl
<|endoftext|>