<commit_before>#include "KBot.h"

#include "Squad.h"
#include "utils.h"

// Some ugly macro magic to get BUILDNUMBER as a string.
#pragma warning(push)
#pragma warning(disable: 4003) // there is some silly warning in VS2017
#define MACROSTR(S) #S ""
#define STRINGER(X) MACROSTR(X)
static const std::string buildNumber = STRINGER(BUILDNUMBER);
#pragma warning(pop)

namespace KBot {

    using namespace BWAPI;

    KBot::KBot() : m_manager(*this), m_general(*this), m_enemy(*this) {}

    // Called only once at the beginning of a game.
    void KBot::onStart() {
        if (Broodwar->isReplay() || !Broodwar->self())
            return;

        // Print build information
        Broodwar << "KBot build " << (buildNumber.size() ? buildNumber : "local") << std::endl;

        // This bot is written for Terran, so make sure we are indeed Terran!
        if (Broodwar->self()->getRace() != Races::Terran) {
            Broodwar << "Wrong race selected! KBot has to be Terran." << std::endl;
            Broodwar->leaveGame();
        }

        // This bot is written for one-on-one melee games.
        if (Broodwar->getGameType() != GameTypes::Melee) {
            Broodwar << "Unexpected game type. KBot might not work correctly." << std::endl;
            // Unfortunate, but no reason to leave.
        }

        // Set the command optimization level so that common commands can be grouped.
        Broodwar->setCommandOptimizationLevel(2);

        // BWEM map initialization
        m_map.Initialize();
        m_map.EnableAutomaticPathAnalysis();
        const bool r = m_map.FindBasesForStartingLocations();
        assert(r);

        // Test BuildTask, TODO: Replace hardcoded build order
        // http://wiki.teamliquid.net/starcraft/2_Rax_FE_(vs._Zerg)
        using namespace UnitTypes;
        const auto buildorder = {
            Terran_SCV, Terran_SCV, Terran_SCV, Terran_SCV, Terran_SCV, Terran_Supply_Depot, // @ 9/10 supply
            Terran_SCV, Terran_SCV, Terran_Barracks, // @ 11/18 supply
            Terran_SCV, Terran_SCV, Terran_Barracks, // @ 13/18 supply
            Terran_SCV, Terran_Supply_Depot, // @ 14/18 supply
            Terran_SCV, Terran_Marine, Terran_SCV, Terran_Marine, Terran_Refinery, // @ 18/26 supply
            Terran_SCV, Terran_Marine, Terran_SCV, Terran_Marine, Terran_Academy, // @ 22/26 supply
            Terran_SCV, Terran_Marine, Terran_Supply_Depot // @ 24/26 supply
        };

        int priority = (int) BuildTask::Priority::buildorder;
        for (const auto &unit : buildorder)
            m_manager.addBuildTask({m_manager, unit, (BuildTask::Priority) priority--});

        // Ready to go. Good luck, have fun!
        Broodwar->sendText("gl hf");
    }

    // Called once at the end of a game.
    void KBot::onEnd(bool isWinner) {}

    // Called once for every execution of a logical frame in Broodwar.
    void KBot::onFrame() {
        // Return if the game is a replay or is paused
        if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
            return;

        // Display some debug information
        Broodwar->drawTextScreen(2, 0, "FPS: %d, APM: %d", Broodwar->getFPS(), Broodwar->getAPM());
        Broodwar->drawTextScreen(2, 10, "Scouted enemy positions: %d", m_enemy.getPositionCount());

        if (m_enemy.getPositionCount()) {
            const auto enemyPosition = m_enemy.getClosestPosition();
            Broodwar->drawTextScreen(2, 20, "Next enemy position: (%d, %d)", enemyPosition.x, enemyPosition.y);
        } else
            Broodwar->drawTextScreen(2, 20, "Next enemy position: Unknown");

        // Update manager
        m_manager.update();

        // Update general
        m_general.update();

        // Update enemy
        m_enemy.update();

        // ----- Prevent spamming -----------------------------------------------
        // Everything below is executed only occasionally and not on every frame.
        if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
            return;
    }

    // Called when the user attempts to send a text message.
    void KBot::onSendText(std::string text) {}

    // Called when the client receives a message from another Player.
    void KBot::onReceiveText(BWAPI::Player player, std::string text) {}

    // Called when a Player leaves the game.
    void KBot::onPlayerLeft(BWAPI::Player player) {}

    // Called when a Nuke has been launched somewhere on the map.
    void KBot::onNukeDetect(BWAPI::Position target) {}

    // Called when a Unit becomes accessible.
    void KBot::onUnitDiscover(BWAPI::Unit unit) {
        assert(unit->exists());
    }

    // Called when a Unit becomes inaccessible.
    void KBot::onUnitEvade(BWAPI::Unit unit) {
        assert(!unit->exists());
    }

    // Called when a previously invisible unit becomes visible.
    void KBot::onUnitShow(BWAPI::Unit unit) {
        assert(unit->exists());

        // Update enemy positions
        if (Broodwar->self()->isEnemy(unit->getPlayer()) && unit->getType().isBuilding())
            m_enemy.addPosition(TilePosition(unit->getPosition()));
    }

    // Called just as a visible unit is becoming invisible.
    void KBot::onUnitHide(BWAPI::Unit unit) {
        assert(!unit->exists()); // ???
    }

    // Called when any unit is created.
    void KBot::onUnitCreate(BWAPI::Unit unit) {
        assert(unit->exists());

        // My unit
        if (unit->getPlayer() == Broodwar->self()) {
            // Notify build tasks
            m_manager.buildTaskOnUnitCreatedOrMorphed(unit);
        }

    }

    // Called when a unit is removed from the game either through death or other means.
    void KBot::onUnitDestroy(BWAPI::Unit unit) {
        assert(!unit->exists());

        // My unit
        if (unit->getPlayer() == Broodwar->self()) {
            // Notify build tasks
            m_manager.buildTaskOnUnitDestroyed(unit);

            // Dispatch
            if (unit->getType().isBuilding() || unit->getType().isWorker() || unit->getType().isMineralField())
                m_manager.takeOwnership(unit);
            else
                m_general.takeOwnership(unit);
        }

        // Update BWEM information
        if (unit->getType().isMineralField())
            m_map.OnMineralDestroyed(unit);
        else if (unit->getType().isSpecialBuilding())
            m_map.OnStaticBuildingDestroyed(unit);
    }

    // Called when a unit changes its UnitType.
    void KBot::onUnitMorph(BWAPI::Unit unit) {
        // For example, when a Drone transforms into a Hatchery, a Siege Tank uses Siege Mode, or a Vespene Geyser receives a Refinery.
        assert(unit->exists());

        const auto type = unit->getType();
        Broodwar << type << std::endl; // DEBUG!

        // My unit
        if (unit->getPlayer() == Broodwar->self()) {
            // Notify build tasks
            m_manager.buildTaskOnUnitCreatedOrMorphed(unit);
        }
    }

    // Called when a unit changes ownership.
    void KBot::onUnitRenegade(BWAPI::Unit unit) {
        // This occurs when the Protoss ability Mind Control is used, or if a unit changes ownership in Use Map Settings.
        // TODO!
    }

    // Called when the state of the Broodwar game is saved to file.
    void KBot::onSaveGame(std::string gameName) {
        Broodwar << "The game was saved to \"" << gameName << "\"" << std::endl;
    }

    // Called when the state of a unit changes from incomplete to complete.
    void KBot::onUnitComplete(BWAPI::Unit unit) {
        assert(unit->exists());

        // My unit
        if (unit->getPlayer() == Broodwar->self()) {
            // Notify build tasks
            m_manager.buildTaskOnUnitCompleted(unit);

            // Dispatch ownership
            if (unit->getType().isBuilding() || unit->getType().isWorker())
                m_manager.giveOwnership(unit);
            else
                m_general.giveOwnership(unit);
        }
    }

} // namespace
<commit_msg>Removed debug code.<commit_after>#include "KBot.h"

#include "Squad.h"
#include "utils.h"

// Some ugly macro magic to get BUILDNUMBER as a string.
#pragma warning(push)
#pragma warning(disable: 4003) // there is some silly warning in VS2017
#define MACROSTR(S) #S ""
#define STRINGER(X) MACROSTR(X)
static const std::string buildNumber = STRINGER(BUILDNUMBER);
#pragma warning(pop)

namespace KBot {

    using namespace BWAPI;

    KBot::KBot() : m_manager(*this), m_general(*this), m_enemy(*this) {}

    // Called only once at the beginning of a game.
    void KBot::onStart() {
        if (Broodwar->isReplay() || !Broodwar->self())
            return;

        // Print build information
        Broodwar << "KBot build " << (buildNumber.size() ? buildNumber : "local") << std::endl;

        // This bot is written for Terran, so make sure we are indeed Terran!
        if (Broodwar->self()->getRace() != Races::Terran) {
            Broodwar << "Wrong race selected! KBot has to be Terran." << std::endl;
            Broodwar->leaveGame();
        }

        // This bot is written for one-on-one melee games.
        if (Broodwar->getGameType() != GameTypes::Melee) {
            Broodwar << "Unexpected game type. KBot might not work correctly." << std::endl;
            // Unfortunate, but no reason to leave.
        }

        // Set the command optimization level so that common commands can be grouped.
        Broodwar->setCommandOptimizationLevel(2);

        // BWEM map initialization
        m_map.Initialize();
        m_map.EnableAutomaticPathAnalysis();
        const bool r = m_map.FindBasesForStartingLocations();
        assert(r);

        // Test BuildTask, TODO: Replace hardcoded build order
        // http://wiki.teamliquid.net/starcraft/2_Rax_FE_(vs._Zerg)
        using namespace UnitTypes;
        const auto buildorder = {
            Terran_SCV, Terran_SCV, Terran_SCV, Terran_SCV, Terran_SCV, Terran_Supply_Depot, // @ 9/10 supply
            Terran_SCV, Terran_SCV, Terran_Barracks, // @ 11/18 supply
            Terran_SCV, Terran_SCV, Terran_Barracks, // @ 13/18 supply
            Terran_SCV, Terran_Supply_Depot, // @ 14/18 supply
            Terran_SCV, Terran_Marine, Terran_SCV, Terran_Marine, Terran_Refinery, // @ 18/26 supply
            Terran_SCV, Terran_Marine, Terran_SCV, Terran_Marine, Terran_Academy, // @ 22/26 supply
            Terran_SCV, Terran_Marine, Terran_Supply_Depot // @ 24/26 supply
        };

        int priority = (int) BuildTask::Priority::buildorder;
        for (const auto &unit : buildorder)
            m_manager.addBuildTask({m_manager, unit, (BuildTask::Priority) priority--});

        // Ready to go. Good luck, have fun!
        Broodwar->sendText("gl hf");
    }

