aboutsummaryrefslogtreecommitdiff
path: root/src/util/pointedthing.h
blob: 5b30ed03135446706883ea3a60408967368b9dd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#pragma once

#include "irrlichttypes.h"
#include "irr_v3d.h"
#include <iostream>
#include <string>

enum PointedThingType
{
	POINTEDTHING_NOTHING,
	POINTEDTHING_NODE,
	POINTEDTHING_OBJECT
};

//! An active object or node which is selected by a ray on the map.
struct PointedThing
{
	//! The type of the pointed object.
	PointedThingType type = POINTEDTHING_NOTHING;
	/*!
	 * Only valid if type is POINTEDTHING_NODE.
	 * The coordinates of the node which owns the
	 * nodebox that the ray hits first.
	 * This may differ from node_real_undersurface if
	 * a nodebox exceeds the limits of its node.
	 */
	v3s16 node_undersurface;
	/*!
	 * Only valid if type is POINTEDTHING_NODE.
	 * The coordinates of the last node the ray intersects
	 * before node_undersurface. Same as node_undersurface
	 * if the ray starts in a nodebox.
	 */
	v3s16 node_abovesurface;
	/*!
	 * Only valid if type is POINTEDTHING_NODE.
	 * The coordinates of the node which contains the
	 * point of the collision and the nodebox of the node.
	 */
	v3s16 node_real_undersurface;
	/*!
	 * Only valid if type is POINTEDTHING_OBJECT.
	 * The ID of the object the ray hit.
	 */
	s16 object_id = -1;
	/*!
	 * Only valid if type isn't POINTEDTHING_NONE.
	 * First intersection point of the ray and the nodebox in irrlicht
	 * coordinates.
	 */
	v3f intersection_point;
	/*!
	 * Only valid if type isn't POINTEDTHING_NONE.
	 * Normal vector of the intersection.
	 * This is perpendicular to the face the ray hits,
	 * points outside of the box and it's length is 1.
	 */
	v3s16 intersection_normal;
	/*!
	 * Only valid if type isn't POINTEDTHING_NONE.
	 * Indicates which selection box is selected, if there are more of them.
	 */
	u16 box_id = 0;
	/*!
	 * Square of the distance between the pointing
	 * ray's start point and the intersection point in irrlicht coordinates.
	 */
	f32 distanceSq = 0;

	//! Constructor for POINTEDTHING_NOTHING
	PointedThing() = default;
	//! Constructor for POINTEDTHING_NODE
	PointedThing(const v3s16 &under, const v3s16 &above,
		const v3s16 &real_under, const v3f &point, const v3s16 &normal,
		u16 box_id, f32 distSq);
	//! Constructor for POINTEDTHING_OBJECT
	PointedThing(s16 id, const v3f &point, const v3s16 &normal, f32 distSq);
	std::string dump() const;
	void serialize(std::ostream &os) const;
	void deSerialize(std::istream &is);
	/*!
	 * This function ignores the intersection point and normal.
	 */
	bool operator==(const PointedThing &pt2) const;
	bool operator!=(const PointedThing &pt2) const;
};
1 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "rollback.h"
#include <fstream>
#include <list>
#include <sstream>
#include "log.h"
#include "mapnode.h"
#include "gamedef.h"
#include "nodedef.h"
#include "util/serialize.h"
#include "util/string.h"
#include "util/numeric.h"
#include "inventorymanager.h" // deserializing InventoryLocations
#include "sqlite3.h"
#include "filesys.h"

#define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"

#define POINTS_PER_NODE (16.0)

static std::string dbp;
static sqlite3* dbh                        = NULL;
static sqlite3_stmt* dbs_insert            = NULL;
static sqlite3_stmt* dbs_replace           = NULL;
static sqlite3_stmt* dbs_select            = NULL;
static sqlite3_stmt* dbs_select_range      = NULL;
static sqlite3_stmt* dbs_select_withActor  = NULL;
static sqlite3_stmt* dbs_knownActor_select = NULL;
static sqlite3_stmt* dbs_knownActor_insert = NULL;
static sqlite3_stmt* dbs_knownNode_select  = NULL;
static sqlite3_stmt* dbs_knownNode_insert  = NULL;

