aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorsfan5 <sfan5@live.de>2019-11-14 17:38:15 +0100
committerrubenwardy <rw@rubenwardy.com>2019-12-31 21:31:53 +0000
commit1c61fe5ed930720485ef42571739e5efc39a14c9 (patch)
tree66e72a976a8aa7c5a88343181e69a3bfa21ebcc9
parent57409ef382509a4a293683b78b44816ee29bb8d4 (diff)
Rework packet receiving in ServerThread
Notably it tries to receive all queued packets between server steps, not just one.
-rw-r--r--src/network/connection.cpp27
-rw-r--r--src/network/connection.h3
-rw-r--r--src/network/networkpacket.cpp9
-rw-r--r--src/network/networkpacket.h1
-rw-r--r--src/server.cpp70
5 files changed, 86 insertions, 24 deletions
diff --git a/src/network/connection.cpp b/src/network/connection.cpp
index 0bc13a2f0..a99e5b145 100644
--- a/src/network/connection.cpp
+++ b/src/network/connection.cpp
@@ -1323,16 +1323,21 @@ void Connection::Disconnect()
putCommand(c);
}
-void Connection::Receive(NetworkPacket* pkt)
+bool Connection::Receive(NetworkPacket *pkt, u32 timeout)
{
+ /*
+ Note that this function can potentially wait infinitely if non-data
+ events keep happening before the timeout expires.
+ This is not considered to be a problem (is it?)
+ */
for(;;) {
- ConnectionEvent e = waitEvent(m_bc_receive_timeout);
+ ConnectionEvent e = waitEvent(timeout);
if (e.type != CONNEVENT_NONE)
LOG(dout_con << getDesc() << ": Receive: got event: "
<< e.describe() << std::endl);
switch(e.type) {
case CONNEVENT_NONE:
- throw NoIncomingDataException("No incoming data");
+ return false;
case CONNEVENT_DATA_RECEIVED:
// Data size is lesser than command size, ignoring packet
if (e.data.getSize() < 2) {
@@ -1340,7 +1345,7 @@ void Connection::Receive(NetworkPacket* pkt)
}
pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
- return;
+ return true;
case CONNEVENT_PEER_ADDED: {
UDPPeer tmp(e.peer_id, e.address, this);
if (m_bc_peerhandler)
@@ -1358,7 +1363,19 @@ void Connection::Receive(NetworkPacket* pkt)
"(port already in use?)");
}
}
- throw NoIncomingDataException("No incoming data");
+ return false;
+}
+
+void Connection::Receive(NetworkPacket *pkt)
+{
+ bool any = Receive(pkt, m_bc_receive_timeout);
+ if (!any)
+ throw NoIncomingDataException("No incoming data");
+}
+
+bool Connection::TryReceive(NetworkPacket *pkt)
+{
+ return Receive(pkt, 0);
}
void Connection::Send(session_t peer_id, u8 channelnum,
diff --git a/src/network/connection.h b/src/network/connection.h
index 057bd39f6..d7f1e0fe8 100644
--- a/src/network/connection.h
+++ b/src/network/connection.h
@@ -771,6 +771,7 @@ public:
bool Connected();
void Disconnect();
void Receive(NetworkPacket* pkt);
+ bool TryReceive(NetworkPacket *pkt);
void Send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable);
session_t GetPeerID() const { return m_peer_id; }
Address GetPeerAddress(session_t peer_id);
@@ -803,6 +804,8 @@ protected:
UDPSocket m_udpSocket;
MutexedQueue<ConnectionCommand> m_command_queue;
+ bool Receive(NetworkPacket *pkt, u32 timeout);
+
void putEvent(ConnectionEvent &e);
void TriggerSend();
diff --git a/src/network/networkpacket.cpp b/src/network/networkpacket.cpp
index 22c035c5b..4d531b611 100644
--- a/src/network/networkpacket.cpp
+++ b/src/network/networkpacket.cpp
@@ -66,6 +66,15 @@ void NetworkPacket::putRawPacket(u8 *data, u32 datasize, session_t peer_id)
memcpy(m_data.data(), &data[2], m_datasize);
}
+void NetworkPacket::clear()
+{
+ m_data.clear();
+ m_datasize = 0;
+ m_read_offset = 0;
+ m_command = 0;
+ m_peer_id = 0;
+}
+
const char* NetworkPacket::getString(u32 from_offset)
{
checkReadOffset(from_offset, 0);
diff --git a/src/network/networkpacket.h b/src/network/networkpacket.h
index a8b741374..fc8617651 100644
--- a/src/network/networkpacket.h
+++ b/src/network/networkpacket.h
@@ -35,6 +35,7 @@ public:
~NetworkPacket();
void putRawPacket(u8 *data, u32 datasize, session_t peer_id);
+ void clear();
// Getters
u32 getSize() const { return m_datasize; }
diff --git a/src/server.cpp b/src/server.cpp
index 4aa8375c8..d914beead 100644
--- a/src/server.cpp
+++ b/src/server.cpp
@@ -93,6 +93,15 @@ void *ServerThread::run()
{
BEGIN_DEBUG_EXCEPTION_HANDLER
+ /*
+ * The real business of the server happens on the ServerThread.
+ * How this works:
+ * AsyncRunStep() runs an actual server step as soon as enough time has
+ * passed (dedicated_server_loop keeps track of that).
+ * Receive() blocks at least(!) 30ms waiting for a packet (so this loop
+ * doesn't busy wait) and will process any remaining packets.
+ */
+
m_server->AsyncRunStep(true);
while (!stopRequested()) {
@@ -101,7 +110,6 @@ void *ServerThread::run()
m_server->Receive();
- } catch (con::NoIncomingDataException &e) {
} catch (con::PeerNotFoundException &e) {
infostream<<"Server: PeerNotFoundException"<<std::endl;
} catch (ClientNotFoundException &e) {
@@ -911,24 +919,43 @@ void Server::AsyncRunStep(bool initial_step)
void Server::Receive()
{
- session_t peer_id = 0;
- try {
- NetworkPacket pkt;
- m_con->Receive(&pkt);
- peer_id = pkt.getPeerId();
- ProcessData(&pkt);
- } catch (const con::InvalidIncomingDataException &e) {
- infostream << "Server::Receive(): InvalidIncomingDataException: what()="
- << e.what() << std::endl;
- } catch (const SerializationError &e) {
- infostream << "Server::Receive(): SerializationError: what()="
- << e.what() << std::endl;
- } catch (const ClientStateError &e) {
- errorstream << "ProcessData: peer=" << peer_id << e.what() << std::endl;
- DenyAccess_Legacy(peer_id, L"Your client sent something server didn't expect."
- L"Try reconnecting or updating your client");
- } catch (const con::PeerNotFoundException &e) {
- // Do nothing
+ NetworkPacket pkt;
+ session_t peer_id;
+ bool first = true;
+ for (;;) {
+ pkt.clear();
+ peer_id = 0;
+ try {
+ /*
+ In the first iteration *wait* for a packet, afterwards process
+ all packets that are immediately available (no waiting).
+ */
+ if (first) {
+ m_con->Receive(&pkt);
+ first = false;
+ } else {
+ if (!m_con->TryReceive(&pkt))
+ return;
+ }
+
+ peer_id = pkt.getPeerId();
+ ProcessData(&pkt);
+ } catch (const con::InvalidIncomingDataException &e) {
+ infostream << "Server::Receive(): InvalidIncomingDataException: what()="
+ << e.what() << std::endl;
+ } catch (const SerializationError &e) {
+ infostream << "Server::Receive(): SerializationError: what()="
+ << e.what() << std::endl;
+ } catch (const ClientStateError &e) {
+ errorstream << "ProcessData: peer=" << peer_id << " what()="
+ << e.what() << std::endl;
+ DenyAccess_Legacy(peer_id, L"Your client sent something server didn't expect."
+ L"Try reconnecting or updating your client");
+ } catch (const con::PeerNotFoundException &e) {
+ // Do nothing
+ } catch (const con::NoIncomingDataException &e) {
+ return;
+ }
}
}
@@ -3728,6 +3755,11 @@ void dedicated_server_loop(Server &server, bool &kill)
static thread_local const float profiler_print_interval =
g_settings->getFloat("profiler_print_interval");
+ /*
+ * The dedicated server loop only does time-keeping (in Server::step) and
+ * provides a way to main.cpp to kill the server externally (bool &kill).
+ */
+
for(;;) {
// This is kind of a hack but can be done like this
// because server.step() is very light
3 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 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
\documentclass[notitlepage]{article}
\ifdefined\HCode
  \def\pgfsysdriver{pgfsys-dvisvgm4ht.def} % for HTML output
\fi
\usepackage[a4paper,margin=2cm]{geometry}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\ifx\HCode\undefined
\usepackage{beton}
\usepackage{eulervm}
\fi
\setlength{\parindent}{0pt}
\setlength{\parskip}{1ex}
\usepackage{listings}
\usepackage{hyperref}
\usepackage{amsmath,amssymb,siunitx}
\usepackage[x11names,svgnames]{xcolor}
\usepackage{tikz}
\usetikzlibrary{arrows,backgrounds,calc,patterns,shapes.geometric}

\usepackage{imakeidx}
\makeindex[columns=1,title=Alphabetical Index,intoc]

% Font substitution: taken from https://ctan.org/tex-archive/macros/latex/contrib/beton/beton.pdf
\ifx\HCode\undefined
\AtBeginDocument{
  \DeclareFontShape\encodingdefault{ccr}{bx}{n}{<->sub*cmss/sbc/n}{}
  \DeclareFontShape\encodingdefault{ccr}{bx}{it}{<->sub*cmss/sbc/it}{}
  \DeclareFontShape\encodingdefault{ccr}{bx}{sl}{<->sub*cmss/sbc/sl}{}
  \DeclareFontShape\encodingdefault{ccr}{bx}{sc}{<->sub*cmss/sbc/sc}{}
}
\fi

\lstdefinestyle{luastyle}{
  language=[5.1]Lua,
  basicstyle=\ttfamily,
  columns=spaceflexible,
  tabsize=2
}

\ifdefined\HCode
\newcommand{\var}[1]{$\langle$\texttt{#1}$\rangle$}
\newcommand{\varnth}[2]{\var{#1\HCode{<sub>}#2\HCode{</sub>}}}
\newcommand{\ovar}[1]{$[\langle$\texttt{#1}$\rangle]$}
\else
\newcommand{\var}[1]{$\mathit{\langle}$\textrm{\textmd{\textit{#1}}}$\mathit{\rangle}$}
\newcommand{\varnth}[2]{\var{#1$_{#2}$}}
\newcommand{\ovar}[1]{$\mathit{[\langle}$\textrm{\textmd{\textit{#1}}}$\mathit{\rangle]}$}
\fi

\newcommand{\varzero}[1]{\varnth{#1}{0}}
\newcommand{\vari}[1]{\varnth{#1}{1}}
\newcommand{\varii}[1]{\varnth{#1}{2}}

\def\luatrue{\texttt{true}}
\def\luafalse{\texttt{false}}
\def\luanil{\texttt{nil}}
\def\luanan{\texttt{nan}}
\def\advtrains{\textsc{advtrains}}

\newenvironment{centeredtikzpicture}[1][]{
  \begin{center}
    \begin{tikzpicture}[#1]
    }{
    \end{tikzpicture}
  \end{center}
}

\newenvironment{apidoc}[1]{
  \begin{list}{}{
  \setlength{\labelwidth}{0pt}
  \setlength{\labelsep}{0pt}
  \setlength{\leftmargin}{0pt}
  \setlength{\listparindent}{1em}
}
\index{#1}
\ifdefined\HCode
\providecommand{\apientp}[2]{\HCode{<br/>}##1\HCode{<span style="float:right">}##2\HCode{</span><br/>}}
\else
\providecommand{\apientp}[2]{##1\hfill {##2}\par}
\fi
\providecommand{\apient}[2]{\apientp{##1}{##2}\index{##1}}
\providecommand{\apip}[2]{\apientp{\texttt{##1}}{##2}}
\providecommand{\api}[2]{\apient{\texttt{##1}}{##2}}
\providecommand{\apiasp}[1]{\apientp{##1}{signal aspect}\index{#1!##1}}
\providecommand{\apicmd}[1]{\api{##1}{command}}
\providecommand{\apienum}[1]{\apip{##1}{enumeration}}
\providecommand{\apifield}[1]{\apip{##1}{field}}
\providecommand{\apiitem}[1]{\apient{##1}{item}}
\providecommand{\apivar}[1]{\apip{##1}{variable}\index{#1!\texttt{##1}}}
\providecommand{\apifunc}[2]{\apip{##1(##2)}{function}\index{#1!\texttt{##1}}}
\providecommand{\apilex}[1]{\apip{##1}{lexical syntax}}
\providecommand{\apipat}[1]{\apip{##1}{pattern}}
\providecommand{\apiterm}[1]{\apient{##1}{term}}
\providecommand{\apitrainmode}[1]{\apient{##1}{train mode}}
\providecommand{\apiui}[1]{\apientp{##1}{UI element}}
}{\end{list}}

\tikzset{
  signal/.pic = {
    \draw (0,0) -- (0,0.2) -- (0.15,0.2);
    \draw [fill=#1] (0.15,0.2) circle [radius=0.05];
  },
  tcb/.pic = {
    \draw (0,0) -- (0,0.2);
    \draw [<->] (-0.15,0.2) -- (0.15,0.2);
  },
  Ks signal/.pic = {
    \fill[black] (-1,-1.3) rectangle (1,1.6);
    \fill[gray] (-0.7,1.3) circle [radius=0.1];
    \fill[gray] (0,1) circle [radius=0.2];
    \fill[gray] (-0.4,0.2) circle [radius=0.2];
    \fill[gray] (0.4,0.2) circle [radius=0.2];
    \foreach \x in {-0.3,0,0.3} {
      \fill[gray] (\x,-0.5) circle [radius=0.1];
    }
    \foreach \x in {-0.3,0} {
      \fill[gray] (\x,-0.8) circle [radius=0.1];
    }
  },
  Ks signal Hp 0/.pic = {
    \pic at (0,0) {Ks signal};
    \fill[red] (0,1) circle [radius=0.2];
  },
  Ks signal Hp 0 with Sh 1/.pic = {
    \pic at (0,0) {Ks signal Hp 0};
    \foreach \x/\y in {0/-0.5,-0.3/-0.8} {
      \fill[white] (\x,\y) circle [radius=0.1];
    }
  },
  Ks signal Ks 1/.pic = {
    \pic at (0,0) {Ks signal};
    \fill[green] (-0.4,0.2) circle [radius=0.2];
  },
  Ks signal Ks 2/.pic = {
    \pic at (0,0) {Ks signal};
    \fill[orange] (0.4,0.2) circle [radius=0.2];
  },
  shunt signal/.pic = {
    \fill[black] (-1,0) -- (-1,-1) -- (1,-1) -- (1,0) -- (0.5,0.5) -- (-0.5,0.5) -- cycle;
    \fill[gray] (-0.5,0) circle [radius=0.1];
    \fill[gray] (0.5,0) circle [radius=0.1];
    \fill[gray] (-0.5,-0.7) circle [radius=0.1];
    \fill[gray] (0.2,0) circle [radius=0.1];
  },
  shunt signal Sh 0/.pic = {
    \pic at (0,0) {shunt signal};
    \fill[red] (-0.5,0) circle [radius=0.1];
    \fill[red] (0.5,0) circle [radius=0.1];
  },
  shunt signal Sh 1/.pic = {
    \pic at (0,0) {shunt signal};
    \fill[white] (-0.5,-0.7) circle [radius=0.1];
    \fill[white] (0.2,0) circle [radius=0.1];
  },
  signal sign Zs 3/.pic = {
    \node[fill=black,text=white,regular polygon,regular polygon sides=3,inner sep=0.5ex,shape border rotate=180] at (0,0) {\Huge #1};
  },
  signal sign Zs 10/.pic = {
    \fill[black] (-1,-1) -- (0,0) -- (1,-1) -- (1,4) -- (0,5) -- (-1,4) -- cycle;
    \fill[white] (-0.8,-0.6) -- (0,0.2) -- (0.8,-0.6) -- (0.8,4) -- (0,4.8) -- (-0.8,4) -- cycle;
    \fill[black] (-0.6,-0.2) -- (0,0.4) -- (0.6,-0.2) -- (0.6,4) -- (0,4.6) -- (-0.6,4) -- cycle;
  },
  signal sign Lf 1 and 2/.pic = {
    \draw[fill=orange] (-0.5,-0.75) rectangle (0.5,0.75);
    \node at (0,0) {\Huge #1};
  },
  signal sign Lf 3/.pic = {
    \draw (-0.5,-0.75) rectangle (0.5,0.75);
    \node at (0,0) {\Huge E};
  },
  signal sign Lf 7/.pic = {
    \draw (-0.5,-0.75) rectangle (0.5,0.75);
    \node at (0,0) {\Huge #1};
  },
  signal sign Ra 10/.pic = {
    \draw (-1.5,0) -- (1.5,0) arc [start angle=0, end angle=180, radius=1.5];
    \node [above] at ($(0,0)+(0,2.4em)$) {\large Halt};
    \node [above] at ($(0,0)+(0,1.2em)$) {für};
    \node [above] at (0,0) {Rangierfahrten};
  },
  signal sign PAM/.pic = {
    \draw (-0.5,-0.5) rectangle (0.5,1);
    \node at (0,0) {\huge S};
    \draw [green,->,very thick,line width=2pt] (0,0.4) -- (0,0.8);
  }
}
\ifdefined\HCode
\tikzset{
  pattern or line fill/.style={fill=cyan}
}
\else
\tikzset{
  pattern or line fill/.style={pattern=north west lines,pattern color=gray}
}
\fi

\title{The \advtrains{} mod for Minetest}
\author{}

\begin{document}

\ifx\HCode\undefined
\thispagestyle{empty}
\begin{tikzpicture}[remember picture,overlay]
  \newcommand{\HUGE}[1]{\scalebox{2}{\Huge #1}}
  \fill[Turquoise] (current page.south west) rectangle (current page.north east);
  \node [below,inner sep=0,outer sep=0,name=coverimage] at (current page.north) {\includegraphics[width=2\paperwidth]{../../screenshot.png}};
  \draw ($0.5*(coverimage.south)+0.5*(current page.south)$)
  +(0,0.5) node [above] {\HUGE{Advanced Trains}}
  +(0,-0.5) node [below] {\HUGE{for Minetest}};
\end{tikzpicture}
\fi

\newpage
\maketitle
\tableofcontents

\newpage
\section*{Introduction}
\addcontentsline{toc}{section}{Introduction}
\advtrains{} is a mod with the goal of introducing realistic trains and rail equipments. It also has features allowing automated trains on a large scale, including interlocking and a few methods of scripting.

This manual is written for the specific version of \advtrains{} that the corresponding \LaTeX{} source is distributed with. It is divided into two parts, where the first part mainly documents the various features of \advtrains, and the second part focuses on the internals of \advtrains.

\subsection*{Acknowledgments}

A notable portion of the manual is influenced by various other guides and manuals for \advtrains. In particular:
\begin{itemize}
\item The format of the API documentation is influenced by R$^7$RS.
\item Section \ref{s:interlocking} is written with reference to orwell's interlocking guide and Blockhead's video explaining the three-station setup. The links to both sources can be found in that section.
\item Section \ref{s:luaatc} is a reformatted and restructured version of the LuaATC documentation, written by orwell and Maverick2797.
\item Section \ref{s:tilrwt} is a modified version of the railway time API documentation written by orwell. Part of the section is also taken from \texttt{advtrains\_line\_automation/railwaytime.lua}
\end{itemize}

\subsection*{Conventions}
\begin{itemize}
\item Unless otherwise specified, the unit of length is meter (or, more technically, nodes).
\item Unless otherwise specified, the unit of speed is meter per second.
\item Unless otherwise specified, the unit of acceleration is meter per second squared.
\item The \tikz \pic at (0,0) {tcb}; symbol stands for a TCB assigned to the track.
\item The \tikz \pic (0,0) {signal=red}; symbol stands for a TCB assigned to the track with a signal assigned to the TCB side opposite of that of the direction in which the TCB is facing (here: the signal is assigned to the left side of the TCB).
\item Arguments to functions and ATC commands are delimited using angle brackets \var{like this}.
\item Argument names are generally lowercase, but the first letter may be capitalized.
\item Lua string constants are written without quotation marks when the content does not resemble any numeric or symbolic constant and when used as enumerators or table indices.
\item Like in other parts of \advtrains, Lua code is indented with tabs.
\item An error situation that may or may not be reported are referred to as \textit{an error}. An error situation that is always reported is one where \textit{an error is signaled}.
\item Unless otherwise specified, the return value of any Lua API function is undefined.
\item The action of left-clicking a node with a trackworker is called \textit{rotation}. The action of right-clicking a node with a trackworker is called \textit{adjustment}.
\end{itemize}

\newpage
\part{User Guide}

\section{Tracks}

\subsection{Angles}

Unlike regular carts in Minetest, tracks can connect in 16 cardinal directions instead of four:

\begin{centeredtikzpicture}
  \draw[step=1,gray,very thin] (0,0) grid (5,5);
  \def\dirs{
    0/1,1/2,1/1,2/1,1/0,2/-1,1/-1,1/-2,
    0/-1,-1/-2,-1/-1,-2/-1,-1/0,-2/1,-1/1,-1/2
  }
  \foreach \dx/\dy in \dirs {
    \draw[pattern or line fill,shift={(\dx,\dy)}] (2,2) rectangle +(1,1);
  }
  \foreach \dx/\dy in \dirs {
    \draw[very thick,->] (2.5,2.5) -- +(\dx,\dy);
  }
  \node[circle,draw=black,fill=white,text=black] at (2.5,2.5) {A};
\end{centeredtikzpicture}

In the figure above, the filled squares show possible connections from the track at A.

Tracks that are not axis-aligned are sometimes referred to as 30\textdegree{} (although it is technically $\arcsin 0.5$) or 45\textdegree{} tracks. However, the specific meaning of the terms may depend on the context of the discussion.

The use of 16 cardinal directions instead of four allows the creation of curves that are more realistic than their counterparts made using minecart rails. A typical 90\textdegree{} curve looks like this:

\begin{centeredtikzpicture}
  \draw[step=1,gray,very thin] (0,0) grid (6,6);
  \foreach \x/\y in {0/0,0/1,1/3,2/4,4/5,5/5} {
    \draw[pattern or line fill] (\x,\y) rectangle +(1,1);
  }
  \draw[<->,very thick] (0.5,0.5) -- ++(0,1) -- ++(1,2) -- ++(1,1) -- ++(2,1) -- ++(1,0);
\end{centeredtikzpicture}

However, this is still notably smaller than in real life. For comparison, the smallest curve for the H0 model (1:87) has a radius of 360mm, which is 31.32m when scaled to real life.

\subsection{Track placement}

The usual way of placing a track is with a ``track placer'', a tool that places the tracks and, in many cases, automatically adjusts them to connect to nearby tracks.

You can get track placers from the creative inventory or by crafting. Please refer to the crafting guide for the recipe.

To place the track, simply right click the node to place the track on with the trace placer. To place slopes, face the upper end of the slope and click on the $n$th node before the upper end of the slope for a slope with an incline of $1/n$. For example, if you want to build a slope with an incline of 50\% (the slope marked gray), you would look at node A and click on node B while standing in such a way that the direction you are looking at is also the direction in which the slope goes up (e.g. at node P):
\begin{centeredtikzpicture}
  \draw[step=1,gray!50!white,thin] (-2,0) grid (3,2);
  \draw[fill=black!40!gray] (0,1) -- ++(2,0) -- ++(0,1) -- cycle;
  \foreach \x/\y/\l in {0/0/B,1/0/,2/1/A}{
    \draw[fill=cyan] (\x,\y) rectangle +(1,1);
    \node[text=black,shift={(0.5,0.5)}] at (\x,\y) {\l};
  }
  \node[text=black] at (-1.5,1.5) {P};
\end{centeredtikzpicture}

Please note that, in the figure above, the three colored nodes must already be placed.

\subsection{Track adjustment}
You can use a trackworker to make certain adjustments to tracks. Specifically,
\begin{itemize}
\item Left-clicking on a track with the trackworker toggles between the variants of the particular track, if any.
\item Right-clicking on a track with the trackworker rotates the track counterclockwise.
\end{itemize}

Typical examples of ``variants'' of tracks include turnouts and curves. Please note that Y-turnouts and different types of crossings have their own variants. These variants are described below. Additionally, special tracks (ATC track, station tracks, etc.) are usually only straight, and certain mods that provide additional tracks (e.g. linetrack) may not provide a full set of tracks available in the official track set.

\subsection{Turnouts}
Turnouts are tracks that connect tracks from more than one direction. Some examples of turnouts are shown below.

\begin{centeredtikzpicture}
  \draw[step=1,gray,thin,shift={(-0.5,-0.5)}] (0,0) grid (10,4);
  \def\turnouts{
    1/{0/-1, 0/1, -1/2},
    2/{0/-1, 0/1, 1/2},
    5/{0/-1, -1/2, 1/2},
    8/{0/-1, 0/1, -1/2, 1/2},
  }
  \foreach \base/\dirs in \turnouts {
    \draw[->, very thick] (\base,1) -- +(0,-1);
    \foreach \dx/\dy in \dirs {
      \draw[->, very thick] (\base,1) -- +(\dx,\dy);
    }
  }
\end{centeredtikzpicture}

The figure above aligns the tracks in a way that they always merge into the track that connects to the south. This is mainly done for intuitivity - you can rotate the turnouts freely in any of the 16 directions.

\subsection{Crossings}\label{s:xings}
There are a few crossing nodes that allow you to create intersections:
\begin{itemize}
\item Perpendicular crossings: intersections where two tracks are perpendicular to each other
\item $90^\circ+x$ crossings: intersections where only one of the two tracks is axis-aligned
\item diagonal crossings: other crossings that do not fit in the two categories mentioned above
\end{itemize}

Each type of crossing has its own track placer. The trackworker can not be used to switch between the different types of crossing tracks.

The figure below shows a few examples of crossings that are available.
\begin{centeredtikzpicture}[scale=0.9]
  \draw[gray,thin, shift={(-0.5,-0.5)}] (0,0) grid (11,11);
  \def\xings{
    2/2/1/2/2/1,
    2/8/2/1/1/-2,
    8/1/2/1/1/0,
    8/5/2/1/2/-1,
    8/9/2/1/1/-1
  }
  \foreach \x/\y/\ax/\ay/\bx/\by in \xings {
    \foreach \dx/\dy in {\ax/\ay,\bx/\by} {
      \draw [<->, very thick] ($(\x,\y)-(\dx,\dy)$) -- +($2*(\dx,\dy)$);
    }
  }
\end{centeredtikzpicture}

It is also possible to create track layouts without using crossings. Some examples are shown below.

\begin{centeredtikzpicture}[scale=0.9]
  \draw[gray,thin, shift={(-0.5,-0.5)}] (0,0) grid (12,4);
  \def\lines{
    0/0/3/3,0/3/3/0,
    5/0/11/3,6/3/9/0
  }
  \def\squares{
    0/0,1/1,2/2,3/3,0/3,1/2,2/1,3/0,
    5/0,7/1,9/2,11/3,6/3,7/2,8/1,9/0
  }
  \foreach \x/\y in \squares {
    \draw [pattern or line fill,shift={(-0.5,-0.5)}] (\x,\y) rectangle +(1,1);
  }
  \foreach \ax/\ay/\bx/\by in \lines {
    \draw [<->, very thick] (\ax,\ay) -- (\bx,\by);
  }
\end{centeredtikzpicture}

Exercise: Build a T junction. You will need this later in section \ref{s:iljunctions}. You can also look at the scheme in that section if you need a hint.

\subsection{Special tracks}

\advtrains{} also have a few special tracks, some of which are explain in their own sections.

\begin{apidoc}{Special tracks}