    // Called once at the end of a game.
    void KBot::onEnd(bool isWinner) {}

    // Called once for every execution of a logical frame in Broodwar.
    void KBot::onFrame() {
        // Return if the game is a replay or is paused
        if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
            return;

        // Display some debug information
        Broodwar->drawTextScreen(2, 0, "FPS: %d, APM: %d", Broodwar->getFPS(), Broodwar->getAPM());
        Broodwar->drawTextScreen(2, 10, "Scouted enemy positions: %d", m_enemy.getPositionCount());

        if (m_enemy.getPositionCount()) {
            const auto enemyPosition = m_enemy.getClosestPosition();
            Broodwar->drawTextScreen(2, 20, "Next enemy position: (%d, %d)", enemyPosition.x, enemyPosition.y);
        } else
            Broodwar->drawTextScreen(2, 20, "Next enemy position: Unknown");

        // Update manager
        m_manager.update();

        // Update general
        m_general.update();

        // Update enemy
        m_enemy.update();

        // ----- Prevent spamming -----------------------------------------------
        // Everything below is executed only occasionally and not on every frame.
        if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
            return;
    }

    // Called when the user attempts to send a text message.
    void KBot::onSendText(std::string text) {}

    // Called when the client receives a message from another Player.
    void KBot::onReceiveText(BWAPI::Player player, std::string text) {}

    // Called when a Player leaves the game.
    void KBot::onPlayerLeft(BWAPI::Player player) {}

    // Called when a Nuke has been launched somewhere on the map.
    void KBot::onNukeDetect(BWAPI::Position target) {}

    // Called when a Unit becomes accessible.
    void KBot::onUnitDiscover(BWAPI::Unit unit) {
        assert(unit->exists());
    }

    // Called when a Unit becomes inaccessible.
    void KBot::onUnitEvade(BWAPI::Unit unit) {
        assert(!unit->exists());
    }

    // Called when a previously invisible unit becomes visible.
    void KBot::onUnitShow(BWAPI::Unit unit) {
        assert(unit->exists());

        // Update enemy positions
        if (Broodwar->self()->isEnemy(unit->getPlayer()) && unit->getType().isBuilding())
            m_enemy.addPosition(TilePosition(unit->getPosition()));
    }

    // Called just as a visible unit is becoming invisible.
    void KBot::onUnitHide(BWAPI::Unit unit) {
        assert(!unit->exists()); // ???
    }

    // Called when any unit is created.
    void KBot::onUnitCreate(BWAPI::Unit unit) {
        assert(unit->exists());

        // My unit
        if (unit->getPlayer() == Broodwar->self()) {
            // Notify build tasks
            m_manager.buildTaskOnUnitCreatedOrMorphed(unit);
        }

    }

    // Called when a unit is removed from the game either through death or other means.
    void KBot::onUnitDestroy(BWAPI::Unit unit) {
        assert(!unit->exists());

        // My unit
        if (unit->getPlayer() == Broodwar->self()) {
            // Notify build tasks
            m_manager.buildTaskOnUnitDestroyed(unit);

            // Dispatch
            if (unit->getType().isBuilding() || unit->getType().isWorker() || unit->getType().isMineralField())
                m_manager.takeOwnership(unit);
            else
                m_general.takeOwnership(unit);
        }

        // Update BWEM information
        if (unit->getType().isMineralField())
            m_map.OnMineralDestroyed(unit);
        else if (unit->getType().isSpecialBuilding())
            m_map.OnStaticBuildingDestroyed(unit);
    }

    // Called when a unit changes its UnitType.
    void KBot::onUnitMorph(BWAPI::Unit unit) {
        // For example, when a Drone transforms into a Hatchery, a Siege Tank uses Siege Mode, or a Vespene Geyser receives a Refinery.
        assert(unit->exists());

        // My unit
        if (unit->getPlayer() == Broodwar->self()) {
            // Notify build tasks
            m_manager.buildTaskOnUnitCreatedOrMorphed(unit);
        }
    }

    // Called when a unit changes ownership.
    void KBot::onUnitRenegade(BWAPI::Unit unit) {
        // This occurs when the Protoss ability Mind Control is used, or if a unit changes ownership in Use Map Settings.
        // TODO!
    }

    // Called when the state of the Broodwar game is saved to file.
    void KBot::onSaveGame(std::string gameName) {
        Broodwar << "The game was saved to \"" << gameName << "\"" << std::endl;
    }

    // Called when the state of a unit changes from incomplete to complete.
    void KBot::onUnitComplete(BWAPI::Unit unit) {
        assert(unit->exists());

        // My unit
        if (unit->getPlayer() == Broodwar->self()) {
            // Notify build tasks
            m_manager.buildTaskOnUnitCompleted(unit);

            // Dispatch ownership
            if (unit->getType().isBuilding() || unit->getType().isWorker())
                m_manager.giveOwnership(unit);
            else
                m_general.giveOwnership(unit);
        }
    }

} // namespace
<|endoftext|>


<commit_before>#include "MemoryManager.h"
#include "LuaManager.h"
#include "MongoManager.h"
#include "CliArgs.h"
#include <iostream> //getline
//#include <conio.h> //_kbhit

#define LUA_DB_VERSION "0.1.0.0"

int run(int argc, char* argv[]) {
	CliArgs args;
	CliArgs::parse(argc, argv, &args);
	const String uri = MongoManager::getUri(args.host, args.port);

	args.database = "test";

	printf("LuaDB shell version: %s\n", LUA_DB_VERSION);
	if (args.database.size()) {
		printf("Connecting to : %s/%s\n", uri.c_str(), args.database.c_str());
	}
	else {
		printf("Connecting to : %s\n", uri.c_str());
	}

	LuaManager *pLua = LuaManager::getInstance();

	bson_t reply;
	if (!pLua->getMongo()->connect(uri, &reply)) {
		printf("Error: couldn't connect to server, connection attempt failed\n");
		return -1;
	}

	bson_iter_t it;
	if (bson_iter_init_find(&it, &reply, "version")) {
		printf("MongoDB server version: %s\n", bson_iter_utf8(&it, nullptr));
	}
	bson_destroy(&reply);

	if (args.database.size()) {
		pLua->useDatabase(args.database);
	}

	pLua->loadFile("../test/test_bsonTypes.lua");
	pLua->loadFile("../test/test_crud.lua");
	//pLua->loadFile("../test/performance.lua");

	if (args.files.size()) {
		for (int i = 0; i < args.files.size(); ++i) {
			printf("\nLoading file: %s\n\n", args.files[i].c_str());
			pLua->loadFile(args.files[i]);
		}
		if (args.shell) {
			printf("\n");
		}
		pLua->setIsRunning(args.shell);
	}

	if (pLua->isRunning()) {
		printf("Type \"help()\" for help\n");
		while (pLua->isRunning()) {
			printf("> ");
			String commandStr;
			String inputStr;
			if (std::getline(std::cin, inputStr)) {
				commandStr += inputStr;
//				while (_kbhit()) {
//					printf("... ");
//					std::getline(std::cin, inputStr);
//					commandStr += inputStr + "\n";
//				}
			}
			if (!commandStr.empty()) {
				pLua->loadString(commandStr.c_str());
			}
		}
	}

	return 0;
}

int main(int argc, char* argv[]) {
	run(argc, argv);
	LuaManager::destroyInstance();
	#ifdef DEBUG
		if (MemoryManager::getInstance()->hasLeak()) {
			printf("\n");
			MemoryManager::getInstance()->displayInfo();
			getchar();
			return 1;
		}
	#endif
	return 0;
}<commit_msg>removed test files are always run<commit_after>#include "MemoryManager.h"
#include "LuaManager.h"
#include "MongoManager.h"
#include "CliArgs.h"
#include <iostream> //getline
//#include <conio.h> //_kbhit

#define LUA_DB_VERSION "0.1.0.0"

int run(int argc, char* argv[]) {
	CliArgs args;
	CliArgs::parse(argc, argv, &args);
	const String uri = MongoManager::getUri(args.host, args.port);

	args.database = "test";

	printf("LuaDB shell version: %s\n", LUA_DB_VERSION);
	if (args.database.size()) {
		printf("Connecting to : %s/%s\n", uri.c_str(), args.database.c_str());
	}
	else {
		printf("Connecting to : %s\n", uri.c_str());
	}

	LuaManager *pLua = LuaManager::getInstance();

	bson_t reply;
	if (!pLua->getMongo()->connect(uri, &reply)) {
		printf("Error: couldn't connect to server, connection attempt failed\n");
		return -1;
	}

	bson_iter_t it;
	if (bson_iter_init_find(&it, &reply, "version")) {
		printf("MongoDB server version: %s\n", bson_iter_utf8(&it, nullptr));
	}
	bson_destroy(&reply);

	if (args.database.size()) {
		pLua->useDatabase(args.database);
	}

//	pLua->loadFile("../test/test_bsonTypes.lua");
//	pLua->loadFile("../test/test_crud.lua");
	//pLua->loadFile("../test/performance.lua");

	if (args.files.size()) {
		for (int i = 0; i < args.files.size(); ++i) {
			printf("\nLoading file: %s\n\n", args.files[i].c_str());
			pLua->loadFile(args.files[i]);
		}
		if (args.shell) {
			printf("\n");
		}
		pLua->setIsRunning(args.shell);
	}

	if (pLua->isRunning()) {
		printf("Type \"help()\" for help\n");
		while (pLua->isRunning()) {
			printf("> ");
			String commandStr;
			String inputStr;
			if (std::getline(std::cin, inputStr)) {
				commandStr += inputStr;
//				while (_kbhit()) {
//					printf("... ");
//					std::getline(std::cin, inputStr);
//					commandStr += inputStr + "\n";
//				}
			}
			if (!commandStr.empty()) {
				pLua->loadString(commandStr.c_str());
			}
		}
	}

	return 0;
}

int main(int argc, char* argv[]) {
	run(argc, argv);
	LuaManager::destroyInstance();
	#ifdef DEBUG
		if (MemoryManager::getInstance()->hasLeak()) {
			printf("\n");
			MemoryManager::getInstance()->displayInfo();
			getchar();
			return 1;
		}
	#endif
	return 0;
}<|endoftext|>


<commit_before>#include "ObjParser.hpp"
#include "Shaders.hpp"
#include "Viewer.hpp"

#include <GL/freeglut.h>

#include <iostream>
#include <string>