struct Stack {
	int node;
	int quantity;
};
struct ActionRow {
	int         id;
	int         actor;
	time_t      timestamp;
	int         type;
	std::string location, list;
	int         index, add;
	Stack       stack;
	int         nodeMeta;
	int         x, y, z;
	int         oldNode;
	int         oldParam1, oldParam2;
	std::string oldMeta;
	int         newNode;
	int         newParam1, newParam2;
	std::string newMeta;
	int         guessed;
};

struct Entity {
	int         id;
	std::string name;
};

typedef std::vector<Entity> Entities;

Entities KnownActors;
Entities KnownNodes;

void registerNewActor(int id, std::string name)
{
	Entity newActor;

	newActor.id   = id;
	newActor.name = name;

	KnownActors.push_back(newActor);

	//std::cout << "New actor registered: " << id << " | " << name << std::endl;
}

void registerNewNode(int id, std::string name)
{
	Entity newNode;

	newNode.id   = id;
	newNode.name = name;

	KnownNodes.push_back(newNode);

	//std::cout << "New node registered: " << id << " | " << name << std::endl;
}

int getActorId(std::string name)
{
	Entities::const_iterator iter;

	for (iter = KnownActors.begin(); iter != KnownActors.end(); ++iter)
		if (iter->name == name) {
			return iter->id;
		}

	sqlite3_reset(dbs_knownActor_insert);
	sqlite3_bind_text(dbs_knownActor_insert, 1, name.c_str(), -1, NULL);
	sqlite3_step(dbs_knownActor_insert);

	int id = sqlite3_last_insert_rowid(dbh);

	//std::cout << "Actor ID insert returns " << insert << std::endl;

	registerNewActor(id, name);

	return id;
}

int getNodeId(std::string name)
{
	Entities::const_iterator iter;

	for (iter = KnownNodes.begin(); iter != KnownNodes.end(); ++iter)
		if (iter->name == name) {
			return iter->id;
		}

	sqlite3_reset(dbs_knownNode_insert);
	sqlite3_bind_text(dbs_knownNode_insert, 1, name.c_str(), -1, NULL);
	sqlite3_step(dbs_knownNode_insert);

	int id = sqlite3_last_insert_rowid(dbh);

	registerNewNode(id, name);

	return id;
}

const char * getActorName(int id)
{
	Entities::const_iterator iter;

	//std::cout << "getActorName of id " << id << std::endl;

	for (iter = KnownActors.begin(); iter != KnownActors.end(); ++iter)
		if (iter->id == id) {
			return iter->name.c_str();
		}

	return "";
}

const char * getNodeName(int id)
{
	Entities::const_iterator iter;

	//std::cout << "getNodeName of id " << id << std::endl;

	for (iter = KnownNodes.begin(); iter != KnownNodes.end(); ++iter)
		if (iter->id == id) {
			return iter->name.c_str();
		}

	return "";
}

Stack getStackFromString(std::string text)
{
	Stack stack;

	size_t off = text.find_last_of(" ");

	stack.node     = getNodeId(text.substr(0, off));
	stack.quantity = atoi(text.substr(off + 1).c_str());

	return stack;
}

std::string getStringFromStack(Stack stack)
{
	std::string text;

	text.append(getNodeName(stack.node));
	text.append(" ");
	text.append(itos(stack.quantity));

	return text;
}

