aboutsummaryrefslogtreecommitdiff
path: root/src/client/gameui.cpp
blob: 1f433e49a261436dc01333a6626ebbcf118d67f3 (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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr>

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 "gameui.h"
#include <irrlicht_changes/static_text.h>
#include <gettext.h>
#include "gui/mainmenumanager.h"
#include "util/pointedthing.h"
#include "client.h"
#include "clientmap.h"
#include "fontengine.h"
#include "nodedef.h"
#include "profiler.h"
#include "renderingengine.h"
#include "version.h"

inline static const char *yawToDirectionString(int yaw)
{
	static const char *direction[4] =
		{"North +Z", "West -X", "South -Z", "East +X"};

	yaw = wrapDegrees_0_360(yaw);
	yaw = (yaw + 45) % 360 / 90;

	return direction[yaw];
}

GameUI::GameUI()
{
	if (guienv && guienv->getSkin())
		m_statustext_initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
	else
		m_statustext_initial_color = video::SColor(255, 0, 0, 0);

}
void GameUI::init()
{
	// First line of debug text
	m_guitext = gui::StaticText::add(guienv, utf8_to_wide(PROJECT_NAME_C).c_str(),
		core::rect<s32>(0, 0, 0, 0), false, false, guiroot);

	// Second line of debug text
	m_guitext2 = gui::StaticText::add(guienv, L"", core::rect<s32>(0, 0, 0, 0), false,
		false, guiroot);

	// At the middle of the screen
	// Object infos are shown in this
	m_guitext_info = gui::StaticText::add(guienv, L"",
		core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5)
			+ v2s32(100, 200), false, true, guiroot);

	// Status text (displays info when showing and hiding GUI stuff, etc.)
	m_guitext_status = gui::StaticText::add(guienv, L"<Status>",
		core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
	m_guitext_status->setVisible(false);

	// Chat text
	m_guitext_chat = gui::StaticText::add(guienv, L"", core::rect<s32>(0, 0, 0, 0),
		//false, false); // Disable word wrap as of now
		false, true, guiroot);

	// Profiler text (size is updated when text is updated)
	m_guitext_profiler = gui::StaticText::add(guienv, L"<Profiler>",
		core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
	m_guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
	m_guitext_profiler->setVisible(false);
	m_guitext_profiler->setWordWrap(true);
}

void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_control,
	const CameraOrientation &cam, const PointedThing &pointed_old, float dtime)
{
	v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();

	if (m_flags.show_debug) {
		static float drawtime_avg = 0;
		drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
		u16 fps = 1.0 / stats.dtime_jitter.avg;

		std::ostringstream os(std::ios_base::binary);
		os << std::fixed
			<< PROJECT_NAME_C " " << g_version_hash
			<< ", FPS: " << fps
			<< std::setprecision(0)
			<< ", drawtime: " << drawtime_avg << "ms"
			<< std::setprecision(1)
			<< ", dtime jitter: "
			<< (stats.dtime_jitter.max_fraction * 100.0) << "%"
			<< std::setprecision(1)
			<< ", view range: "
			<< (draw_control->range_all ? "All" : itos(draw_control->wanted_range))
			<< std::setprecision(3)
			<< ", RTT: " << client->getRTT() << "s";
		setStaticText(m_guitext, utf8_to_wide(os.str()).c_str());

		m_guitext->setRelativePosition(core::rect<s32>(5, 5, screensize.X,
			5 + g_fontengine->getTextHeight()));
	}

	// Finally set the guitext visible depending on the flag
	m_guitext->setVisible(m_flags.show_debug);

	if (m_flags.show_debug) {
		LocalPlayer *player = client->getEnv().getLocalPlayer();
		v3f player_position = player->getPosition();

		std::ostringstream os(std::ios_base::binary);
		os << std::setprecision(1) << std::fixed
			<< "pos: (" << (player_position.X / BS)
			<< ", " << (player_position.Y / BS)
			<< ", " << (player_position.Z / BS)
			<< "), yaw: " << (wrapDegrees_0_360(cam.camera_yaw)) << "° "
			<< yawToDirectionString(cam.camera_yaw)
			<< ", seed: " << ((u64)client->getMapSeed());

		if (pointed_old.type == POINTEDTHING_NODE) {
			ClientMap &map = client->getEnv().getClientMap();
			const NodeDefManager *nodedef = client->getNodeDefManager();
			MapNode n = map.getNodeNoEx(pointed_old.node_undersurface);

			if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
				os << ", pointed: " << nodedef->get(n).name
					<< ", param2: " << (u64) n.getParam2();
			}
		}

		setStaticText(m_guitext2, utf8_to_wide(os.str()).c_str());

		m_guitext2->setRelativePosition(core::rect<s32>(5,
			5 + g_fontengine->getTextHeight(), screensize.X,
			5 + g_fontengine->getTextHeight() * 2
		));
	}

	m_guitext2->setVisible(m_flags.show_debug);

	setStaticText(m_guitext_info, translate_string(m_infotext).c_str());
	m_guitext_info->setVisible(m_flags.show_hud && g_menumgr.menuCount() == 0);

	static const float statustext_time_max = 1.5f;

	if (!m_statustext.empty()) {
		m_statustext_time += dtime;

		if (m_statustext_time >= statustext_time_max) {
			clearStatusText();
			m_statustext_time = 0.0f;
		}
	}

	setStaticText(m_guitext_status, translate_string(m_statustext).c_str());
	m_guitext_status->setVisible(!m_statustext.empty());

	if (!m_statustext.empty()) {
		s32 status_width  = m_guitext_status->getTextWidth();
		s32 status_height = m_guitext_status->getTextHeight();
		s32 status_y = screensize.Y - 150;
		s32 status_x = (screensize.X - status_width) / 2;

		m_guitext_status->setRelativePosition(core::rect<s32>(status_x ,
			status_y - status_height, status_x + status_width, status_y));

		// Fade out
		video::SColor final_color = m_statustext_initial_color;
		final_color.setAlpha(0);
		video::SColor fade_color = m_statustext_initial_color.getInterpolated_quadratic(
			m_statustext_initial_color, final_color, m_statustext_time / statustext_time_max);
		m_guitext_status->setOverrideColor(fade_color);
		m_guitext_status->enableOverrideColor(true);
	}
}