int main(int argc, char** argv) {
	if (argc == 1) {
		std::cout << "Usage: obj-viewer FILE" << std::endl;
		return -1;
	}

	std::cout << std::string(argv[0]) << std::endl;

	std::string file = std::string(argv[1]);

	ObjParser parser(file);

	Viewer viewer("Model Viewer", 1024, 768);

	ModelPtr model = parser.parseObj();
	viewer.setModel(model);

	viewer.initGlut(argc, argv);
	viewer.initGl();

	std::string prefix = std::string(INSTALL_PREFIX) + "/share/obj-viewer/shaders";
	std::string vsFile = prefix + "/lambertian.vs";
	std::string fsFile = prefix + "/lambertian.fs";

	ShadersPtr shaders = ShadersPtr(new Shaders(vsFile, fsFile));
	shaders->setSamplerName("texMap");

	model->loadTextures();
	model->compileLists();
	model->setShaders(shaders);

	Viewer::setInstance(&viewer);

	viewer.start();

	return 0;
}
<commit_msg>Removed extraneous print statement.<commit_after>#include "ObjParser.hpp"
#include "Shaders.hpp"
#include "Viewer.hpp"

#include <GL/freeglut.h>

#include <iostream>
#include <string>

int main(int argc, char** argv) {
	if (argc == 1) {
		std::cout << "Usage: obj-viewer FILE" << std::endl;
		return -1;
	}

	std::string file = std::string(argv[1]);

	ObjParser parser(file);

	Viewer viewer("Model Viewer", 1024, 768);

	ModelPtr model = parser.parseObj();
	viewer.setModel(model);

	viewer.initGlut(argc, argv);
	viewer.initGl();

	std::string prefix = std::string(INSTALL_PREFIX) + "/share/obj-viewer/shaders";
	std::string vsFile = prefix + "/lambertian.vs";
	std::string fsFile = prefix + "/lambertian.fs";

	ShadersPtr shaders = ShadersPtr(new Shaders(vsFile, fsFile));
	shaders->setSamplerName("texMap");

	model->loadTextures();
	model->compileLists();
	model->setShaders(shaders);

	Viewer::setInstance(&viewer);

	viewer.start();

	return 0;
}
<|endoftext|>


<commit_before>//
//  Main.cpp
//  Addie
//
//  Created by Joachim Wester on 22/04/16.
//  Copyright © 2016 Joachim Wester, Starcounter AB.
//
#include "Helpers.h"

#include "Reader.hpp"
#include <iostream>
#include "../tests/TestHashTrie.hpp"
#include "Compiler.hpp"
#include "Interpreter.hpp"

VALUE IllustrateParse( const char* str ) {
    std::cout << "\n**** Parsing ****\n" << str << "\n";
    std::cout << "===>\n";

    auto teststr = StringReader(str,strlen(str));
    VALUE v = Parser::ParseForm( &teststr );
    std::cout << v.Print();
    std::cout << "\n\n";
    return v;
}

VALUE TestParse( const char* input, const char* expectedOutput ) {
    VALUE v = IllustrateParse( input );
    const char* output = v.Print().c_str();;
    assert( strcmp( expectedOutput, output ) == 0 );
    return v;
}

int main(int argc, const char * argv[]) {

    Isolate isolate;
    CurrentIsolate = &isolate;

    assert( sizeof(VALUE) == sizeof(uintptr_t) ); // If we are on a 64 bit machine we want 64
                                                  // bit values
    assert( sizeof(Instruction) == 4 );           // Our byte instructions are 32 bit

//    IllustrateParse( "[]" );
    TestParse( "﹇﹈","[]");
    TestParse( "⎴ ⎵ ","[]");
    TestParse( "⏜⏝","()");
//    TestParse( "⏞ ⏟","{}");
//    TestParse("︷ ︸","{}");
    IllustrateParse( "\"Jack Gök Wester\"" );
    IllustrateParse("(\"Jack\" \"Wester\")");
    IllustrateParse( "⏜\nif (= einstein genius)\n  (print \"e=mc²\")\n  (print \"e!=mc²\")\n⏝" );

    VALUE v = TestParse("⏜\n   ⏜\n   defn pow [n] \n      ⏜\n      fn [x]\n         (apply * (repeat n x))\n      ⏝\n   ⏝\n   (def ² (pow 2))\n   (def ³ (pow 3))\n⏝",
          "((defn pow [n[n] (fn [x[x] (apply * (repeat n x)))) (def ² (pow 2)) (def ³ (pow 3)))"

                        );

    v = IllustrateParse("⏜\nlet ﹇\n    a 10\n    b 20\n    ﹈\n    (print (+ a b))\n⏝");

    Compilation* code = Compiler::Compile( v );
    STRINGOLD str = Compiler::Disassemble(code);

    std::cout << str.ToString();

    Continuation c = Interpreter::Interpret(code);

    // str = Compiler::Disassemble(code);

    //std::cout << str.ToString();

    Interpreter::Interpret(c);
    std::cout << "\n\n";

}<commit_msg>Cleanup<commit_after>//
//  Main.cpp
//  Addie
//
//  Created by Joachim Wester on 22/04/16.
//  Copyright © 2016 Joachim Wester, Starcounter AB.
//
#include "Helpers.h"

#include "Reader.hpp"
#include <iostream>
#include "Compiler.hpp"
#include "Interpreter.hpp"

VALUE IllustrateParse( const char* str ) {
    std::cout << "\n**** Parsing ****\n" << str << "\n";
    std::cout << "===>\n";

    auto teststr = StringReader(str,strlen(str));
    VALUE v = Parser::ParseForm( &teststr );
    std::cout << v.Print();
    std::cout << "\n";
    return v;
}

VALUE TestParse( const char* input, const char* expectedOutput ) {
    VALUE v = IllustrateParse( input );
    const char* output = v.Print().c_str();;
    assert( strcmp( expectedOutput, output ) == 0 );
    return v;
}

int main(int argc, const char * argv[]) {

    Isolate isolate;
    CurrentIsolate = &isolate;

    assert( sizeof(VALUE) == sizeof(uintptr_t) ); // If we are on a 64 bit machine we want 64
                                                  // bit values
    assert( sizeof(Instruction) == 4 );           // Our byte instructions are 32 bit

//    IllustrateParse( "[]" );
    TestParse( "﹇﹈","[]");
    TestParse( "⎴ ⎵ ","[]");
    TestParse( "⏜⏝","()");
//    TestParse( "⏞ ⏟","{}");
//    TestParse("︷ ︸","{}");
    TestParse( "\"Jack Gök Wester\"", "\"Jack Gök Wester\"" );
    TestParse("(\"Jack\" \"Wester\")","(\"Jack\" \"Wester\")");
    TestParse( "⏜\nif (= einstein genius)\n  (print \"e=mc²\")\n  (print \"e!=mc²\")\n⏝",
                    "(if (= einstein genius) (print \"e=mc²\") (print \"e!=mc²\"))");

    VALUE v = TestParse("⏜\n   ⏜\n   defn pow [n] \n      ⏜\n      fn [x]\n         (apply * (repeat n x))\n      ⏝\n   ⏝\n   (def ² (pow 2))\n   (def ³ (pow 3))\n⏝",
          "((defn pow [n[n] (fn [x[x] (apply * (repeat n x)))) (def ² (pow 2)) (def ³ (pow 3)))"

                        );

    v = TestParse("⏜\nlet ﹇\n    a 10\n    b 20\n    ﹈\n    (print (+ a b))\n⏝",
                  "(let [a 10 b 20] (print (+ a b)))");

    Compilation* code = Compiler::Compile( v );
    STRINGOLD str = Compiler::Disassemble(code);

    std::cout << str.ToString();

    Continuation c = Interpreter::Interpret(code);

    // str = Compiler::Disassemble(code);

    //std::cout << str.ToString();

    Interpreter::Interpret(c);
    std::cout << "\n\n";

}<|endoftext|>


<commit_before>/*
   Copyright (c) 2010 Aldo J. Nunez

   Licensed under the Apache License, Version 2.0.
   See the LICENSE text file for details.
*/

#include "Common.h"
#include "DecodeX86.h"

struct Prefixes32
{
    bool    AddressSize;    // 67
    bool    OperandSize;    // 66
    bool    Lock;           // F0
    bool    RepF2;          // F2
    bool    RepF3;          // F3
    bool    Cs;             // 2E
    bool    Ds;             // 3E
    bool    Es;             // 26
    bool    Fs;             // 64
    bool    Gs;             // 65
    bool    Ss;             // 36
};

union RexPrefix
{
    struct
    {
        bool    B : 1;
        bool    X : 1;
        bool    R : 1;
        bool    W : 1;
        uint8_t RexConst : 4;
    } Bits;
    uint8_t Byte;
};

struct Prefixes64
{
    RexPrefix   Rex;
};

struct Prefixes
{
    Prefixes32  Pre32;
    Prefixes64  Pre64;
};

// number of prefixes
static int ReadPrefixes( uint8_t* mem, int memLen, CpuSizeMode mode, Prefixes& prefixes )
{
    _ASSERT( (mode == Cpu_32) || (mode == Cpu_64) );

    int i;

    for ( i = 0; i < memLen; i++ )
    {
        bool    found = false;

        switch ( mem[i] )
        {
        case 0x67:  prefixes.Pre32.AddressSize = true; break;
        case 0x66:  prefixes.Pre32.OperandSize = true; break;
        case 0xF0:  prefixes.Pre32.Lock = true; break;
        case 0xF2:  prefixes.Pre32.RepF2 = true; break;
        case 0xF3:  prefixes.Pre32.RepF3 = true; break;
        case 0x2E:  prefixes.Pre32.Cs = true; break;
        case 0x3E:  prefixes.Pre32.Ds = true; break;
        case 0x26:  prefixes.Pre32.Es = true; break;
        case 0x64:  prefixes.Pre32.Fs = true; break;
        case 0x65:  prefixes.Pre32.Gs = true; break;
        case 0x36:  prefixes.Pre32.Ss = true; break;
        default:
            if ( mode == Cpu_64 )
            {
                if ( (mem[i] >= 0x40) && (mem[i] <= 0x4F) )
                {
                    found = true;
                    prefixes.Pre64.Rex.Byte = mem[i];
                }
            }

            if ( !found )
                return i;
            break;
        }
    }

    return i;
}

static int GetModRmSize16( uint8_t modRm )
{
    int     instSize = 1;       // already includes modRm byte
    BYTE    mod = (modRm >> 6) & 3;
    BYTE    rm = (modRm & 7);

    // mod == 3 is only for single direct register values
    if ( mod != 3 )
    {
        if ( mod == 2 )
            instSize += 2;      // disp16
        else if ( mod == 1 )
            instSize += 1;      // disp8

        if ( (mod == 0) && (rm == 6) )
            instSize += 2;      // disp16
    }

    return instSize;
}