bool SQL_createDatabase(void)
{
	infostream << "CreateDB:" << dbp << std::endl;

	int dbs = sqlite3_exec(dbh,
		"CREATE TABLE IF NOT EXISTS `actor` ("
			"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
			"`name` TEXT NOT NULL);"
			"CREATE TABLE IF NOT EXISTS `node` ("
			"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
			"`name` TEXT NOT NULL);"
		"CREATE TABLE IF NOT EXISTS `action` ("
			"`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
			"`actor` INTEGER NOT NULL,"
			"`timestamp` TIMESTAMP NOT NULL,"
			"`type` INTEGER NOT NULL,"
			"`list` TEXT,"
			"`index` INTEGER,"
			"`add` INTEGER,"
			"`stackNode` INTEGER,"
			"`stackQuantity` INTEGER,"
			"`nodeMeta` INTEGER,"
			"`x` INT,"
			"`y` INT,"
			"`z` INT,"
			"`oldNode` INTEGER,"
			"`oldParam1` INTEGER,"
			"`oldParam2` INTEGER,"
			"`oldMeta` TEXT,"
			"`newNode` INTEGER,"
			"`newParam1` INTEGER,"
			"`newParam2` INTEGER,"
			"`newMeta` TEXT,"
			"`guessedActor` INTEGER,"
			"FOREIGN KEY (`actor`)   REFERENCES `actor`(`id`),"
			"FOREIGN KEY (`oldNode`) REFERENCES `node`(`id`),"
			"FOREIGN KEY (`newNode`) REFERENCES `node`(`id`));"
		"CREATE INDEX IF NOT EXISTS `actionActor` ON `action`(`actor`);"
		"CREATE INDEX IF NOT EXISTS `actionTimestamp` ON `action`(`timestamp`);",
		NULL, NULL, NULL);
	if (dbs == SQLITE_ABORT) {
		throw FileNotGoodException("Could not create sqlite3 database structure");
	} else if (dbs != 0) {
		throw FileNotGoodException("SQL Rollback: Exec statement to create table structure returned a non-zero value");
	} else {
		infostream << "SQL Rollback: SQLite3 database structure was created" << std::endl;
	}

	return true;
}
void SQL_databaseCheck(void)
{
	if (dbh) {
		return;
	}

	infostream << "Database connection setup" << std::endl;

	bool needsCreate = !fs::PathExists(dbp);
	int  dbo = sqlite3_open_v2(dbp.c_str(), &dbh, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
	                           NULL);

	if (dbo != SQLITE_OK) {
		infostream << "SQLROLLBACK: SQLite3 database failed to open: "
		           << sqlite3_errmsg(dbh) << std::endl;
		throw FileNotGoodException("Cannot open database file");
	}

	if (needsCreate) {
		SQL_createDatabase();
	}

	int dbr;

	dbr = sqlite3_prepare_v2(dbh,
		"INSERT INTO `action` ("
		"	`actor`, `timestamp`, `type`,"
		"	`list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,"
		"	`x`, `y`, `z`,"
		"	`oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,"
		"	`newNode`, `newParam1`, `newParam2`, `newMeta`,"
		"	`guessedActor`"
		") VALUES ("
		"	?, ?, ?,"
		"	?, ?, ?, ?, ?, ?,"
		"	?, ?, ?,"
		"	?, ?, ?, ?,"
		"	?, ?, ?, ?,"
		"	?"
		");",
		-1, &dbs_insert, NULL);

	if (dbr != SQLITE_OK) {
		throw FileNotGoodException(sqlite3_errmsg(dbh));
	}

	dbr = sqlite3_prepare_v2(dbh,
		"REPLACE INTO `action` ("
		"	`actor`, `timestamp`, `type`,"
		"	`list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,"
		"	`x`, `y`, `z`,"
		"	`oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,"
		"	`newNode`, `newParam1`, `newParam2`, `newMeta`,"
		"	`guessedActor`, `id`"
		") VALUES ("
		"	?, ?, ?,"
		"	?, ?, ?, ?, ?, ?,"
		"	?, ?, ?,"
		"	?, ?, ?, ?,"
		"	?, ?, ?, ?,"
		"	?, ?"
		");",
		-1, &dbs_replace, NULL);

	if (dbr != SQLITE_OK) {
		throw FileNotGoodException(sqlite3_errmsg(dbh));
	}

	dbr = sqlite3_prepare_v2(dbh,
		"SELECT"
		"	`actor`, `timestamp`, `type`,"
		"	`list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,"
		"	`x`, `y`, `z`,"
		"	`oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,"
		"	`newNode`, `newParam1`, `newParam2`, `newMeta`,"
		"	`guessedActor`"
		" FROM	`action`"
		" WHERE	`timestamp` >= ?"
		" ORDER BY `timestamp` DESC, `id` DESC",
		-1, &dbs_select, NULL);
	if (dbr != SQLITE_OK) {
		throw FileNotGoodException(itos(dbr).c_str());
	}

	dbr = sqlite3_prepare_v2(dbh,
		"SELECT"
		"	`actor`, `timestamp`, `type`,"
		"	`list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,"
		"	`x`, `y`, `z`,"
		"	`oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,"
		"	`newNode`, `newParam1`, `newParam2`, `newMeta`,"
		"	`guessedActor`"
		" FROM	`action`"
		" WHERE	`timestamp` >= ?"
		" AND   `x` IS NOT NULL"
		" AND   `y` IS NOT NULL"
		" AND   `z` IS NOT NULL"
		" AND   ABS(`x` - ?) <= ?"
		" AND   ABS(`y` - ?) <= ?"
		" AND   ABS(`z` - ?) <= ?"
		" ORDER BY `timestamp` DESC, `id` DESC"
		" LIMIT 0,?",
		-1, &dbs_select_range, NULL);
	if (dbr != SQLITE_OK) {
		throw FileNotGoodException(itos(dbr).c_str());
	}

	dbr = sqlite3_prepare_v2(dbh,
		"SELECT"
		"	`actor`, `timestamp`, `type`,"
		"	`list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,"
		"	`x`, `y`, `z`,"
		"	`oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,"
		"	`newNode`, `newParam1`, `newParam2`, `newMeta`,"
		"	`guessedActor`"
		" FROM	`action`"
		" WHERE	`timestamp` >= ?"
		" AND   `actor` = ?"
		" ORDER BY `timestamp` DESC, `id` DESC",
		-1, &dbs_select_withActor, NULL);
	if (dbr != SQLITE_OK) {
		throw FileNotGoodException(itos(dbr).c_str());
	}

	dbr = sqlite3_prepare_v2(dbh, "SELECT `id`, `name` FROM `actor`", -1,
	                         &dbs_knownActor_select, NULL);
	if (dbr != SQLITE_OK) {
		throw FileNotGoodException(itos(dbr).c_str());
	}

	dbr = sqlite3_prepare_v2(dbh, "INSERT INTO `actor` (`name`) VALUES (?)", -1,
	                         &dbs_knownActor_insert, NULL);
	if (dbr != SQLITE_OK) {
		throw FileNotGoodException(itos(dbr).c_str());
	}

	dbr = sqlite3_prepare_v2(dbh, "SELECT `id`, `name` FROM `node`", -1,
	                         &dbs_knownNode_select, NULL);
	if (dbr != SQLITE_OK) {
		throw FileNotGoodException(itos(dbr).c_str());
	}

	dbr = sqlite3_prepare_v2(dbh, "INSERT INTO `node` (`name`) VALUES (?)", -1,
	                         &dbs_knownNode_insert, NULL);
	if (dbr != SQLITE_OK) {
		throw FileNotGoodException(itos(dbr).c_str());
	}

	infostream << "SQL prepared statements setup correctly" << std::endl;

	int select;

	sqlite3_reset(dbs_knownActor_select);
	while (SQLITE_ROW == (select = sqlite3_step(dbs_knownActor_select)))
		registerNewActor(
		        sqlite3_column_int(dbs_knownActor_select, 0),
		        reinterpret_cast<const char *>(sqlite3_column_text(dbs_knownActor_select, 1))
		);

	sqlite3_reset(dbs_knownNode_select);
	while (SQLITE_ROW == (select = sqlite3_step(dbs_knownNode_select)))
		registerNewNode(
		        sqlite3_column_int(dbs_knownNode_select, 0),
		        reinterpret_cast<const char *>(sqlite3_column_text(dbs_knownNode_select, 1))
		);

	return;
}
bool SQL_registerRow(ActionRow row)
{
	SQL_databaseCheck();

	sqlite3_stmt * dbs_do = (row.id) ? dbs_replace : dbs_insert;

	/*
	std::cout
		<< (row.id? "Replacing": "Inserting")
		<< " ActionRow" << std::endl;
	*/
	sqlite3_reset(dbs_do);

	int bind [22], ii = 0;
	bool nodeMeta = false;

	bind[ii++] = sqlite3_bind_int(dbs_do, 1, row.actor);
	bind[ii++] = sqlite3_bind_int64(dbs_do, 2, row.timestamp);
	bind[ii++] = sqlite3_bind_int(dbs_do, 3, row.type);

	if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
		std::string loc		= row.location;
		std::string locType	= loc.substr(0, loc.find(":"));
		nodeMeta = (locType == "nodemeta");

		bind[ii++] = sqlite3_bind_text(dbs_do, 4, row.list.c_str(), row.list.size(), NULL);
		bind[ii++] = sqlite3_bind_int(dbs_do, 5, row.index);
		bind[ii++] = sqlite3_bind_int(dbs_do, 6, row.add);
		bind[ii++] = sqlite3_bind_int(dbs_do, 7, row.stack.node);
		bind[ii++] = sqlite3_bind_int(dbs_do, 8, row.stack.quantity);
		bind[ii++] = sqlite3_bind_int(dbs_do, 9, (int) nodeMeta);

		if (nodeMeta) {
			std::string x, y, z;
			int	l, r;
			l = loc.find(':') + 1;
			r = loc.find(',');
			x = loc.substr(l, r - l);
			l = r + 1;
			r = loc.find(',', l);
			y = loc.substr(l, r - l);
			z = loc.substr(r + 1);
			bind[ii++] = sqlite3_bind_int(dbs_do, 10, atoi(x.c_str()));
			bind[ii++] = sqlite3_bind_int(dbs_do, 11, atoi(y.c_str()));
			bind[ii++] = sqlite3_bind_int(dbs_do, 12, atoi(z.c_str()));
		}
	} else {
		bind[ii++] = sqlite3_bind_null(dbs_do, 4);
		bind[ii++] = sqlite3_bind_null(dbs_do, 5);
		bind[ii++] = sqlite3_bind_null(dbs_do, 6);
		bind[ii++] = sqlite3_bind_null(dbs_do, 7);
		bind[ii++] = sqlite3_bind_null(dbs_do, 8);
		bind[ii++] = sqlite3_bind_null(dbs_do, 9);
	}

	if (row.type == RollbackAction::TYPE_SET_NODE) {
		bind[ii++] = sqlite3_bind_int(dbs_do, 10, row.x);
		bind[ii++] = sqlite3_bind_int(dbs_do, 11, row.y);
		bind[ii++] = sqlite3_bind_int(dbs_do, 12, row.z);
		bind[ii++] = sqlite3_bind_int(dbs_do, 13, row.oldNode);
		bind[ii++] = sqlite3_bind_int(dbs_do, 14, row.oldParam1);
		bind[ii++] = sqlite3_bind_int(dbs_do, 15, row.oldParam2);
		bind[ii++] = sqlite3_bind_text(dbs_do, 16, row.oldMeta.c_str(), row.oldMeta.size(), NULL);
		bind[ii++] = sqlite3_bind_int(dbs_do, 17, row.newNode);
		bind[ii++] = sqlite3_bind_int(dbs_do, 18, row.newParam1);
		bind[ii++] = sqlite3_bind_int(dbs_do, 19, row.newParam2);
		bind[ii++] = sqlite3_bind_text(dbs_do, 20, row.newMeta.c_str(), row.newMeta.size(), NULL);
		bind[ii++] = sqlite3_bind_int(dbs_do, 21, row.guessed ? 1 : 0);
	} else {
		if (!nodeMeta) {
			bind[ii++] = sqlite3_bind_null(dbs_do, 10);
			bind[ii++] = sqlite3_bind_null(dbs_do, 11);
			bind[ii++] = sqlite3_bind_null(dbs_do, 12);
		}
		bind[ii++] = sqlite3_bind_null(dbs_do, 13);
		bind[ii++] = sqlite3_bind_null(dbs_do, 14);
		bind[ii++] = sqlite3_bind_null(dbs_do, 15);
		bind[ii++] = sqlite3_bind_null(dbs_do, 16);
		bind[ii++] = sqlite3_bind_null(dbs_do, 17);
		bind[ii++] = sqlite3_bind_null(dbs_do, 18);
		bind[ii++] = sqlite3_bind_null(dbs_do, 19);
		bind[ii++] = sqlite3_bind_null(dbs_do, 20);
		bind[ii++] = sqlite3_bind_null(dbs_do, 21);
	}

	if (row.id) {
		bind[ii++] = sqlite3_bind_int(dbs_do, 22, row.id);
	}

	for (ii = 0; ii < 20; ++ii)
		if (bind[ii] != SQLITE_OK)
			infostream
			                << "WARNING: failed to bind param " << ii + 1
			                << " when inserting an entry in table setnode" << std::endl;

	/*
	std::cout << "========DB-WRITTEN==========" << std::endl;
	std::cout << "id:        " << row.id << std::endl;
	std::cout << "actor:     " << row.actor << std::endl;
	std::cout << "time:      " << row.timestamp << std::endl;
	std::cout << "type:      " << row.type << std::endl;
	if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
	{
		std::cout << "Location:   " << row.location << std::endl;
		std::cout << "List:       " << row.list << std::endl;
		std::cout << "Index:      " << row.index << std::endl;
		std::cout << "Add:        " << row.add << std::endl;
		std::cout << "Stack:      " << row.stack << std::endl;
	}
	if (row.type == RollbackAction::TYPE_SET_NODE)
	{
		std::cout << "x:         " << row.x << std::endl;
		std::cout << "y:         " << row.y << std::endl;
		std::cout << "z:         " << row.z << std::endl;
		std::cout << "oldNode:   " << row.oldNode << std::endl;
		std::cout << "oldParam1: " << row.oldParam1 << std::endl;
		std::cout << "oldParam2: " << row.oldParam2 << std::endl;
		std::cout << "oldMeta:   " << row.oldMeta << std::endl;
		std::cout << "newNode:   " << row.newNode << std::endl;
		std::cout << "newParam1: " << row.newParam1 << std::endl;
		std::cout << "newParam2: " << row.newParam2 << std::endl;
		std::cout << "newMeta:   " << row.newMeta << std::endl;
		std::cout << "DESERIALIZE" << row.newMeta.c_str() << std::endl;
		std::cout << "guessed:   " << row.guessed << std::endl;
	}
	*/

	int written = sqlite3_step(dbs_do);

	return written == SQLITE_DONE;

	//if  (written != SQLITE_DONE)
	//	 std::cout << "WARNING: rollback action not written: " << sqlite3_errmsg(dbh) << std::endl;
	//else std::cout << "Action correctly inserted via SQL" << std::endl;
}
std::list<ActionRow> actionRowsFromSelect(sqlite3_stmt* stmt)
{
	std::list<ActionRow> rows;
	const unsigned char * text;
	size_t size;

	while (SQLITE_ROW == sqlite3_step(stmt)) {
		ActionRow row;

		row.actor     = sqlite3_column_int(stmt, 0);
		row.timestamp = sqlite3_column_int64(stmt, 1);
		row.type      = sqlite3_column_int(stmt, 2);

		if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
			text               = sqlite3_column_text(stmt, 3);
			size               = sqlite3_column_bytes(stmt, 3);
			row.list           = std::string(reinterpret_cast<const char*>(text), size);
			row.index          = sqlite3_column_int(stmt, 4);
			row.add            = sqlite3_column_int(stmt, 5);
			row.stack.node     = sqlite3_column_int(stmt, 6);
			row.stack.quantity = sqlite3_column_int(stmt, 7);
			row.nodeMeta       = sqlite3_column_int(stmt, 8);
		}

		if (row.type == RollbackAction::TYPE_SET_NODE || row.nodeMeta) {
			row.x = sqlite3_column_int(stmt,  9);
			row.y = sqlite3_column_int(stmt, 10);
			row.z = sqlite3_column_int(stmt, 11);
		}

		if (row.type == RollbackAction::TYPE_SET_NODE) {
			row.oldNode		= sqlite3_column_int(stmt, 12);
			row.oldParam1 = sqlite3_column_int(stmt, 13);
			row.oldParam2 = sqlite3_column_int(stmt, 14);
			text          = sqlite3_column_text(stmt, 15);
			size          = sqlite3_column_bytes(stmt, 15);
			row.oldMeta   = std::string(reinterpret_cast<const char*>(text), size);
			row.newNode   = sqlite3_column_int(stmt, 16);
			row.newParam1 = sqlite3_column_int(stmt, 17);
			row.newParam2 = sqlite3_column_int(stmt, 18);
			text          = sqlite3_column_text(stmt, 19);
			size          = sqlite3_column_bytes(stmt, 19);
			row.newMeta   = std::string(reinterpret_cast<const char*>(text), size);
			row.guessed   = sqlite3_column_int(stmt, 20);
		}

		row.location = row.nodeMeta ? "nodemeta:" : getActorName(row.actor);

		if (row.nodeMeta) {
			row.location.append(itos(row.x));
			row.location.append(",");
			row.location.append(itos(row.y));
			row.location.append(",");
			row.location.append(itos(row.z));
		}

		/*
		std::cout << "=======SELECTED==========" << "\n";
		std::cout << "Actor: " << row.actor << "\n";
		std::cout << "Timestamp: " << row.timestamp << "\n";

		if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
		{
			std::cout << "list: " << row.list << "\n";
			std::cout << "index: " << row.index << "\n";
			std::cout << "add: " << row.add << "\n";
			std::cout << "stackNode: " << row.stack.node << "\n";
			std::cout << "stackQuantity: " << row.stack.quantity << "\n";
			if (row.nodeMeta)
			{
				std::cout << "X: " << row.x << "\n";
				std::cout << "Y: " << row.y << "\n";
				std::cout << "Z: " << row.z << "\n";
			}
			std::cout << "Location: " << row.location << "\n";
		}
			else
		{
			std::cout << "X: " << row.x << "\n";
			std::cout << "Y: " << row.y << "\n";
			std::cout << "Z: " << row.z << "\n";
			std::cout << "oldNode: " << row.oldNode << "\n";
			std::cout << "oldParam1: " << row.oldParam1 << "\n";
			std::cout << "oldParam2: " << row.oldParam2 << "\n";
			std::cout << "oldMeta: " << row.oldMeta << "\n";
			std::cout << "newNode: " << row.newNode << "\n";
			std::cout << "newParam1: " << row.newParam1 << "\n";
			std::cout << "newParam2: " << row.newParam2 << "\n";
			std::cout << "newMeta: " << row.newMeta << "\n";
			std::cout << "guessed: " << row.guessed << "\n";
		}
		*/

		rows.push_back(row);
	}

	return rows;
}
ActionRow actionRowFromRollbackAction(RollbackAction action)
{
	ActionRow row;

	row.id        = 0;
	row.actor     = getActorId(action.actor);
	row.timestamp = action.unix_time;
	row.type      = action.type;

	if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
		row.location = action.inventory_location;
		row.list     = action.inventory_list;
		row.index    = action.inventory_index;
		row.add      = action.inventory_add;
		row.stack    = getStackFromString(action.inventory_stack);
	} else {
		row.x         = action.p.X;
		row.y         = action.p.Y;
		row.z         = action.p.Z;
		row.oldNode   = getNodeId(action.n_old.name);
		row.oldParam1 = action.n_old.param1;
		row.oldParam2 = action.n_old.param2;
		row.oldMeta   = action.n_old.meta;
		row.newNode   = getNodeId(action.n_new.name);
		row.newParam1 = action.n_new.param1;
		row.newParam2 = action.n_new.param2;
		row.newMeta   = action.n_new.meta;
		row.guessed   = action.actor_is_guess;
	}

	return row;
}
std::list<RollbackAction> rollbackActionsFromActionRows(std::list<ActionRow> rows)
{
	std::list<RollbackAction> actions;
	std::list<ActionRow>::const_iterator it;

	for (it = rows.begin(); it != rows.end(); ++it) {
		RollbackAction action;
		action.actor     = (it->actor) ? getActorName(it->actor) : "";
		action.unix_time = it->timestamp;
		action.type      = static_cast<RollbackAction::Type>(it->type);

		switch (action.type) {
		case RollbackAction::TYPE_MODIFY_INVENTORY_STACK:

			action.inventory_location = it->location.c_str();
			action.inventory_list     = it->list;
			action.inventory_index    = it->index;
			action.inventory_add      = it->add;
			action.inventory_stack    = getStringFromStack(it->stack);
			break;

		case RollbackAction::TYPE_SET_NODE:

			action.p            = v3s16(it->x, it->y, it->z);
			action.n_old.name   = getNodeName(it->oldNode);
			action.n_old.param1 = it->oldParam1;
			action.n_old.param2 = it->oldParam2;
			action.n_old.meta   = it->oldMeta;
			action.n_new.name   = getNodeName(it->newNode);
			action.n_new.param1 = it->newParam1;
			action.n_new.param2 = it->newParam2;
			action.n_new.meta   = it->newMeta;
			break;

		default:

			throw ("W.T.F.");
			break;
		}

		actions.push_back(action);
	}

	return actions;
}