void GameUI::initFlags()
{
	m_flags = GameUI::Flags();
	m_flags.show_debug = g_settings->getBool("show_debug");
}

void GameUI::showMinimap(bool show)
{
	m_flags.show_minimap = show;
}

void GameUI::showTranslatedStatusText(const char *str)
{
	const wchar_t *wmsg = wgettext(str);
	showStatusText(wmsg);
	delete[] wmsg;
}

void GameUI::setChatText(const EnrichedString &chat_text, u32 recent_chat_count)
{
	setStaticText(m_guitext_chat, chat_text);

	// Update gui element size and position
	s32 chat_y = 5;

	if (m_flags.show_debug)
		chat_y += 2 * g_fontengine->getLineHeight();

	// first pass to calculate height of text to be set
	const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
	s32 width = std::min(g_fontengine->getTextWidth(chat_text.c_str()) + 10,
		window_size.X - 20);
	m_guitext_chat->setRelativePosition(core::rect<s32>(10, chat_y, width,
		chat_y + window_size.Y));

	// now use real height of text and adjust rect according to this size
	m_guitext_chat->setRelativePosition(core::rect<s32>(10, chat_y, width,
		chat_y + m_guitext_chat->getTextHeight()));

	// Don't show chat if disabled or empty or profiler is enabled
	m_guitext_chat->setVisible(m_flags.show_chat &&
		recent_chat_count != 0 && m_profiler_current_page == 0);
}