static int GetModRmSize32( uint8_t modRm )
{
    int     instSize = 1;       // already includes modRm byte
    BYTE    mod = (modRm >> 6) & 3;
    BYTE    rm = (modRm & 7);

    // mod == 3 is only for single direct register values
    if ( mod != 3 )
    {
        if ( rm == 4 )
            instSize += 1;      // SIB

        if ( mod == 2 )
            instSize += 4;      // disp32
        else if ( mod == 1 )
            instSize += 1;      // disp8

        if ( (mod == 0) && (rm == 5) )
            instSize += 4;      // disp32
    }

    return instSize;
}

InstructionType GetInstructionTypeAndSize( uint8_t* mem, int memLen, CpuSizeMode mode, int& size )
{
    _ASSERT( (mode == Cpu_32) || (mode == Cpu_64) );

    InstructionType type = Inst_Other;
    int             instSize = 0;
    int             remSize = 0;
    int             prefixSize = 0;
    Prefixes        prefixes = { 0 };

    if ( memLen > MAX_INSTRUCTION_SIZE )
        memLen = MAX_INSTRUCTION_SIZE;

    prefixSize = ReadPrefixes( mem, memLen, mode, prefixes );
    if ( prefixSize >= memLen )
        return Inst_None;

    remSize = memLen - prefixSize;

    switch ( mem[0] )
    {
    case 0xCC:
        instSize = 1;
        type = Inst_Breakpoint;
        break;

        // call instructions
    case 0xE8:
        if ( prefixes.Pre32.OperandSize && (mode == Cpu_32) )
            instSize = 3;
        else
            instSize = 5;

        if ( instSize > 0 )
            type = Inst_Call;
        break;

    case 0x9A:
        if ( mode == Cpu_32 )
        {
            if ( prefixes.Pre32.OperandSize )
                instSize = 5;
            else
                instSize = 7;
        }

        if ( instSize > 0 )
            type = Inst_Call;
        break;

        // call or jmp instructions
    case 0xFF:
        {
            if ( remSize < 2 )
                break;

            BYTE    regOp = (mem[1] >> 3) & 7;
            if ( (regOp == 2) || (regOp == 3) )
            {
                if ( (mode == Cpu_64) || !prefixes.Pre32.AddressSize )
                    instSize = 1 + GetModRmSize32( mem[1] );
                else
                    instSize = 1 + GetModRmSize16( mem[1] );

                if ( instSize > 0 )
                    type = Inst_Call;
            }
            else if ( (regOp == 4) || (regOp == 5) )
            {
                if ( (mode == Cpu_64) || !prefixes.Pre32.AddressSize )
                    instSize = 1 + GetModRmSize32( mem[1] );
                else
                    instSize = 1 + GetModRmSize16( mem[1] );

                type = Inst_Jmp;
            }
        }
        break;

        // jmp instructions
    case 0xEB:
        instSize = 2;
        type = Inst_Jmp;
        break;

    case 0xE9:
        if ( prefixes.Pre32.OperandSize && (mode == Cpu_32) )
            instSize = 3;
        else
            instSize = 5;
        type = Inst_Jmp;
        break;

    case 0xEA:
        if ( mode == Cpu_32 )
        {
            if ( prefixes.Pre32.OperandSize )
                instSize = 5;
            else
                instSize = 7;
            type = Inst_Jmp;
        }
        break;

        // system call instructions
    case 0x0F:
        if ( remSize < 2 )
            break;
        if ( (mem[1] == 0x05) || (mem[1] == 0x34) )
            instSize = 2;

        if ( instSize > 0 )
            type = Inst_Syscall;
        break;

    default:
        // rep prefixed instructions
        if ( remSize < 2 )
            break;

        if ( prefixes.Pre32.RepF2 )
        {
            if ( (mem[1] == 0xA6) || (mem[1] == 0xA7) || (mem[1] == 0xAE) || (mem[1] == 0xAF) )
                instSize = 2;
        }
        else if ( prefixes.Pre32.RepF3 )
        {
            if ( ((mem[1] >= 0x6C) && (mem[1] <= 0x6F))
                || ((mem[1] >= 0xA4) && (mem[1] <= 0xA7))
                || ((mem[1] >= 0xAA) && (mem[1] <= 0xAF)) )
                instSize = 2;
        }

        if ( instSize > 0 )
            type = Inst_RepString;
        break;
    }

    // sanity check, is it longer than available memory?
    if ( instSize > memLen )
        return Inst_None;

    size = instSize;

    return type;
}
<commit_msg>Step over in 64-bit mode wasn't working, because calls weren't being recognized.<commit_after>/*
   Copyright (c) 2010 Aldo J. Nunez

   Licensed under the Apache License, Version 2.0.
   See the LICENSE text file for details.
*/

#include "Common.h"
#include "DecodeX86.h"

struct Prefixes32
{
    bool    AddressSize;    // 67
    bool    OperandSize;    // 66
    bool    Lock;           // F0
    bool    RepF2;          // F2
    bool    RepF3;          // F3
    bool    Cs;             // 2E
    bool    Ds;             // 3E
    bool    Es;             // 26
    bool    Fs;             // 64
    bool    Gs;             // 65
    bool    Ss;             // 36
};

union RexPrefix
{
    struct
    {
        bool    B : 1;
        bool    X : 1;
        bool    R : 1;
        bool    W : 1;
        uint8_t RexConst : 4;
    } Bits;
    uint8_t Byte;
};

struct Prefixes64
{
    RexPrefix   Rex;
};

struct Prefixes
{
    Prefixes32  Pre32;
    Prefixes64  Pre64;
};

// number of prefixes
static int ReadPrefixes( uint8_t* mem, int memLen, CpuSizeMode mode, Prefixes& prefixes )
{
    _ASSERT( (mode == Cpu_32) || (mode == Cpu_64) );

    int i;

    for ( i = 0; i < memLen; i++ )
    {
        bool    found = false;

        switch ( mem[i] )
        {
        case 0x67:  prefixes.Pre32.AddressSize = true; break;
        case 0x66:  prefixes.Pre32.OperandSize = true; break;
        case 0xF0:  prefixes.Pre32.Lock = true; break;
        case 0xF2:  prefixes.Pre32.RepF2 = true; break;
        case 0xF3:  prefixes.Pre32.RepF3 = true; break;
        case 0x2E:  prefixes.Pre32.Cs = true; break;
        case 0x3E:  prefixes.Pre32.Ds = true; break;
        case 0x26:  prefixes.Pre32.Es = true; break;
        case 0x64:  prefixes.Pre32.Fs = true; break;
        case 0x65:  prefixes.Pre32.Gs = true; break;
        case 0x36:  prefixes.Pre32.Ss = true; break;
        default:
            if ( mode == Cpu_64 )
            {
                if ( (mem[i] >= 0x40) && (mem[i] <= 0x4F) )
                {
                    found = true;
                    prefixes.Pre64.Rex.Byte = mem[i];
                }
            }

            if ( !found )
                return i;
            break;
        }
    }

    return i;
}

static int GetModRmSize16( uint8_t modRm )
{
    int     instSize = 1;       // already includes modRm byte
    BYTE    mod = (modRm >> 6) & 3;
    BYTE    rm = (modRm & 7);

    // mod == 3 is only for single direct register values
    if ( mod != 3 )
    {
        if ( mod == 2 )
            instSize += 2;      // disp16
        else if ( mod == 1 )
            instSize += 1;      // disp8

        if ( (mod == 0) && (rm == 6) )
            instSize += 2;      // disp16
    }

    return instSize;
}

static int GetModRmSize32( uint8_t modRm )
{
    int     instSize = 1;       // already includes modRm byte
    BYTE    mod = (modRm >> 6) & 3;
    BYTE    rm = (modRm & 7);

    // mod == 3 is only for single direct register values
    if ( mod != 3 )
    {
        if ( rm == 4 )
            instSize += 1;      // SIB

        if ( mod == 2 )
            instSize += 4;      // disp32
        else if ( mod == 1 )
            instSize += 1;      // disp8

        if ( (mod == 0) && (rm == 5) )
            instSize += 4;      // disp32
    }

    return instSize;
}

InstructionType GetInstructionTypeAndSize( uint8_t* mem, int memLen, CpuSizeMode mode, int& size )
{
    _ASSERT( (mode == Cpu_32) || (mode == Cpu_64) );

    InstructionType type = Inst_Other;
    int             instSize = 0;
    int             remSize = 0;
    int             prefixSize = 0;
    Prefixes        prefixes = { 0 };

    if ( memLen > MAX_INSTRUCTION_SIZE )
        memLen = MAX_INSTRUCTION_SIZE;

    prefixSize = ReadPrefixes( mem, memLen, mode, prefixes );
    if ( prefixSize >= memLen )
        return Inst_None;

    remSize = memLen - prefixSize;

    // now that we've considered prefixes, change the base to where the opcode begins
    mem = &mem[prefixSize];

    switch ( mem[0] )
    {
    case 0xCC:
        instSize = 1;
        type = Inst_Breakpoint;
        break;

        // call instructions
    case 0xE8:
        if ( prefixes.Pre32.OperandSize && (mode == Cpu_32) )
            instSize = 3;
        else
            instSize = 5;

        if ( instSize > 0 )
            type = Inst_Call;
        break;

    case 0x9A:
        if ( mode == Cpu_32 )
        {
            if ( prefixes.Pre32.OperandSize )
                instSize = 5;
            else
                instSize = 7;
        }

        if ( instSize > 0 )
            type = Inst_Call;
        break;

        // call or jmp instructions
    case 0xFF:
        {
            if ( remSize < 2 )
                break;

            BYTE    regOp = (mem[1] >> 3) & 7;
            if ( (regOp == 2) || (regOp == 3) )
            {
                if ( (mode == Cpu_64) || !prefixes.Pre32.AddressSize )
                    instSize = 1 + GetModRmSize32( mem[1] );
                else
                    instSize = 1 + GetModRmSize16( mem[1] );

                if ( instSize > 0 )
                    type = Inst_Call;
            }
            else if ( (regOp == 4) || (regOp == 5) )
            {
                if ( (mode == Cpu_64) || !prefixes.Pre32.AddressSize )
                    instSize = 1 + GetModRmSize32( mem[1] );
                else
                    instSize = 1 + GetModRmSize16( mem[1] );

                type = Inst_Jmp;
            }
        }
        break;

        // jmp instructions
    case 0xEB:
        instSize = 2;
        type = Inst_Jmp;
        break;

    case 0xE9:
        if ( prefixes.Pre32.OperandSize && (mode == Cpu_32) )
            instSize = 3;
        else
            instSize = 5;
        type = Inst_Jmp;
        break;

    case 0xEA:
        if ( mode == Cpu_32 )
        {
            if ( prefixes.Pre32.OperandSize )
                instSize = 5;
            else
                instSize = 7;
            type = Inst_Jmp;
        }
        break;

        // system call instructions
    case 0x0F:
        if ( remSize < 2 )
            break;
        if ( (mem[1] == 0x05) || (mem[1] == 0x34) )
            instSize = 2;

        if ( instSize > 0 )
            type = Inst_Syscall;
        break;

    default:
        // rep prefixed instructions
        if ( remSize < 2 )
            break;

        if ( prefixes.Pre32.RepF2 )
        {
            if ( (mem[1] == 0xA6) || (mem[1] == 0xA7) || (mem[1] == 0xAE) || (mem[1] == 0xAF) )
                instSize = 2;
        }
        else if ( prefixes.Pre32.RepF3 )
        {
            if ( ((mem[1] >= 0x6C) && (mem[1] <= 0x6F))
                || ((mem[1] >= 0xA4) && (mem[1] <= 0xA7))
                || ((mem[1] >= 0xAA) && (mem[1] <= 0xAF)) )
                instSize = 2;
        }

        if ( instSize > 0 )
            type = Inst_RepString;
        break;
    }

    // sanity check, is it longer than available memory?
    if ( instSize > memLen )
        return Inst_None;

    size = instSize + prefixSize;

    return type;
}
<|endoftext|>