std::list<ActionRow> SQL_getRowsSince(time_t firstTime, std::string actor = "")
{
	sqlite3_stmt *dbs_stmt = (!actor.length()) ? dbs_select : dbs_select_withActor;
	sqlite3_reset(dbs_stmt);
	sqlite3_bind_int64(dbs_stmt, 1, firstTime);

	if (actor.length()) {
		sqlite3_bind_int(dbs_stmt, 2, getActorId(actor));
	}

	return actionRowsFromSelect(dbs_stmt);
}

std::list<ActionRow> SQL_getRowsSince_range(time_t firstTime, v3s16 p, int range,
                int limit)
{
	sqlite3_stmt *stmt = dbs_select_range;
	sqlite3_reset(stmt);

	sqlite3_bind_int64(stmt, 1, firstTime);
	sqlite3_bind_int(stmt, 2, (int) p.X);
	sqlite3_bind_int(stmt, 3, range);
	sqlite3_bind_int(stmt, 4, (int) p.Y);
	sqlite3_bind_int(stmt, 5, range);
	sqlite3_bind_int(stmt, 6, (int) p.Z);
	sqlite3_bind_int(stmt, 7, range);
	sqlite3_bind_int(stmt, 8, limit);

	return actionRowsFromSelect(stmt);
}