void GameUI::updateProfiler()
{
	if (m_profiler_current_page != 0) {
		std::ostringstream os(std::ios_base::binary);
		g_profiler->printPage(os, m_profiler_current_page, m_profiler_max_page);

		std::wstring text = translate_string(utf8_to_wide(os.str()));
		setStaticText(m_guitext_profiler, text.c_str());

		s32 w = g_fontengine->getTextWidth(text);

		if (w < 400)
			w = 400;

		u32 text_height = g_fontengine->getTextHeight();

		core::position2di upper_left, lower_right;

		upper_left.X  = 6;
		upper_left.Y  = (text_height + 5) * 2;
		lower_right.X = 12 + w;
		lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;

		s32 screen_height = RenderingEngine::get_video_driver()->getScreenSize().Height;

		if (lower_right.Y > screen_height * 2 / 3)
			lower_right.Y = screen_height * 2 / 3;

		m_guitext_profiler->setRelativePosition(core::rect<s32>(upper_left, lower_right));
	}

	m_guitext_profiler->setVisible(m_profiler_current_page != 0);
}

void GameUI::toggleChat()
{
	m_flags.show_chat = !m_flags.show_chat;
	if (m_flags.show_chat)
		showTranslatedStatusText("Chat shown");
	else
		showTranslatedStatusText("Chat hidden");
}

void GameUI::toggleHud()
{
	m_flags.show_hud = !m_flags.show_hud;
	if (m_flags.show_hud)
		showTranslatedStatusText("HUD shown");
	else
		showTranslatedStatusText("HUD hidden");
}