<commit_before>#include "YuanSu.h"
#include "..\GameGrail.h"
#include "..\UserTask.h"

YuanSu::YuanSu(GameGrail *engine, int id, int color): PlayerEntity(engine, id, color)
{
	tokenMax[0] = 3;
}

int YuanSu::v_magic_skill(Action* action)
{
	int actionID = action->action_id();
	int cardID, cardID2;
	int playerID = action->src_id();
	CardEntity* card, *card2;
	PlayerEntity* dst;

	if(playerID != id){
		return GE_INVALID_PLAYERID;
	}

	switch (actionID)
	{
	case FENG_REN:
	case BING_DONG:
	case HUO_QIU:
	case YUN_SHI:
	case LEI_JI:
		cardID = action->card_ids(0);
		card = getCardByID(cardID);
		dst = engine->getPlayerEntity(action->dst_ids(0));
		//Լ                          || ǶӦԪ
		if(GE_SUCCESS != checkOneHandCard(cardID) || !card->checkSpeciality(actionID)){
			return GE_INVALID_ACTION;
		}
		if (action->card_ids_size() > 1)
		{
			cardID2 = action->card_ids(1);
			card2 = getCardByID(cardID2);
			if (card->getElement() != card2->getElement() || GE_SUCCESS != checkOneHandCard(cardID))
				return GE_INVALID_ACTION;
		}
		if (actionID == BING_DONG && action->dst_ids_size() < 2)
			// Ҫ2Ŀ
			return GE_INVALID_ACTION;

		break;
	case YUAN_SU_DIAN_RAN:
		dst = engine->getPlayerEntity(action->dst_ids(0));
		if (token[0] != tokenMax[0])
			return GE_INVALID_ACTION;
		break;
	case YUE_GUANG:
		dst = engine->getPlayerEntity(action->dst_ids(0));
		if (gem == 0)
			return GE_INVALID_ACTION;
		break;
	default:
		return GE_INVALID_ACTION;
	}

	return GE_SUCCESS;
}