std::list<RollbackAction> SQL_getActionsSince_range(time_t firstTime, v3s16 p, int range,
                int limit)
{
	std::list<ActionRow> rows = SQL_getRowsSince_range(firstTime, p, range, limit);

	return rollbackActionsFromActionRows(rows);
}

std::list<RollbackAction> SQL_getActionsSince(time_t firstTime, std::string actor = "")
{
	std::list<ActionRow> rows = SQL_getRowsSince(firstTime, actor);
	return rollbackActionsFromActionRows(rows);
}

void TXT_migrate(std::string filepath)
{
	std::cout << "Migrating from rollback.txt to rollback.sqlite" << std::endl;
	SQL_databaseCheck();

	std::ifstream fh(filepath.c_str(), std::ios::in | std::ios::ate);
	if (!fh.good()) {
		throw ("DIE");
	}

	std::streampos filesize = fh.tellg();

	if (filesize > 10) {
		fh.seekg(0);

		std::string bit;
		int i   = 0;
		int id  = 1;
		time_t t   = 0;
		do {
			ActionRow row;

			row.id = id;

			// Get the timestamp
			std::getline(fh, bit, ' ');
			bit = trim(bit);
			if (!atoi(trim(bit).c_str())) {
				std::getline(fh, bit);
				continue;
			}
			row.timestamp = atoi(bit.c_str());

			// Get the actor
			row.actor = getActorId(trim(deSerializeJsonString(fh)));

			// Get the action type
			std::getline(fh, bit, '[');
			std::getline(fh, bit, ' ');

			if (bit == "modify_inventory_stack") {
				row.type = RollbackAction::TYPE_MODIFY_INVENTORY_STACK;
			}

			if (bit == "set_node") {
				row.type = RollbackAction::TYPE_SET_NODE;
			}

			if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
				row.location = trim(deSerializeJsonString(fh));
				std::getline(fh, bit, ' ');
				row.list     = trim(deSerializeJsonString(fh));
				std::getline(fh, bit, ' ');
				std::getline(fh, bit, ' ');
				row.index    = atoi(trim(bit).c_str());
				std::getline(fh, bit, ' ');
				row.add      = (int)(trim(bit) == "add");
				row.stack    = getStackFromString(trim(deSerializeJsonString(fh)));
				std::getline(fh, bit);
			} else if (row.type == RollbackAction::TYPE_SET_NODE) {
				std::getline(fh, bit, '(');
				std::getline(fh, bit, ',');
				row.x       = atoi(trim(bit).c_str());
				std::getline(fh, bit, ',');
				row.y       = atoi(trim(bit).c_str());
				std::getline(fh, bit, ')');
				row.z       = atoi(trim(bit).c_str());
				std::getline(fh, bit, ' ');
				row.oldNode = getNodeId(trim(deSerializeJsonString(fh)));
				std::getline(fh, bit, ' ');
				std::getline(fh, bit, ' ');
				row.oldParam1 = atoi(trim(bit).c_str());
				std::getline(fh, bit, ' ');
				row.oldParam2 = atoi(trim(bit).c_str());
				row.oldMeta   = trim(deSerializeJsonString(fh));
				std::getline(fh, bit, ' ');
				row.newNode   = getNodeId(trim(deSerializeJsonString(fh)));
				std::getline(fh, bit, ' ');
				std::getline(fh, bit, ' ');
				row.newParam1 = atoi(trim(bit).c_str());
				std::getline(fh, bit, ' ');
				row.newParam2 = atoi(trim(bit).c_str());
				row.newMeta   = trim(deSerializeJsonString(fh));
				std::getline(fh, bit, ' ');
				std::getline(fh, bit, ' ');
				std::getline(fh, bit);
				row.guessed = (int)(trim(bit) == "actor_is_guess");
			}

			/*
			std::cout << "==========READ===========" << std::endl;
			std::cout << "time:      " << row.timestamp << std::endl;
			std::cout << "actor:     " << row.actor << std::endl;
			std::cout << "type:      " << row.type << std::endl;
			if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
			{