void GameUI::toggleProfiler()
{
	m_profiler_current_page = (m_profiler_current_page + 1) % (m_profiler_max_page + 1);

	// FIXME: This updates the profiler with incomplete values
	updateProfiler();

	if (m_profiler_current_page != 0) {
		wchar_t buf[255];
		const wchar_t* str = wgettext("Profiler shown (page %d of %d)");
		swprintf(buf, sizeof(buf) / sizeof(wchar_t), str,
			m_profiler_current_page, m_profiler_max_page);
		delete[] str;
		showStatusText(buf);
	} else {
		showTranslatedStatusText("Profiler hidden");
	}
}
span>(train) --apply off-track handling: local front_off_track=train.max_index_on_track and train.index>train.max_index_on_track local back_off_track=train.min_index_on_track and train_end_index<train.min_index_on_track if front_off_track and back_off_track then--allow movement in both directions if train.tarvelocity>1 then train.tarvelocity=1 end elseif front_off_track then--allow movement only backward if train.movedir==1 and train.tarvelocity>0 then train.tarvelocity=0 end if train.movedir==-1 and train.tarvelocity>1 then train.tarvelocity=1 end elseif back_off_track then--allow movement only forward if train.movedir==-1 and train.tarvelocity>0 then train.tarvelocity=0 end if train.movedir==1 and train.tarvelocity>1 then train.tarvelocity=1 end end --update advtrains.detector if not train.detector_old_index then train.detector_old_index = math.floor(train_end_index) train.detector_old_end_index = math.floor(train_end_index) end local ifo, ifn, ibo, ibn = train.detector_old_index, math.floor(train.index), train.detector_old_end_index, math.floor(train_end_index) if ifn>ifo then for i=ifo, ifn do if path[i] then advtrains.detector.enter_node(path[i], id) end end elseif ifn<ifo then for i=ifn, ifo do if path[i] then advtrains.detector.leave_node(path[i], id) end end end if ibn<ibo then for i=ibn, ibn do if path[i] then advtrains.detector.enter_node(path[i], id) end end elseif ibn>ibo then for i=ibo, ibn do if path[i] then advtrains.detector.leave_node(path[i], id) end end end train.detector_old_index = math.floor(train.index) train.detector_old_end_index = math.floor(train_end_index) if train_moves then --check for collisions by finding objects --front local search_radius=4 --coupling local couple_outward=1 local posfront=advtrains.get_real_index_position(path, train.index+couple_outward) local posback=advtrains.get_real_index_position(path, train_end_index-couple_outward) for _,pos in ipairs({posfront, posback}) do if pos then local objrefs=minetest.get_objects_inside_radius(pos, search_radius) for _,v in pairs(objrefs) do local le=v:get_luaentity() if le and le.is_wagon and le.initialized and le.train_id~=id then advtrains.try_connect_trains(id, le.train_id) end end end end --heh, new collision again. --this time, based on NODES and the advtrains.detector.on_node table. local collpos local coll_grace=1 if train.movedir==1 then collpos=advtrains.get_real_index_position(path, train.index-coll_grace) else collpos=advtrains.get_real_index_position(path, train_end_index+coll_grace) end if collpos then local rcollpos=advtrains.round_vector_floor_y(collpos) for x=-1,1 do for z=-1,1 do local testpts=minetest.pos_to_string(vector.add(rcollpos, {x=x, y=0, z=z})) if advtrains.detector.on_node[testpts] and advtrains.detector.on_node[testpts]~=id then --collides train.recently_collided_with_env=true train.velocity=0.5*train.velocity train.movedir=train.movedir*-1 train.tarvelocity=0 end end end end end --check for any trainpart entities if they have been unloaded. do this only if train is near a player, to not spawn entities into unloaded areas train.check_trainpartload=(train.check_trainpartload or 0)-dtime local node_range=(math.max((minetest.setting_get("active_block_range") or 0),1)*16) if train.check_trainpartload<=0 then local ori_pos=advtrains.get_real_index_position(path, train.index) --not much to calculate print("[advtrains][train "..id.."] at "..minetest.pos_to_string(vector.round(ori_pos))) local should_check=false for _,p in ipairs(minetest.get_connected_players()) do should_check=should_check or ((vector.distance(ori_pos, p:getpos())<node_range)) end if should_check then --it is better to iterate luaentites only once --print("check_trainpartload") local found_uids={} for _,wagon in pairs(minetest.luaentities) do if wagon.is_wagon and wagon.initialized and wagon.train_id==id then if found_uids[wagon.unique_id] then --duplicate found, delete it if wagon.object then wagon.object:remove() end else found_uids[wagon.unique_id]=true end end end --print("found_uids: "..dump(found_uids)) --now iterate trainparts and check. then cross them out to see if there are wagons over for any reason for pit, w_id in ipairs(train.trainparts) do if found_uids[w_id] then --print(w_id.." still loaded") elseif advtrains.wagon_save[w_id] then --print(w_id.." not loaded, but save available") --spawn a new and initialize it with the properties from wagon_save local le=minetest.add_entity(ori_pos, advtrains.wagon_save[w_id].entity_name):get_luaentity() if le then -- Don't crash if traintype has been removed le:init_from_wagon_save(w_id) end else print(w_id.." not loaded and no save available") --what the hell... table.remove(train.trainparts, pit) end end end train.check_trainpartload=2 end --handle collided_with_env if train.recently_collided_with_env then train.tarvelocity=0 if not train_moves then train.recently_collided_with_env=false--reset status when stopped end end if train.locomotives_in_train==0 then train.tarvelocity=0 end --make brake adjust the tarvelocity if necessary if train.brake and (math.ceil(train.velocity)-1)<train.tarvelocity then train.tarvelocity=math.max((math.ceil(train.velocity)-1), 0) end --apply tarvel(but with physics in mind!) if train.velocity~=train.tarvelocity then local applydiff=0 local mass=#train.trainparts local diff=train.tarvelocity-train.velocity if diff>0 then--accelerating, force will be brought on only by locomotives. --print("accelerating with default force") applydiff=(math.min((advtrains.train_accel_force*train.locomotives_in_train*dtime)/mass, math.abs(diff))) else--decelerating if front_off_track or back_off_track or train.recently_collided_with_env then --every wagon has a brake, so not divided by mass. --print("braking with emergency force") applydiff= -(math.min((advtrains.train_emerg_force*dtime), math.abs(diff))) elseif train.brake then --print("braking with default force") --no math.min, because it can grow beyond tarvelocity, see up there --dont worry, it will never fall below zero. applydiff= -((advtrains.train_brake_force*dtime)) else --print("roll") applydiff= -(math.min((advtrains.train_roll_force*dtime), math.abs(diff))) end end train.last_accel=(applydiff*train.movedir) train.velocity=math.min(math.max( train.velocity+applydiff , 0), advtrains.all_traintypes[train.traintype].max_speed) else train.last_accel=0 end --move --TODO 3,5 + 0.7 train.index=train.index and train.index+(((train.velocity*train.movedir)/(train.path_dist[math.floor(train.index)] or 1))*dtime) or 0 end --structure of train table: --[[ trains={ [train_id]={ trainparts={ [n]=wagon_id } path={path} velocity tarvelocity index trainlen path_inv_level last_pos | last_dir | for pathpredicting. } } --a wagon itself has the following properties: wagon={ unique_id train_id pos_in_train (is index difference, including train_span stuff) pos_in_trainparts (is index in trainparts tabel of trains) } inherited by metatable: wagon_proto={ wagon_span } ]] --returns new id function advtrains.create_new_train_at(pos, pos_prev, traintype) local newtrain_id=os.time()..os.clock() while advtrains.trains[newtrain_id] do newtrain_id=os.time()..os.clock() end--ensure uniqueness(will be unneccessary) advtrains.trains[newtrain_id]={} advtrains.trains[newtrain_id].last_pos=pos advtrains.trains[newtrain_id].last_pos_prev=pos_prev advtrains.trains[newtrain_id].traintype=traintype advtrains.trains[newtrain_id].tarvelocity=0 advtrains.trains[newtrain_id].velocity=0 advtrains.trains[newtrain_id].trainparts={} return newtrain_id end --returns false on failure. handle this case! function advtrains.pathpredict(id, train) --print("pos ",x,y,z) --::rerun:: if not train.index then train.index=0 end if not train.path or #train.path<2 then if not train.last_pos then --no chance to recover print("[advtrains]train hasn't saved last-pos, removing train.") advtrains.train[id]=nil return false end local node_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(train.last_pos), train.traintype) if node_ok==nil then --block not loaded, do nothing return nil elseif node_ok==false then print("[advtrains]no track here, (fail) removing train.") advtrains.trains[id]=nil return false end if not train.last_pos_prev then --no chance to recover print("[advtrains]train hasn't saved last-pos_prev, removing train.") advtrains.trains[id]=nil return false end local prevnode_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(train.last_pos_prev), train.traintype) if prevnode_ok==nil then --block not loaded, do nothing return nil elseif prevnode_ok==false then print("[advtrains]no track at prev, (fail) removing train.") advtrains.trains[id]=nil return false end train.index=(train.restore_add_index or 0)+(train.savedpos_off_track_index_offset or 0) --restore_add_index is set by save() to prevent trains hopping to next round index. should be between -0.5 and 0.5 --savedpos_off_track_index_offset is set if train went off track. see below. train.path={} train.path_dist={} train.path[0]=train.last_pos train.path[-1]=train.last_pos_prev train.path_dist[-1]=vector.distance(train.last_pos, train.last_pos_prev) end local pregen_front=2 local pregen_back=2 if train.velocity>0 then if train.movedir>0 then pregen_front=2+math.ceil(train.velocity*0.15) --assumes server step of 0.1 seconds, +50% tolerance else pregen_back=2+math.ceil(train.velocity*0.15) end end local maxn=advtrains.maxN(train.path) while (maxn-train.index) < pregen_front do--pregenerate --print("[advtrains]maxn conway for ",maxn,minetest.pos_to_string(path[maxn]),maxn-1,minetest.pos_to_string(path[maxn-1])) local conway=advtrains.conway(train.path[maxn], train.path[maxn-1], train.traintype) if conway then train.path[maxn+1]=conway train.max_index_on_track=maxn else --do as if nothing has happened and preceed with path --but do not update max_index_on_track --print("over-generating path max to index "..maxn+1) train.path[maxn+1]=vector.add(train.path[maxn], vector.subtract(train.path[maxn], train.path[maxn-1])) end train.path_dist[maxn]=vector.distance(train.path[maxn+1], train.path[maxn]) maxn=advtrains.maxN(train.path) end local minn=advtrains.minN(train.path) while (train.index-minn) < (train.trainlen or 0) + pregen_back do --post_generate. has to be at least trainlen. (we let go of the exact calculation here since this would be unuseful here) --print("[advtrains]minn conway for ",minn,minetest.pos_to_string(path[minn]),minn+1,minetest.pos_to_string(path[minn+1])) local conway=advtrains.conway(train.path[minn], train.path[minn+1], train.traintype) if conway then train.path[minn-1]=conway train.min_index_on_track=minn else --do as if nothing has happened and preceed with path --but do not update min_index_on_track --print("over-generating path min to index "..minn-1) train.path[minn-1]=vector.add(train.path[minn], vector.subtract(train.path[minn], train.path[minn+1])) end train.path_dist[minn-1]=vector.distance(train.path[minn], train.path[minn-1]) minn=advtrains.minN(train.path) end if not train.min_index_on_track then train.min_index_on_track=0 end if not train.max_index_on_track then train.max_index_on_track=0 end --make pos/yaw available for possible recover calls if train.max_index_on_track<train.index then --whoops, train went too far. the saved position will be the last one that lies on a track, and savedpos_off_track_index_offset will hold how far to go from here train.savedpos_off_track_index_offset=train.index-train.max_index_on_track train.last_pos=train.path[train.max_index_on_track] train.last_pos_prev=train.path[train.max_index_on_track-1] --print("train is off-track (front), last positions kept at "..minetest.pos_to_string(train.last_pos).." / "..minetest.pos_to_string(train.last_pos_prev)) elseif train.min_index_on_track+1>train.index then --whoops, train went even more far. same behavior train.savedpos_off_track_index_offset=train.index-train.min_index_on_track train.last_pos=train.path[train.min_index_on_track+1] train.last_pos_prev=train.path[train.min_index_on_track] --print("train is off-track (back), last positions kept at "..minetest.pos_to_string(train.last_pos).." / "..minetest.pos_to_string(train.last_pos_prev)) else --regular case train.savedpos_off_track_index_offset=nil train.last_pos=train.path[math.floor(train.index+0.5)] train.last_pos_prev=train.path[math.floor(train.index-0.5)] end return train.path end function advtrains.get_train_end_index(train) return advtrains.get_real_path_index(train, train.trainlen or 2)--this function can be found inside wagons.lua since it's more related to wagons. we just set trainlen as pos_in_train end function advtrains.get_or_create_path(id, train) if not train.path then return advtrains.pathpredict(id, train) end return train.path end function advtrains.add_wagon_to_train(wagon, train_id, index) local train=advtrains.trains[train_id] if index then table.insert(train.trainparts, index, wagon.unique_id) else table.insert(train.trainparts, wagon.unique_id) end --this is not the usual case!!! --we may set initialized because the wagon has no chance to step() wagon.initialized=true --TODO is this art or can we throw it away? advtrains.update_trainpart_properties(train_id) end function advtrains.update_trainpart_properties(train_id, invert_flipstate) local train=advtrains.trains[train_id] local rel_pos=0 local count_l=0 for i, w_id in ipairs(train.trainparts) do local any_loaded=false for _,wagon in pairs(minetest.luaentities) do if wagon.is_wagon and wagon.initialized and wagon.unique_id==w_id then rel_pos=rel_pos+wagon.wagon_span wagon.train_id=train_id wagon.pos_in_train=rel_pos wagon.pos_in_trainparts=i wagon.old_velocity_vector=nil if wagon.is_locomotive then count_l=count_l+1 end if invert_flipstate then wagon.wagon_flipped = not wagon.wagon_flipped end rel_pos=rel_pos+wagon.wagon_span any_loaded=true end end if not any_loaded then print("update_trainpart_properties wagon "..w_id.." not loaded, ignoring it.") end end train.trainlen=rel_pos train.locomotives_in_train=count_l end function advtrains.split_train_at_wagon(wagon) --get train local train=advtrains.trains[wagon.train_id] local real_pos_in_train=advtrains.get_real_path_index(train, wagon.pos_in_train) local pos_for_new_train=advtrains.get_or_create_path(wagon.train_id, train)[math.floor(real_pos_in_train+wagon.wagon_span)] local pos_for_new_train_prev=advtrains.get_or_create_path(wagon.train_id, train)[math.floor(real_pos_in_train-1+wagon.wagon_span)] --before doing anything, check if both are rails. else do not allow if not pos_for_new_train then print("split_train: pos_for_new_train not set") return false end local node_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(pos_for_new_train), train.traintype) if not node_ok then print("split_train: pos_for_new_train "..minetest.pos_to_string(advtrains.round_vector_floor_y(pos_for_new_train_prev)).." not loaded or is not a rail") return false end if not train.last_pos_prev then print("split_train: pos_for_new_train_prev not set") return false end local prevnode_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(pos_for_new_train), train.traintype) if not prevnode_ok then print("split_train: pos_for_new_train_prev "..minetest.pos_to_string(advtrains.round_vector_floor_y(pos_for_new_train_prev)).." not loaded or is not a rail") return false end --create subtrain local newtrain_id=advtrains.create_new_train_at(pos_for_new_train, pos_for_new_train_prev, train.traintype) local newtrain=advtrains.trains[newtrain_id] --insert all wagons to new train for k,v in ipairs(train.trainparts) do if k>=wagon.pos_in_trainparts then table.insert(newtrain.trainparts, v) train.trainparts[k]=nil end end --update train parts advtrains.update_trainpart_properties(wagon.train_id)--atm it still is the desierd id. advtrains.update_trainpart_properties(newtrain_id) train.tarvelocity=0 newtrain.velocity=train.velocity newtrain.tarvelocity=0 end --there are 4 cases: --1/2. F<->R F<->R regular, put second train behind first --->frontpos of first train will match backpos of second --3. F<->R R<->F flip one of these trains, take the other as new train --->backpos's will match --4. R<->F F<->R flip one of these trains and take it as new parent --->frontpos's will match function advtrains.try_connect_trains(id1, id2) local train1=advtrains.trains[id1] local train2=advtrains.trains[id2] if not train1 or not train2 then return end if not train1.path or not train2.path then return end if #train1.trainparts==0 or #train2.trainparts==0 then return end local frontpos1=advtrains.get_real_index_position(train1.path, train1.index) local backpos1=advtrains.get_real_index_position(train1.path, advtrains.get_train_end_index(train1)) --couple logic if train1.traintype==train2.traintype then local frontpos2=advtrains.get_real_index_position(train2.path, train2.index) local backpos2=advtrains.get_real_index_position(train2.path, advtrains.get_train_end_index(train2)) if not frontpos1 or not frontpos2 or not backpos1 or not backpos2 then return end local couple_spawnradius=0.7 --case 1 (first train is front) if vector.distance(frontpos2, backpos1)<couple_spawnradius then advtrains.spawn_couple_if_neccessary(backpos1, frontpos2, id1, id2, true, false) --case 2 (second train is front) elseif vector.distance(frontpos1, backpos2)<couple_spawnradius then advtrains.spawn_couple_if_neccessary(backpos2, frontpos1, id2, id1, true, false) --case 3 elseif vector.distance(backpos2, backpos1)<couple_spawnradius then advtrains.spawn_couple_if_neccessary(backpos1, backpos2, id1, id2, true, true) --case 4 elseif vector.distance(frontpos2, frontpos1)<couple_spawnradius then advtrains.spawn_couple_if_neccessary(frontpos1, frontpos2, id1, id2, false, false) end end end --true when trains are facing each other. needed on colliding. -- check done by iterating paths and checking their direction --returns nil when not on the same track at all OR when required path items are not generated. this distinction may not always be needed. function advtrains.trains_facing(train1, train2) local sr_pos=train1.path[math.floor(train1.index)] local sr_pos_p=train1.path[math.floor(train1.index)-1] for i=advtrains.minN(train2.path), advtrains.maxN(train2.path) do if vector.equals(sr_pos, train2.path[i]) then if train2.path[i+1] and vector.equals(sr_pos_p, train2.path[i+1]) then return true end if train2.path[i-1] and vector.equals(sr_pos_p, train2.path[i-1]) then return false end return nil end end return nil end --order of trains may be irrelevant in some cases. check opposite cases. TODO does this work? --pos1 and pos2 are just needed to form a median. function advtrains.spawn_couple_if_neccessary(pos1, pos2, tid1, tid2, train1_is_backpos, train2_is_backpos) --print("spawn_couple_if_neccessary..."..dump({pos1=pos1, pos2=pos2, train1_is_backpos=train1_is_backpos, train2_is_backpos=train2_is_backpos})) local train1=advtrains.trains[tid1] local train2=advtrains.trains[tid2] local t1_has_couple if train1_is_backpos then t1_has_couple=train1.couple_eid_back else t1_has_couple=train1.couple_eid_front end local t2_has_couple if train2_is_backpos then t2_has_couple=train2.couple_eid_back else t2_has_couple=train2.couple_eid_front end if t1_has_couple and t2_has_couple then if t1_has_couple~=t2_has_couple then--what the hell if minetest.object_refs[t2_has_couple] then minetest.object_refs[t2_has_couple]:remove() end if train2_is_backpos then train2.couple_eid_back=t1_has_couple else train2.couple_eid_front=t1_has_couple end end --[[elseif t1_has_couple and not t2_has_couple then if train2_is_backpos then train2.couple_eid_back=t1_has_couple else train2.couple_eid_front=t1_has_couple end elseif not t1_has_couple and t2_has_couple then if train1_is_backpos then train1.couple_eid_back=t2_has_couple else train1.couple_eid_front=t2_has_couple end]] else local pos=advtrains.pos_median(pos1, pos2) local obj=minetest.add_entity(pos, "advtrains:couple") if not obj then print("failed creating object") return end local le=obj:get_luaentity() le.train_id_1=tid1 le.train_id_2=tid2 le.train1_is_backpos=train1_is_backpos le.train2_is_backpos=train2_is_backpos --find in object_refs for aoi, compare in pairs(minetest.object_refs) do if compare==obj then if train1_is_backpos then train1.couple_eid_back=aoi else train1.couple_eid_front=aoi end if train2_is_backpos then train2.couple_eid_back=aoi else train2.couple_eid_front=aoi end end end end end function advtrains.do_connect_trains(first_id, second_id) local first_wagoncnt=#advtrains.trains[first_id].trainparts local second_wagoncnt=#advtrains.trains[second_id].trainparts for _,v in ipairs(advtrains.trains[second_id].trainparts) do table.insert(advtrains.trains[first_id].trainparts, v) end --kick it like physics (with mass being #wagons) local new_velocity=((advtrains.trains[first_id].velocity*first_wagoncnt)+(advtrains.trains[second_id].velocity*second_wagoncnt))/(first_wagoncnt+second_wagoncnt) advtrains.trains[second_id]=nil advtrains.update_trainpart_properties(first_id) advtrains.trains[first_id].velocity=new_velocity advtrains.trains[first_id].tarvelocity=0 end function advtrains.invert_train(train_id) local train=advtrains.trains[train_id] local old_path=advtrains.get_or_create_path(train_id, train) train.path={} train.index= - advtrains.get_train_end_index(train) train.velocity=-train.velocity train.tarvelocity=-train.tarvelocity for k,v in pairs(old_path) do train.path[-k]=v end local old_trainparts=train.trainparts train.trainparts={} for k,v in ipairs(old_trainparts) do table.insert(train.trainparts, 1, v)--notice insertion at first place end advtrains.update_trainpart_properties(train_id, true) end function advtrains.is_train_at_pos(pos) --print("istrainat: pos "..minetest.pos_to_string(pos)) local checked_trains={} local objrefs=minetest.get_objects_inside_radius(pos, 2) for _,v in pairs(objrefs) do local le=v:get_luaentity() if le and le.is_wagon and le.initialized and le.train_id and not checked_trains[le.train_id] then --print("istrainat: checking "..le.train_id) checked_trains[le.train_id]=true