aboutsummaryrefslogtreecommitdiff
path: root/advtrains/trackplacer.lua
blob: db65cd9d6d805015c637a6475dadac8926b57bc2 (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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
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
--trackplacer.lua
--holds code for the track-placing system. the default 'track' item will be a craftitem that places rails as needed. this will neither place or change switches nor place vertical rails.

--all new trackplacer code
local tp={
	tracks={}
}

function tp.register_tracktype(nnprefix, n_suffix)
	if tp.tracks[nnprefix] then return end--due to the separate registration of slopes and flats for the same nnpref, definition would be overridden here. just don't.
	tp.tracks[nnprefix]={
		default=n_suffix,
		single_conn={},
		single_conn_1={},
		single_conn_2={},
		double_conn={},
		double_conn_1={},
		double_conn_2={},
		--keys:conn1_conn2 (example:1_4)
		--values:{name=x, param2=x}
		twcycle={},
		twrotate={},--indexed by suffix, list, tells order of rotations
		modify={},
	}
end
function tp.add_double_conn(nnprefix, suffix, rotation, conns)
	local nodename=nnprefix.."_"..suffix..rotation
	for i=0,3 do
		tp.tracks[nnprefix].double_conn[((conns.conn1+4*i)%16).."_"..((conns.conn2+4*i)%16)]={name=nodename, param2=i}
		tp.tracks[nnprefix].double_conn[((conns.conn2+4*i)%16).."_"..((conns.conn1+4*i)%16)]={name=nodename, param2=i}
		tp.tracks[nnprefix].double_conn_1[((conns.conn1+4*i)%16).."_"..((conns.conn2+4*i)%16)]={name=nodename, param2=i}
		tp.tracks[nnprefix].double_conn_2[((conns.conn2+4*i)%16).."_"..((conns.conn1+4*i)%16)]={name=nodename, param2=i}
	end
	tp.tracks[nnprefix].modify[nodename]=true
end
function tp.add_single_conn(nnprefix, suffix, rotation, conns)
	local nodename=nnprefix.."_"..suffix..rotation
	for i=0,3 do
		tp.tracks[nnprefix].single_conn[((conns.conn1+4*i)%16)]={name=nodename, param2=i}
		tp.tracks[nnprefix].single_conn[((conns.conn2+4*i)%16)]={name=nodename, param2=i}
		tp.tracks[nnprefix].single_conn_1[((conns.conn1+4*i)%16)]={name=nodename, param2=i}
		tp.tracks[nnprefix].single_conn_2[((conns.conn2+4*i)%16)]={name=nodename, param2=i}
	end
	tp.tracks[nnprefix].modify[nodename]=true
end


function tp.add_worked(nnprefix, suffix, rotation, cycle_follows)
	tp.tracks[nnprefix].twcycle[suffix]=cycle_follows
	if not tp.tracks[nnprefix].twrotate[suffix] then tp.tracks[nnprefix].twrotate[suffix]={} end
	table.insert(tp.tracks[nnprefix].twrotate[suffix], rotation)
end


--[[
	rewrite algorithm.
	selection criteria: these will never be changed or even selected:
	- tracks being already connected on both sides
	- tracks that are already connected on one side but are not bendable to the desired position
	the following situations can occur:
	1. there are two more than two rails around
		1.1 there is one or more subset(s) that can be directly connected
			-> choose the first possibility
		2.2 not
			-> choose the first one and orient straight
	2. there's exactly 1 rail around
		-> choose and orient straight
	3. there's no rail around
		-> set straight
]]

local function istrackandbc(pos_p, conn)
	local tpos = pos_p
	local cnode=minetest.get_node(advtrains.dirCoordSet(tpos, conn.c))
	if advtrains.is_track_and_drives_on(cnode.name, advtrains.all_tracktypes) then
		local cconns=advtrains.get_track_connections(cnode.name, cnode.param2)
		return advtrains.conn_matches_to(conn, cconns)
	end
	--try the same 1 node below
	tpos = {x=tpos.x, y=tpos.y-1, z=tpos.z}
	cnode=minetest.get_node(advtrains.dirCoordSet(tpos, conn.c))
	if advtrains.is_track_and_drives_on(cnode.name, advtrains.all_tracktypes) then
		local cconns=advtrains.get_track_connections(cnode.name, cnode.param2)
		return advtrains.conn_matches_to(conn, cconns)
	end
	return false
end

function tp.find_already_connected(pos)
	local dnode=minetest.get_node(pos)
	local dconns=advtrains.get_track_connections(dnode.name, dnode.param2)
	local found_conn
	for connid, conn in ipairs(dconns) do
		if istrackandbc(pos, conn) then
			if found_conn then --we found one in previous iteration
				return true, true --signal that it's connected
			else
				found_conn = conn.c
			end
		end
	end
	return found_conn
end
function tp.rail_and_can_be_bent(originpos, conn)
	local pos=advtrains.dirCoordSet(originpos, conn)
	local newdir=(conn+8)%16
	local node=minetest.get_node(pos)
	if not advtrains.is_track_and_drives_on(node.name, advtrains.all_tracktypes) then
		return false
	end
	local ndef=minetest.registered_nodes[node.name]
	local nnpref = ndef and ndef.at_nnpref
	if not nnpref then return false end
	local tr=tp.tracks[nnpref]
	if not tr then return false end
	if not tr.modify[node.name] then 
		--we actually can use this rail, but only if it already points to the desired direction.
		if advtrains.is_track_and_drives_on(node.name, advtrains.all_tracktypes) then
			local cconns=advtrains.get_track_connections(node.name, node.param2)
			return advtrains.conn_matches_to(conn, cconns)
		end
	end
	--rail at other end?
	local adj1, adj2=tp.find_already_connected(pos)
	if adj1 and adj2 then
		return false--dont destroy existing track
	elseif adj1 and not adj2 then
		if tr.double_conn[adj1.."_"..newdir] then
			return true--if exists, connect new rail and old end
		end
		return false
	else
		if tr.single_conn[newdir] then--just rotate old rail to right orientation
			return true
		end
		return false
	end
end
function tp.bend_rail(originpos, conn)
	local pos=advtrains.dirCoordSet(originpos, conn)
	local newdir=advtrains.oppd(conn)
	local node=minetest.get_node(pos)
	local ndef=minetest.registered_nodes[node.name]
	local nnpref = ndef and ndef.at_nnpref
	if not nnpref then return false end
	local tr=tp.tracks[nnpref]
	if not tr then return false end
	--is rail already connected? no need to bend.
	local conns=advtrains.get_track_connections(node.name, node.param2)
	if advtrains.conn_matches_to(conn, conns) then
		return
	end
	--rail at other end?
	local adj1, adj2=tp.find_already_connected(pos)
	if adj1 and adj2 then
		return false--dont destroy existing track
	elseif adj1 and not adj2 then
		if tr.double_conn[adj1.."_"..newdir] then
			advtrains.ndb.swap_node(pos, tr.double_conn[adj1.."_"..newdir])
			return true--if exists, connect new rail and old end
		end
		return false
	else
		if tr.single_conn[newdir] then--just rotate old rail to right orientation
			advtrains.ndb.swap_node(pos, tr.single_conn[newdir])
			return true
		end
		return false
	end
end
function tp.placetrack(pos, nnpref, placer, itemstack, pointed_thing, yaw)
	--1. find all rails that are likely to be connected
	local tr=tp.tracks[nnpref]
	local p_rails={}
	local p_railpos={}
	for i=0,15 do
		if tp.rail_and_can_be_bent(pos, i, nnpref) then
			p_rails[#p_rails+1]=i
			p_railpos[i] = pos
		else
			local upos = {x=pos.x, y=pos.y-1, z=pos.z}
			if tp.rail_and_can_be_bent(upos, i, nnpref) then
				p_rails[#p_rails+1]=i
				p_railpos[i] = upos
			end
		end
	end
	
	-- try double_conn
	if #p_rails > 1 then
		--iterate subsets
		for k1, conn1 in ipairs(p_rails) do
			for k2, conn2 in ipairs(p_rails) do
				if k1~=k2 then
					local dconn1 = tr.double_conn_1
					local dconn2 = tr.double_conn_2
					if not (advtrains.yawToDirection(yaw, conn1, conn2) == conn1) then
						dconn1 = tr.double_conn_2
						dconn2 = tr.double_conn_1
					end
					-- Checks are made this way round so that dconn1 has priority (this will make arrows of atc rails
					-- point in the right direction)
					local using
					if (dconn2[conn1.."_"..conn2]) then
						using = dconn2[conn1.."_"..conn2]
					end
					if (dconn1[conn1.."_"..conn2]) then
						using = dconn1[conn1.."_"..conn2]
					end
					if using then
						-- has found a fitting rail in either direction
						-- if not, continue loop
						tp.bend_rail(p_railpos[conn1], conn1, nnpref)
						tp.bend_rail(p_railpos[conn2], conn2, nnpref)
						advtrains.ndb.swap_node(pos, using)
						local nname=using.name
						if minetest.registered_nodes[nname] and minetest.registered_nodes[nname].after_place_node then
							minetest.registered_nodes[nname].after_place_node(pos, placer, itemstack, pointed_thing)
						end
						return
					end
				end
			end
		end
	end
	-- try single_conn
	if #p_rails > 0 then
		for ix, p_rail in ipairs(p_rails) do
			local sconn1 = tr.single_conn_1
			local sconn2 = tr.single_conn_2
			if not (advtrains.yawToDirection(yaw, p_rail, (p_rail+8)%16) == p_rail) then
				sconn1 = tr.single_conn_2
				sconn2 = tr.single_conn_1
			end
			if sconn1[p_rail] then
				local using = sconn1[p_rail]
				tp.bend_rail(p_railpos[p_rail], p_rail, nnpref)
				advtrains.ndb.swap_node(pos, using)
				local nname=using.name
				if minetest.registered_nodes[nname] and minetest.registered_nodes[nname].after_place_node then
					minetest.registered_nodes[nname].after_place_node(pos, placer, itemstack, pointed_thing)
				end
				return
			end
			if sconn2[p_rail] then
				local using = sconn2[p_rail]
				tp.bend_rail(p_railpos[p_rail], p_rail, nnpref)
				advtrains.ndb.swap_node(pos, using)
				local nname=using.name
				if minetest.registered_nodes[nname] and minetest.registered_nodes[nname].after_place_node then
					minetest.registered_nodes[nname].after_place_node(pos, placer, itemstack, pointed_thing)
				end
				return
			end
		end
	end
	--use default
	minetest.set_node(pos, {name=nnpref.."_"..tr.default})
	if minetest.registered_nodes[nnpref.."_"..tr.default] and minetest.registered_nodes[nnpref.."_"..tr.default].after_place_node then
		minetest.registered_nodes[nnpref.."_"..tr.default].after_place_node(pos, placer, itemstack, pointed_thing)
	end
end


function tp.register_track_placer(nnprefix, imgprefix, dispname, def)
	minetest.register_craftitem(":"..nnprefix.."_placer",{
		description = dispname,
		inventory_image = imgprefix.."_placer.png",
		wield_image = imgprefix.."_placer.png",
		groups={advtrains_trackplacer=1, digtron_on_place=1},
		liquids_pointable = def.liquids_pointable,
		on_place = function(itemstack, placer, pointed_thing)
			return advtrains.pcall(function()
					local name = placer:get_player_name()
				if not name then
				   return itemstack, false
				end
				if pointed_thing.type=="node" then
					local pos=pointed_thing.above
					local upos=vector.subtract(pointed_thing.above, {x=0, y=1, z=0})
					if not advtrains.check_track_protection(pos, name) then
						return itemstack, false
					end
					if minetest.registered_nodes[minetest.get_node(pos).name] and minetest.registered_nodes[minetest.get_node(pos).name].buildable_to then
						if def.suitable_substrate then
							s = def.suitable_substrate(upos)
						else
							s = minetest.registered_nodes[minetest.get_node(upos).name] and minetest.registered_nodes[minetest.get_node(upos).name].walkable
						end
						if s then
--						minetest.chat_send_all(nnprefix)
							local yaw = placer:get_look_horizontal()
							tp.placetrack(pos, nnprefix, placer, itemstack, pointed_thing, yaw)
							if not advtrains.is_creative(name) then
								itemstack:take_item()
							end
						end
					end
				end
				return itemstack, true
			end)
		end,
	})
end



minetest.register_craftitem("advtrains:trackworker",{
	description = attrans("Track Worker Tool\n\nLeft-click: change rail type (straight/curve/switch)\nRight-click: rotate rail/bumper/signal/etc."),
	groups = {cracky=1}, -- key=name, value=rating; rating=1..3.
	inventory_image = "advtrains_trackworker.png",
	wield_image = "advtrains_trackworker.png",
	stack_max = 1,
	on_place = function(itemstack, placer, pointed_thing)
		return advtrains.pcall(function()
			local name = placer:get_player_name()
			if not name then
				return
			end
			local has_aux1_down = placer:get_player_control().aux1
			if pointed_thing.type=="node" then
				local pos=pointed_thing.under
				if not advtrains.check_track_protection(pos, name) then
					return
				end
				local node=minetest.get_node(pos)

				--if not advtrains.is_track_and_drives_on(minetest.get_node(pos).name, advtrains.all_tracktypes) then return end
				if advtrains.get_train_at_pos(pos) then return end
				
				if has_aux1_down then
					--feature: flip the node by 180°
					--i've always wanted this!
					advtrains.ndb.swap_node(pos, {name=node.name, param2=(node.param2+2)%4})
					return
				end

				local nnprefix, suffix, rotation=string.match(node.name, "^(.+)_([^_]+)(_[^_]+)$")
				--atdebug(node.name.."\npattern recognizes:"..nnprefix.." / "..suffix.." / "..rotation)
				--atdebug("nntab: ",tp.tracks[nnprefix])
				if not tp.tracks[nnprefix] or not tp.tracks[nnprefix].twrotate[suffix] then
					nnprefix, suffix=string.match(node.name, "^(.+)_([^_]+)$")
					rotation = ""
					if not tp.tracks[nnprefix] or not tp.tracks[nnprefix].twrotate[suffix] then
						minetest.chat_send_player(placer:get_player_name(), attrans("This node can't be rotated using the trackworker!"))
						return
					end
				end
				local modext=tp.tracks[nnprefix].twrotate[suffix]

				if rotation==modext[#modext] then --increase param2
					advtrains.ndb.swap_node(pos, {name=nnprefix.."_"..suffix..modext[1], param2=(node.param2+1)%4})
					return
				else
					local modpos
					for k,v in pairs(modext) do
						if v==rotation then modpos=k end
					end
					if not modpos then
						minetest.chat_send_player(placer:get_player_name(), attrans("This node can't be rotated using the trackworker!"))
						return
					end
					advtrains.ndb.swap_node(pos, {name=nnprefix.."_"..suffix..modext[modpos+1], param2=node.param2})
				end
			end
		end)
	end,
	on_use=function(itemstack, user, pointed_thing)
		return advtrains.pcall(function()
				local name = user:get_player_name()
			if not name then
			   return
			end
			if pointed_thing.type=="node" then
				local pos=pointed_thing.under
				local node=minetest.get_node(pos)
				if not advtrains.check_track_protection(pos, name) then
					return
				end
				
				--if not advtrains.is_track_and_drives_on(minetest.get_node(pos).name, advtrains.all_tracktypes) then return end
				if advtrains.get_train_at_pos(pos) then return end
				local nnprefix, suffix, rotation=string.match(node.name, "^(.+)_([^_]+)(_[^_]+)$")
				--atdebug(node.name.."\npattern recognizes:"..nodeprefix.." / "..railtype.." / "..rotation)
				if not tp.tracks[nnprefix] or not tp.tracks[nnprefix].twcycle[suffix] then
				  nnprefix, suffix=string.match(node.name, "^(.+)_([^_]+)$")
				  rotation = ""
				  if not tp.tracks[nnprefix] or not tp.tracks[nnprefix].twcycle[suffix] then
					minetest.chat_send_player(user:get_player_name(), attrans("This node can't be changed using the trackworker!"))
					return
				  end
				end
				local nextsuffix=tp.tracks[nnprefix].twcycle[suffix]
				advtrains.ndb.swap_node(pos, {name=nnprefix.."_"..nextsuffix..rotation, param2=node.param2})
				
			else
				atprint(name, dump(tp.tracks))
			end
		end)
	end,
})

--putting into right place
advtrains.trackplacer=tp
wa">new TempRow[rowcount]; // Get em width. Pedantically speaking, the width of "M" is not // necessarily the same as the em width, but whatever, close enough. s32 em = 6; if (m_font) em = m_font->getDimension(L"M").Width; s32 default_tooltip_index = allocString(""); std::map<s32, s32> active_image_indices; // Process content in column-major order for (s32 j = 0; j < colcount; ++j) { // Check column type ColumnType columntype = COLUMN_TYPE_TEXT; if (columns[j].type == "text") columntype = COLUMN_TYPE_TEXT; else if (columns[j].type == "image") columntype = COLUMN_TYPE_IMAGE; else if (columns[j].type == "color") columntype = COLUMN_TYPE_COLOR; else if (columns[j].type == "indent") columntype = COLUMN_TYPE_INDENT; else if (columns[j].type == "tree") columntype = COLUMN_TYPE_TREE; else errorstream<<"Invalid table column type: \"" <<columns[j].type<<"\""<<std::endl; // Process column options s32 padding = myround(0.5 * em); s32 tooltip_index = default_tooltip_index; s32 align = 0; s32 width = 0; s32 span = colcount; if (columntype == COLUMN_TYPE_INDENT) { padding = 0; // default indent padding } if (columntype == COLUMN_TYPE_INDENT || columntype == COLUMN_TYPE_TREE) { width = myround(em * 1.5); // default indent width } for (const Option &option : columns[j].options) { const std::string &name = option.name; const std::string &value = option.value; if (name == "padding") padding = myround(stof(value) * em); else if (name == "tooltip") tooltip_index = allocString(value); else if (name == "align" && value == "left") align = 0; else if (name == "align" && value == "center") align = 1; else if (name == "align" && value == "right") align = 2; else if (name == "align" && value == "inline") align = 3; else if (name == "width") width = myround(stof(value) * em); else if (name == "span" && columntype == COLUMN_TYPE_COLOR) span = stoi(value); else if (columntype == COLUMN_TYPE_IMAGE && !name.empty() && string_allowed(name, "0123456789")) { s32 content_index = allocImage(value); active_image_indices.insert(std::make_pair( stoi(name), content_index)); } else { errorstream<<"Invalid table column option: \""<<name<<"\"" <<" (value=\""<<value<<"\")"<<std::endl; } } // If current column type can use information from "color" columns, // find out which of those is currently active if (columntype == COLUMN_TYPE_TEXT) { for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; while (!row->colors.empty() && row->colors.back().second < j) row->colors.pop_back(); } } // Make template for new cells Cell newcell; newcell.content_type = columntype; newcell.tooltip_index = tooltip_index; newcell.reported_column = j+1; if (columntype == COLUMN_TYPE_TEXT) { // Find right edge of column s32 xmax = 0; for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; row->content_index = allocString(content[i * colcount + j]); const core::stringw &text = m_strings[row->content_index]; row->content_width = m_font ? m_font->getDimension(text.c_str()).Width : 0; row->content_width = MYMAX(row->content_width, width); s32 row_xmax = row->x + padding + row->content_width; xmax = MYMAX(xmax, row_xmax); } // Add a new cell (of text type) to each row for (s32 i = 0; i < rowcount; ++i) { newcell.xmin = rows[i].x + padding; alignContent(&newcell, xmax, rows[i].content_width, align); newcell.content_index = rows[i].content_index; newcell.color_defined = !rows[i].colors.empty(); if (newcell.color_defined) newcell.color = rows[i].colors.back().first; rows[i].cells.push_back(newcell); rows[i].x = newcell.xmax; } } else if (columntype == COLUMN_TYPE_IMAGE) { // Find right edge of column s32 xmax = 0; for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; row->content_index = -1; // Find content_index. Image indices are defined in // column options so check active_image_indices. s32 image_index = stoi(content[i * colcount + j]); std::map<s32, s32>::iterator image_iter = active_image_indices.find(image_index); if (image_iter != active_image_indices.end()) row->content_index = image_iter->second; // Get texture object (might be NULL) video::ITexture *image = NULL; if (row->content_index >= 0) image = m_images[row->content_index]; // Get content width and update xmax row->content_width = image ? image->getOriginalSize().Width : 0; row->content_width = MYMAX(row->content_width, width); s32 row_xmax = row->x + padding + row->content_width; xmax = MYMAX(xmax, row_xmax); } // Add a new cell (of image type) to each row for (s32 i = 0; i < rowcount; ++i) { newcell.xmin = rows[i].x + padding; alignContent(&newcell, xmax, rows[i].content_width, align); newcell.content_index = rows[i].content_index; rows[i].cells.push_back(newcell); rows[i].x = newcell.xmax; } active_image_indices.clear(); } else if (columntype == COLUMN_TYPE_COLOR) { for (s32 i = 0; i < rowcount; ++i) { video::SColor cellcolor(255, 255, 255, 255); if (parseColorString(content[i * colcount + j], cellcolor, true)) rows[i].colors.emplace_back(cellcolor, j+span); } } else if (columntype == COLUMN_TYPE_INDENT || columntype == COLUMN_TYPE_TREE) { // For column type "tree", reserve additional space for +/- // Also enable special processing for treeview-type tables s32 content_width = 0; if (columntype == COLUMN_TYPE_TREE) { content_width = m_font ? m_font->getDimension(L"+").Width : 0; m_has_tree_column = true; } // Add a new cell (of indent or tree type) to each row for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; s32 indentlevel = stoi(content[i * colcount + j]); indentlevel = MYMAX(indentlevel, 0); if (columntype == COLUMN_TYPE_TREE) row->indent = indentlevel; newcell.xmin = row->x + padding; newcell.xpos = newcell.xmin + indentlevel * width; newcell.xmax = newcell.xpos + content_width; newcell.content_index = 0; newcell.color_defined = !rows[i].colors.empty(); if (newcell.color_defined) newcell.color = rows[i].colors.back().first; row->cells.push_back(newcell); row->x = newcell.xmax; } } } // Copy temporary rows to not so temporary rows if (rowcount >= 1) { m_rows.resize(rowcount); for (s32 i = 0; i < rowcount; ++i) { Row *row = &m_rows[i]; row->cellcount = rows[i].cells.size(); row->cells = new Cell[row->cellcount]; memcpy((void*) row->cells, (void*) &rows[i].cells[0], row->cellcount * sizeof(Cell)); row->indent = rows[i].indent; row->visible_index = i; m_visible_rows.push_back(i); } } if (m_has_tree_column) { // Treeview: convert tree to indent cells on leaf rows for (s32 i = 0; i < rowcount; ++i) { if (i == rowcount-1 || m_rows[i].indent >= m_rows[i+1].indent) for (s32 j = 0; j < m_rows[i].cellcount; ++j) if (m_rows[i].cells[j].content_type == COLUMN_TYPE_TREE) m_rows[i].cells[j].content_type = COLUMN_TYPE_INDENT; } // Treeview: close rows according to opendepth option std::set<s32> opened_trees; for (s32 i = 0; i < rowcount; ++i) if (m_rows[i].indent < opendepth) opened_trees.insert(i); setOpenedTrees(opened_trees); } // Delete temporary information used only during setTable() delete[] rows; allocationComplete(); // Clamp scroll bar position updateScrollBar(); } void GUITable::clear() { // Clean up cells and rows for (GUITable::Row &row : m_rows) delete[] row.cells; m_rows.clear(); m_visible_rows.clear(); // Get colors from skin gui::IGUISkin *skin = Environment->getSkin(); m_color = skin->getColor(gui::EGDC_BUTTON_TEXT); m_background = skin->getColor(gui::EGDC_3D_HIGH_LIGHT); m_highlight = skin->getColor(gui::EGDC_HIGH_LIGHT); m_highlight_text = skin->getColor(gui::EGDC_HIGH_LIGHT_TEXT); // Reset members m_is_textlist = false; m_has_tree_column = false; m_selected = -1; m_sel_column = 0; m_sel_doubleclick = false; m_keynav_time = 0; m_keynav_buffer = L""; m_border = true; m_strings.clear(); m_images.clear(); m_alloc_strings.clear(); m_alloc_images.clear(); } std::string GUITable::checkEvent() { s32 sel = getSelected(); assert(sel >= 0); if (sel == 0) { return "INV"; } std::ostringstream os(std::ios::binary); if (m_sel_doubleclick) { os<<"DCL:"; m_sel_doubleclick = false; } else { os<<"CHG:"; } os<<sel; if (!m_is_textlist) { os<<":"<<m_sel_column; } return os.str(); } s32 GUITable::getSelected() const { if (m_selected < 0) return 0; assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size()); return m_visible_rows[m_selected] + 1; } void GUITable::setSelected(s32 index) { s32 old_selected = m_selected; m_selected = -1; m_sel_column = 0; m_sel_doubleclick = false; --index; // Switch from 1-based indexing to 0-based indexing s32 rowcount = m_rows.size(); if (rowcount == 0 || index < 0) { return; } if (index >= rowcount) { index = rowcount - 1; } // If the selected row is not visible, open its ancestors to make it visible bool selection_invisible = m_rows[index].visible_index < 0; if (selection_invisible) { std::set<s32> opened_trees; getOpenedTrees(opened_trees); s32 indent = m_rows[index].indent; for (s32 j = index - 1; j >= 0; --j) { if (m_rows[j].indent < indent) { opened_trees.insert(j); indent = m_rows[j].indent; } } setOpenedTrees(opened_trees); } if (index >= 0) { m_selected = m_rows[index].visible_index; assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size()); } if (m_selected != old_selected || selection_invisible) { autoScroll(); } } void GUITable::setOverrideFont(IGUIFont *font) { if (m_font == font) return; if (font == nullptr) font = Environment->getSkin()->getFont(); if (m_font) m_font->drop(); m_font = font; m_font->grab(); m_rowheight = m_font->getDimension(L"Ay").Height + 4; m_rowheight = MYMAX(m_rowheight, 1); updateScrollBar(); } IGUIFont *GUITable::getOverrideFont() const { return m_font; } GUITable::DynamicData GUITable::getDynamicData() const { DynamicData dyndata; dyndata.selected = getSelected(); dyndata.scrollpos = m_scrollbar->getPos(); dyndata.keynav_time = m_keynav_time; dyndata.keynav_buffer = m_keynav_buffer; if (m_has_tree_column) getOpenedTrees(dyndata.opened_trees); return dyndata; } void GUITable::setDynamicData(const DynamicData &dyndata) { if (m_has_tree_column) setOpenedTrees(dyndata.opened_trees); m_keynav_time = dyndata.keynav_time; m_keynav_buffer = dyndata.keynav_buffer; setSelected(dyndata.selected); m_sel_column = 0; m_sel_doubleclick = false; m_scrollbar->setPos(dyndata.scrollpos); } const c8* GUITable::getTypeName() const { return "GUITable"; } void GUITable::updateAbsolutePosition() { IGUIElement::updateAbsolutePosition(); updateScrollBar(); } void GUITable::draw() { if (!IsVisible) return; gui::IGUISkin *skin = Environment->getSkin(); // draw background bool draw_background = m_background.getAlpha() > 0; if (m_border) skin->draw3DSunkenPane(this, m_background, true, draw_background, AbsoluteRect, &AbsoluteClippingRect); else if (draw_background) skin->draw2DRectangle(this, m_background, AbsoluteRect, &AbsoluteClippingRect); // get clipping rect core::rect<s32> client_clip(AbsoluteRect); client_clip.UpperLeftCorner.Y += 1; client_clip.UpperLeftCorner.X += 1; client_clip.LowerRightCorner.Y -= 1; client_clip.LowerRightCorner.X -= 1; if (m_scrollbar->isVisible()) { client_clip.LowerRightCorner.X = m_scrollbar->getAbsolutePosition().UpperLeftCorner.X; } client_clip.clipAgainst(AbsoluteClippingRect); // draw visible rows s32 scrollpos = m_scrollbar->getPos(); s32 row_min = scrollpos / m_rowheight; s32 row_max = (scrollpos + AbsoluteRect.getHeight() - 1) / m_rowheight + 1; row_max = MYMIN(row_max, (s32) m_visible_rows.size()); core::rect<s32> row_rect(AbsoluteRect); if (m_scrollbar->isVisible()) row_rect.LowerRightCorner.X -= skin->getSize(gui::EGDS_SCROLLBAR_SIZE); row_rect.UpperLeftCorner.Y += row_min * m_rowheight - scrollpos; row_rect.LowerRightCorner.Y = row_rect.UpperLeftCorner.Y + m_rowheight; for (s32 i = row_min; i < row_max; ++i) { Row *row = &m_rows[m_visible_rows[i]]; bool is_sel = i == m_selected; video::SColor color = m_color; if (is_sel) { skin->draw2DRectangle(this, m_highlight, row_rect, &client_clip); color = m_highlight_text; } for (s32 j = 0; j < row->cellcount; ++j) drawCell(&row->cells[j], color, row_rect, client_clip); row_rect.UpperLeftCorner.Y += m_rowheight; row_rect.LowerRightCorner.Y += m_rowheight; } // Draw children IGUIElement::draw(); } void GUITable::drawCell(const Cell *cell, video::SColor color, const core::rect<s32> &row_rect, const core::rect<s32> &client_clip) { if ((cell->content_type == COLUMN_TYPE_TEXT) || (cell->content_type == COLUMN_TYPE_TREE)) { core::rect<s32> text_rect = row_rect; text_rect.UpperLeftCorner.X = row_rect.UpperLeftCorner.X + cell->xpos; text_rect.LowerRightCorner.X = row_rect.UpperLeftCorner.X + cell->xmax; if (cell->color_defined) color = cell->color; if (m_font) { if (cell->content_type == COLUMN_TYPE_TEXT) m_font->draw(m_strings[cell->content_index], text_rect, color, false, true, &client_clip); else // tree m_font->draw(cell->content_index ? L"+" : L"-", text_rect, color, false, true, &client_clip); } } else if (cell->content_type == COLUMN_TYPE_IMAGE) { if (cell->content_index < 0) return; video::IVideoDriver *driver = Environment->getVideoDriver(); video::ITexture *image = m_images[cell->content_index]; if (image) { core::position2d<s32> dest_pos = row_rect.UpperLeftCorner; dest_pos.X += cell->xpos; core::rect<s32> source_rect( core::position2d<s32>(0, 0), image->getOriginalSize()); s32 imgh = source_rect.LowerRightCorner.Y; s32 rowh = row_rect.getHeight(); if (imgh < rowh) dest_pos.Y += (rowh - imgh) / 2; else source_rect.LowerRightCorner.Y = rowh; video::SColor color(255, 255, 255, 255); driver->draw2DImage(image, dest_pos, source_rect, &client_clip, color, true); } } } bool GUITable::OnEvent(const SEvent &event) { if (!isEnabled()) return IGUIElement::OnEvent(event); if (event.EventType == EET_KEY_INPUT_EVENT) { if (event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_DOWN || event.KeyInput.Key == KEY_UP || event.KeyInput.Key == KEY_HOME || event.KeyInput.Key == KEY_END || event.KeyInput.Key == KEY_NEXT || event.KeyInput.Key == KEY_PRIOR)) { s32 offset = 0; switch (event.KeyInput.Key) { case KEY_DOWN: offset = 1; break; case KEY_UP: offset = -1; break; case KEY_HOME: offset = - (s32) m_visible_rows.size(); break; case KEY_END: offset = m_visible_rows.size(); break; case KEY_NEXT: offset = AbsoluteRect.getHeight() / m_rowheight; break; case KEY_PRIOR: offset = - (s32) (AbsoluteRect.getHeight() / m_rowheight); break; default: break; } s32 old_selected = m_selected; s32 rowcount = m_visible_rows.size(); if (rowcount != 0) { m_selected = rangelim(m_selected + offset, 0, rowcount-1); autoScroll(); } if (m_selected != old_selected) sendTableEvent(0, false); return true; } if (event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT)) { // Open/close subtree via keyboard if (m_selected >= 0) { int dir = event.KeyInput.Key == KEY_LEFT ? -1 : 1; toggleVisibleTree(m_selected, dir, true); } return true; } else if (!event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { sendTableEvent(0, true); return true; } else if (event.KeyInput.Key == KEY_ESCAPE || event.KeyInput.Key == KEY_SPACE) { // pass to parent } else if (event.KeyInput.PressedDown && event.KeyInput.Char) { // change selection based on text as it is typed u64 now = porting::getTimeMs(); if (now - m_keynav_time >= 500) m_keynav_buffer = L""; m_keynav_time = now; // add to key buffer if not a key repeat if (!(m_keynav_buffer.size() == 1 && m_keynav_buffer[0] == event.KeyInput.Char)) { m_keynav_buffer.append(event.KeyInput.Char); } // find the selected item, starting at the current selection // don't change selection if the key buffer matches the current item s32 old_selected = m_selected; s32 start = MYMAX(m_selected, 0); s32 rowcount = m_visible_rows.size(); for (s32 k = 1; k < rowcount; ++k) { s32 current = start + k; if (current >= rowcount) current -= rowcount; if (doesRowStartWith(getRow(current), m_keynav_buffer)) { m_selected = current; break; } } autoScroll(); if (m_selected != old_selected) sendTableEvent(0, false); return true; } } if (event.EventType == EET_MOUSE_INPUT_EVENT) { core::position2d<s32> p(event.MouseInput.X, event.MouseInput.Y); if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) { m_scrollbar->setPos(m_scrollbar->getPos() + (event.MouseInput.Wheel < 0 ? -3 : 3) * - (s32) m_rowheight / 2); return true; } // Find hovered row and cell bool really_hovering = false; s32 row_i = getRowAt(p.Y, really_hovering); const Cell *cell = NULL; if (really_hovering) { s32 cell_j = getCellAt(p.X, row_i); if (cell_j >= 0) cell = &(getRow(row_i)->cells[cell_j]); } // Update tooltip setToolTipText(cell ? m_strings[cell->tooltip_index].c_str() : L""); // Fix for #1567/#1806: // IGUIScrollBar passes double click events to its parent, // which we don't want. Detect this case and discard the event if (event.MouseInput.Event != EMIE_MOUSE_MOVED && m_scrollbar->isVisible() && m_scrollbar->isPointInside(p)) return true; if (event.MouseInput.isLeftPressed() && (isPointInside(p) || event.MouseInput.Event == EMIE_MOUSE_MOVED)) { s32 sel_column = 0; bool sel_doubleclick = (event.MouseInput.Event == EMIE_LMOUSE_DOUBLE_CLICK); bool plusminus_clicked = false; // For certain events (left click), report column // Also open/close subtrees when the +/- is clicked if (cell && ( event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN || event.MouseInput.Event == EMIE_LMOUSE_DOUBLE_CLICK || event.MouseInput.Event == EMIE_LMOUSE_TRIPLE_CLICK)) { sel_column = cell->reported_column; if (cell->content_type == COLUMN_TYPE_TREE) plusminus_clicked = true; } if (plusminus_clicked) { if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { toggleVisibleTree(row_i, 0, false); } } else { // Normal selection s32 old_selected = m_selected; m_selected = row_i; autoScroll(); if (m_selected != old_selected || sel_column >= 1 || sel_doubleclick) { sendTableEvent(sel_column, sel_doubleclick); } // Treeview: double click opens/closes trees if (m_has_tree_column && sel_doubleclick) { toggleVisibleTree(m_selected, 0, false); } } } return true; } if (event.EventType == EET_GUI_EVENT && event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED && event.GUIEvent.Caller == m_scrollbar) { // Don't pass events from our scrollbar to the parent return true; } return IGUIElement::OnEvent(event); } /******************************************************************************/ /* GUITable helper functions */ /******************************************************************************/ s32 GUITable::allocString(const std::string &text) { std::map<std::string, s32>::iterator it = m_alloc_strings.find(text); if (it == m_alloc_strings.end()) { s32 id = m_strings.size(); std::wstring wtext = utf8_to_wide(text); m_strings.emplace_back(wtext.c_str()); m_alloc_strings.insert(std::make_pair(text, id)); return id; } return it->second; } s32 GUITable::allocImage(const std::string &imagename) { std::map<std::string, s32>::iterator it = m_alloc_images.find(imagename); if (it == m_alloc_images.end()) { s32 id = m_images.size(); m_images.push_back(m_tsrc->getTexture(imagename)); m_alloc_images.insert(std::make_pair(imagename, id)); return id; } return it->second; } void GUITable::allocationComplete() { // Called when done with creating rows and cells from table data, // i.e. when allocString and allocImage won't be called anymore m_alloc_strings.clear(); m_alloc_images.clear(); } const GUITable::Row* GUITable::getRow(s32 i) const { if (i >= 0 && i < (s32) m_visible_rows.size()) return &m_rows[m_visible_rows[i]]; return NULL; } bool GUITable::doesRowStartWith(const Row *row, const core::stringw &str) const { if (row == NULL) return false; for (s32 j = 0; j < row->cellcount; ++j) { Cell *cell = &row->cells[j]; if (cell->content_type == COLUMN_TYPE_TEXT) { const core::stringw &cellstr = m_strings[cell->content_index]; if (cellstr.size() >= str.size() && str.equals_ignore_case(cellstr.subString(0, str.size()))) return true; } } return false; } s32 GUITable::getRowAt(s32 y, bool &really_hovering) const { really_hovering = false; s32 rowcount = m_visible_rows.size(); if (rowcount == 0) return -1; // Use arithmetic to find row s32 rel_y = y - AbsoluteRect.UpperLeftCorner.Y - 1; s32 i = (rel_y + m_scrollbar->getPos()) / m_rowheight; if (i >= 0 && i < rowcount) { really_hovering = true; return i; } if (i < 0) return 0; return rowcount - 1; } s32 GUITable::getCellAt(s32 x, s32 row_i) const { const Row *row = getRow(row_i); if (row == NULL) return -1; // Use binary search to find cell in row s32 rel_x = x - AbsoluteRect.UpperLeftCorner.X - 1; s32 jmin = 0; s32 jmax = row->cellcount - 1; while (jmin < jmax) { s32 pivot = jmin + (jmax - jmin) / 2; assert(pivot >= 0 && pivot < row->cellcount); const Cell *cell = &row->cells[pivot]; if (rel_x >= cell->xmin && rel_x <= cell->xmax) return pivot; if (rel_x < cell->xmin) jmax = pivot - 1; else jmin = pivot + 1; } if (jmin >= 0 && jmin < row->cellcount && rel_x >= row->cells[jmin].xmin && rel_x <= row->cells[jmin].xmax) return jmin; return -1; } void GUITable::autoScroll() { if (m_selected >= 0) { s32 pos = m_scrollbar->getPos(); s32 maxpos = m_selected * m_rowheight; s32 minpos = maxpos - (AbsoluteRect.getHeight() - m_rowheight); if (pos > maxpos) m_scrollbar->setPos(maxpos); else if (pos < minpos) m_scrollbar->setPos(minpos); } } void GUITable::updateScrollBar() { s32 totalheight = m_rowheight * m_visible_rows.size(); s32 scrollmax = MYMAX(0, totalheight - AbsoluteRect.getHeight()); m_scrollbar->setVisible(scrollmax > 0); m_scrollbar->setMax(scrollmax); m_scrollbar->setSmallStep(m_rowheight); m_scrollbar->setLargeStep(2 * m_rowheight); m_scrollbar->setPageSize(totalheight); } void GUITable::sendTableEvent(s32 column, bool doubleclick) { m_sel_column = column; m_sel_doubleclick = doubleclick; if (Parent) { SEvent e; memset(&e, 0, sizeof e); e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; e.GUIEvent.Element = 0; e.GUIEvent.EventType = gui::EGET_TABLE_CHANGED; Parent->OnEvent(e); } } void GUITable::getOpenedTrees(std::set<s32> &opened_trees) const { opened_trees.clear(); s32 rowcount = m_rows.size(); for (s32 i = 0; i < rowcount - 1; ++i) { if (m_rows[i].indent < m_rows[i+1].indent && m_rows[i+1].visible_index != -2) opened_trees.insert(i); } } void GUITable::setOpenedTrees(const std::set<s32> &opened_trees) { s32 old_selected = -1; if (m_selected >= 0) old_selected = m_visible_rows[m_selected]; std::vector<s32> parents; std::vector<s32> closed_parents; m_visible_rows.clear(); for (size_t i = 0; i < m_rows.size(); ++i) { Row *row = &m_rows[i]; // Update list of ancestors while (!parents.empty() && m_rows[parents.back()].indent >= row->indent) parents.pop_back(); while (!closed_parents.empty() && m_rows[closed_parents.back()].indent >= row->indent) closed_parents.pop_back(); assert(closed_parents.size() <= parents.size()); if (closed_parents.empty()) { // Visible row row->visible_index = m_visible_rows.size(); m_visible_rows.push_back(i); } else if (parents.back() == closed_parents.back()) { // Invisible row, direct parent is closed row->visible_index = -2; } else { // Invisible row, direct parent is open, some ancestor is closed row->visible_index = -1; } // If not a leaf, add to parents list if (i < m_rows.size()-1 && row->indent < m_rows[i+1].indent) { parents.push_back(i); s32 content_index = 0; // "-", open