int YuanSu::p_magic_skill(int &step, Action *action)
{
	int ret;
	switch(action->action_id())
	{
	case FENG_REN:
		ret = FengRen(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	case BING_DONG:
		ret = BingDong(step, action);
		if (GE_URGENT == ret){
			// 2ϣ˺ͼ
			step = BING_DONG;
		}
		else if (GE_SUCCESS == ret){
			step = STEP_DONE;
		}
		break;
	case HUO_QIU:
		ret = HuoQiu(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	case YUN_SHI:
		ret = YunShi(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	case LEI_JI:
		ret = LeiJi(step, action);
		if (GE_URGENT == ret){
			// ۼƴ2ϣ˺ͼӱʯ
			step = LEI_JI;
		}
		else if (GE_SUCCESS == ret){
			step = STEP_DONE;
		}
		break;
	case YUAN_SU_DIAN_RAN:
		ret = YuanSuDianRan(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	case YUE_GUANG:
		ret = YueGuang(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	default:
		return GE_INVALID_ACTION;
	}

	return ret;
}

// Ԫ
int YuanSu::p_timeline_3(int &step, CONTEXT_TIMELINE_3 *con)
{
	//  Լɵ˺        && ħ˺                     && Ԫصȼɵ˺
	if (con->harm.srcID == id && con->harm.type == HARM_MAGIC && con->harm.cause != YUAN_SU_DIAN_RAN)
	{
		SkillMsg skill_msg;
		Coder::skillNotice(id, id, YUAN_SU_XI_SHOU, skill_msg);
		engine->sendMessage(-1, MSG_SKILL, skill_msg);

		setToken(0, getToken(0)+1);
		GameInfo game_info;
		Coder::tokenNotice(id, 0, getToken(0), game_info);
		engine->sendMessage(-1, MSG_GAME, game_info);
	}
	return GE_SUCCESS;
}

int YuanSu::YunShi(Action *action)
{
	// һħж˺ǰͺһΪ˷㣬Է˺ǰ
	addAction(ACTION_MAGIC, YUN_SHI);
	return YuanSuDamage(action);
}

int YuanSu::FengRen(Action *action)
{
	// һж˺ǰͺһΪ˷㣬Է˺ǰ
	addAction(ACTION_ATTACK, FENG_REN);
	return YuanSuDamage(action);
}

int YuanSu::HuoQiu(Action *action)
{
	return YuanSuDamage(action);
}

int YuanSu::LeiJi(int step, Action *action)
{
	if (step != LEI_JI)
	{
		return YuanSuDamage(action);
	}
	else
	{
		int dstID = action->dst_ids(0);
		GameInfo update_info;
		TeamArea* team_area = engine->getTeamArea();
		team_area->setGem(color, team_area->getGem(color)+1);
		if (color == RED)
			update_info.set_red_gem(team_area->getGem(color));
		else
			update_info.set_blue_gem(team_area->getGem(color));
		engine->sendMessage(-1, MSG_GAME, update_info);

		return GE_SUCCESS;
	}
}

int YuanSu::BingDong(int step, Action *action)
{
	if (step != BING_DONG)
	{
		return YuanSuDamage(action);
	}
	else
	{
		int dstID = action->dst_ids(0);
		PlayerEntity* dst = engine->getPlayerEntity(action->dst_ids(1));
		dst->addCrossNum(1);
		GameInfo game_info;
		Coder::crossNotice(dst->getID(), dst->getCrossNum(), game_info);
		engine->sendMessage(-1, MSG_GAME, game_info);

		return GE_SUCCESS;
	}
}

int YuanSu::YuanSuDianRan(Action *action)
{
	// һħж˺ǰͺһΪ˷㣬Է˺ǰ
	addAction(ACTION_MAGIC, YUAN_SU_DIAN_RAN);

	int dstID = action->dst_ids(0);
	SkillMsg skill_msg;
	Coder::skillNotice(id, dstID, YUAN_SU_DIAN_RAN, skill_msg);
	engine->sendMessage(-1, MSG_SKILL, skill_msg);

	setToken(0, 0);
	GameInfo game_info;
	Coder::tokenNotice(id, 0, getToken(0), game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);

	HARM dianran;
	dianran.cause = YUAN_SU_DIAN_RAN;
	dianran.point = 2;
	dianran.srcID = id;
	dianran.type = HARM_MAGIC;
	engine->setStateTimeline3(dstID, dianran);

	return GE_URGENT;
}

int YuanSu::YueGuang(Action *action)
{
	int dstID = action->dst_ids(0);
	SkillMsg skill_msg;
	Coder::skillNotice(id, dstID, YUE_GUANG, skill_msg);
	engine->sendMessage(-1, MSG_SKILL, skill_msg);

	--gem;
	GameInfo game_info;
	Coder::energyNotice(id, gem, crystal, game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);

	HARM yueguang;
	yueguang.cause = YUE_GUANG;
	yueguang.point = gem+crystal+1;
	yueguang.srcID = id;
	yueguang.type = HARM_MAGIC;
	engine->setStateTimeline3(dstID, yueguang);

	return GE_URGENT;
}

int YuanSu::YuanSuDamage(Action *action)
{
	int dstID = action->dst_ids(0);
	int magic_id = action->action_id();
	SkillMsg skill_msg;
	Coder::skillNotice(id, dstID, magic_id, skill_msg);
	engine->sendMessage(-1, MSG_SKILL, skill_msg);

	// ʹõ
	vector<int> cards;
	cards.push_back(action->card_ids(0));
	if (action->card_ids_size() > 1)
		cards.push_back(action->card_ids(1));

	// ˺
	HARM harm;
	harm.cause = magic_id;
	harm.point = cards.size();
	if (magic_id == HUO_QIU)
		++harm.point;
	harm.srcID = id;
	harm.type = HARM_MAGIC;
	engine->setStateTimeline3(dstID, harm);

	//
	engine->setStateMoveCardsNotToHand(id, DECK_HAND, -1, DECK_DISCARD, cards.size(), cards, id, magic_id, true);

	return GE_URGENT;
}<commit_msg>元素法术手牌展示<commit_after>#include "YuanSu.h"
#include "..\GameGrail.h"
#include "..\UserTask.h"

YuanSu::YuanSu(GameGrail *engine, int id, int color): PlayerEntity(engine, id, color)
{
	tokenMax[0] = 3;
}

int YuanSu::v_magic_skill(Action* action)
{
	int actionID = action->action_id();
	int cardID, cardID2;
	int playerID = action->src_id();
	CardEntity* card, *card2;
	PlayerEntity* dst;

	if(playerID != id){
		return GE_INVALID_PLAYERID;
	}

	switch (actionID)
	{
	case FENG_REN:
	case BING_DONG:
	case HUO_QIU:
	case YUN_SHI:
	case LEI_JI:
		cardID = action->card_ids(0);
		card = getCardByID(cardID);
		dst = engine->getPlayerEntity(action->dst_ids(0));
		//Լ                          || ǶӦԪ
		if(GE_SUCCESS != checkOneHandCard(cardID) || !card->checkSpeciality(actionID)){
			return GE_INVALID_ACTION;
		}
		if (action->card_ids_size() > 1)
		{
			cardID2 = action->card_ids(1);
			card2 = getCardByID(cardID2);
			if (card->getElement() != card2->getElement() || GE_SUCCESS != checkOneHandCard(cardID))
				return GE_INVALID_ACTION;
		}
		if (actionID == BING_DONG && action->dst_ids_size() < 2)
			// Ҫ2Ŀ
			return GE_INVALID_ACTION;

		break;
	case YUAN_SU_DIAN_RAN:
		dst = engine->getPlayerEntity(action->dst_ids(0));
		if (token[0] != tokenMax[0])
			return GE_INVALID_ACTION;
		break;
	case YUE_GUANG:
		dst = engine->getPlayerEntity(action->dst_ids(0));
		if (gem == 0)
			return GE_INVALID_ACTION;
		break;
	default:
		return GE_INVALID_ACTION;
	}

	return GE_SUCCESS;
}

int YuanSu::p_magic_skill(int &step, Action *action)
{
	int ret;
	switch(action->action_id())
	{
	case FENG_REN:
		ret = FengRen(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	case BING_DONG:
		ret = BingDong(step, action);
		if (GE_URGENT == ret){
			// 2ϣ˺ͼ
			step = BING_DONG;
		}
		else if (GE_SUCCESS == ret){
			step = STEP_DONE;
		}
		break;
	case HUO_QIU:
		ret = HuoQiu(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	case YUN_SHI:
		ret = YunShi(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	case LEI_JI:
		ret = LeiJi(step, action);
		if (GE_URGENT == ret){
			// ۼƴ2ϣ˺ͼӱʯ
			step = LEI_JI;
		}
		else if (GE_SUCCESS == ret){
			step = STEP_DONE;
		}
		break;
	case YUAN_SU_DIAN_RAN:
		ret = YuanSuDianRan(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	case YUE_GUANG:
		ret = YueGuang(action);
		if(GE_URGENT == ret){
			step = STEP_DONE;
		}
		break;
	default:
		return GE_INVALID_ACTION;
	}

	return ret;
}

// Ԫ
int YuanSu::p_timeline_3(int &step, CONTEXT_TIMELINE_3 *con)
{
	//  Լɵ˺        && ħ˺                     && Ԫصȼɵ˺
	if (con->harm.srcID == id && con->harm.type == HARM_MAGIC && con->harm.cause != YUAN_SU_DIAN_RAN)
	{
		SkillMsg skill_msg;
		Coder::skillNotice(id, id, YUAN_SU_XI_SHOU, skill_msg);
		engine->sendMessage(-1, MSG_SKILL, skill_msg);

		setToken(0, getToken(0)+1);
		GameInfo game_info;
		Coder::tokenNotice(id, 0, getToken(0), game_info);
		engine->sendMessage(-1, MSG_GAME, game_info);
	}
	return GE_SUCCESS;
}

int YuanSu::YunShi(Action *action)
{
	// һħж˺ǰͺһΪ˷㣬Է˺ǰ
	addAction(ACTION_MAGIC, YUN_SHI);
	return YuanSuDamage(action);
}

int YuanSu::FengRen(Action *action)
{
	// һж˺ǰͺһΪ˷㣬Է˺ǰ
	addAction(ACTION_ATTACK, FENG_REN);
	return YuanSuDamage(action);
}

int YuanSu::HuoQiu(Action *action)
{
	return YuanSuDamage(action);
}

int YuanSu::LeiJi(int step, Action *action)
{
	if (step != LEI_JI)
	{
		return YuanSuDamage(action);
	}
	else
	{
		int dstID = action->dst_ids(0);
		GameInfo update_info;
		TeamArea* team_area = engine->getTeamArea();
		team_area->setGem(color, team_area->getGem(color)+1);
		if (color == RED)
			update_info.set_red_gem(team_area->getGem(color));
		else
			update_info.set_blue_gem(team_area->getGem(color));
		engine->sendMessage(-1, MSG_GAME, update_info);

		return GE_SUCCESS;
	}
}

int YuanSu::BingDong(int step, Action *action)
{
	if (step != BING_DONG)
	{
		return YuanSuDamage(action);
	}
	else
	{
		int dstID = action->dst_ids(0);
		PlayerEntity* dst = engine->getPlayerEntity(action->dst_ids(1));
		dst->addCrossNum(1);
		GameInfo game_info;
		Coder::crossNotice(dst->getID(), dst->getCrossNum(), game_info);
		engine->sendMessage(-1, MSG_GAME, game_info);

		return GE_SUCCESS;
	}
}

int YuanSu::YuanSuDianRan(Action *action)
{
	// һħж˺ǰͺһΪ˷㣬Է˺ǰ
	addAction(ACTION_MAGIC, YUAN_SU_DIAN_RAN);

	int dstID = action->dst_ids(0);
	SkillMsg skill_msg;
	Coder::skillNotice(id, dstID, YUAN_SU_DIAN_RAN, skill_msg);
	engine->sendMessage(-1, MSG_SKILL, skill_msg);

	setToken(0, 0);
	GameInfo game_info;
	Coder::tokenNotice(id, 0, getToken(0), game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);

	HARM dianran;
	dianran.cause = YUAN_SU_DIAN_RAN;
	dianran.point = 2;
	dianran.srcID = id;
	dianran.type = HARM_MAGIC;
	engine->setStateTimeline3(dstID, dianran);

	return GE_URGENT;
}

int YuanSu::YueGuang(Action *action)
{
	int dstID = action->dst_ids(0);
	SkillMsg skill_msg;
	Coder::skillNotice(id, dstID, YUE_GUANG, skill_msg);
	engine->sendMessage(-1, MSG_SKILL, skill_msg);

	--gem;
	GameInfo game_info;
	Coder::energyNotice(id, gem, crystal, game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);

	HARM yueguang;
	yueguang.cause = YUE_GUANG;
	yueguang.point = gem+crystal+1;
	yueguang.srcID = id;
	yueguang.type = HARM_MAGIC;
	engine->setStateTimeline3(dstID, yueguang);

	return GE_URGENT;
}

int YuanSu::YuanSuDamage(Action *action)
{
	int dstID = action->dst_ids(0);
	int magic_id = action->action_id();
	SkillMsg skill_msg;
	Coder::skillNotice(id, dstID, magic_id, skill_msg);
	engine->sendMessage(-1, MSG_SKILL, skill_msg);

	// ʹõ
	vector<int> cards;
	cards.push_back(action->card_ids(0));
	if (action->card_ids_size() > 1)
		cards.push_back(action->card_ids(1));

	// ˺
	HARM harm;
	harm.cause = magic_id;
	harm.point = cards.size();
	if (magic_id == HUO_QIU)
		++harm.point;
	harm.srcID = id;
	harm.type = HARM_MAGIC;
	engine->setStateTimeline3(dstID, harm);

	//
	CardMsg show_card;
	Coder::showCardNotice(id, cards.size(), cards, show_card);
	engine->sendMessage(-1, MSG_CARD, show_card);
	engine->setStateMoveCardsNotToHand(id, DECK_HAND, -1, DECK_DISCARD, cards.size(), cards, id, magic_id, true);

	return GE_URGENT;
}<|endoftext|>


<commit_before>
namespace cypher
{
  std::string rot13(std::wstring message);
}
<commit_msg>Create rot13.hpp<commit_after>/******************************************************************************
Copyright 2017 Pedro Luis Valadés Viera

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/

namespace cypher
{
  std::string rot13(std::wstring message);
}
<|endoftext|>


<commit_before>/*
*
COPYRIGHT AND LICENSE

Copyright (c) 2011 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

3. All advertising materials mentioning features or use of this
software must display the following acknowledgement: This product
includes software developed by the San Diego Supercomputer Center.

4. Neither the names of the Centers nor the names of the contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*
*
* Based on the notes by Prof. Ramon Arrowsmith(ramon.arrowsmith@asu.edu)
* Authors: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
*
*/

#include <points2grid/config.h>
#include <points2grid/Interpolation.hpp>
#include <points2grid/Global.hpp>

#include <string.h>
#include <math.h>
#include <float.h>
#include <stddef.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>

#ifdef PDAL_FOUND
#include <pdal/pdal.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/Dimension.hpp>
#include <pdal/Schema.hpp>
#else /* LIBLAS_FOUND */
extern "C" {
    #include <liblas/capi/liblas.h> // the C API is stable across liblas versions
}
#endif

#include <boost/scoped_ptr.hpp>

#include <fstream>  // std::ifstream
#include <iostream> // std::cout
#include <string.h>

/////////////////////////////////////////////////////////////
// Public Methods
/////////////////////////////////////////////////////////////

Interpolation::Interpolation(double x_dist, double y_dist, double radius,
                             int _window_size, int _interpolation_mode = INTERP_AUTO) : GRID_DIST_X (x_dist), GRID_DIST_Y(y_dist)
{
    data_count = 0;
    radius_sqr = radius * radius;
    window_size = _window_size;
    interpolation_mode = _interpolation_mode;

    min_x = DBL_MAX;
    min_y = DBL_MAX;

    max_x = -DBL_MAX;
    max_y = -DBL_MAX;
}

Interpolation::~Interpolation()
{
    delete interp;
}

int Interpolation::init(char *inputName, int inputFormat)
{
    //unsigned int i;

    //struct tms tbuf;
    clock_t t0, t1;

    //////////////////////////////////////////////////////////////////////
    // MIN/MAX SEARCHING
    // TODO: the size of data, min, max of each coordinate
    //       are required to implement streaming processing....
    //
    // This code can be eliminated if database can provide these values
    //////////////////////////////////////////////////////////////////////

    //t0 = times(&tbuf);
    t0 = clock();

    if(inputName == NULL)
    {
        cout << "Wrong Input File Name" << endl;
        return -1;
    }

    printf("inputName: '%s'\n", inputName);

    if (inputFormat == INPUT_ASCII) {
        FILE *fp;
        char line[1024];
        double data_x, data_y;
        //double data_z;

        if((fp = fopen(inputName, "r")) == NULL)
        {
            cout << "file open error" << endl;
            return -1;
        }

        // throw the first line away - it contains the header
        fgets(line, sizeof(line), fp);

        // read the data points to find min and max values
        while(fgets(line, sizeof(line), fp) != NULL)
        {
            data_x = atof(strtok(line, ",\n"));
            if(min_x > data_x) min_x = data_x;
            if(max_x < data_x) max_x = data_x;

            data_y = atof(strtok(NULL, ",\n"));
            if(min_y > data_y) min_y = data_y;
            if(max_y < data_y) max_y = data_y;

            data_count++;

            /*
            // tokenizing
            string strLine(line);

            // first token
            string::size_type pos = strLine.find_first_of(",",0);
            string::size_type lastPos = strLine.find_first_not_of(",",0);

            string strX = strLine.substr(lastPos, pos - lastPos);

            // second token
            lastPos = strLine.find_first_not_of(",", pos);
            pos = strLine.find_first_of(",", lastPos);

            string strY = strLine.substr(lastPos, pos - lastPos);

            // third token
            lastPos = strLine.find_first_not_of(",", pos);
            pos = strLine.find_first_of("\n", lastPos);

            string strZ = strLine.substr(lastPos, pos - lastPos);

            // data conversion
            arrX[data_count] = atof(strX.c_str());
            if(min_x > arrX[data_count]) min_x = arrX[data_count];
            if(max_x < arrX[data_count]) max_x = arrX[data_count];

            arrY[data_count] = atof(strY.c_str());
            if(min_y > arrY[data_count]) min_y = arrY[data_count];
            if(max_y < arrY[data_count]) max_y = arrY[data_count];

            arrZ[data_count++] = atof(strZ.c_str());
            */
        }

        fclose(fp);
    } else { // las input
#ifdef PDAL_FOUND
        try {

            pdal::Options options;
            options.add("filename", inputName);

            pdal::StageFactory factory;
            pdal::Stage* reader = factory.createReader("drivers.pipeline.reader", options);

            reader->initialize();

            pdal::Bounds<double> bounds = reader->getBounds();

            min_x = bounds.getMinimum(0);
            min_y = bounds.getMinimum(1);
            max_x = bounds.getMaximum(0);
            max_y = bounds.getMaximum(1);

            // boost::scoped_ptr<boost::StageSequentialIterator> iter(reader.createSequentialIterator());
            // iter->skip(m_pointNumber);
        } catch (std::runtime_error &e) {
            cout << "error while reading LAS file: verify that the input is valid LAS file" << e.what() << endl;
            return -1;
        }
#else /* LIBLAS_FOUND */
        LASReaderH lr = LASReader_Create(inputName);
        LASHeaderH lh = LASReader_GetHeader(lr);

        if (lh == NULL) {
            LASError_Print("error while reading LAS file: verify that the input is valid LAS file.");
            LASReader_Destroy(lr);

            return -1;
        }

        min_x = LASHeader_GetMinX(lh);
        min_y = LASHeader_GetMinY(lh);
        max_x = LASHeader_GetMaxX(lh);
        max_y = LASHeader_GetMaxY(lh);
        data_count = LASHeader_GetPointRecordsCount(lh);

        LASReader_Destroy(lr);
#endif
    }

    t1 = clock();
    printf("Min/Max searching time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

    //t0 = times(&tbuf);

    //////////////////////////////////////////////////////////////////////
    // Intialization Step excluding min/max searching
    //////////////////////////////////////////////////////////////////////
    /*
      for(i = 0; i < data_count; i++)
      {
      arrX[i] -= min_x;
      arrY[i] -= min_y;
      //printf("%f,%f,%f\n", arrX[i] , arrY[i] ,arrZ[i]);
      }
    */

    cout << "min_x: " << min_x << ", max_x: " << max_x << ", min_y: " << min_y << ", max_y: " << max_y << endl;

    GRID_SIZE_X = (int)(ceil((max_x - min_x)/GRID_DIST_X)) + 1;
    GRID_SIZE_Y = (int)(ceil((max_y - min_y)/GRID_DIST_Y)) + 1;

    cout << "GRID_SIZE_X " << GRID_SIZE_X << endl;
    cout << "GRID_SIZE_Y " << GRID_SIZE_Y << endl;

    if (interpolation_mode == INTERP_AUTO) {
        // if the size is too big to fit in memory,
        // then construct out-of-core structure
        if(GRID_SIZE_X * GRID_SIZE_Y > MEM_LIMIT) {
            interpolation_mode= INTERP_OUTCORE;
        } else {
            interpolation_mode = INTERP_INCORE;
        }
    }

    if (interpolation_mode == INTERP_OUTCORE) {
        cout << "Using out of core interp code" << endl;;

        interp = new OutCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);
        if(interp == NULL)
        {
            cout << "OutCoreInterp construction error" << endl;
            return -1;
        }

        cout << "Interpolation uses out-of-core algorithm" << endl;

    } else {
        cout << "Using incore interp code" << endl;

        interp = new InCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);

        cout << "Interpolation uses in-core algorithm" << endl;
    }

    if(interp->init() < 0)
    {
        cout << "inter->init() error" << endl;
        return -1;
    }

    cout << "Interpolation::init() done successfully" << endl;

    return 0;
}

int Interpolation::interpolation(char *inputName,
                                 char *outputName,
                                 int inputFormat,
                                 int outputFormat,
                                 unsigned int outputType)
{
    int rc;
    //unsigned int i;
    double data_x, data_y;
    double data_z;

    //struct tms tbuf;
    //clock_t t0, t1;

    printf("Interpolation Starts\n");

    //t0 = times(&tbuf);

    //cout << "data_count: " << data_count << endl;

    /*
      if((rc = interp->init()) < 0)
      {
      cout << "inter->init() error" << endl;
      return -1;
      }
    */

    if (inputFormat == INPUT_ASCII) {
        FILE *fp;
        char line[1024];

        if((fp = fopen(inputName, "r")) == NULL)
        {
            printf("file open error\n");
            return -1;
        }

        // throw the first line away - it contains the header
        fgets(line, sizeof(line), fp);

        // read every point and generate DEM
        while(fgets(line, sizeof(line), fp) != NULL)
        {
            data_x = atof(strtok(line, ",\n"));
            data_y = atof(strtok(NULL, ",\n"));
            data_z = atof(strtok(NULL, ",\n"));

            data_x -= min_x;
            data_y -= min_y;

            //if((rc = interp->update(arrX[i], arrY[i], arrZ[i])) < 0)
            if((rc = interp->update(data_x, data_y, data_z)) < 0)
            {
                cout << "interp->update() error while processing " << endl;
                return -1;
            }
        }

        fclose(fp);
    } else { // input format is LAS

#ifdef PDAL_FOUND
        pdal::Options options;
        options.add("filename", inputName);

        pdal::StageFactory factory;
        pdal::Stage* reader = factory.createReader("drivers.pipeline.reader", options);

        reader->initialize();
        const pdal::Schema& schema = reader->getSchema();

        pdal::PointBuffer data(schema, 32768);

        boost::scoped_ptr<pdal::StageSequentialIterator> iter(reader->createSequentialIterator());

        int xPos = schema.getDimensionIndex(pdal::DimensionId::X_i32);
        pdal::Dimension const& xDim = schema.getDimension(xPos);

        int yPos = schema.getDimensionIndex(pdal::DimensionId::Y_i32);
        pdal::Dimension const& yDim = schema.getDimension(yPos);

        int zPos = schema.getDimensionIndex(pdal::DimensionId::Z_i32);
        pdal::Dimension const& zDim = schema.getDimension(zPos);

        iter->read(data);

        while (true) {
            if (iter->atEnd()) break;
            for (boost::uint32_t pointIndex=0; pointIndex < data.getNumPoints(); pointIndex++)
            {
                boost::int32_t x = data.getField<boost::int32_t>(pointIndex, xPos);
                boost::int32_t y = data.getField<boost::int32_t>(pointIndex, yPos);
                boost::int32_t z = data.getField<boost::int32_t>(pointIndex, zPos);

                data_x = xDim.applyScaling<boost::int32_t>(x);
                data_y = yDim.applyScaling<boost::int32_t>(y);
                data_z = zDim.applyScaling<boost::int32_t>(z);
                data_x -= min_x;
                data_y -= min_y;

                //if((rc = interp->update(arrX[i], arrY[i], arrZ[i])) < 0)
                if((rc = interp->update(data_x, data_y, data_z)) < 0)
                {
                    cout << "interp->update() error while processing " << endl;
                    return -1;
                }
            }
            iter->read(data);
        }
#else /* LIBLAS_FOUND */
        LASReaderH lr = LASReader_Create(inputName);
        LASPointH lp;

        while (lp = LASReader_GetNextPoint(lr)) {
            data_x = LASPoint_GetX(lp);
            data_y = LASPoint_GetY(lp);
            data_z = LASPoint_GetZ(lp);

            data_x -= min_x;
            data_y -= min_y;

            if ((rc = interp->update(data_x, data_y, data_z)) < 0) {
                cout << "interp->update() error while processing " << endl;
                return -1;
            }
        }

        LASReader_Destroy(lr);
#endif

    }

    if((rc = interp->finish(outputName, outputFormat, outputType)) < 0)
    {
        cout << "interp->finish() error" << endl;
        return -1;
    }

    cout << "Interpolation::interpolation() done successfully" << endl;

    return 0;
}

void Interpolation::setRadius(double r)
{
    radius_sqr = r * r;
}

unsigned int Interpolation::getDataCount()
{
    return data_count;
}

unsigned int Interpolation::getGridSizeX()
{
    return GRID_SIZE_X;
}

unsigned int Interpolation::getGridSizeY()
{
    return GRID_SIZE_Y;
}

<commit_msg>Adding additional error checking for libLAS C API calls.<commit_after>/*
*
COPYRIGHT AND LICENSE

Copyright (c) 2011 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

3. All advertising materials mentioning features or use of this
software must display the following acknowledgement: This product
includes software developed by the San Diego Supercomputer Center.

4. Neither the names of the Centers nor the names of the contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*
*
* Based on the notes by Prof. Ramon Arrowsmith(ramon.arrowsmith@asu.edu)
* Authors: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
*
*/

#include <points2grid/config.h>
#include <points2grid/Interpolation.hpp>
#include <points2grid/Global.hpp>

#include <string.h>
#include <math.h>
#include <float.h>
#include <stddef.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>

#ifdef PDAL_FOUND
#include <pdal/pdal.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/Dimension.hpp>
#include <pdal/Schema.hpp>
#else /* LIBLAS_FOUND */
extern "C" {
    #include <liblas/capi/liblas.h> // the C API is stable across liblas versions
}
#endif

#include <boost/scoped_ptr.hpp>

#include <fstream>  // std::ifstream
#include <iostream> // std::cout
#include <string.h>

/////////////////////////////////////////////////////////////
// Public Methods
/////////////////////////////////////////////////////////////

Interpolation::Interpolation(double x_dist, double y_dist, double radius,
                             int _window_size, int _interpolation_mode = INTERP_AUTO) : GRID_DIST_X (x_dist), GRID_DIST_Y(y_dist)
{
    data_count = 0;
    radius_sqr = radius * radius;
    window_size = _window_size;
    interpolation_mode = _interpolation_mode;

    min_x = DBL_MAX;
    min_y = DBL_MAX;

    max_x = -DBL_MAX;
    max_y = -DBL_MAX;
}

Interpolation::~Interpolation()
{
    delete interp;
}

int Interpolation::init(char *inputName, int inputFormat)
{
    //unsigned int i;

    //struct tms tbuf;
    clock_t t0, t1;

    //////////////////////////////////////////////////////////////////////
    // MIN/MAX SEARCHING
    // TODO: the size of data, min, max of each coordinate
    //       are required to implement streaming processing....
    //
    // This code can be eliminated if database can provide these values
    //////////////////////////////////////////////////////////////////////

    //t0 = times(&tbuf);
    t0 = clock();

    if(inputName == NULL)
    {
        cout << "Wrong Input File Name" << endl;
        return -1;
    }

    printf("inputName: '%s'\n", inputName);

    if (inputFormat == INPUT_ASCII) {
        FILE *fp;
        char line[1024];
        double data_x, data_y;
        //double data_z;

        if((fp = fopen(inputName, "r")) == NULL)
        {
            cout << "file open error" << endl;
            return -1;
        }

        // throw the first line away - it contains the header
        fgets(line, sizeof(line), fp);

        // read the data points to find min and max values
        while(fgets(line, sizeof(line), fp) != NULL)
        {
            data_x = atof(strtok(line, ",\n"));
            if(min_x > data_x) min_x = data_x;
            if(max_x < data_x) max_x = data_x;

            data_y = atof(strtok(NULL, ",\n"));
            if(min_y > data_y) min_y = data_y;
            if(max_y < data_y) max_y = data_y;

            data_count++;

            /*
            // tokenizing
            string strLine(line);

            // first token
            string::size_type pos = strLine.find_first_of(",",0);
            string::size_type lastPos = strLine.find_first_not_of(",",0);

            string strX = strLine.substr(lastPos, pos - lastPos);

            // second token
            lastPos = strLine.find_first_not_of(",", pos);
            pos = strLine.find_first_of(",", lastPos);

            string strY = strLine.substr(lastPos, pos - lastPos);

            // third token
            lastPos = strLine.find_first_not_of(",", pos);
            pos = strLine.find_first_of("\n", lastPos);

            string strZ = strLine.substr(lastPos, pos - lastPos);

            // data conversion
            arrX[data_count] = atof(strX.c_str());
            if(min_x > arrX[data_count]) min_x = arrX[data_count];
            if(max_x < arrX[data_count]) max_x = arrX[data_count];

            arrY[data_count] = atof(strY.c_str());
            if(min_y > arrY[data_count]) min_y = arrY[data_count];
            if(max_y < arrY[data_count]) max_y = arrY[data_count];

            arrZ[data_count++] = atof(strZ.c_str());
            */
        }

        fclose(fp);
    } else { // las input
#ifdef PDAL_FOUND
        try {

            pdal::Options options;
            options.add("filename", inputName);

            pdal::StageFactory factory;
            pdal::Stage* reader = factory.createReader("drivers.pipeline.reader", options);

            reader->initialize();

            pdal::Bounds<double> bounds = reader->getBounds();

            min_x = bounds.getMinimum(0);
            min_y = bounds.getMinimum(1);
            max_x = bounds.getMaximum(0);
            max_y = bounds.getMaximum(1);

            // boost::scoped_ptr<boost::StageSequentialIterator> iter(reader.createSequentialIterator());
            // iter->skip(m_pointNumber);
        } catch (std::runtime_error &e) {
            cout << "error while reading LAS file: verify that the input is valid LAS file" << e.what() << endl;
            return -1;
        }
#else /* LIBLAS_FOUND */
        LASReaderH lr = LASReader_Create(inputName);
        if (!lr) {
            LASError_Print("Could not open file to read.");
            return -1;
        }

        LASHeaderH lh = LASReader_GetHeader(lr);
        if (!lh) {
            LASError_Print("error while reading LAS file: verify that the input is valid LAS file.");
            LASReader_Destroy(lr);
            return -1;
        }

        min_x = LASHeader_GetMinX(lh);
        min_y = LASHeader_GetMinY(lh);
        max_x = LASHeader_GetMaxX(lh);
        max_y = LASHeader_GetMaxY(lh);
        data_count = LASHeader_GetPointRecordsCount(lh);

        LASReader_Destroy(lr);
#endif
    }

    t1 = clock();
    printf("Min/Max searching time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

    //t0 = times(&tbuf);

    //////////////////////////////////////////////////////////////////////
    // Intialization Step excluding min/max searching
    //////////////////////////////////////////////////////////////////////
    /*
      for(i = 0; i < data_count; i++)
      {
      arrX[i] -= min_x;
      arrY[i] -= min_y;
      //printf("%f,%f,%f\n", arrX[i] , arrY[i] ,arrZ[i]);
      }
    */

    cout << "min_x: " << min_x << ", max_x: " << max_x << ", min_y: " << min_y << ", max_y: " << max_y << endl;

    GRID_SIZE_X = (int)(ceil((max_x - min_x)/GRID_DIST_X)) + 1;
    GRID_SIZE_Y = (int)(ceil((max_y - min_y)/GRID_DIST_Y)) + 1;

    cout << "GRID_SIZE_X " << GRID_SIZE_X << endl;
    cout << "GRID_SIZE_Y " << GRID_SIZE_Y << endl;

    if (interpolation_mode == INTERP_AUTO) {
        // if the size is too big to fit in memory,
        // then construct out-of-core structure
        if(GRID_SIZE_X * GRID_SIZE_Y > MEM_LIMIT) {
            interpolation_mode= INTERP_OUTCORE;
        } else {
            interpolation_mode = INTERP_INCORE;
        }
    }

    if (interpolation_mode == INTERP_OUTCORE) {
        cout << "Using out of core interp code" << endl;;

        interp = new OutCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);
        if(interp == NULL)
        {
            cout << "OutCoreInterp construction error" << endl;
            return -1;
        }

        cout << "Interpolation uses out-of-core algorithm" << endl;

    } else {
        cout << "Using incore interp code" << endl;

        interp = new InCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);

        cout << "Interpolation uses in-core algorithm" << endl;
    }

    if(interp->init() < 0)
    {
        cout << "inter->init() error" << endl;
        return -1;
    }

    cout << "Interpolation::init() done successfully" << endl;

    return 0;
}

int Interpolation::interpolation(char *inputName,
                                 char *outputName,
                                 int inputFormat,
                                 int outputFormat,
                                 unsigned int outputType)
{
    int rc;
    //unsigned int i;
    double data_x, data_y;
    double data_z;

    //struct tms tbuf;
    //clock_t t0, t1;

    printf("Interpolation Starts\n");

    //t0 = times(&tbuf);

    //cout << "data_count: " << data_count << endl;

    /*
      if((rc = interp->init()) < 0)
      {
      cout << "inter->init() error" << endl;
      return -1;
      }
    */

    if (inputFormat == INPUT_ASCII) {
        FILE *fp;
        char line[1024];

        if((fp = fopen(inputName, "r")) == NULL)
        {
            printf("file open error\n");
            return -1;
        }

        // throw the first line away - it contains the header
        fgets(line, sizeof(line), fp);

        // read every point and generate DEM
        while(fgets(line, sizeof(line), fp) != NULL)
        {
            data_x = atof(strtok(line, ",\n"));
            data_y = atof(strtok(NULL, ",\n"));
            data_z = atof(strtok(NULL, ",\n"));

            data_x -= min_x;
            data_y -= min_y;

            //if((rc = interp->update(arrX[i], arrY[i], arrZ[i])) < 0)
            if((rc = interp->update(data_x, data_y, data_z)) < 0)
            {
                cout << "interp->update() error while processing " << endl;
                return -1;
            }
        }

        fclose(fp);
    } else { // input format is LAS

#ifdef PDAL_FOUND
        pdal::Options options;
        options.add("filename", inputName);

        pdal::StageFactory factory;
        pdal::Stage* reader = factory.createReader("drivers.pipeline.reader", options);

        reader->initialize();
        const pdal::Schema& schema = reader->getSchema();

        pdal::PointBuffer data(schema, 32768);

        boost::scoped_ptr<pdal::StageSequentialIterator> iter(reader->createSequentialIterator());

        int xPos = schema.getDimensionIndex(pdal::DimensionId::X_i32);
        pdal::Dimension const& xDim = schema.getDimension(xPos);

        int yPos = schema.getDimensionIndex(pdal::DimensionId::Y_i32);
        pdal::Dimension const& yDim = schema.getDimension(yPos);

        int zPos = schema.getDimensionIndex(pdal::DimensionId::Z_i32);
        pdal::Dimension const& zDim = schema.getDimension(zPos);

        iter->read(data);

        while (true) {
            if (iter->atEnd()) break;
            for (boost::uint32_t pointIndex=0; pointIndex < data.getNumPoints(); pointIndex++)
            {
                boost::int32_t x = data.getField<boost::int32_t>(pointIndex, xPos);
                boost::int32_t y = data.getField<boost::int32_t>(pointIndex, yPos);
                boost::int32_t z = data.getField<boost::int32_t>(pointIndex, zPos);

                data_x = xDim.applyScaling<boost::int32_t>(x);
                data_y = yDim.applyScaling<boost::int32_t>(y);
                data_z = zDim.applyScaling<boost::int32_t>(z);
                data_x -= min_x;
                data_y -= min_y;

                //if((rc = interp->update(arrX[i], arrY[i], arrZ[i])) < 0)
                if((rc = interp->update(data_x, data_y, data_z)) < 0)
                {
                    cout << "interp->update() error while processing " << endl;
                    return -1;
                }
            }
            iter->read(data);
        }
#else /* LIBLAS_FOUND */
        LASReaderH lr = LASReader_Create(inputName);
        if (!lr) {
            LASError_Print("Could not open file to read.");
            return -1;
        }

        LASPointH lp;
        while ((lp = LASReader_GetNextPoint(lr))) {
            data_x = LASPoint_GetX(lp);
            data_y = LASPoint_GetY(lp);
            data_z = LASPoint_GetZ(lp);

            data_x -= min_x;
            data_y -= min_y;

            if ((rc = interp->update(data_x, data_y, data_z)) < 0) {
                cout << "interp->update() error while processing " << endl;
                return -1;
            }
        }

        LASReader_Destroy(lr);
#endif

    }

    if((rc = interp->finish(outputName, outputFormat, outputType)) < 0)
    {
        cout << "interp->finish() error" << endl;
        return -1;
    }

    cout << "Interpolation::interpolation() done successfully" << endl;

    return 0;
}

void Interpolation::setRadius(double r)
{
    radius_sqr = r * r;
}

unsigned int Interpolation::getDataCount()
{
    return data_count;
}

unsigned int Interpolation::getGridSizeX()
{
    return GRID_SIZE_X;
}

unsigned int Interpolation::getGridSizeY()
{
    return GRID_SIZE_Y;
}

<|endoftext|>